FinancialController.cs 380 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264
  1. using Aspose.Cells;
  2. using Aspose.Words;
  3. using EyeSoft.Extensions;
  4. using EyeSoft.IO;
  5. using FluentValidation;
  6. using NPOI.SS.UserModel;
  7. using NPOI.XSSF.UserModel;
  8. using OASystem.API.OAMethodLib;
  9. using OASystem.API.OAMethodLib.APNs;
  10. using OASystem.API.OAMethodLib.File;
  11. using OASystem.API.OAMethodLib.QiYeWeChatAPI.AppNotice;
  12. using OASystem.Domain.AesEncryption;
  13. using OASystem.Domain.Dtos.Financial;
  14. using OASystem.Domain.Dtos.Groups;
  15. using OASystem.Domain.Entities.Customer;
  16. using OASystem.Domain.Entities.Financial;
  17. using OASystem.Domain.Entities.Groups;
  18. using OASystem.Domain.ViewModels.Financial;
  19. using OASystem.Domain.ViewModels.Groups;
  20. using OASystem.Infrastructure.Repositories.Financial;
  21. using OASystem.Infrastructure.Repositories.Groups;
  22. using OfficeOpenXml;
  23. using SqlSugar.Extensions;
  24. using System.Collections;
  25. using System.Data;
  26. using System.Data.OleDb;
  27. using System.Diagnostics;
  28. using System.Globalization;
  29. using System.IO.Compression;
  30. using static OASystem.API.OAMethodLib.JWTHelper;
  31. namespace OASystem.API.Controllers
  32. {
  33. /// <summary>
  34. /// 财务模块
  35. /// </summary>
  36. [Route("api/[controller]/[action]")]
  37. [ApiController]
  38. public class FinancialController : ControllerBase
  39. {
  40. private readonly IMapper _mapper;
  41. private readonly IConfiguration _config;
  42. private readonly ILogger<FinancialController> _logger;
  43. private readonly SqlSugarClient _sqlSugar;
  44. private readonly HttpClient _httpClient;
  45. private readonly SetDataTypeRepository _setDataTypeRep;
  46. private readonly SetDataRepository _setDataRep;
  47. private readonly DailyFeePaymentRepository _daiRep; //日付申请仓库
  48. private readonly TeamRateRepository _teamRateRep; //团组汇率仓库
  49. private readonly ForeignReceivablesRepository _ForForeignReceivablesRep; //对外收款账单仓库
  50. private readonly ProceedsReceivedRepository _proceedsReceivedRep; //已收款项仓库
  51. private readonly PaymentRefundAndOtherMoneyRepository _paymentRefundAndOtherMoneyRep; //收款退还与其他款项 仓库
  52. private readonly DelegationInfoRepository _delegationInfoRep; //团组信息 仓库
  53. private readonly ForeignReceivablesRepository _foreignReceivablesRepository;
  54. private readonly CheckBoxsRepository _groupCheckBox; //团组成本选中项 仓库
  55. /// <summary>
  56. /// 初始化
  57. /// </summary>
  58. public FinancialController(
  59. IMapper mapper,
  60. IConfiguration configuration,
  61. ILogger<FinancialController> logger,
  62. DailyFeePaymentRepository daiRep,
  63. SqlSugarClient sqlSugar,
  64. SetDataTypeRepository setDataTypeRep,
  65. TeamRateRepository teamRateRep,
  66. ForeignReceivablesRepository ForForeignReceivablesRep,
  67. ProceedsReceivedRepository proceedsReceivedRep,
  68. PaymentRefundAndOtherMoneyRepository paymentRefundAndOtherMoneyRep,
  69. HttpClient httpClient,
  70. DelegationInfoRepository delegationInfoRep,
  71. SetDataRepository setDataRep,
  72. ForeignReceivablesRepository foreignReceivablesRepository,
  73. CheckBoxsRepository groupCheckBox
  74. )
  75. {
  76. _mapper = mapper;
  77. _config = configuration;
  78. _logger = logger;
  79. _daiRep = daiRep;
  80. _sqlSugar = sqlSugar;
  81. _setDataTypeRep = setDataTypeRep;
  82. _teamRateRep = teamRateRep;
  83. _ForForeignReceivablesRep = ForForeignReceivablesRep;
  84. _proceedsReceivedRep = proceedsReceivedRep;
  85. _paymentRefundAndOtherMoneyRep = paymentRefundAndOtherMoneyRep;
  86. _httpClient = httpClient;
  87. _delegationInfoRep = delegationInfoRep;
  88. _setDataRep = setDataRep;
  89. _foreignReceivablesRepository = foreignReceivablesRepository;
  90. _groupCheckBox = groupCheckBox;
  91. }
  92. #region 日付申请
  93. /// <summary>
  94. /// 获取日付申请 基础数据源
  95. /// </summary>
  96. /// <param name="dto"> 日付申请 分页 dto</param>
  97. /// <returns></returns>
  98. [HttpPost]
  99. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  100. public async Task<IActionResult> PostPageSearchDailyPaymentPriceTypeData(PortDtoBase dto)
  101. {
  102. var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
  103. if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
  104. var result = await _daiRep.GetPagePriceTypeData(dto, currUserInfo.UserId);
  105. if (result == null || result.Code != 0)
  106. {
  107. return Ok(JsonView(false, result.Msg));
  108. }
  109. var data = result.Data;
  110. return Ok(JsonView(data));
  111. }
  112. /// <summary>
  113. /// 获取日付申请 基础数据源 - 转账表识
  114. /// </summary>
  115. /// <param name="dto"> 日付申请 分页 dto</param>
  116. /// <returns></returns>
  117. [HttpPost]
  118. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  119. public async Task<IActionResult> GetSearchDailyPaymentPriceTypeAddData(PortDtoBase dto)
  120. {
  121. var result = await _daiRep.GetPriceTypeAddData(dto);
  122. if (result == null || result.Code != 0)
  123. {
  124. return Ok(JsonView(false, result.Msg));
  125. }
  126. var data = result.Data;
  127. return Ok(JsonView(data));
  128. }
  129. /// <summary>
  130. /// 日付申请 Page Search
  131. /// </summary>
  132. /// <param name="dto"> 日付申请 分页 dto</param>
  133. /// <returns></returns>
  134. [HttpPost]
  135. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  136. public async Task<IActionResult> PostPageSearchDailyPaymentList(PageDailyFeePaymentDto dto)
  137. {
  138. var result = await _daiRep.GetPageSearchAll(dto);
  139. if (result == null || result.Code != 0)
  140. {
  141. return Ok(JsonView(false, result.Msg));
  142. }
  143. var data = result.Data;
  144. if (data == null)
  145. {
  146. return Ok(JsonView(false, result.Msg));
  147. }
  148. return Ok(JsonView(data));
  149. }
  150. /// <summary>
  151. /// 日付申请 Single Search By Id
  152. /// </summary>
  153. /// <param name="dto"></param>
  154. /// <returns></returns>
  155. [HttpPost]
  156. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  157. public async Task<IActionResult> PostSearchDailyPaymentInfo(SearchDailyFeePaymentDto dto)
  158. {
  159. var result = await _daiRep.GetSearchById(dto);
  160. if (result == null || result.Code != 0)
  161. {
  162. return Ok(JsonView(false, result.Msg));
  163. }
  164. return Ok(JsonView(result.Data));
  165. }
  166. /// <summary>
  167. /// 日付申请 添加
  168. /// </summary>
  169. /// <param name="dto"> 日付申请 添加 dto</param>
  170. /// <returns></returns>
  171. [HttpPost]
  172. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  173. public async Task<IActionResult> PostAddDailyPayment(AddDailyFeePaymentDto dto)
  174. {
  175. var result = await _daiRep.Add(dto);
  176. if (result == null || result.Code != 0)
  177. {
  178. return Ok(JsonView(false, result.Msg));
  179. }
  180. #region 应用推送
  181. try
  182. {
  183. int dailyId = result.Data.GetType().GetProperty("dailyId").GetValue(result.Data, null);
  184. int sign = result.Data.GetType().GetProperty("sign").GetValue(result.Data, null);
  185. await AppNoticeLibrary.DailyPayReminders_Create_ToCaiwuChat(dailyId, sign, QiyeWeChatEnum.CaiWuChat);
  186. //2024-10-21 新增LZ UID
  187. var userIds = new List<int>() { 21 };
  188. string title = $"系统通知";
  189. var dailyInfo = await _sqlSugar.Queryable<Fin_DailyFeePayment>().Where(x => x.Id == dailyId).FirstAsync();
  190. string content = $"[新增-日付申请]一项费用:[费用说明:{dailyInfo.Instructions}]{dailyInfo.SumPrice:#0.00} CNY;";
  191. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.DailyPayment, title, content, userIds, 0);
  192. var h5 = new PageParam_PriceAuditH5() { diid = "", uid = "21" };
  193. await APNsTools.iOS_PushNotifications1("051", "日付费用审核", "", content, true, "ExpenseAuditWebView", h5);
  194. //罗颖申请的费用发送通知
  195. if (dto.UserId == 374)
  196. {
  197. var qw_userIds = new List<string>() {
  198. //"374", //罗颖
  199. "208", //雷怡
  200. "309", //赖红燕
  201. };
  202. //Todo:企微消息通知
  203. await AppNoticeLibrary.SendUserMsg_CompanyShare_ToDailtPay(dailyId, 374, qw_userIds);
  204. }
  205. }
  206. catch (Exception ex)
  207. {
  208. }
  209. #endregion
  210. return Ok(JsonView(true));
  211. }
  212. /// <summary>
  213. /// 日付申请 Update
  214. /// </summary>
  215. /// <param name="dto"> 日付申请 修改 dto</param>
  216. /// <returns></returns>
  217. [HttpPost]
  218. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  219. public async Task<IActionResult> PostEditDailyPayment(EditDailyFeePaymentDto dto)
  220. {
  221. var result = await _daiRep.Edit(dto);
  222. if (result == null || result.Code != 0)
  223. {
  224. return Ok(JsonView(false, result.Msg));
  225. }
  226. #region 应用推送
  227. try
  228. {
  229. int dailyId = result.Data.GetType().GetProperty("dailyId").GetValue(result.Data, null);
  230. int sign = result.Data.GetType().GetProperty("sign").GetValue(result.Data, null);
  231. await AppNoticeLibrary.DailyPayReminders_Create_ToCaiwuChat(dailyId, sign, QiyeWeChatEnum.CaiWuChat);
  232. //2024-10-21 新增LZ UID
  233. var userIds = new List<int>() { 21 };
  234. string title = $"系统通知";
  235. var dailyInfo = await _sqlSugar.Queryable<Fin_DailyFeePayment>().Where(x => x.Id == dailyId).FirstAsync();
  236. string content = $"[更新-日付申请]一项费用:[费用说明:{dailyInfo.Instructions}]{dailyInfo.SumPrice:#0.00} CNY;";
  237. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.DailyPayment, title, content, userIds, 0);
  238. var h5 = new PageParam_PriceAuditH5() { diid = "", uid = "21" };
  239. await APNsTools.iOS_PushNotifications1("051", "日付费用审核", "", content, true, "ExpenseAuditWebView", h5);
  240. }
  241. catch (Exception ex)
  242. {
  243. }
  244. #endregion
  245. return Ok(JsonView(true));
  246. }
  247. /// <summary>
  248. /// 日付申请 Del
  249. /// </summary>
  250. /// <param name="dto"> 日付申请 删除 dto</param>
  251. /// <returns></returns>
  252. [HttpPost]
  253. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  254. public async Task<IActionResult> PostDelDailyPayment(DelDailyFeePaymentDto dto)
  255. {
  256. _sqlSugar.BeginTran();
  257. var result = await _daiRep.Del(dto);
  258. //删除日付关联表
  259. var delCount = _sqlSugar.Updateable<Fin_RoyaltyForm>()
  260. .Where(x => x.IsDel == 0 && x.DayOverhead == dto.Id)
  261. .SetColumns(x => new Fin_RoyaltyForm
  262. {
  263. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  264. DeleteUserId = dto.UserId,
  265. IsDel = 1
  266. }).ExecuteCommand();
  267. _sqlSugar.CommitTran();
  268. if (result == null || result.Code != 0)
  269. {
  270. return Ok(JsonView(false, result.Msg));
  271. }
  272. return Ok(JsonView(true));
  273. }
  274. /// <summary>
  275. /// 日付申请 财务审核
  276. /// </summary>
  277. /// <param name="dto"> dto </param>
  278. /// <returns></returns>
  279. [HttpPost]
  280. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  281. public async Task<IActionResult> PostDelDailyPaymentAudit(DP_AuditStatusDto dto)
  282. {
  283. var result = await _daiRep.DailyPaymentAudit(dto);
  284. if (result == null || result.Code != 0)
  285. {
  286. return Ok(JsonView(false, result.Msg));
  287. }
  288. return Ok(JsonView(true));
  289. }
  290. /// <summary>
  291. /// 日付申请 Single Excel Download
  292. /// </summary>
  293. /// <param name="dto"> dto </param>
  294. /// <returns></returns>
  295. [HttpPost]
  296. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  297. public async Task<IActionResult> PostExcelDailyPaymentDownload(SearchDailyFeePaymentDto dto)
  298. {
  299. if (dto.PortType == 1 || dto.PortType == 2)
  300. {
  301. string feeSql = string.Format(@"Select * From Fin_DailyFeePayment
  302. Where IsDel=0 And Id = {0} ", dto.Id);
  303. var feeData = await _sqlSugar.SqlQueryable<Fin_DailyFeePaymentInfolView>(feeSql).FirstAsync();
  304. if (feeData == null)
  305. {
  306. return Ok(JsonView(false, "暂无数据!"));
  307. }
  308. string feeContentSql = string.Format(@"Select * From Fin_DailyFeePaymentContent
  309. Where IsDel=0 And DFPId = {0} ", dto.Id);
  310. feeData.FeeContents = await _sqlSugar.SqlQueryable<Fin_DailyFeePaymentContentInfolView>(feeContentSql).ToListAsync();
  311. if (feeData != null)
  312. {
  313. string userName = string.Empty;
  314. string userSql = string.Format("Select * From Sys_Users Where Id={0} And Isdel = {1}", feeData.CreateUserId, 0);
  315. Sys_Users user = await _sqlSugar.SqlQueryable<Sys_Users>(userSql).FirstAsync();
  316. if (user != null) { userName = user.CnName; }
  317. var setData = _setDataTypeRep.QueryDto<Sys_SetData, Fin_DailyFeePaymentPagePriceSubTypeView>().ToList();
  318. //48人员费用 49办公费用 50 销售费用 51 其他费用 55 大运会
  319. var priceSubTypeData = setData.Where(s => s.STid == 55).ToList();
  320. var pairs = new Dictionary<string, object>();
  321. var datas = new List<DataTable>();
  322. //if (priceSubTypeData.Where(s => s.Id == feeData.PriceTypeId).ToList().Count() > 0)//大运会专属模板
  323. //{
  324. // //AsposeHelper.ExpertExcelToModel("日常费用付款申请模板-大运会数据.xls", "DailyPayment", "大运会所有日常费用付款申请.xls",
  325. // // pairs, datas);
  326. //}
  327. //else //日付常规模板
  328. //{
  329. pairs.Clear();
  330. pairs.Add("Opertor", userName);
  331. pairs.Add("DateTime", feeData.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
  332. pairs.Add("FAuditStatus", feeData.FAuditDesc);
  333. pairs.Add("MAuditStatus", feeData.MAuditDesc);
  334. pairs.Add("SumPrice", feeData.SumPrice);
  335. DataTable data = AsposeHelper.ListToDataTable("DailyFeePayment", feeData.FeeContents);
  336. datas.Clear();
  337. datas.Add(data);
  338. string fileName = string.Format("{0}-日常费用付款申请.xlsx", feeData.Instructions);
  339. string msg = AsposeHelper.ExpertExcelToModel("日常费用付款申请模板.xlsx", "DailyPayment", fileName, pairs, datas);
  340. return Ok(JsonView(true, msg));
  341. //}
  342. }
  343. else
  344. {
  345. return Ok(JsonView(false, "暂无数据!"));
  346. }
  347. }
  348. return Ok(JsonView(true));
  349. }
  350. /// <summary>
  351. /// 日付申请
  352. /// 总经理未审核 日付信息
  353. /// </summary>
  354. /// <returns></returns>
  355. [HttpGet]
  356. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  357. public async Task<IActionResult> DailyPaymentGMUnAudited()
  358. {
  359. var dailyInfos = await _sqlSugar.Queryable<Fin_DailyFeePayment>()
  360. .LeftJoin<Sys_Users>((dfp, u) => dfp.CreateUserId == u.Id)
  361. .Where(dfp => dfp.IsDel == 0 &&
  362. //dfp.FAudit == 1 &&
  363. //dfp.IsPay == 0 &&
  364. dfp.MAudit == 0
  365. )
  366. .OrderBy(dfp => dfp.CreateTime, OrderByType.Desc)
  367. //.OrderBy(dfp => dfp.FAudit, OrderByType.Desc)
  368. .Select((dfp, u) => new
  369. {
  370. id = dfp.Id,
  371. amountName = dfp.Instructions,
  372. amount = dfp.SumPrice,
  373. fAuditStatus = dfp.FAudit == 1 ? "审核通过" :
  374. dfp.FAudit == 2 ? "审核未通过" : "未审核",
  375. fAuditDate = dfp.FAuditDate,
  376. applicant = u.CnName,
  377. applicantDate = dfp.CreateTime
  378. })
  379. //.ToListAsync();
  380. .CountAsync();
  381. //int count = dailyInfos.Count;
  382. return Ok(JsonView(true, "查询成功", dailyInfos));
  383. }
  384. #endregion
  385. #region 团组提成
  386. /// <summary>
  387. /// 提成 Page Search
  388. /// </summary>
  389. /// <param name="dto"> 提成 分页 dto</param>
  390. /// <returns></returns>
  391. [HttpPost]
  392. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  393. public async Task<IActionResult> PostPageSearchCommissionList(GroupCommissionDto dto)
  394. {
  395. var data = await GroupCommission.GetCommissionPageList(dto);
  396. return Ok(JsonView(data.Data));
  397. }
  398. #endregion
  399. #region 团组汇率
  400. /// <summary>
  401. /// 团组汇率 Select数据源(团组列,汇率列)
  402. /// </summary>
  403. /// <param name="dto"></param>
  404. /// <returns></returns>
  405. [HttpPost]
  406. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  407. public async Task<IActionResult> GetGroupRateDataSources(TeamRateDto dto)
  408. {
  409. try
  410. {
  411. //迁移数据更新团组汇率
  412. //Result teamRateData1 = await _teamRateRep.GetGroupRateChangeData();
  413. //var data = await _teamRateRep.PostGroupTeamRateHot();
  414. Stopwatch stopwatch = Stopwatch.StartNew();
  415. var groupNameDto = new GroupNameDto() { PortType = dto.PortType };
  416. var groups = await _delegationInfoRep.GetGroupNameList(groupNameDto);
  417. var _currData = new List<CurrencyHot>();
  418. string currData = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>("GroupTeamCurrencyData");//string 取
  419. if (!string.IsNullOrEmpty(currData))
  420. {
  421. _currData = JsonConvert.DeserializeObject<List<CurrencyHot>>(currData);
  422. }
  423. else
  424. {
  425. _currData = await _teamRateRep.PostGroupTeamRateHot();
  426. //过期时间 25 Hours
  427. TimeSpan ts = DateTime.Now.AddHours(25).TimeOfDay;
  428. await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync("GroupTeamCurrencyData", JsonConvert.SerializeObject(_currData), ts);
  429. }
  430. var _data = new { GroupData = groups.Data, TeamRateData = _currData };
  431. stopwatch.Stop();
  432. return Ok(JsonView(true, $"查询成功!耗时:{stopwatch.ElapsedMilliseconds / 1000}s", _data));
  433. }
  434. catch (Exception ex)
  435. {
  436. return Ok(JsonView(false, ex.Message));
  437. }
  438. }
  439. ///// <summary>
  440. ///// 团组汇率 changge
  441. ///// </summary>
  442. ///// <returns></returns>
  443. //[HttpPost]
  444. //[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  445. //public async Task<IActionResult> ChangeGroupRateInfo()
  446. //{
  447. // try
  448. // {
  449. // Result teamRateData = await _teamRateRep.GetGroupRateChangeData();
  450. // if (teamRateData.Code != 0)
  451. // {
  452. // return Ok(JsonView(false, teamRateData.Msg));
  453. // }
  454. // return Ok(JsonView(true, teamRateData.Msg, teamRateData.Data));
  455. // }
  456. // catch (Exception ex)
  457. // {
  458. // return Ok(JsonView(false, ex.Message));
  459. // throw;
  460. // }
  461. //}
  462. /// <summary>
  463. /// 团组汇率 Select汇率详情
  464. /// </summary>
  465. /// <param name="dto"></param>
  466. /// <returns></returns>
  467. [HttpPost]
  468. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  469. public async Task<IActionResult> GetGroupRateInfo(TeamRateInfoDto dto)
  470. {
  471. try
  472. {
  473. Result teamRateData = await _teamRateRep.GetGroupRateInfoByDiid(dto);
  474. if (teamRateData.Code != 0)
  475. {
  476. return Ok(JsonView(false, teamRateData.Msg));
  477. }
  478. return Ok(JsonView(true, teamRateData.Msg, teamRateData.Data));
  479. }
  480. catch (Exception ex)
  481. {
  482. return Ok(JsonView(false, ex.Message));
  483. throw;
  484. }
  485. }
  486. /// <summary>
  487. /// 团组汇率 添加 or 更新
  488. /// </summary>
  489. /// <param name="dto"></param>
  490. /// <returns></returns>
  491. [HttpPost]
  492. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  493. public async Task<IActionResult> PostGroupRateUpdate(TeamRateUpdateDto dto)
  494. {
  495. try
  496. {
  497. Result teamRateData = await _teamRateRep.PostGroupRateUpdate(dto);
  498. if (teamRateData.Code != 0)
  499. {
  500. return Ok(JsonView(false, teamRateData.Msg));
  501. }
  502. return Ok(JsonView(true, teamRateData.Msg, teamRateData.Data));
  503. }
  504. catch (Exception ex)
  505. {
  506. return Ok(JsonView(false, ex.Message));
  507. throw;
  508. }
  509. }
  510. #endregion
  511. #region 对外收款账单 关联已收款项
  512. /// <summary>
  513. /// 对外收款账单 Select数据源(团组名,币种,汇款方式)
  514. /// 关联已收款项
  515. /// </summary>
  516. /// <param name="dto"></param>
  517. /// <returns></returns>
  518. [HttpPost]
  519. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  520. public async Task<IActionResult> GetForeignReceivablesDataSources(ForeignReceivablesDataSourcesDto dto)
  521. {
  522. return Ok(await _ForForeignReceivablesRep.GetDataSource(dto));
  523. }
  524. /// <summary>
  525. /// 对外收款账单
  526. /// 账单详情
  527. /// 关联已收款项
  528. /// </summary>
  529. /// <param name="dto"></param>
  530. /// <returns></returns>
  531. [HttpPost]
  532. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  533. public async Task<IActionResult> GetGroupReceivablesInfoByDiId(ForForeignReceivablesInfoDto dto)
  534. {
  535. try
  536. {
  537. Result ffrData = await _ForForeignReceivablesRep.GetGroupReceivablesInfoByDiId(dto);
  538. if (ffrData.Code != 0)
  539. {
  540. return Ok(JsonView(false, ffrData.Msg));
  541. }
  542. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  543. }
  544. catch (Exception ex)
  545. {
  546. return Ok(JsonView(false, ex.Message));
  547. throw;
  548. }
  549. }
  550. /// <summary>
  551. /// 对外收款账单
  552. /// 账单 删除
  553. /// 关联已收款项
  554. /// </summary>
  555. /// <param name="dto"></param>
  556. /// <returns></returns>
  557. [HttpPost]
  558. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  559. public async Task<IActionResult> PostGroupReceivablesDel(DelForForeignReceivablesInfoDto dto)
  560. {
  561. try
  562. {
  563. Result ffrData = await _ForForeignReceivablesRep._Del(dto);
  564. if (ffrData.Code != 0)
  565. {
  566. return Ok(JsonView(false, ffrData.Msg));
  567. }
  568. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  569. }
  570. catch (Exception ex)
  571. {
  572. return Ok(JsonView(false, ex.Message));
  573. throw;
  574. }
  575. }
  576. /// <summary>
  577. /// 对外收款账单
  578. /// 添加 And 更新
  579. /// 关联已收款项
  580. /// </summary>
  581. /// <param name="dto"></param>
  582. /// <returns></returns>
  583. [HttpPost]
  584. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  585. public async Task<IActionResult> PostReceivablesOperate(ForeignReceivablesAddAndUpdateDto dto)
  586. {
  587. try
  588. {
  589. Result ffrData = await _ForForeignReceivablesRep.PostReceivablesOperate(dto);
  590. if (ffrData.Code != 0)
  591. {
  592. return Ok(JsonView(false, ffrData.Msg));
  593. }
  594. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  595. }
  596. catch (Exception ex)
  597. {
  598. return Ok(JsonView(false, ex.Message));
  599. throw;
  600. }
  601. }
  602. /// <summary>
  603. /// 已收款项
  604. /// 账单 删除
  605. /// 关联已收款项
  606. /// </summary>
  607. /// <param name="dto"></param>
  608. /// <returns></returns>
  609. [HttpPost]
  610. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  611. public async Task<IActionResult> PostAmountReceivedDel(ProceedsReceivedDelDto dto)
  612. {
  613. try
  614. {
  615. Result ffrData = await _proceedsReceivedRep._Del(dto);
  616. if (ffrData.Code != 0)
  617. {
  618. return Ok(JsonView(false, ffrData.Msg));
  619. }
  620. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  621. }
  622. catch (Exception ex)
  623. {
  624. return Ok(JsonView(false, ex.Message));
  625. throw;
  626. }
  627. }
  628. /// <summary>
  629. /// 已收款项
  630. /// 添加 And 更新
  631. /// 关联已收款项
  632. /// </summary>
  633. /// <param name="dto"></param>
  634. /// <returns></returns>
  635. [HttpPost]
  636. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  637. public async Task<IActionResult> PostAmountReceivedOperate(ProceedsReceivedDto dto)
  638. {
  639. try
  640. {
  641. Result ffrData = await _proceedsReceivedRep.PostAmountReceivedOperate(dto);
  642. if (ffrData.Code != 0)
  643. {
  644. return Ok(JsonView(false, ffrData.Msg));
  645. }
  646. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  647. }
  648. catch (Exception ex)
  649. {
  650. return Ok(JsonView(false, ex.Message));
  651. throw;
  652. }
  653. }
  654. /// <summary>
  655. /// 财务 已收款项
  656. /// 分配已收款项至 应收项下
  657. /// 关联已收款项
  658. /// </summary>
  659. /// <param name="dto"></param>
  660. /// <returns></returns>
  661. [HttpPost]
  662. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  663. public async Task<IActionResult> PostAllocateAmountReceived(AllocateAmountReceivedDto dto)
  664. {
  665. try
  666. {
  667. Result ffrData = await _proceedsReceivedRep.PostAllocateAmountReceived(dto);
  668. if (ffrData.Code != 0)
  669. {
  670. return Ok(JsonView(false, ffrData.Msg));
  671. }
  672. return Ok(JsonView(true));
  673. }
  674. catch (Exception ex)
  675. {
  676. return Ok(JsonView(false, ex.Message));
  677. throw;
  678. }
  679. }
  680. ///// <summary>
  681. ///// 财务 收款账单
  682. ///// 导出Word(北京,四川)
  683. ///// </summary>
  684. ///// <param name="dto"></param>
  685. ///// <returns></returns>
  686. //[HttpPost]
  687. //[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  688. //public async Task<IActionResult> PostAccountReceivableWordExport(AccountReceivableWordExportDto dto)
  689. //{
  690. // try
  691. // {
  692. // //模板处理
  693. // string typeName = string.Empty;
  694. // if (dto.TemplateType == 1) //四川
  695. // {
  696. // typeName = "四川";
  697. // }
  698. // else if (dto.TemplateType == 2) //北京
  699. // {
  700. // typeName = "北京";
  701. // }
  702. // else return Ok(JsonView(false,"请选择正确的模板类型!"));
  703. // string wordTempName = string.Format("收款账单({0})模板.doc", typeName);
  704. // }
  705. // catch (Exception ex)
  706. // {
  707. // return Ok(JsonView(false, ex.Message));
  708. // }
  709. //}
  710. #endregion
  711. #region 对外收款账单
  712. /// <summary>
  713. /// 对外收款账单
  714. /// 数据源
  715. /// </summary>
  716. /// <param name="dto"></param>
  717. /// <returns></returns>
  718. [HttpPost]
  719. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  720. public async Task<IActionResult> PostGroupReceivablesDataSource(ForeignReceivablesDataSourcesDto dto)
  721. {
  722. return Ok(await _ForForeignReceivablesRep.PostDataSource(dto));
  723. }
  724. /// <summary>
  725. /// 对外收款账单,团组列表分页
  726. /// 数据源
  727. /// </summary>
  728. /// <param name="dto"></param>
  729. /// <returns></returns>
  730. [HttpPost]
  731. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  732. public async Task<IActionResult> ForeignReceivablesDataSourcesOffSet(ForeignReceivablesDataSourcesOffSetDto dto)
  733. {
  734. return Ok(await _ForForeignReceivablesRep.PostDataSourceOffSet(dto));
  735. }
  736. /// <summary>
  737. /// 对外收款账单
  738. /// 账单详情
  739. /// </summary>
  740. /// <param name="dto"></param>
  741. /// <returns></returns>
  742. [HttpPost]
  743. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  744. public async Task<IActionResult> PostGroupReceivablesInfoByDiId(ForForeignReceivablesNewDto dto)
  745. {
  746. return Ok(await _ForForeignReceivablesRep.PostGroupReceivablesInfoByDiId(dto));
  747. }
  748. /// <summary>
  749. /// 对外收款账单
  750. /// 添加 And 更新
  751. /// </summary>
  752. /// <param name="dto"></param>
  753. /// <returns></returns>
  754. [HttpPost]
  755. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  756. public async Task<IActionResult> PostReceivablesSave(ForeignReceivablesSaveDto dto)
  757. {
  758. return Ok(await _ForForeignReceivablesRep.PostReceivablesSave(dto));
  759. }
  760. /// <summary>
  761. /// 对外收款账单
  762. /// (单条数据)添加 And 更新
  763. /// </summary>
  764. /// <param name="dto"></param>
  765. /// <returns></returns>
  766. [HttpPost]
  767. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  768. public async Task<IActionResult> PostReceivablesSingleSave(PostReceivablesSingleSaveDto dto)
  769. {
  770. return Ok(await _ForForeignReceivablesRep.PostReceivablesSingleSave(dto));
  771. }
  772. /// <summary>
  773. /// 对外收款账单
  774. /// 审核
  775. /// </summary>
  776. /// <param name="dto"></param>
  777. /// <returns></returns>
  778. [HttpPost]
  779. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  780. public async Task<IActionResult> PostReceivablesAudit(FeeAuditDto dto)
  781. {
  782. return Ok(await _ForForeignReceivablesRep.FeeAudit(dto));
  783. }
  784. /// <summary>
  785. /// 已收账单
  786. /// 删除
  787. /// </summary>
  788. /// <param name="dto"></param>
  789. /// <returns></returns>
  790. [HttpPost]
  791. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  792. public async Task<IActionResult> PostReceivablesDel(ForeignReceivablesDelDto dto)
  793. {
  794. Result ffrData = await _ForForeignReceivablesRep.PostReceivablesDel(dto);
  795. if (ffrData.Code != 0)
  796. {
  797. return Ok(JsonView(false, ffrData.Msg));
  798. }
  799. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  800. }
  801. private readonly static Dictionary<int, string> _receivablesFeilDownloadType = new Dictionary<int, string>()
  802. {
  803. { 1,"生成收款单(四川)"},
  804. { 2,"生成收款单(北京)"},
  805. { 3,"汇款账单"},
  806. { 4,"实际报价明细"}
  807. };
  808. /// <summary>
  809. /// 已收账单
  810. /// File Download
  811. /// Init
  812. /// </summary>
  813. /// <returns></returns>
  814. [HttpPost]
  815. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  816. public async Task<IActionResult> PostReceivablesFeilDownloadInit()
  817. {
  818. return Ok(JsonView(true, "操作成功!", _receivablesFeilDownloadType.Select(kv => new
  819. {
  820. Id = kv.Key,
  821. Name = kv.Value
  822. }).ToList()));
  823. }
  824. private class EnterExitCostCurrency
  825. {
  826. public string Name { get; set; }
  827. public string Code { get; set; }
  828. public decimal Rate { get; set; }
  829. }
  830. /// <summary>
  831. /// 已收账单
  832. /// File Downloasd
  833. /// </summary>
  834. /// <param name="dto"></param>
  835. /// <returns></returns>
  836. [HttpPost]
  837. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  838. public async Task<IActionResult> PostReceivablesFeilDownload(ForeignReceivablesFeilDownloadDto dto)
  839. {
  840. try
  841. {
  842. if (dto.DiId < 1)
  843. {
  844. return Ok(JsonView(false, "请传入有效DiId参数!"));
  845. }
  846. if (!_receivablesFeilDownloadType.ContainsKey(dto.FileType))
  847. {
  848. return Ok(JsonView(false, $"未找到ID为{dto.FileType}的文件下载类型。支持的ID范围: {string.Join(", ", _receivablesFeilDownloadType.Keys)}"));
  849. }
  850. var _currencyDatas = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 66).ToList();
  851. var _DelegationInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0 && it.Id == dto.DiId).First();
  852. if (_DelegationInfo == null)
  853. {
  854. return Ok(JsonView(false, "暂无团组信息!!"));
  855. }
  856. if (dto.FileType == 1 || dto.FileType == 2)
  857. {
  858. var _ForeignReceivables = _sqlSugar.Queryable<Fin_ForeignReceivables>().Where(it => it.IsDel == 0 && it.Diid == dto.DiId).ToList();
  859. if (_ForeignReceivables.Count < 1)
  860. {
  861. return Ok(JsonView(false, "暂无收款信息!!"));
  862. }
  863. string tempName = "";
  864. if (dto.FileType == 1) tempName = $"收款账单(四川)模板.docx";
  865. else if (dto.FileType == 2) tempName = $"收款账单(北京)模板.docx";
  866. string tempPath = AppSettingsHelper.Get("WordBasePath") + $"ForeignReceivables/Temp/{tempName}";
  867. //载入模板
  868. var doc = new Document(tempPath);
  869. var builder = new DocumentBuilder(doc);
  870. #region 替换Word模板书签内容
  871. //这里可以创建个DataTable循环添加书签的值,这里提示一下就不多做修改了
  872. //付款方
  873. if (doc.Range.Bookmarks["To"] != null)
  874. {
  875. Bookmark mark = doc.Range.Bookmarks["To"];
  876. mark.Text = _ForeignReceivables[0].To == null ? "" : _ForeignReceivables[0].To.ToString();
  877. }
  878. //付款方电话
  879. if (doc.Range.Bookmarks["ToTel"] != null)
  880. {
  881. Bookmark mark = doc.Range.Bookmarks["ToTel"];
  882. mark.Text = _ForeignReceivables[0].ToTel == null ? "" : _ForeignReceivables[0].ToTel.ToString();
  883. }
  884. //导出时间
  885. if (doc.Range.Bookmarks["Date"] != null)
  886. {
  887. Bookmark mark = doc.Range.Bookmarks["Date"];
  888. mark.Text = DateTime.Now.ToString("yyyy-MM-dd");
  889. }
  890. //注
  891. if (doc.Range.Bookmarks["Attention"] != null)
  892. {
  893. Bookmark mark = doc.Range.Bookmarks["Attention"];
  894. mark.Text = _ForeignReceivables[0].Attention == null ? "" : _ForeignReceivables[0].Attention.ToString();
  895. }
  896. //团队名称
  897. if (doc.Range.Bookmarks["Team"] != null)
  898. {
  899. Bookmark mark = doc.Range.Bookmarks["Team"];
  900. mark.Text = _DelegationInfo.VisitCountry == null ? "" : _DelegationInfo.VisitCountry.Replace("|", "、").ToString();
  901. }
  902. //付款日期
  903. if (doc.Range.Bookmarks["PayDate"] != null)
  904. {
  905. Bookmark mark = doc.Range.Bookmarks["PayDate"];
  906. mark.Text = _ForeignReceivables[0].PayDate == null ? "" : Convert.ToDateTime(_ForeignReceivables[0].PayDate).ToString("yyyy年MM月dd日");
  907. }
  908. decimal sumPrice = 0;
  909. //各项费用
  910. if (doc.Range.Bookmarks["PayItemContent"] != null)
  911. {
  912. string items = "";
  913. foreach (var fr in _ForeignReceivables)
  914. {
  915. var currInfo = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == fr.Currency).First();
  916. items += $"{fr.PriceName} {currInfo?.Name} {fr.Price:#0.00} * {fr.Count} {fr.Unit} * {fr.Rate}.................. RMB {fr.ItemSumPrice:#0.00}\n";
  917. sumPrice += fr.ItemSumPrice;
  918. }
  919. Bookmark mark = doc.Range.Bookmarks["PayItemContent"];
  920. mark.Text = items;
  921. }
  922. //合计
  923. if (doc.Range.Bookmarks["Total"] != null)
  924. {
  925. Bookmark mark = doc.Range.Bookmarks["Total"];
  926. mark.Text = sumPrice.ToString("#0.00");
  927. }
  928. #endregion
  929. //文件名
  930. string strFileName = _DelegationInfo.TeamName + "-收款账单.docx";
  931. //去水印
  932. new Aspose.Words.License().SetLicense(new MemoryStream(Convert.FromBase64String(AsposeHelper.asposeKey)));
  933. doc.Save(AppSettingsHelper.Get("WordBasePath") + "ForeignReceivables/File/" + strFileName);
  934. string url = AppSettingsHelper.Get("WordBaseUrl") + "Office/Word/ForeignReceivables/File/" + strFileName;
  935. return Ok(JsonView(true, "成功", new { Url = url }));
  936. }
  937. else if (dto.FileType == 3) //汇款通知
  938. {
  939. var _EnterExitCosts = _sqlSugar.Queryable<Grp_EnterExitCost>().Where(it => it.IsDel == 0 && it.DiId == dto.DiId).First();
  940. var _DayAndCosts = _sqlSugar.Queryable<Grp_DayAndCost>().Where(it => it.IsDel == 0 && it.DiId == dto.DiId && it.NationalTravelFeeId > 0).ToList();
  941. if (_EnterExitCosts == null)
  942. {
  943. return Ok(JsonView(false, "该团组未填写出入境费用;"));
  944. }
  945. var _EnterExitCostCurrencys = new List<EnterExitCostCurrency>();
  946. if (!string.IsNullOrEmpty(_EnterExitCosts.CurrencyRemark))
  947. {
  948. var currency1 = _EnterExitCosts.CurrencyRemark.Split("|");
  949. foreach (var item in currency1)
  950. {
  951. var currency2 = item.Split(":");
  952. var currency3 = currency2[0].Split("(");
  953. var currencyName = currency3[0].ToString();
  954. var currencyCode = currency3[1].Split(")")[0].ToString();
  955. _EnterExitCostCurrencys.Add(new EnterExitCostCurrency
  956. {
  957. Name = currencyName,
  958. Code = currencyCode,
  959. Rate = Convert.ToDecimal(currency2[1] ?? "0")
  960. });
  961. }
  962. }
  963. var _cityFee = _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(it => it.IsDel == 0).ToList();
  964. foreach (var item in _DayAndCosts)
  965. {
  966. var cityInfo = _cityFee.Where(it => it.Id == item.NationalTravelFeeId).FirstOrDefault();
  967. if (cityInfo != null)
  968. {
  969. if (cityInfo.City.Contains("全部城市") || cityInfo.City.Contains("其他城市") || cityInfo.City.Contains("所有城市"))
  970. {
  971. item.Place = cityInfo.Country;
  972. }
  973. else item.Place = cityInfo.City;
  974. }
  975. }
  976. //数据源
  977. //住宿费 伙食费 公杂费 培训费 选中才计算出费用
  978. //住宿费 选中赋值
  979. List<Grp_DayAndCost> dac1 = new List<Grp_DayAndCost>();
  980. if (_EnterExitCosts.ChoiceThree == 1) dac1 = _DayAndCosts.Where(it => it.Type == 1).ToList(); //住宿费
  981. //伙食费 选中赋值
  982. List<Grp_DayAndCost> dac2 = new List<Grp_DayAndCost>();
  983. if (_EnterExitCosts.ChoiceFour == 1) dac2 = _DayAndCosts.Where(it => it.Type == 2).ToList(); //伙食费
  984. //公杂费 选中赋值
  985. List<Grp_DayAndCost> dac3 = new List<Grp_DayAndCost>();
  986. if (_EnterExitCosts.ChoiceFour == 1) dac3 = _DayAndCosts.Where(it => it.Type == 3).ToList(); //公杂费
  987. //培训费 选中赋值
  988. List<Grp_DayAndCost> dac4 = new List<Grp_DayAndCost>();
  989. if (_EnterExitCosts.ChoiceFour == 1) dac4 = _DayAndCosts.Where(it => it.Type == 4).ToList(); //培训费
  990. //币种Data
  991. var currData = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0 && it.STid == 66).ToList();
  992. var DeleClientList = _sqlSugar.Queryable<Grp_TourClientList>()
  993. .LeftJoin<Crm_DeleClient>((tcl, dc) => tcl.ClientId == dc.Id && dc.IsDel == 0)
  994. .LeftJoin<Crm_CustomerCompany>((tcl, dc, cc) => dc.CrmCompanyId == cc.Id && dc.IsDel == 0)
  995. .Where((tcl, dc, cc) => tcl.IsDel == 0 && tcl.DiId == dto.DiId)
  996. .Select((tcl, dc, cc) => new ClientAirInfo
  997. {
  998. LastName = dc.LastName,
  999. FirstName = dc.FirstName,
  1000. Sex = dc.Sex,
  1001. Birthday = dc.BirthDay,
  1002. Company = cc.CompanyFullName,
  1003. Job = dc.Job,
  1004. AirType = tcl.ShippingSpaceTypeId
  1005. })
  1006. .ToList();
  1007. if (DeleClientList.Count < 1)
  1008. {
  1009. return Ok(JsonView(false, "暂无团组成员,请先填写团组成员!!!"));
  1010. }
  1011. foreach (var item in DeleClientList)
  1012. {
  1013. EncryptionProcessor.DecryptProperties(item);
  1014. item.Company = item.Company.Replace("\n", "");
  1015. }
  1016. var _ClientNames = DeleClientList.Select(x => x.Name).ToList();
  1017. var _GroupClient = DeleClientList.GroupBy(x => x.Company).ToList();
  1018. Dictionary<string, string> bookmarkArr = null;
  1019. string tempPath = AppSettingsHelper.Get("WordBasePath") + $"ForeignReceivables/Temp/汇款通知.docx";
  1020. //载入模板
  1021. var doc = new Document(tempPath);
  1022. DocumentBuilder builder = null;
  1023. var filesToZip = new List<string>();
  1024. foreach (var ClientItem in _GroupClient) //遍历单位
  1025. {
  1026. doc = new Document(tempPath);
  1027. builder = new DocumentBuilder(doc);
  1028. var paragraph = new Paragraph(doc);
  1029. bookmarkArr = new Dictionary<string, string>
  1030. {
  1031. { "titleClientUnit", ClientItem.Key }, //title单位
  1032. { "ClientUnit", ClientItem.Key }, //单位
  1033. { "VisitStartDate", _DelegationInfo.VisitStartDate.ToString("yyyy年MM月dd日") },//出发日期
  1034. { "name", string.Join(",", ClientItem.Select(x => x.Name).ToArray()).TrimEnd(',') },//全部人员信息
  1035. { "VisitCountry", _DelegationInfo.VisitCountry.Replace("|", "、") },//出访国家
  1036. { "dayTime", DateTime.Now.ToString("yyyy年MM月dd日") }//今天日期
  1037. };
  1038. var ClientItemList = ClientItem.ToList();
  1039. string UsersTop = string.Empty;//word中人员以及金额
  1040. decimal WordAllPrice = 0.00M;
  1041. //int[] infoColumn = new int[5] {dac1.Select(x=>x.Place.Length).ToList().Max(),2, dac1.Select(x => x.Cost.Length).Max() + dac1.Select(x => x.Currency.Length).Max(),
  1042. // 6, 3 + dac1.Where(x=>!string.IsNullOrWhiteSpace(x.Place)).Select(x=>(Convert.ToDecimal(x.SubTotal) / Convert.ToDecimal(x.Cost)).ToString().Length).Max() };
  1043. //遍历人员
  1044. for (int i = 0; i < ClientItemList.Count; i++)
  1045. {
  1046. var TeableBookmarkArr = new Dictionary<string, string>();
  1047. var client = ClientItemList[i]; //每个人员
  1048. var firstName = ClientItemList[i].Name;
  1049. /*
  1050. * 457 头等舱
  1051. * 458 公务舱
  1052. * 460 经济舱
  1053. */
  1054. decimal airPrice = 0.00M,
  1055. cityTranffic = 0.00M;
  1056. string airName = string.Empty;
  1057. if (client.AirType == 457)
  1058. {
  1059. airName = $"头等舱";
  1060. airPrice = _EnterExitCosts.AirTD;
  1061. cityTranffic = _EnterExitCosts.CityTranffic2;
  1062. }
  1063. else if (client.AirType == 458)
  1064. {
  1065. airName = $"公务舱";
  1066. airPrice = _EnterExitCosts.AirGW;
  1067. cityTranffic = _EnterExitCosts.CityTranffic1;
  1068. }
  1069. else if (client.AirType == 460)
  1070. {
  1071. airName = $"经济舱";
  1072. airPrice = _EnterExitCosts.AirJJ;
  1073. cityTranffic = _EnterExitCosts.CityTranffic;
  1074. }
  1075. //计算费用总和
  1076. decimal AllPrice = airPrice + cityTranffic + dac1.Sum(x => x.SubTotal) + dac2.Sum(x => x.SubTotal) +
  1077. dac3.Sum(x => x.SubTotal) + dac4.Sum(x => x.SubTotal) + _EnterExitCosts.Visa + _EnterExitCosts.Safe +
  1078. +_EnterExitCosts.YiMiao + _EnterExitCosts.YiMiao + _EnterExitCosts.Ticket + _EnterExitCosts.Service;
  1079. WordAllPrice += AllPrice;
  1080. UsersTop += firstName + "出访费用为¥" + AllPrice.ToString("#0.00") + "元、";
  1081. TeableBookmarkArr.Add("jp", airPrice.ToString("#0.00") + " 元"); //机票金额
  1082. TeableBookmarkArr.Add("cs", $"{cityTranffic:#0.00} 元"); //城市交通费用
  1083. TeableBookmarkArr.Add("zs", dac1.Sum(x => Convert.ToDecimal(x.SubTotal)).ToString("#0.00") + " 元"); //住宿费
  1084. string zsinfo = string.Empty;
  1085. string hsinfo = string.Empty;
  1086. string gzinfo = string.Empty;
  1087. var placeArr = new List<string>();
  1088. Aspose.Words.Tables.Table FirstTable = (Aspose.Words.Tables.Table)doc.GetChild(NodeType.Table, 0, true);
  1089. Aspose.Words.Tables.Table ChildTable = (Aspose.Words.Tables.Table)FirstTable.GetChild(NodeType.Table, 0, true);
  1090. Aspose.Words.Tables.Table ChildTable1 = (Aspose.Words.Tables.Table)FirstTable.GetChild(NodeType.Table, 1, true);
  1091. Aspose.Words.Tables.Table ChildTable2 = (Aspose.Words.Tables.Table)FirstTable.GetChild(NodeType.Table, 2, true);
  1092. int rowIndex = 0;
  1093. if (dac1.Count <= 0 && ChildTable != null) ChildTable.Remove(); //删除表格
  1094. foreach (var item in dac1)
  1095. {
  1096. if (string.IsNullOrWhiteSpace(item.Place))
  1097. {
  1098. continue;
  1099. }
  1100. if (placeArr.Contains(item.Place))
  1101. {
  1102. continue;
  1103. }
  1104. else
  1105. {
  1106. placeArr.Add(item.Place);
  1107. }
  1108. if (!string.IsNullOrWhiteSpace(item.Place))
  1109. {
  1110. if (rowIndex > ChildTable.Rows.Count - 1)
  1111. {
  1112. var chitableRow = ChildTable.LastRow.Clone(true);
  1113. ChildTable.AppendChild(chitableRow);
  1114. }
  1115. int days = dac1.FindAll(x => x.Place == item.Place).Count;
  1116. SetCells(ChildTable, doc, rowIndex, 0, item.Place);
  1117. SetCells(ChildTable, doc, rowIndex, 1, days + "晚");
  1118. string currencyCode = currData.Find(it => it.Id == item.Currency)?.Remark ?? "Unknown";
  1119. SetCells(ChildTable, doc, rowIndex, 2, item.Cost.ToString("#0.00") + currencyCode + "/晚");
  1120. var currencyRate = DecimalToString((item.SubTotal / item.Cost), 4);
  1121. var sys_currencyInfo = _currencyDatas.Find(x => item.Currency == x.Id);
  1122. if (sys_currencyInfo != null)
  1123. {
  1124. var sys_currencyCode = sys_currencyInfo.Name;
  1125. var eec_currencyInfo = _EnterExitCostCurrencys.Find(x => x.Code.Equals(sys_currencyCode));
  1126. if (eec_currencyInfo != null)
  1127. {
  1128. currencyRate = DecimalToString(eec_currencyInfo.Rate, 4);
  1129. }
  1130. }
  1131. SetCells(ChildTable, doc, rowIndex, 3, "汇率" + currencyRate);
  1132. SetCells(ChildTable, doc, rowIndex, 4, "CNY " + item.SubTotal + "\r\n");
  1133. rowIndex++;
  1134. zsinfo += item.Place + " " + days + "晚 " + item.Cost.ToString("#0.00") + currencyCode + "/晚" + " 汇率" + (item.SubTotal / item.Cost).ToString("#0.0000") + " CNY " + item.SubTotal * days + "\r\n";
  1135. }
  1136. }
  1137. placeArr.Clear();
  1138. rowIndex = 0;
  1139. if (dac2.Count <= 0 && ChildTable1 != null) ChildTable1.Remove(); //删除表格
  1140. foreach (var item in dac2)
  1141. {
  1142. if (string.IsNullOrWhiteSpace(item.Place))
  1143. {
  1144. continue;
  1145. }
  1146. if (placeArr.Contains(item.Place))
  1147. {
  1148. continue;
  1149. }
  1150. else
  1151. {
  1152. placeArr.Add(item.Place);
  1153. }
  1154. if (!string.IsNullOrWhiteSpace(item.Place))
  1155. {
  1156. if (rowIndex > ChildTable1.Rows.Count - 1)
  1157. {
  1158. var chitableRow = ChildTable1.LastRow.Clone(true);
  1159. ChildTable1.AppendChild(chitableRow);
  1160. }
  1161. int days = dac2.FindAll(x => x.Place == item.Place).Count;
  1162. SetCells(ChildTable1, doc, rowIndex, 0, item.Place);
  1163. SetCells(ChildTable1, doc, rowIndex, 1, days + "天");
  1164. string currencyCode = currData.Find(it => it.Id == item.Currency)?.Remark ?? "Unknown";
  1165. SetCells(ChildTable1, doc, rowIndex, 2, item.Cost.ToString("#0.00") + currencyCode + "/天");
  1166. var currencyRate = DecimalToString((item.SubTotal / item.Cost), 4);
  1167. var sys_currencyInfo = _currencyDatas.Find(x => item.Currency == x.Id);
  1168. if (sys_currencyInfo != null)
  1169. {
  1170. var sys_currencyCode = sys_currencyInfo.Name;
  1171. var eec_currencyInfo = _EnterExitCostCurrencys.Find(x => x.Code.Equals(sys_currencyCode));
  1172. if (eec_currencyInfo != null)
  1173. {
  1174. currencyRate = DecimalToString(eec_currencyInfo.Rate, 4);
  1175. }
  1176. }
  1177. SetCells(ChildTable1, doc, rowIndex, 3, "汇率" + currencyRate);
  1178. SetCells(ChildTable1, doc, rowIndex, 4, "CNY " + item.SubTotal);
  1179. rowIndex++;
  1180. hsinfo += item.Place + " " + days + "天 " + item.Cost.ToString("#0.00") + currencyCode + "/天" + " 汇率" + (item.SubTotal / item.Cost).ToString("#0.0000") + " CNY " + item.SubTotal * days + "\r\n";
  1181. }
  1182. }
  1183. placeArr.Clear();
  1184. rowIndex = 0;
  1185. if (dac2.Count <= 0 && ChildTable2 != null) ChildTable2.Remove(); //删除表格
  1186. foreach (var item in dac3)
  1187. {
  1188. if (string.IsNullOrWhiteSpace(item.Place))
  1189. {
  1190. continue;
  1191. }
  1192. if (placeArr.Contains(item.Place))
  1193. {
  1194. continue;
  1195. }
  1196. else
  1197. {
  1198. placeArr.Add(item.Place);
  1199. }
  1200. if (!string.IsNullOrWhiteSpace(item.Place))
  1201. {
  1202. if (rowIndex > ChildTable2.Rows.Count - 1)
  1203. {
  1204. var chitableRow = ChildTable2.LastRow.Clone(true);
  1205. ChildTable2.AppendChild(chitableRow);
  1206. }
  1207. int days = dac3.FindAll(x => x.Place == item.Place).Count;
  1208. SetCells(ChildTable2, doc, rowIndex, 0, item.Place);
  1209. SetCells(ChildTable2, doc, rowIndex, 1, days + "天");
  1210. string currencyCode = currData.Find(it => it.Id == item.Currency)?.Remark ?? "Unknown";
  1211. SetCells(ChildTable2, doc, rowIndex, 2, item.Cost.ToString("#0.00") + currencyCode + "/天");
  1212. var currencyRate = DecimalToString((item.SubTotal / item.Cost), 4);
  1213. var sys_currencyInfo = _currencyDatas.Find(x => item.Currency == x.Id);
  1214. if (sys_currencyInfo != null)
  1215. {
  1216. var sys_currencyCode = sys_currencyInfo.Name;
  1217. var eec_currencyInfo = _EnterExitCostCurrencys.Find(x => x.Code.Equals(sys_currencyCode));
  1218. if (eec_currencyInfo != null)
  1219. {
  1220. currencyRate = DecimalToString(eec_currencyInfo.Rate, 4);
  1221. }
  1222. }
  1223. SetCells(ChildTable2, doc, rowIndex, 3, "汇率" + currencyRate);
  1224. SetCells(ChildTable2, doc, rowIndex, 4, "CNY " + item.SubTotal + "\r\n");
  1225. rowIndex++;
  1226. gzinfo += item.Place + " " + days + "天 " + item.Cost.ToString("#0.00") + currencyCode + "/天" + " 汇率" + (item.SubTotal / item.Cost).ToString("#0.00") + " CNY " + item.SubTotal * days + "\r\n";
  1227. }
  1228. }
  1229. placeArr.Clear();
  1230. TeableBookmarkArr.Add("zsinfo", zsinfo); //住宿费详情
  1231. TeableBookmarkArr.Add("hs", dac2.Sum(x => Convert.ToDecimal(x.SubTotal)).ToString("#0.00") + " 元"); //伙食费
  1232. TeableBookmarkArr.Add("hsinfo", hsinfo); //伙食费详情
  1233. TeableBookmarkArr.Add("gz", dac3.Sum(x => Convert.ToDecimal(x.SubTotal)).ToString("#0.00") + " 元"); //公杂费
  1234. TeableBookmarkArr.Add("gzinfo", gzinfo); //公杂费详情
  1235. string otherFeestr = "";
  1236. decimal otherFee = 0.00M;
  1237. if (_EnterExitCosts.Visa > 0.00M)
  1238. {
  1239. otherFee += _EnterExitCosts.Visa;
  1240. otherFeestr += $"签证费{_EnterExitCosts.Visa:#0.00}元、";
  1241. }
  1242. if (_EnterExitCosts.YiMiao > 0.00M)
  1243. {
  1244. otherFee += _EnterExitCosts.YiMiao;
  1245. otherFeestr += $"疫苗费{_EnterExitCosts.YiMiao:#0.00}元、";
  1246. }
  1247. if (_EnterExitCosts.HeSuan > 0.00M)
  1248. {
  1249. otherFee += _EnterExitCosts.HeSuan;
  1250. otherFeestr += $"核酸检测费{_EnterExitCosts.HeSuan:#0.00}元、";
  1251. }
  1252. if (_EnterExitCosts.Safe > 0.00M)
  1253. {
  1254. otherFee += _EnterExitCosts.Safe;
  1255. otherFeestr += $"保险费{_EnterExitCosts.Safe:#0.00}元、";
  1256. }
  1257. if (_EnterExitCosts.Ticket > 0.00M)
  1258. {
  1259. otherFee += _EnterExitCosts.Ticket;
  1260. otherFeestr += $"参展门票费{_EnterExitCosts.Ticket:#0.00}元、";
  1261. }
  1262. if (otherFeestr.Length > 0)
  1263. {
  1264. otherFeestr = otherFeestr.Substring(0, otherFeestr.Length - 1);
  1265. otherFeestr += "等费用";
  1266. }
  1267. TeableBookmarkArr.Add("qt", otherFee.ToString("#0.00") + " 元");//其他费用
  1268. TeableBookmarkArr.Add("qtinfo", otherFeestr);//其他费用第二列
  1269. TeableBookmarkArr.Add("fw", _EnterExitCosts.Service.ToString("#0.00") + "元/人");//服务费
  1270. TeableBookmarkArr.Add("AllPrice", AllPrice.ToString("#0.00") + "元/人");//表格合计费用
  1271. TeableBookmarkArr.Add("title", $"费用清单-{airName}({firstName})");
  1272. foreach (var book in TeableBookmarkArr.Keys)
  1273. {
  1274. if (doc.Range.Bookmarks[book] != null)
  1275. {
  1276. Bookmark mark = doc.Range.Bookmarks[book];
  1277. mark.Text = TeableBookmarkArr[book];
  1278. }
  1279. }
  1280. if (i != ClientItemList.Count - 1)
  1281. {
  1282. builder.PageSetup.Orientation = Aspose.Words.Orientation.Portrait;
  1283. Aspose.Words.Tables.Table table = (Aspose.Words.Tables.Table)doc.GetChild(NodeType.Table, 0, true);
  1284. table.ParentNode.InsertAfter(paragraph, table);
  1285. var CloneTable = (Aspose.Words.Tables.Table)table.Clone(true);
  1286. table.ParentNode.InsertAfter(CloneTable, paragraph);
  1287. }
  1288. TeableBookmarkArr.Clear();
  1289. }
  1290. bookmarkArr.Add("VisitPrice", WordAllPrice.ToString());//出访费用总额
  1291. bookmarkArr.Add("CnAllPrice", WordAllPrice.ConvertCNYUpper());//出访费用总额中文
  1292. bookmarkArr.Add("namesPrice", UsersTop.TrimEnd('、'));//各人员出访费用 付辰同志出访费用为¥73,604.8元
  1293. foreach (var book in bookmarkArr.Keys)
  1294. {
  1295. if (doc.Range.Bookmarks[book] != null)
  1296. {
  1297. Bookmark mark = doc.Range.Bookmarks[book];
  1298. mark.Text = bookmarkArr[book];
  1299. }
  1300. }
  1301. //MemoryStream outSteam = new MemoryStream();
  1302. string filsPath = AppSettingsHelper.Get("WordBasePath") + $"ForeignReceivables/File/{ClientItem.Key.Replace("\n", "")}_{_DelegationInfo.VisitCountry.Replace("|", "、")}.docx";
  1303. //去水印
  1304. new Aspose.Words.License().SetLicense(new MemoryStream(Convert.FromBase64String(AsposeHelper.asposeKey)));
  1305. doc.Save(filsPath);
  1306. filesToZip.Add(filsPath);
  1307. //streams.Add(ClientItem.Key + ".docx", outSteam.ToArray());
  1308. }
  1309. //文件名
  1310. string zipFileName = _DelegationInfo.TeamName + "-收款账单.zip";
  1311. string zipPath = $"ForeignReceivables/File/{_DelegationInfo.TeamName}-收款账单{DateTime.Now:yyyyMMddHHmmss}.zip";
  1312. try
  1313. {
  1314. using (var zip = ZipFile.Open(AppSettingsHelper.Get("WordBasePath") + zipPath, ZipArchiveMode.Create))
  1315. {
  1316. foreach (var file in filesToZip)
  1317. {
  1318. zip.CreateEntryFromFile(file, Path.GetFileName(file));
  1319. }
  1320. }
  1321. }
  1322. catch (Exception ex)
  1323. {
  1324. return Ok(JsonView(false, ex.Message));
  1325. }
  1326. string url = AppSettingsHelper.Get("WordBaseUrl") + $"Office/Word/{zipPath}";
  1327. return Ok(JsonView(true, "成功", new { Url = url }));
  1328. }
  1329. else if (dto.FileType == 4) //实际报价明细
  1330. {
  1331. try
  1332. {
  1333. var filePaths = _DelegationInfo.FrFilePaths;
  1334. // 1. 文件验证
  1335. if (filePaths == null || filePaths.Count < 1)
  1336. {
  1337. return Ok(JsonView(false, "该团组未上传实际报价相关文件!"));
  1338. }
  1339. // 2. 构建源文件夹路径
  1340. var groupDir = $"{_DelegationInfo.TeamName}_{_DelegationInfo.Id}";
  1341. var sourceFolderPath = AppSettingsHelper.Get("ReceivablesUploadFileBasePath");
  1342. if (!Directory.Exists(sourceFolderPath))
  1343. {
  1344. return NotFound(JsonView(false, $"文件夹不存在: {sourceFolderPath}"));
  1345. }
  1346. // 3. 检查文件夹是否为空
  1347. var files = Directory.GetFiles(sourceFolderPath, "*.*", SearchOption.AllDirectories);
  1348. if (files.Length == 0)
  1349. {
  1350. return BadRequest(JsonView(false, $"文件夹为空: {Path.GetFileName(sourceFolderPath)}"));
  1351. }
  1352. for (int i = 0; i < filePaths.Count; i++)
  1353. {
  1354. filePaths[i] = Path.Combine(sourceFolderPath, filePaths[i]);
  1355. }
  1356. // 4. 生成目标Zip文件路径
  1357. var zipFileName = $"{_DelegationInfo.TeamName}_{Guid.NewGuid().ToString().Substring(0, 8)}.zip";
  1358. string targetZipPath = Path.Combine(
  1359. AppSettingsHelper.Get("ReceivablesUploadFileBasePath") + @"/" + groupDir,
  1360. zipFileName
  1361. );
  1362. // 或者如果已经有特定的zip文件名,确保添加扩展名
  1363. // string targetZipPath = Path.Combine(sourceFolderPath, "ReceivablesFiles.zip");
  1364. // 5. 确保目标目录存在(应该已经存在)
  1365. var targetDirectory = Path.GetDirectoryName(targetZipPath);
  1366. if (!Directory.Exists(targetDirectory))
  1367. {
  1368. Directory.CreateDirectory(targetDirectory);
  1369. }
  1370. // 6. 检查并处理现有文件
  1371. if (System.IO.File.Exists(targetZipPath))
  1372. {
  1373. try
  1374. {
  1375. System.IO.File.Delete(targetZipPath);
  1376. }
  1377. catch (IOException ex)
  1378. {
  1379. // 文件可能被占用,尝试生成新的文件名
  1380. targetZipPath = Path.Combine(
  1381. Path.GetDirectoryName(targetZipPath),
  1382. $"{Path.GetFileNameWithoutExtension(targetZipPath)}_{DateTime.Now:HHmmss}{Path.GetExtension(targetZipPath)}"
  1383. );
  1384. }
  1385. }
  1386. // 7. 验证源文件是否存在
  1387. var missingFiles = filePaths.Where(f => !System.IO.File.Exists(f)).ToList();
  1388. if (missingFiles.Any())
  1389. {
  1390. return Ok(JsonView(false, $"以下文件不存在: {string.Join(", ", missingFiles.Select(Path.GetFileName))}"));
  1391. }
  1392. // 8. 创建Zip包
  1393. try
  1394. {
  1395. sourceFolderPath = sourceFolderPath + @"\" + groupDir;
  1396. using (var zipFileStream = new FileStream(targetZipPath, FileMode.Create))
  1397. {
  1398. using (var zipArchive = new ZipArchive(zipFileStream, ZipArchiveMode.Create))
  1399. {
  1400. foreach (string filePath in filePaths)
  1401. {
  1402. if (!string.IsNullOrEmpty(filePath) && System.IO.File.Exists(filePath))
  1403. {
  1404. // 使用相对路径作为zip内的文件结构
  1405. string relativePath = filePath.Substring(sourceFolderPath.Length).TrimStart('\\', '/');
  1406. zipArchive.CreateEntryFromFile(filePath, relativePath);
  1407. }
  1408. }
  1409. }
  1410. }
  1411. }
  1412. catch (UnauthorizedAccessException ex)
  1413. {
  1414. // 特定处理权限错误
  1415. return Ok(JsonView(false, $"没有权限创建文件到目录: {Path.GetDirectoryName(targetZipPath)},错误: {ex.Message}"));
  1416. }
  1417. catch (IOException ex)
  1418. {
  1419. // 处理文件被占用等情况
  1420. return Ok(JsonView(false, $"文件操作失败,可能文件被占用: {ex.Message}"));
  1421. }
  1422. // 9. 验证Zip文件是否创建成功
  1423. if (!System.IO.File.Exists(targetZipPath))
  1424. {
  1425. return Ok(JsonView(false, "Zip文件创建失败!"));
  1426. }
  1427. // 10. 返回文件信息
  1428. var url = @$"{AppSettingsHelper.Get("OfficeBaseUrl")}{AppSettingsHelper.Get("ReceivablesUploadFileFtpPath")}/{groupDir}/{zipFileName}";
  1429. return Ok(JsonView(true, "操作成功!", new { Url = url }));
  1430. }
  1431. catch (Exception ex)
  1432. {
  1433. // 记录详细错误日志
  1434. _logger.LogError(ex, "创建应收款文件Zip包失败");
  1435. return Ok(JsonView(false, $"系统错误: {ex.Message}"));
  1436. }
  1437. }
  1438. return Ok(JsonView(false));
  1439. }
  1440. catch (Exception ex)
  1441. {
  1442. return Ok(JsonView(false, ex.Message));
  1443. }
  1444. }
  1445. /// <summary>
  1446. /// decimal保留指定位数小数
  1447. /// </summary>
  1448. /// <param name="num">原始数量</param>
  1449. /// <param name="scale">保留小数位数</param>
  1450. /// <returns>截取指定小数位数后的数量字符串</returns>
  1451. private static string DecimalToString(decimal num, int scale)
  1452. {
  1453. string numToString = num.ToString();
  1454. int index = numToString.IndexOf(".");
  1455. int length = numToString.Length;
  1456. if (index != -1)
  1457. {
  1458. return string.Format("{0}.{1}",
  1459. numToString.Substring(0, index),
  1460. numToString.Substring(index + 1, Math.Min(length - index - 1, scale)));
  1461. }
  1462. else
  1463. {
  1464. return num.ToString();
  1465. }
  1466. }
  1467. /// <summary>
  1468. /// 保留小数位数
  1469. /// </summary>
  1470. /// <param name="n">待处理的值</param>
  1471. /// <param name="d">保留位数</param>
  1472. /// <param name="isEnter">是否四舍五入</param>
  1473. /// <returns></returns>
  1474. private static decimal Round(decimal n, int d, bool isEnter = false)
  1475. {
  1476. if (isEnter)
  1477. return decimal.Round(n, d, MidpointRounding.AwayFromZero);
  1478. return Math.Truncate(n * (decimal)Math.Pow(10, d)) / (decimal)Math.Pow(10, d);
  1479. }
  1480. private void SetCells(Aspose.Words.Tables.Table table, Document doc, int rows, int cells, string val)
  1481. {
  1482. //获取table中的某个单元格,从0开始
  1483. Aspose.Words.Tables.Cell lshCell = table.Rows[rows].Cells[cells];
  1484. //将单元格中的第一个段落移除
  1485. lshCell.FirstParagraph.Remove();
  1486. //if (cells == 0) lshCell.CellFormat.Width = 120;
  1487. //else if (cells == 1) lshCell.CellFormat.Width = 50;
  1488. //else if (cells == 2) lshCell.CellFormat.Width = 120;
  1489. //else if (cells == 3) lshCell.CellFormat.Width = 100;
  1490. //else if (cells == 4) lshCell.CellFormat.Width = 120;
  1491. //新建一个段落
  1492. var p = new Paragraph(doc);
  1493. var r = new Run(doc, val);
  1494. r.Font.Size = 8;
  1495. //把设置的值赋给之前新建的段落
  1496. p.AppendChild(r);
  1497. //将此段落加到单元格内
  1498. lshCell.AppendChild(p);
  1499. }
  1500. /// <summary>
  1501. /// 已收账单
  1502. /// 提示导入出入境报价费用
  1503. /// </summary>
  1504. /// <param name="groupId"></param>
  1505. /// <returns></returns>
  1506. [HttpPost]
  1507. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1508. public async Task<IActionResult> PostReceivablesImportFee(int groupId)
  1509. {
  1510. if (groupId < 1) return Ok(JsonView(false, "请传入有效的GroupId参数!"));
  1511. var data = await GeneralMethod.ReceivablesImportFeeAsync(groupId);
  1512. var view = _mapper.Map<List<ProceedsReceivedNewView>>(data);
  1513. return Ok(JsonView(true, "操作成功", view));
  1514. }
  1515. /// <summary>
  1516. /// 已收账单上传文件
  1517. /// </summary>
  1518. /// <param name="groupId">团组ID</param>
  1519. /// <param name="files">上传的文件列表</param>
  1520. /// <returns>操作结果</returns>
  1521. [HttpPost]
  1522. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1523. [ProducesResponseType(typeof(JsonView), StatusCodes.Status400BadRequest)]
  1524. public async Task<IActionResult> ReceivablesUploadFile(int groupId, List<IFormFile> files)
  1525. {
  1526. try
  1527. {
  1528. // 1. 参数验证
  1529. if (groupId < 1) return Ok(JsonView(false, "请传入有效的GroupId参数!"));
  1530. if (files == null || !files.Any()) return Ok(JsonView(false, "请选择要上传的文件!"));
  1531. // 2. 文件验证
  1532. var fileValidationResult = await ValidateFilesAsync(files);
  1533. if (!fileValidationResult.IsValid)
  1534. {
  1535. return Ok(JsonView(false, fileValidationResult.ErrorMessage));
  1536. }
  1537. // 3. 检查团组信息
  1538. var groupInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>().FirstAsync(x => x.IsDel == 0 && x.Id == groupId);
  1539. if (groupInfo == null)
  1540. {
  1541. return Ok(JsonView(false, $"团组信息不存在!"));
  1542. }
  1543. // 4. 创建文件存储目录
  1544. var groupDir = @$"{groupInfo.TeamName}_{groupInfo.Id}";
  1545. var fileServerPath = AppSettingsHelper.Get("ReceivablesUploadFileBasePath") + @"/" + groupDir;
  1546. if (!Directory.Exists(fileServerPath)) Directory.CreateDirectory(fileServerPath);
  1547. // 5. 为文件生成安全文件名
  1548. var uploadResults = new List<string>();
  1549. foreach (var file in fileValidationResult.ValidFiles)
  1550. {
  1551. var safeFileName = GenerateSafeFileName(file.FileName, groupInfo);
  1552. var savePath = Path.Combine(fileServerPath, safeFileName);
  1553. // 防止文件名冲突
  1554. var uniqueFileName = GetUniqueFileName(savePath);
  1555. var finalSavePath = Path.Combine(fileServerPath, uniqueFileName);
  1556. // 确保资源释放
  1557. using (var fileStream = new FileStream(finalSavePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
  1558. {
  1559. await file.CopyToAsync(fileStream);
  1560. // 刷新缓冲区
  1561. await fileStream.FlushAsync();
  1562. }
  1563. uploadResults.Add($"{groupDir}/{uniqueFileName}");
  1564. }
  1565. if (!uploadResults.Any())
  1566. {
  1567. return Ok(JsonView(false, "文件存储失败!"));
  1568. }
  1569. // 5. 数据库存储路径
  1570. var upd = await _sqlSugar.Updateable<Grp_DelegationInfo>()
  1571. .SetColumns(x => x.FrFilePaths == uploadResults)
  1572. .Where(x => x.Id == groupId)
  1573. .ExecuteCommandAsync();
  1574. if (upd < 1)
  1575. {
  1576. return Ok(JsonView(false, "文件路径存储失败!"));
  1577. }
  1578. // 返回上传结果
  1579. var url = AppSettingsHelper.Get("OfficeBaseUrl");
  1580. var pathPrefix = AppSettingsHelper.Get("ReceivablesUploadFileFtpPath");
  1581. for (int i = 0; i < uploadResults.Count; i++)
  1582. {
  1583. uploadResults[i] = @$"{url}/{pathPrefix}/{uploadResults[i]}";
  1584. }
  1585. return Ok(JsonView(true, "操作成功!", uploadResults));
  1586. }
  1587. catch (Exception ex)
  1588. {
  1589. _logger.LogError(ex, "已收账单文件上传失败,GroupId: {GroupId}", groupId);
  1590. return StatusCode(StatusCodes.Status500InternalServerError,
  1591. JsonView(false, "系统繁忙,请稍后重试"));
  1592. }
  1593. }
  1594. #region 文件名安全处理
  1595. /// <summary>
  1596. /// 生成安全的文件名
  1597. /// </summary>
  1598. private string GenerateSafeFileName(string originalFileName, Grp_DelegationInfo groupInfo)
  1599. {
  1600. // 1. 移除路径信息,只保留文件名
  1601. var fileName = Path.GetFileName(originalFileName);
  1602. // 2. 移除特殊字符和危险字符
  1603. fileName = RemoveDangerousCharacters(fileName);
  1604. // 3. 移除或替换空白字符
  1605. fileName = RemoveWhitespaceCharacters(fileName);
  1606. // 4. 限制文件名长度
  1607. fileName = LimitFileNameLength(fileName);
  1608. // 5. 可选:添加时间戳和团组标识
  1609. //fileName = AddFileIdentifier(fileName, groupInfo);
  1610. return fileName;
  1611. }
  1612. /// <summary>
  1613. /// 移除危险字符
  1614. /// </summary>
  1615. private string RemoveDangerousCharacters(string fileName)
  1616. {
  1617. if (string.IsNullOrWhiteSpace(fileName))
  1618. return Guid.NewGuid().ToString(); // 如果文件名无效,生成GUID
  1619. // 定义危险字符(包含路径遍历、特殊系统字符等)
  1620. var dangerousChars = new[]
  1621. {
  1622. "..", "/", "\\", ":", "*", "?", "\"", "<", ">", "|",
  1623. "\0", "\r", "\n", "\t", "\b", "\f" // 控制字符
  1624. };
  1625. // 定义需要替换的字符
  1626. var charMap = new Dictionary<char, char>
  1627. {
  1628. ['#'] = '-',
  1629. ['%'] = '-',
  1630. ['&'] = '-',
  1631. ['@'] = '-',
  1632. ['+'] = '-',
  1633. ['='] = '-',
  1634. [';'] = '-',
  1635. [','] = '-',
  1636. ['`'] = '-',
  1637. ['~'] = '-',
  1638. ['!'] = '-',
  1639. ['^'] = '-',
  1640. ['('] = '-',
  1641. [')'] = '-',
  1642. ['['] = '-',
  1643. [']'] = '-',
  1644. ['{'] = '-',
  1645. ['}'] = '-',
  1646. ['$'] = '-'
  1647. };
  1648. // 移除危险字符串
  1649. foreach (var dangerous in dangerousChars)
  1650. {
  1651. fileName = fileName.Replace(dangerous, string.Empty);
  1652. }
  1653. // 替换特殊字符
  1654. var chars = fileName.ToCharArray();
  1655. for (int i = 0; i < chars.Length; i++)
  1656. {
  1657. if (charMap.TryGetValue(chars[i], out var replacement))
  1658. {
  1659. chars[i] = replacement;
  1660. }
  1661. }
  1662. return new string(chars);
  1663. }
  1664. /// <summary>
  1665. /// 移除空白字符
  1666. /// </summary>
  1667. private string RemoveWhitespaceCharacters(string fileName)
  1668. {
  1669. // 移除开头和结尾的空白
  1670. fileName = fileName.Trim();
  1671. // 替换内部连续空白为单个下划线
  1672. var regex = new Regex(@"\s+");
  1673. fileName = regex.Replace(fileName, "_");
  1674. return fileName;
  1675. }
  1676. /// <summary>
  1677. /// 限制文件名长度
  1678. /// </summary>
  1679. private string LimitFileNameLength(string fileName)
  1680. {
  1681. const int maxFileNameLength = 100; // 限制文件名最大长度
  1682. if (fileName.Length <= maxFileNameLength)
  1683. return fileName;
  1684. // 获取文件扩展名
  1685. var extension = Path.GetExtension(fileName);
  1686. var nameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
  1687. if (string.IsNullOrEmpty(extension))
  1688. {
  1689. // 没有扩展名,直接截断
  1690. return fileName.Substring(0, maxFileNameLength);
  1691. }
  1692. // 保留扩展名,截断主文件名
  1693. var maxNameLength = maxFileNameLength - extension.Length;
  1694. if (maxNameLength <= 0)
  1695. {
  1696. // 如果扩展名太长,使用短名称
  1697. return Guid.NewGuid().ToString().Substring(0, 8) + extension;
  1698. }
  1699. if (nameWithoutExtension.Length > maxNameLength)
  1700. {
  1701. nameWithoutExtension = nameWithoutExtension.Substring(0, maxNameLength);
  1702. }
  1703. return nameWithoutExtension + extension;
  1704. }
  1705. /// <summary>
  1706. /// 添加文件标识符
  1707. /// </summary>
  1708. private string AddFileIdentifier(string fileName, Grp_DelegationInfo groupInfo)
  1709. {
  1710. // 可选:添加时间戳
  1711. var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
  1712. // 可选:添加团组标识
  1713. var groupIdentifier = $"{groupInfo.TeamName}_{groupInfo.Id}";
  1714. groupIdentifier = RemoveDangerousCharacters(groupIdentifier);
  1715. groupIdentifier = RemoveWhitespaceCharacters(groupIdentifier);
  1716. // 获取文件扩展名
  1717. var extension = Path.GetExtension(fileName);
  1718. var nameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
  1719. // 如果文件名太短,添加标识符
  1720. if (string.IsNullOrWhiteSpace(nameWithoutExtension) || nameWithoutExtension.Length < 3)
  1721. {
  1722. nameWithoutExtension = $"{groupIdentifier}_{timestamp}";
  1723. }
  1724. else
  1725. {
  1726. // 添加标识符前缀
  1727. nameWithoutExtension = $"{groupIdentifier}_{timestamp}_{nameWithoutExtension}";
  1728. }
  1729. return nameWithoutExtension + extension;
  1730. }
  1731. /// <summary>
  1732. /// 获取唯一文件名(防止冲突)
  1733. /// </summary>
  1734. private string GetUniqueFileName(string filePath)
  1735. {
  1736. var directory = Path.GetDirectoryName(filePath);
  1737. var fileName = Path.GetFileName(filePath);
  1738. var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
  1739. var extension = Path.GetExtension(fileName);
  1740. var counter = 1;
  1741. var newFileName = fileName;
  1742. while (System.IO.File.Exists(Path.Combine(directory, newFileName)))
  1743. {
  1744. newFileName = $"{fileNameWithoutExtension}_{counter}{extension}";
  1745. counter++;
  1746. // 防止无限循环
  1747. if (counter > 1000)
  1748. {
  1749. newFileName = $"{fileNameWithoutExtension}_{Guid.NewGuid().ToString().Substring(0, 8)}{extension}";
  1750. break;
  1751. }
  1752. }
  1753. return newFileName;
  1754. }
  1755. #region 私有方法
  1756. /// <summary>
  1757. /// 验证文件
  1758. /// </summary>
  1759. private async Task<(bool IsValid, string ErrorMessage, List<IFormFile> ValidFiles)> ValidateFilesAsync(List<IFormFile> files)
  1760. {
  1761. var allowedExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
  1762. {
  1763. ".pdf", ".xls", ".xlsx", ".jpg", ".jpeg", ".png", ".doc", ".docx", ".txt"
  1764. };
  1765. const long maxFileSize = 20 * 1024 * 1024; // 20MB
  1766. var invalidFiles = new List<string>();
  1767. var validFiles = new List<IFormFile>();
  1768. foreach (var file in files)
  1769. {
  1770. // 检查文件大小
  1771. if (file.Length > maxFileSize)
  1772. {
  1773. string[] sizes = { "B", "KB", "MB", "GB", "TB" };
  1774. double len = file.Length;
  1775. int order = 0;
  1776. while (len >= 1024 && order < sizes.Length - 1)
  1777. {
  1778. order++;
  1779. len = len / 1024;
  1780. }
  1781. string fileSize = string.Format("{0:0.##} {1}", len, sizes[order]);
  1782. invalidFiles.Add($"{file.FileName} 文件大小({fileSize})超过限制(20MB)");
  1783. continue;
  1784. }
  1785. // 检查扩展名
  1786. var fileExtension = Path.GetExtension(file.FileName);
  1787. if (string.IsNullOrEmpty(fileExtension) || !allowedExtensions.Contains(fileExtension))
  1788. {
  1789. invalidFiles.Add($"{file.FileName} 文件类型({fileExtension})不支持");
  1790. continue;
  1791. }
  1792. // 基础文件名安全检查
  1793. var fileName = Path.GetFileName(file.FileName);
  1794. if (!IsFileNameSafe(fileName))
  1795. {
  1796. invalidFiles.Add($"{file.FileName} 文件名包含非法字符");
  1797. continue;
  1798. }
  1799. validFiles.Add(file);
  1800. }
  1801. if (invalidFiles.Any())
  1802. {
  1803. return (false, $"文件验证失败: {string.Join("; ", invalidFiles)}", new List<IFormFile>());
  1804. }
  1805. return (true, string.Empty, validFiles);
  1806. }
  1807. /// <summary>
  1808. /// 基础文件名安全检查
  1809. /// </summary>
  1810. private bool IsFileNameSafe(string fileName)
  1811. {
  1812. if (string.IsNullOrWhiteSpace(fileName))
  1813. return false;
  1814. // 检查是否包含路径遍历
  1815. if (fileName.Contains(".."))
  1816. return false;
  1817. // 检查是否包含路径分隔符
  1818. if (fileName.Contains("/") || fileName.Contains("\\"))
  1819. return false;
  1820. // 检查系统保留字符
  1821. var systemChars = new[] { ":", "*", "?", "\"", "<", ">", "|", "\0" };
  1822. if (systemChars.Any(ch => fileName.Contains(ch)))
  1823. return false;
  1824. return true;
  1825. }
  1826. // ... 其他方法保持不变
  1827. #endregion
  1828. #endregion
  1829. /// <summary>
  1830. /// 已收账单 删除已上传的文件
  1831. /// </summary>
  1832. /// <param name="groupId">团组ID</param>
  1833. /// <param name="fileName">要删除的文件名</param>
  1834. /// <returns>操作结果</returns>
  1835. [HttpDelete]
  1836. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1837. [ProducesResponseType(typeof(JsonView), StatusCodes.Status400BadRequest)]
  1838. [ProducesResponseType(typeof(JsonView), StatusCodes.Status404NotFound)]
  1839. public async Task<IActionResult> DeleteReceivablesFile(int groupId, [FromBody] string fileName)
  1840. {
  1841. try
  1842. {
  1843. // 1. 参数验证
  1844. if (groupId < 1)
  1845. {
  1846. return Ok(JsonView(false, "请传入有效的GroupId参数!"));
  1847. }
  1848. if (string.IsNullOrWhiteSpace(fileName))
  1849. {
  1850. return Ok(JsonView(false, "请指定要删除的文件名!"));
  1851. }
  1852. // 2. 安全检查:防止路径遍历攻击
  1853. if (fileName.Contains("..") || fileName.Contains("/") || fileName.Contains("\\"))
  1854. {
  1855. return Ok(JsonView(false, "文件名包含非法字符!"));
  1856. }
  1857. // 3. 获取团组信息
  1858. var groupInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>().FirstAsync(x => x.IsDel == 0 && x.Id == groupId);
  1859. if (groupInfo == null)
  1860. {
  1861. return Ok(JsonView(false, $"团组信息不存在!"));
  1862. }
  1863. // 4. 获取当前文件列表
  1864. var currentFilePaths = groupInfo.FrFilePaths ?? new List<string>();
  1865. var groupDir = @$"{groupInfo.TeamName}({groupInfo.Id})";
  1866. // 5. 检查要删除的文件是否存在
  1867. if (!currentFilePaths.Contains(groupDir + @"/" + fileName))
  1868. {
  1869. return Ok(JsonView(false, $"文件 '{fileName}' 不存在于该团组的文件列表中!"));
  1870. }
  1871. // 6. 构建文件完整路径
  1872. var fileServerPath = AppSettingsHelper.Get("ReceivablesUploadFileBasePath") + @"/" + groupDir;
  1873. var fullFilePath = Path.Combine(fileServerPath, fileName);
  1874. // 7. 验证文件是否存在
  1875. if (!System.IO.File.Exists(fullFilePath))
  1876. {
  1877. // 文件在磁盘上不存在,但从数据库中移除记录
  1878. var upd = await RemoveFileFromDatabaseAsync(groupId, groupDir + @"/" + fileName, currentFilePaths);
  1879. return Ok(JsonView(false, $"文件 '{fileName}' 在服务器上不存在,已从数据库中移除记录!"));
  1880. }
  1881. // 8. 删除物理文件
  1882. bool fileDeleted = false;
  1883. try
  1884. {
  1885. System.IO.File.Delete(fullFilePath);
  1886. fileDeleted = true;
  1887. }
  1888. catch (IOException ioEx)
  1889. {
  1890. _logger.LogError(ioEx, "删除文件失败,FilePath: {FilePath}", fullFilePath);
  1891. return Ok(JsonView(false, $"删除文件失败:文件可能正在被使用或不存在。"));
  1892. }
  1893. catch (UnauthorizedAccessException authEx)
  1894. {
  1895. _logger.LogError(authEx, "删除文件权限不足,FilePath: {FilePath}", fullFilePath);
  1896. return Ok(JsonView(false, $"删除文件失败:权限不足。"));
  1897. }
  1898. if (!fileDeleted)
  1899. {
  1900. return Ok(JsonView(false, $"删除文件失败!"));
  1901. }
  1902. // 9. 更新数据库(从文件列表中移除该文件)
  1903. await RemoveFileFromDatabaseAsync(groupId, groupDir + @"/" + fileName, currentFilePaths);
  1904. return Ok(JsonView(true, $"文件 '{fileName}' 删除成功!"));
  1905. }
  1906. catch (Exception ex)
  1907. {
  1908. _logger.LogError(ex, "删除文件失败,GroupId: {GroupId}, FileName: {FileName}", groupId, fileName);
  1909. return StatusCode(StatusCodes.Status500InternalServerError,
  1910. JsonView(false, "系统繁忙,请稍后重试"));
  1911. }
  1912. }
  1913. /// <summary>
  1914. /// 从数据库中移除文件记录
  1915. /// </summary>
  1916. private async Task<bool> RemoveFileFromDatabaseAsync(int groupId, string fileName, List<string> currentFilePaths)
  1917. {
  1918. try
  1919. {
  1920. // 从当前文件列表中移除指定文件
  1921. var updatedFileList = currentFilePaths.Where(f => f != fileName).ToList();
  1922. // 更新数据库
  1923. var upd = await _sqlSugar.Updateable<Grp_DelegationInfo>()
  1924. .SetColumns(x => x.FrFilePaths == updatedFileList)
  1925. .Where(x => x.Id == groupId)
  1926. .ExecuteCommandAsync();
  1927. return upd > 0;
  1928. }
  1929. catch (Exception ex)
  1930. {
  1931. _logger.LogError(ex, "更新数据库文件列表失败,GroupId: {GroupId}, FileName: {FileName}",
  1932. groupId, fileName);
  1933. }
  1934. return false;
  1935. }
  1936. #endregion
  1937. #region 已收款项
  1938. /// <summary>
  1939. /// 已收款项
  1940. /// 查询
  1941. /// </summary>
  1942. /// <param name="dto"></param>
  1943. /// <returns></returns>
  1944. [HttpPost]
  1945. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1946. public async Task<IActionResult> PostAmountReceived(AmountReceivedDto dto)
  1947. {
  1948. try
  1949. {
  1950. if (dto == null)
  1951. {
  1952. return Ok(JsonView(false, "参数不能为空!"));
  1953. }
  1954. Result ffrData = await _proceedsReceivedRep.PostAmountReceived(dto.DiId);
  1955. dynamic data = null;
  1956. if (dto.PortType == 1)
  1957. {
  1958. if (ffrData.Code != 0)
  1959. {
  1960. return Ok(JsonView(false, ffrData.Msg));
  1961. }
  1962. data = ffrData.Data;
  1963. }
  1964. else if (dto.PortType == 2)
  1965. {
  1966. if (ffrData.Code != 0)
  1967. {
  1968. return Ok(JsonView(false, ffrData.Msg));
  1969. }
  1970. data = ffrData.Data;
  1971. }
  1972. else if (dto.PortType == 2)
  1973. {
  1974. if (ffrData.Code != 0)
  1975. {
  1976. return Ok(JsonView(false, ffrData.Msg));
  1977. }
  1978. data = ffrData.Data;
  1979. }
  1980. else return Ok(JsonView(false, "请选择正确的端口号!"));
  1981. return Ok(JsonView(true, "操作成功!", data));
  1982. }
  1983. catch (Exception ex)
  1984. {
  1985. return Ok(JsonView(false, ex.Message));
  1986. }
  1987. }
  1988. /// <summary>
  1989. /// 已收款项
  1990. /// Add Or Edit
  1991. /// </summary>
  1992. /// <param name="dto"></param>
  1993. /// <returns></returns>
  1994. [HttpPost]
  1995. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1996. public async Task<IActionResult> PostAmountReceivedAddOrEdit(AmountReceivedAddOrEditDto dto)
  1997. {
  1998. try
  1999. {
  2000. if (dto == null)
  2001. {
  2002. return Ok(JsonView(false, "参数不能为空!"));
  2003. }
  2004. Result ffrData = await _proceedsReceivedRep.PostAmountReceivedAddOrEditDto(dto);
  2005. #region 判断金额是否收完
  2006. //已收
  2007. var Fin_ProceedsReceived_SumPrice = _sqlSugar
  2008. .Queryable<Fin_ProceedsReceived>()
  2009. .Where(x => x.Diid == dto.DiId && x.IsDel == 0)
  2010. .Sum(x => x.Price);
  2011. //收款账单金额 (应收)
  2012. var Fin_ForeignReceivables_SumPrice = _sqlSugar
  2013. .Queryable<Fin_ForeignReceivables>()
  2014. .Where(x => x.Diid == dto.DiId && x.IsDel == 0)
  2015. .Sum(x => x.ItemSumPrice);
  2016. if ((Fin_ProceedsReceived_SumPrice - Fin_ForeignReceivables_SumPrice) >= 0)
  2017. {
  2018. _sqlSugar.Updateable<Grp_DelegationInfo>()
  2019. .Where(x => x.Id == dto.DiId && x.IsDel == 0)
  2020. .SetColumns(x => new Grp_DelegationInfo { IsSure = 1 })
  2021. .ExecuteCommand();
  2022. }
  2023. #endregion
  2024. if (dto.PortType == 1)
  2025. {
  2026. if (ffrData.Code != 0)
  2027. {
  2028. return Ok(JsonView(false, ffrData.Msg));
  2029. }
  2030. }
  2031. else if (dto.PortType == 2)
  2032. {
  2033. if (ffrData.Code != 0)
  2034. {
  2035. return Ok(JsonView(false, ffrData.Msg));
  2036. }
  2037. }
  2038. else if (dto.PortType == 2)
  2039. {
  2040. if (ffrData.Code != 0)
  2041. {
  2042. return Ok(JsonView(false, ffrData.Msg));
  2043. }
  2044. }
  2045. else
  2046. {
  2047. return Ok(JsonView(false, "请选择正确的端口号!"));
  2048. }
  2049. return Ok(JsonView(true, "操作成功!"));
  2050. }
  2051. catch (Exception ex)
  2052. {
  2053. return Ok(JsonView(false, ex.Message));
  2054. }
  2055. }
  2056. /// <summary>
  2057. /// 已收款项
  2058. /// Del
  2059. /// </summary>
  2060. /// <param name="dto"></param>
  2061. /// <returns></returns>
  2062. [HttpPost]
  2063. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2064. public async Task<IActionResult> PostAmountReceived_Del(AmountReceivedDelDto dto)
  2065. {
  2066. try
  2067. {
  2068. if (dto == null)
  2069. {
  2070. return Ok(JsonView(false, "参数不能为空!"));
  2071. }
  2072. Result ffrData = await _proceedsReceivedRep.PostAmountReceivedDel(dto);
  2073. if (ffrData.Code != 0)
  2074. {
  2075. return Ok(JsonView(false, ffrData.Msg));
  2076. }
  2077. return Ok(JsonView(true, "操作成功!"));
  2078. }
  2079. catch (Exception ex)
  2080. {
  2081. return Ok(JsonView(false, ex.Message));
  2082. }
  2083. }
  2084. /// <summary>
  2085. /// 已收款项
  2086. /// 会计团组费用excel下载
  2087. /// </summary>
  2088. /// <param name="dto"></param>
  2089. /// <returns></returns>
  2090. [HttpPost]
  2091. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2092. public async Task<IActionResult> GroupAccFee‌ExcelDownload(GroupAccFee‌ExcelDto dto)
  2093. {
  2094. //用户权限验证:只有财务部门的同事才能下载
  2095. var userInfo = await _sqlSugar.Queryable<Sys_Users>()
  2096. .LeftJoin<Sys_Department>((x, y) => x.DepId == y.Id)
  2097. .Where((x, y) => x.Id == dto.UserId && x.IsDel == 0 && y.DepName.Contains("财务"))
  2098. .FirstAsync();
  2099. if (userInfo == null) return Ok(JsonView(false, "只有财务部同事可下载!"));
  2100. //团组信息验证
  2101. var groupInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  2102. .FirstAsync(x => x.Id == dto.GroupId && x.IsDel == 0);
  2103. if (groupInfo == null) return Ok(JsonView(false, "团组信息不存在或已删除,不可下载!"));
  2104. //已收款项信息验证
  2105. var proceedInfos = await _sqlSugar.Queryable<Fin_ProceedsReceived>()
  2106. .Where(x => x.Diid == dto.GroupId && x.IsDel == 0)
  2107. .Select(x => new GroupAccFee‌ExcelView()
  2108. {
  2109. OrgName‌ = x.Client,
  2110. VisitorNum‌ = 1, //假设每条记录代表一个访客
  2111. ActualAR = 0.00M,
  2112. PaidDate‌ = x.SectionTime,
  2113. PaidAmount‌ = x.Price,
  2114. Remark = x.Remark,
  2115. })
  2116. .ToListAsync();
  2117. if (!proceedInfos.Any()) return Ok(JsonView(false, "已收款项信息不存在或已删除,不可下载!"));
  2118. var costInfo = await _sqlSugar.Queryable<Grp_EnterExitCost>()
  2119. .Where(x => x.DiId == dto.GroupId && x.IsDel == 0)
  2120. .FirstAsync();
  2121. var rateInfos = CommonFun.GetCurrencyChinaToList(costInfo.CurrencyRemark);
  2122. var hotelCostInfos = await _sqlSugar.Queryable<Grp_DayAndCost>()
  2123. .LeftJoin<Sys_SetData>((x, y) => x.Currency == y.Id)
  2124. .Where((x, y) => x.DiId == dto.GroupId && x.Type == 1 && x.IsDel == 0)
  2125. .Select((x, y) => new { x.Place, x.Cost, x.Currency, y.Name, CurrencyName = y.Remark, Rate = x.SubTotal / x.Cost, x.SubTotal })
  2126. .ToListAsync();
  2127. decimal visaFee = costInfo?.Visa ?? 0.00M, //签证费
  2128. //intercityFare = costInfo?.CityTranffic ?? 0.00M, //城市区间交通费
  2129. hotelFee = hotelCostInfos.Sum(x => x.Cost), //住宿费
  2130. hotelCNYEquivalent = hotelCostInfos.Sum(x => x.SubTotal), //住宿费CNY折算价
  2131. hotelRate = rateInfos.FirstOrDefault(x => x.CurrencyCode.Equals(hotelCostInfos.FirstOrDefault().Name))?.Rate ?? 0.00M; //住宿费汇率
  2132. string hotelCurrency = hotelCostInfos.FirstOrDefault()?.CurrencyName ?? "-"; //住宿费币种
  2133. var costInfosNew = new List<GroupAccFee‌ExcelView>() {
  2134. new (){ CostName = "酒店",CostAmt = hotelFee,CostCurrency = hotelCurrency, CostRate = hotelRate, CNYEquivalent = hotelCNYEquivalent},
  2135. new (){ CostName = "市区间交通-经济舱",CostAmt = costInfo?.CityTranffic ?? 0.00M,CostCurrency = "人民币" },
  2136. new (){ CostName = "市区间交通-公务舱",CostAmt = costInfo?.CityTranffic1 ?? 0.00M,CostCurrency = "人民币" },
  2137. new (){ CostName = "市区间交通-头等舱",CostAmt = costInfo?.CityTranffic2 ?? 0.00M,CostCurrency = "人民币" },
  2138. new (){ CostName = "签证",CostAmt = visaFee,CostCurrency = "人民币" },
  2139. };
  2140. if (proceedInfos == null || proceedInfos.Count < 1) proceedInfos = costInfosNew;
  2141. int replaceCount = Math.Min(proceedInfos.Count, costInfosNew.Count);
  2142. // 替换元素
  2143. for (int i = 0; i < replaceCount; i++)
  2144. {
  2145. var newInfo = costInfosNew[i];
  2146. proceedInfos[i].CostName = newInfo.CostName;
  2147. if (newInfo.CostAmt != null && newInfo.CostAmt > 0.00M) proceedInfos[i].CostAmt = newInfo.CostAmt;
  2148. if (newInfo.CostRate != null && newInfo.CostRate > 0.00M) proceedInfos[i].CostRate = newInfo.CostRate;
  2149. if (newInfo.CNYEquivalent != null && newInfo.CNYEquivalent > 0.00M) proceedInfos[i].CNYEquivalent = newInfo.CNYEquivalent;
  2150. proceedInfos[i].CostCurrency = newInfo.CostCurrency;
  2151. }
  2152. // 添加剩余元素
  2153. if (costInfosNew.Count > proceedInfos.Count) proceedInfos.AddRange(costInfosNew.Skip(proceedInfos.Count));
  2154. int index = 1;
  2155. proceedInfos.ForEach(x =>
  2156. {
  2157. x.Index = index;
  2158. index++;
  2159. });
  2160. string url = string.Empty;
  2161. #region 生成Excel文件
  2162. var designer = new WorkbookDesigner
  2163. {
  2164. Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/‌GroupAccFee‌Temp.xlsx")
  2165. };
  2166. designer.SetDataSource("DataView", proceedInfos);
  2167. //根据数据源处理生成报表内容
  2168. designer.Process();
  2169. //设置sum函数
  2170. int cellIndex = proceedInfos.Count + 3;
  2171. int cellFormulaIndex = cellIndex - 1;
  2172. var calcFormula‌ = $"=SUM(F3:F{cellFormulaIndex})";
  2173. designer.Workbook.Worksheets[0].Cells[$"F{cellIndex}"].Formula = calcFormula‌;
  2174. //计算sum函数
  2175. designer.Workbook.Worksheets[0].CalculateFormula(new CalculationOptions() { IgnoreError = true }, true);
  2176. string fileName = $"AmountReceived/{groupInfo.TeamName}_会计团组费用{Guid.NewGuid()}.xlsx";
  2177. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  2178. url = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  2179. #endregion
  2180. return Ok(JsonView(true, "操作成功!", url));
  2181. }
  2182. #endregion
  2183. #region 收款退还与其他款项 --> 收款退还
  2184. /// <summary>
  2185. /// 收款退还与其他款项
  2186. /// 查询 根据团组Id
  2187. /// </summary>
  2188. /// <param name="dto"></param>
  2189. /// <returns></returns>
  2190. [HttpPost]
  2191. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2192. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyItemByDiId(PaymentRefundAndOtherMoneyItemByDiIdDto dto)
  2193. {
  2194. if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
  2195. if (dto.PageId <= 0) return Ok(JsonView(false, "请传入正确的的页面Id!"));
  2196. if (dto.UserId <= 0) return Ok(JsonView(false, "请传入正确的的员工Id!"));
  2197. #region 页面功能权限处理
  2198. var pageFunAuth = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  2199. if (pageFunAuth.CheckAuth == 0)
  2200. {
  2201. return Ok(JsonView(false, "您没有当前页面查询权限!"));
  2202. }
  2203. #endregion
  2204. Result _result = await _paymentRefundAndOtherMoneyRep.ItemByDiId(dto.DiId);
  2205. if (dto.PortType == 1 || dto.PortType == 2 || dto.PortType == 3) //1 Web 2 Android 3 Ios
  2206. {
  2207. if (_result.Code != 0)
  2208. {
  2209. return Ok(JsonView(false, _result.Msg));
  2210. }
  2211. var data = new
  2212. {
  2213. PageFuncAuth = pageFunAuth,
  2214. _result.Data
  2215. };
  2216. return Ok(JsonView(true, "操作成功!", data));
  2217. }
  2218. else
  2219. {
  2220. return Ok(JsonView(false, "请输入正确的端口号! 1 Web 2 Android 3 Ios;"));
  2221. }
  2222. }
  2223. /// <summary>
  2224. /// 收款退还与其他款项
  2225. /// 删除
  2226. /// </summary>
  2227. /// <param name="dto"></param>
  2228. /// <returns></returns>
  2229. [HttpPost]
  2230. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2231. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyDel(PaymentRefundAndOtherMoneyDelDto dto)
  2232. {
  2233. if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
  2234. if (dto.PageId <= 0) return Ok(JsonView(false, "请传入正确的的页面Id!"));
  2235. if (dto.UserId <= 0) return Ok(JsonView(false, "请传入正确的的员工Id!"));
  2236. #region 页面功能权限处理
  2237. var pageFunAuth = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  2238. #endregion
  2239. if (pageFunAuth.DeleteAuth == 0)
  2240. {
  2241. return Ok(JsonView(false, "您没有当前页面删除权限!"));
  2242. }
  2243. Result _result = await _paymentRefundAndOtherMoneyRep.Del(dto);
  2244. if (_result.Code != 0)
  2245. {
  2246. return Ok(JsonView(false, _result.Msg));
  2247. }
  2248. return Ok(JsonView(true, "操作成功!"));
  2249. }
  2250. /// <summary>
  2251. /// 收款退还与其他款项
  2252. /// Info Data Source
  2253. /// </summary>
  2254. /// <param name="dto"></param>
  2255. /// <returns></returns>
  2256. [HttpPost]
  2257. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2258. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyInfoDataSource(PortDtoBase dto)
  2259. {
  2260. Result _result = await _paymentRefundAndOtherMoneyRep.InfoDataSource(dto);
  2261. if (_result.Code != 0)
  2262. {
  2263. return Ok(JsonView(false, _result.Msg));
  2264. }
  2265. return Ok(JsonView(true, "查询成功!", _result.Data));
  2266. }
  2267. /// <summary>
  2268. /// 收款退还与其他款项
  2269. /// Info
  2270. /// </summary>
  2271. /// <param name="dto"></param>
  2272. /// <returns></returns>
  2273. [HttpPost]
  2274. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2275. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyInfo(PaymentRefundAndOtherMoneyInfoDto dto)
  2276. {
  2277. if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
  2278. var view = await _paymentRefundAndOtherMoneyRep.Info(dto);
  2279. return Ok(view);
  2280. }
  2281. /// <summary>
  2282. /// 收款退还与其他款项 --> 收款退还(只保留人名币)
  2283. /// 操作(Add Or Edit)
  2284. /// </summary>
  2285. /// <param name="dto"></param>
  2286. /// <returns></returns>
  2287. [HttpPost]
  2288. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2289. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyAddOrEdit(PaymentRefundAndOtherMoneyAddOrEditDto dto)
  2290. {
  2291. if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
  2292. if (dto.PageId <= 0) return Ok(JsonView(false, "请传入正确的的页面Id!"));
  2293. if (dto.UserId <= 0) return Ok(JsonView(false, "请传入正确的的员工Id!"));
  2294. #region 页面功能权限处理
  2295. var pageFunAuth = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  2296. #endregion
  2297. if (dto.Status == 1) //add
  2298. {
  2299. if (pageFunAuth.AddAuth == 0) return Ok(JsonView(false, "您没有当前页面添加权限!"));
  2300. }
  2301. else if (dto.Status == 2) //edit
  2302. {
  2303. if (pageFunAuth.EditAuth == 0) return Ok(JsonView(false, "您没有当前页面编辑权限!"));
  2304. }
  2305. else return Ok(JsonView(false, "请输入正确的操作状态! 1 添加 2 修改!"));
  2306. return Ok(await _paymentRefundAndOtherMoneyRep.AddOrEdit(dto));
  2307. }
  2308. #endregion
  2309. #region 应收报表
  2310. /// <summary>
  2311. /// 查询单个团组的应收报表 费用明细
  2312. /// </summary>
  2313. /// <param name="groupId"></param>
  2314. /// <returns></returns>
  2315. [HttpGet]
  2316. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2317. public async Task<IActionResult> GetSyntheticalReceivableFeeDetails(int groupId)
  2318. {
  2319. // 参数验证
  2320. if (groupId <= 0)
  2321. {
  2322. return Ok(JsonView(false, "团组ID无效。"));
  2323. }
  2324. // 验证团组是否存在
  2325. var groupValid = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  2326. .Where(x => x.Id == groupId && x.IsDel == 0)
  2327. .AnyAsync();
  2328. if (!groupValid)
  2329. {
  2330. return Ok(JsonView(false, "团组ID无效或已被删除。"));
  2331. }
  2332. // 使用参数化查询避免SQL注入
  2333. string sql = @"
  2334. Select
  2335. Id,
  2336. TeamName,
  2337. CTable,
  2338. ModuleName,
  2339. CNYMoney
  2340. from
  2341. (
  2342. SELECT
  2343. di.Id,
  2344. di.TeamName,
  2345. sd.Name AS ModuleName,
  2346. ccp.CTable,
  2347. CASE
  2348. WHEN ccp.CTable = 76 THEN (
  2349. SELECT
  2350. hotelname
  2351. FROM
  2352. Grp_HotelReservations hr
  2353. WHERE
  2354. hr.Id = ccp.CId
  2355. and hr.IsDel = 0
  2356. )
  2357. WHEN ccp.CTable = 79 THEN (
  2358. SELECT
  2359. PriceName
  2360. FROM
  2361. Grp_CarTouristGuideGroundReservations ctgr
  2362. WHERE
  2363. ctgr.Id = ccp.CId
  2364. and ctgr.IsDel = 0
  2365. )
  2366. WHEN ccp.CTable = 80 THEN (
  2367. SELECT
  2368. Area
  2369. FROM
  2370. Grp_VisaInfo vi
  2371. WHERE
  2372. vi.Id = ccp.CId
  2373. and vi.IsDel = 0
  2374. )
  2375. WHEN ccp.CTable = 81 THEN (
  2376. SELECT
  2377. InviterArea
  2378. FROM
  2379. Grp_InvitationOfficialActivities ioa
  2380. WHERE
  2381. ioa.Id = ccp.CId
  2382. and ioa.IsDel = 0
  2383. )
  2384. WHEN ccp.CTable = 82 THEN (
  2385. SELECT
  2386. (
  2387. SELECT
  2388. GName
  2389. FROM
  2390. Grp_InsuranceCost ic
  2391. WHERE
  2392. ic.Id = c.Iid
  2393. )
  2394. FROM
  2395. Grp_Customers c
  2396. WHERE
  2397. c.Id = ccp.CId
  2398. and c.IsDel = 0
  2399. )
  2400. WHEN ccp.CTable = 85 THEN (
  2401. SELECT
  2402. FlightsCode
  2403. FROM
  2404. Grp_AirTicketReservations atr
  2405. WHERE
  2406. atr.Id = ccp.CId
  2407. and atr.IsDel = 0
  2408. )
  2409. WHEN ccp.CTable = 98 THEN (
  2410. SELECT
  2411. PriceName
  2412. FROM
  2413. Grp_DecreasePayments dp
  2414. WHERE
  2415. dp.Id = ccp.CId
  2416. and dp.IsDel = 0
  2417. )
  2418. WHEN ccp.CTable = 1015 THEN (
  2419. SELECT
  2420. PriceName
  2421. FROM
  2422. Fin_GroupExtraCost gec
  2423. WHERE
  2424. gec.Id = ccp.CId
  2425. and gec.IsDel = 0
  2426. )
  2427. ELSE '-'
  2428. END AS PriceName,
  2429. CASE
  2430. WHEN ccp.CTable = 76 THEN (
  2431. SELECT
  2432. IsDel
  2433. FROM
  2434. Grp_HotelReservations hr
  2435. WHERE
  2436. hr.Id = ccp.CId
  2437. and hr.IsDel = 0
  2438. )
  2439. WHEN ccp.CTable = 79 THEN (
  2440. SELECT
  2441. IsDel
  2442. FROM
  2443. Grp_CarTouristGuideGroundReservations ctgr
  2444. WHERE
  2445. ctgr.Id = ccp.CId
  2446. and ctgr.IsDel = 0
  2447. )
  2448. WHEN ccp.CTable = 80 THEN (
  2449. SELECT
  2450. IsDel
  2451. FROM
  2452. Grp_VisaInfo vi
  2453. WHERE
  2454. vi.Id = ccp.CId
  2455. and vi.IsDel = 0
  2456. )
  2457. WHEN ccp.CTable = 81 THEN (
  2458. SELECT
  2459. IsDel
  2460. FROM
  2461. Grp_InvitationOfficialActivities ioa
  2462. WHERE
  2463. ioa.Id = ccp.CId
  2464. and ioa.IsDel = 0
  2465. )
  2466. WHEN ccp.CTable = 82 THEN (
  2467. SELECT
  2468. IsDel
  2469. FROM
  2470. Grp_Customers c
  2471. WHERE
  2472. c.Id = ccp.CId
  2473. and c.IsDel = 0
  2474. )
  2475. WHEN ccp.CTable = 85 THEN (
  2476. SELECT
  2477. IsDel
  2478. FROM
  2479. Grp_AirTicketReservations atr
  2480. WHERE
  2481. atr.Id = ccp.CId
  2482. and atr.IsDel = 0
  2483. )
  2484. WHEN ccp.CTable = 98 THEN (
  2485. SELECT
  2486. IsDel
  2487. FROM
  2488. Grp_DecreasePayments dp
  2489. WHERE
  2490. dp.Id = ccp.CId
  2491. and dp.IsDel = 0
  2492. )
  2493. WHEN ccp.CTable = 1015 THEN (
  2494. SELECT
  2495. IsDel
  2496. FROM
  2497. Fin_GroupExtraCost gec
  2498. WHERE
  2499. gec.Id = ccp.CId
  2500. and gec.IsDel = 0
  2501. )
  2502. ELSE '1'
  2503. END AS ChildIsDel,
  2504. (ccp.PayMoney * ccp.DayRate) AS CNYMoney,
  2505. ccp.IsDel AS CcpIsDel,
  2506. di.IsDel AS DiIsDel
  2507. FROM
  2508. Grp_CreditCardPayment ccp
  2509. INNER JOIN Grp_DelegationInfo di ON ccp.DIId = di.Id
  2510. LEFT JOIN sys_setdata sd ON ccp.CTable = sd.Id
  2511. ) as view1
  2512. WHERE
  2513. DiIsDel = 0
  2514. AND ChildIsDel = 0
  2515. AND DiIsDel = 0
  2516. AND Id = @GroupId";
  2517. try
  2518. {
  2519. var datas = await _sqlSugar.SqlQueryable<SyntheticalReceivableFeeDetailsView>(sql)
  2520. .AddParameters(new { GroupId = groupId })
  2521. .ToListAsync();
  2522. // 分组统计并排序
  2523. var feeDatas = datas
  2524. .GroupBy(g => new { g.CTable, g.ModuleName })
  2525. .Select(s => new SyntheticalReceivableFeeDetailsView
  2526. {
  2527. ModuleName = s.Key.ModuleName ?? "未知模块",
  2528. CTable = s.Key.CTable,
  2529. CNYMoney = s.Sum(ss => ss.CNYMoney)
  2530. })
  2531. .OrderBy(x => x.CTable)
  2532. .ToList();
  2533. // 构建结果字符串
  2534. var feeLabel = new StringBuilder();
  2535. foreach (var item in feeDatas)
  2536. {
  2537. feeLabel.AppendLine($"{item.ModuleName} :{item.CNYMoney:#,##0.00} CNY");
  2538. feeLabel.AppendLine(); // 空行
  2539. }
  2540. // 如果没有数据,返回提示信息
  2541. if (feeDatas.Count == 0)
  2542. {
  2543. return Ok(JsonView(true, "查询成功,但未找到相关费用明细。", "暂无费用明细"));
  2544. }
  2545. return Ok(JsonView(true, "操作成功", feeLabel.ToString()));
  2546. }
  2547. catch (Exception ex)
  2548. {
  2549. // 记录日志
  2550. _logger.LogError(ex, "查询团组费用明细时发生错误,团组ID:{GroupId}", groupId);
  2551. return Ok(JsonView(false, "查询过程中发生错误,请稍后重试。"));
  2552. }
  2553. }
  2554. /// <summary>
  2555. /// 应收报表
  2556. /// 查询 根据日期范围
  2557. /// </summary>
  2558. /// <param name="dto"></param>
  2559. /// <returns></returns>
  2560. [HttpPost]
  2561. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2562. public async Task<IActionResult> PostSyntheticalReceivableByDateRange(PostSyntheticalReceivableByDateRangeDto dto)
  2563. {
  2564. #region 老版查询
  2565. //string sqlWhere = " Where di.IsDel=0 ";
  2566. //#region 验证
  2567. //if (string.IsNullOrEmpty(dto.beginDt) && string.IsNullOrEmpty(dto.endDt))
  2568. //{
  2569. // return Ok(JsonView(false, "日期参数至少填写一个!"));
  2570. //}
  2571. //if (!string.IsNullOrEmpty(dto.beginDt))
  2572. //{
  2573. // if (Regex.Match(dto.beginDt, @"^\d{4}-\d{2}-\d{2}$").Value.Length < 1)
  2574. // {
  2575. // return Ok(JsonView(false, "日期参数格式错误,应为yyyy-MM-dd!"));
  2576. // }
  2577. // else
  2578. // {
  2579. // sqlWhere += string.Format(@" And di.VisitDate >= '{0} 00:00:00' ", dto.beginDt);
  2580. // }
  2581. //}
  2582. //if (!string.IsNullOrEmpty(dto.endDt))
  2583. //{
  2584. // if (Regex.Match(dto.endDt, @"^\d{4}-\d{2}-\d{2}$").Value.Length < 1)
  2585. // {
  2586. // return Ok(JsonView(false, "日期参数格式错误,应为yyyy-MM-dd!"));
  2587. // }
  2588. // else
  2589. // {
  2590. // sqlWhere += string.Format(@" And di.VisitDate <= '{0} 23:59:59' ", dto.endDt);
  2591. // }
  2592. //}
  2593. //if (!string.IsNullOrEmpty(dto.groupName))
  2594. //{
  2595. // sqlWhere += string.Format(@" And di.TeamName Like '%{0}%' ", dto.groupName);
  2596. //}
  2597. //#endregion
  2598. ////已收款项 判断如果是市场部的人员进来的话 只显示自己的 其他的都显示全部的
  2599. //string userSqlWhere = "";
  2600. //var userInfos = await _sqlSugar.Queryable<Sys_Users>()
  2601. // .InnerJoin<Sys_Department>((u, d) => u.DepId == d.Id)
  2602. // .Where((u, d) => u.IsDel == 0 && d.DepName.Contains("市场部") && u.Id == dto.CurrUserId)
  2603. // .ToListAsync();
  2604. //if (userInfos.Count > 0) userSqlWhere = string.Format(@$" And JietuanOperator={dto.CurrUserId} ");
  2605. ////排序倒序
  2606. //string sql = string.Format(@$"select distinct fr.diid,di.TeamName,di.ClientUnit,di.VisitDate,di.CreateTime from Fin_ForeignReceivables fr join Grp_DelegationInfo di on fr.DIID = di.id {sqlWhere} {userSqlWhere} Order By di.VisitDate Desc");
  2607. //var list_rst = _sqlSugar.SqlQueryable<PostSyntheticalReceivableByDateRangeView>(sql).ToList();
  2608. #endregion
  2609. //日期验证
  2610. var startTimeFlag = DateTime.TryParse(dto.beginDt, out DateTime begintime);
  2611. var endTimeFlag = DateTime.TryParse(dto.endDt, out DateTime endtime);
  2612. if (!startTimeFlag || !endTimeFlag) return Ok(JsonView(false, "请输入正确的开始、结束时间!"));
  2613. string groupName = dto.groupName;
  2614. int currUserId = dto.CurrUserId;
  2615. //已收款项 判断如果是市场部的人员进来的话 只显示自己的 其他的都显示全部的
  2616. var marketStaffFlag = await _sqlSugar.Queryable<Sys_Users>()
  2617. .InnerJoin<Sys_Department>((u, d) => u.DepId == d.Id)
  2618. .Where((u, d) => u.IsDel == 0 && d.DepName.Contains("市场部") && u.Id == dto.CurrUserId)
  2619. .AnyAsync();
  2620. var list_rst = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  2621. .LeftJoin<Sys_Users>((x, y) => x.JietuanOperator == y.Id)
  2622. .Where((x, y) => x.IsDel == 0)
  2623. .WhereIF(startTimeFlag && endTimeFlag, (x, y) => x.VisitDate >= begintime && x.VisitDate <= endtime)
  2624. .WhereIF(!string.IsNullOrEmpty(groupName), (x, y) => x.TeamName.Contains(groupName))
  2625. .WhereIF(marketStaffFlag, (x, y) => x.JietuanOperator == currUserId)
  2626. .OrderBy((x, y) => x.VisitDate)
  2627. .Select((x, y) => new PostSyntheticalReceivableByDateRangeView()
  2628. {
  2629. diid = x.Id,
  2630. teamName = x.TeamName,
  2631. clientUnit = x.ClientUnit,
  2632. visitDate = x.VisitDate.ToString("yyyy-MM-dd"),
  2633. fulfiller = y.CnName,
  2634. })
  2635. .ToListAsync();
  2636. var setData = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
  2637. decimal sumAll_fr = 0M; //应收
  2638. decimal sumAll_pr = 0M; //已收
  2639. decimal sumAll_balance = 0M; //尾款
  2640. var result = new PostSyntheticalReceivableByDateRangeResultView();
  2641. if (list_rst.Any())
  2642. {
  2643. //查询团组各模块费用信息
  2644. string sql = @"
  2645. Select
  2646. Id,
  2647. TeamName,
  2648. CTable,
  2649. ModuleName,
  2650. CNYMoney
  2651. from
  2652. (
  2653. SELECT
  2654. di.Id,
  2655. di.TeamName,
  2656. sd.Name AS ModuleName,
  2657. ccp.CTable,
  2658. CASE
  2659. WHEN ccp.CTable = 76 THEN (
  2660. SELECT
  2661. hotelname
  2662. FROM
  2663. Grp_HotelReservations hr
  2664. WHERE
  2665. hr.Id = ccp.CId
  2666. and hr.IsDel = 0
  2667. )
  2668. WHEN ccp.CTable = 79 THEN (
  2669. SELECT
  2670. PriceName
  2671. FROM
  2672. Grp_CarTouristGuideGroundReservations ctgr
  2673. WHERE
  2674. ctgr.Id = ccp.CId
  2675. and ctgr.IsDel = 0
  2676. )
  2677. WHEN ccp.CTable = 80 THEN (
  2678. SELECT
  2679. Area
  2680. FROM
  2681. Grp_VisaInfo vi
  2682. WHERE
  2683. vi.Id = ccp.CId
  2684. and vi.IsDel = 0
  2685. )
  2686. WHEN ccp.CTable = 81 THEN (
  2687. SELECT
  2688. InviterArea
  2689. FROM
  2690. Grp_InvitationOfficialActivities ioa
  2691. WHERE
  2692. ioa.Id = ccp.CId
  2693. and ioa.IsDel = 0
  2694. )
  2695. WHEN ccp.CTable = 82 THEN (
  2696. SELECT
  2697. (
  2698. SELECT
  2699. GName
  2700. FROM
  2701. Grp_InsuranceCost ic
  2702. WHERE
  2703. ic.Id = c.Iid
  2704. )
  2705. FROM
  2706. Grp_Customers c
  2707. WHERE
  2708. c.Id = ccp.CId
  2709. and c.IsDel = 0
  2710. )
  2711. WHEN ccp.CTable = 85 THEN (
  2712. SELECT
  2713. FlightsCode
  2714. FROM
  2715. Grp_AirTicketReservations atr
  2716. WHERE
  2717. atr.Id = ccp.CId
  2718. and atr.IsDel = 0
  2719. )
  2720. WHEN ccp.CTable = 98 THEN (
  2721. SELECT
  2722. PriceName
  2723. FROM
  2724. Grp_DecreasePayments dp
  2725. WHERE
  2726. dp.Id = ccp.CId
  2727. and dp.IsDel = 0
  2728. )
  2729. WHEN ccp.CTable = 1015 THEN (
  2730. SELECT
  2731. PriceName
  2732. FROM
  2733. Fin_GroupExtraCost gec
  2734. WHERE
  2735. gec.Id = ccp.CId
  2736. and gec.IsDel = 0
  2737. )
  2738. ELSE '-'
  2739. END AS PriceName,
  2740. CASE
  2741. WHEN ccp.CTable = 76 THEN (
  2742. SELECT
  2743. IsDel
  2744. FROM
  2745. Grp_HotelReservations hr
  2746. WHERE
  2747. hr.Id = ccp.CId
  2748. and hr.IsDel = 0
  2749. )
  2750. WHEN ccp.CTable = 79 THEN (
  2751. SELECT
  2752. IsDel
  2753. FROM
  2754. Grp_CarTouristGuideGroundReservations ctgr
  2755. WHERE
  2756. ctgr.Id = ccp.CId
  2757. and ctgr.IsDel = 0
  2758. )
  2759. WHEN ccp.CTable = 80 THEN (
  2760. SELECT
  2761. IsDel
  2762. FROM
  2763. Grp_VisaInfo vi
  2764. WHERE
  2765. vi.Id = ccp.CId
  2766. and vi.IsDel = 0
  2767. )
  2768. WHEN ccp.CTable = 81 THEN (
  2769. SELECT
  2770. IsDel
  2771. FROM
  2772. Grp_InvitationOfficialActivities ioa
  2773. WHERE
  2774. ioa.Id = ccp.CId
  2775. and ioa.IsDel = 0
  2776. )
  2777. WHEN ccp.CTable = 82 THEN (
  2778. SELECT
  2779. IsDel
  2780. FROM
  2781. Grp_Customers c
  2782. WHERE
  2783. c.Id = ccp.CId
  2784. and c.IsDel = 0
  2785. )
  2786. WHEN ccp.CTable = 85 THEN (
  2787. SELECT
  2788. IsDel
  2789. FROM
  2790. Grp_AirTicketReservations atr
  2791. WHERE
  2792. atr.Id = ccp.CId
  2793. and atr.IsDel = 0
  2794. )
  2795. WHEN ccp.CTable = 98 THEN (
  2796. SELECT
  2797. IsDel
  2798. FROM
  2799. Grp_DecreasePayments dp
  2800. WHERE
  2801. dp.Id = ccp.CId
  2802. and dp.IsDel = 0
  2803. )
  2804. WHEN ccp.CTable = 1015 THEN (
  2805. SELECT
  2806. IsDel
  2807. FROM
  2808. Fin_GroupExtraCost gec
  2809. WHERE
  2810. gec.Id = ccp.CId
  2811. and gec.IsDel = 0
  2812. )
  2813. ELSE '1'
  2814. END AS ChildIsDel,
  2815. (ccp.PayMoney * ccp.DayRate) AS CNYMoney,
  2816. ccp.IsDel AS CcpIsDel,
  2817. di.IsDel AS DiIsDel
  2818. FROM
  2819. Grp_CreditCardPayment ccp
  2820. INNER JOIN Grp_DelegationInfo di ON ccp.DIId = di.Id
  2821. LEFT JOIN sys_setdata sd ON ccp.CTable = sd.Id
  2822. ) as view1
  2823. WHERE
  2824. DiIsDel = 0
  2825. AND ChildIsDel = 0
  2826. AND DiIsDel = 0
  2827. AND Id IN (@GroupIds)";
  2828. var groupIds = list_rst.Select(x => x.diid).ToList();
  2829. var datas = _sqlSugar.SqlQueryable<SyntheticalReceivableFeeDetailsView>(sql)
  2830. .AddParameters(new { GroupIds = groupIds })
  2831. .ToList();
  2832. #region 2025-12-01 新增团组成本报价
  2833. string groupCostSql = @"select * from Grp_GroupCostParameter where IsDel = 0 and CostType = 'A' And diid IN (@GroupIds)";
  2834. var groupCostDatas = _sqlSugar.SqlQueryable<GroupCostCalculate>(groupCostSql)
  2835. .AddParameters(new { GroupIds = groupIds })
  2836. .ToList();
  2837. #endregion
  2838. int rowNumber = 1;
  2839. foreach (var item_rst in list_rst)
  2840. {
  2841. item_rst.No = rowNumber;
  2842. rowNumber++;
  2843. int diId = item_rst.diid;
  2844. decimal sum_fr = 0M;
  2845. decimal sum_pr = 0M;
  2846. string str_client = string.Empty;
  2847. decimal sum_refund = 0M; //收款退还
  2848. decimal sum_extra = 0M; //超支费用
  2849. //decimal balance = 0M;
  2850. string str_schedule = string.Empty;
  2851. //1.应收
  2852. string sql_fr = string.Format(@" Select * From Fin_ForeignReceivables Where IsDel=0 And Diid={0} ", diId);
  2853. List<Fin_ForeignReceivables> list_fr = _sqlSugar.SqlQueryable<Fin_ForeignReceivables>(sql_fr).ToList();
  2854. sum_fr = list_fr.Sum(s => s.ItemSumPrice);
  2855. //2.已收
  2856. string sql_pr = string.Format(@" Select * From Fin_ProceedsReceived Where IsDel=0 And Diid={0} ", diId);
  2857. List<Fin_ProceedsReceived> list_pr = _sqlSugar.SqlQueryable<Fin_ProceedsReceived>(sql_pr).ToList();
  2858. foreach (var item_pr in list_pr)
  2859. {
  2860. sum_pr += item_pr.Price;
  2861. str_client += string.Format(@"{0};", item_pr.Client);
  2862. str_schedule += string.Format(@"{0};", item_pr.Remark);
  2863. }
  2864. if (str_schedule.Length > 0)
  2865. {
  2866. str_schedule = str_schedule.TrimEnd(';');
  2867. }
  2868. if (str_client.Length > 0)
  2869. {
  2870. str_client = str_client.TrimEnd(';');
  2871. }
  2872. //3.收款退还
  2873. string sql_other = string.Format(@"Select * From Fin_PaymentRefundAndOtherMoney prao
  2874. Inner Join Grp_CreditCardPayment ccp On prao.Id = ccp.CId
  2875. Where ccp.CTable = 285 And ccp.IsPay = 1 And prao.IsDel = 0 And ccp.IsDel = 0 And prao.DiId = {0}", diId);
  2876. List<Grp_CreditCardPayment> list_other = _sqlSugar.SqlQueryable<Grp_CreditCardPayment>(sql_other).ToList();
  2877. sum_refund = list_other.Sum(s => s.PayMoney * s.DayRate);
  2878. //4.超支
  2879. //string sql_extra = string.Format(@" Select c.* From Fin_GroupExtraCost f
  2880. //Inner join Grp_CreditCardPayment c On f.Id = c.CId
  2881. //Where c.CTable = 1015 And c.IsPay = 1 And f.IsDel = 0 And c.IsDel = 0 And f.DiId = {0} ", diId);
  2882. //List<Grp_CreditCardPayment> list_extra = _sqlSugar.SqlQueryable<Grp_CreditCardPayment>(sql_extra).ToList();
  2883. //sum_extra = list_extra.Sum(s => s.PayMoney * s.DayRate);
  2884. item_rst.frPrice = sum_fr.ToString("#0.00");
  2885. item_rst.extraPrice = sum_extra.ToString("#0.00");
  2886. item_rst.receivableTotal = (sum_fr + sum_extra).ToString("#0.00");
  2887. item_rst.prPrice = sum_pr.ToString("#0.00");
  2888. item_rst.refundAmount = sum_refund.ToString("#0.00");
  2889. //item_rst.receivedTotal = (sum_pr - sum_refund).ToString("#0.00");
  2890. item_rst.receivedTotal = sum_pr.ToString("#0.00");
  2891. //item_rst.balPrice = ((sum_fr + sum_extra) - (sum_pr - sum_refund)).ToString("#0.00");
  2892. item_rst.balPrice = ((sum_fr + sum_extra) - sum_pr).ToString("#0.00");
  2893. item_rst.prClient = str_client;
  2894. item_rst.schedule = str_schedule;
  2895. string tempVisitDate = Convert.ToDateTime(item_rst.visitDate).ToString("yyyy-MM-dd");
  2896. sumAll_fr += (sum_fr + sum_extra);
  2897. //sumAll_pr += (sum_pr - sum_refund);
  2898. sumAll_pr += sum_pr;
  2899. //sumAll_balance += ((sum_fr + sum_extra) - (sum_pr - sum_refund));
  2900. sumAll_balance += ((sum_fr + sum_extra) - sum_pr);
  2901. //应收、已收、收款退还、余款 都为零 且 团组费用有值时 变色
  2902. if (sum_fr <= 0m && (sum_fr + sum_extra) <= 0m && sum_refund <= 0m && ((sum_fr + sum_extra) - (sum_pr - sum_refund)) <= 0m)
  2903. {
  2904. item_rst.isChangeColorRed = true;
  2905. var currDatas = datas.Where(w => w.Id == diId).ToList();
  2906. decimal totalCost = currDatas.Sum(s => s.CNYMoney);
  2907. if (totalCost > 0m)
  2908. {
  2909. // 分组统计并排序
  2910. var feeDatas1 = currDatas
  2911. .GroupBy(g => new { g.CTable, g.ModuleName })
  2912. .Select(s => new SyntheticalReceivableFeeDetailsView
  2913. {
  2914. ModuleName = s.Key.ModuleName ?? "未知模块",
  2915. CTable = s.Key.CTable,
  2916. CNYMoney = s.Sum(ss => ss.CNYMoney)
  2917. })
  2918. .OrderBy(x => x.CTable)
  2919. .ToList();
  2920. // 构建结果字符串
  2921. var feeLabel = new StringBuilder();
  2922. foreach (var item in feeDatas1)
  2923. {
  2924. feeLabel.AppendLine(); // 空行
  2925. feeLabel.AppendLine($"{item.ModuleName} :{item.CNYMoney:#,##0.00} CNY");
  2926. }
  2927. //item_rst.isChangeColorRed = false; //红色/橙色只显示一个
  2928. item_rst.isChangeColor = true;
  2929. item_rst.ChangeColorLabel = feeLabel.ToString();
  2930. }
  2931. }
  2932. #region 单位应收已收细项(以应收费用名称为主去(已收费用)匹配) 新增 雷怡 2024-5-08 16:35:28
  2933. var feeDatas = new List<ClientFeeInfoView>();
  2934. //匹配上的数据
  2935. foreach (var item in list_fr)
  2936. {
  2937. var prInfo = list_pr.Find(it => item.PriceName.Contains(it.Client) || item.PriceName.Equals(it.Client));
  2938. decimal _balancePayment = 0.00M;
  2939. if (item.Currency == prInfo?.Currency)
  2940. {
  2941. _balancePayment = item.ItemSumPrice - prInfo?.Price ?? 0.00M;
  2942. }
  2943. feeDatas.Add(new ClientFeeInfoView
  2944. {
  2945. client = item.PriceName,
  2946. frMoney = item.ItemSumPrice.ToString("#0.00"),
  2947. frCurrency = setData.Find(it => it.Id == item.Currency)?.Name ?? "-",
  2948. frRate = item.Rate.ToString("#0.0000"),
  2949. prReceivablesType = setData.Find(it => it.Id == prInfo?.ReceivablesType)?.Name ?? "",
  2950. prTime = prInfo?.SectionTime ?? "-",
  2951. prMoney = prInfo?.Price.ToString("#0.00") ?? "-",
  2952. prCurrency = setData.Find(it => it.Id == prInfo?.Currency)?.Name ?? "",
  2953. balPayment = _balancePayment.ToString("#0.00")
  2954. });
  2955. }
  2956. //未匹配上的数据
  2957. foreach (var item in list_pr)
  2958. {
  2959. var frInfo = list_fr.Find(it => it.PriceName.Contains(item.Client) || it.PriceName.Equals(item.Client));
  2960. if (frInfo == null)
  2961. {
  2962. feeDatas.Add(new ClientFeeInfoView
  2963. {
  2964. client = item.Client + "[未匹配上的已收数据(应收已收公司名称不一致)]",
  2965. frMoney = "0.00",
  2966. frCurrency = "-",
  2967. frRate = "0.0000",
  2968. prReceivablesType = setData.Find(it => it.Id == item?.ReceivablesType)?.Name ?? "",
  2969. prTime = item?.SectionTime ?? "-",
  2970. prMoney = item?.Price.ToString("#0.00") ?? "0.00",
  2971. prCurrency = setData.Find(it => it.Id == item?.Currency)?.Name ?? "",
  2972. balPayment = "0.00"
  2973. });
  2974. }
  2975. }
  2976. if (feeDatas.Count < 1)
  2977. {
  2978. feeDatas.Add(new ClientFeeInfoView() { });
  2979. }
  2980. item_rst.feeItem = feeDatas;
  2981. #endregion
  2982. #region 团组成本报价信息 2025-12-01 13:56:55
  2983. var groupCostInfo = groupCostDatas.FirstOrDefault(f => f.DiId == diId);
  2984. item_rst.groupCost = groupCostInfo?.GroupTotalPrice ?? 0.00m;
  2985. item_rst.groupCostItem = groupCostInfo?.ChildFeeInfos ?? new List<ChildFeeInfo>();
  2986. #endregion
  2987. }
  2988. result.total_fr = sumAll_fr.ToString("#0.00");
  2989. result.total_pr = sumAll_pr.ToString("#0.00");
  2990. result.total_balance = sumAll_balance.ToString("#0.00");
  2991. result.dataList = new List<PostSyntheticalReceivableByDateRangeView>(list_rst);
  2992. if (dto.requestType == 1)
  2993. {
  2994. return Ok(JsonView(true, "请求成功", result, list_rst.Count));
  2995. }
  2996. else if (dto.requestType == 2)
  2997. {
  2998. //----------------------------
  2999. var list_Ex = new List<Excel_SyntheticalReceivableByDateRange>();
  3000. var designer = new WorkbookDesigner()
  3001. {
  3002. Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/应收款项模板 - 副本.xls")
  3003. };
  3004. int excNo = 1;
  3005. foreach (var item in list_rst)
  3006. {
  3007. var exc = new Excel_SyntheticalReceivableByDateRange
  3008. {
  3009. No = excNo.ToString(),
  3010. TeamName = item.teamName,
  3011. ClientUnit = item.clientUnit,
  3012. VisitDate = item.visitDate,
  3013. Accounts = item.frPrice,
  3014. Extra = item.extraPrice,
  3015. ReceivableTotal = item.receivableTotal,
  3016. Received = item.prPrice,
  3017. RefundAmount = item.refundAmount,
  3018. ReceivedTotal = item.receivedTotal,
  3019. Balance = item.balPrice,
  3020. Collection = item.schedule,
  3021. GroupCost = item.groupCost.ToString("#0.00"),
  3022. fulfiller = item.fulfiller
  3023. };
  3024. excNo++;
  3025. DateTime time = Convert.ToDateTime(item.visitDate);
  3026. TimeSpan ts = DateTime.Now - time;
  3027. float sy = float.Parse(item.balPrice);
  3028. if (ts.Days >= 365 && sy > 0)
  3029. {
  3030. exc.Sign = "需收款";
  3031. }
  3032. else
  3033. {
  3034. exc.Sign = "";
  3035. }
  3036. list_Ex.Add(exc);
  3037. }
  3038. var dt = CommonFun.GetDataTableFromIList(list_Ex);
  3039. dt.TableName = "Excel_SyntheticalReceivableByDateRange";
  3040. if (dt != null)
  3041. {
  3042. designer.SetDataSource("SumPrice", "应收合计:" + result.total_fr + "RMB 已收合计:" + result.total_pr + "RMB 余款合计:" + result.total_balance + "RMB");
  3043. //数据源
  3044. designer.SetDataSource(dt);
  3045. //根据数据源处理生成报表内容
  3046. designer.Process();
  3047. string fileName = ("Receivable/应收款项(" + dto.beginDt + "~" + dto.endDt + ").xlsx");
  3048. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  3049. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  3050. return Ok(JsonView(true, "成功", new { url = rst }));
  3051. }
  3052. }
  3053. else if (dto.requestType == 3)
  3054. {
  3055. //----------------------------
  3056. var list_Ex_Orange = new List<Excel_SyntheticalReceivableByDateRange>();
  3057. var list_Ex_Red = new List<Excel_SyntheticalReceivableByDateRange>();
  3058. var designer = new WorkbookDesigner()
  3059. {
  3060. Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/应收款项模板1.xls")
  3061. };
  3062. //只查询标注颜色的数据
  3063. var list_rst_orange = list_rst.Where(x => x.isChangeColor).ToList();
  3064. var orangeGroupIds = list_rst.Where(x => x.isChangeColor).Select(x => x.diid).ToList();
  3065. var list_rst_red = list_rst.Where(x => x.isChangeColorRed && !orangeGroupIds.Contains(x.diid)).ToList();
  3066. int excNo1 = 1, excNo2 = 1;
  3067. foreach (var item in list_rst_orange)
  3068. {
  3069. var exc = new Excel_SyntheticalReceivableByDateRange
  3070. {
  3071. No = excNo1.ToString(),
  3072. TeamName = item.teamName,
  3073. ClientUnit = item.clientUnit,
  3074. VisitDate = item.visitDate,
  3075. ChangeColorLabel = item.ChangeColorLabel,
  3076. GroupCost = item.groupCost.ToString("#0.00"),
  3077. fulfiller = item.fulfiller
  3078. };
  3079. excNo1++;
  3080. list_Ex_Orange.Add(exc);
  3081. }
  3082. foreach (var item in list_rst_red)
  3083. {
  3084. var exc = new Excel_SyntheticalReceivableByDateRange
  3085. {
  3086. No = excNo2.ToString(),
  3087. TeamName = item.teamName,
  3088. ClientUnit = item.clientUnit,
  3089. VisitDate = item.visitDate,
  3090. ChangeColorLabel = item.ChangeColorLabel,
  3091. GroupCost = item.groupCost.ToString("#0.00"),
  3092. fulfiller = item.fulfiller
  3093. };
  3094. excNo2++;
  3095. list_Ex_Red.Add(exc);
  3096. }
  3097. var dt_orange = CommonFun.GetDataTableFromIList(list_Ex_Orange);
  3098. dt_orange.TableName = "DataSource1";
  3099. var dt_red = CommonFun.GetDataTableFromIList(list_Ex_Red);
  3100. dt_red.TableName = "DataSource2";
  3101. if (dt_orange != null || dt_red != null)
  3102. {
  3103. //数据源
  3104. designer.SetDataSource(dt_orange);
  3105. designer.SetDataSource(dt_red);
  3106. //根据数据源处理生成报表内容
  3107. designer.Process();
  3108. string fileName = $"Receivable/应收款项{dto.beginDt}~{dto.endDt})_标注团组{Guid.NewGuid():N}.xlsx";
  3109. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  3110. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  3111. return Ok(JsonView(true, "成功", new { url = rst }));
  3112. }
  3113. }
  3114. }
  3115. return Ok(JsonView(true, "暂无数据", result, list_rst.Count));
  3116. }
  3117. #endregion
  3118. #region 付款申请
  3119. /// <summary>
  3120. /// 付款申请
  3121. /// 基础数据
  3122. /// </summary>
  3123. /// <returns></returns>
  3124. [HttpPost]
  3125. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3126. public async Task<IActionResult> PostPayRequestInit()
  3127. {
  3128. var conpanyDatas = _sqlSugar.Queryable<Sys_Company>()
  3129. .Where(it => it.IsDel == 0)
  3130. .Select(it => new
  3131. {
  3132. it.Id,
  3133. it.CompanyName
  3134. }).ToList();
  3135. return Ok(JsonView(true, "操作成功!", new { ConpanyData = conpanyDatas }));
  3136. }
  3137. /// <summary>
  3138. /// 付款申请 (PageId=51)
  3139. /// 查询 根据日期范围
  3140. /// </summary>
  3141. /// <param name="dto"></param>
  3142. /// <returns></returns>
  3143. [HttpPost]
  3144. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3145. public async Task<IActionResult> PostPayRequest_Center(PostPayRequestByDateRangeDto dto)
  3146. {
  3147. Stopwatch stopwatch = Stopwatch.StartNew();
  3148. #region 验证
  3149. string format = "yyyy-MM-dd";
  3150. if (!DateTime.TryParseExact(dto.beginDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime beginDt))
  3151. {
  3152. return Ok(JsonView(false, "开始日期格式不正确!正确格式:yyyy-MM-dd"));
  3153. }
  3154. if (!DateTime.TryParseExact(dto.endDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime endDt))
  3155. {
  3156. return Ok(JsonView(false, "结束日期格式不正确!正确格式:yyyy-MM-dd"));
  3157. }
  3158. #region 页面操作权限验证
  3159. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3160. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  3161. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  3162. #endregion
  3163. #endregion
  3164. try
  3165. {
  3166. PaymentRequestCheckedView checkedView = new PaymentRequestCheckedView();
  3167. var checkedStr = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>("paymentRequestCheckedData");
  3168. if (checkedStr != null)
  3169. {
  3170. checkedView = JsonConvert.DeserializeObject<PaymentRequestCheckedView>(checkedStr.ToString());
  3171. if (checkedView.GroupIds.Count > 0)
  3172. {
  3173. checkedView.GroupIds = checkedView.GroupIds.OrderBy(x => x).ToList();
  3174. }
  3175. }
  3176. tree_Fin_DailyFeePaymentResult dailyResult = PayRequest_DailyByDateRange(dto.Status, checkedView.DailyPaymentIds, dto.beginDt, dto.endDt);
  3177. tree_Group_DailyFeePaymentResult groupResult = PayRequest_GroupPaymentByDateRange(dto.Status, checkedView.GroupIds, checkedView.HotelSubIds, dto.beginDt, dto.endDt);
  3178. stopwatch.Stop();
  3179. return Ok(JsonView(true, $"查询成功!耗时{stopwatch.ElapsedMilliseconds / 1000}s", new { daily = dailyResult, group = groupResult }));
  3180. }
  3181. catch (Exception ex)
  3182. {
  3183. return Ok(JsonView(false, ex.Message));
  3184. }
  3185. }
  3186. /// <summary>
  3187. /// 根据团组类型类型处理团组费用所属公司
  3188. /// </summary>
  3189. /// <param name="teamId"></param>
  3190. /// <returns></returns>
  3191. private CompanyInfo ExpenseCompanyByTeamId(int teamId)
  3192. {
  3193. var _companyInfo = new CompanyInfo()
  3194. {
  3195. Id = 2,
  3196. ConpanyName = "四川泛美交流有限公司"
  3197. };
  3198. var _SiChuan = new List<int>() {
  3199. 38, // 政府团
  3200. 39, // 企业团
  3201. 40, // 散客团
  3202. 102, // 未知
  3203. 248, // 非团组
  3204. 691, // 四川-会务活动
  3205. 762, // 四川-赛事项目收入
  3206. 1048,//高校团
  3207. };
  3208. var _ChengDu = new List<int>() {
  3209. 302, // 成都-会务活动
  3210. 1047, // 成都-赛事项目收入
  3211. };
  3212. if (_SiChuan.Contains(teamId))
  3213. {
  3214. _companyInfo.Id = 2;
  3215. _companyInfo.ConpanyName = "四川泛美交流有限公司";
  3216. }
  3217. if (_ChengDu.Contains(teamId))
  3218. {
  3219. _companyInfo.Id = 1;
  3220. _companyInfo.ConpanyName = "成都泛美商务有限公司";
  3221. }
  3222. return _companyInfo;
  3223. }
  3224. /// <summary>
  3225. /// 付款申请(团组费用申请相关)
  3226. /// 查询 根据日期范围
  3227. /// </summary>
  3228. /// <param name="status"></param>
  3229. /// <param name="_groupIds"></param>
  3230. /// <param name="_hotelSubIds"></param>
  3231. /// <param name="beginDt"></param>
  3232. /// <param name="endDt"></param>
  3233. /// <returns></returns>
  3234. private tree_Group_DailyFeePaymentResult PayRequest_GroupPaymentByDateRange(int status, List<int> _groupIds, List<int> _hotelSubIds, string beginDt, string endDt)
  3235. {
  3236. var _DailyFeePaymentResult = new tree_Group_DailyFeePaymentResult();
  3237. var dataList = new List<tree_Group_DailyFeePaymentPageListView>();
  3238. #region sql条件处理
  3239. string sqlWhere = string.Format(@" And (AuditGMDate Between '{0} 00:00:00' And '{1} 23:59:59') ", beginDt, endDt);
  3240. if (status == 2)
  3241. {
  3242. if (_hotelSubIds.Count > 1)
  3243. {
  3244. var hrIds = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => _hotelSubIds.Contains(it.Id) && it.Price != 0).Select(it => it.HrId).Distinct().ToList();
  3245. var hrIds1 = _sqlSugar.Queryable<Grp_CreditCardPayment>().Where(it => it.CTable == 76 && hrIds.Contains(it.CId)).Select(it => it.Id).ToList();
  3246. if (hrIds1.Count > 1)
  3247. {
  3248. _groupIds.AddRange(hrIds1);
  3249. }
  3250. }
  3251. if (_groupIds.Count < 1)
  3252. {
  3253. _DailyFeePaymentResult.dataList = new List<tree_Group_DailyFeePaymentPageListView>();
  3254. return _DailyFeePaymentResult;
  3255. }
  3256. sqlWhere += string.Format(@" And Id In ({0})", string.Join(",", _groupIds));
  3257. }
  3258. string sql_1 = string.Format(@"Select * From Grp_CreditCardPayment Where IsDel = 0 And IsPay = 0 And (IsAuditGM = 1 Or IsAuditGM = 3 ){0}", sqlWhere);
  3259. #endregion
  3260. var _paymentDatas = _sqlSugar.SqlQueryable<Grp_CreditCardPayment>(sql_1).ToList();//付款信息
  3261. _DailyFeePaymentResult.gz = _paymentDatas.Where(it => it.OrbitalPrivateTransfer == 0).Sum(it => ((it.PayMoney * it.DayRate) / 100) * it.PayPercentage); //公转
  3262. _DailyFeePaymentResult.sz = _paymentDatas.Where(it => it.OrbitalPrivateTransfer == 1).Sum(it => ((it.PayMoney * it.DayRate) / 100) * it.PayPercentage); ; //私转
  3263. List<int> groupIds = _paymentDatas.Select(it => it.DIId).Distinct().ToList();
  3264. var _groupDatas = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0 && groupIds.Contains(it.Id)).ToList();
  3265. //_groupDatas = (List<Grp_DelegationInfo>)_groupDatas.GroupBy(it => it.TeamDid);
  3266. #region 相关基础数据源
  3267. var userDatas = _sqlSugar.Queryable<Sys_Users>().ToList();
  3268. var setDatas = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
  3269. var countryFeeDatas = _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(it => it.IsDel == 0).ToList();
  3270. var hotelDatas = _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  3271. var hotelContentDatas = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => it.IsDel == 0 && it.IsPay == 0 && it.Price != 0 && groupIds.Contains(it.DiId)).ToList();
  3272. var opDatas = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  3273. var visaDatas = _sqlSugar.Queryable<Grp_VisaInfo>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DIId)).ToList();
  3274. var ioaDatas = _sqlSugar.Queryable<Grp_InvitationOfficialActivities>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  3275. var insureDatas = _sqlSugar.Queryable<Grp_Customers>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  3276. var airDatas = _sqlSugar.Queryable<Grp_AirTicketReservations>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DIId)).ToList();
  3277. //var otherMoneyDatas = _sqlSugar.Queryable<Fin_OtherPrice>().Where(it => it.IsDel == 0 && groupIds.Contains(it.Diid)).ToList();
  3278. var otherMoneyDatas = _sqlSugar.Queryable<Grp_DecreasePayments>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  3279. var refundPaymentDatas = _sqlSugar.Queryable<Fin_PaymentRefundAndOtherMoney>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  3280. var ExtraCostDatas = _sqlSugar.Queryable<Fin_GroupExtraCost>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  3281. #endregion
  3282. //Expense company
  3283. foreach (var groupInfo in _groupDatas)
  3284. {
  3285. var childList = new List<Group_DailyFeePaymentContentInfolView>();
  3286. var groupPaymentDatas = _paymentDatas.Where(it => groupInfo.Id == it.DIId).ToList();
  3287. int rouNumber = 1;
  3288. foreach (var payInfo in groupPaymentDatas)
  3289. {
  3290. string priName = "-";
  3291. string orbitalPrivateTransfer = payInfo.OrbitalPrivateTransfer == 0 ? "公转" : payInfo.OrbitalPrivateTransfer == 1 ? "私转" : "-";
  3292. switch (payInfo.CTable)
  3293. {
  3294. case 76: //76 酒店预订
  3295. priName = $"[费用名称:{hotelDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.HotelName ?? ""}]";
  3296. if (payInfo.IsAuditGM == 1)
  3297. {
  3298. }
  3299. break;
  3300. case 79: //79 车/导游地接
  3301. var opData = opDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id);
  3302. if (opData != null)
  3303. {
  3304. string area = "";
  3305. bool b = int.TryParse(opData.Area, out int areaId);
  3306. if (b)
  3307. {
  3308. string area1 = countryFeeDatas.Find(it => it.Id == areaId)?.Country ?? "-";
  3309. area = $"{area1}({setDatas.Find(it => it.Id == opData.PriceType)?.Name ?? "-"})";
  3310. }
  3311. else area = opData.Area;
  3312. string opPriName = "-";
  3313. if (!string.IsNullOrEmpty(opData.PriceName)) opPriName = opData.PriceName;
  3314. area += $"({opPriName})";
  3315. if (payInfo.OrbitalPrivateTransfer == 0) //公转
  3316. {
  3317. priName = $"【{orbitalPrivateTransfer}】【导游: {opData.ServiceGuide} 】[费用名称:{area}]";
  3318. }
  3319. else if (payInfo.OrbitalPrivateTransfer == 1) //私转
  3320. {
  3321. priName = $"【{orbitalPrivateTransfer}】【导游:{opData.ServiceGuide}】[费用名称:{area}]";
  3322. }
  3323. }
  3324. break;
  3325. case 80: // 80 签证
  3326. string sql = string.Format("select b.Id,b.Pinyin,b.lastName,b.firstName,b.phone from Grp_TourClientList a, Crm_DeleClient b where a.clientid = b.id and a.isdel = 0 and a.diid = {0}", groupInfo.Id);
  3327. var arr = _sqlSugar.SqlQueryable<SimplClientInfo>(sql).ToList();
  3328. string visaClientName = visaDatas.Find(it => payInfo.DIId == it.DIId && payInfo.CId == it.Id)?.VisaClient ?? "";
  3329. string clientName = "-";
  3330. if (Regex.Match(visaClientName, @"\d+,?").Value.Length > 0)
  3331. {
  3332. string[] temparr = visaClientName.Split(',');
  3333. string fistrStr = temparr[0];
  3334. int count = temparr.Length;
  3335. int tempId;
  3336. bool success = int.TryParse(fistrStr, out tempId);
  3337. if (success)
  3338. {
  3339. SimplClientInfo tempInfo = arr.FirstOrDefault(s => s.Id == tempId);
  3340. if (tempInfo != null)
  3341. {
  3342. EncryptionProcessor.DecryptProperties(tempInfo);
  3343. if (count > 1)
  3344. {
  3345. clientName = string.Format(@"{0}{1}等{2}人", tempInfo.LastName, tempInfo.FirstName, count);
  3346. }
  3347. else
  3348. {
  3349. clientName = string.Format(@"{0}{1}", tempInfo.LastName, tempInfo.FirstName);
  3350. }
  3351. }
  3352. }
  3353. else
  3354. {
  3355. clientName = fistrStr;
  3356. }
  3357. }
  3358. priName = $"[费用名称:{clientName}]";
  3359. break;
  3360. case 81: // 81 邀请/公务活动
  3361. priName = $"[费用名称:{ioaDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.Inviter ?? " -"}]";
  3362. break;
  3363. case 82: // 82 团组客户保险
  3364. string bx_sql = string.Format("select b.Id,b.Pinyin,b.lastName,b.firstName,b.phone from Grp_TourClientList a, Crm_DeleClient b where a.clientid = b.id and a.isdel = 0 and a.diid = {0}", groupInfo.Id);
  3365. var bx_arr = _sqlSugar.SqlQueryable<SimplClientInfo>(bx_sql).ToList();
  3366. foreach (var bx in bx_arr) EncryptionProcessor.DecryptProperties(bx);
  3367. string bx_ClientName = insureDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.ClientName ?? "";
  3368. string bx_clientName = "-";
  3369. if (Regex.Match(bx_ClientName, @"\d+,?").Value.Length > 0)
  3370. {
  3371. string[] temparr = bx_ClientName.Split(',');
  3372. string fistrStr = temparr[0];
  3373. int count = temparr.Length;
  3374. int tempId;
  3375. bool success = int.TryParse(fistrStr, out tempId);
  3376. if (success)
  3377. {
  3378. SimplClientInfo tempInfo = bx_arr.FirstOrDefault(s => s.Id == tempId);
  3379. if (tempInfo != null)
  3380. {
  3381. if (count > 1)
  3382. {
  3383. bx_clientName = string.Format(@"{0}{1}等{2}人", tempInfo.LastName, tempInfo.FirstName, count);
  3384. }
  3385. else
  3386. {
  3387. bx_clientName = string.Format(@"{0}{1}", tempInfo.LastName, tempInfo.FirstName);
  3388. }
  3389. }
  3390. }
  3391. else
  3392. {
  3393. bx_clientName = fistrStr;
  3394. }
  3395. }
  3396. //priName = $"[费用名称:{insureDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.ClientName ?? " -"}]";
  3397. priName = $"[费用名称:{bx_clientName}]";
  3398. break;
  3399. case 85: // 85 机票预订
  3400. string flightsCode = airDatas.Find(it => payInfo.DIId == it.DIId && payInfo.CId == it.Id)?.FlightsCode ?? "-";
  3401. string airPayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "-";
  3402. priName = $"{flightsCode}【{airPayType}】";
  3403. break;
  3404. case 98: // 98 其他款项
  3405. priName = $"[费用名称:{otherMoneyDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  3406. break;
  3407. case 285: // 285 收款退还
  3408. priName = $"[费用名称:{refundPaymentDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  3409. break;
  3410. case 1015: // 1015 超支费用
  3411. priName = $"[费用名称:{ExtraCostDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  3412. break;
  3413. default:
  3414. priName = "";
  3415. break;
  3416. }
  3417. bool status1 = false;
  3418. if (_groupIds != null)
  3419. {
  3420. status1 = _groupIds.Contains(payInfo.Id);
  3421. }
  3422. if (payInfo.CTable == 76) //酒店单独处理
  3423. {
  3424. var hotelContents = hotelContentDatas.Where(it => it.HrId == payInfo.CId);
  3425. var childInfos = new List<Group_DailyFeePaymentContentInfolView>();
  3426. foreach (var hotelContent in hotelContents)
  3427. {
  3428. string subPriceName = "";
  3429. if (hotelContent.PriceType == 1) subPriceName = "房费";
  3430. else if (hotelContent.PriceType == 2) subPriceName = "早餐";
  3431. else if (hotelContent.PriceType == 3) subPriceName = "地税";
  3432. else if (hotelContent.PriceType == 4) subPriceName = "城市税";
  3433. if (string.IsNullOrEmpty(subPriceName)) subPriceName = priName;
  3434. else subPriceName = $"{priName.Replace("]", "")}-{subPriceName}]";
  3435. string payeeStr1 = string.Format(@" {0},开户行:{1},银行卡号:{2} ",
  3436. string.IsNullOrEmpty(hotelContent.Payee) ? "-" : hotelContent.Payee,
  3437. string.IsNullOrEmpty(hotelContent.OtherBankName) ? "-" : hotelContent.OtherBankName,
  3438. string.IsNullOrEmpty(hotelContent.OtherSideNo) ? "-" : hotelContent.OtherSideNo);
  3439. decimal _PaymentAmount1 = hotelContent.Price;//此次付款金额
  3440. decimal _CNYSubTotalAmount1 = _PaymentAmount1 * hotelContent.Rate;//此次付款金额
  3441. _CNYSubTotalAmount1 = Convert.ToDecimal(_CNYSubTotalAmount1.ToString("#0.00"));
  3442. //酒店子项Id选中状态更改
  3443. if (_hotelSubIds != null) status1 = _hotelSubIds.Contains(hotelContent.Id);
  3444. var childInfo1 = new Group_DailyFeePaymentContentInfolView()
  3445. {
  3446. IsChecked = status1,
  3447. Id = payInfo.Id,
  3448. HotelSubId = hotelContent.Id,
  3449. Payee = payeeStr1,
  3450. RowNumber = rouNumber,
  3451. Applicant = userDatas.Find(it => it.Id == payInfo.CreateUserId)?.CnName ?? "",
  3452. ApplicantDt = payInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
  3453. PayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "",
  3454. TransferMark = orbitalPrivateTransfer,
  3455. PriceName = subPriceName,
  3456. ModuleName = setDatas.Find(it => it.Id == payInfo.CTable)?.Name ?? "",
  3457. PayCurrCode = setDatas.Find(it => it.Id == hotelContent.Currency)?.Name ?? "",
  3458. PaymentAmount = _PaymentAmount1,
  3459. PayRate = hotelContent.Rate,
  3460. CNYSubTotalAmount = _CNYSubTotalAmount1,
  3461. AuditStatus = payInfo.IsAuditGM,
  3462. IsBgColorShown = Setting_IsBgColorShown(payInfo.CTable, payInfo.IsAuditGM)
  3463. };
  3464. string remaksDescription1 = $"【{childInfo1.PayType}】【{childInfo1.ModuleName}】{rouNumber}、[申请人:{childInfo1.Applicant}]{subPriceName}[收款方:{childInfo1.Payee}] {childInfo1.PayCurrCode} {_PaymentAmount1:#0.00}、CNY:{childInfo1.CNYSubTotalAmount:#0.00}(团组:{groupInfo.TeamName})";
  3465. childInfo1.RemaksDescription = remaksDescription1;
  3466. if (status == 2)
  3467. {
  3468. if (status1)
  3469. {
  3470. childInfos.Add(childInfo1);
  3471. }
  3472. }
  3473. else childInfos.Add(childInfo1);
  3474. rouNumber++;
  3475. }
  3476. childList.AddRange(childInfos);
  3477. }
  3478. else
  3479. {
  3480. string payeeStr = string.Format(@" {0},开户行:{1},银行卡号:{2} ",
  3481. string.IsNullOrEmpty(payInfo.Payee) ? "-" : payInfo.Payee,
  3482. string.IsNullOrEmpty(payInfo.OtherBankName) ? "-" : payInfo.OtherBankName,
  3483. string.IsNullOrEmpty(payInfo.OtherSideNo) ? "-" : payInfo.OtherSideNo);
  3484. decimal _PaymentAmount = (payInfo.PayMoney / 100) * payInfo.PayPercentage;//此次付款金额
  3485. decimal _CNYSubTotalAmount = _PaymentAmount * payInfo.DayRate;//此次付款金额
  3486. _CNYSubTotalAmount = Convert.ToDecimal(_CNYSubTotalAmount.ToString("#0.00"));
  3487. var childInfo = new Group_DailyFeePaymentContentInfolView()
  3488. {
  3489. IsChecked = status1,
  3490. Id = payInfo.Id,
  3491. Payee = payeeStr,
  3492. RowNumber = rouNumber,
  3493. Applicant = userDatas.Find(it => it.Id == payInfo.CreateUserId)?.CnName ?? "",
  3494. ApplicantDt = payInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
  3495. PayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "",
  3496. TransferMark = orbitalPrivateTransfer,
  3497. PriceName = priName,
  3498. ModuleName = setDatas.Find(it => it.Id == payInfo.CTable)?.Name ?? "",
  3499. PayCurrCode = setDatas.Find(it => it.Id == payInfo.PaymentCurrency)?.Name ?? "",
  3500. PaymentAmount = _PaymentAmount,
  3501. PayRate = payInfo.DayRate,
  3502. CNYSubTotalAmount = _CNYSubTotalAmount,
  3503. AuditStatus = payInfo.IsAuditGM,
  3504. IsBgColorShown = Setting_IsBgColorShown(payInfo.CTable, payInfo.IsAuditGM)
  3505. };
  3506. string remaksDescription = $"【{childInfo.PayType}】【{childInfo.ModuleName}】{rouNumber}、[申请人:{childInfo.Applicant}]{priName}[收款方:{childInfo.Payee}] {childInfo.PayCurrCode} {_PaymentAmount:#0.00}、CNY:{childInfo.CNYSubTotalAmount:#0.00}(团组:{groupInfo.TeamName})";
  3507. childInfo.RemaksDescription = remaksDescription;
  3508. childList.Add(childInfo);
  3509. rouNumber++;
  3510. }
  3511. }
  3512. var companyInfo = ExpenseCompanyByTeamId(groupInfo.TeamDid);
  3513. dataList.Add(new tree_Group_DailyFeePaymentPageListView()
  3514. {
  3515. Id = Guid.NewGuid().ToString("N"),
  3516. GroupName = groupInfo.TeamName,
  3517. CompanyId = companyInfo.Id,
  3518. ConpanyName = companyInfo.ConpanyName,
  3519. CNYTotalAmount = childList.Sum(it => it.CNYSubTotalAmount),
  3520. ChildList = childList,
  3521. });
  3522. }
  3523. _DailyFeePaymentResult.dataList = dataList;
  3524. return _DailyFeePaymentResult;
  3525. }
  3526. /// <summary>
  3527. /// 设置背景颜色显示与否
  3528. /// 费用类型限制:76-酒店预订、79-车/导游地接、85-机票预订
  3529. /// </summary>
  3530. /// <param name="cType"></param>
  3531. /// <param name="auditStatus"></param>
  3532. /// <returns></returns>
  3533. private static bool Setting_IsBgColorShown(int cType, int auditStatus)
  3534. {
  3535. //费用类型限制
  3536. var types = new List<int>() { 76, 79, 85, };
  3537. if (types.Contains(cType) && auditStatus == 1)
  3538. {
  3539. return true;
  3540. }
  3541. return false;
  3542. }
  3543. /// <summary>
  3544. /// 付款申请(日付申请相关)
  3545. /// 查询 根据日期范围
  3546. /// </summary>
  3547. /// <param name="status"></param>
  3548. /// <param name="_dailyIds"></param>
  3549. /// <param name="beginDt"></param>
  3550. /// <param name="endDt"></param>
  3551. /// <returns></returns>
  3552. private tree_Fin_DailyFeePaymentResult PayRequest_DailyByDateRange(int status, List<int> _dailyIds, string beginDt, string endDt)
  3553. {
  3554. #region sql条件处理
  3555. string sqlWhere = string.Format(@" And dfp.CreateTime between '{0} 00:00:00' And '{1} 23:59:59' ", beginDt, endDt);
  3556. if (status == 2)
  3557. {
  3558. if (_dailyIds.Count < 1)
  3559. {
  3560. return new tree_Fin_DailyFeePaymentResult() { childList = new List<Fin_DailyFeePaymentContentInfolView>() };
  3561. }
  3562. sqlWhere += string.Format(@" And dfp.Id In({0}) ", string.Join(",", _dailyIds));
  3563. }
  3564. string sql_1 = string.Format(@"Select * From (
  3565. Select row_number() over (order by dfp.Id Desc) as RowNumber,
  3566. dfp.Id,dfp.CompanyId,c.CompanyName,dfp.Instructions,dfp.SumPrice,
  3567. dfp.CreateUserId,u.CnName CreateUser,dfp.CreateTime,dfp.FAudit,dfp.MAudit,
  3568. dfp.PriceTypeId,dfp.TransferTypeId
  3569. From Fin_DailyFeePayment dfp
  3570. Inner Join Sys_Company c On dfp.CompanyId = c.Id
  3571. Left Join Sys_Users u On dfp.CreateUserId = u.Id
  3572. Where dfp.IsDel=0 {0}
  3573. AND (dfp.FAudit = 1 OR dfp.FAudit = 3)
  3574. AND (dfp.MAudit = 1 OR dfp.MAudit = 3)
  3575. AND dfp.IsPay = 0
  3576. ) temp ", sqlWhere);
  3577. #endregion
  3578. List<tree_Fin_DailyFeePaymentPageListView> DailyFeePaymentData = _sqlSugar.SqlQueryable<tree_Fin_DailyFeePaymentPageListView>(sql_1).ToList();
  3579. var dic_setData = new Dictionary<int, string>();
  3580. Sys_SetDataType stGZ = _daiRep.Query<Sys_SetDataType>(s => s.Name == "公转").First();
  3581. Sys_SetDataType stSZ = _daiRep.Query<Sys_SetDataType>(s => s.Name == "私转").First();
  3582. foreach (var item in DailyFeePaymentData)
  3583. {
  3584. if (_dailyIds != null)
  3585. {
  3586. item.IsChecked = _dailyIds.Contains(item.Id);
  3587. }
  3588. if (dic_setData.ContainsKey(item.PriceTypeId))
  3589. {
  3590. item.priceTypeStr = dic_setData[item.PriceTypeId];
  3591. }
  3592. else
  3593. {
  3594. Sys_SetData sd_priceType = _daiRep.Query<Sys_SetData>(s => s.Id == item.PriceTypeId).First();
  3595. if (sd_priceType != null)
  3596. {
  3597. item.priceTypeStr = sd_priceType.Name;
  3598. dic_setData.Add(item.PriceTypeId, sd_priceType.Name);
  3599. }
  3600. }
  3601. if (dic_setData.ContainsKey(item.transferTypeId))
  3602. {
  3603. item.transferTypeIdStr = dic_setData[item.transferTypeId];
  3604. Sys_SetData sd_transfer = _daiRep.Query<Sys_SetData>(s => s.Id == item.transferTypeId).First();
  3605. if (sd_transfer != null)
  3606. {
  3607. item.transferParentId = sd_transfer.STid;
  3608. item.transferParentIdStr = sd_transfer.STid == stGZ.Id ? "公转" : sd_transfer.STid == stSZ.Id ? "私转" : "";
  3609. }
  3610. }
  3611. else
  3612. {
  3613. Sys_SetData sd_transfer = _daiRep.Query<Sys_SetData>(s => s.Id == item.transferTypeId).First();
  3614. if (sd_transfer != null)
  3615. {
  3616. item.transferTypeIdStr = sd_transfer.Name;
  3617. item.transferParentId = sd_transfer.STid;
  3618. item.transferParentIdStr = sd_transfer.STid == stGZ.Id ? "公转" : sd_transfer.STid == stSZ.Id ? "私转" : "";
  3619. dic_setData.Add(item.transferTypeId, sd_transfer.Name);
  3620. }
  3621. }
  3622. string feeContentSql = string.Format(@"Select * From Fin_DailyFeePaymentContent
  3623. Where IsDel=0 And DFPId = {0} ", item.Id);
  3624. item.childList = _sqlSugar.SqlQueryable<Fin_DailyFeePaymentContentInfolView>(feeContentSql).ToList();
  3625. int rowNumber = 1;
  3626. foreach (var subItem in item.childList)
  3627. {
  3628. string remaksDescription = $"{rowNumber}、【{item.priceTypeStr}】{item.Instructions}({subItem.PriceName}) CNY:{subItem.ItemTotal.ToString("#0.0000")}(单价:{subItem.Price.ToString("#0.0000")} * {subItem.Quantity.ToString("#0.0000")})";
  3629. subItem.RemaksDescription = remaksDescription;
  3630. string excelRemaksDescription = $"【{item.priceTypeStr}】{item.Instructions}({subItem.PriceName}) CNY:{subItem.ItemTotal.ToString("#0.0000")}(单价:{subItem.Price.ToString("#0.0000")} * {subItem.Quantity.ToString("#0.0000")})【申请人:{item.CreateUser} 申请时间:{item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")}】";
  3631. subItem.ExcelRemaksDescription = excelRemaksDescription;
  3632. rowNumber++;
  3633. }
  3634. }
  3635. decimal total_gz = DailyFeePaymentData.Where(s => s.transferParentId == stGZ.Id).Sum(d => d.SumPrice ?? 0M);
  3636. decimal total_sz = DailyFeePaymentData.Where(s => s.transferParentId == stSZ.Id).Sum(d => d.SumPrice ?? 0M);
  3637. var result = new tree_Fin_DailyFeePaymentResult() { gz = total_gz, sz = total_sz, dataList = DailyFeePaymentData };
  3638. return result;
  3639. }
  3640. /// <summary>
  3641. /// 付款申请 (PageId=51)
  3642. /// 团组,日付相关费用 选中状态变更
  3643. /// </summary>
  3644. /// <param name="dto"></param>
  3645. /// <returns></returns>
  3646. [HttpPost]
  3647. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3648. public async Task<IActionResult> PostPayRequestCheckedChange(PayRequestCheckedChangeDto dto)
  3649. {
  3650. #region 验证
  3651. if (dto.Type < 1 || dto.Type > 2)
  3652. {
  3653. return Ok(JsonView(false, "请传入有效的Type参数! 1 checked 2 清除上次勾选"));
  3654. }
  3655. #endregion
  3656. var requestCheckedView = new PaymentRequestCheckedView();
  3657. var groupIds = new List<int>();
  3658. var dailyPaymentIds = new List<int>();
  3659. var hotelIds = new List<int>();
  3660. #region 参数处理
  3661. if (!string.IsNullOrEmpty(dto.GroupIds))
  3662. {
  3663. if (dto.GroupIds.Contains(","))
  3664. {
  3665. groupIds = dto.GroupIds.Split(',').Select(int.Parse).ToList();
  3666. }
  3667. else
  3668. {
  3669. groupIds.Add(int.Parse(dto.GroupIds));
  3670. }
  3671. }
  3672. if (!string.IsNullOrEmpty(dto.HotelSubIds))
  3673. {
  3674. if (dto.HotelSubIds.Contains(","))
  3675. {
  3676. hotelIds = dto.HotelSubIds.Split(',').Select(int.Parse).ToList();
  3677. }
  3678. else
  3679. {
  3680. hotelIds.Add(int.Parse(dto.HotelSubIds));
  3681. }
  3682. }
  3683. if (!string.IsNullOrEmpty(dto.DailyPaymentIds))
  3684. {
  3685. if (dto.DailyPaymentIds.Contains(","))
  3686. {
  3687. dailyPaymentIds = dto.DailyPaymentIds.Split(',').Select(int.Parse).ToList();
  3688. }
  3689. else
  3690. {
  3691. dailyPaymentIds.Add(int.Parse(dto.DailyPaymentIds));
  3692. }
  3693. }
  3694. #endregion
  3695. requestCheckedView.GroupIds = groupIds;
  3696. requestCheckedView.HotelSubIds = hotelIds;
  3697. requestCheckedView.DailyPaymentIds = dailyPaymentIds;
  3698. if (dto.Type == 1)
  3699. {
  3700. TimeSpan ts = DateTime.Now.AddDays(180) - DateTime.Now; //设置redis 过期时间 半年(180)
  3701. var status = await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync<string>("paymentRequestCheckedData", JsonConvert.SerializeObject(requestCheckedView), ts);
  3702. if (status)
  3703. {
  3704. return Ok(JsonView(true, "操作成功!"));
  3705. }
  3706. }
  3707. else if (dto.Type == 2)
  3708. {
  3709. var status = await RedisRepository.RedisFactory.CreateRedisRepository().KeyDeleteAsync("paymentRequestCheckedData");
  3710. if (status)
  3711. {
  3712. return Ok(JsonView(true, "操作成功!"));
  3713. }
  3714. }
  3715. return Ok(JsonView(false, "操作失败!"));
  3716. }
  3717. /// <summary>
  3718. /// 付款申请 (PageId=51)
  3719. /// 团组,日付相关费用 汇率变更
  3720. /// </summary>
  3721. /// <param name="dto"></param>
  3722. /// <returns></returns>
  3723. [HttpPost]
  3724. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3725. public async Task<IActionResult> PostPayRequestRateChange(PayRequestRateChangeDto dto)
  3726. {
  3727. #region 验证
  3728. DateTime beginDt, endDt;
  3729. string format = "yyyy-MM-dd";
  3730. if (!DateTime.TryParseExact(dto.beginDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out beginDt))
  3731. {
  3732. return Ok(JsonView(false, "开始日期格式不正确!正确格式:yyyy-MM-dd"));
  3733. }
  3734. if (!DateTime.TryParseExact(dto.endDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDt))
  3735. {
  3736. return Ok(JsonView(false, "结束日期格式不正确!正确格式:yyyy-MM-dd"));
  3737. }
  3738. if (dto.UserId < 1) return Ok(JsonView(false, "请传入有效的UserId参数!"));
  3739. if (dto.Id < 1) return Ok(JsonView(false, "请传入有效的Id参数!"));
  3740. if (dto.Rate <= 0) return Ok(JsonView(false, "请传入有效的Rate参数!"));
  3741. #endregion
  3742. int hotelSubStatus = 0, status = 0;
  3743. int diid = 0, cTable = 0, currId = 0;
  3744. if (dto.HotelSubId > 0)
  3745. {
  3746. //更改酒店子表汇率
  3747. hotelSubStatus = _sqlSugar.Updateable<Grp_HotelReservationsContent>()
  3748. .SetColumns(it => it.Rate == dto.Rate)
  3749. .Where(it => it.Id == dto.HotelSubId)
  3750. .ExecuteCommand();
  3751. if (hotelSubStatus > 0)
  3752. {
  3753. var hotelSubInfo = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => it.Id == dto.HotelSubId).First();
  3754. if (hotelSubInfo != null)
  3755. {
  3756. diid = hotelSubInfo.DiId;
  3757. currId = hotelSubInfo.Currency;
  3758. }
  3759. //付款申请汇率更改成功;更改团组汇率对应币种
  3760. string currCode = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == currId).First()?.Name ?? "";
  3761. await _teamRateRep.UpdateGroupRateByDiIdAndCTableId(diid, 76, currCode, dto.Rate);
  3762. }
  3763. }
  3764. if (dto.Id > 0)
  3765. {
  3766. var ccpInfo = _sqlSugar.Queryable<Grp_CreditCardPayment>().Where(it => it.Id == dto.Id).First();
  3767. decimal cnyMoney = 0.00M;
  3768. if (ccpInfo != null)
  3769. {
  3770. cnyMoney = ccpInfo.PayMoney * dto.Rate;
  3771. diid = ccpInfo.DIId;
  3772. cTable = ccpInfo.CTable;
  3773. currId = ccpInfo.PaymentCurrency;
  3774. }
  3775. status = _sqlSugar.Updateable<Grp_CreditCardPayment>()
  3776. .SetColumns(it => it.DayRate == dto.Rate)
  3777. .SetColumns(it => it.RMBPrice == cnyMoney)
  3778. .Where(it => it.Id == dto.Id)
  3779. .ExecuteCommand();
  3780. if (status > 0)
  3781. {
  3782. //付款申请汇率更改成功;更改团组汇率对应币种
  3783. if (cTable != 76)
  3784. {
  3785. string currCode = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == currId).First()?.Name ?? "";
  3786. await _teamRateRep.UpdateGroupRateByDiIdAndCTableId(diid, cTable, currCode, dto.Rate);
  3787. }
  3788. }
  3789. }
  3790. if (hotelSubStatus > 0 || status > 0)
  3791. {
  3792. PaymentRequestCheckedView checkedView = new PaymentRequestCheckedView();
  3793. var checkedStr = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>("paymentRequestCheckedData");
  3794. if (checkedStr != null)
  3795. {
  3796. checkedView = JsonConvert.DeserializeObject<PaymentRequestCheckedView>(checkedStr.ToString());
  3797. }
  3798. tree_Fin_DailyFeePaymentResult dailyResult = PayRequest_DailyByDateRange(1, checkedView.DailyPaymentIds, dto.beginDt, dto.endDt);
  3799. tree_Group_DailyFeePaymentResult groupResult = PayRequest_GroupPaymentByDateRange(1, checkedView.GroupIds, checkedView.HotelSubIds, dto.beginDt, dto.endDt);
  3800. decimal _gz = dailyResult.gz + groupResult.gz;
  3801. decimal _sz = dailyResult.sz + groupResult.sz;
  3802. return Ok(JsonView(true, "操作成功!", new { gz = dailyResult, sz = groupResult }));
  3803. }
  3804. return Ok(JsonView(false, "该项汇率修改失败!"));
  3805. }
  3806. /// <summary>
  3807. /// 付款申请 (PageId=51)
  3808. /// 团组,日付相关费用 付款状态变更
  3809. /// </summary>
  3810. /// <param name="dto"></param>
  3811. /// <returns></returns>
  3812. [HttpPost]
  3813. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3814. public async Task<IActionResult> PostPayRequestPayChange(PayRequestPayChangeDto dto)
  3815. {
  3816. if (dto.UserId < 1) return Ok(JsonView(false, "请传入有效的UserId参数!"));
  3817. //if (string.IsNullOrEmpty(dto.GroupIds))
  3818. //{
  3819. // return Ok(JsonView(false, "请传入有效的GroupIds参数!"));
  3820. //}
  3821. //if (string.IsNullOrEmpty(dto.DailyPaymentIds))
  3822. //{
  3823. // return Ok(JsonView(false, "请传入有效的DailyPaymentIds参数!"));
  3824. //}
  3825. List<int> groupIds = new List<int>();
  3826. List<int> dailyPaymentIds = new List<int>();
  3827. List<int> hotelSubIds = new List<int>();
  3828. #region 参数处理
  3829. if (!string.IsNullOrEmpty(dto.GroupIds))
  3830. {
  3831. if (dto.GroupIds.Contains(",")) groupIds = dto.GroupIds.Split(',').Select(int.Parse).ToList();
  3832. else groupIds.Add(int.Parse(dto.GroupIds));
  3833. }
  3834. if (!string.IsNullOrEmpty(dto.HotelSubIds))
  3835. {
  3836. if (dto.HotelSubIds.Contains(",")) hotelSubIds = dto.HotelSubIds.Split(',').Select(int.Parse).ToList();
  3837. else hotelSubIds.Add(int.Parse(dto.HotelSubIds));
  3838. if (hotelSubIds.Count > 0)
  3839. {
  3840. foreach (var item in hotelSubIds)
  3841. {
  3842. if (item < 1)
  3843. {
  3844. hotelSubIds.Remove(item);
  3845. }
  3846. }
  3847. }
  3848. }
  3849. if (!string.IsNullOrEmpty(dto.DailyPaymentIds))
  3850. {
  3851. if (dto.DailyPaymentIds.Contains(",")) dailyPaymentIds = dto.DailyPaymentIds.Split(',').Select(int.Parse).ToList();
  3852. else dailyPaymentIds.Add(int.Parse(dto.DailyPaymentIds));
  3853. }
  3854. #endregion
  3855. bool changeStatus = false;
  3856. _sqlSugar.BeginTran();
  3857. if (groupIds.Count > 0)
  3858. {
  3859. var ccpInfos = _sqlSugar.Queryable<Grp_CreditCardPayment>().Where(it => it.IsDel == 0 && groupIds.Contains(it.Id)).ToList();
  3860. var otherTypeCcpIds = ccpInfos.Where(it => it.CTable != 76).Select(it => it.Id).ToList();
  3861. var hotelTyprCcpIds = ccpInfos.Where(it => it.CTable == 76).Select(it => it.Id).ToList();
  3862. int groupStatus = 0;
  3863. if (otherTypeCcpIds.Count > 0) //其他费用类型 正常付款
  3864. {
  3865. groupStatus = _sqlSugar.Updateable<Grp_CreditCardPayment>()
  3866. .SetColumns(it => it.IsPay == 1)
  3867. .Where(it => otherTypeCcpIds.Contains(it.Id))
  3868. .ExecuteCommand();
  3869. changeStatus = true;
  3870. }
  3871. if (hotelTyprCcpIds.Count > 0) //酒店费用子项逻辑付款,酒店子项费用全部付完款,c表ispay=1
  3872. {
  3873. if (hotelSubIds.Count > 0)
  3874. {
  3875. List<int> hrPayIds = new List<int>();
  3876. var hrIspayStatus = _sqlSugar.Updateable<Grp_HotelReservationsContent>()
  3877. .SetColumns(it => it.IsPay == 1)
  3878. .Where(it => hotelSubIds.Contains(it.Id))
  3879. .ExecuteCommand();
  3880. changeStatus = true;
  3881. //酒店子项是否全部付完款
  3882. List<int> hrIds = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => it.IsDel == 0 && hotelSubIds.Contains(it.Id)).Select(it => it.HrId).Distinct().ToList();
  3883. if (hrIds.Count > 0)
  3884. {
  3885. var hotelSubFeeData = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => it.IsDel == 0 && hrIds.Contains(it.HrId)).ToList();
  3886. var hotelSubFeeGroupData = hotelSubFeeData.GroupBy(it => it.HrId).ToList();
  3887. foreach (var item in hotelSubFeeGroupData)
  3888. {
  3889. var allTotal = item.Where(it => it.Price > 0).ToList().Count;
  3890. var paymentTotal = item.Where(it => it.Price > 0 && it.IsPay == 1).ToList().Count;
  3891. if (allTotal == paymentTotal)
  3892. {
  3893. hrPayIds.Add(item.Key);
  3894. }
  3895. }
  3896. }
  3897. if (hrPayIds.Count > 0)
  3898. {
  3899. //c表更改全部付款的酒店费用
  3900. groupStatus = _sqlSugar.Updateable<Grp_CreditCardPayment>()
  3901. .SetColumns(it => it.IsPay == 1)
  3902. .Where(it => it.CTable == 76 && hrPayIds.Contains(it.CId))
  3903. .ExecuteCommand();
  3904. }
  3905. }
  3906. }
  3907. }
  3908. //if (hotelSubIds.Count > 0)
  3909. //{
  3910. // var groupStatus = _sqlSugar.Updateable<Grp_HotelReservationsContent>()
  3911. // .SetColumns(it => it.IsPay == 1)
  3912. // .Where(it => hotelSubIds.Contains(it.Id))
  3913. // .ExecuteCommand();
  3914. // if (groupStatus > 0)
  3915. // {
  3916. // changeStatus = true;
  3917. // }
  3918. //}
  3919. if (dailyPaymentIds.Count > 0)
  3920. {
  3921. var dailyPaymentStatus = _sqlSugar.Updateable<Fin_DailyFeePayment>()
  3922. .SetColumns(it => it.IsPay == 1)
  3923. .Where(it => dailyPaymentIds.Contains(it.Id))
  3924. .ExecuteCommand();
  3925. //修改提成关联表
  3926. var ids = _sqlSugar.Queryable<Fin_DailyFeePayment>()
  3927. .LeftJoin<Fin_RoyaltyForm>((dfp, rf) => dfp.Id == rf.DayOverhead && rf.IsDel == 0)
  3928. .Where(dfp => dailyPaymentIds.Contains(dfp.Id) && dfp.IsDel == 0)
  3929. .Select((dfp, rf) => rf.ConfirmIdArr).ToList();
  3930. var idsList = string.Join(',', ids).Split(',')
  3931. .Select(x =>
  3932. {
  3933. if (!string.IsNullOrWhiteSpace(x) && int.TryParse(x, out int intx))
  3934. {
  3935. return intx;
  3936. }
  3937. return 0;
  3938. })
  3939. .Where(x => x != 0)
  3940. .Distinct()
  3941. .ToList();
  3942. _sqlSugar.Updateable<Fin_RoyaltyConfirm>()
  3943. .SetColumns(it => it.IsSeed == 1)
  3944. .Where(it => idsList.Contains(it.Id) && it.IsSeed == 0)
  3945. .ExecuteCommand();
  3946. if (dailyPaymentStatus > 0)
  3947. {
  3948. changeStatus = true;
  3949. }
  3950. }
  3951. if (changeStatus)
  3952. {
  3953. _sqlSugar.CommitTran();
  3954. //todo:日志记录
  3955. _logger.LogInformation("【付款申请】【状态:操作成功!】请求参数: OpUserId: {UserId}, GroupIds: {GroupIds}, DailyPaymentIds: {DailyPaymentIds}, HotelSubIds: {HotelSubIds}",
  3956. dto.UserId, string.Join(",", groupIds), string.Join(",", dailyPaymentIds), string.Join(",", hotelSubIds));
  3957. #region 应用推送
  3958. try
  3959. {
  3960. foreach (int ccpId in groupIds)
  3961. {
  3962. List<string> tempList = new List<string>() { ccpId.ToString() };
  3963. await AppNoticeLibrary.SendUserMsg_GroupStatus_PayResult(ccpId, tempList);
  3964. }
  3965. foreach (int dailyId in dailyPaymentIds)
  3966. {
  3967. List<string> tempList = new List<string>() { dailyId.ToString() };
  3968. await AppNoticeLibrary.DailyPayReminder_Pay_ToUser(dailyId, tempList);
  3969. }
  3970. }
  3971. catch (Exception ex)
  3972. {
  3973. }
  3974. #endregion
  3975. return Ok(JsonView(true, "操作成功!"));
  3976. }
  3977. _sqlSugar.RollbackTran();
  3978. //todo:日志记录
  3979. _logger.LogWarning("【付款申请】【状态:操作失败!】 请求参数:OpUserId: {UserId}, GroupIds: {GroupIds}, DailyPaymentIds: {DailyPaymentIds}, HotelSubIds: {HotelSubIds}",
  3980. dto.UserId, string.Join(",", groupIds), string.Join(",", dailyPaymentIds), string.Join(",", hotelSubIds));
  3981. return Ok(JsonView(false, "付款状态修改失败!"));
  3982. }
  3983. /// <summary>
  3984. /// 付款申请 (PageId=51)
  3985. /// File Download
  3986. /// </summary>
  3987. /// <param name="dto"></param>
  3988. /// <returns></returns>
  3989. [HttpPost]
  3990. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3991. public async Task<IActionResult> PostPayRequestFileDownload(PayRequestFileDownloadDto dto)
  3992. {
  3993. Stopwatch stopwatch = Stopwatch.StartNew();
  3994. #region 参数,权限 验证
  3995. if (dto.PortType < 1)
  3996. {
  3997. return Ok(JsonView(false, "请传入有效的PortType参数!"));
  3998. }
  3999. if (dto.UserId < 1)
  4000. {
  4001. return Ok(JsonView(false, "请传入有效的UserId参数!"));
  4002. }
  4003. if (dto.PageId < 1)
  4004. {
  4005. dto.PageId = 51;
  4006. return Ok(JsonView(false, "请传入有效的PageId参数!"));
  4007. }
  4008. var conpanyDatas = _sqlSugar.Queryable<Sys_Company>()
  4009. .Where(it => it.IsDel == 0)
  4010. .Select(it => new
  4011. {
  4012. Id = it.Id,
  4013. ConpamyName = it.CompanyName
  4014. }).ToList();
  4015. var conpanyIds = conpanyDatas.Select(x => x.Id).ToList();
  4016. if (!conpanyIds.Contains(dto.ConpanyId))
  4017. {
  4018. return Ok(JsonView(false, "请传入有效的ConpanyId参数!"));
  4019. }
  4020. #region 页面操作权限验证
  4021. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  4022. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权限!"));
  4023. #endregion
  4024. #endregion
  4025. try
  4026. {
  4027. var checkedView = new PaymentRequestCheckedView();
  4028. var checkedStr = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>("paymentRequestCheckedData");
  4029. if (checkedStr != null)
  4030. {
  4031. checkedView = JsonConvert.DeserializeObject<PaymentRequestCheckedView>(checkedStr.ToString());
  4032. }
  4033. if (checkedView == null)
  4034. {
  4035. return Ok(JsonView(false, "没有选中的数据!"));
  4036. }
  4037. if (checkedView.GroupIds == null && checkedView.DailyPaymentIds == null)
  4038. {
  4039. return Ok(JsonView(false, "没有选中的数据!"));
  4040. }
  4041. tree_Fin_DailyFeePaymentResult dailyResult = PayRequest_DailyByDateRange(2, checkedView.DailyPaymentIds, dto.beginDt, dto.endDt);
  4042. tree_Group_DailyFeePaymentResult groupResult = PayRequest_GroupPaymentByDateRange(2, checkedView.GroupIds, checkedView.HotelSubIds, dto.beginDt, dto.endDt);
  4043. if (dailyResult.childList == null)
  4044. {
  4045. dailyResult.childList = new List<Fin_DailyFeePaymentContentInfolView>();
  4046. }
  4047. var _GroupData = new List<tree_Group_DailyFeePaymentPageListView>();
  4048. var _DailyData = new List<tree_Fin_DailyFeePaymentPageListView>();
  4049. if (groupResult.dataList != null && groupResult.dataList.Any()) _GroupData = groupResult.dataList.Where(it => it.CompanyId == dto.ConpanyId).ToList();
  4050. if (dailyResult.dataList != null && dailyResult.dataList.Any()) _DailyData = dailyResult.dataList.Where(it => it.CompanyId == dto.ConpanyId).ToList();
  4051. ////1 成都泛美商务有限公司
  4052. //if (dto.ConpanyId == 1)
  4053. //{
  4054. // if (groupResult.dataList != null && groupResult.dataList.Count > 0) _GroupData = groupResult.dataList.Where(it => it.CompanyId == 1).ToList();
  4055. // if (dailyResult.dataList != null && dailyResult.dataList.Count > 0) _DailyData = dailyResult.dataList.Where(it => it.CompanyId == 1).ToList();
  4056. //}
  4057. ////2 四川泛美交流有限公司
  4058. //else if (dto.ConpanyId == 2)
  4059. //{
  4060. // if (groupResult.dataList != null && groupResult.dataList.Count > 0) _GroupData = groupResult.dataList.Where(it => it.CompanyId == 2).ToList();
  4061. // if (dailyResult.dataList != null && dailyResult.dataList.Count > 0) _DailyData = dailyResult.dataList.Where(it => it.CompanyId == 2).ToList();
  4062. //}
  4063. ////3 成都纽茵教育科技有限公司
  4064. //else if (dto.ConpanyId == 3)
  4065. //{
  4066. // if (groupResult.dataList != null && groupResult.dataList.Count > 0) _GroupData = groupResult.dataList.Where(it => it.CompanyId == 3).ToList();
  4067. // if (dailyResult.dataList != null && dailyResult.dataList.Count > 0) _DailyData = dailyResult.dataList.Where(it => it.CompanyId == 3).ToList();
  4068. //}
  4069. ////4 成都鸿企中元科技有限公司
  4070. //else if (dto.ConpanyId == 4)
  4071. //{
  4072. // return Ok(JsonView(false, "暂未开放该类型!"));
  4073. //}
  4074. //else
  4075. //{
  4076. // return Ok(JsonView(false, "参数ConpanyId不可使用!"));
  4077. //}
  4078. string _requestPaymentDt = DateTime.Now.ToString("yyyy-MM-dd"),//申请付款日期
  4079. _appliedAmount = "", //申请付款金额
  4080. _GZStr = "", //公转价格描述
  4081. _SZStr = ""; //私转价格描述
  4082. decimal groupGZAmout = 0.00M, groupSZAmout = 0.00M;
  4083. decimal dailyGZAmout = 0.00M, dailySZAmout = 0.00M;
  4084. string dailyGZStr = "", dailySZStr = "", groupGZStr = "", groupSZStr = "";
  4085. #region 数据处理
  4086. //团组费用相关
  4087. foreach (var item in _GroupData)
  4088. {
  4089. string groupGZSubStr = "";
  4090. string groupSZSubStr = "";
  4091. foreach (var subItem in item.ChildList)
  4092. {
  4093. if (subItem.TransferMark.Equals("公转"))
  4094. {
  4095. groupGZAmout += subItem.CNYSubTotalAmount;
  4096. groupGZSubStr += $"{subItem.RemaksDescription}\r\n";
  4097. }
  4098. else if (subItem.TransferMark.Equals("私转"))
  4099. {
  4100. groupSZAmout += subItem.CNYSubTotalAmount;
  4101. groupSZSubStr += $"{subItem.RemaksDescription}\r\n";
  4102. }
  4103. //groupGZSubStr += $"\t";
  4104. }
  4105. //if (!string.IsNullOrEmpty(groupGZSubStr)) groupGZStr += $"团组:{item.GroupName}\r\n{groupGZSubStr}\r\n";
  4106. //if (!string.IsNullOrEmpty(groupSZSubStr)) groupSZStr += $"团组:{item.GroupName}\r\n{groupSZSubStr}\r\n";
  4107. if (!string.IsNullOrEmpty(groupGZSubStr)) groupGZStr += $"{groupGZSubStr}\r\n";
  4108. if (!string.IsNullOrEmpty(groupSZSubStr)) groupSZStr += $"{groupSZSubStr}\r\n";
  4109. }
  4110. //日常费用相关
  4111. foreach (var item in _DailyData)
  4112. {
  4113. foreach (var subItem in item.childList)
  4114. {
  4115. if (item.transferParentId == 62) //公转
  4116. {
  4117. dailyGZAmout += item.SumPrice ?? 0.00M;
  4118. dailyGZStr += $"{item.RowNumber}、【{item.CompanyName}】{subItem.ExcelRemaksDescription}\r\n";
  4119. }
  4120. else if (item.transferParentId == 63) //私转
  4121. {
  4122. dailySZAmout += item.SumPrice ?? 0.00M;
  4123. dailySZStr += $"{item.RowNumber}、【{item.CompanyName}】{subItem.ExcelRemaksDescription}\r\n";
  4124. }
  4125. }
  4126. }
  4127. _GZStr = $"【公转】团组相关费用(合计:CNY {groupGZAmout:#0.00}):\r\n{groupGZStr}【公转】日常付款费用(合计:CNY {dailyGZAmout:#0.00}):\r\n{dailyGZStr}";
  4128. _SZStr = $"【私转】团组相关费用(合计:CNY {groupSZAmout:#0.00}):\r\n{groupSZStr}【私转】日常付款费用(合计:CNY {dailySZAmout:#0.00}):\r\n{dailySZStr}";
  4129. _appliedAmount = $"公转:CNY {(groupGZAmout + dailyGZAmout).ToString("#0.00")}\r\n私转:CNY {(groupSZAmout + dailySZAmout).ToString("#0.00")}";
  4130. #endregion
  4131. var designer = new WorkbookDesigner
  4132. {
  4133. Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/付款申请书.xls")
  4134. };
  4135. designer.SetDataSource("Date", _requestPaymentDt);
  4136. designer.SetDataSource("Price", _appliedAmount);
  4137. designer.SetDataSource("Content", _GZStr);
  4138. designer.SetDataSource("Content1", _SZStr);
  4139. //根据数据源处理生成报表内容
  4140. designer.Process();
  4141. string fileName = ("PayRequest/付款申请(" + dto.beginDt + "~" + dto.endDt + ").xlsx");
  4142. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  4143. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  4144. stopwatch.Stop();
  4145. return Ok(JsonView(true, $"操作成功!{stopwatch.ElapsedMilliseconds / 1000}s", new { url = rst }));
  4146. }
  4147. catch (Exception ex)
  4148. {
  4149. return Ok(JsonView(false, ex.Message));
  4150. }
  4151. }
  4152. #endregion
  4153. #region 超支费用
  4154. /// <summary>
  4155. /// 超支费用
  4156. /// 1增、2改、3删
  4157. /// </summary>
  4158. /// <param name="dto"></param>
  4159. /// <returns></returns>
  4160. [HttpPost]
  4161. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4162. public async Task<IActionResult> PostGroupExtraCost_Operator(Fin_GroupExtraCostDto_OP dto)
  4163. {
  4164. #region 验证
  4165. #endregion
  4166. var _entity = new Fin_GroupExtraCost
  4167. {
  4168. DiId = dto.diId,
  4169. PriceName = dto.priceName,
  4170. Price = dto.price,
  4171. PriceCurrency = dto.currency,
  4172. PriceType = dto.priceType,
  4173. Coefficient = dto.coefficient,
  4174. PriceDetailType = dto.priceDetailType,
  4175. FilePath = dto.filePath,
  4176. Remark = dto.remark,
  4177. PriceCount = dto.PriceCount,
  4178. Area = dto.Area,
  4179. SupervisorConfirm = dto.SupervisorConfirm,
  4180. ManagerConfirm = dto.ManagerConfirm,
  4181. SYsupervisorConfirm = dto.SYsupervisorConfirm
  4182. };
  4183. bool b_PriceDt = DateTime.TryParse(dto.PriceDt, out DateTime dt_PriceDt);
  4184. if (b_PriceDt)
  4185. {
  4186. _entity.PriceDt = dt_PriceDt;
  4187. }
  4188. else
  4189. {
  4190. _entity.PriceDt = DateTime.MinValue;
  4191. }
  4192. _entity.PriceSum = dto.price * dto.PriceCount;
  4193. _daiRep.BeginTran();
  4194. if (dto.editType == 1)
  4195. {
  4196. _entity.CreateUserId = dto.createUser;
  4197. _entity.CreateTime = DateTime.Now;
  4198. _entity.IsDel = 0;
  4199. int returnId = await _daiRep.AddAsyncReturnId<Fin_GroupExtraCost>(_entity);
  4200. if (returnId > 0)
  4201. {
  4202. dto.Id = returnId;
  4203. }
  4204. }
  4205. else if (dto.editType == 2)
  4206. {
  4207. bool res = await _daiRep.UpdateAsync<Fin_GroupExtraCost>(s => s.Id == dto.Id, s => new Fin_GroupExtraCost
  4208. {
  4209. PriceName = dto.priceName,
  4210. Price = dto.price,
  4211. PriceCurrency = dto.currency,
  4212. PriceType = dto.priceType,
  4213. PriceDetailType = dto.priceDetailType,
  4214. Coefficient = dto.coefficient,
  4215. FilePath = dto.filePath,
  4216. Remark = dto.remark,
  4217. PriceCount = dto.PriceCount,
  4218. PriceDt = _entity.PriceDt,
  4219. PriceSum = _entity.PriceSum,
  4220. Area = _entity.Area,
  4221. });
  4222. if (!res)
  4223. {
  4224. _daiRep.RollbackTran();
  4225. return Ok(JsonView(false, "2操作失败!"));
  4226. }
  4227. }
  4228. else if (dto.editType == 3)
  4229. {
  4230. string delTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
  4231. bool res = await _daiRep.UpdateAsync<Fin_GroupExtraCost>(s => s.Id == dto.Id, s => new Fin_GroupExtraCost
  4232. {
  4233. IsDel = 1,
  4234. DeleteTime = delTime,
  4235. DeleteUserId = dto.createUser
  4236. });
  4237. if (!res)
  4238. {
  4239. _daiRep.RollbackTran();
  4240. return Ok(JsonView(false, "3操作失败!"));
  4241. }
  4242. }
  4243. else
  4244. {
  4245. _daiRep.RollbackTran();
  4246. return Ok(JsonView(false, "未知的editType"));
  4247. }
  4248. if (!ExtraCost_editCreditCardPayment(dto))
  4249. {
  4250. return Ok(JsonView(false, "ccp操作失败"));
  4251. }
  4252. //同步修改收款账单
  4253. _foreignReceivablesRepository.OverSpSeteceivables(new OverSpSeteceivablesDto
  4254. {
  4255. CreateUserId = dto.createUser,
  4256. DiId = dto.diId,
  4257. });
  4258. _daiRep.CommitTran();
  4259. return Ok(JsonView(true, "操作成功"));
  4260. }
  4261. private Result PostCurrencyByDiid_Sync(int diId, int CId, int currencyId)
  4262. {
  4263. if (diId == 0)
  4264. {
  4265. return new Result() { Code = -1, Msg = "请传入团组Id!" };
  4266. }
  4267. if (CId == 0)
  4268. {
  4269. return new Result() { Code = -1, Msg = "请传入类型Id!" };
  4270. }
  4271. if (currencyId == 0)
  4272. {
  4273. return new Result() { Code = -1, Msg = "请传入币种Id!" };
  4274. }
  4275. Grp_TeamRate _TeamRate = _sqlSugar.Queryable<Grp_TeamRate>().First(a => a.DiId == diId && a.IsDel == 0 && a.CTable == CId);
  4276. var currencyInfos = new List<CurrencyInfo>();
  4277. var CurrencyRate = new CurrencyInfo();
  4278. try
  4279. {
  4280. if (_TeamRate != null)
  4281. {
  4282. Sys_SetData _SetData = _sqlSugar.Queryable<Sys_SetData>().First(a => a.IsDel == 0 && a.Id == currencyId);
  4283. if (_SetData != null)
  4284. {
  4285. currencyInfos = CommonFun.GetCurrencyChinaToList(_TeamRate.Remark);
  4286. CurrencyRate = currencyInfos.FirstOrDefault(a => a.CurrencyCode == _SetData.Name);
  4287. if (CurrencyRate != null)
  4288. {
  4289. return new Result() { Code = 0, Msg = "查询成功!", Data = CurrencyRate };
  4290. }
  4291. else
  4292. {
  4293. return new Result() { Code = -1, Msg = "暂无团组汇率,请前往设置!", Data = CurrencyRate };
  4294. }
  4295. }
  4296. else
  4297. {
  4298. return new Result() { Code = -1, Msg = "暂无团组汇率,请前往设置!", Data = CurrencyRate };
  4299. }
  4300. }
  4301. else
  4302. {
  4303. return new Result() { Code = -1, Msg = "暂无团组汇率,请前往设置!", Data = CurrencyRate };
  4304. }
  4305. }
  4306. catch (Exception)
  4307. {
  4308. return new Result() { Code = -1, Msg = "查询异常!", Data = CurrencyRate };
  4309. }
  4310. }
  4311. private bool ExtraCost_editCreditCardPayment(Fin_GroupExtraCostDto_OP costDto)
  4312. {
  4313. //设置团组汇率
  4314. decimal dcm_dayrate = 1M;
  4315. decimal dcm_rmbPrice = costDto.price;
  4316. int ispay = costDto.payType == 72 ? 1 : 0;
  4317. if (costDto.costSign != 3)
  4318. {
  4319. //获取新汇率 int diId,int CId, int currencyId
  4320. Result rate = this.PostCurrencyByDiid_Sync(costDto.diId, 1015, costDto.currency);
  4321. if (rate.Code == 0)
  4322. {
  4323. var rateInfo = (rate.Data as CurrencyInfo);
  4324. if (rateInfo is not null)
  4325. {
  4326. dcm_dayrate = rateInfo.Rate;
  4327. dcm_rmbPrice = rateInfo.Rate * dcm_rmbPrice;
  4328. }
  4329. else
  4330. {
  4331. dcm_dayrate = 1;
  4332. }
  4333. }
  4334. }
  4335. Grp_CreditCardPayment ccp = _daiRep.Query<Grp_CreditCardPayment>(s => s.CId == costDto.Id && s.CTable == 1015).First();
  4336. if (ccp == null)
  4337. {
  4338. ccp = new Grp_CreditCardPayment();
  4339. ccp.PayDId = costDto.payType;// dto
  4340. ccp.ConsumptionPatterns = "";
  4341. ccp.ConsumptionDate = "";
  4342. ccp.CTDId = costDto.payCardId;// dto
  4343. ccp.BankNo = "";
  4344. ccp.CardholderName = "";
  4345. ccp.PayMoney = costDto.price;// dto
  4346. ccp.PaymentCurrency = costDto.currency;// dto
  4347. ccp.CompanyBankNo = "";
  4348. ccp.OtherBankName = "";
  4349. ccp.OtherSideNo = "";
  4350. ccp.OtherSideName = "";
  4351. ccp.Remark = "";
  4352. ccp.CreateUserId = costDto.createUser;
  4353. ccp.CreateTime = DateTime.Now;
  4354. ccp.MFOperator = 0;
  4355. ccp.MFOperatorDate = "";
  4356. ccp.IsAuditDM = 0;
  4357. ccp.AuditDMOperate = 0;
  4358. ccp.AuditDMDate = "";
  4359. ccp.IsAuditMF = 0;
  4360. ccp.AuditMFOperate = 0;
  4361. ccp.AuditMFDate = "";
  4362. ccp.IsAuditGM = 0;
  4363. ccp.AuditGMOperate = 0;
  4364. ccp.AuditGMDate = "";
  4365. ccp.IsPay = ispay; // upd
  4366. ccp.DIId = costDto.diId;// dto
  4367. ccp.CId = costDto.Id;// dto
  4368. ccp.CTable = 1015; //超支费用指向id
  4369. ccp.IsDel = 0;
  4370. ccp.PayPercentage = 100M;
  4371. ccp.PayThenMoney = 0M;
  4372. ccp.PayPercentageOld = 100M;
  4373. ccp.PayThenMoneyOld = 0M;
  4374. ccp.UpdateDate = "";
  4375. ccp.Payee = costDto.payee;// dto
  4376. ccp.OrbitalPrivateTransfer = costDto.costSign;// dto
  4377. ccp.ExceedBudget = 0;
  4378. ccp.DayRate = dcm_dayrate; //upd
  4379. ccp.RMBPrice = dcm_rmbPrice; //upd
  4380. int ccpInsertId = _daiRep.AddReturnId<Grp_CreditCardPayment>(ccp);
  4381. if (ccpInsertId > 0)
  4382. {
  4383. return true;
  4384. }
  4385. }
  4386. else
  4387. {
  4388. if (costDto.editType == 2)
  4389. {
  4390. bool res = _daiRep.Update<Grp_CreditCardPayment>(s => s.Id == ccp.Id, s => new Grp_CreditCardPayment
  4391. {
  4392. PayDId = costDto.payType,
  4393. CTDId = costDto.payCardId,
  4394. PayMoney = costDto.price,
  4395. PaymentCurrency = costDto.currency,
  4396. IsPay = ispay,
  4397. Payee = costDto.payee,
  4398. OrbitalPrivateTransfer = costDto.costSign,
  4399. DayRate = dcm_dayrate,
  4400. RMBPrice = dcm_rmbPrice
  4401. });
  4402. return res;
  4403. }
  4404. else if (costDto.editType == 3)
  4405. {
  4406. string delTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
  4407. bool res2 = _daiRep.Update<Grp_CreditCardPayment>(s => s.Id == ccp.Id, s => new Grp_CreditCardPayment
  4408. {
  4409. IsDel = 1,
  4410. DeleteTime = delTime,
  4411. DeleteUserId = costDto.createUser
  4412. });
  4413. return res2;
  4414. }
  4415. }
  4416. return false;
  4417. }
  4418. /// <summary>
  4419. /// 超支费用
  4420. /// 详情查询
  4421. /// </summary>
  4422. /// <param name="dto"></param>
  4423. /// <returns></returns>
  4424. [HttpPost]
  4425. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4426. public async Task<IActionResult> PostGroupExtraCost_Detail(Fin_GroupExtraCostDto_Detail dto)
  4427. {
  4428. if (dto.Id < 1)
  4429. {
  4430. return Ok(JsonView(false, "查询失败"));
  4431. }
  4432. string sql = string.Format(@" Select
  4433. f.Id,f.DiId,
  4434. f.PriceName,f.Price,f.PriceCurrency,c.Payee,c.OrbitalPrivateTransfer,c.PayDId,f.area,
  4435. c.CTDId,f.PriceType,f.PriceDetailType,f.Coefficient,f.Remark,f.PriceCount,f.PriceDt
  4436. From Fin_GroupExtraCost f
  4437. Inner Join Grp_CreditCardPayment c On f.Id = c.CId
  4438. Left Join Sys_Users u On f.CreateUserId = u.Id
  4439. Where f.IsDel=0 And c.CTable = 1015
  4440. And f.Id = {0} ", dto.Id);
  4441. Fin_GroupExtraCostDetailView detailView = await _sqlSugar.SqlQueryable<Fin_GroupExtraCostDetailView>(sql).FirstAsync();
  4442. if (detailView == null)
  4443. {
  4444. return Ok(JsonView(false, "查询失败"));
  4445. }
  4446. if (!string.IsNullOrEmpty(detailView.Remark))
  4447. {
  4448. detailView.Remark = detailView.Remark.Replace("[TuT]", string.Empty);
  4449. }
  4450. return Ok(JsonView(true, "查询成功", detailView));
  4451. }
  4452. /// <summary>
  4453. /// 超支费用
  4454. /// 列表查询
  4455. /// </summary>
  4456. /// <param name="dto"></param>
  4457. /// <returns></returns>
  4458. [HttpPost]
  4459. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4460. public async Task<IActionResult> PostGroupExtraCost_Search(Fin_GroupExtraCostDto_Search dto)
  4461. {
  4462. string sqlWhere = string.Format(@" And f.DiId = {0} ", dto.diId);
  4463. int startIndex = (dto.PageIndex - 1) * dto.PageSize + 1;
  4464. int endIndex = startIndex + dto.PageSize - 1;
  4465. string sql_data = string.Format(@"Select * From (
  4466. Select row_number() over (order by f.Id Desc) as RowNumber,f.Id,f.DiId,
  4467. f.PriceName,f.PriceType,f.PriceDetailType,CAST(f.Price as varchar)+' '+s.[Name] as PriceStr,f.PriceCount,CAST(f.PriceSum as varchar)+' '+s.[Name] as PriceSumStr,
  4468. f.CreateUserId,f.PriceDt,c.IsAuditGM,f.ManagerConfirm,f.SupervisorConfirm,f.Remark,
  4469. CASE ManagerConfirm WHEN 1 THEN '已确认' ELSE '未确认' END as 'ManagerConfirmStr' , CASE SupervisorConfirm WHEN 1 THEN '已确认' ELSE '未确认' END as 'SupervisorConfirmStr',
  4470. CASE SYsupervisorConfirm WHEN 1 THEN '已确认' ELSE '未确认' END as 'SYsupervisorConfirmStr'
  4471. From Fin_GroupExtraCost f
  4472. Inner Join Grp_CreditCardPayment c On f.Id = c.CId
  4473. Inner Join Sys_SetData s On f.PriceCurrency = s.Id
  4474. Left Join Sys_Users u On f.CreateUserId = u.Id
  4475. Where f.IsDel=0 And c.CTable = 1015 {0}
  4476. ) temp Where RowNumber Between {1} and {2}", sqlWhere, startIndex, endIndex);
  4477. string sql_count = string.Format(@"Select Count(1) as DataCount From (
  4478. Select row_number() over (order by f.Id Desc) as RowNumber,f.Id,f.DiId,
  4479. f.PriceName,f.PriceType,f.Price,f.FilePath,f.CreateUserId,f.CreateTime,c.IsAuditGM,f.ManagerConfirm,f.SupervisorConfirm,f.Remark,
  4480. CASE ManagerConfirm WHEN 1 THEN '已确认' ELSE '未确认' END as 'ManagerConfirmStr' , CASE SupervisorConfirm WHEN 1 THEN '已确认' ELSE '未确认' END as 'SupervisorConfirmStr',
  4481. CASE SYsupervisorConfirm WHEN 1 THEN '已确认' ELSE '未确认' END as 'SYsupervisorConfirmStr'
  4482. From Fin_GroupExtraCost f
  4483. Inner Join Grp_CreditCardPayment c On f.Id = c.CId
  4484. Inner Join Sys_SetData s On f.PriceCurrency = s.Id
  4485. Left Join Sys_Users u On f.CreateUserId = u.Id
  4486. Where f.IsDel=0 And c.CTable = 1015 {0}
  4487. ) temp ", sqlWhere);
  4488. if (dto.PortType == 1 || dto.PortType == 2 || dto.PortType == 3) //web
  4489. {
  4490. //Fin_DailyFeePaymentPageCount
  4491. var count = await _sqlSugar.SqlQueryable<Fin_GroupExtraCostViewDataCount>(sql_count).FirstAsync();
  4492. List<Fin_GroupExtraCostView> dataList = await _sqlSugar.SqlQueryable<Fin_GroupExtraCostView>(sql_data).ToListAsync();
  4493. Dictionary<int, string> dic_setData = new Dictionary<int, string>();
  4494. Dictionary<int, string> dic_user = new Dictionary<int, string>();
  4495. foreach (var item in dataList)
  4496. {
  4497. bool b_ct = DateTime.TryParse(item.PriceDt, out DateTime dtTemp_PriceDt);
  4498. if (b_ct)
  4499. {
  4500. item.PriceDt = dtTemp_PriceDt.ToString("yyyy-MM-dd");
  4501. }
  4502. //费用类型
  4503. if (dic_setData.ContainsKey(item.PriceType))
  4504. {
  4505. item.PriceTypeStr = dic_setData[item.PriceType];
  4506. }
  4507. else
  4508. {
  4509. Sys_SetData sd_priceTypeDetail = _daiRep.Query<Sys_SetData>(s => s.Id == item.PriceType).First();
  4510. if (sd_priceTypeDetail != null)
  4511. {
  4512. string tempName = sd_priceTypeDetail.Name.Replace("n", "");
  4513. item.PriceTypeStr = tempName;
  4514. dic_setData.Add(item.PriceType, tempName);
  4515. }
  4516. }
  4517. if (item.PriceDetailType > 0)
  4518. {
  4519. if (dic_setData.ContainsKey(item.PriceDetailType))
  4520. {
  4521. item.PriceTypeStr = item.PriceTypeStr + " - " + dic_setData[item.PriceDetailType];
  4522. }
  4523. else
  4524. {
  4525. Sys_SetData sd_priceTypeDetail = _daiRep.Query<Sys_SetData>(s => s.Id == item.PriceDetailType).First();
  4526. if (sd_priceTypeDetail != null)
  4527. {
  4528. string tempName = sd_priceTypeDetail.Name.Replace("n", "");
  4529. item.PriceTypeStr = item.PriceTypeStr + " - " + tempName;
  4530. dic_setData.Add(item.PriceDetailType, tempName);
  4531. }
  4532. }
  4533. }
  4534. //系统用户
  4535. if (dic_user.ContainsKey(item.CreateUserId))
  4536. {
  4537. item.CreateUserIdStr = dic_user[item.CreateUserId];
  4538. }
  4539. else
  4540. {
  4541. Sys_Users users = _daiRep.Query<Sys_Users>(s => s.Id == item.CreateUserId).First();
  4542. if (users != null)
  4543. {
  4544. item.CreateUserIdStr = users.CnName;
  4545. dic_user.Add(item.CreateUserId, users.CnName);
  4546. }
  4547. }
  4548. switch (item.IsAuditGM)
  4549. {
  4550. case 0: item.IsAuditGMStr = "未审核"; break;
  4551. case 1: item.IsAuditGMStr = "已通过"; break;
  4552. case 2: item.IsAuditGMStr = "未通过"; break;
  4553. default: item.IsAuditGMStr = "未知状态"; break;
  4554. }
  4555. }
  4556. var overspendAuditUser = AppSettingsHelper.Get<OverspendAuditUserView>("OverspendAuditUser");
  4557. var result = new
  4558. {
  4559. CurrPageIndex = dto.PageIndex,
  4560. CurrPageSize = dto.PageSize,
  4561. DataCount = count.DataCount,
  4562. DataList = dataList,
  4563. overspendAuditUser = new
  4564. {
  4565. jinliExpand = overspendAuditUser.Find(x => x.Job == "opJinLi").Users.Select(x => x.Id),
  4566. zhuguanExpand = overspendAuditUser.Find(x => x.Job == "opZhuGuan").Users.Select(x => x.Id),
  4567. syzhuguanExpand = overspendAuditUser.Find(x => x.Job == "syZhuGuan").Users.Select(x => x.Id),
  4568. }
  4569. };
  4570. return Ok(JsonView(true, "查询成功", result));
  4571. }
  4572. return Ok(JsonView(false, "查询失败"));
  4573. }
  4574. /// <summary>
  4575. /// 超支费用
  4576. /// 数据集合配置
  4577. /// </summary>
  4578. /// <param name="dto"></param>
  4579. /// <returns></returns>
  4580. [HttpPost]
  4581. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4582. public async Task<IActionResult> PostGroupExtraCost_ListDataInit(Fin_GroupExtraCostDto_DataListInit dto)
  4583. {
  4584. //支付方式
  4585. List<Sys_SetData> Payment = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 14 && a.IsDel == 0).ToList();
  4586. List<SetDataInfoView> _Payment = _mapper.Map<List<SetDataInfoView>>(Payment);
  4587. //信用卡类型
  4588. List<Sys_SetData> Card = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 15 && a.IsDel == 0).ToList();
  4589. List<SetDataInfoView> _Card = _mapper.Map<List<SetDataInfoView>>(Card);
  4590. //超支费用类型
  4591. List<Sys_SetData> PriceType = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 79 && a.IsDel == 0).ToList();
  4592. List<SetDataInfoView> _PriceType = _mapper.Map<List<SetDataInfoView>>(PriceType);
  4593. //超支费用详细类型
  4594. List<Sys_SetData> PriceDetailType = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 80 && a.IsDel == 0).ToList();
  4595. PriceDetailType.ForEach(a => { a.Name = a.Name.Replace("n", ""); });
  4596. List<SetDataInfoView> _PriceDetailType = _mapper.Map<List<SetDataInfoView>>(PriceDetailType);
  4597. var data = new
  4598. {
  4599. Payment = _Payment,
  4600. Card = _Card,
  4601. PriceType = _PriceType,
  4602. PriceDetailType = _PriceDetailType
  4603. };
  4604. return Ok(JsonView(true, "", data));
  4605. }
  4606. /// <summary>
  4607. /// 超支费用
  4608. /// 导出团组超支费用Excel
  4609. /// </summary>
  4610. /// <param name="dto"></param>
  4611. /// <returns></returns>
  4612. [HttpPost]
  4613. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4614. public async Task<IActionResult> PostGroupExtraCost_OutputExcel(Fin_GroupExtraCostExcelDto dto)
  4615. {
  4616. string sqlGroup = string.Format(@" Select * From Grp_DelegationInfo WIth(Nolock) where Id = {0} ", dto.diId);
  4617. Grp_DelegationInfo grp_DelegationInfo = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sqlGroup).FirstAsync();
  4618. if (grp_DelegationInfo == null)
  4619. {
  4620. return Ok(JsonView(false, "导出失败,未查询到团组"));
  4621. }
  4622. Workbook workbook = new Workbook();
  4623. Worksheet sheet = workbook.Worksheets[0];
  4624. Cells cells = sheet.Cells;
  4625. //sheet.Protect(Aspose.Cells.ProtectionType.All, "123123", "");//保护工作表
  4626. //sheet.Protection.IsSelectingLockedCellsAllowed = true;//设置只能选择解锁单元格
  4627. //sheet.Protection.IsFormattingColumnsAllowed = true;//设置可以调整列
  4628. //sheet.Protection.IsFormattingRowsAllowed = true;//设置可以调整行
  4629. #region 数据源
  4630. string sqlData = string.Format(@" Select f.PriceType,REPLACE(s2.[Name],'超支费用','') as PriceTypeStr,'('+REPLACE(s3.[Name],'n','')+')' as PriceDetailTypeStr, PriceDt,PriceName,
  4631. Price,PriceCount,s.[Name] as Currency,PriceSum,f.Remark
  4632. From Fin_GroupExtraCost as f With(Nolock)
  4633. Inner Join Grp_CreditCardPayment as c With(Nolock) On f.Id = c.CId
  4634. Inner Join Sys_SetData as s With(Nolock) On f.PriceCurrency = s.Id
  4635. Inner Join Sys_SetData as s2 With(Nolock) On f.PriceType = s2.Id
  4636. Inner Join Sys_SetData as s3 With(Nolock) On f.PriceDetailType = s3.Id
  4637. Where f.DiId = {0} And f.IsDel=0 And c.CTable=1015
  4638. Order by PriceType ASC,PriceDt ASC ", dto.diId);
  4639. string sqlDataCount = string.Format(@" Select f.PriceType,COUNT(f.PriceType) as DataCount
  4640. From Fin_GroupExtraCost as f With(Nolock)
  4641. Inner Join Grp_CreditCardPayment as c With(Nolock) On f.Id = c.CId
  4642. Where f.DiId = {0} And f.IsDel=0 And c.CTable=1015
  4643. Group by PriceType ", dto.diId);
  4644. List<Fin_GroupExtraCost_ExcelView> dataList = await _sqlSugar.SqlQueryable<Fin_GroupExtraCost_ExcelView>(sqlData).ToListAsync();
  4645. List<Fin_GroupExtraCost_ExcelCountView> countList = await _sqlSugar.SqlQueryable<Fin_GroupExtraCost_ExcelCountView>(sqlDataCount).ToListAsync();
  4646. if (dataList.Count < 1 || countList.Count < 1)
  4647. {
  4648. return Ok(JsonView(false, "导出失败,未查询到数据"));
  4649. }
  4650. #endregion
  4651. #region 标题
  4652. string cellValue_Header = grp_DelegationInfo.TeamName;
  4653. //Aspose.Cells.Style style1 = workbook.Styles[workbook.Styles.Add()];//新增样式
  4654. Aspose.Cells.Style style_Header = workbook.CreateStyle();
  4655. style_Header.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  4656. style_Header.VerticalAlignment = TextAlignmentType.Center;
  4657. style_Header.Font.Name = "微软雅黑";//文字字体
  4658. style_Header.Font.Size = 18;//文字大小
  4659. style_Header.IsLocked = false;//单元格解锁
  4660. style_Header.Font.IsBold = false;//粗体
  4661. style_Header.Font.Color = Color.FromArgb(255, 0, 0);
  4662. //style1.ForegroundColor = Color.FromArgb(0x99, 0xcc, 0xff);//设置背景色
  4663. //style1.Pattern = BackgroundType.Solid; //设置背景样式
  4664. //style1.IsTextWrapped = true;//单元格内容自动换行
  4665. style_Header.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
  4666. style_Header.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
  4667. style_Header.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
  4668. style_Header.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
  4669. cells.Merge(1, 1, 1, 10);
  4670. Aspose.Cells.Range range_header = cells.CreateRange(1, 1, 1, 10);
  4671. range_header.PutValue(cellValue_Header, false, false);
  4672. range_header.SetStyle(style_Header);
  4673. cells.SetRowHeight(1, 35);
  4674. #endregion
  4675. #region 列名
  4676. Aspose.Cells.Style style_colName = workbook.CreateStyle();
  4677. style_colName.Name = "colName";
  4678. style_colName.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  4679. style_colName.VerticalAlignment = TextAlignmentType.Center;
  4680. style_colName.Font.Name = "微软雅黑";//文字字体
  4681. style_colName.Font.Size = 12;//文字大小
  4682. style_colName.IsLocked = false;//单元格解锁
  4683. style_colName.Font.IsBold = true;//粗体
  4684. style_colName.Font.Color = Color.FromArgb(0, 0, 0);
  4685. style_colName.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
  4686. style_colName.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
  4687. style_colName.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
  4688. style_colName.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
  4689. List<Fin_GroupExtraCostExcelColumnSetting> colNameSettingList = new List<Fin_GroupExtraCostExcelColumnSetting>()
  4690. {
  4691. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 1, columnName="类型", columnWidth= 25},
  4692. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 2, columnName="时间", columnWidth= 16},
  4693. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 3, columnName="内容", columnWidth= 35},
  4694. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 4, columnName="单价", columnWidth= 12},
  4695. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 5, columnName="数量", columnWidth= 12},
  4696. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 6, columnName="货币", columnWidth= 12},
  4697. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 7, columnName="费用", columnWidth= 12},
  4698. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 8, columnName="汇率", columnWidth= 12},
  4699. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 9, columnName="人民币", columnWidth= 12},
  4700. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 10, columnName="备注信息", columnWidth= 24}
  4701. };
  4702. foreach (var col in colNameSettingList)
  4703. {
  4704. cells[2, col.columnIndex].PutValue(col.columnName);
  4705. cells[2, col.columnIndex].SetStyle(style_colName);
  4706. cells.SetColumnWidth(col.columnIndex, col.columnWidth);
  4707. }
  4708. cells.SetRowHeight(2, 25);
  4709. #endregion
  4710. #region 数据填充
  4711. Aspose.Cells.Style style_dataCol = workbook.GetNamedStyle("colName");
  4712. style_dataCol.Font.IsBold = false;
  4713. style_dataCol.Name = "dataCol";
  4714. Aspose.Cells.Style style_dataBlue = workbook.CreateStyle();
  4715. style_dataBlue.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  4716. style_dataBlue.VerticalAlignment = TextAlignmentType.Center;
  4717. style_dataBlue.Font.Name = "微软雅黑";//文字字体
  4718. style_dataBlue.Font.Size = 12;//文字大小
  4719. style_dataBlue.IsLocked = false;//单元格解锁
  4720. style_dataBlue.Font.IsBold = false;//粗体
  4721. style_dataBlue.ForegroundColor = Color.FromArgb(189, 215, 238);
  4722. style_dataBlue.Pattern = BackgroundType.Solid;
  4723. style_dataBlue.Font.Color = Color.FromArgb(0, 0, 0);
  4724. style_dataBlue.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
  4725. style_dataBlue.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
  4726. style_dataBlue.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
  4727. style_dataBlue.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
  4728. Aspose.Cells.Style style_dataYellow = workbook.CreateStyle();
  4729. style_dataYellow.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  4730. style_dataYellow.VerticalAlignment = TextAlignmentType.Center;
  4731. style_dataYellow.Font.Name = "微软雅黑";//文字字体
  4732. style_dataYellow.Font.Size = 12;//文字大小
  4733. style_dataYellow.IsLocked = false;//单元格解锁
  4734. style_dataYellow.Font.IsBold = false;//粗体
  4735. style_dataYellow.ForegroundColor = Color.FromArgb(255, 242, 204);
  4736. style_dataYellow.Pattern = BackgroundType.Solid;
  4737. style_dataYellow.Font.Color = Color.FromArgb(0, 0, 0);
  4738. style_dataYellow.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
  4739. style_dataYellow.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
  4740. style_dataYellow.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
  4741. style_dataYellow.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
  4742. int rowIndex = 4;
  4743. foreach (var d in dataList)
  4744. {
  4745. //内容
  4746. string typeStr = d.PriceDetailTypeStr + d.PriceName;
  4747. cells["B" + rowIndex.ToString()].PutValue(d.PriceTypeStr);
  4748. cells["C" + rowIndex.ToString()].PutValue(d.PriceDtStr);
  4749. cells["D" + rowIndex.ToString()].PutValue(typeStr);
  4750. cells["E" + rowIndex.ToString()].PutValue(d.Price.ToString("#0.00"));
  4751. cells["F" + rowIndex.ToString()].PutValue(d.PriceCount);
  4752. cells["G" + rowIndex.ToString()].PutValue(d.Currency);
  4753. cells["H" + rowIndex.ToString()].PutValue(d.PriceSum.ToString("#0.00"));
  4754. cells["K" + rowIndex.ToString()].PutValue(d.Remark);
  4755. //样式
  4756. cells["B" + rowIndex.ToString()].SetStyle(style_dataCol);
  4757. cells["C" + rowIndex.ToString()].SetStyle(style_dataCol);
  4758. cells["D" + rowIndex.ToString()].SetStyle(style_dataCol);
  4759. cells["E" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4760. cells["F" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4761. cells["G" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4762. cells["H" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4763. cells["I" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4764. cells["J" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4765. cells["K" + rowIndex.ToString()].SetStyle(style_dataYellow);
  4766. //公式
  4767. cells["H" + rowIndex.ToString()].Formula = string.Format(@"E{0}*F{0}", rowIndex);
  4768. cells["J" + rowIndex.ToString()].Formula = string.Format(@"H{0}*I{0}", rowIndex);
  4769. cells.SetRowHeight(rowIndex - 1, 25);
  4770. rowIndex++;
  4771. }
  4772. cells["B" + rowIndex.ToString()].SetStyle(style_dataCol);
  4773. cells["C" + rowIndex.ToString()].SetStyle(style_dataCol);
  4774. cells["D" + rowIndex.ToString()].SetStyle(style_dataCol);
  4775. cells["E" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4776. cells["F" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4777. cells["G" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4778. cells["H" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4779. cells["I" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4780. cells["J" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4781. cells["K" + rowIndex.ToString()].SetStyle(style_dataYellow);
  4782. rowIndex++;
  4783. cells["B" + rowIndex.ToString()].SetStyle(style_dataCol);
  4784. cells["C" + rowIndex.ToString()].SetStyle(style_dataCol);
  4785. cells["D" + rowIndex.ToString()].SetStyle(style_dataCol);
  4786. cells["E" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4787. cells["F" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4788. cells["G" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4789. cells["H" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4790. cells["I" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4791. cells["J" + rowIndex.ToString()].SetStyle(style_dataBlue);
  4792. cells["K" + rowIndex.ToString()].SetStyle(style_dataYellow);
  4793. rowIndex = 3;
  4794. int tempPriceType = 0;
  4795. foreach (var c in dataList)
  4796. {
  4797. if (tempPriceType == c.PriceType)
  4798. {
  4799. continue;
  4800. }
  4801. tempPriceType = c.PriceType;
  4802. int _rowCount = countList.First(s => s.PriceType == tempPriceType).DataCount;
  4803. cells.Merge(rowIndex, 1, _rowCount, 1);
  4804. Aspose.Cells.Range tempRange = cells.CreateRange(rowIndex, 1, _rowCount, 1);
  4805. rowIndex += _rowCount;
  4806. }
  4807. rowIndex = 4 + dataList.Count;
  4808. cells["D" + rowIndex.ToString()].PutValue("合计");
  4809. cells["J" + rowIndex.ToString()].Formula = string.Format(@"SUM(J4,J{0})", rowIndex - 1);
  4810. cells.SetRowHeight(rowIndex - 1, 25);
  4811. rowIndex++;
  4812. cells["D" + rowIndex.ToString()].PutValue("服务费10%开票税金8%");
  4813. cells["J" + rowIndex.ToString()].Formula = string.Format(@"J{0}*1.1*1.08", rowIndex - 1);
  4814. cells.SetRowHeight(rowIndex - 1, 25);
  4815. #endregion
  4816. #region IO
  4817. System.IO.MemoryStream ms = workbook.SaveToStream();//生成数据流
  4818. string fileName = ("GroupExtraCost/超支费用(" + cellValue_Header + ").xlsx");
  4819. byte[] bt = ms.ToArray();
  4820. workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  4821. #endregion
  4822. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  4823. return Ok(JsonView(true, "成功", new { url = rst }));
  4824. }
  4825. /// <summary>
  4826. /// 超支费用Excel导出
  4827. /// </summary>
  4828. /// <param name="dto"></param>
  4829. /// <returns></returns>
  4830. [HttpPost]
  4831. public IActionResult ExportOverspendExcel(Fin_GroupExtraCostExcelDto dto)
  4832. {
  4833. var jw = JsonView(false);
  4834. var grp_DelegationInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().First(x => x.Id == dto.diId && x.IsDel == 0);
  4835. if (grp_DelegationInfo == null)
  4836. {
  4837. return Ok(JsonView(false, "团组信息有误!"));
  4838. }
  4839. Dictionary<int, int> dicSoure = new Dictionary<int, int>()
  4840. {
  4841. {1077,1074 },
  4842. {1078,1075 },
  4843. {1079,1076 }
  4844. };
  4845. Dictionary<int, int> mealsDic = new Dictionary<int, int>()
  4846. {
  4847. {988,1074},
  4848. {93,1075},
  4849. {989,1076},
  4850. };
  4851. var checkBoxDataArr = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 17).ToList();
  4852. var CurrDataArr = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 66).ToList();
  4853. var joinTable = _sqlSugar.Queryable<Fin_GroupExtraCost, Grp_CreditCardPayment, Sys_SetData, Grp_NationalTravelFee,
  4854. Fin_LocalGuideRelevancyOverspend, Grp_CarTouristGuideGroundReservations, Sys_SetData, Grp_DelegationInfo>(
  4855. (f, c, s, g, r, l, s1, i) => new JoinQueryInfos(
  4856. JoinType.Left, f.Id == c.CId && c.CTable == 1015 && c.IsDel == 0,
  4857. JoinType.Left, c.PaymentCurrency == s.Id && s.IsDel == 0,
  4858. JoinType.Left, g.IsDel == 0 && g.Id == f.Area,
  4859. JoinType.Left, f.Id == r.OverspendId && r.IsDel == 0,
  4860. JoinType.Left, l.Id == r.LocalGuideId && l.IsDel == 0,
  4861. JoinType.Left, s1.Id == l.toCurr && s1.IsDel == 0,
  4862. JoinType.Left, i.Id == l.DiId && i.IsDel == 0
  4863. ))
  4864. .Where((f, c, s, g) => f.IsDel == 0 && f.DiId == dto.diId)
  4865. .Select((f, c, s, g, r, l, s1, i) => new
  4866. {
  4867. c.PaymentCurrency,
  4868. c.DayRate,
  4869. PaymentCurrencyStr = s.Name,
  4870. f.PriceName,
  4871. f.Remark,
  4872. f.PriceCount,
  4873. Price = f.Price * f.Coefficient,
  4874. c.PayMoney,
  4875. RMBPrice = c.RMBPrice * f.Coefficient,
  4876. Offer = c.RMBPrice * f.PriceCount * f.Coefficient,
  4877. c.CTable,
  4878. f.PriceDetailType,
  4879. Area = g.Country ?? "未选择地区!",
  4880. l.toCurr,
  4881. l.Rate,
  4882. toCurrStr = s1.Name,
  4883. g.FoodCost,
  4884. CarParentId = l.Id,
  4885. f.PriceDt,
  4886. i.VisitPNumber,
  4887. f.DiId,
  4888. f.PriceCurrency,
  4889. f.SupervisorConfirm,
  4890. f.ManagerConfirm,
  4891. f.SYsupervisorConfirm,
  4892. })
  4893. .ToList()
  4894. .Where(x =>
  4895. {
  4896. var count = 0;
  4897. var stringArr = new string[] { "SYsupervisorConfirm", "SupervisorConfirm", "ManagerConfirm" };
  4898. var max = 0;
  4899. foreach (var item in stringArr)
  4900. {
  4901. var number = x.GetType()?.GetProperty(item)?.GetValue(x).ObjToInt();
  4902. if (number > 0)
  4903. {
  4904. count++;
  4905. }
  4906. }
  4907. if (x.PriceDetailType == 1044)
  4908. {
  4909. max = 0;
  4910. }
  4911. return count > max;
  4912. })
  4913. .Select(x =>
  4914. {
  4915. var costPirce = x.Price;
  4916. decimal costRMBPrice = x.RMBPrice;
  4917. decimal costDayRate = x.DayRate;
  4918. string remake = x.Remark;
  4919. if (x.VisitPNumber > 0 && x.PriceDetailType != 1088)
  4920. {
  4921. decimal cost = x.FoodCost;
  4922. //decimal.TryParse(x.FoodCost, out decimal cost);
  4923. cost /= 2;
  4924. decimal oldPrice = costPirce;
  4925. costPirce *= x.Rate; //转换币种
  4926. if (x.toCurr != x.PaymentCurrency)
  4927. {
  4928. var rate = _setDataRep.PostCurrencyByDiid(x.DiId, 1015, x.toCurr).Result;
  4929. if (rate.Code == 0)
  4930. {
  4931. var rateData = rate.Data as CurrencyInfo;
  4932. if (rateData != null)
  4933. {
  4934. costDayRate = rateData.Rate;
  4935. }
  4936. }
  4937. }
  4938. if (dicSoure.ContainsKey(x.PriceDetailType))
  4939. {
  4940. var carCenterList = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(x1 => x1.CTGGRId == x.CarParentId && x1.IsDel == 0
  4941. && x1.SId == mealsDic.First(x2 => x2.Value == dicSoure[x.PriceDetailType]).Key).ToList();
  4942. var CarCenter = carCenterList.FirstOrDefault(x1 => (DateTime.Compare(x1.DatePrice.ObjToDate(), x.PriceDt) == 0)) ?? new
  4943. Grp_CarTouristGuideGroundReservationsContent();
  4944. costPirce += (CarCenter.Price * CarCenter.Count * x.Rate);
  4945. oldPrice += (CarCenter.Price * CarCenter.Count);
  4946. var costResultPirce = costPirce - x.VisitPNumber * cost;
  4947. costResultPirce = Convert.ToInt32(Math.Round(costResultPirce));
  4948. var findCheck = checkBoxDataArr.Find(s => s.Id == CarCenter.SId);
  4949. if (x.toCurr != x.PaymentCurrency)
  4950. {
  4951. remake += $" {x.PriceDt:M/d} {findCheck?.Name} {x.PaymentCurrencyStr} {(int)Math.Round(oldPrice)}( 折算{x.toCurrStr} {(int)Math.Round(costPirce)}) - 财政{cost} * {x.VisitPNumber} = {x.toCurrStr}{costResultPirce}";
  4952. }
  4953. else
  4954. {
  4955. remake += $" {x.PriceDt:M/d} {findCheck?.Name}{x.PaymentCurrencyStr} {(int)Math.Round(costPirce)} - 财政{cost} * {x.VisitPNumber} = {x.PaymentCurrencyStr}{costResultPirce}";
  4956. }
  4957. costPirce = costResultPirce;
  4958. }
  4959. else
  4960. {
  4961. costPirce = Convert.ToInt32(Math.Round(costPirce));
  4962. }
  4963. costRMBPrice = Convert.ToInt32(Math.Round(costPirce * costDayRate));
  4964. }
  4965. if (remake.Contains("[TuT]"))
  4966. {
  4967. remake = remake.Replace("[TuT]", "");
  4968. }
  4969. return new
  4970. {
  4971. x.PaymentCurrency,
  4972. DayRate = costDayRate,
  4973. x.PaymentCurrencyStr,
  4974. x.PriceName,
  4975. Remark = remake,
  4976. x.PriceCount,
  4977. Price = costPirce,
  4978. x.PayMoney,
  4979. RMBPrice = costRMBPrice,
  4980. Offer = costRMBPrice * x.PriceCount,
  4981. x.CTable,
  4982. x.PriceDetailType,
  4983. x.Area,
  4984. x.toCurr,
  4985. x.toCurrStr,
  4986. ItemPrice = costPirce * x.PriceCount,
  4987. };
  4988. })
  4989. .ToList();
  4990. var PriceDetailTypeArr = new int[] { 1088, 1074, 1075, 1076 };
  4991. var whereArr = joinTable.Where(x => PriceDetailTypeArr.Contains(x.PriceDetailType)).ToList();
  4992. _ = joinTable.RemoveAll(x => PriceDetailTypeArr.Contains(x.PriceDetailType));
  4993. foreach (var item in whereArr)
  4994. {
  4995. joinTable.Insert(0, item);
  4996. }
  4997. var dicClounm = new Dictionary<int, string>()
  4998. {
  4999. { 0,"Area" },
  5000. { 1,"PriceName" },
  5001. { 2,"Remark" },
  5002. { 3,"PriceCount" },
  5003. { 4,"Price" },
  5004. { 5,"ItemPrice" },
  5005. { 6,"DayRate" },
  5006. { 7,"Offer" },
  5007. };
  5008. var rowStartIndex = 2;
  5009. string filePath = AppSettingsHelper.Get("ExcelBasePath") + "\\Template\\超支费用表.xlsx";
  5010. IWorkbook workbook = new XSSFWorkbook(new FileStream(filePath, FileMode.Open, FileAccess.Read));
  5011. ISheet sheet = workbook.GetSheetAt(0);
  5012. var initStyleRow = sheet.GetRow(2);
  5013. var clounmCount = dicClounm.Count;
  5014. Action cloneRowFn = () =>
  5015. {
  5016. rowStartIndex++;
  5017. var cloneRow = sheet.CreateRow(rowStartIndex);
  5018. // 复制样式
  5019. for (int i = initStyleRow.FirstCellNum; i < initStyleRow.LastCellNum; i++)
  5020. {
  5021. ICell sourceCell = initStyleRow.GetCell(i);
  5022. ICell targetCell = cloneRow.GetCell(i) ?? cloneRow.CreateCell(i);
  5023. // 确保单元格存在样式
  5024. if (sourceCell.CellStyle != null)
  5025. {
  5026. targetCell.CellStyle = sourceCell.CellStyle;
  5027. }
  5028. }
  5029. };
  5030. sheet.GetRow(0).GetCell(0).SetCellValue($"{grp_DelegationInfo.TeamName}—超支费用");
  5031. foreach (var item in joinTable)
  5032. {
  5033. for (int i = 0; i < clounmCount; i++)
  5034. {
  5035. string property = dicClounm[i];
  5036. string value = item.GetType()!.GetProperty(property)!.GetValue(item)?.ToString() ?? "";
  5037. sheet.GetRow(rowStartIndex).GetCell(i).SetCellValue(value);
  5038. }
  5039. cloneRowFn();
  5040. }
  5041. sheet.GetRow(rowStartIndex).GetCell(2).SetCellValue($"小计:");
  5042. sheet.GetRow(rowStartIndex).GetCell(3).SetCellValue($"{joinTable.Sum(x => x.RMBPrice)}元");
  5043. var path = $"GroupExtraCost/{grp_DelegationInfo.TeamName}_超支费用.xlsx";
  5044. using (var stream = new MemoryStream())
  5045. {
  5046. workbook.Write(stream, true);
  5047. stream.Flush();
  5048. stream.Seek(0, SeekOrigin.Begin);
  5049. var pathinfo = AppSettingsHelper.Get("ExcelBasePath") + path;
  5050. if (System.IO.File.Exists(pathinfo))
  5051. {
  5052. System.IO.File.Delete(pathinfo);
  5053. }
  5054. stream.SaveToFile(AppSettingsHelper.Get("ExcelBasePath") + path);
  5055. }
  5056. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + path;
  5057. jw = JsonView(true, "成功", new { url = rst });
  5058. return Ok(jw);
  5059. }
  5060. /// <summary>
  5061. /// 获取超支系数配置
  5062. /// </summary>
  5063. /// <returns></returns>
  5064. [HttpPost]
  5065. public IActionResult QueryCoefficientConfig()
  5066. {
  5067. var arr = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.STid == 80 && x.IsDel == 0).ToList();
  5068. var carCoefficient = new int[] { 1050 }; //2.4
  5069. var menpiaoCoefficient = new int[] { 1086 }; // 1.2
  5070. var airCoefficient = new int[] { 1035, 1036 }; // 2.0
  5071. var HotelCoefficient = new int[] { 1044, 1045, 1046, 1041, 1042, 1043, 1038 }; // 1.5
  5072. var fanyiCoefficient = new int[] { 1087 }; // 1.5
  5073. var resultArr = new
  5074. ArrayList();
  5075. foreach (var item in arr)
  5076. {
  5077. var a = new { coefficient = 1M, id = 0 };
  5078. if (carCoefficient.Contains(item.Id))
  5079. {
  5080. a = a with
  5081. {
  5082. coefficient = 2.4M,
  5083. id = item.Id
  5084. };
  5085. }
  5086. else if (menpiaoCoefficient.Contains(item.Id))
  5087. {
  5088. a = a with
  5089. {
  5090. coefficient = 1.2M,
  5091. id = item.Id
  5092. };
  5093. }
  5094. else if (airCoefficient.Contains(item.Id))
  5095. {
  5096. a = a with
  5097. {
  5098. coefficient = 2.0M,
  5099. id = item.Id
  5100. };
  5101. }
  5102. else if (HotelCoefficient.Contains(item.Id))
  5103. {
  5104. a = a with
  5105. {
  5106. coefficient = 1.5M,
  5107. id = item.Id
  5108. };
  5109. }
  5110. else if (fanyiCoefficient.Contains(item.Id))
  5111. {
  5112. a = a with
  5113. {
  5114. coefficient = 1.5M,
  5115. id = item.Id
  5116. };
  5117. }
  5118. else
  5119. {
  5120. a = a with
  5121. {
  5122. coefficient = 1M,
  5123. id = item.Id
  5124. };
  5125. }
  5126. resultArr.Add(a);
  5127. }
  5128. return Ok(JsonView(true, "获取成功!", resultArr));
  5129. }
  5130. /// <summary>
  5131. /// 退费确认
  5132. /// </summary>
  5133. /// <returns></returns>
  5134. [HttpPost]
  5135. public IActionResult ReturnPremiumConfirm(ReturnPremiumConfirmDto dto)
  5136. {
  5137. var jw = JsonView(false);
  5138. var confirmStatusArr = new Dictionary<int, string>()
  5139. {
  5140. {1 ,"ManagerConfirm" },
  5141. {2 ,"SupervisorConfirm" },
  5142. {3 ,"SYsupervisorConfirm" },
  5143. };
  5144. if (dto.DataId < 1 || confirmStatusArr.Keys.Contains(dto.ConfirmId) == false)
  5145. {
  5146. jw.Msg = "参数有误!";
  5147. return Ok(jw);
  5148. }
  5149. Fin_GroupExtraCost fge = _sqlSugar.Queryable<Fin_GroupExtraCost>().First(it => it.Id == dto.DataId && it.IsDel == 0);
  5150. try
  5151. {
  5152. if (fge == null)
  5153. throw new Exception("数据不存在!");
  5154. fge.GetType().GetProperty(confirmStatusArr[dto.ConfirmId]).SetValue(fge, dto.status);
  5155. var isSaveCollectionStatement = true;
  5156. //确认后,同步修改收款账单
  5157. foreach (var item in confirmStatusArr.Keys)
  5158. {
  5159. var value = fge.GetType().GetProperty(confirmStatusArr[item]).GetValue(fge).ObjToInt();
  5160. //if (value == 0)
  5161. //{
  5162. // isSaveCollectionStatement = false;
  5163. // break;
  5164. //}
  5165. }
  5166. _sqlSugar.BeginTran();
  5167. _sqlSugar.Updateable<Fin_GroupExtraCost>(fge).ExecuteCommand();
  5168. if (isSaveCollectionStatement)
  5169. {
  5170. //同步修改收款账单
  5171. _foreignReceivablesRepository.OverSpSeteceivables(new OverSpSeteceivablesDto
  5172. {
  5173. CreateUserId = fge.CreateUserId,
  5174. DiId = fge.DiId,
  5175. });
  5176. }
  5177. }
  5178. catch (Exception ex)
  5179. {
  5180. _sqlSugar.RollbackTran();
  5181. jw.Msg = "Error! " + ex.Message;
  5182. return Ok(jw);
  5183. }
  5184. _sqlSugar.CommitTran();
  5185. jw = JsonView(true, "操作成功!");
  5186. return Ok(jw);
  5187. }
  5188. #endregion
  5189. #region 信用卡对账
  5190. /// <summary>
  5191. ///将指定的Excel的文件转换成DataTable(Excel的第一个sheet)
  5192. /// </summary>
  5193. /// <param name="fullFielPath">文件的绝对路径</param>
  5194. /// <param name="sheetName"></param>
  5195. /// <returns></returns>
  5196. private DataTable WorksheetToTable(string fullFielPath, string? sheetName = null)
  5197. {
  5198. //如果是“EPPlus”,需要指定LicenseContext。
  5199. //EPPlus.Core 不需要指定。
  5200. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  5201. var existingFile = new FileInfo(fullFielPath);
  5202. var package = new ExcelPackage(existingFile);
  5203. ExcelWorksheet worksheet;
  5204. if (string.IsNullOrEmpty(sheetName))
  5205. {
  5206. //不传入 sheetName 默认取第1个sheet。
  5207. //EPPlus 索引是0
  5208. //EPPlus.Core 索引是1
  5209. worksheet = package.Workbook.Worksheets[0];
  5210. }
  5211. else
  5212. {
  5213. worksheet = package.Workbook.Worksheets[sheetName];
  5214. }
  5215. if (worksheet == null)
  5216. throw new Exception("指定的sheetName不存在");
  5217. return WorksheetToTable(worksheet);
  5218. }
  5219. /// <summary>
  5220. /// 将worksheet转成datatable
  5221. /// </summary>
  5222. /// <param name="worksheet">待处理的worksheet</param>
  5223. /// <returns>返回处理后的datatable</returns>
  5224. private DataTable WorksheetToTable(ExcelWorksheet worksheet)
  5225. {
  5226. //获取worksheet的行数
  5227. int rows = worksheet.Dimension.End.Row;
  5228. //获取worksheet的列数
  5229. int cols = worksheet.Dimension.End.Column;
  5230. var dt = new DataTable(worksheet.Name);
  5231. DataRow dr = null;
  5232. for (int i = 1; i <= rows; i++)
  5233. {
  5234. if (i > 1)
  5235. dr = dt.Rows.Add();
  5236. for (int j = 1; j <= cols; j++)
  5237. {
  5238. //默认将第一行设置为datatable的标题
  5239. if (i == 1)
  5240. dt.Columns.Add(GetString(worksheet.Cells[i, j].Value));
  5241. //剩下的写入datatable
  5242. else
  5243. {
  5244. var cell = worksheet.Cells[i, j];
  5245. if (j == 1 || j == 2)
  5246. {
  5247. if (cell.Value is double)
  5248. {
  5249. dr[j - 1] = EPPlusConvertToDateTime((double)cell.Value).ToString("MM/dd");
  5250. }
  5251. }
  5252. else
  5253. {
  5254. dr[j - 1] = GetString(cell.Value);
  5255. }
  5256. }
  5257. }
  5258. }
  5259. return dt;
  5260. }
  5261. private string GetString(object obj)
  5262. {
  5263. if (obj == null)
  5264. return "";
  5265. return obj.ToString();
  5266. }
  5267. public static DateTime EPPlusConvertToDateTime(double numericDate)
  5268. {
  5269. // Excel起始日期
  5270. var startDate = new DateTime(1899, 12, 30);
  5271. // 将数字日期转换为时间间隔,并加上起始日期
  5272. var duration = new TimeSpan((long)(numericDate * TimeSpan.TicksPerDay));
  5273. return startDate.Add(duration);
  5274. }
  5275. private DataTable ExcelFileToDataTable(IFormFile file)
  5276. {
  5277. DataTable dtTest = null;
  5278. using (var stream = new MemoryStream())
  5279. {
  5280. file.CopyTo(stream);
  5281. using (var package = new ExcelPackage(stream))
  5282. {
  5283. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  5284. ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
  5285. dtTest = WorksheetToTable(worksheet);
  5286. }
  5287. }
  5288. return dtTest;
  5289. }
  5290. /// <summary>
  5291. /// 信用卡对账--基础数据
  5292. /// </summary>
  5293. /// <returns></returns>
  5294. [HttpPost]
  5295. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5296. public async Task<IActionResult> PostCreditCardBillInit()
  5297. {
  5298. var data = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 15).Select(x => new { x.Id, x.Name }).ToListAsync();
  5299. return Ok(JsonView(true, "操作成功!", data));
  5300. }
  5301. /// <summary>
  5302. /// 信用卡对账
  5303. /// </summary>
  5304. /// <param name="file"></param>
  5305. /// <param name="cardType"></param>
  5306. /// <param name="beginDt"></param>
  5307. /// <param name="endDt"></param>
  5308. /// <returns></returns>
  5309. [HttpPost]
  5310. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5311. public async Task<IActionResult> PostCreditCardBill(IFormFile file, int cardType, string beginDt, string endDt)
  5312. {
  5313. if (file == null || file.Length < 1)
  5314. {
  5315. return Ok(JsonView(false, "请上传文件!"));
  5316. }
  5317. string fileName = file.FileName;
  5318. if (!fileName.EndsWith(".xlsx") && !fileName.EndsWith(".xls"))
  5319. {
  5320. return Ok(JsonView(false, "请上传Excel文件!"));
  5321. }
  5322. if (cardType < 1) return Ok(JsonView(false, "请传入有效的卡类型!"));
  5323. if (string.IsNullOrEmpty(beginDt) || string.IsNullOrEmpty(endDt)) return Ok(JsonView(false, "请输入开始/结束日期!"));
  5324. var beginValid = DateTime.TryParse(beginDt, out DateTime _beginDt);
  5325. var endValid = DateTime.TryParse(endDt, out DateTime _endDt);
  5326. if (!beginValid || !endValid) return Ok(JsonView(false, "请输入正确的日期格式"));
  5327. //读取ExcelFile
  5328. DataTable dt = ExcelFileToDataTable(file);
  5329. if (dt == null)
  5330. {
  5331. return Ok(JsonView(false, $"您上传的Excel工作表没有内容,请检查!!!"));
  5332. }
  5333. dt.TableName = "TB";
  5334. //信用卡信息
  5335. string sql = string.Format($"Select * From Grp_CreditCardPayment Where Isdel = 0 And CTDId = {cardType} And ConsumptionDate between '{beginDt}' and '{endDt}' ");
  5336. var List_ccp = await _sqlSugar.SqlQueryable<Grp_CreditCardPayment>(sql).ToListAsync();
  5337. if (List_ccp.Count < 1)
  5338. {
  5339. return Ok(JsonView(false, $"未查询到 {beginDt} 至 {endDt} 信用卡账单信息!!!!"));
  5340. }
  5341. //酒店刷卡信息
  5342. var hotelData = await _sqlSugar.Queryable<Grp_HotelReservations>()
  5343. .LeftJoin<Grp_HotelReservationsContent>((hr, hrc) => hr.Id == hrc.HrId)
  5344. .Where((hr, hrc) => hr.IsDel == 0 && hrc.Price > 0 && hrc.IsPay == 1)
  5345. .Select((hr, hrc) => new
  5346. {
  5347. hrc.DiId,
  5348. hrc.HrId,
  5349. hrc.Id,
  5350. hrc.PriceType,
  5351. hrc.Price,
  5352. hrc.Currency,
  5353. hrc.Rate,
  5354. hrc.IsOppay,
  5355. hrc.PayDId,
  5356. hrc.ConsumptionPatterns,
  5357. hrc.ConsumptionDate,
  5358. ConsumptionDt = string.IsNullOrEmpty(hrc.ConsumptionDate) ? new DateTime(1990, 12, 30) : Convert.ToDateTime(hrc.ConsumptionDate),
  5359. hrc.CTDId,
  5360. hrc.BankNo,
  5361. hrc.CardholderName,
  5362. hrc.CompanyBankNo,
  5363. hrc.OtherBankName,
  5364. hrc.OtherSideNo,
  5365. hrc.IsPay,
  5366. hrc.Payee,
  5367. hrc.OrbitalPrivateTransfer
  5368. })
  5369. .ToListAsync();
  5370. if (hotelData.Count > 0)
  5371. {
  5372. hotelData = hotelData.Where(x => x.ConsumptionDt >= _beginDt && x.ConsumptionDt <= _endDt).ToList();
  5373. }
  5374. //资源信息
  5375. var delegationInfos = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).ToList();
  5376. var users = _sqlSugar.Queryable<Sys_Users>().Where(it => it.IsDel == 0).ToList();
  5377. string url = string.Empty;
  5378. try
  5379. {
  5380. /*
  5381. * 卡类型
  5382. * 74 美元卡 1
  5383. * 75 欧元卡 1
  5384. * 86 招行卡 1
  5385. * 346 中信卡 1
  5386. * 363 交行卡 1
  5387. *
  5388. */
  5389. var ids = new List<int>();
  5390. if (cardType == 74) //美元卡
  5391. {
  5392. var AirGroupReuslt = List_ccp.Where(x => x.CTable == 85).GroupBy(x => x.DIId).ToList();
  5393. if (AirGroupReuslt != null && AirGroupReuslt.Count > 0)
  5394. {
  5395. foreach (var item in AirGroupReuslt)
  5396. {
  5397. if (item.Count() > 1)
  5398. {
  5399. var obj = item.FirstOrDefault();
  5400. obj.RMBPrice = item.Sum(x => x.PayMoney);//合计币种金额
  5401. obj.Remark = "团组机票总价(虚拟)";
  5402. List_ccp.Add(obj);
  5403. }
  5404. }
  5405. }
  5406. //dt.AcceptChanges(); //提交
  5407. //修改table列名
  5408. dt.Columns[0].ColumnName = "accountType"; // 账户类型
  5409. dt.Columns[1].ColumnName = "tradeDate"; //交易日期
  5410. dt.Columns[2].ColumnName = "BillingDate"; // 记账日期
  5411. dt.Columns[3].ColumnName = "CardNo"; // 卡号
  5412. dt.Columns[4].ColumnName = "deposit"; // 存入金额
  5413. dt.Columns[5].ColumnName = "SpendingAmount"; // 支出金额
  5414. dt.Columns[6].ColumnName = "TransactionDescription"; // 交易描述
  5415. dt.Columns[7].ColumnName = "TeamRemark"; // 团组备注描述
  5416. dt.Columns[8].ColumnName = "Handlers"; // 经手人
  5417. dt.Columns[9].ColumnName = "State"; // 状态
  5418. //删除第一行数据
  5419. if (dt.Rows.Count > 0)
  5420. {
  5421. string accountType = dt.Rows[0]["accountType"].ToString();
  5422. if (dt.Rows[0]["accountType"].ToString().Equals("账户类型"))
  5423. {
  5424. dt.Rows[0].Delete();
  5425. dt.AcceptChanges(); //提交
  5426. }
  5427. }
  5428. foreach (DataRow item in dt.Rows)
  5429. {
  5430. #region 匹配的金额
  5431. decimal ExcelAmount = 0.00M;
  5432. decimal deposit = 0.00M;
  5433. if (!string.IsNullOrEmpty(item["SpendingAmount"].ToString()))
  5434. {
  5435. var isParase = decimal.TryParse(item["SpendingAmount"].ToString(), out ExcelAmount);
  5436. if (isParase)
  5437. {
  5438. var CList = List_ccp.FindAll(x => x.PayMoney == ExcelAmount);
  5439. if (CList != null && CList.Count > 0)
  5440. {
  5441. item["TeamRemark"] = delegationInfos.Find(it => it.Id == CList.First().DIId)?.TeamName;
  5442. item["Handlers"] = users.Find(it => it.Id == CList.First().CreateUserId)?.CnName;
  5443. item["State"] = 1;
  5444. }
  5445. }
  5446. }
  5447. if (!string.IsNullOrEmpty(item["deposit"].ToString()))
  5448. {
  5449. var isParse = decimal.TryParse(item["deposit"].ToString(), out deposit);
  5450. if (isParse)
  5451. {
  5452. var CList = List_ccp.FindAll(x => x.PayMoney == deposit);
  5453. if (CList != null && CList.Count > 0)
  5454. {
  5455. item["TeamRemark"] = delegationInfos.Find(it => it.Id == CList.First().DIId)?.TeamName;
  5456. item["Handlers"] = users.Find(it => it.Id == CList.First().CreateUserId)?.CnName;
  5457. item["State"] = 1;
  5458. }
  5459. }
  5460. }
  5461. #endregion
  5462. //交易描述
  5463. if (!string.IsNullOrEmpty(item["TransactionDescription"].ToString()))
  5464. {
  5465. string TransactionDescription = item["TransactionDescription"].ToString();
  5466. var startIndex = TransactionDescription.LastIndexOf("[");
  5467. var endIndex = TransactionDescription.LastIndexOf("]");
  5468. if (startIndex != -1 && endIndex != -1)
  5469. {
  5470. var moenyList = TransactionDescription.Substring(startIndex + 1, endIndex - startIndex - 1).Split(' ').
  5471. Where(x => !string.IsNullOrEmpty(x)).ToList();
  5472. decimal money = 0.00M;
  5473. foreach (var itemMoeny in moenyList)
  5474. {
  5475. if (itemMoeny.Contains('.'))
  5476. {
  5477. string itemMoenyStr = itemMoeny.Replace(",", string.Empty);
  5478. bool istrue = decimal.TryParse(itemMoenyStr, out money);
  5479. if (istrue)
  5480. {
  5481. var CList = List_ccp.FindAll(x => x.PayMoney == money);
  5482. if (CList != null && CList.Count > 0)
  5483. {
  5484. item["TeamRemark"] = delegationInfos.Find(it => it.Id == CList.First().DIId)?.TeamName;
  5485. item["Handlers"] = users.Find(it => it.Id == CList.First().CreateUserId)?.CnName;
  5486. item["State"] = 1;
  5487. }
  5488. }
  5489. }
  5490. }
  5491. }
  5492. }
  5493. }
  5494. string fileName1 = $"信用卡账单(美元卡){DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  5495. var pairs = new Dictionary<string, object>();
  5496. var datas = new List<DataTable>
  5497. {
  5498. dt
  5499. };
  5500. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-美元卡.xls", $"CreditCardBill", fileName1, pairs, datas);
  5501. }
  5502. else if (cardType == 75) //欧元卡
  5503. {
  5504. if (dt.Rows.Count > 0)
  5505. {
  5506. string accountType = dt.Rows[0][0].ToString();
  5507. if (accountType.Equals("账户类型"))
  5508. {
  5509. dt.Rows[0].Delete();
  5510. dt.AcceptChanges(); //提交
  5511. }
  5512. }
  5513. //dt.Columns[0].ColumnName = "All";
  5514. var dt1 = new DataTable
  5515. {
  5516. TableName = "TB"
  5517. };
  5518. dt1.Columns.Add("TradingDate", Type.GetType("System.String"));//交易日期
  5519. dt1.Columns.Add("TallyDate", Type.GetType("System.String")); //记账日期
  5520. dt1.Columns.Add("TradindDesc", Type.GetType("System.String"));//交易描述
  5521. dt1.Columns.Add("TradindMoney", Type.GetType("System.String"));//交易币种/金额
  5522. dt1.Columns.Add("ClearindMoney", Type.GetType("System.String"));// 清算币种/金额
  5523. dt1.Columns.Add("TeamRemark", Type.GetType("System.String")); //团组备注描述
  5524. dt1.Columns.Add("Handlers", Type.GetType("System.String")); //经手人
  5525. dt1.Columns.Add("State", Type.GetType("System.String")); //状态
  5526. for (int i = 0; i < dt.Rows.Count; i++)
  5527. {
  5528. string[] str = dt.Rows[i]["All"].ToString().Split(' ');
  5529. //string[] str = dt.Rows[i];
  5530. var dr = dt1.NewRow();
  5531. dr["TradingDate"] = str[0].ToString();
  5532. dr["TallyDate"] = str[1].ToString();
  5533. dr["TradindDesc"] = str[2].ToString() + " " + str[3].ToString();
  5534. dr["TradindMoney"] = str[4].ToString() + " " + str[5].ToString();
  5535. dr["ClearindMoney"] = str[6].ToString() + " " + str[7].ToString();
  5536. dt1.Rows.Add(dr);
  5537. }
  5538. foreach (DataRow item in dt1.Rows)
  5539. {
  5540. for (int i = 0; i < List_ccp.Count; i++)
  5541. {
  5542. DateTime dtTime1 = Convert.ToDateTime(item["TradingDate"].ToString() == "" ? DateTime.Now.ToString("MM/dd") : item["TradingDate"].ToString()); //交易日期
  5543. string USDPrice = item["TradindMoney"].ToString(); //支出金额
  5544. USDPrice = USDPrice.Split(' ')[1].Trim(); //替换掉非数字
  5545. //USDPrice = USDPrice.Split('/')[1];
  5546. // 经手人 and excel行状态
  5547. if (!string.IsNullOrEmpty(List_ccp[i].ConsumptionDate) && !string.IsNullOrEmpty(USDPrice))
  5548. {
  5549. DateTime dtTime2 = Convert.ToDateTime(List_ccp[i].ConsumptionDate.ToString() == "" ? DateTime.Now.ToString("MM/dd") : List_ccp[i].ConsumptionDate.ToString());
  5550. float price1 = float.Parse(USDPrice);
  5551. float price2 = float.Parse(List_ccp[i].PayMoney.ToString("F2"));
  5552. if (dtTime1 == dtTime2 && price1 == price2)
  5553. {
  5554. item["TeamRemark"] = delegationInfos.Find(it => it.Id == List_ccp[i].DIId)?.TeamName;
  5555. item["Handlers"] = users.Find(it => it.Id == List_ccp[i].CreateUserId)?.CnName;
  5556. item["State"] = "1";
  5557. i = List_ccp.Count - 1;
  5558. }
  5559. else item["State"] = "0";
  5560. }
  5561. else item["State"] = "0";
  5562. }
  5563. if (item["TradindDesc"].ToString().Contains("财付通"))
  5564. item["State"] = "2";
  5565. else if (item["TradindDesc"].ToString().Contains("京东"))
  5566. item["State"] = "2";
  5567. else if (item["TradindDesc"].ToString().Contains("微信支付"))
  5568. item["State"] = "2";
  5569. else if (item["TradindDesc"].ToString().Contains("淘宝"))
  5570. item["State"] = "2";
  5571. }
  5572. string fileName1 = $"信用卡账单(欧元卡){DateTime.Now:yyyy.MM.dd}.xls";
  5573. var pairs = new Dictionary<string, object>();
  5574. var datas = new List<DataTable>
  5575. {
  5576. dt
  5577. };
  5578. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-欧元卡.xls", "TB", fileName1, pairs, datas);
  5579. }
  5580. else if (cardType == 86) //招行卡
  5581. {
  5582. var AirGroupReuslt1 = List_ccp.Where(x => x.CTable == 85).GroupBy(x => x.DIId).ToList();
  5583. if (AirGroupReuslt1 != null && AirGroupReuslt1.Count > 0)
  5584. {
  5585. foreach (var item in AirGroupReuslt1)
  5586. {
  5587. if (item.Count() > 1)
  5588. {
  5589. var di = delegationInfos.Find(it => it.Id == item.Key);
  5590. var obj = item.FirstOrDefault();
  5591. obj.Remark = "团组机票总价";
  5592. if (di != null)
  5593. {
  5594. obj.Remark = "团组机票总价(" + di.TeamName + ")";
  5595. }
  5596. obj.RMBPrice = item.Sum(x => x.RMBPrice);//合计人民币
  5597. List_ccp.Add(obj);
  5598. }
  5599. }
  5600. }
  5601. //查询所有刷卡的团组
  5602. //将刷卡团组内刷卡金额的金额存入ccp_list
  5603. //将excel作比较
  5604. //机票刷卡记录
  5605. var AirListAndPayID = List_ccp.Where(x => x.CTable == 85 && x.PayDId == 72).Select(x => x.DIId).Distinct().ToList();
  5606. var AirData = _sqlSugar.Queryable<Grp_AirTicketReservations>().Where(it => AirListAndPayID.Contains(it.DIId) && it.PrePrice != it.Price).ToList();
  5607. foreach (var item in AirData)
  5608. {
  5609. var DBwhere = List_ccp.Find(x => x.PayMoney == item.PrePrice);
  5610. if (DBwhere == null)
  5611. {
  5612. List_ccp.Add(new Grp_CreditCardPayment
  5613. {
  5614. PayMoney = item.PrePrice,
  5615. DIId = item.DIId,
  5616. CreateUserId = item.CreateUserId,
  5617. Remark = "(机票单价价格)",
  5618. });
  5619. }
  5620. }
  5621. //机票刷卡记录
  5622. var hotelGroupReuslt = hotelData.Where(x => x.CTDId == 86).GroupBy(x => x.DiId).ToList();
  5623. if (hotelGroupReuslt != null && hotelGroupReuslt.Count > 0)
  5624. {
  5625. foreach (var item in hotelGroupReuslt)
  5626. {
  5627. if (item.Count() > 0)
  5628. {
  5629. var hotelInfo = new Grp_CreditCardPayment()
  5630. {
  5631. Remark = $"团组酒店总价(" + delegationInfos.Find(it => it.Id == item.Key)?.TeamName ?? "" + ")",
  5632. RMBPrice = item.Sum(x => x.Price * x.Rate),
  5633. ConsumptionDate = item.FirstOrDefault()?.ConsumptionDate ?? ""
  5634. };
  5635. List_ccp.Add(hotelInfo);
  5636. }
  5637. }
  5638. }
  5639. #region
  5640. dt.Rows[0].Delete();//删除列名行
  5641. dt.AcceptChanges();
  5642. var dt1 = new DataTable
  5643. {
  5644. TableName = "TB"
  5645. };
  5646. dt1.Columns.Add("TradingDay", Type.GetType("System.String")); // 交易日
  5647. dt1.Columns.Add("TallyDay", Type.GetType("System.String")); // 记账日
  5648. dt1.Columns.Add("TransactionDesc", Type.GetType("System.String")); // 交易描述
  5649. dt1.Columns.Add("RMBMoney", Type.GetType("System.String")); // 人名币金额
  5650. dt1.Columns.Add("CardNo", Type.GetType("System.String")); // 卡号
  5651. dt1.Columns.Add("TradingMoney", Type.GetType("System.String")); // 交易地金额
  5652. dt1.Columns.Add("Currency", Type.GetType("System.String")); // 币种
  5653. dt1.Columns.Add("TeamRemark", Type.GetType("System.String")); //团组备注描述
  5654. dt1.Columns.Add("Handlers", Type.GetType("System.String")); //经手人
  5655. dt1.Columns.Add("State", Type.GetType("System.String")); //状态
  5656. for (int j = 0; j < dt.Rows.Count; j++)//遍历行
  5657. {
  5658. DataRow dr = dt1.NewRow(); //获取每一行的数据
  5659. var tradingDay = dt.Rows[j][0].ToString();
  5660. dr["TradingDay"] = tradingDay;
  5661. var tallyDay = dt.Rows[j][1].ToString();
  5662. dr["TallyDay"] = tallyDay;
  5663. dr["TransactionDesc"] = dt.Rows[j][2].ToString();
  5664. dr["RMBMoney"] = dt.Rows[j][3].ToString();
  5665. dr["CardNo"] = dt.Rows[j][4].ToString();
  5666. string currency = "CN";
  5667. string money = dt.Rows[j][5].ToString();
  5668. if (money.Contains('('))
  5669. {
  5670. string[] strs = money.Split('(');
  5671. money = strs[0];
  5672. currency = strs[1].Replace(")", "");
  5673. }
  5674. dr["TradingMoney"] = money;
  5675. dr["Currency"] = currency;
  5676. if (string.IsNullOrEmpty(money))
  5677. {
  5678. continue;
  5679. }
  5680. dt1.Rows.Add(dr);
  5681. }
  5682. //datatable 排序
  5683. dt1.DefaultView.Sort = "TradingDay asc";
  5684. dt1 = dt1.DefaultView.ToTable();
  5685. foreach (DataRow item in dt1.Rows)
  5686. {
  5687. if (item["TradingDay"].ToString() == "" && item["RMBMoney"].ToString() == "")
  5688. {
  5689. continue;
  5690. }
  5691. //excel获取交易日期
  5692. string ExcelDt = string.Empty;
  5693. //C表交易日期
  5694. string DBDt = string.Empty;
  5695. //excel交易的金额
  5696. decimal TradingMoney = decimal.Parse(item["TradingMoney"].ToString());
  5697. if (item["TradingDay"] != null)
  5698. {
  5699. ExcelDt = item["TradingDay"].ToString();
  5700. }
  5701. //加一获取金额区间
  5702. decimal MaxTradingMoney = TradingMoney + 1;
  5703. decimal MinTradingMoney = TradingMoney - 1;
  5704. //匹配C表金额相等的值
  5705. var CList = List_ccp.FindAll(x => x.PayMoney <= MaxTradingMoney && x.PayMoney >= MinTradingMoney);
  5706. if (CList != null && CList.Count > 0)
  5707. {
  5708. #region 日期匹配
  5709. foreach (var Citem in CList)
  5710. {
  5711. if (!string.IsNullOrWhiteSpace(Citem.ConsumptionDate))
  5712. {
  5713. DBDt = DateTime.Parse(Citem.ConsumptionDate).ToString("MM/dd");
  5714. if (DBDt.Equals(ExcelDt))
  5715. {
  5716. item["TeamRemark"] = delegationInfos.Find(it => it.Id == Citem.DIId)?.TeamName;
  5717. item["Handlers"] = users.Find(it => it.Id == Citem.CreateUserId)?.CnName;
  5718. ids.Add(Citem.Id);
  5719. }
  5720. }
  5721. }
  5722. #endregion
  5723. }
  5724. var whereRange = new List<string>() { "财付通", "京东", "微信", "淘宝", "支付宝", "拼多多" };
  5725. foreach (var where in whereRange)
  5726. {
  5727. if (item["TransactionDesc"].ToString().Contains(where)) item["State"] = "2";
  5728. else item["State"] = "0";
  5729. }
  5730. if (!string.IsNullOrEmpty(item["TeamRemark"].ToString()) && !string.IsNullOrEmpty(item["Handlers"].ToString()))
  5731. item["State"] = "1";
  5732. }
  5733. //更改匹配项状态
  5734. if (ids.Count > 0)
  5735. {
  5736. var _CreditCardPayments = new List<Grp_CreditCardPayment>();
  5737. foreach (var item in ids)
  5738. {
  5739. _CreditCardPayments.Add(new Grp_CreditCardPayment() { Id = item, IsMatchCreditCard = 1.00M });
  5740. }
  5741. var updateStatus = _sqlSugar.Updateable<Grp_CreditCardPayment>(_CreditCardPayments)
  5742. .UpdateColumns(it => new { it.IsMatchCreditCard })
  5743. .Where(it => ids.Contains(it.Id))
  5744. .ExecuteCommand();
  5745. }
  5746. string fileName1 = $"信用卡账单(招行卡){DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  5747. var pairs = new Dictionary<string, object>();
  5748. var datas = new List<DataTable>
  5749. {
  5750. dt1
  5751. };
  5752. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-招行卡.xls", "CreditCardBill", fileName1, pairs, datas);
  5753. #endregion
  5754. }
  5755. else if (cardType == 346) //中信卡
  5756. {
  5757. dt.Columns.Add("TeamRemark", Type.GetType("System.String")); //团组备注描述
  5758. dt.Columns.Add("Handlers", Type.GetType("System.String")); //经手人
  5759. dt.Columns.Add("State", Type.GetType("System.String")); //状态
  5760. //修改table列名
  5761. dt.Columns[0].ColumnName = "TransactionDesc"; // 交易描述
  5762. dt.Columns[1].ColumnName = "TradingCurrencyAndMoney"; // 交易币种和金额
  5763. dt.Columns[2].ColumnName = "TransactionDate"; // 交易日期
  5764. dt.Columns[3].ColumnName = "SettlementCurrencyAndMoney";// 结算币种和金额
  5765. dt.Columns[4].ColumnName = "BookedDate"; // 入账日期
  5766. foreach (DataRow item in dt.Rows)
  5767. {
  5768. for (int i = 0; i < List_ccp.Count; i++)
  5769. {
  5770. if (string.IsNullOrEmpty(item["TransactionDate"].ToString()))
  5771. break;
  5772. DateTime dtTime1 = Convert.ToDateTime(item["TransactionDate"].ToString()); //交易日期
  5773. string USDPrice = item["TradingCurrencyAndMoney"].ToString(); //支出金额
  5774. USDPrice = USDPrice.Split('/')[1];
  5775. //string USDPrice1 = USDPrice.ToString("0.00");
  5776. // 经手人 and excel行状态
  5777. if (!string.IsNullOrEmpty(List_ccp[i].ConsumptionDate) && !string.IsNullOrEmpty(USDPrice))
  5778. {
  5779. DateTime dtTime2 = Convert.ToDateTime(List_ccp[i].ConsumptionDate);
  5780. float price1 = float.Parse(USDPrice);
  5781. float price2 = float.Parse(List_ccp[i].PayMoney.ToString("F2"));
  5782. if (dtTime1 == dtTime2 && price1 == price2)
  5783. {
  5784. item["TeamRemark"] = delegationInfos.Find(it => it.Id == List_ccp[i].DIId)?.TeamName;
  5785. item["Handlers"] = users.Find(it => it.Id == List_ccp[i].CreateUserId)?.CnName;
  5786. item["State"] = "1";
  5787. i = List_ccp.Count - 1;
  5788. }
  5789. else
  5790. item["State"] = "0";
  5791. }
  5792. else
  5793. item["State"] = "0";
  5794. }
  5795. //判断是否是数字
  5796. //if (IsNumber(item["TradingCurrencyAndMoney"].ToString().Split('/')[1]) == false)
  5797. // item["State"] = "0";
  5798. if (item["TransactionDesc"].ToString().Contains("财付通"))
  5799. item["State"] = "2";
  5800. else if (item["TransactionDesc"].ToString().Contains("京东"))
  5801. item["State"] = "2";
  5802. else if (item["TransactionDesc"].ToString().Contains("微信支付"))
  5803. item["State"] = "2";
  5804. else if (item["TransactionDesc"].ToString().Contains("淘宝"))
  5805. item["State"] = "2";
  5806. }
  5807. #region DownExcel
  5808. string fileName1 = $"信用卡账单(中信卡){DateTime.Now:yyyy.MM.dd}.xls";
  5809. var pairs = new Dictionary<string, object>();
  5810. var datas = new List<DataTable>
  5811. {
  5812. dt
  5813. };
  5814. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-中信卡.xls", "TB", fileName1, pairs, datas);
  5815. #endregion
  5816. }
  5817. else if (cardType == 363) //交行卡
  5818. {
  5819. dt.Columns[0].ColumnName = "All";
  5820. var dt1 = new DataTable();
  5821. dt1.Columns.Add("TradingDate", Type.GetType("System.String"));//交易日期
  5822. dt1.Columns.Add("TallyDate", Type.GetType("System.String")); //记账日期
  5823. dt1.Columns.Add("TradindDesc", Type.GetType("System.String"));//交易描述
  5824. dt1.Columns.Add("TradindMoney", Type.GetType("System.String"));//交易币种/金额
  5825. dt1.Columns.Add("ClearindMoney", Type.GetType("System.String"));// 清算币种/金额
  5826. dt1.Columns.Add("TeamRemark", Type.GetType("System.String")); //团组备注描述
  5827. dt1.Columns.Add("Handlers", Type.GetType("System.String")); //经手人
  5828. dt1.Columns.Add("State", Type.GetType("System.String")); //状态
  5829. for (int i = 0; i < dt.Rows.Count; i++)
  5830. {
  5831. string[] str = dt.Rows[i]["All"].ToString().Split(' ');
  5832. DataRow dr = dt1.NewRow();
  5833. dr["TradingDate"] = str[0].ToString();
  5834. dr["TallyDate"] = str[1].ToString();
  5835. dr["TradindDesc"] = str[2].ToString() + " " + str[3].ToString();
  5836. dr["TradindMoney"] = str[4].ToString() + " " + str[5].ToString();
  5837. dr["ClearindMoney"] = str[6].ToString() + " " + str[7].ToString();
  5838. dt1.Rows.Add(dr);
  5839. }
  5840. foreach (DataRow item in dt1.Rows)
  5841. {
  5842. for (int i = 0; i < List_ccp.Count; i++)
  5843. {
  5844. DateTime dtTime1 = Convert.ToDateTime(item["TradingDate"].ToString() == "" ? DateTime.Now.ToString("MM/dd") : item["TradingDate"].ToString()); //交易日期
  5845. string USDPrice = item["TradindMoney"].ToString(); //支出金额
  5846. USDPrice = USDPrice.Split(' ')[1].Trim(); //替换掉非数字
  5847. //USDPrice = USDPrice.Split('/')[1];
  5848. // 经手人 and excel行状态
  5849. if (!string.IsNullOrEmpty(List_ccp[i].ConsumptionDate) && !string.IsNullOrEmpty(USDPrice))
  5850. {
  5851. DateTime dtTime2 = Convert.ToDateTime(List_ccp[i].ConsumptionDate.ToString() == "" ? DateTime.Now.ToString("MM/dd") : List_ccp[i].ConsumptionDate.ToString());
  5852. float price1 = float.Parse(USDPrice);
  5853. float price2 = float.Parse(List_ccp[i].PayMoney.ToString("F2"));
  5854. if (dtTime1 == dtTime2 && price1 == price2)
  5855. {
  5856. item["TeamRemark"] = delegationInfos.Find(it => it.Id == List_ccp[i].DIId)?.TeamName;
  5857. item["Handlers"] = users.Find(it => it.Id == List_ccp[i].CreateUserId)?.CnName;
  5858. item["State"] = "1";
  5859. i = List_ccp.Count - 1;
  5860. }
  5861. else
  5862. item["State"] = "0";
  5863. }
  5864. else
  5865. item["State"] = "0";
  5866. }
  5867. if (item["TradindDesc"].ToString().Contains("财付通"))
  5868. item["State"] = "2";
  5869. else if (item["TradindDesc"].ToString().Contains("京东"))
  5870. item["State"] = "2";
  5871. else if (item["TradindDesc"].ToString().Contains("微信支付"))
  5872. item["State"] = "2";
  5873. else if (item["TradindDesc"].ToString().Contains("淘宝"))
  5874. item["State"] = "2";
  5875. }
  5876. string fileName1 = $"信用卡账单(交行卡){DateTime.Now:yyyy.MM.dd}.xls";
  5877. var pairs = new Dictionary<string, object>();
  5878. var datas = new List<DataTable>
  5879. {
  5880. dt
  5881. };
  5882. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-交行卡.xls", "TB", fileName1, pairs, datas);
  5883. }
  5884. }
  5885. catch (Exception ex)
  5886. {
  5887. return Ok(JsonView(false, $"匹配失败,{ex.Message}!"));
  5888. }
  5889. return Ok(JsonView(true, "操作成功", new { url }));
  5890. }
  5891. /// <summary>
  5892. /// 把数据从Excel装载到DataTable
  5893. /// </summary>
  5894. /// <param name="pathName">带路径的Excel文件名</param>
  5895. /// <param name="sheetName">工作表名</param>
  5896. /// <returns></returns>
  5897. public static DataTable ExcelToDataTable(string pathName, string sheetName = "")
  5898. {
  5899. var tbContainer = new DataTable();
  5900. string strConn = string.Empty;
  5901. if (string.IsNullOrEmpty(sheetName)) { sheetName = "Sheet1"; }
  5902. var file = new FileInfo(pathName);
  5903. if (!file.Exists) { throw new Exception("文件不存在"); }
  5904. string extension = file.Extension;
  5905. strConn = extension switch
  5906. {
  5907. ".xls" => "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'",
  5908. ".xlsx" => "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'",
  5909. _ => "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'",
  5910. };
  5911. //链接Excel
  5912. var cnnxls = new OleDbConnection(strConn);
  5913. //读取Excel里面有 表Sheet1
  5914. var oda = new System.Data.OleDb.OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
  5915. //将Excel里面有表内容装载到内存表中!
  5916. oda.Fill(tbContainer);
  5917. return tbContainer;
  5918. }
  5919. #endregion
  5920. #region 提成计算
  5921. /// <summary>
  5922. /// 提成计算
  5923. /// </summary>
  5924. /// <param name="dto"></param>
  5925. /// <returns></returns>
  5926. [HttpPost]
  5927. public IActionResult ComputeRoyalties(ComputeRoyaltiesDto dto)
  5928. {
  5929. var jw = JsonView(false);
  5930. var userId = dto.UserId;
  5931. var user = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == userId);
  5932. //jw.Data = System.Array.Empty<string>();
  5933. if (user == null)
  5934. {
  5935. jw.Msg = "暂无该用户!";
  5936. return Ok(jw);
  5937. }
  5938. if (!DateTime.TryParse(dto.StartDate, out DateTime StartDateTime))
  5939. {
  5940. jw.Msg = "开始时间格式有误!";
  5941. return Ok(jw);
  5942. }
  5943. if (!DateTime.TryParse(dto.EndDate, out DateTime EndDateTime))
  5944. {
  5945. jw.Msg = "结束时间格式有误!";
  5946. return Ok(jw);
  5947. }
  5948. if (DateTime.Compare(StartDateTime, EndDateTime) > 0)
  5949. {
  5950. jw.Msg = "开始时间大于结束时间!";
  5951. return Ok(jw);
  5952. }
  5953. int[] jobPostIds = { 24, 25, 26, 27, 28 };
  5954. var userGroups = _sqlSugar.Queryable<Sys_Users>()
  5955. .Where(x => x.IsDel == 0 && jobPostIds.Contains(x.JobPostId))
  5956. .Select(x => new { x.Id, x.JobPostId })
  5957. .ToArray()
  5958. .GroupBy(x => x.JobPostId)
  5959. .ToDictionary(g => g.Key, g => g.Select(x => x.Id).ToArray());
  5960. int[] AirTicket = userGroups.ContainsKey(24) ? userGroups[24] : Array.Empty<int>();
  5961. int[] Hotel = userGroups.ContainsKey(25) ? userGroups[25] : Array.Empty<int>();
  5962. int[] OP = userGroups.ContainsKey(28) ? userGroups[28] : Array.Empty<int>();
  5963. int[] Invitation = userGroups.ContainsKey(27) ? userGroups[27] : Array.Empty<int>();
  5964. int[] Visa = userGroups.ContainsKey(26) ? userGroups[26] : Array.Empty<int>();
  5965. //主管职位
  5966. //string[] Manager = { "149", "283" };
  5967. List<ComputeRoyaltiesView> resultArr = new List<ComputeRoyaltiesView>();
  5968. var teamLv = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.STid == 56 && x.IsDel == 0).ToList();
  5969. var auditState = new int[] { 1, 3 };
  5970. if (AirTicket.Contains(userId))
  5971. {
  5972. //提成方式:¥10/人×人数×段数(每个组团涉及的换机次数)
  5973. var listAir = _sqlSugar.Queryable<Grp_AirTicketReservations, Grp_DelegationInfo, Grp_CreditCardPayment>((x, a, b) => new
  5974. JoinQueryInfos(
  5975. JoinType.Left, a.Id == x.DIId,
  5976. JoinType.Left, b.CTable == 85 && b.CId == x.Id)
  5977. )
  5978. .Where((x, a, b) => x.IsDel == 0 && x.CreateUserId == userId && a.IsDel == 0 && a.VisitDate >= StartDateTime
  5979. && a.VisitDate <= EndDateTime && b.IsDel == 0 && auditState.Contains(b.IsAuditGM)) // 取消团组确认状态 && a.IsSure == 1
  5980. .Select((x, a, b) => new
  5981. {
  5982. x.FlightsDescription,
  5983. a.Id,
  5984. a.TeamName,
  5985. a.VisitDate,
  5986. a.TeamLevSId,
  5987. a.VisitPNumber,
  5988. x.Price,
  5989. x.ClientName,
  5990. x.ClientNum,
  5991. x.FlightsCode,
  5992. a.IsSure
  5993. })
  5994. .ToList();
  5995. var groupByid = listAir.GroupBy(x => x.Id);
  5996. foreach (var airArr in groupByid)
  5997. {
  5998. var groupAirCount = 0; //团组航段数量
  5999. var infos = new List<string>();
  6000. foreach (var air in airArr)
  6001. {
  6002. var airCount = 0; // 单条航段数量
  6003. if (air.FlightsDescription.IsNullOrWhiteSpace())
  6004. {
  6005. continue;
  6006. }
  6007. if (air.ClientName.Contains("-1") || air.ClientName.Contains("行程单") || air.FlightsCode.Contains("行程单"))
  6008. {
  6009. continue;
  6010. }
  6011. string errMsg = string.Empty;
  6012. if (air.FlightsDescription.Contains("\r\n") || Regex.Split(air.FlightsDescription, "\\d+\\.", RegexOptions.IgnoreCase).Length > 1)
  6013. {
  6014. var rowCode = Regex.Split(air.FlightsDescription, "\\d+\\.", RegexOptions.IgnoreCase).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();
  6015. for (int i = 0; i < rowCode.Length; i++)
  6016. {
  6017. if (i != 0)
  6018. {
  6019. try
  6020. {
  6021. //var columnValue = rowCode[i].Split(' ').Where(x => !string.IsNullOrEmpty(x)).ToList();
  6022. //string day = columnValue[2].Substring(2, 2);//日
  6023. //string monthAbbreviations = columnValue[2].Substring(4, 3).ToUpper();//月份
  6024. //monthAbbreviations = GeneralMethod.GetLonger(monthAbbreviations);
  6025. //string EndHHmm = columnValue[5].Substring(0, 2) + ":" + columnValue[5].Substring(2, 2);
  6026. //DateTime EndData = DateTime.Parse($"{DateTime.Now.Year}-{monthAbbreviations}-{day} {EndHHmm}");//当前班次
  6027. //var spDotandEmpty1 = rowCode[i - 1].Split(' ').Where(x => !string.IsNullOrEmpty(x)).ToList();
  6028. //string day1 = spDotandEmpty1[2].Substring(2, 2);//日
  6029. //string monthAbbreviations1 = spDotandEmpty1[2].Substring(4, 3).ToUpper();//月份
  6030. //monthAbbreviations1 = GeneralMethod.GetLonger(monthAbbreviations1);
  6031. //string HHmm = spDotandEmpty1[6].Substring(0, 2) + ":" + spDotandEmpty1[6].Substring(2, 2);
  6032. //DateTime data = DateTime.Parse($"{DateTime.Now.Year}-{monthAbbreviations1}-{day1} {HHmm}");//上个班次
  6033. //TimeSpan t3 = EndData - data; //两个时间相减 。默认得到的是 两个时间之间的天数 得到:365.00:00:00
  6034. //double getHour = t3.TotalHours;
  6035. //if (getHour >= 6)
  6036. //{
  6037. // if (air.Price > 0)
  6038. // {
  6039. // airCount += 1;
  6040. // }
  6041. // else
  6042. // {
  6043. // airCount -= 1;
  6044. // }
  6045. //}
  6046. if (air.Price > 0)
  6047. {
  6048. airCount += 1;
  6049. }
  6050. else
  6051. {
  6052. airCount -= 1;
  6053. }
  6054. }
  6055. catch (Exception ex)
  6056. {
  6057. errMsg = "机票行程代码格式有误!解析失败!" + $"({ex.Message})";
  6058. break;
  6059. }
  6060. }
  6061. else
  6062. {
  6063. if (air.Price > 0)
  6064. {
  6065. airCount += 1;
  6066. }
  6067. else
  6068. {
  6069. airCount -= 1;
  6070. }
  6071. }
  6072. }
  6073. }
  6074. else
  6075. {
  6076. if (air.Price > 0)
  6077. {
  6078. airCount++;
  6079. }
  6080. else
  6081. {
  6082. airCount--;
  6083. }
  6084. }
  6085. string info = $"航班{air.FlightsCode} {(air.Price > 0 ? "" : "此笔为退费!")} 人数为{air.ClientNum} 有效段数为{airCount} 总段数为{airCount * air.ClientNum}";
  6086. if (!string.IsNullOrWhiteSpace(errMsg))
  6087. {
  6088. info = $"航班{air.FlightsCode} " + errMsg;
  6089. }
  6090. infos.Add(info);
  6091. groupAirCount += airCount * air.ClientNum;
  6092. }
  6093. var groupinfo = listAir.First(x => x.Id == airArr.Key);
  6094. string temp = "本团人数" + Convert.ToInt32(groupinfo.VisitPNumber) + ",该人员" + user.CnName + "共订航段数" + groupAirCount.ToString() + ",每程航班提成为10元," + user.CnName + "提成共" + (groupAirCount * 10).ToString("#0.00");
  6095. resultArr.Add(new ComputeRoyaltiesView
  6096. {
  6097. TeamName = groupinfo.TeamName,
  6098. TeamId = groupinfo.Id,
  6099. ChiArr = infos,
  6100. TeamLvStr = teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name,
  6101. VisitDate = groupinfo.VisitDate,
  6102. Temp = temp,
  6103. Price = (groupAirCount * 10),
  6104. State = groupinfo.IsSure
  6105. });
  6106. }
  6107. }
  6108. else if (Hotel.Contains(userId))
  6109. {
  6110. //标准团组:¥10/间/晚 * 实际订房间数 * 实际订房晚数; setdata id 1001 客人房
  6111. var listHotel = _sqlSugar.Queryable<Grp_HotelReservations, Grp_DelegationInfo, Grp_CreditCardPayment>((x, a, b) => new JoinQueryInfos(
  6112. JoinType.Left, x.DiId == a.Id,
  6113. JoinType.Left, b.CTable == 76 && b.CId == x.Id))
  6114. .Where((x, a, b) => x.IsDel == 0 && x.CreateUserId == userId && a.VisitDate >= StartDateTime
  6115. && a.VisitDate <= EndDateTime && a.IsDel == 0 && b.IsDel == 0 && x.CardPrice != 0 && auditState.Contains(b.IsAuditGM) && x.CheckType == 1001)
  6116. .Select((x, a, b) => new // && a.IsSure == 1
  6117. {
  6118. a.Id,
  6119. a.TeamName,
  6120. a.VisitDate,
  6121. a.TeamLevSId,
  6122. a.VisitPNumber,
  6123. x.SingleRoomCount,
  6124. x.SuiteRoomCount,
  6125. x.DoubleRoomCount,
  6126. x.OtherRoomCount,
  6127. x.CheckInDate,
  6128. x.CheckOutDate,
  6129. x.HotelName,
  6130. a.IsSure
  6131. })
  6132. .ToList();
  6133. var groupByid = listHotel.GroupBy(x => x.Id);
  6134. var propertys = new string[] { "SingleRoomCount", "SuiteRoomCount", "DoubleRoomCount", "OtherRoomCount" };
  6135. foreach (var group in groupByid)
  6136. {
  6137. var infos = new List<string>();
  6138. var totalPrice = 0.00M;
  6139. foreach (var item in group)
  6140. {
  6141. var hotelCount = 0;
  6142. foreach (var property in propertys)
  6143. {
  6144. var value = item.GetType().GetProperty(property).GetValue(item).ObjToInt();
  6145. if (value > 0)
  6146. {
  6147. hotelCount += value;
  6148. }
  6149. }
  6150. if (hotelCount > 0)
  6151. {
  6152. if (DateTime.TryParse(item.CheckInDate, out DateTime checkin) && DateTime.TryParse(item.CheckOutDate, out DateTime checkout))
  6153. {
  6154. var day = checkout - checkin;
  6155. infos.Add($"{item.HotelName} 共有 {hotelCount} 间房 , 入住时间{item.CheckInDate} - {item.CheckOutDate} 共 {day.TotalDays}晚 提成数量:{hotelCount * day.TotalDays} 提成金额:{hotelCount * day.TotalDays * 10}");
  6156. totalPrice += (decimal)(hotelCount * day.TotalDays * 10);
  6157. }
  6158. else
  6159. {
  6160. infos.Add(item.HotelName + " 时间有误!请检查 。");
  6161. }
  6162. }
  6163. }
  6164. var groupinfo = listHotel.First(x => x.Id == group.Key);
  6165. var temp = "本团人数" + groupinfo.VisitPNumber + ",该人员" + user.CnName + "共操作酒店晚数" + totalPrice / 10 + ",每间每晚提成10元," + user.CnName + "提成共" + totalPrice.ToString("#0.00") + "元";
  6166. resultArr.Add(new ComputeRoyaltiesView
  6167. {
  6168. TeamName = groupinfo.TeamName,
  6169. TeamId = groupinfo.Id,
  6170. ChiArr = infos,
  6171. TeamLvStr = teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name,
  6172. VisitDate = groupinfo.VisitDate,
  6173. Temp = temp,
  6174. Price = totalPrice,
  6175. State = groupinfo.IsSure,
  6176. });
  6177. }
  6178. }
  6179. else if (OP.Contains(userId))
  6180. {
  6181. var OPList = _sqlSugar.Queryable<Grp_DelegationInfo>()
  6182. .Where((a) => a.IsDel == 0 && a.VisitDate >= StartDateTime && a.VisitDate <= EndDateTime)
  6183. .ToList(); // && a.IsSure == 1
  6184. var LvArr = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.STid == 70 && x.IsDel == 0).ToList();
  6185. foreach (var groupinfo in OPList)
  6186. {
  6187. var price = LvArr.Find(x => x.Id == groupinfo.OpRoyaltyLv)?.Name.ObjToInt() ?? 0;
  6188. string temp = $"本团等级为{teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name} 提成金额为{price} {(string.IsNullOrWhiteSpace(groupinfo.OpRoyaltyRemark) ? "" : "提成说明:" + groupinfo.OpRoyaltyRemark)}";
  6189. if (price == 0)
  6190. {
  6191. temp = $"本团等级为{teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name} op提成选项未选择!";
  6192. }
  6193. resultArr.Add(new ComputeRoyaltiesView
  6194. {
  6195. TeamName = groupinfo.TeamName,
  6196. TeamId = groupinfo.Id,
  6197. ChiArr = new List<string>() { temp },
  6198. TeamLvStr = teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name,
  6199. VisitDate = groupinfo.VisitDate,
  6200. Temp = temp,
  6201. Price = price,
  6202. State = groupinfo.IsSure,
  6203. });
  6204. }
  6205. }
  6206. else if (Invitation.Contains(userId))
  6207. {
  6208. //2)付费公务活动部分:¥50 / 团;
  6209. //4)不付费公务活动部分(自己联络)额外奖励:¥200 / 团(若公务活动方与邀请方为同一机构,奖励金额为¥100 / 团);
  6210. //5)只发邀请的团组不付费邀请额外奖励:¥100 / 团;
  6211. //邀请方已授权我司签发的邀请仍按照:¥100 / 团,无额外奖励。
  6212. const int payingOfficial = 50; // 付费单公务 50
  6213. const int notPayingOfficial = 200; // 不付费单场公务 200
  6214. const int payInvitation = 100; // 付费单邀请函 100元 / 份 一个国家只发放一份邀请函费用
  6215. const int notpayInvitation = 400; // 不付费邀请函 400 / 份 一个国家只发放一份邀请函费用,多拿的邀请函不进行叠加
  6216. //不付费邀请函 400 / 份 一个国家只发放一份邀请函费用,多拿的邀请函不进行叠加
  6217. //不付费单场公务 200 / 场 / 团 按照标准公务完成要求,确认实际场数
  6218. //付费单邀请函 100元 / 份 一个国家只发放一份邀请函费用
  6219. //付费单公务 50 / 场 / 团 按照标准公务完成要求,确认实际场数
  6220. //客户报批内容涉及的调研 / 参观性质点位 50 / 场 / 团 需提供给客户有效联系方式、点位地址等符合有效公务完成标准。每个国家原则上不超过2场(特殊增加场次以客户要求制定),超出部分,公司不发放提成。
  6221. var officialList = _sqlSugar.Queryable<Res_OfficialActivities, Grp_DelegationInfo>((x, a) => new JoinQueryInfos(JoinType.Left, a.Id == x.DiId))
  6222. .Where((x, a) => x.IsSubmitApproval == 0 && x.IsDel == 0 && a.IsDel == 0
  6223. && a.VisitDate >= StartDateTime && a.VisitDate <= EndDateTime // && a.IsSure == 1
  6224. && x.CreateUserId == userId && x.DataSource != 1335) //客人不提成
  6225. .Select((x, a) => new
  6226. {
  6227. a.Id,
  6228. a.TeamName,
  6229. a.VisitDate,
  6230. x.CreateUserId,
  6231. x.Type,
  6232. a.TeamLevSId,
  6233. x.Country,
  6234. x.Area,
  6235. x.Date,
  6236. x.Client,
  6237. a.IsSure,
  6238. x.IsPay, // 是否付费
  6239. a.VisitPNumber,
  6240. x.OfficialForm,
  6241. })
  6242. .ToList();
  6243. var groups = officialList.GroupBy(x => x.Id);
  6244. foreach (var group in groups)
  6245. {
  6246. var groupinfo = officialList.First(x => x.Id == group.Key);
  6247. string temp = string.Empty;
  6248. var money = 0;
  6249. var infos = new List<string>();
  6250. var existsCountry = new List<string>(); //邀请函国家判断
  6251. foreach (var item in group)
  6252. {
  6253. if (item.OfficialForm == 1338 || item.OfficialForm == 384) // 调研 / 参观性质点位 50 / 场 / 团
  6254. {
  6255. infos.Add($"{item.Client}为调研 / 参观性质点位,提成金额为50");
  6256. money += 50;
  6257. continue;
  6258. }
  6259. //0带公务 1不带公务 2纯公务
  6260. //1082 带公务
  6261. //1083 不带公务
  6262. //1084 纯公务
  6263. if (item.Type == 0 || item.Type == 1082)
  6264. {
  6265. if (!existsCountry.Contains(item.Country))
  6266. {
  6267. if (item.IsPay == 1) //付费邀请函
  6268. {
  6269. infos.Add($"{item.Client} 为付费邀请函,提成金额为 {payInvitation}");
  6270. money += payingOfficial;
  6271. }
  6272. else
  6273. {
  6274. infos.Add($"{item.Client} 为非付费邀请函,提成金额为 {notpayInvitation}");
  6275. money += notPayingOfficial;
  6276. }
  6277. }
  6278. }
  6279. else if (item.Type == 2 || item.Type == 1084)
  6280. {
  6281. if (item.IsPay == 1) //付费公务
  6282. {
  6283. infos.Add($"{item.Client} 为付费公务,提成金额为 {payingOfficial}");
  6284. money += payingOfficial;
  6285. }
  6286. else
  6287. {
  6288. infos.Add($"{item.Client} 为非付费公务,提成金额为 {notPayingOfficial}");
  6289. money += notPayingOfficial;
  6290. }
  6291. }
  6292. }
  6293. temp = "本团人数" + groupinfo.VisitPNumber + ",该人员" + user.CnName + "共操作公务数" + group.Count() + $",付费公务提成金额为{payingOfficial}" + $",非付费公务提成金额为{notPayingOfficial}," + user.CnName + "提成共" + money + "元"; ;
  6294. resultArr.Add(new ComputeRoyaltiesView
  6295. {
  6296. TeamName = groupinfo.TeamName,
  6297. TeamId = groupinfo.Id,
  6298. ChiArr = infos,
  6299. TeamLvStr = teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name,
  6300. VisitDate = groupinfo.VisitDate,
  6301. Temp = temp,
  6302. Price = money,
  6303. State = groupinfo.IsSure,
  6304. });
  6305. }
  6306. }
  6307. else if (Visa.Contains(userId)) //签证
  6308. {
  6309. // 1)办理英国、加拿大、美国签证¥50元 / 人 / 团;
  6310. // 申根国家及其他所有国家¥30元 / 人 / 团;
  6311. // setdata id 974 客人
  6312. var existsCountry = new string[] { "英国", "加拿大", "美国" };
  6313. var whereExpression = Expressionable.Create<Grp_VisaInfo, Grp_DelegationInfo, Grp_CreditCardPayment>()
  6314. .And(
  6315. (x, a, b) => x.IsDel == 0 && x.CreateUserId == userId && (b.IsAuditGM == 1 || b.IsAuditGM == 3)
  6316. && a.IsDel == 0 && a.VisitDate >= StartDateTime && a.VisitDate <= EndDateTime
  6317. && b.IsDel == 0 && x.IsThird == 0 && x.PassengerType == 974
  6318. && auditState.Contains(b.IsAuditGM) // && a.IsSure == 1
  6319. );
  6320. var listVisa = _sqlSugar.Queryable<Grp_VisaInfo, Grp_DelegationInfo, Grp_CreditCardPayment>((x, a, b) => new
  6321. JoinQueryInfos(
  6322. JoinType.Left, a.Id == x.DIId,
  6323. JoinType.Left, b.CTable == 80 && b.CId == x.Id)
  6324. )
  6325. .Where(whereExpression.ToExpression())
  6326. .Select((x, a, b) => new
  6327. {
  6328. a.Id,
  6329. a.TeamName,
  6330. a.VisitDate,
  6331. a.TeamLevSId,
  6332. a.VisitPNumber,
  6333. a.VisitCountry,
  6334. x.VisaDescription,
  6335. x.VisaFreeNumber,
  6336. x.VisaNumber,
  6337. x.VisaPrice,
  6338. a.IsSure,
  6339. })
  6340. .ToList();
  6341. var groupByid = listVisa.GroupBy(x => x.Id);
  6342. foreach (var visaArr in groupByid)
  6343. {
  6344. var groupinfo = listVisa.First(x => x.Id == visaArr.Key);
  6345. var singlePrice = existsCountry.Where(x => groupinfo.VisitCountry.Contains(x)).Count() > 0 ? 50 : 30;
  6346. int count = 0, money = 0;
  6347. var arr = new List<string>();
  6348. foreach (var visa in visaArr)
  6349. {
  6350. if (visa.VisaPrice > 0)
  6351. {
  6352. count += visa.VisaFreeNumber + visa.VisaNumber;
  6353. money += singlePrice * (visa.VisaFreeNumber + visa.VisaNumber);
  6354. }
  6355. else
  6356. {
  6357. count -= visa.VisaFreeNumber + visa.VisaNumber;
  6358. money -= singlePrice * (visa.VisaFreeNumber + visa.VisaNumber);
  6359. }
  6360. string info = $"签证 {visa.VisaDescription} {(visa.VisaPrice > 0 ? "" : "此笔为退费!")} 人数为{visa.VisaFreeNumber + visa.VisaNumber} 单价为{singlePrice} 金额为{singlePrice * (visa.VisaFreeNumber + visa.VisaNumber)}";
  6361. arr.Add(info);
  6362. }
  6363. string temp = "本团人数" + groupinfo.VisitPNumber + ",该人员" + user.CnName + "共办理英国、加拿大、美国签证" + (singlePrice == 50 ? count : 0).ToString() + "本护照(包含免签人员),申根国家及其他所有国家" + (singlePrice == 30 ? count : 0).ToString() + "本。" + user.CnName + "提成共" + money.ToString("#0.00") + "元";
  6364. resultArr.Add(new ComputeRoyaltiesView
  6365. {
  6366. TeamName = groupinfo.TeamName,
  6367. TeamId = groupinfo.Id,
  6368. ChiArr = arr,
  6369. TeamLvStr = teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name,
  6370. VisitDate = groupinfo.VisitDate,
  6371. Temp = temp,
  6372. Price = money,
  6373. State = groupinfo.IsSure,
  6374. });
  6375. }
  6376. }
  6377. if (resultArr.Count > 0)
  6378. {
  6379. jw.Code = 200;
  6380. jw.Msg = "success!";
  6381. decimal total = 0;
  6382. foreach (var item in resultArr)
  6383. {
  6384. //var number = item.GetType().GetProperty("price")?.GetValue(item)?.ToString();
  6385. //total += decimal.TryParse(number,out decimal numberInt) ? numberInt : 0.00M;
  6386. total += item.Price;
  6387. }
  6388. jw.Data = new
  6389. {
  6390. resultArr,
  6391. totalPrice = total,
  6392. };
  6393. }
  6394. else
  6395. {
  6396. jw.Msg = "暂无数据!";
  6397. }
  6398. return Ok(jw);
  6399. }
  6400. /// <summary>
  6401. /// 导出提成表格
  6402. /// </summary>
  6403. /// <returns></returns>
  6404. [HttpPost]
  6405. public IActionResult ExportRoyaltyExcel(ExportRoyaltyExcelDto dto)
  6406. {
  6407. var jw = JsonView(false);
  6408. var apiResult = ComputeRoyalties(new
  6409. ComputeRoyaltiesDto
  6410. {
  6411. EndDate = dto.EndDate,
  6412. StartDate = dto.StartDate,
  6413. UserId = dto.UserId,
  6414. });
  6415. var parseApiResult = ((apiResult as OkObjectResult)?.Value) as OASystem.Domain.ViewModels.JsonView;
  6416. if (parseApiResult != null && parseApiResult.Code == 200)
  6417. {
  6418. var apiArr = (parseApiResult.Data?.GetType().GetProperty("resultArr")?.GetValue(parseApiResult.Data)) as List<ComputeRoyaltiesView>;
  6419. var user = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == dto.UserId);
  6420. if (apiArr != null && apiArr.Count > 0)
  6421. {
  6422. var dic = new Dictionary<string, string>
  6423. {
  6424. //dic.Add("Name", "人员:" + user.CnName);
  6425. { "startTime", dto.StartDate },
  6426. { "endTime", dto.EndDate },
  6427. { "operName", user.CnName },
  6428. { "timeNow", DateTime.Now.ToString("yyyy年MM月dd日") },
  6429. //dic.Add("DowntimeNow", DateTime.Now.ToString("yyyy年MM月dd日"));
  6430. { "totalPrice", ("总金额:" + parseApiResult.Data?.GetType().GetProperty("totalPrice")?.GetValue(parseApiResult.Data).ObjToDecimal().ToString() ?? "0") + " 元" }
  6431. };
  6432. var ToTableArr = new ArrayList();
  6433. int No = 1;
  6434. //打开excel模板
  6435. foreach (var item in apiArr)
  6436. {
  6437. //载入数据
  6438. ToTableArr.Add(new
  6439. {
  6440. No,
  6441. item.TeamName,
  6442. item.VisitDate,
  6443. item.TeamLvStr,
  6444. item.Temp,
  6445. infos = string.Join("\r\n", item.ChiArr),
  6446. price = item.Price + "元",
  6447. });
  6448. No++;
  6449. }
  6450. DataTable TbData = CommonFun.ToDataTableArray(ToTableArr);
  6451. TbData.TableName = "TbData";
  6452. var designer = new WorkbookDesigner
  6453. {
  6454. Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/提成结算template.xlsx")
  6455. };
  6456. foreach (var key in dic.Keys)
  6457. {
  6458. designer.SetDataSource(key, dic[key]);
  6459. }
  6460. //数据源
  6461. designer.SetDataSource(TbData);
  6462. designer.Process();
  6463. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "RoyaltyExcel/" + user.CnName + "_提成结算.xlsx");
  6464. jw = JsonView(true, "success!", new
  6465. {
  6466. Url = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + "RoyaltyExcel/" + user.CnName + "_提成结算.xlsx",
  6467. });
  6468. }
  6469. }
  6470. else
  6471. {
  6472. jw.Msg = "获取提成信息error " + jw.Msg;
  6473. }
  6474. return Ok(jw);
  6475. }
  6476. /// <summary>
  6477. /// 提成财务确认通知
  6478. /// </summary>
  6479. /// <returns></returns>
  6480. [HttpPost]
  6481. public async Task<IActionResult> RoyaltyConfirmByFin(RoyaltyConfirmDto dto)
  6482. {
  6483. var jw = JsonView(false);
  6484. if (!DateTime.TryParse(dto.StartData, out DateTime StartDateTime))
  6485. {
  6486. jw.Msg = "开始时间格式有误!";
  6487. return Ok(jw);
  6488. }
  6489. if (!DateTime.TryParse(dto.EndData, out DateTime EndDateTime))
  6490. {
  6491. jw.Msg = "结束时间格式有误!";
  6492. return Ok(jw);
  6493. }
  6494. if (DateTime.Compare(StartDateTime, EndDateTime) > 0)
  6495. {
  6496. jw.Msg = "开始时间大于结束时间!";
  6497. return Ok(jw);
  6498. }
  6499. if (dto.ComputeRoyaltiesList.Count != 0)
  6500. {
  6501. var user = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == dto.UserId);
  6502. if (user == null) { return Ok(JsonView(false, "通知失败! 人员信息有误!")); }
  6503. //保存提成信息
  6504. //消息通知对应人员(公司 部门 人员 时间段 团组id 是否确定 )
  6505. List<Fin_RoyaltyConfirm> entitys = dto.ComputeRoyaltiesList.Select(x => new Fin_RoyaltyConfirm
  6506. {
  6507. UserId = dto.UserId,
  6508. ChiArr = JsonConvert.SerializeObject(x.ChiArr),
  6509. CreateTime = DateTime.Now,
  6510. CreateUserId = dto.UserId,
  6511. IsConfirm = 0,
  6512. TeamId = x.TeamId,
  6513. TeamLvStr = x.TeamLvStr,
  6514. Price = x.Price,
  6515. VisitDate = x.VisitDate,
  6516. TeamName = x.TeamName,
  6517. Temp = x.Temp,
  6518. IsSeed = 0
  6519. }).ToList();
  6520. var expressionSoftDeleteWhere = Expressionable.Create<Fin_RoyaltyConfirm>()
  6521. .And(it => it.VisitDate >= StartDateTime)
  6522. .And(it => it.VisitDate <= EndDateTime)
  6523. .And(it => it.IsDel == 0)
  6524. .And(it => it.UserId == dto.UserId)
  6525. .And(it => it.IsSeed == 0)
  6526. .ToExpression();
  6527. var expressionSelectWhere = Expressionable.Create<Fin_RoyaltyConfirm>()
  6528. .And(it => it.VisitDate >= StartDateTime)
  6529. .And(it => it.VisitDate <= EndDateTime)
  6530. .And(it => it.IsDel == 0)
  6531. .And(it => it.UserId == dto.UserId)
  6532. .And(it => it.IsSeed == 1)
  6533. .ToExpression();
  6534. _sqlSugar.BeginTran();
  6535. try
  6536. {
  6537. _ = _sqlSugar.Updateable<Fin_RoyaltyConfirm>().SetColumns(it => new Fin_RoyaltyConfirm() { IsDel = 1, DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm"), DeleteUserId = dto.UserId })
  6538. .Where(expressionSoftDeleteWhere)
  6539. .ExecuteCommand();
  6540. var confirmYes = _sqlSugar.Queryable<Fin_RoyaltyConfirm>().Where(expressionSelectWhere).Select(x => x.TeamId).ToList();
  6541. entitys = entitys.Where(x => !confirmYes.Contains(x.TeamId)).ToList();
  6542. _ = _sqlSugar.Insertable<Fin_RoyaltyConfirm>(entitys).ExecuteCommand();
  6543. _sqlSugar.CommitTran();
  6544. //调用通知
  6545. var title = "提成确认";
  6546. var center = $"【{dto.StartData}】 - 【{dto.EndData}】提成财务已确认,请尽快查看!";
  6547. //【{dto.StartData}-{dto.EndData}-{dto.CompanyId}-{dto.DeparId}-{dto.UserId}】";
  6548. var ids = new List<int> { 235, 233 }; //dto.UserId
  6549. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations, title, center, ids);
  6550. jw = JsonView(true, $"人员:{user.CnName} {dto.StartData}-{dto.EndData} 通知成功!");
  6551. }
  6552. catch (Exception ex)
  6553. {
  6554. _sqlSugar.RollbackTran();
  6555. jw = JsonView(false, "保存失败!" + ex.Message);
  6556. }
  6557. }
  6558. else
  6559. {
  6560. jw = JsonView(false, "保存失败! 无提成信息");
  6561. }
  6562. return Ok(jw);
  6563. }
  6564. /// <summary>
  6565. /// 查询提成信息
  6566. /// </summary>
  6567. /// <param name="dto"></param>
  6568. /// <returns></returns>
  6569. [HttpPost]
  6570. public IActionResult QueryRoyaltyInfo(QueryRoyaltyInfoDto dto)
  6571. {
  6572. var jw = JsonView(false);
  6573. var stateArr = new int[] { -1, 0, 1 };
  6574. if (!DateTime.TryParse(dto.StartDate, out DateTime StartDateTime))
  6575. {
  6576. jw.Msg = "开始时间格式有误!";
  6577. return Ok(jw);
  6578. }
  6579. if (!DateTime.TryParse(dto.EndDate, out DateTime EndDateTime))
  6580. {
  6581. jw.Msg = "结束时间格式有误!";
  6582. return Ok(jw);
  6583. }
  6584. if (DateTime.Compare(StartDateTime, EndDateTime) > 0)
  6585. {
  6586. jw.Msg = "开始时间大于结束时间!";
  6587. return Ok(jw);
  6588. }
  6589. if (!stateArr.Contains(dto.Send) || !stateArr.Contains(dto.Confirm))
  6590. {
  6591. jw.Msg = "状态标识有误!";
  6592. return Ok(jw);
  6593. }
  6594. var expressionSelectWhere = Expressionable.Create<Fin_RoyaltyConfirm>()
  6595. .And(it => it.VisitDate >= StartDateTime)
  6596. .And(it => it.VisitDate <= EndDateTime)
  6597. .And(it => it.IsDel == 0)
  6598. .And(it => it.UserId == dto.UserId)
  6599. .AndIF(dto.Confirm != -1, it => it.IsConfirm == dto.Confirm)
  6600. .AndIF(dto.Send != -1, it => it.IsSeed == dto.Send)
  6601. .ToExpression();
  6602. try
  6603. {
  6604. var query = _sqlSugar.Queryable<Fin_RoyaltyConfirm>().Where(expressionSelectWhere).ToList().Select(x => new
  6605. {
  6606. x.Price,
  6607. ChiArr = JsonConvert.DeserializeObject<List<string>>(x.ChiArr),
  6608. x.IsConfirm,
  6609. x.Id,
  6610. x.TeamId,
  6611. x.TeamName,
  6612. x.TeamLvStr,
  6613. x.Temp,
  6614. x.VisitDate,
  6615. x.IsSeed
  6616. });
  6617. jw = JsonView(true, "获取成功!", new
  6618. {
  6619. List = query,
  6620. CostPrice = query.Sum(x => x.Price),
  6621. ConfirmPrice = query.Where(x => x.IsConfirm == 1).Sum(x => x.Price),
  6622. NoConfirmPrice = query.Where(x => x.IsConfirm == 0).Sum(x => x.Price),
  6623. SeedPrice = query.Where(x => x.IsSeed == 1).Sum(x => x.Price),
  6624. NoSeedPrice = query.Where(x => x.IsSeed == 0).Sum(x => x.Price),
  6625. });
  6626. }
  6627. catch (Exception ex)
  6628. {
  6629. jw = JsonView(true, "获取失败!" + ex.Message);
  6630. }
  6631. return Ok(jw);
  6632. }
  6633. /// <summary>
  6634. /// 个人提成确认
  6635. /// </summary>
  6636. /// <param name="dto"></param>
  6637. /// <returns></returns>
  6638. [HttpPost]
  6639. public IActionResult RoyaltyConfirmByUser(RoyaltyConfirmByUserDto dto)
  6640. {
  6641. var jw = JsonView(false);
  6642. var stateArr = new int[] { 0, 1 };
  6643. if (!stateArr.Contains(dto.State))
  6644. {
  6645. return Ok(JsonView(false, "状态标识有误!"));
  6646. }
  6647. if (dto.Data != null && dto.Data.Count != 0)
  6648. {
  6649. var expressionUpdateWhere = Expressionable.Create<Fin_RoyaltyConfirm>()
  6650. .And(it => dto.Data.Contains(it.Id))
  6651. .And(it => it.IsDel == 0)
  6652. .ToExpression();
  6653. var count = _sqlSugar.Updateable<Fin_RoyaltyConfirm>().SetColumns(x => new Fin_RoyaltyConfirm
  6654. {
  6655. IsConfirm = dto.State,
  6656. })
  6657. .Where(expressionUpdateWhere).ExecuteCommand();
  6658. jw.Msg = $"{count}个团组确认成功!";
  6659. jw.Code = 200;
  6660. }
  6661. else
  6662. {
  6663. jw.Msg = "Data为空!";
  6664. }
  6665. return Ok(jw);
  6666. }
  6667. /// <summary>
  6668. /// 提成发放
  6669. /// </summary>
  6670. /// <param name="dto"></param>
  6671. /// <returns></returns>
  6672. [HttpPost]
  6673. public IActionResult RoyaltySeed(RoyaltySeedDto dto)
  6674. {
  6675. var jw = JsonView(false);
  6676. if (dto.Data != null && dto.Data.Count > 0)
  6677. {
  6678. var updateCount = _sqlSugar.Updateable<Fin_RoyaltyConfirm>().SetColumns(x => new Fin_RoyaltyConfirm
  6679. { IsSeed = 1 }).Where(x => dto.Data.Contains(x.Id) && x.IsDel == 0 && x.IsConfirm == 1).ExecuteCommand();
  6680. var info = $"{updateCount}个团组提成发放成功!";
  6681. if (dto.Data.Count > updateCount)
  6682. {
  6683. info += $"/r/n{dto.Data.Count - updateCount}个团组未确认!";
  6684. }
  6685. jw = JsonView(true, info);
  6686. }
  6687. else
  6688. {
  6689. jw.Msg = "发放的数据为空!";
  6690. }
  6691. return Ok(jw);
  6692. }
  6693. /// <summary>
  6694. /// 提成确认信息
  6695. /// </summary>
  6696. /// <returns></returns>
  6697. [HttpPost]
  6698. public IActionResult RoyaltyConfirmInfo()
  6699. {
  6700. var jw = JsonView(false);
  6701. var queryExpression = Expressionable.Create<Fin_RoyaltyConfirm>()
  6702. .And(r => r.IsDel == 0)
  6703. .And(r => r.IsConfirm == 1)
  6704. .And(r => r.IsSeed == 0)
  6705. .ToExpression();
  6706. var DbQueryConfirmInfo = _sqlSugar.Queryable<Fin_RoyaltyConfirm>()
  6707. .LeftJoin<Sys_Users>((r, s) => s.IsDel == 0 && s.Id == r.UserId)
  6708. .LeftJoin<Sys_JobPost>((r, s, p) => p.IsDel == 0 && p.Id == s.JobPostId)
  6709. .LeftJoin<Sys_Department>((r, s, p, d) => d.IsDel == 0 && d.Id == p.DepId)
  6710. .LeftJoin<Sys_Company>((r, s, p, d, c) => c.IsDel == 0 && c.Id == d.CompanyId)
  6711. .Where(queryExpression)
  6712. .Select((r, s, p, d, c) => new
  6713. {
  6714. r.UserId,
  6715. r.TeamId,
  6716. r.Id,
  6717. r.TeamName,
  6718. r.Price,
  6719. s.CnName,
  6720. p.JobName,
  6721. d.DepName,
  6722. c.CompanyName
  6723. })
  6724. .ToList();
  6725. var groupConfirmInfoByUser = DbQueryConfirmInfo.GroupBy(x => x.UserId);
  6726. var returnData = new ArrayList();
  6727. foreach (var item in groupConfirmInfoByUser)
  6728. {
  6729. var first = item.First();
  6730. returnData.Add(new
  6731. {
  6732. UserId = item.Key,
  6733. Count = item.Count(),
  6734. first.CompanyName,
  6735. first.DepName,
  6736. first.JobName,
  6737. first.CnName,
  6738. SumPrice = item.Sum(x => x.Price),
  6739. RoyaltyIdArr = item.Select(x => x.Id)
  6740. });
  6741. }
  6742. jw = JsonView(true, "获取成功!", returnData);
  6743. return Ok(jw);
  6744. }
  6745. /// <summary>
  6746. /// 提交到日付申请
  6747. /// </summary>
  6748. /// <returns></returns>
  6749. [HttpPost]
  6750. public async Task<IActionResult> RoyaltyFormPrice(RoyaltyFromPriceDto dto)
  6751. {
  6752. var jw = JsonView(false, "用户ID为空!");
  6753. var User = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id
  6754. == dto.CreateId && x.IsDel == 0);
  6755. if (User == null)
  6756. {
  6757. JsonView(false, "createid 不存在!");
  6758. }
  6759. if (dto.Items.Count > 0)
  6760. {
  6761. var queryExpression = Expressionable.Create<Fin_RoyaltyConfirm>()
  6762. .And(r => r.IsDel == 0)
  6763. .And(r => r.IsConfirm == 1)
  6764. .And(r => dto.Items.Select(x => x.UserId).Contains(r.UserId))
  6765. .ToExpression();
  6766. var DbQueryConfirmInfo = _sqlSugar.Queryable<Fin_RoyaltyConfirm>()
  6767. .LeftJoin<Sys_Users>((r, s) => s.IsDel == 0 && s.Id == r.UserId)
  6768. .LeftJoin<Sys_JobPost>((r, s, p) => p.IsDel == 0 && p.Id == s.JobPostId)
  6769. .LeftJoin<Sys_Department>((r, s, p, d) => d.IsDel == 0 && d.Id == p.DepId)
  6770. .LeftJoin<Sys_Company>((r, s, p, d, c) => c.IsDel == 0 && c.Id == d.CompanyId)
  6771. .Where(queryExpression)
  6772. .Select((r, s, p, d, c) => new
  6773. {
  6774. r.UserId,
  6775. r.TeamId,
  6776. r.Id,
  6777. r.TeamName,
  6778. r.Price,
  6779. s.CnName,
  6780. p.JobName,
  6781. d.DepName,
  6782. c.CompanyName,
  6783. CompanyId = c.Id,
  6784. UserName = s.CnName,
  6785. })
  6786. .ToList();
  6787. //已经提交到日付的用户提成信息
  6788. var existsDb = _sqlSugar.Queryable<Fin_RoyaltyForm>()
  6789. .Where(x => dto.Items
  6790. .Select(x => x.UserId).Contains(x.UserId) && x.IsDel == 0)
  6791. .ToList();
  6792. var GroupByConfirmInfo = DbQueryConfirmInfo.GroupBy(x => x.UserId).ToList();
  6793. //关联信息
  6794. var relevanceSoure = new List<Fin_RoyaltyForm>();
  6795. var dayPrice = new AddDailyFeePaymentDto()
  6796. {
  6797. UserId = dto.CreateId,
  6798. Instructions = DateTime.Now.ToString("yyyy-MM-dd HH:mm") + " 提成导入日付!",
  6799. PortType = 1,
  6800. CompanyId = 2,
  6801. PriceTypeId = 668,
  6802. TransferTypeId = 798,
  6803. };
  6804. var ChiDayPrice = new List<AddDailyFeePaymentContentDto>();
  6805. _sqlSugar.BeginTran();
  6806. try
  6807. {
  6808. string message = string.Empty;
  6809. foreach (var item in GroupByConfirmInfo)
  6810. {
  6811. var first = item.First();
  6812. var reqBody = dto.Items.Find(x => x.UserId == item.Key);
  6813. var exists = item.Where(x => reqBody!.ChiArr.Contains(x.Id));
  6814. var existsDbByUser = existsDb.Where(x => x.UserId == item.Key);
  6815. var idsByUser = string.Join(',', existsDbByUser.Select(x => x.ConfirmIdArr));
  6816. var idsByUserList = idsByUser.Split(',')
  6817. .Select(x =>
  6818. {
  6819. if (!string.IsNullOrWhiteSpace(x) && int.TryParse(x, out int intx))
  6820. {
  6821. return intx;
  6822. }
  6823. return 0;
  6824. })
  6825. .Where(x => x != 0)
  6826. .ToList();
  6827. var saveArr = exists.Where(x => !idsByUserList.Contains(x.Id));
  6828. var existsYes = exists.Where(x => idsByUserList.Contains(x.Id));
  6829. var yesPrice = existsYes.Sum(x => x.Price);
  6830. var savePrice = saveArr.Sum(x => x.Price);
  6831. if (saveArr.Any())
  6832. {
  6833. ChiDayPrice.Add(new
  6834. AddDailyFeePaymentContentDto
  6835. {
  6836. ItemTotal = savePrice,
  6837. Price = savePrice,
  6838. Quantity = 1,
  6839. PriceName = first.CnName + "提成金额!",
  6840. });
  6841. relevanceSoure.Add(new
  6842. Fin_RoyaltyForm
  6843. {
  6844. CreateUserId = dto.CreateId,
  6845. ConfirmIdArr = string.Join(',', saveArr.Select(x => x.Id)),
  6846. CreateTime = DateTime.Now,
  6847. IsDel = 0,
  6848. UserId = item.Key,
  6849. });
  6850. }
  6851. if (yesPrice > 0)
  6852. {
  6853. message += $"{first.CnName} 提成 {savePrice}元已导入日付申请 , {yesPrice} 元已经存在 ! \r\n";
  6854. }
  6855. else
  6856. {
  6857. message += $"{first.CnName} 提成 {savePrice}元已导入日付申请 ! \r\n";
  6858. }
  6859. }
  6860. dayPrice.FeeContents = ChiDayPrice;
  6861. dayPrice.SumPrice = ChiDayPrice.Sum(x => x.ItemTotal);
  6862. if (dayPrice.SumPrice != 0)
  6863. {
  6864. var ApiResult = await _daiRep.Add(dayPrice);
  6865. int dailyId = Convert.ToInt32(ApiResult?.Data?.GetType().GetProperty("dailyId").GetValue(ApiResult.Data));
  6866. int sign = Convert.ToInt32(ApiResult?.Data?.GetType().GetProperty("sign").GetValue(ApiResult.Data));
  6867. relevanceSoure.ForEach(x => x.DayOverhead = dailyId);
  6868. var addCount = _sqlSugar.Insertable<Fin_RoyaltyForm>(relevanceSoure).ExecuteCommand();
  6869. }
  6870. _sqlSugar.CommitTran();
  6871. //消息通知
  6872. //await AppNoticeLibrary.DailyPayReminders_Create_ToCaiwuChat(dailyId, sign, QiyeWeChatEnum.CaiWuChat);
  6873. jw = JsonView(true, message);
  6874. }
  6875. catch (Exception ex)
  6876. {
  6877. _sqlSugar.RollbackTran();
  6878. jw = JsonView(false, $" Api Error ({ex.Message})");
  6879. }
  6880. }
  6881. return Ok(jw);
  6882. }
  6883. #endregion
  6884. #region 团组未审核数据
  6885. /// <summary>
  6886. /// 团组未审核费用数据
  6887. /// </summary>
  6888. /// <param name="beginDt"></param>
  6889. /// <param name="endDt"></param>
  6890. /// <param name="teamName"></param>
  6891. /// <returns></returns>
  6892. [HttpGet]
  6893. public async Task<IActionResult> GroupUnAuditFeeList(string beginDt, string endDt, string teamName)
  6894. {
  6895. var jw = JsonView(false);
  6896. bool beginDtBool = DateTime.TryParse(beginDt, out DateTime _beginDt),
  6897. endDtBool = DateTime.TryParse(endDt, out DateTime _endDt);
  6898. if (!beginDtBool && !endDtBool)
  6899. {
  6900. jw.Msg = $"开始或者结束时间格式不正确!";
  6901. return Ok(jw);
  6902. }
  6903. // 主查询
  6904. var query = _sqlSugar.Queryable<Grp_DelegationInfo>()
  6905. .Where(x => x.IsDel == 0 &&
  6906. x.VisitDate >= _beginDt &&
  6907. x.VisitDate <= _endDt);
  6908. if (!string.IsNullOrEmpty(teamName))
  6909. {
  6910. query = query.Where(x => x.TeamName.Contains(teamName));
  6911. var keywords = teamName.Trim()
  6912. .Split(new[] { ' ', ',', ',' }, StringSplitOptions.RemoveEmptyEntries);
  6913. foreach (var keyword in keywords.Where(k => !string.IsNullOrWhiteSpace(k)))
  6914. {
  6915. query = query.Where(x => x.TeamName.Contains(keyword.Trim()));
  6916. }
  6917. }
  6918. var _groupDatas = query
  6919. .OrderByDescending(x => x.CreateTime)
  6920. .ToList();
  6921. var _groupIds = _groupDatas.Select(x => x.Id).ToList();
  6922. if (_groupIds.Count < 1)
  6923. {
  6924. jw.Msg = $"该时间段暂无出访的团组!";
  6925. return Ok(jw);
  6926. }
  6927. var _DailyFeePaymentResult = new tree_Group_DailyFeePaymentResult();
  6928. var dataList = new List<tree_Group_DailyFeePaymentPageListView>();
  6929. var _paymentDatas = _sqlSugar.Queryable<Grp_CreditCardPayment>()
  6930. .Where(x => x.IsDel == 0 &&
  6931. _groupIds.Contains(x.DIId) &&
  6932. x.IsAuditGM == 0
  6933. )
  6934. .ToList();
  6935. _DailyFeePaymentResult.gz = _paymentDatas.Where(it => it.OrbitalPrivateTransfer == 0).Sum(it => ((it.PayMoney * it.DayRate) / 100) * it.PayPercentage); //公转
  6936. _DailyFeePaymentResult.sz = _paymentDatas.Where(it => it.OrbitalPrivateTransfer == 1).Sum(it => ((it.PayMoney * it.DayRate) / 100) * it.PayPercentage); ; //私转
  6937. #region 相关基础数据源
  6938. var userDatas = _sqlSugar.Queryable<Sys_Users>().ToList();
  6939. var setDatas = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
  6940. var countryFeeDatas = _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(it => it.IsDel == 0).ToList();
  6941. //76 酒店预订
  6942. var hotelDatas = _sqlSugar.Queryable<Grp_HotelReservations>()
  6943. .InnerJoin<Grp_CreditCardPayment>((hr, ccp) => hr.Id == ccp.CId &&
  6944. ccp.CTable == 76 &&
  6945. ccp.IsDel == 0
  6946. )
  6947. .Where((hr, ccp) => hr.IsDel == 0 && _groupIds.Contains(hr.DiId) && ccp.IsAuditGM == 0)
  6948. .ToList();
  6949. var hotelContentDatas = _sqlSugar.Queryable<Grp_HotelReservationsContent>()
  6950. .Where(it => it.IsDel == 0 &&
  6951. it.IsPay == 0 &&
  6952. it.Price != 0 &&
  6953. _groupIds.Contains(it.DiId)
  6954. )
  6955. .ToList();
  6956. //79 车/导游地接
  6957. var opDatas = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>()
  6958. .InnerJoin<Grp_CreditCardPayment>((ctggr, ccp) => ctggr.Id == ccp.CId &&
  6959. ccp.CTable == 79 &&
  6960. ccp.IsDel == 0
  6961. )
  6962. .Where((ctggr, ccp) => ctggr.IsDel == 0 && _groupIds.Contains(ctggr.DiId) && ccp.IsAuditGM == 0)
  6963. .ToList();
  6964. // 80 签证
  6965. var visaDatas = _sqlSugar.Queryable<Grp_VisaInfo>()
  6966. .InnerJoin<Grp_CreditCardPayment>((vi, ccp) => vi.Id == ccp.CId &&
  6967. ccp.CTable == 80 &&
  6968. ccp.IsDel == 0
  6969. )
  6970. .Where((vi, ccp) => vi.IsDel == 0 && _groupIds.Contains(vi.DIId) && ccp.IsAuditGM == 0)
  6971. .ToList();
  6972. // 81 邀请/公务活动
  6973. var ioaDatas = _sqlSugar.Queryable<Grp_InvitationOfficialActivities>()
  6974. .InnerJoin<Grp_CreditCardPayment>((ioa, ccp) => ioa.Id == ccp.CId &&
  6975. ccp.CTable == 81 &&
  6976. ccp.IsDel == 0
  6977. )
  6978. .Where((ioa, ccp) => ioa.IsDel == 0 && _groupIds.Contains(ioa.DiId) && ccp.IsAuditGM == 0)
  6979. .ToList();
  6980. // 82 团组客户保险
  6981. var insureDatas = _sqlSugar.Queryable<Grp_Customers>()
  6982. .InnerJoin<Grp_CreditCardPayment>((c, ccp) => c.Id == ccp.CId &&
  6983. ccp.CTable == 82 &&
  6984. ccp.IsDel == 0
  6985. )
  6986. .Where((c, ccp) => c.IsDel == 0 && _groupIds.Contains(c.DiId) && ccp.IsAuditGM == 0)
  6987. .ToList();
  6988. // 85 机票预订
  6989. var airDatas = _sqlSugar.Queryable<Grp_AirTicketReservations>()
  6990. .InnerJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId &&
  6991. ccp.CTable == 85 &&
  6992. ccp.IsDel == 0
  6993. )
  6994. .Where((atr, ccp) => atr.IsDel == 0 && _groupIds.Contains(atr.DIId) && ccp.IsAuditGM == 0)
  6995. .ToList();
  6996. // 98 其他款项
  6997. var otherMoneyDatas = _sqlSugar.Queryable<Grp_DecreasePayments>()
  6998. .InnerJoin<Grp_CreditCardPayment>((dp, ccp) => dp.Id == ccp.CId &&
  6999. ccp.CTable == 98 &&
  7000. ccp.IsDel == 0
  7001. )
  7002. .Where((dp, ccp) => dp.IsDel == 0 && _groupIds.Contains(dp.DiId) && ccp.IsAuditGM == 0)
  7003. .ToList();
  7004. // 285 收款退还
  7005. var refundPaymentDatas = _sqlSugar.Queryable<Fin_PaymentRefundAndOtherMoney>()
  7006. .InnerJoin<Grp_CreditCardPayment>((prom, ccp) => prom.Id == ccp.CId &&
  7007. ccp.CTable == 285 &&
  7008. ccp.IsDel == 0
  7009. )
  7010. .Where((prom, ccp) => prom.IsDel == 0 && _groupIds.Contains(prom.DiId) && ccp.IsAuditGM == 0)
  7011. .ToList();
  7012. // 1015 超支费用
  7013. var extraCostDatas = _sqlSugar.Queryable<Fin_GroupExtraCost>()
  7014. .InnerJoin<Grp_CreditCardPayment>((gec, ccp) => gec.Id == ccp.CId &&
  7015. ccp.CTable == 1015 &&
  7016. ccp.IsDel == 0
  7017. )
  7018. .Where((gec, ccp) => gec.IsDel == 0 && _groupIds.Contains(gec.DiId) && ccp.IsAuditGM == 0)
  7019. .ToList();
  7020. #endregion
  7021. //Expense company
  7022. foreach (var groupInfo in _groupDatas)
  7023. {
  7024. var childList = new List<Group_DailyFeePaymentContentInfolView>();
  7025. var groupPaymentDatas = _paymentDatas.Where(it => groupInfo.Id == it.DIId).ToList();
  7026. if (groupPaymentDatas.Count > 0)
  7027. {
  7028. int rouNumber = 1;
  7029. foreach (var payInfo in groupPaymentDatas)
  7030. {
  7031. string priName = "-";
  7032. string orbitalPrivateTransfer = payInfo.OrbitalPrivateTransfer == 0 ? "公转" : payInfo.OrbitalPrivateTransfer == 1 ? "私转" : "-";
  7033. switch (payInfo.CTable)
  7034. {
  7035. case 76: //76 酒店预订
  7036. priName = $"[费用名称:{hotelDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.HotelName ?? ""}]";
  7037. break;
  7038. case 79: //79 车/导游地接
  7039. var opData = opDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id);
  7040. if (opData != null)
  7041. {
  7042. string area = "";
  7043. bool b = int.TryParse(opData.Area, out int areaId);
  7044. if (b)
  7045. {
  7046. string area1 = countryFeeDatas.Find(it => it.Id == areaId)?.Country ?? "-";
  7047. area = $"{area1}({setDatas.Find(it => it.Id == opData.PriceType)?.Name ?? "-"})";
  7048. }
  7049. else area = opData.Area;
  7050. string opPriName = "-";
  7051. if (!string.IsNullOrEmpty(opData.PriceName)) opPriName = opData.PriceName;
  7052. area += $"({opPriName})";
  7053. if (payInfo.OrbitalPrivateTransfer == 0) //公转
  7054. {
  7055. priName = $"【{orbitalPrivateTransfer}】【导游: {opData.ServiceGuide} 】[费用名称:{area}]";
  7056. }
  7057. else if (payInfo.OrbitalPrivateTransfer == 1) //私转
  7058. {
  7059. priName = $"【{orbitalPrivateTransfer}】【导游:{opData.ServiceGuide}】[费用名称:{area}]";
  7060. }
  7061. }
  7062. break;
  7063. case 80: // 80 签证
  7064. string sql = string.Format("select b.Id,b.Pinyin,b.lastName,b.firstName,b.phone from Grp_TourClientList a, Crm_DeleClient b where a.clientid = b.id and a.isdel = 0 and a.diid = {0}", groupInfo.Id);
  7065. List<SimplClientInfo> arr = _sqlSugar.SqlQueryable<SimplClientInfo>(sql).ToList();
  7066. string visaClientName = visaDatas.Find(it => payInfo.DIId == it.DIId && payInfo.CId == it.Id)?.VisaClient ?? "";
  7067. string clientName = "-";
  7068. if (Regex.Match(visaClientName, @"\d+,?").Value.Length > 0)
  7069. {
  7070. string[] temparr = visaClientName.Split(',');
  7071. string fistrStr = temparr[0];
  7072. int count = temparr.Length;
  7073. int tempId;
  7074. bool success = int.TryParse(fistrStr, out tempId);
  7075. if (success)
  7076. {
  7077. SimplClientInfo tempInfo = arr.FirstOrDefault(s => s.Id == tempId);
  7078. if (tempInfo != null)
  7079. {
  7080. string lastName = AesEncryptionHelper.Decrypt(tempInfo.LastName),
  7081. firstName = AesEncryptionHelper.Decrypt(tempInfo.FirstName);
  7082. if (count > 1)
  7083. {
  7084. clientName = string.Format(@"{0}{1}等{2}人", lastName, firstName, count);
  7085. }
  7086. else
  7087. {
  7088. clientName = string.Format(@"{0}{1}", lastName, firstName);
  7089. }
  7090. }
  7091. }
  7092. else
  7093. {
  7094. clientName = fistrStr;
  7095. }
  7096. }
  7097. priName = $"[费用名称:{clientName}]";
  7098. break;
  7099. case 81: // 81 邀请/公务活动
  7100. priName = $"[费用名称:{ioaDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.Inviter ?? " -"}]";
  7101. break;
  7102. case 82: // 82 团组客户保险
  7103. string bx_sql = string.Format("select b.Id,b.Pinyin,b.lastName,b.firstName,b.phone from Grp_TourClientList a, Crm_DeleClient b where a.clientid = b.id and a.isdel = 0 and a.diid = {0}", groupInfo.Id);
  7104. List<SimplClientInfo> bx_arr = _sqlSugar.SqlQueryable<SimplClientInfo>(bx_sql).ToList();
  7105. string bx_ClientName = insureDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.ClientName ?? "";
  7106. string bx_clientName = "-";
  7107. if (Regex.Match(bx_ClientName, @"\d+,?").Value.Length > 0)
  7108. {
  7109. string[] temparr = bx_ClientName.Split(',');
  7110. string fistrStr = temparr[0];
  7111. int count = temparr.Length;
  7112. int tempId;
  7113. bool success = int.TryParse(fistrStr, out tempId);
  7114. if (success)
  7115. {
  7116. SimplClientInfo tempInfo = bx_arr.FirstOrDefault(s => s.Id == tempId);
  7117. if (tempInfo != null)
  7118. {
  7119. string lastName = AesEncryptionHelper.Decrypt(tempInfo.LastName),
  7120. firstName = AesEncryptionHelper.Decrypt(tempInfo.FirstName);
  7121. if (count > 1)
  7122. {
  7123. bx_clientName = string.Format(@"{0}{1}等{2}人", lastName, firstName, count);
  7124. }
  7125. else
  7126. {
  7127. bx_clientName = string.Format(@"{0}{1}", lastName, firstName);
  7128. }
  7129. }
  7130. }
  7131. else
  7132. {
  7133. bx_clientName = fistrStr;
  7134. }
  7135. }
  7136. //priName = $"[费用名称:{insureDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.ClientName ?? " -"}]";
  7137. priName = $"[费用名称:{bx_clientName}]";
  7138. break;
  7139. case 85: // 85 机票预订
  7140. string flightsCode = airDatas.Find(it => payInfo.DIId == it.DIId && payInfo.CId == it.Id)?.FlightsCode ?? "-";
  7141. string airPayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "-";
  7142. priName = $"{flightsCode}【{airPayType}】";
  7143. break;
  7144. case 98: // 98 其他款项
  7145. priName = $"[费用名称:{otherMoneyDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  7146. break;
  7147. case 285: // 285 收款退还
  7148. priName = $"[费用名称:{refundPaymentDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  7149. break;
  7150. case 1015: // 1015 超支费用
  7151. priName = $"[费用名称:{extraCostDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  7152. break;
  7153. default:
  7154. priName = "";
  7155. break;
  7156. }
  7157. if (payInfo.CTable == 76) //酒店单独处理
  7158. {
  7159. var hotelContents = hotelContentDatas.Where(it => it.HrId == payInfo.CId);
  7160. List<Group_DailyFeePaymentContentInfolView> childInfos = new List<Group_DailyFeePaymentContentInfolView>();
  7161. foreach (var hotelContent in hotelContents)
  7162. {
  7163. string subPriceName = "";
  7164. if (hotelContent.PriceType == 1) subPriceName = "房费";
  7165. else if (hotelContent.PriceType == 2) subPriceName = "早餐";
  7166. else if (hotelContent.PriceType == 3) subPriceName = "地税";
  7167. else if (hotelContent.PriceType == 4) subPriceName = "城市税";
  7168. if (string.IsNullOrEmpty(subPriceName)) subPriceName = priName;
  7169. else subPriceName = $"{priName.Replace("]", "")}-{subPriceName}]";
  7170. string payeeStr1 = string.Format(@" {0},开户行:{1},银行卡号:{2} ",
  7171. string.IsNullOrEmpty(hotelContent.Payee) ? "-" : hotelContent.Payee,
  7172. string.IsNullOrEmpty(hotelContent.OtherBankName) ? "-" : hotelContent.OtherBankName,
  7173. string.IsNullOrEmpty(hotelContent.OtherSideNo) ? "-" : hotelContent.OtherSideNo);
  7174. decimal _PaymentAmount1 = hotelContent.Price;//此次付款金额
  7175. decimal _CNYSubTotalAmount1 = _PaymentAmount1 * hotelContent.Rate;//此次付款金额
  7176. _CNYSubTotalAmount1 = Convert.ToDecimal(_CNYSubTotalAmount1.ToString("#0.00"));
  7177. var childInfo1 = new Group_DailyFeePaymentContentInfolView()
  7178. {
  7179. Id = payInfo.Id,
  7180. HotelSubId = hotelContent.Id,
  7181. Payee = payeeStr1,
  7182. RowNumber = rouNumber,
  7183. Applicant = userDatas.Find(it => it.Id == payInfo.CreateUserId)?.CnName ?? "",
  7184. ApplicantDt = payInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
  7185. PayType = setDatas.Find(it => it.Id == hotelContent.PayDId)?.Name ?? "",
  7186. TransferMark = orbitalPrivateTransfer,
  7187. PriceName = subPriceName,
  7188. ModuleName = setDatas.Find(it => it.Id == payInfo.CTable)?.Name ?? "",
  7189. PayCurrCode = setDatas.Find(it => it.Id == hotelContent.Currency)?.Name ?? "",
  7190. PaymentAmount = _PaymentAmount1,
  7191. PayRate = hotelContent.Rate,
  7192. CNYSubTotalAmount = _CNYSubTotalAmount1,
  7193. AuditStatus = payInfo.IsAuditGM
  7194. };
  7195. string remaksDescription1 = $"【{childInfo1.PayType}】【{childInfo1.ModuleName}】{rouNumber}、[申请人:{childInfo1.Applicant}]{subPriceName}[收款方:{childInfo1.Payee}] {childInfo1.PayCurrCode} {_PaymentAmount1:#0.00}、CNY:{childInfo1.CNYSubTotalAmount:#0.00}(团组:{groupInfo.TeamName})";
  7196. childInfo1.RemaksDescription = remaksDescription1;
  7197. childInfos.Add(childInfo1);
  7198. rouNumber++;
  7199. }
  7200. childList.AddRange(childInfos);
  7201. }
  7202. else
  7203. {
  7204. string payeeStr = string.Format(@" {0},开户行:{1},银行卡号:{2} ",
  7205. string.IsNullOrEmpty(payInfo.Payee) ? "-" : payInfo.Payee,
  7206. string.IsNullOrEmpty(payInfo.OtherBankName) ? "-" : payInfo.OtherBankName,
  7207. string.IsNullOrEmpty(payInfo.OtherSideNo) ? "-" : payInfo.OtherSideNo);
  7208. decimal _PaymentAmount = (payInfo.PayMoney / 100) * payInfo.PayPercentage;//此次付款金额
  7209. decimal _CNYSubTotalAmount = _PaymentAmount * payInfo.DayRate;//此次付款金额
  7210. _CNYSubTotalAmount = Convert.ToDecimal(_CNYSubTotalAmount.ToString("#0.00"));
  7211. var childInfo = new Group_DailyFeePaymentContentInfolView()
  7212. {
  7213. Id = payInfo.Id,
  7214. Payee = payeeStr,
  7215. RowNumber = rouNumber,
  7216. Applicant = userDatas.Find(it => it.Id == payInfo.CreateUserId)?.CnName ?? "",
  7217. ApplicantDt = payInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
  7218. PayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "",
  7219. TransferMark = orbitalPrivateTransfer,
  7220. PriceName = priName,
  7221. ModuleName = setDatas.Find(it => it.Id == payInfo.CTable)?.Name ?? "",
  7222. PayCurrCode = setDatas.Find(it => it.Id == payInfo.PaymentCurrency)?.Name ?? "",
  7223. PaymentAmount = _PaymentAmount,
  7224. PayRate = payInfo.DayRate,
  7225. CNYSubTotalAmount = _CNYSubTotalAmount,
  7226. AuditStatus = payInfo.IsAuditGM
  7227. };
  7228. string remaksDescription = $"【{childInfo.PayType}】【{childInfo.ModuleName}】{rouNumber}、[申请人:{childInfo.Applicant}]{priName}[收款方:{childInfo.Payee}] {childInfo.PayCurrCode} {_PaymentAmount:#0.00}、CNY:{childInfo.CNYSubTotalAmount:#0.00}(团组:{groupInfo.TeamName})";
  7229. childInfo.RemaksDescription = remaksDescription;
  7230. childList.Add(childInfo);
  7231. rouNumber++;
  7232. }
  7233. }
  7234. var companyInfo = ExpenseCompanyByTeamId(groupInfo.TeamDid);
  7235. dataList.Add(new tree_Group_DailyFeePaymentPageListView()
  7236. {
  7237. Id = Guid.NewGuid().ToString("N"),
  7238. GroupName = groupInfo.TeamName,
  7239. CompanyId = companyInfo.Id,
  7240. ConpanyName = companyInfo.ConpanyName,
  7241. CNYTotalAmount = childList.Sum(it => it.CNYSubTotalAmount),
  7242. ChildList = childList,
  7243. });
  7244. }
  7245. }
  7246. var dataList1 = new List<tree_Group_DailyFeePaymentPageListView>();
  7247. //移除没有数据的团
  7248. foreach (var item in dataList)
  7249. {
  7250. if (item.CNYTotalAmount > 0 && item.ChildList.Count > 0)
  7251. {
  7252. dataList1.Add(item);
  7253. }
  7254. }
  7255. _DailyFeePaymentResult.dataList = dataList1;
  7256. jw.Code = StatusCodes.Status200OK;
  7257. jw.Msg = $"操作成功!";
  7258. jw.Data = _DailyFeePaymentResult;
  7259. return Ok(jw);
  7260. }
  7261. #endregion
  7262. }
  7263. }