FinancialController.cs 298 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413
  1. using Aspose.Cells;
  2. using Aspose.Words;
  3. using Aspose.Words.Drawing;
  4. using EyeSoft.Extensions;
  5. using EyeSoft.IO;
  6. using EyeSoft.Runtime.InteropServices;
  7. using FluentValidation;
  8. using MathNet.Numerics.Distributions;
  9. using Microsoft.EntityFrameworkCore.Query.Internal;
  10. using Microsoft.OpenApi.Expressions;
  11. using NPOI.HPSF;
  12. using NPOI.HSSF.UserModel;
  13. using NPOI.SS.Formula.Functions;
  14. using NPOI.SS.Formula.PTG;
  15. using NPOI.SS.UserModel;
  16. using NPOI.Util;
  17. using NPOI.XSSF.UserModel;
  18. using OASystem.API.OAMethodLib;
  19. using OASystem.API.OAMethodLib.File;
  20. using OASystem.API.OAMethodLib.QiYeWeChatAPI.AppNotice;
  21. using OASystem.Domain.Dtos.Financial;
  22. using OASystem.Domain.Dtos.Groups;
  23. using OASystem.Domain.Entities.Customer;
  24. using OASystem.Domain.Entities.Financial;
  25. using OASystem.Domain.Entities.Groups;
  26. using OASystem.Domain.ViewModels.Financial;
  27. using OASystem.Domain.ViewModels.Groups;
  28. using OASystem.Infrastructure.Repositories.Financial;
  29. using OASystem.Infrastructure.Repositories.Groups;
  30. using OfficeOpenXml;
  31. using Org.BouncyCastle.Math;
  32. using SqlSugar.Extensions;
  33. using System.Collections;
  34. using System.ComponentModel.Design;
  35. using System.Data;
  36. using System.Data.OleDb;
  37. using System.Diagnostics;
  38. using System.Globalization;
  39. using System.IO.Compression;
  40. using System.IO.Pipelines;
  41. using System.Linq.Expressions;
  42. namespace OASystem.API.Controllers
  43. {
  44. /// <summary>
  45. /// 财务模块
  46. /// </summary>
  47. [Route("api/[controller]/[action]")]
  48. [ApiController]
  49. public class FinancialController : ControllerBase
  50. {
  51. private readonly IMapper _mapper;
  52. private readonly IConfiguration _config;
  53. private readonly SqlSugarClient _sqlSugar;
  54. private readonly HttpClient _httpClient;
  55. private readonly SetDataTypeRepository _setDataTypeRep;
  56. private readonly SetDataRepository _setDataRep;
  57. private readonly DailyFeePaymentRepository _daiRep; //日付申请仓库
  58. private readonly TeamRateRepository _teamRateRep; //团组汇率仓库
  59. private readonly ForeignReceivablesRepository _ForForeignReceivablesRep; //对外收款账单仓库
  60. private readonly ProceedsReceivedRepository _proceedsReceivedRep; //已收款项仓库
  61. private readonly PaymentRefundAndOtherMoneyRepository _paymentRefundAndOtherMoneyRep; //收款退还与其他款项 仓库
  62. private readonly DelegationInfoRepository _delegationInfoRep; //团组信息 仓库
  63. /// <summary>
  64. /// 初始化
  65. /// </summary>
  66. public FinancialController(IMapper mapper, IConfiguration configuration, DailyFeePaymentRepository daiRep, SqlSugarClient sqlSugar, SetDataTypeRepository setDataTypeRep,
  67. TeamRateRepository teamRateRep, ForeignReceivablesRepository ForForeignReceivablesRep, ProceedsReceivedRepository proceedsReceivedRep,
  68. PaymentRefundAndOtherMoneyRepository paymentRefundAndOtherMoneyRep, HttpClient httpClient, DelegationInfoRepository delegationInfoRep, SetDataRepository setDataRep)
  69. {
  70. _mapper = mapper;
  71. _config = configuration;
  72. _daiRep = daiRep;
  73. _sqlSugar = sqlSugar;
  74. _setDataTypeRep = setDataTypeRep;
  75. _teamRateRep = teamRateRep;
  76. _ForForeignReceivablesRep = ForForeignReceivablesRep;
  77. _proceedsReceivedRep = proceedsReceivedRep;
  78. _paymentRefundAndOtherMoneyRep = paymentRefundAndOtherMoneyRep;
  79. _httpClient = httpClient;
  80. _delegationInfoRep = delegationInfoRep;
  81. _setDataRep = setDataRep;
  82. }
  83. #region 日付申请
  84. /// <summary>
  85. /// 获取日付申请 基础数据源
  86. /// </summary>
  87. /// <param name="dto"> 日付申请 分页 dto</param>
  88. /// <returns></returns>
  89. [HttpPost]
  90. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  91. public async Task<IActionResult> PostPageSearchDailyPaymentPriceTypeData(PortDtoBase dto)
  92. {
  93. var result = await _daiRep.GetPagePriceTypeData(dto);
  94. if (result == null || result.Code != 0)
  95. {
  96. return Ok(JsonView(false, result.Msg));
  97. }
  98. var data = result.Data;
  99. return Ok(JsonView(data));
  100. }
  101. /// <summary>
  102. /// 获取日付申请 基础数据源 - 转账表识
  103. /// </summary>
  104. /// <param name="dto"> 日付申请 分页 dto</param>
  105. /// <returns></returns>
  106. [HttpPost]
  107. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  108. public async Task<IActionResult> GetSearchDailyPaymentPriceTypeAddData(PortDtoBase dto)
  109. {
  110. var result = await _daiRep.GetPriceTypeAddData(dto);
  111. if (result == null || result.Code != 0)
  112. {
  113. return Ok(JsonView(false, result.Msg));
  114. }
  115. var data = result.Data;
  116. return Ok(JsonView(data));
  117. }
  118. /// <summary>
  119. /// 日付申请 Page Search
  120. /// </summary>
  121. /// <param name="dto"> 日付申请 分页 dto</param>
  122. /// <returns></returns>
  123. [HttpPost]
  124. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  125. public async Task<IActionResult> PostPageSearchDailyPaymentList(PageDailyFeePaymentDto dto)
  126. {
  127. var result = await _daiRep.GetPageSearchAll(dto);
  128. if (result == null || result.Code != 0)
  129. {
  130. return Ok(JsonView(false, result.Msg));
  131. }
  132. var data = result.Data;
  133. if (data == null)
  134. {
  135. return Ok(JsonView(false, result.Msg));
  136. }
  137. return Ok(JsonView(data));
  138. }
  139. /// <summary>
  140. /// 日付申请 Single Search By Id
  141. /// </summary>
  142. /// <param name="dto"></param>
  143. /// <returns></returns>
  144. [HttpPost]
  145. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  146. public async Task<IActionResult> PostSearchDailyPaymentInfo(SearchDailyFeePaymentDto dto)
  147. {
  148. var result = await _daiRep.GetSearchById(dto);
  149. if (result == null || result.Code != 0)
  150. {
  151. return Ok(JsonView(false, result.Msg));
  152. }
  153. return Ok(JsonView(result.Data));
  154. }
  155. /// <summary>
  156. /// 日付申请 添加
  157. /// </summary>
  158. /// <param name="dto"> 日付申请 添加 dto</param>
  159. /// <returns></returns>
  160. [HttpPost]
  161. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  162. public async Task<IActionResult> PostAddDailyPayment(AddDailyFeePaymentDto dto)
  163. {
  164. var result = await _daiRep.Add(dto);
  165. if (result == null || result.Code != 0)
  166. {
  167. return Ok(JsonView(false, result.Msg));
  168. }
  169. #region 应用推送
  170. try
  171. {
  172. int dailyId = result.Data.GetType().GetProperty("dailyId").GetValue(result.Data, null);
  173. int sign = result.Data.GetType().GetProperty("sign").GetValue(result.Data, null);
  174. await AppNoticeLibrary.DailyPayReminders_Create_ToCaiwuChat(dailyId, sign, QiyeWeChatEnum.CaiWuChat);
  175. }
  176. catch (Exception ex)
  177. {
  178. }
  179. #endregion
  180. return Ok(JsonView(true));
  181. }
  182. /// <summary>
  183. /// 日付申请 Update
  184. /// </summary>
  185. /// <param name="dto"> 日付申请 修改 dto</param>
  186. /// <returns></returns>
  187. [HttpPost]
  188. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  189. public async Task<IActionResult> PostEditDailyPayment(EditDailyFeePaymentDto dto)
  190. {
  191. var result = await _daiRep.Edit(dto);
  192. if (result == null || result.Code != 0)
  193. {
  194. return Ok(JsonView(false, result.Msg));
  195. }
  196. #region 应用推送
  197. try
  198. {
  199. int dailyId = result.Data.GetType().GetProperty("dailyId").GetValue(result.Data, null);
  200. int sign = result.Data.GetType().GetProperty("sign").GetValue(result.Data, null);
  201. await AppNoticeLibrary.DailyPayReminders_Create_ToCaiwuChat(dailyId, sign, QiyeWeChatEnum.CaiWuChat);
  202. }
  203. catch (Exception ex)
  204. {
  205. }
  206. #endregion
  207. return Ok(JsonView(true));
  208. }
  209. /// <summary>
  210. /// 日付申请 Del
  211. /// </summary>
  212. /// <param name="dto"> 日付申请 删除 dto</param>
  213. /// <returns></returns>
  214. [HttpPost]
  215. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  216. public async Task<IActionResult> PostDelDailyPayment(DelDailyFeePaymentDto dto)
  217. {
  218. _sqlSugar.BeginTran();
  219. var result = await _daiRep.Del(dto);
  220. //删除日付关联表
  221. var delCount = _sqlSugar.Updateable<Fin_RoyaltyForm>()
  222. .Where(x => x.IsDel == 0 && x.DayOverhead == dto.Id)
  223. .SetColumns(x => new Fin_RoyaltyForm
  224. {
  225. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  226. DeleteUserId = dto.UserId,
  227. IsDel = 1
  228. }).ExecuteCommand();
  229. _sqlSugar.CommitTran();
  230. if (result == null || result.Code != 0)
  231. {
  232. return Ok(JsonView(false, result.Msg));
  233. }
  234. return Ok(JsonView(true));
  235. }
  236. /// <summary>
  237. /// 日付申请 财务审核
  238. /// </summary>
  239. /// <param name="dto"> dto </param>
  240. /// <returns></returns>
  241. [HttpPost]
  242. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  243. public async Task<IActionResult> PostDelDailyPaymentAudit(DP_AuditStatusDto dto)
  244. {
  245. var result = await _daiRep.DailyPaymentAudit(dto);
  246. if (result == null || result.Code != 0)
  247. {
  248. return Ok(JsonView(false, result.Msg));
  249. }
  250. return Ok(JsonView(true));
  251. }
  252. /// <summary>
  253. /// 日付申请 Single Excel Download
  254. /// </summary>
  255. /// <param name="dto"> dto </param>
  256. /// <returns></returns>
  257. [HttpPost]
  258. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  259. public async Task<IActionResult> PostExcelDailyPaymentDownload(SearchDailyFeePaymentDto dto)
  260. {
  261. if (dto.PortType == 1 || dto.PortType == 2)
  262. {
  263. Fin_DailyFeePaymentInfolView feeData = new Fin_DailyFeePaymentInfolView();
  264. string feeSql = string.Format(@"Select * From Fin_DailyFeePayment
  265. Where IsDel=0 And Id = {0} ", dto.Id);
  266. feeData = await _sqlSugar.SqlQueryable<Fin_DailyFeePaymentInfolView>(feeSql).FirstAsync();
  267. if (feeData == null)
  268. {
  269. return Ok(JsonView(false, "暂无数据!"));
  270. }
  271. string feeContentSql = string.Format(@"Select * From Fin_DailyFeePaymentContent
  272. Where IsDel=0 And DFPId = {0} ", dto.Id);
  273. feeData.FeeContents = await _sqlSugar.SqlQueryable<Fin_DailyFeePaymentContentInfolView>(feeContentSql).ToListAsync();
  274. if (feeData != null)
  275. {
  276. string userName = string.Empty;
  277. string userSql = string.Format("Select * From Sys_Users Where Id={0} And Isdel = {1}", feeData.CreateUserId, 0);
  278. Sys_Users user = await _sqlSugar.SqlQueryable<Sys_Users>(userSql).FirstAsync();
  279. if (user != null) { userName = user.CnName; }
  280. var setData = _setDataTypeRep.QueryDto<Sys_SetData, Fin_DailyFeePaymentPagePriceSubTypeView>().ToList();
  281. //48人员费用 49办公费用 50 销售费用 51 其他费用 55 大运会
  282. var priceSubTypeData = setData.Where(s => s.STid == 55).ToList();
  283. Dictionary<string, object> pairs = new Dictionary<string, object>();
  284. List<DataTable> datas = new List<DataTable>();
  285. //if (priceSubTypeData.Where(s => s.Id == feeData.PriceTypeId).ToList().Count() > 0)//大运会专属模板
  286. //{
  287. // //AsposeHelper.ExpertExcelToModel("日常费用付款申请模板-大运会数据.xls", "DailyPayment", "大运会所有日常费用付款申请.xls",
  288. // // pairs, datas);
  289. //}
  290. //else //日付常规模板
  291. //{
  292. pairs.Clear();
  293. pairs.Add("Opertor", userName);
  294. pairs.Add("DateTime", feeData.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
  295. pairs.Add("FAuditStatus", feeData.FAuditDesc);
  296. pairs.Add("MAuditStatus", feeData.MAuditDesc);
  297. pairs.Add("SumPrice", feeData.SumPrice);
  298. DataTable data = AsposeHelper.ListToDataTable("DailyFeePayment", feeData.FeeContents);
  299. datas.Clear();
  300. datas.Add(data);
  301. string fileName = string.Format("{0}-日常费用付款申请.xlsx", feeData.Instructions);
  302. string msg = AsposeHelper.ExpertExcelToModel("日常费用付款申请模板.xlsx", "DailyPayment", fileName, pairs, datas);
  303. return Ok(JsonView(true, msg));
  304. //}
  305. }
  306. else
  307. {
  308. return Ok(JsonView(false, "暂无数据!"));
  309. }
  310. }
  311. return Ok(JsonView(true));
  312. }
  313. /// <summary>
  314. /// 日付申请
  315. /// 总经理未审核 日付信息
  316. /// </summary>
  317. /// <param name="dto"> dto </param>
  318. /// <returns></returns>
  319. [HttpGet]
  320. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  321. public async Task<IActionResult> DailyPaymentGMUnAudited()
  322. {
  323. var dailyInfos = await _sqlSugar.Queryable<Fin_DailyFeePayment>()
  324. .LeftJoin<Sys_Users>((dfp, u) => dfp.CreateUserId == u.Id)
  325. .Where(dfp => dfp.IsDel == 0 &&
  326. //dfp.FAudit == 1 &&
  327. //dfp.IsPay == 0 &&
  328. dfp.MAudit == 0
  329. )
  330. .OrderBy(dfp => dfp.CreateTime, OrderByType.Desc)
  331. //.OrderBy(dfp => dfp.FAudit, OrderByType.Desc)
  332. .Select((dfp, u) => new
  333. {
  334. id = dfp.Id,
  335. amountName = dfp.Instructions,
  336. amount = dfp.SumPrice,
  337. fAuditStatus = dfp.FAudit == 1 ? "审核通过" :
  338. dfp.FAudit == 2 ? "审核未通过" : "未审核",
  339. fAuditDate = dfp.FAuditDate,
  340. applicant = u.CnName,
  341. applicantDate = dfp.CreateTime
  342. })
  343. //.ToListAsync();
  344. .CountAsync();
  345. //int count = dailyInfos.Count;
  346. return Ok(JsonView(true,"查询成功", dailyInfos));
  347. }
  348. #endregion
  349. #region 团组提成
  350. /// <summary>
  351. /// 提成 Page Search
  352. /// </summary>
  353. /// <param name="dto"> 提成 分页 dto</param>
  354. /// <returns></returns>
  355. [HttpPost]
  356. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  357. public async Task<IActionResult> PostPageSearchCommissionList(GroupCommissionDto dto)
  358. {
  359. var data = await GroupCommission.GetCommissionPageList(dto);
  360. return Ok(JsonView(data.Data));
  361. }
  362. #endregion
  363. #region 团组汇率
  364. /// <summary>
  365. /// 团组汇率 Select数据源(团组列,汇率列)
  366. /// </summary>
  367. /// <param name="dto"></param>
  368. /// <returns></returns>
  369. [HttpPost]
  370. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  371. public async Task<IActionResult> GetGroupRateDataSources(TeamRateDto dto)
  372. {
  373. try
  374. {
  375. //迁移数据更新团组汇率
  376. //Result teamRateData1 = await _teamRateRep.GetGroupRateChangeData();
  377. //var data = await _teamRateRep.PostGroupTeamRateHot();
  378. Stopwatch stopwatch = Stopwatch.StartNew();
  379. GroupNameDto groupNameDto = new GroupNameDto() { PortType = dto.PortType };
  380. var groups = await _delegationInfoRep.GetGroupNameList(groupNameDto);
  381. List<CurrencyHot> _currData = new List<CurrencyHot>();
  382. string currData = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>("GroupTeamCurrencyData");//string 取
  383. if (!string.IsNullOrEmpty(currData))
  384. {
  385. _currData = JsonConvert.DeserializeObject<List<CurrencyHot>>(currData);
  386. }
  387. else
  388. {
  389. _currData = await _teamRateRep.PostGroupTeamRateHot();
  390. //过期时间 25 Hours
  391. TimeSpan ts = DateTime.Now.AddHours(25).TimeOfDay;
  392. await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync("GroupTeamCurrencyData", JsonConvert.SerializeObject(_currData), ts);
  393. }
  394. var _data = new { GroupData = groups.Data, TeamRateData = _currData };
  395. stopwatch.Stop();
  396. return Ok(JsonView(true, $"查询成功!耗时:{stopwatch.ElapsedMilliseconds / 1000}s", _data));
  397. }
  398. catch (Exception ex)
  399. {
  400. return Ok(JsonView(false, ex.Message));
  401. }
  402. }
  403. ///// <summary>
  404. ///// 团组汇率 changge
  405. ///// </summary>
  406. ///// <returns></returns>
  407. //[HttpPost]
  408. //[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  409. //public async Task<IActionResult> ChangeGroupRateInfo()
  410. //{
  411. // try
  412. // {
  413. // Result teamRateData = await _teamRateRep.GetGroupRateChangeData();
  414. // if (teamRateData.Code != 0)
  415. // {
  416. // return Ok(JsonView(false, teamRateData.Msg));
  417. // }
  418. // return Ok(JsonView(true, teamRateData.Msg, teamRateData.Data));
  419. // }
  420. // catch (Exception ex)
  421. // {
  422. // return Ok(JsonView(false, ex.Message));
  423. // throw;
  424. // }
  425. //}
  426. /// <summary>
  427. /// 团组汇率 Select汇率详情
  428. /// </summary>
  429. /// <param name="dto"></param>
  430. /// <returns></returns>
  431. [HttpPost]
  432. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  433. public async Task<IActionResult> GetGroupRateInfo(TeamRateInfoDto dto)
  434. {
  435. try
  436. {
  437. Result teamRateData = await _teamRateRep.GetGroupRateInfoByDiid(dto);
  438. if (teamRateData.Code != 0)
  439. {
  440. return Ok(JsonView(false, teamRateData.Msg));
  441. }
  442. return Ok(JsonView(true, teamRateData.Msg, teamRateData.Data));
  443. }
  444. catch (Exception ex)
  445. {
  446. return Ok(JsonView(false, ex.Message));
  447. throw;
  448. }
  449. }
  450. /// <summary>
  451. /// 团组汇率 添加 or 更新
  452. /// </summary>
  453. /// <param name="dto"></param>
  454. /// <returns></returns>
  455. [HttpPost]
  456. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  457. public async Task<IActionResult> PostGroupRateUpdate(TeamRateUpdateDto dto)
  458. {
  459. try
  460. {
  461. Result teamRateData = await _teamRateRep.PostGroupRateUpdate(dto);
  462. if (teamRateData.Code != 0)
  463. {
  464. return Ok(JsonView(false, teamRateData.Msg));
  465. }
  466. return Ok(JsonView(true, teamRateData.Msg, teamRateData.Data));
  467. }
  468. catch (Exception ex)
  469. {
  470. return Ok(JsonView(false, ex.Message));
  471. throw;
  472. }
  473. }
  474. #endregion
  475. #region 对外收款账单 关联已收款项
  476. /// <summary>
  477. /// 对外收款账单 Select数据源(团组名,币种,汇款方式)
  478. /// 关联已收款项
  479. /// </summary>
  480. /// <param name="dto"></param>
  481. /// <returns></returns>
  482. [HttpPost]
  483. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  484. public async Task<IActionResult> GetForeignReceivablesDataSources(ForeignReceivablesDataSourcesDto dto)
  485. {
  486. return Ok(await _ForForeignReceivablesRep.GetDataSource(dto));
  487. }
  488. /// <summary>
  489. /// 对外收款账单
  490. /// 账单详情
  491. /// 关联已收款项
  492. /// </summary>
  493. /// <param name="dto"></param>
  494. /// <returns></returns>
  495. [HttpPost]
  496. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  497. public async Task<IActionResult> GetGroupReceivablesInfoByDiId(ForForeignReceivablesInfoDto dto)
  498. {
  499. try
  500. {
  501. Result ffrData = await _ForForeignReceivablesRep.GetGroupReceivablesInfoByDiId(dto);
  502. if (ffrData.Code != 0)
  503. {
  504. return Ok(JsonView(false, ffrData.Msg));
  505. }
  506. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  507. }
  508. catch (Exception ex)
  509. {
  510. return Ok(JsonView(false, ex.Message));
  511. throw;
  512. }
  513. }
  514. /// <summary>
  515. /// 对外收款账单
  516. /// 账单 删除
  517. /// 关联已收款项
  518. /// </summary>
  519. /// <param name="dto"></param>
  520. /// <returns></returns>
  521. [HttpPost]
  522. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  523. public async Task<IActionResult> PostGroupReceivablesDel(DelForForeignReceivablesInfoDto dto)
  524. {
  525. try
  526. {
  527. Result ffrData = await _ForForeignReceivablesRep._Del(dto);
  528. if (ffrData.Code != 0)
  529. {
  530. return Ok(JsonView(false, ffrData.Msg));
  531. }
  532. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  533. }
  534. catch (Exception ex)
  535. {
  536. return Ok(JsonView(false, ex.Message));
  537. throw;
  538. }
  539. }
  540. /// <summary>
  541. /// 对外收款账单
  542. /// 添加 And 更新
  543. /// 关联已收款项
  544. /// </summary>
  545. /// <param name="dto"></param>
  546. /// <returns></returns>
  547. [HttpPost]
  548. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  549. public async Task<IActionResult> PostReceivablesOperate(ForeignReceivablesAddAndUpdateDto dto)
  550. {
  551. try
  552. {
  553. Result ffrData = await _ForForeignReceivablesRep.PostReceivablesOperate(dto);
  554. if (ffrData.Code != 0)
  555. {
  556. return Ok(JsonView(false, ffrData.Msg));
  557. }
  558. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  559. }
  560. catch (Exception ex)
  561. {
  562. return Ok(JsonView(false, ex.Message));
  563. throw;
  564. }
  565. }
  566. /// <summary>
  567. /// 已收款项
  568. /// 账单 删除
  569. /// 关联已收款项
  570. /// </summary>
  571. /// <param name="dto"></param>
  572. /// <returns></returns>
  573. [HttpPost]
  574. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  575. public async Task<IActionResult> PostAmountReceivedDel(ProceedsReceivedDelDto dto)
  576. {
  577. try
  578. {
  579. Result ffrData = await _proceedsReceivedRep._Del(dto);
  580. if (ffrData.Code != 0)
  581. {
  582. return Ok(JsonView(false, ffrData.Msg));
  583. }
  584. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  585. }
  586. catch (Exception ex)
  587. {
  588. return Ok(JsonView(false, ex.Message));
  589. throw;
  590. }
  591. }
  592. /// <summary>
  593. /// 已收款项
  594. /// 添加 And 更新
  595. /// 关联已收款项
  596. /// </summary>
  597. /// <param name="dto"></param>
  598. /// <returns></returns>
  599. [HttpPost]
  600. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  601. public async Task<IActionResult> PostAmountReceivedOperate(ProceedsReceivedDto dto)
  602. {
  603. try
  604. {
  605. Result ffrData = await _proceedsReceivedRep.PostAmountReceivedOperate(dto);
  606. if (ffrData.Code != 0)
  607. {
  608. return Ok(JsonView(false, ffrData.Msg));
  609. }
  610. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  611. }
  612. catch (Exception ex)
  613. {
  614. return Ok(JsonView(false, ex.Message));
  615. throw;
  616. }
  617. }
  618. /// <summary>
  619. /// 财务 已收款项
  620. /// 分配已收款项至 应收项下
  621. /// 关联已收款项
  622. /// </summary>
  623. /// <param name="dto"></param>
  624. /// <returns></returns>
  625. [HttpPost]
  626. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  627. public async Task<IActionResult> PostAllocateAmountReceived(AllocateAmountReceivedDto dto)
  628. {
  629. try
  630. {
  631. Result ffrData = await _proceedsReceivedRep.PostAllocateAmountReceived(dto);
  632. if (ffrData.Code != 0)
  633. {
  634. return Ok(JsonView(false, ffrData.Msg));
  635. }
  636. return Ok(JsonView(true));
  637. }
  638. catch (Exception ex)
  639. {
  640. return Ok(JsonView(false, ex.Message));
  641. throw;
  642. }
  643. }
  644. ///// <summary>
  645. ///// 财务 收款账单
  646. ///// 导出Word(北京,四川)
  647. ///// </summary>
  648. ///// <param name="dto"></param>
  649. ///// <returns></returns>
  650. //[HttpPost]
  651. //[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  652. //public async Task<IActionResult> PostAccountReceivableWordExport(AccountReceivableWordExportDto dto)
  653. //{
  654. // try
  655. // {
  656. // //模板处理
  657. // string typeName = string.Empty;
  658. // if (dto.TemplateType == 1) //四川
  659. // {
  660. // typeName = "四川";
  661. // }
  662. // else if (dto.TemplateType == 2) //北京
  663. // {
  664. // typeName = "北京";
  665. // }
  666. // else return Ok(JsonView(false,"请选择正确的模板类型!"));
  667. // string wordTempName = string.Format("收款账单({0})模板.doc", typeName);
  668. // }
  669. // catch (Exception ex)
  670. // {
  671. // return Ok(JsonView(false, ex.Message));
  672. // }
  673. //}
  674. #endregion
  675. #region 对外收款账单
  676. /// <summary>
  677. /// 对外收款账单
  678. /// 数据源
  679. /// </summary>
  680. /// <param name="dto"></param>
  681. /// <returns></returns>
  682. [HttpPost]
  683. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  684. public async Task<IActionResult> PostGroupReceivablesDataSource(ForeignReceivablesDataSourcesDto dto)
  685. {
  686. return Ok(await _ForForeignReceivablesRep.PostDataSource(dto));
  687. }
  688. /// <summary>
  689. /// 对外收款账单
  690. /// 账单详情
  691. /// </summary>
  692. /// <param name="dto"></param>
  693. /// <returns></returns>
  694. [HttpPost]
  695. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  696. public async Task<IActionResult> PostGroupReceivablesInfoByDiId(ForForeignReceivablesNewDto dto)
  697. {
  698. return Ok(await _ForForeignReceivablesRep.PostGroupReceivablesInfoByDiId(dto));
  699. }
  700. /// <summary>
  701. /// 对外收款账单
  702. /// 添加 And 更新
  703. /// </summary>
  704. /// <param name="dto"></param>
  705. /// <returns></returns>
  706. [HttpPost]
  707. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  708. public async Task<IActionResult> PostReceivablesSave(ForeignReceivablesSaveDto dto)
  709. {
  710. return Ok(await _ForForeignReceivablesRep.PostReceivablesSave(dto));
  711. }
  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> PostReceivablesAudit(FeeAuditDto dto)
  721. {
  722. return Ok(await _ForForeignReceivablesRep.FeeAudit(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> PostReceivablesDel(ForeignReceivablesDelDto dto)
  733. {
  734. try
  735. {
  736. Result ffrData = await _ForForeignReceivablesRep.PostReceivablesDel(dto);
  737. if (ffrData.Code != 0)
  738. {
  739. return Ok(JsonView(false, ffrData.Msg));
  740. }
  741. return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
  742. }
  743. catch (Exception ex)
  744. {
  745. return Ok(JsonView(false, ex.Message));
  746. throw;
  747. }
  748. }
  749. /// <summary>
  750. /// 已收账单
  751. /// File Downloasd
  752. /// Init
  753. /// </summary>
  754. /// <param name="dto"></param>
  755. /// <returns></returns>
  756. [HttpPost]
  757. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  758. public async Task<IActionResult> PostReceivablesFeilDownloadInit()
  759. {
  760. return Ok(JsonView(true, "操作成功!", new List<dynamic> {
  761. new { Id = 1, Name = "生成收款单(四川)" },
  762. new { Id = 2, Name = "生成收款单(北京)" },
  763. new { Id = 3, Name = "汇款账单" }
  764. }
  765. ));
  766. }
  767. /// <summary>
  768. /// 已收账单
  769. /// File Downloasd
  770. /// </summary>
  771. /// <param name="dto"></param>
  772. /// <returns></returns>
  773. [HttpPost]
  774. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  775. public async Task<IActionResult> PostReceivablesFeilDownload(ForeignReceivablesFeilDownloadDto dto)
  776. {
  777. try
  778. {
  779. if (dto.DiId < 1)
  780. {
  781. return Ok(JsonView(false, "请传入有效DiId参数!"));
  782. }
  783. if (dto.FileType < 1 || dto.FileType > 3)
  784. {
  785. return Ok(JsonView(false, "请传入有效FileType参数! 1 生成收款单(四川) 2 生成收款单(北京) 3 汇款账单"));
  786. }
  787. var _DelegationInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0 && it.Id == dto.DiId).First();
  788. if (_DelegationInfo == null)
  789. {
  790. return Ok(JsonView(false, "暂无团组信息!!"));
  791. }
  792. if (dto.FileType == 1 || dto.FileType == 2)
  793. {
  794. var _ForeignReceivables = _sqlSugar.Queryable<Fin_ForeignReceivables>().Where(it => it.IsDel == 0 && it.Diid == dto.DiId).ToList();
  795. if (_ForeignReceivables.Count < 1)
  796. {
  797. return Ok(JsonView(false, "暂无收款信息!!"));
  798. }
  799. string tempName = "";
  800. if (dto.FileType == 1) tempName = $"收款账单(四川)模板.docx";
  801. else if (dto.FileType == 2) tempName = $"收款账单(北京)模板.docx";
  802. string tempPath = AppSettingsHelper.Get("WordBasePath") + $"ForeignReceivables/Temp/{tempName}";
  803. //载入模板
  804. Document doc = new Document(tempPath);
  805. DocumentBuilder builder = new DocumentBuilder(doc);
  806. #region 替换Word模板书签内容
  807. //这里可以创建个DataTable循环添加书签的值,这里提示一下就不多做修改了
  808. //付款方
  809. if (doc.Range.Bookmarks["To"] != null)
  810. {
  811. Bookmark mark = doc.Range.Bookmarks["To"];
  812. mark.Text = _ForeignReceivables[0].To == null ? "" : _ForeignReceivables[0].To.ToString();
  813. }
  814. //付款方电话
  815. if (doc.Range.Bookmarks["ToTel"] != null)
  816. {
  817. Bookmark mark = doc.Range.Bookmarks["ToTel"];
  818. mark.Text = _ForeignReceivables[0].ToTel == null ? "" : _ForeignReceivables[0].ToTel.ToString();
  819. }
  820. //导出时间
  821. if (doc.Range.Bookmarks["Date"] != null)
  822. {
  823. Bookmark mark = doc.Range.Bookmarks["Date"];
  824. mark.Text = DateTime.Now.ToString("yyyy-MM-dd");
  825. }
  826. //注
  827. if (doc.Range.Bookmarks["Attention"] != null)
  828. {
  829. Bookmark mark = doc.Range.Bookmarks["Attention"];
  830. mark.Text = _ForeignReceivables[0].Attention == null ? "" : _ForeignReceivables[0].Attention.ToString();
  831. }
  832. //团队名称
  833. if (doc.Range.Bookmarks["Team"] != null)
  834. {
  835. Bookmark mark = doc.Range.Bookmarks["Team"];
  836. mark.Text = _DelegationInfo.VisitCountry == null ? "" : _DelegationInfo.VisitCountry.Replace("|", "、").ToString();
  837. }
  838. //付款日期
  839. if (doc.Range.Bookmarks["PayDate"] != null)
  840. {
  841. Bookmark mark = doc.Range.Bookmarks["PayDate"];
  842. mark.Text = _ForeignReceivables[0].PayDate == null ? "" : Convert.ToDateTime(_ForeignReceivables[0].PayDate).ToString("yyyy年MM月dd日");
  843. }
  844. decimal sumPrice = 0;
  845. //各项费用
  846. if (doc.Range.Bookmarks["PayItemContent"] != null)
  847. {
  848. string items = "";
  849. foreach (var fr in _ForeignReceivables)
  850. {
  851. var currInfo = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == fr.Currency).First();
  852. items += $"{fr.PriceName} {currInfo?.Name} {fr.Price.ToString("#0.00")} * {fr.Count} {fr.Unit} * {fr.Rate}.................. RMB {fr.ItemSumPrice.ToString("#0.00")}\n";
  853. sumPrice += fr.ItemSumPrice;
  854. }
  855. Bookmark mark = doc.Range.Bookmarks["PayItemContent"];
  856. mark.Text = items;
  857. }
  858. //合计
  859. if (doc.Range.Bookmarks["Total"] != null)
  860. {
  861. Bookmark mark = doc.Range.Bookmarks["Total"];
  862. mark.Text = sumPrice.ToString("#0.00");
  863. }
  864. #endregion
  865. //文件名
  866. string strFileName = _DelegationInfo.TeamName + "-收款账单.docx";
  867. //去水印
  868. new Aspose.Words.License().SetLicense(new MemoryStream(Convert.FromBase64String(AsposeHelper.asposeKey)));
  869. doc.Save(AppSettingsHelper.Get("WordBasePath") + "ForeignReceivables/File/" + strFileName);
  870. string url = AppSettingsHelper.Get("WordBaseUrl") + "Office/Word/ForeignReceivables/File/" + strFileName;
  871. return Ok(JsonView(true, "成功", new { Url = url }));
  872. }
  873. else if (dto.FileType == 3) //汇款通知
  874. {
  875. var _EnterExitCosts = _sqlSugar.Queryable<Grp_EnterExitCost>().Where(it => it.IsDel == 0 && it.DiId == dto.DiId).First();
  876. var _DayAndCosts = _sqlSugar.Queryable<Grp_DayAndCost>().Where(it => it.IsDel == 0 && it.DiId == dto.DiId && it.NationalTravelFeeId > 0).ToList();
  877. if (_EnterExitCosts == null)
  878. {
  879. return Ok(JsonView(false, "该团组未填写出入境费用;"));
  880. }
  881. var _cityFee = _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(it => it.IsDel == 0).ToList();
  882. foreach (var item in _DayAndCosts)
  883. {
  884. var cityInfo = _cityFee.Where(it => it.Id == item.NationalTravelFeeId).FirstOrDefault();
  885. if (cityInfo != null)
  886. {
  887. if (cityInfo.City.Contains("全部城市") || cityInfo.City.Contains("其他城市") || cityInfo.City.Contains("所有城市"))
  888. {
  889. item.Place = cityInfo.Country;
  890. }
  891. else item.Place = cityInfo.City;
  892. }
  893. }
  894. //数据源
  895. List<Grp_DayAndCost> dac1 = _DayAndCosts.Where(it => it.Type == 1).ToList(); //住宿费
  896. List<Grp_DayAndCost> dac2 = _DayAndCosts.Where(it => it.Type == 2).ToList(); //伙食费
  897. List<Grp_DayAndCost> dac3 = _DayAndCosts.Where(it => it.Type == 3).ToList(); //公杂费
  898. List<Grp_DayAndCost> dac4 = _DayAndCosts.Where(it => it.Type == 4).ToList(); //培训费
  899. //币种Data
  900. var currData = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0 && it.STid == 66).ToList();
  901. var DeleClientList = _sqlSugar.Queryable<Grp_TourClientList>()
  902. .LeftJoin<Crm_DeleClient>((tcl, dc) => tcl.ClientId == dc.Id && dc.IsDel == 0)
  903. .LeftJoin<Crm_CustomerCompany>((tcl, dc, cc) => dc.CrmCompanyId == cc.Id && dc.IsDel == 0)
  904. .Where((tcl, dc, cc) => tcl.IsDel == 0 && tcl.DiId == dto.DiId)
  905. .Select((tcl, dc, cc) => new
  906. {
  907. Name = dc.LastName + dc.FirstName,
  908. Sex = dc.Sex,
  909. Birthday = dc.BirthDay,
  910. Company = cc.CompanyFullName.Replace("\n",""),
  911. Job = dc.Job,
  912. AirType = tcl.ShippingSpaceTypeId
  913. })
  914. .ToList();
  915. if (DeleClientList.Count < 1)
  916. {
  917. return Ok(JsonView(false, "暂无团组成员,请先填写团组成员!!!"));
  918. }
  919. var _ClientNames = DeleClientList.Select(x => x.Name).ToList();
  920. var _GroupClient = DeleClientList.GroupBy(x => x.Company).ToList();
  921. Dictionary<string, string> bookmarkArr = null;
  922. string tempPath = AppSettingsHelper.Get("WordBasePath") + $"ForeignReceivables/Temp/汇款通知.docx";
  923. //载入模板
  924. Document doc = new Document(tempPath);
  925. DocumentBuilder builder = null;
  926. List<string> filesToZip = new List<string>();
  927. foreach (var ClientItem in _GroupClient) //遍历单位
  928. {
  929. doc = new Document(tempPath);
  930. builder = new DocumentBuilder(doc);
  931. Paragraph paragraph = new Paragraph(doc);
  932. bookmarkArr = new Dictionary<string, string>();
  933. bookmarkArr.Add("titleClientUnit", ClientItem.Key); //title单位
  934. bookmarkArr.Add("ClientUnit", ClientItem.Key); //单位
  935. bookmarkArr.Add("VisitStartDate", _DelegationInfo.VisitStartDate.ToString("yyyy年MM月dd日"));//出发日期
  936. bookmarkArr.Add("name", string.Join(",", ClientItem.Select(x => x.Name).ToArray()).TrimEnd(','));//全部人员信息
  937. bookmarkArr.Add("VisitCountry", _DelegationInfo.VisitCountry.Replace("|", "、"));//出访国家
  938. bookmarkArr.Add("dayTime", DateTime.Now.ToString("yyyy年MM月dd日"));//今天日期
  939. var ClientItemList = ClientItem.ToList();
  940. string UsersTop = string.Empty;//word中人员以及金额
  941. decimal WordAllPrice = 0.00M;
  942. //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(),
  943. // 6, 3 + dac1.Where(x=>!string.IsNullOrWhiteSpace(x.Place)).Select(x=>(Convert.ToDecimal(x.SubTotal) / Convert.ToDecimal(x.Cost)).ToString().Length).Max() };
  944. //遍历人员
  945. for (int i = 0; i < ClientItemList.Count(); i++)
  946. {
  947. Dictionary<string, string> TeableBookmarkArr = new Dictionary<string, string>();
  948. var client = ClientItemList[i]; //每个人员
  949. var firstName = ClientItemList[i].Name;
  950. /*
  951. * 457 头等舱
  952. * 458 公务舱
  953. * 460 经济舱
  954. */
  955. decimal airPrice = 0.00M;
  956. string airName = string.Empty;
  957. if (client.AirType == 457)
  958. {
  959. airName = $"头等舱";
  960. airPrice = _EnterExitCosts.AirTD;
  961. }else if (client.AirType == 458)
  962. {
  963. airName = $"公务舱";
  964. airPrice = _EnterExitCosts.AirGW;
  965. }else if (client.AirType == 460)
  966. {
  967. airName = $"经济舱";
  968. airPrice = _EnterExitCosts.AirJJ;
  969. }
  970. //计算费用总和
  971. decimal AllPrice = airPrice + _EnterExitCosts.CityTranffic + dac1.Sum(x => x.SubTotal) + dac2.Sum(x => x.SubTotal) +
  972. dac3.Sum(x => x.SubTotal) + dac4.Sum(x => x.SubTotal) + _EnterExitCosts.Visa + _EnterExitCosts.Safe +
  973. +_EnterExitCosts.YiMiao + _EnterExitCosts.YiMiao + _EnterExitCosts.Ticket + _EnterExitCosts.Service;
  974. WordAllPrice += AllPrice;
  975. UsersTop += firstName + "出访费用为¥" + AllPrice.ToString("#0.00") + "元、";
  976. TeableBookmarkArr.Add("jp", airPrice.ToString("#0.00") + " 元"); //机票金额
  977. TeableBookmarkArr.Add("cs", _EnterExitCosts.CityTranffic.ToString("#0.00") + " 元"); //城市交通费用
  978. TeableBookmarkArr.Add("zs", dac1.Sum(x => Convert.ToDecimal(x.SubTotal)).ToString("#0.00") + " 元"); //住宿费
  979. string zsinfo = string.Empty;
  980. string hsinfo = string.Empty;
  981. string gzinfo = string.Empty;
  982. List<string> placeArr = new List<string>();
  983. Aspose.Words.Tables.Table FirstTable = (Aspose.Words.Tables.Table)doc.GetChild(NodeType.Table, 0, true);
  984. Aspose.Words.Tables.Table ChildTable = (Aspose.Words.Tables.Table)FirstTable.GetChild(NodeType.Table, 0, true);
  985. Aspose.Words.Tables.Table ChildTable1 = (Aspose.Words.Tables.Table)FirstTable.GetChild(NodeType.Table, 1, true);
  986. Aspose.Words.Tables.Table ChildTable2 = (Aspose.Words.Tables.Table)FirstTable.GetChild(NodeType.Table, 2, true);
  987. int rowIndex = 0;
  988. foreach (var item in dac1)
  989. {
  990. if (string.IsNullOrWhiteSpace(item.Place))
  991. {
  992. continue;
  993. }
  994. if (placeArr.Contains(item.Place))
  995. {
  996. continue;
  997. }
  998. else
  999. {
  1000. placeArr.Add(item.Place);
  1001. }
  1002. if (!string.IsNullOrWhiteSpace(item.Place))
  1003. {
  1004. if (rowIndex > ChildTable.Rows.Count - 1)
  1005. {
  1006. var chitableRow = ChildTable.LastRow.Clone(true);
  1007. ChildTable.AppendChild(chitableRow);
  1008. }
  1009. int days = dac1.FindAll(x => x.Place == item.Place).Count();
  1010. SetCells(ChildTable, doc, rowIndex, 0, item.Place);
  1011. SetCells(ChildTable, doc, rowIndex, 1, days + "晚");
  1012. string currencyCode = currData.Find(it => it.Id == item.Currency)?.Remark ?? "Unknown";
  1013. SetCells(ChildTable, doc, rowIndex, 2, item.Cost.ToString("#0.00") + currencyCode + "/晚");
  1014. SetCells(ChildTable, doc, rowIndex, 3, " 汇率" + (item.SubTotal / item.Cost).ToString("#0.00"));
  1015. SetCells(ChildTable, doc, rowIndex, 4, "CNY " + item.SubTotal + "\r\n");
  1016. rowIndex++;
  1017. zsinfo += item.Place + " " + days + "晚 " + item.Cost.ToString("#0.00") + currencyCode + "/晚" + " 汇率" + (item.SubTotal / item.Cost).ToString("#0.0000") + " CNY " + item.SubTotal * days + "\r\n";
  1018. }
  1019. }
  1020. placeArr.Clear();
  1021. rowIndex = 0;
  1022. foreach (var item in dac2)
  1023. {
  1024. if (string.IsNullOrWhiteSpace(item.Place))
  1025. {
  1026. continue;
  1027. }
  1028. if (placeArr.Contains(item.Place))
  1029. {
  1030. continue;
  1031. }
  1032. else
  1033. {
  1034. placeArr.Add(item.Place);
  1035. }
  1036. if (!string.IsNullOrWhiteSpace(item.Place))
  1037. {
  1038. if (rowIndex > ChildTable1.Rows.Count - 1)
  1039. {
  1040. var chitableRow = ChildTable1.LastRow.Clone(true);
  1041. ChildTable1.AppendChild(chitableRow);
  1042. }
  1043. int days = dac2.FindAll(x => x.Place == item.Place).Count();
  1044. SetCells(ChildTable1, doc, rowIndex, 0, item.Place);
  1045. SetCells(ChildTable1, doc, rowIndex, 1, days + "天");
  1046. string currencyCode = currData.Find(it => it.Id == item.Currency)?.Remark ?? "Unknown";
  1047. SetCells(ChildTable1, doc, rowIndex, 2, item.Cost.ToString("#0.00") + currencyCode + "/天");
  1048. SetCells(ChildTable1, doc, rowIndex, 3, " 汇率" + (item.SubTotal / item.Cost).ToString("#0.00"));
  1049. SetCells(ChildTable1, doc, rowIndex, 4, "CNY " + item.SubTotal);
  1050. rowIndex++;
  1051. hsinfo += item.Place + " " + days + "天 " + item.Cost.ToString("#0.00") + currencyCode + "/天" + " 汇率" + (item.SubTotal / item.Cost).ToString("#0.0000") + " CNY " + item.SubTotal * days + "\r\n";
  1052. }
  1053. }
  1054. placeArr.Clear();
  1055. rowIndex = 0;
  1056. foreach (var item in dac3)
  1057. {
  1058. if (string.IsNullOrWhiteSpace(item.Place))
  1059. {
  1060. continue;
  1061. }
  1062. if (placeArr.Contains(item.Place))
  1063. {
  1064. continue;
  1065. }
  1066. else
  1067. {
  1068. placeArr.Add(item.Place);
  1069. }
  1070. if (!string.IsNullOrWhiteSpace(item.Place))
  1071. {
  1072. if (rowIndex > ChildTable2.Rows.Count - 1)
  1073. {
  1074. var chitableRow = ChildTable2.LastRow.Clone(true);
  1075. ChildTable2.AppendChild(chitableRow);
  1076. }
  1077. int days = dac3.FindAll(x => x.Place == item.Place).Count();
  1078. SetCells(ChildTable2, doc, rowIndex, 0, item.Place);
  1079. SetCells(ChildTable2, doc, rowIndex, 1, days + "天");
  1080. string currencyCode = currData.Find(it => it.Id == item.Currency)?.Remark ?? "Unknown";
  1081. SetCells(ChildTable2, doc, rowIndex, 2, item.Cost.ToString("#0.00") + currencyCode + "/天");
  1082. SetCells(ChildTable2, doc, rowIndex, 3, " 汇率" + (item.SubTotal / item.Cost).ToString("#0.00"));
  1083. SetCells(ChildTable2, doc, rowIndex, 4, "CNY " + item.SubTotal + "\r\n");
  1084. rowIndex++;
  1085. gzinfo += item.Place + " " + days + "天 " + item.Cost.ToString("#0.00") + currencyCode + "/天" + " 汇率" + (item.SubTotal / item.Cost).ToString("#0.00") + " CNY " + item.SubTotal * days + "\r\n";
  1086. }
  1087. }
  1088. placeArr.Clear();
  1089. TeableBookmarkArr.Add("zsinfo", zsinfo); //住宿费详情
  1090. TeableBookmarkArr.Add("hs", dac2.Sum(x => Convert.ToDecimal(x.SubTotal)).ToString("#0.00") + " 元"); //伙食费
  1091. TeableBookmarkArr.Add("hsinfo", hsinfo); //伙食费详情
  1092. TeableBookmarkArr.Add("gz", dac3.Sum(x => Convert.ToDecimal(x.SubTotal)).ToString("#0.00") + " 元"); //公杂费
  1093. TeableBookmarkArr.Add("gzinfo", gzinfo); //公杂费详情
  1094. string otherFeestr = "";
  1095. decimal otherFee = 0.00M;
  1096. if (_EnterExitCosts.Visa > 0.00M)
  1097. {
  1098. otherFee += _EnterExitCosts.Visa;
  1099. otherFeestr += $"签证费{_EnterExitCosts.Visa.ToString("#0.00")}元、";
  1100. }
  1101. if (_EnterExitCosts.YiMiao > 0.00M)
  1102. {
  1103. otherFee += _EnterExitCosts.YiMiao;
  1104. otherFeestr += $"疫苗费{_EnterExitCosts.YiMiao.ToString("#0.00")}元、";
  1105. }
  1106. if (_EnterExitCosts.HeSuan > 0.00M)
  1107. {
  1108. otherFee += _EnterExitCosts.HeSuan;
  1109. otherFeestr += $"核酸检测费{_EnterExitCosts.HeSuan.ToString("#0.00")}元、";
  1110. }
  1111. if (_EnterExitCosts.Safe > 0.00M)
  1112. {
  1113. otherFee += _EnterExitCosts.Safe;
  1114. otherFeestr += $"保险费{_EnterExitCosts.Safe.ToString("#0.00")}元、";
  1115. }
  1116. if (_EnterExitCosts.Ticket > 0.00M)
  1117. {
  1118. otherFee += _EnterExitCosts.Ticket;
  1119. otherFeestr += $"参展门票费{_EnterExitCosts.Ticket.ToString("#0.00")}元、";
  1120. }
  1121. if (otherFeestr.Length > 0)
  1122. {
  1123. otherFeestr = otherFeestr.Substring(0, otherFeestr.Length - 1);
  1124. otherFeestr += "等费用";
  1125. }
  1126. TeableBookmarkArr.Add("qt", otherFee.ToString("#0.00") + " 元");//其他费用
  1127. TeableBookmarkArr.Add("qtinfo", otherFeestr);//其他费用第二列
  1128. TeableBookmarkArr.Add("fw", _EnterExitCosts.Service.ToString("#0.00") + "元/人");//服务费
  1129. TeableBookmarkArr.Add("AllPrice", AllPrice.ToString("#0.00") + "元/人");//表格合计费用
  1130. TeableBookmarkArr.Add("title", $"费用清单-{airName}({firstName})");
  1131. foreach (var book in TeableBookmarkArr.Keys)
  1132. {
  1133. if (doc.Range.Bookmarks[book] != null)
  1134. {
  1135. Bookmark mark = doc.Range.Bookmarks[book];
  1136. mark.Text = TeableBookmarkArr[book];
  1137. }
  1138. }
  1139. if (i != ClientItemList.Count - 1)
  1140. {
  1141. builder.PageSetup.Orientation = Aspose.Words.Orientation.Portrait;
  1142. Aspose.Words.Tables.Table table = (Aspose.Words.Tables.Table)doc.GetChild(NodeType.Table, 0, true);
  1143. table.ParentNode.InsertAfter(paragraph, table);
  1144. var CloneTable = (Aspose.Words.Tables.Table)table.Clone(true);
  1145. table.ParentNode.InsertAfter(CloneTable, paragraph);
  1146. }
  1147. TeableBookmarkArr.Clear();
  1148. }
  1149. bookmarkArr.Add("VisitPrice", WordAllPrice.ToString());//出访费用总额
  1150. bookmarkArr.Add("CnAllPrice", WordAllPrice.ConvertCNYUpper());//出访费用总额中文
  1151. bookmarkArr.Add("namesPrice", UsersTop.TrimEnd('、'));//各人员出访费用 付辰同志出访费用为¥73,604.8元
  1152. foreach (var book in bookmarkArr.Keys)
  1153. {
  1154. if (doc.Range.Bookmarks[book] != null)
  1155. {
  1156. Bookmark mark = doc.Range.Bookmarks[book];
  1157. mark.Text = bookmarkArr[book];
  1158. }
  1159. }
  1160. //MemoryStream outSteam = new MemoryStream();
  1161. string filsPath = AppSettingsHelper.Get("WordBasePath") + $"ForeignReceivables/File/{ClientItem.Key.Replace("\n", "")}.docx";
  1162. //去水印
  1163. new Aspose.Words.License().SetLicense(new MemoryStream(Convert.FromBase64String(AsposeHelper.asposeKey)));
  1164. doc.Save(filsPath);
  1165. filesToZip.Add(filsPath);
  1166. //streams.Add(ClientItem.Key + ".docx", outSteam.ToArray());
  1167. }
  1168. //文件名
  1169. string zipFileName = _DelegationInfo.TeamName + "-收款账单.zip";
  1170. string zipPath = $"ForeignReceivables/File/{_DelegationInfo.TeamName}-收款账单{DateTime.Now.ToString("yyyyMMddHHmmss")}.zip";
  1171. try
  1172. {
  1173. using (var zip = ZipFile.Open(AppSettingsHelper.Get("WordBasePath") + zipPath, ZipArchiveMode.Create))
  1174. {
  1175. foreach (var file in filesToZip)
  1176. {
  1177. zip.CreateEntryFromFile(file, Path.GetFileName(file));
  1178. }
  1179. }
  1180. }
  1181. catch (Exception ex)
  1182. {
  1183. return Ok(JsonView(false, ex.Message));
  1184. }
  1185. string url = AppSettingsHelper.Get("WordBaseUrl") + $"Office/Word/{zipPath}";
  1186. return Ok(JsonView(true, "成功", new { Url = url }));
  1187. }
  1188. return Ok(JsonView(false, "操作失败!"));
  1189. }
  1190. catch (Exception ex)
  1191. {
  1192. return Ok(JsonView(false, ex.Message));
  1193. }
  1194. }
  1195. private void SetCells(Aspose.Words.Tables.Table table, Document doc, int rows, int cells, string val)
  1196. {
  1197. //获取table中的某个单元格,从0开始
  1198. Aspose.Words.Tables.Cell lshCell = table.Rows[rows].Cells[cells];
  1199. //将单元格中的第一个段落移除
  1200. lshCell.FirstParagraph.Remove();
  1201. //新建一个段落
  1202. Paragraph p = new Paragraph(doc);
  1203. var r = new Run(doc, val);
  1204. r.Font.Size = 8;
  1205. //把设置的值赋给之前新建的段落
  1206. p.AppendChild(r);
  1207. //将此段落加到单元格内
  1208. lshCell.AppendChild(p);
  1209. }
  1210. /// <summary>
  1211. /// 已收账单
  1212. /// 提示导入出入境报价费用
  1213. /// </summary>
  1214. /// <param name="groupId"></param>
  1215. /// <returns></returns>
  1216. [HttpPost]
  1217. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1218. public async Task<IActionResult> PostReceivablesImportFee(int groupId)
  1219. {
  1220. if (groupId < 1) return Ok(JsonView(false, "请传入有效的GroupId参数!"));
  1221. var _EnterExitCosts =await _sqlSugar.Queryable<Grp_EnterExitCost>()
  1222. .Where(it => it.IsDel == 0 && it.DiId == groupId)
  1223. .FirstAsync();
  1224. var _DayAndCosts =await _sqlSugar.Queryable<Grp_DayAndCost>()
  1225. .Where(it => it.IsDel == 0 && it.DiId == groupId)
  1226. .ToListAsync();
  1227. if (_EnterExitCosts == null) return Ok(JsonView(false, "该团组未填写出入境费用;"));
  1228. //数据源
  1229. var stayDatas = _DayAndCosts.Where(it => it.Type == 1).ToList(); //住宿费
  1230. var mealDatas = _DayAndCosts.Where(it => it.Type == 2).ToList(); //伙食费
  1231. var miscellaneousDatas = _DayAndCosts.Where(it => it.Type == 3).ToList(); //公杂费
  1232. var tainDatas = _DayAndCosts.Where(it => it.Type == 4).ToList(); //培训费
  1233. //筛选 陪同人员 = 1
  1234. var groupClientList = await _sqlSugar.Queryable<Grp_TourClientList>()
  1235. .LeftJoin<Crm_DeleClient>((tcl, dc) => tcl.ClientId == dc.Id)
  1236. .LeftJoin<Crm_CustomerCompany>((tcl, dc, cc) => dc.CrmCompanyId == cc.Id)
  1237. .LeftJoin<Sys_SetData>((tcl, dc, cc, sd) => tcl.ShippingSpaceTypeId == sd.Id)
  1238. .Where(tcl => tcl.IsDel == 0 &&
  1239. tcl.DiId == groupId &&
  1240. tcl.IsAccompany == 1
  1241. )
  1242. .Select((tcl, dc, cc, sd) => new
  1243. {
  1244. DiId = tcl.DiId,
  1245. CompanyId = cc.Id,
  1246. CompanyName = cc.CompanyFullName,
  1247. ClienId = dc.Id,
  1248. ClientName = dc.FirstName + dc.LastName,
  1249. SpaceId = tcl.ShippingSpaceTypeId,
  1250. SpaceName = sd.Name
  1251. })
  1252. .ToListAsync();
  1253. if (groupClientList.Count < 1) return Ok(JsonView(false, "该团组未填写接团客户名单;"));
  1254. decimal domesticFeeTotal =0.00M, //境内费用
  1255. economyClassFeeTotal = 0.00M, //经济舱费用
  1256. businessClassFeeTotal = 0.00M, //公务舱费用
  1257. firstClassFeeTotal = 0.00M, //头等舱费用
  1258. stayFeeTotal = 0.00M, //住宿费
  1259. mealsFeeTotal = 0.00M, //餐食费
  1260. miscellaneousFeeTotal = 0.00M, //公杂费
  1261. tainFeeTotal = 0.00M; //培训费
  1262. //境内费用(其他费用)
  1263. if (_EnterExitCosts.ChoiceOne == 1) domesticFeeTotal = _EnterExitCosts.InsidePay;
  1264. //住宿费
  1265. if (_EnterExitCosts.ChoiceThree == 1) stayFeeTotal = stayDatas.Sum(x => x.SubTotal);
  1266. //伙食费
  1267. if (_EnterExitCosts.ChoiceFour == 1) mealsFeeTotal = mealDatas.Sum(x => x.SubTotal);
  1268. //公杂费
  1269. if (_EnterExitCosts.ChoiceFive == 1) miscellaneousFeeTotal = miscellaneousDatas.Sum(x => x.SubTotal);
  1270. //培训费
  1271. if (_EnterExitCosts.ChoiceSix == 1) tainFeeTotal = tainDatas.Sum(x => x.SubTotal);
  1272. decimal otherFeeTotal = domesticFeeTotal + stayFeeTotal + mealsFeeTotal + miscellaneousFeeTotal + tainFeeTotal;
  1273. //国际旅费合计
  1274. //经济舱
  1275. if (_EnterExitCosts.SumJJC == 1) economyClassFeeTotal = _EnterExitCosts.OutsideJJPay + otherFeeTotal;
  1276. //公务舱
  1277. if (_EnterExitCosts.SumGWC == 1) businessClassFeeTotal = _EnterExitCosts.OutsideGWPay + otherFeeTotal;
  1278. //头等舱
  1279. if (_EnterExitCosts.SumTDC == 1) firstClassFeeTotal = _EnterExitCosts.OutsideTDPay + otherFeeTotal;
  1280. var groupClientListGroup = groupClientList.GroupBy(x => x.CompanyId);
  1281. var _view = new List<ProceedsReceivedNewView>();
  1282. foreach (var item in groupClientListGroup)
  1283. {
  1284. string companyName = item.FirstOrDefault().CompanyName;
  1285. var airTicketGroup = item.GroupBy(x => x.SpaceId);
  1286. foreach (var airTicket in airTicketGroup)
  1287. {
  1288. int quantity = airTicket.Count();
  1289. if (quantity > 0)
  1290. {
  1291. decimal price = 0.00M;
  1292. string spaceName = airTicket.FirstOrDefault()?.SpaceName ?? string.Empty;
  1293. if (spaceName.Equals("经济舱")) price = economyClassFeeTotal;
  1294. else if (spaceName.Equals("公务舱")) price = businessClassFeeTotal;
  1295. else if (spaceName.Equals("头等舱")) price = firstClassFeeTotal;
  1296. if (price > 0)
  1297. {
  1298. decimal itemTotal = price * quantity;
  1299. _view.Add(new ProceedsReceivedNewView()
  1300. {
  1301. Id = 0,
  1302. CreateTime = DateTime.Now,
  1303. Diid = groupId,
  1304. PriceName = $"{companyName}-{spaceName}",
  1305. Price = price,
  1306. Count = quantity,
  1307. Unit = "人",
  1308. ItemSumPrice = itemTotal,
  1309. Currency = 836,
  1310. Rate = 1.0000M,
  1311. AddingWay = 2,
  1312. Remark = "由出入境费用导入费用",
  1313. });
  1314. }
  1315. }
  1316. }
  1317. }
  1318. return Ok(JsonView(true, "操作成功", _view));
  1319. }
  1320. #endregion
  1321. #region 已收款项
  1322. /// <summary>
  1323. /// 已收款项
  1324. /// 查询
  1325. /// </summary>
  1326. /// <param name="dto"></param>
  1327. /// <returns></returns>
  1328. [HttpPost]
  1329. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1330. public async Task<IActionResult> PostAmountReceived(AmountReceivedDto dto)
  1331. {
  1332. try
  1333. {
  1334. if (dto == null)
  1335. {
  1336. return Ok(JsonView(false, "参数不能为空!"));
  1337. }
  1338. Result ffrData = await _proceedsReceivedRep.PostAmountReceived(dto.DiId);
  1339. dynamic data = null;
  1340. if (dto.PortType == 1)
  1341. {
  1342. if (ffrData.Code != 0)
  1343. {
  1344. return Ok(JsonView(false, ffrData.Msg));
  1345. }
  1346. data = ffrData.Data;
  1347. }
  1348. else if (dto.PortType == 2)
  1349. {
  1350. if (ffrData.Code != 0)
  1351. {
  1352. return Ok(JsonView(false, ffrData.Msg));
  1353. }
  1354. data = ffrData.Data;
  1355. }
  1356. else if (dto.PortType == 2)
  1357. {
  1358. if (ffrData.Code != 0)
  1359. {
  1360. return Ok(JsonView(false, ffrData.Msg));
  1361. }
  1362. data = ffrData.Data;
  1363. }
  1364. else
  1365. {
  1366. return Ok(JsonView(false, "请选择正确的端口号!"));
  1367. }
  1368. return Ok(JsonView(true, "操作成功!", data));
  1369. }
  1370. catch (Exception ex)
  1371. {
  1372. return Ok(JsonView(false, ex.Message));
  1373. }
  1374. }
  1375. /// <summary>
  1376. /// 已收款项
  1377. /// Add Or Edit
  1378. /// </summary>
  1379. /// <param name="dto"></param>
  1380. /// <returns></returns>
  1381. [HttpPost]
  1382. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1383. public async Task<IActionResult> PostAmountReceivedAddOrEdit(AmountReceivedAddOrEditDto dto)
  1384. {
  1385. try
  1386. {
  1387. if (dto == null)
  1388. {
  1389. return Ok(JsonView(false, "参数不能为空!"));
  1390. }
  1391. Result ffrData = await _proceedsReceivedRep.PostAmountReceivedAddOrEditDto(dto);
  1392. if (dto.PortType == 1)
  1393. {
  1394. if (ffrData.Code != 0)
  1395. {
  1396. return Ok(JsonView(false, ffrData.Msg));
  1397. }
  1398. }
  1399. else if (dto.PortType == 2)
  1400. {
  1401. if (ffrData.Code != 0)
  1402. {
  1403. return Ok(JsonView(false, ffrData.Msg));
  1404. }
  1405. }
  1406. else if (dto.PortType == 2)
  1407. {
  1408. if (ffrData.Code != 0)
  1409. {
  1410. return Ok(JsonView(false, ffrData.Msg));
  1411. }
  1412. }
  1413. else
  1414. {
  1415. return Ok(JsonView(false, "请选择正确的端口号!"));
  1416. }
  1417. return Ok(JsonView(true, "操作成功!"));
  1418. }
  1419. catch (Exception ex)
  1420. {
  1421. return Ok(JsonView(false, ex.Message));
  1422. }
  1423. }
  1424. /// <summary>
  1425. /// 已收款项
  1426. /// Del
  1427. /// </summary>
  1428. /// <param name="dto"></param>
  1429. /// <returns></returns>
  1430. [HttpPost]
  1431. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1432. public async Task<IActionResult> PostAmountReceived_Del(AmountReceivedDelDto dto)
  1433. {
  1434. try
  1435. {
  1436. if (dto == null)
  1437. {
  1438. return Ok(JsonView(false, "参数不能为空!"));
  1439. }
  1440. Result ffrData = await _proceedsReceivedRep.PostAmountReceivedDel(dto);
  1441. if (ffrData.Code != 0)
  1442. {
  1443. return Ok(JsonView(false, ffrData.Msg));
  1444. }
  1445. return Ok(JsonView(true, "操作成功!"));
  1446. }
  1447. catch (Exception ex)
  1448. {
  1449. return Ok(JsonView(false, ex.Message));
  1450. }
  1451. }
  1452. #endregion
  1453. #region 收款退还与其他款项 --> 收款退还
  1454. /// <summary>
  1455. /// 收款退还与其他款项
  1456. /// 查询 根据团组Id
  1457. /// </summary>
  1458. /// <param name="dto"></param>
  1459. /// <returns></returns>
  1460. [HttpPost]
  1461. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1462. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyItemByDiId(PaymentRefundAndOtherMoneyItemByDiIdDto dto)
  1463. {
  1464. try
  1465. {
  1466. if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
  1467. if (dto.PageId <= 0) return Ok(JsonView(false, "请传入正确的的页面Id!"));
  1468. if (dto.UserId <= 0) return Ok(JsonView(false, "请传入正确的的员工Id!"));
  1469. #region 页面功能权限处理
  1470. PageFunAuthViewBase pageFunAuth = new PageFunAuthViewBase();
  1471. pageFunAuth = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1472. if (pageFunAuth.CheckAuth == 0)
  1473. {
  1474. return Ok(JsonView(false, "您没有当前页面查询权限!"));
  1475. }
  1476. #endregion
  1477. Result _result = await _paymentRefundAndOtherMoneyRep._ItemByDiId(dto.DiId);
  1478. if (dto.PortType == 1 || dto.PortType == 2 || dto.PortType == 3) //1 Web 2 Android 3 Ios
  1479. {
  1480. if (_result.Code != 0)
  1481. {
  1482. return Ok(JsonView(false, _result.Msg));
  1483. }
  1484. var data = new
  1485. {
  1486. PageFuncAuth = pageFunAuth,
  1487. Data = _result.Data
  1488. };
  1489. return Ok(JsonView(true, "操作成功!", data));
  1490. }
  1491. else
  1492. {
  1493. return Ok(JsonView(false, "请输入正确的端口号! 1 Web 2 Android 3 Ios;"));
  1494. }
  1495. }
  1496. catch (Exception ex)
  1497. {
  1498. return Ok(JsonView(false, ex.Message));
  1499. }
  1500. }
  1501. /// <summary>
  1502. /// 收款退还与其他款项
  1503. /// 删除
  1504. /// </summary>
  1505. /// <param name="dto"></param>
  1506. /// <returns></returns>
  1507. [HttpPost]
  1508. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1509. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyDel(PaymentRefundAndOtherMoneyDelDto dto)
  1510. {
  1511. try
  1512. {
  1513. if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
  1514. if (dto.PageId <= 0) return Ok(JsonView(false, "请传入正确的的页面Id!"));
  1515. if (dto.UserId <= 0) return Ok(JsonView(false, "请传入正确的的员工Id!"));
  1516. PageFunAuthViewBase pageFunAuth = new PageFunAuthViewBase();
  1517. #region 页面功能权限处理
  1518. pageFunAuth = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1519. #endregion
  1520. if (pageFunAuth.DeleteAuth == 0)
  1521. {
  1522. return Ok(JsonView(false, "您没有当前页面删除权限!"));
  1523. }
  1524. Result _result = await _paymentRefundAndOtherMoneyRep._Del(dto);
  1525. if (_result.Code != 0)
  1526. {
  1527. return Ok(JsonView(false, _result.Msg));
  1528. }
  1529. return Ok(JsonView(true, "操作成功!"));
  1530. }
  1531. catch (Exception ex)
  1532. {
  1533. return Ok(JsonView(false, ex.Message));
  1534. }
  1535. }
  1536. /// <summary>
  1537. /// 收款退还与其他款项
  1538. /// Info Data Source
  1539. /// </summary>
  1540. /// <param name="dto"></param>
  1541. /// <returns></returns>
  1542. [HttpPost]
  1543. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1544. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyInfoDataSource(PortDtoBase dto)
  1545. {
  1546. try
  1547. {
  1548. Result _result = await _paymentRefundAndOtherMoneyRep._InfoDataSource(dto);
  1549. if (_result.Code != 0)
  1550. {
  1551. return Ok(JsonView(false, _result.Msg));
  1552. }
  1553. return Ok(JsonView(true, "查询成功!", _result.Data));
  1554. }
  1555. catch (Exception ex)
  1556. {
  1557. return Ok(JsonView(false, ex.Message));
  1558. }
  1559. }
  1560. /// <summary>
  1561. /// 收款退还与其他款项
  1562. /// Info
  1563. /// </summary>
  1564. /// <param name="dto"></param>
  1565. /// <returns></returns>
  1566. [HttpPost]
  1567. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1568. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyInfo(PaymentRefundAndOtherMoneyInfoDto dto)
  1569. {
  1570. if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
  1571. var view = await _paymentRefundAndOtherMoneyRep._Info(dto);
  1572. return Ok(view);
  1573. }
  1574. /// <summary>
  1575. /// 收款退还与其他款项 --> 收款退还(只保留人名币)
  1576. /// 操作(Add Or Edit)
  1577. /// </summary>
  1578. /// <param name="dto"></param>
  1579. /// <returns></returns>
  1580. [HttpPost]
  1581. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1582. public async Task<IActionResult> PostPaymentRefundAndOtherMoneyAddOrEdit(PaymentRefundAndOtherMoneyAddOrEditDto dto)
  1583. {
  1584. if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
  1585. if (dto.PageId <= 0) return Ok(JsonView(false, "请传入正确的的页面Id!"));
  1586. if (dto.UserId <= 0) return Ok(JsonView(false, "请传入正确的的员工Id!"));
  1587. #region 页面功能权限处理
  1588. PageFunAuthViewBase pageFunAuth = new PageFunAuthViewBase();
  1589. pageFunAuth = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1590. #endregion
  1591. if (dto.Status == 1) //add
  1592. {
  1593. if (pageFunAuth.AddAuth == 0) return Ok(JsonView(false, "您没有当前页面添加权限!"));
  1594. }
  1595. else if (dto.Status == 2) //edit
  1596. {
  1597. if (pageFunAuth.EditAuth == 0) return Ok(JsonView(false, "您没有当前页面编辑权限!"));
  1598. }
  1599. else return Ok(JsonView(false, "请输入正确的操作状态! 1 添加 2 修改!"));
  1600. return Ok(await _paymentRefundAndOtherMoneyRep._AddOrEdit(dto));
  1601. }
  1602. #endregion
  1603. #region 应收报表
  1604. /// <summary>
  1605. /// 应收报表
  1606. /// 查询 根据日期范围
  1607. /// </summary>
  1608. /// <param name="dto"></param>
  1609. /// <returns></returns>
  1610. [HttpPost]
  1611. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1612. public async Task<IActionResult> PostSyntheticalReceivableByDateRange(PostSyntheticalReceivableByDateRangeDto dto)
  1613. {
  1614. string sqlWhere = " Where di.IsDel=0 ";
  1615. #region 验证
  1616. if (string.IsNullOrEmpty(dto.beginDt) && string.IsNullOrEmpty(dto.endDt))
  1617. {
  1618. return Ok(JsonView(false, "日期参数至少填写一个!"));
  1619. }
  1620. if (!string.IsNullOrEmpty(dto.beginDt))
  1621. {
  1622. if (Regex.Match(dto.beginDt, @"^\d{4}-\d{2}-\d{2}$").Value.Length < 1)
  1623. {
  1624. return Ok(JsonView(false, "日期参数格式错误,应为yyyy-MM-dd!"));
  1625. }
  1626. else
  1627. {
  1628. sqlWhere += string.Format(@" And di.VisitDate >= '{0} 00:00:00' ", dto.beginDt);
  1629. }
  1630. }
  1631. if (!string.IsNullOrEmpty(dto.endDt))
  1632. {
  1633. if (Regex.Match(dto.endDt, @"^\d{4}-\d{2}-\d{2}$").Value.Length < 1)
  1634. {
  1635. return Ok(JsonView(false, "日期参数格式错误,应为yyyy-MM-dd!"));
  1636. }
  1637. else
  1638. {
  1639. sqlWhere += string.Format(@" And di.VisitDate <= '{0} 23:59:59' ", dto.endDt);
  1640. }
  1641. }
  1642. #endregion
  1643. //已收款项 判断如果是市场部的人员进来的话 只显示自己的 其他的都显示全部的
  1644. string userSqlWhere = "";
  1645. var userInfos = await _sqlSugar.Queryable<Sys_Users>()
  1646. .InnerJoin<Sys_Department>((u, d) => u.DepId == d.Id)
  1647. .Where((u, d) => u.IsDel == 0 && d.DepName.Contains("市场部") && u.Id == dto.CurrUserId)
  1648. .ToListAsync();
  1649. if (userInfos.Count > 0) userSqlWhere = string.Format(@$" And JietuanOperator={dto.CurrUserId} ");
  1650. //排序倒序
  1651. 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");
  1652. List<PostSyntheticalReceivableByDateRangeView> list_rst = _sqlSugar.SqlQueryable<PostSyntheticalReceivableByDateRangeView>(sql).ToList();
  1653. var setData = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
  1654. decimal sumAll_fr = 0M; //应收
  1655. decimal sumAll_pr = 0M; //已收
  1656. decimal sumAll_balance = 0M; //尾款
  1657. if (list_rst.Count > 0)
  1658. {
  1659. int rowNumber = 1;
  1660. foreach (var item_rst in list_rst)
  1661. {
  1662. DateTime dtTemp;
  1663. bool b = DateTime.TryParse(item_rst.visitDate, out dtTemp);
  1664. if (b)
  1665. {
  1666. item_rst.visitDate = dtTemp.ToString("yyyy-MM-dd");
  1667. }
  1668. item_rst.No = rowNumber;
  1669. rowNumber++;
  1670. int diId = item_rst.diid;
  1671. decimal sum_fr = 0M;
  1672. decimal sum_pr = 0M;
  1673. string str_client = string.Empty;
  1674. decimal sum_refund = 0M; //收款退还
  1675. decimal sum_extra = 0M; //超支费用
  1676. decimal balance = 0M;
  1677. string str_schedule = string.Empty;
  1678. //1.应收
  1679. string sql_fr = string.Format(@" Select * From Fin_ForeignReceivables Where IsDel=0 And Diid={0} ", diId);
  1680. List<Fin_ForeignReceivables> list_fr = _sqlSugar.SqlQueryable<Fin_ForeignReceivables>(sql_fr).ToList();
  1681. sum_fr = list_fr.Sum(s => s.ItemSumPrice);
  1682. //2.已收
  1683. string sql_pr = string.Format(@" Select * From Fin_ProceedsReceived Where IsDel=0 And Diid={0} ", diId);
  1684. List<Fin_ProceedsReceived> list_pr = _sqlSugar.SqlQueryable<Fin_ProceedsReceived>(sql_pr).ToList();
  1685. foreach (var item_pr in list_pr)
  1686. {
  1687. sum_pr += item_pr.Price;
  1688. str_client += string.Format(@"{0};", item_pr.Client);
  1689. str_schedule += string.Format(@"{0};", item_pr.Remark);
  1690. }
  1691. if (str_schedule.Length > 0)
  1692. {
  1693. str_schedule = str_schedule.TrimEnd(';');
  1694. }
  1695. if (str_client.Length > 0)
  1696. {
  1697. str_client = str_client.TrimEnd(';');
  1698. }
  1699. //3.收款退还
  1700. string sql_other = string.Format(@"Select * From Fin_PaymentRefundAndOtherMoney prao
  1701. Inner Join Grp_CreditCardPayment ccp On prao.Id = ccp.CId
  1702. Where ccp.CTable = 285 And ccp.IsPay = 1 And prao.IsDel = 0 And ccp.IsDel = 0 And prao.DiId = {0}", diId);
  1703. List<Grp_CreditCardPayment> list_other = _sqlSugar.SqlQueryable<Grp_CreditCardPayment>(sql_other).ToList();
  1704. sum_refund = list_other.Sum(s => s.PayMoney * s.DayRate);
  1705. //4.超支
  1706. string sql_extra = string.Format(@" Select c.* From Fin_GroupExtraCost f
  1707. Inner join Grp_CreditCardPayment c On f.Id = c.CId
  1708. Where c.CTable = 1015 And c.IsPay = 1 And f.IsDel = 0 And c.IsDel = 0 And f.DiId = {0} ", diId);
  1709. List<Grp_CreditCardPayment> list_extra = _sqlSugar.SqlQueryable<Grp_CreditCardPayment>(sql_extra).ToList();
  1710. sum_extra = list_extra.Sum(s => s.PayMoney * s.DayRate);
  1711. item_rst.frPrice = sum_fr.ToString("#0.00");
  1712. item_rst.extraPrice = sum_extra.ToString("#0.00");
  1713. item_rst.receivableTotal = (sum_fr + sum_extra).ToString("#0.00");
  1714. item_rst.prPrice = sum_pr.ToString("#0.00");
  1715. item_rst.refundAmount = sum_refund.ToString("#0.00");
  1716. item_rst.receivedTotal = (sum_pr - sum_refund).ToString("#0.00");
  1717. item_rst.balPrice = ((sum_fr + sum_extra) - (sum_pr - sum_refund)).ToString("#0.00");
  1718. item_rst.prClient = str_client;
  1719. item_rst.schedule = str_schedule;
  1720. string tempVisitDate = Convert.ToDateTime(item_rst.visitDate).ToString("yyyy-MM-dd");
  1721. sumAll_fr += (sum_fr + sum_extra);
  1722. sumAll_pr += (sum_pr - sum_refund);
  1723. sumAll_balance += ((sum_fr + sum_extra) - (sum_pr - sum_refund));
  1724. #region 单位应收已收细项(以应收费用名称为主去(已收费用)匹配) 新增 雷怡 2024-5-08 16:35:28
  1725. List<ClientFeeInfoView> feeDatas = new List<ClientFeeInfoView>();
  1726. //匹配上的数据
  1727. foreach (var item in list_fr)
  1728. {
  1729. var prInfo = list_pr.Find(it => item.PriceName.Contains(it.Client) || item.PriceName.Equals(it.Client));
  1730. decimal _balancePayment = 0.00M;
  1731. if (item.Currency == prInfo?.Currency)
  1732. {
  1733. _balancePayment = item.ItemSumPrice - prInfo?.Price ?? 0.00M;
  1734. }
  1735. feeDatas.Add(new ClientFeeInfoView
  1736. {
  1737. client = item.PriceName,
  1738. frMoney = item.ItemSumPrice.ToString("#0.00"),
  1739. frCurrency = setData.Find(it => it.Id == item.Currency)?.Name ?? "-",
  1740. frRate = item.Rate.ToString("#0.0000"),
  1741. prReceivablesType = setData.Find(it => it.Id == prInfo?.ReceivablesType)?.Name ?? "",
  1742. prTime = prInfo?.SectionTime ?? "-",
  1743. prMoney = prInfo?.Price.ToString("#0.00") ?? "-",
  1744. prCurrency = setData.Find(it => it.Id == prInfo?.Currency)?.Name ?? "",
  1745. balPayment = _balancePayment.ToString("#0.00")
  1746. });
  1747. }
  1748. //未匹配上的数据
  1749. foreach (var item in list_pr)
  1750. {
  1751. var frInfo = list_fr.Find(it => it.PriceName.Contains(item.Client) || it.PriceName.Equals(item.Client));
  1752. if (frInfo == null)
  1753. {
  1754. feeDatas.Add(new ClientFeeInfoView
  1755. {
  1756. client = item.Client + "[未匹配上的已收数据(应收已收公司名称不一致)]",
  1757. frMoney = "0.00",
  1758. frCurrency = "-",
  1759. frRate = "0.0000",
  1760. prReceivablesType = setData.Find(it => it.Id == item?.ReceivablesType)?.Name ?? "",
  1761. prTime = item?.SectionTime ?? "-",
  1762. prMoney = item?.Price.ToString("#0.00") ?? "0.00",
  1763. prCurrency = setData.Find(it => it.Id == item?.Currency)?.Name ?? "",
  1764. balPayment = "0.00"
  1765. });
  1766. }
  1767. }
  1768. item_rst.feeItem = feeDatas;
  1769. #endregion
  1770. }
  1771. PostSyntheticalReceivableByDateRangeResultView result = new PostSyntheticalReceivableByDateRangeResultView();
  1772. result.total_fr = sumAll_fr.ToString("#0.00");
  1773. result.total_pr = sumAll_pr.ToString("#0.00");
  1774. result.total_balance = sumAll_balance.ToString("#0.00");
  1775. result.dataList = new List<PostSyntheticalReceivableByDateRangeView>(list_rst);
  1776. if (dto.requestType == 1)
  1777. {
  1778. return Ok(JsonView(true, "请求成功", result, list_rst.Count));
  1779. }
  1780. else
  1781. {
  1782. //----------------------------
  1783. List<Excel_SyntheticalReceivableByDateRange> list_Ex = new List<Excel_SyntheticalReceivableByDateRange>();
  1784. WorkbookDesigner designer = new WorkbookDesigner();
  1785. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/应收款项模板 - 副本.xls");
  1786. int excNo = 1;
  1787. foreach (var item in list_rst)
  1788. {
  1789. Excel_SyntheticalReceivableByDateRange exc = new Excel_SyntheticalReceivableByDateRange();
  1790. exc.No = excNo.ToString();
  1791. excNo++;
  1792. exc.TeamName = item.teamName;
  1793. exc.ClientUnit = item.clientUnit;
  1794. exc.VisitDate = item.visitDate;
  1795. exc.Accounts = item.frPrice;
  1796. exc.Extra = item.extraPrice;
  1797. exc.ReceivableTotal = item.receivableTotal;
  1798. exc.Received = item.prPrice;
  1799. exc.RefundAmount = item.refundAmount;
  1800. exc.ReceivedTotal = item.receivedTotal;
  1801. exc.Balance = item.balPrice;
  1802. exc.Collection = item.schedule;
  1803. DateTime time = Convert.ToDateTime(item.visitDate);
  1804. TimeSpan ts = DateTime.Now - time;
  1805. float SY = float.Parse(item.balPrice);
  1806. if (ts.Days >= 365 && SY > 0)
  1807. {
  1808. exc.Sign = "需收款";
  1809. }
  1810. else
  1811. {
  1812. exc.Sign = "";
  1813. }
  1814. list_Ex.Add(exc);
  1815. }
  1816. var dt = CommonFun.GetDataTableFromIList(list_Ex);
  1817. dt.TableName = "Excel_SyntheticalReceivableByDateRange";
  1818. if (dt != null)
  1819. {
  1820. designer.SetDataSource("SumPrice", "应收合计:" + result.total_fr + "RMB 已收合计:" + result.total_pr + "RMB 余款合计:" + result.total_balance + "RMB");
  1821. //数据源
  1822. designer.SetDataSource(dt);
  1823. //根据数据源处理生成报表内容
  1824. designer.Process();
  1825. string fileName = ("Receivable/应收款项(" + dto.beginDt + "~" + dto.endDt + ").xlsx");
  1826. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  1827. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  1828. return Ok(JsonView(true, "成功", new { url = rst }));
  1829. }
  1830. }
  1831. }
  1832. return Ok(JsonView(true, "获取成功", "", list_rst.Count));
  1833. }
  1834. #endregion
  1835. #region 付款申请
  1836. /// <summary>
  1837. /// 付款申请
  1838. /// 基础数据
  1839. /// </summary>
  1840. /// <param name="dto"></param>
  1841. /// <returns></returns>
  1842. [HttpPost]
  1843. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1844. public async Task<IActionResult> PostPayRequestInit()
  1845. {
  1846. try
  1847. {
  1848. var conpanyDatas = _sqlSugar.Queryable<Sys_Company>()
  1849. .Where(it => it.IsDel == 0)
  1850. .Select(it => new
  1851. {
  1852. Id = it.Id,
  1853. ConpamyName = it.CompanyName
  1854. }).ToList();
  1855. return Ok(JsonView(true, "操作成功!", new { ConpanyData = conpanyDatas }));
  1856. }
  1857. catch (Exception ex)
  1858. {
  1859. return Ok(JsonView(false, ex.Message));
  1860. }
  1861. }
  1862. /// <summary>
  1863. /// 付款申请 (PageId=51)
  1864. /// 查询 根据日期范围
  1865. /// </summary>
  1866. /// <param name="dto"></param>
  1867. /// <returns></returns>
  1868. [HttpPost]
  1869. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1870. public async Task<IActionResult> PostPayRequest_Center(PostPayRequestByDateRangeDto dto)
  1871. {
  1872. Stopwatch stopwatch = Stopwatch.StartNew();
  1873. #region 验证
  1874. DateTime beginDt, endDt;
  1875. string format = "yyyy-MM-dd";
  1876. if (!DateTime.TryParseExact(dto.beginDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out beginDt))
  1877. {
  1878. return Ok(JsonView(false, "开始日期格式不正确!正确格式:yyyy-MM-dd"));
  1879. }
  1880. if (!DateTime.TryParseExact(dto.endDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDt))
  1881. {
  1882. return Ok(JsonView(false, "结束日期格式不正确!正确格式:yyyy-MM-dd"));
  1883. }
  1884. #region 页面操作权限验证
  1885. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1886. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  1887. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  1888. #endregion
  1889. #endregion
  1890. try
  1891. {
  1892. PaymentRequestCheckedView checkedView = new PaymentRequestCheckedView();
  1893. var checkedStr = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>("paymentRequestCheckedData");
  1894. if (checkedStr != null)
  1895. {
  1896. checkedView = JsonConvert.DeserializeObject<PaymentRequestCheckedView>(checkedStr.ToString());
  1897. if (checkedView.GroupIds.Count > 0)
  1898. {
  1899. checkedView.GroupIds = checkedView.GroupIds.OrderBy(x => x).ToList();
  1900. }
  1901. }
  1902. tree_Fin_DailyFeePaymentResult dailyResult = PayRequest_DailyByDateRange(dto.Status, checkedView.DailyPaymentIds, dto.beginDt, dto.endDt);
  1903. tree_Group_DailyFeePaymentResult groupResult = PayRequest_GroupPaymentByDateRange(dto.Status, checkedView.GroupIds, checkedView.HotelSubIds, dto.beginDt, dto.endDt);
  1904. stopwatch.Stop();
  1905. return Ok(JsonView(true, $"查询成功!耗时{stopwatch.ElapsedMilliseconds / 1000}s", new { daily = dailyResult, group = groupResult }));
  1906. }
  1907. catch (Exception ex)
  1908. {
  1909. return Ok(JsonView(false, ex.Message));
  1910. }
  1911. }
  1912. /// <summary>
  1913. /// 根据团组类型类型处理团组费用所属公司
  1914. /// </summary>
  1915. /// <param name="teamId"></param>
  1916. /// <returns></returns>
  1917. private CompanyInfo ExpenseCompanyByTeamId(int teamId)
  1918. {
  1919. CompanyInfo _companyInfo = new CompanyInfo();
  1920. List<int> _SiChuan = new List<int>() {
  1921. 38 , // 政府团
  1922. 39 , // 企业团
  1923. 40 , // 散客团
  1924. 102, // 未知
  1925. 248, // 非团组
  1926. 691, // 四川-会务活动
  1927. 762, // 四川-赛事项目收入
  1928. 1048,//高校团
  1929. };
  1930. List<int> _ChengDu = new List<int>() {
  1931. 302, // 成都-会务活动
  1932. 1047, // 成都-赛事项目收入
  1933. };
  1934. if (_SiChuan.Contains(teamId))
  1935. {
  1936. _companyInfo.Id = 2;
  1937. _companyInfo.ConpanyName = "四川泛美交流有限公司";
  1938. }
  1939. if (_ChengDu.Contains(teamId))
  1940. {
  1941. _companyInfo.Id = 1;
  1942. _companyInfo.ConpanyName = "成都泛美商务有限公司";
  1943. }
  1944. return _companyInfo;
  1945. }
  1946. /// <summary>
  1947. /// 付款申请(团组费用申请相关)
  1948. /// 查询 根据日期范围
  1949. /// </summary>
  1950. /// <param name="_groupIds"></param>
  1951. /// <param name="beginDt"></param>
  1952. /// <param name="endDt"></param>
  1953. /// <returns></returns>
  1954. private tree_Group_DailyFeePaymentResult PayRequest_GroupPaymentByDateRange(int status, List<int> _groupIds,List<int> _hotelSubIds, string beginDt, string endDt)
  1955. {
  1956. tree_Group_DailyFeePaymentResult _DailyFeePaymentResult = new tree_Group_DailyFeePaymentResult();
  1957. List<tree_Group_DailyFeePaymentPageListView> dataList = new List<tree_Group_DailyFeePaymentPageListView>();
  1958. #region sql条件处理
  1959. string sqlWhere = string.Format(@" And (AuditGMDate Between '{0} 00:00:00' And '{1} 23:59:59') ", beginDt, endDt);
  1960. if (status == 2)
  1961. {
  1962. if (_hotelSubIds.Count > 1)
  1963. {
  1964. var hrIds = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => _hotelSubIds.Contains(it.Id) && it.Price != 0).Select(it => it.HrId).Distinct().ToList();
  1965. var hrIds1 = _sqlSugar.Queryable<Grp_CreditCardPayment>().Where(it => it.CTable == 76 && hrIds.Contains(it.CId)).Select(it => it.Id).ToList();
  1966. if (hrIds1.Count > 1)
  1967. {
  1968. _groupIds.AddRange(hrIds1);
  1969. }
  1970. }
  1971. if (_groupIds.Count < 1)
  1972. {
  1973. _DailyFeePaymentResult.dataList = new List<tree_Group_DailyFeePaymentPageListView>();
  1974. return _DailyFeePaymentResult;
  1975. }
  1976. sqlWhere += string.Format(@" And Id In ({0})", string.Join(",", _groupIds));
  1977. }
  1978. string sql_1 = string.Format(@"Select * From Grp_CreditCardPayment Where IsDel = 0 And IsPay = 0 And (IsAuditGM = 1 Or IsAuditGM = 3 ){0}", sqlWhere);
  1979. #endregion
  1980. var _paymentDatas = _sqlSugar.SqlQueryable<Grp_CreditCardPayment>(sql_1).ToList();//付款信息
  1981. _DailyFeePaymentResult.gz = _paymentDatas.Where(it => it.OrbitalPrivateTransfer == 0).Sum(it => ((it.PayMoney * it.DayRate) / 100) * it.PayPercentage); //公转
  1982. _DailyFeePaymentResult.sz = _paymentDatas.Where(it => it.OrbitalPrivateTransfer == 1).Sum(it => ((it.PayMoney * it.DayRate) / 100) * it.PayPercentage); ; //私转
  1983. List<int> groupIds = _paymentDatas.Select(it => it.DIId).Distinct().ToList();
  1984. var _groupDatas = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0 && groupIds.Contains(it.Id)).ToList();
  1985. //_groupDatas = (List<Grp_DelegationInfo>)_groupDatas.GroupBy(it => it.TeamDid);
  1986. #region 相关基础数据源
  1987. var userDatas = _sqlSugar.Queryable<Sys_Users>().ToList();
  1988. var setDatas = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
  1989. var countryFeeDatas = _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(it => it.IsDel == 0).ToList();
  1990. var hotelDatas = _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  1991. var hotelContentDatas = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => it.IsDel == 0 && it.IsPay == 0 && it.Price != 0 && groupIds.Contains(it.DiId)).ToList();
  1992. var opDatas = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  1993. var visaDatas = _sqlSugar.Queryable<Grp_VisaInfo>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DIId)).ToList();
  1994. var ioaDatas = _sqlSugar.Queryable<Grp_InvitationOfficialActivities>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  1995. var insureDatas = _sqlSugar.Queryable<Grp_Customers>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  1996. var airDatas = _sqlSugar.Queryable<Grp_AirTicketReservations>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DIId)).ToList();
  1997. //var otherMoneyDatas = _sqlSugar.Queryable<Fin_OtherPrice>().Where(it => it.IsDel == 0 && groupIds.Contains(it.Diid)).ToList();
  1998. var otherMoneyDatas = _sqlSugar.Queryable<Grp_DecreasePayments>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  1999. var refundPaymentDatas = _sqlSugar.Queryable<Fin_PaymentRefundAndOtherMoney>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  2000. var ExtraCostDatas = _sqlSugar.Queryable<Fin_GroupExtraCost>().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
  2001. #endregion
  2002. //Expense company
  2003. foreach (var groupInfo in _groupDatas)
  2004. {
  2005. List<Group_DailyFeePaymentContentInfolView> childList = new List<Group_DailyFeePaymentContentInfolView>();
  2006. var groupPaymentDatas = _paymentDatas.Where(it => groupInfo.Id == it.DIId).ToList();
  2007. int rouNumber = 1;
  2008. foreach (var payInfo in groupPaymentDatas)
  2009. {
  2010. string priName = "-";
  2011. string orbitalPrivateTransfer = payInfo.OrbitalPrivateTransfer == 0 ? "公转" : payInfo.OrbitalPrivateTransfer == 1 ? "私转" : "-";
  2012. switch (payInfo.CTable)
  2013. {
  2014. case 76: //76 酒店预订
  2015. priName = $"[费用名称:{hotelDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.HotelName ?? ""}]";
  2016. break;
  2017. case 79: //79 车/导游地接
  2018. var opData = opDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id);
  2019. if (opData != null)
  2020. {
  2021. string area = "";
  2022. bool b = int.TryParse(opData.Area, out int areaId);
  2023. if (b)
  2024. {
  2025. string area1 = countryFeeDatas.Find(it => it.Id == areaId)?.Country ?? "-";
  2026. area = $"{area1}({setDatas.Find(it => it.Id == opData.PriceType)?.Name ?? "-"})";
  2027. }
  2028. else area = opData.Area;
  2029. string opPriName = "-";
  2030. if (!string.IsNullOrEmpty(opData.PriceName)) opPriName = opData.PriceName;
  2031. area += $"({opPriName})";
  2032. if (payInfo.OrbitalPrivateTransfer == 0) //公转
  2033. {
  2034. priName = $"【{orbitalPrivateTransfer}】【导游: {opData.ServiceGuide} 】[费用名称:{area}]";
  2035. }
  2036. else if (payInfo.OrbitalPrivateTransfer == 1) //私转
  2037. {
  2038. priName = $"【{orbitalPrivateTransfer}】【导游:{opData.ServiceGuide}】[费用名称:{area}]";
  2039. }
  2040. }
  2041. break;
  2042. case 80: // 80 签证
  2043. 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);
  2044. List<SimplClientInfo> arr = _sqlSugar.SqlQueryable<SimplClientInfo>(sql).ToList();
  2045. string visaClientName = visaDatas.Find(it => payInfo.DIId == it.DIId && payInfo.CId == it.Id)?.VisaClient ?? "";
  2046. string clientName = "-";
  2047. if (Regex.Match(visaClientName, @"\d+,?").Value.Length > 0)
  2048. {
  2049. string[] temparr = visaClientName.Split(',');
  2050. string fistrStr = temparr[0];
  2051. int count = temparr.Count();
  2052. int tempId;
  2053. bool success = int.TryParse(fistrStr, out tempId);
  2054. if (success)
  2055. {
  2056. SimplClientInfo tempInfo = arr.FirstOrDefault(s => s.Id == tempId);
  2057. if (tempInfo != null)
  2058. {
  2059. if (count > 1)
  2060. {
  2061. clientName = string.Format(@"{0}{1}等{2}人", tempInfo.LastName, tempInfo.FirstName, count);
  2062. }
  2063. else
  2064. {
  2065. clientName = string.Format(@"{0}{1}", tempInfo.LastName, tempInfo.FirstName);
  2066. }
  2067. }
  2068. }
  2069. else
  2070. {
  2071. clientName = fistrStr;
  2072. }
  2073. }
  2074. priName = $"[费用名称:{clientName}]";
  2075. break;
  2076. case 81: // 81 邀请/公务活动
  2077. priName = $"[费用名称:{ioaDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.Inviter ?? " -"}]";
  2078. break;
  2079. case 82: // 82 团组客户保险
  2080. priName = $"[费用名称:{insureDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.ClientName ?? " -"}]";
  2081. break;
  2082. case 85: // 85 机票预订
  2083. string flightsCode = airDatas.Find(it => payInfo.DIId == it.DIId && payInfo.CId == it.Id)?.FlightsCode ?? "-";
  2084. string airPayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "-";
  2085. priName = $"{flightsCode}【{airPayType}】";
  2086. break;
  2087. case 98: // 98 其他款项
  2088. priName = $"[费用名称:{otherMoneyDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  2089. break;
  2090. case 285: // 285 收款退还
  2091. priName = $"[费用名称:{refundPaymentDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  2092. break;
  2093. case 1015: // 1015 超支费用
  2094. priName = $"[费用名称:{ExtraCostDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  2095. break;
  2096. default:
  2097. priName = "";
  2098. break;
  2099. }
  2100. bool status1 = false;
  2101. if (_groupIds != null)
  2102. {
  2103. status1 = _groupIds.Contains(payInfo.Id);
  2104. }
  2105. if (payInfo.CTable == 76) //酒店单独处理
  2106. {
  2107. var hotelContents = hotelContentDatas.Where(it => it.HrId == payInfo.CId);
  2108. List<Group_DailyFeePaymentContentInfolView> childInfos = new List<Group_DailyFeePaymentContentInfolView>();
  2109. foreach (var hotelContent in hotelContents)
  2110. {
  2111. string subPriceName = "";
  2112. if (hotelContent.PriceType == 1) subPriceName = "房费";
  2113. else if (hotelContent.PriceType == 2) subPriceName = "早餐";
  2114. else if (hotelContent.PriceType == 3) subPriceName = "地税";
  2115. else if (hotelContent.PriceType == 4) subPriceName = "城市税";
  2116. if (string.IsNullOrEmpty(subPriceName)) subPriceName = priName;
  2117. else subPriceName = $"{priName.Replace("]","")}-{subPriceName}]";
  2118. string payeeStr1 = string.Format(@" {0},开户行:{1},银行卡号:{2} ",
  2119. string.IsNullOrEmpty(hotelContent.Payee) ? "-" : hotelContent.Payee,
  2120. string.IsNullOrEmpty(hotelContent.OtherBankName) ? "-" : hotelContent.OtherBankName,
  2121. string.IsNullOrEmpty(hotelContent.OtherSideNo) ? "-" : hotelContent.OtherSideNo);
  2122. decimal _PaymentAmount1 = hotelContent.Price;//此次付款金额
  2123. decimal _CNYSubTotalAmount1 = _PaymentAmount1 * hotelContent.Rate;//此次付款金额
  2124. _CNYSubTotalAmount1 = Convert.ToDecimal(_CNYSubTotalAmount1.ToString("#0.00"));
  2125. //酒店子项Id选中状态更改
  2126. if (_hotelSubIds != null) status1 = _hotelSubIds.Contains(hotelContent.Id);
  2127. var childInfo1 = new Group_DailyFeePaymentContentInfolView()
  2128. {
  2129. IsChecked = status1,
  2130. Id = payInfo.Id,
  2131. HotelSubId = hotelContent.Id,
  2132. Payee = payeeStr1,
  2133. RowNumber = rouNumber,
  2134. Applicant = userDatas.Find(it => it.Id == payInfo.CreateUserId)?.CnName ?? "",
  2135. ApplicantDt = payInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
  2136. PayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "",
  2137. TransferMark = orbitalPrivateTransfer,
  2138. PriceName = subPriceName,
  2139. ModuleName = setDatas.Find(it => it.Id == payInfo.CTable)?.Name ?? "",
  2140. PayCurrCode = setDatas.Find(it => it.Id == hotelContent.Currency)?.Name ?? "",
  2141. PaymentAmount = _PaymentAmount1,
  2142. PayRate = hotelContent.Rate,
  2143. CNYSubTotalAmount = _CNYSubTotalAmount1,
  2144. AuditStatus = payInfo.IsAuditGM
  2145. };
  2146. string remaksDescription1 = $"【{childInfo1.PayType}】【{childInfo1.ModuleName}】{rouNumber}、[申请人:{childInfo1.Applicant}]{subPriceName}[收款方:{childInfo1.Payee}] {childInfo1.PayCurrCode} {_PaymentAmount1.ToString("#0.00")}、CNY:{childInfo1.CNYSubTotalAmount.ToString("#0.00")}(团组:{groupInfo.TeamName})";
  2147. childInfo1.RemaksDescription = remaksDescription1;
  2148. if (status == 2)
  2149. {
  2150. if (status1)
  2151. {
  2152. childInfos.Add(childInfo1);
  2153. }
  2154. }
  2155. else childInfos.Add(childInfo1);
  2156. rouNumber++;
  2157. }
  2158. childList.AddRange(childInfos);
  2159. }
  2160. else
  2161. {
  2162. string payeeStr = string.Format(@" {0},开户行:{1},银行卡号:{2} ",
  2163. string.IsNullOrEmpty(payInfo.Payee) ? "-" : payInfo.Payee,
  2164. string.IsNullOrEmpty(payInfo.OtherBankName) ? "-" : payInfo.OtherBankName,
  2165. string.IsNullOrEmpty(payInfo.OtherSideNo) ? "-" : payInfo.OtherSideNo);
  2166. decimal _PaymentAmount = (payInfo.PayMoney / 100) * payInfo.PayPercentage;//此次付款金额
  2167. decimal _CNYSubTotalAmount = _PaymentAmount * payInfo.DayRate;//此次付款金额
  2168. _CNYSubTotalAmount = Convert.ToDecimal(_CNYSubTotalAmount.ToString("#0.00"));
  2169. var childInfo = new Group_DailyFeePaymentContentInfolView()
  2170. {
  2171. IsChecked = status1,
  2172. Id = payInfo.Id,
  2173. Payee = payeeStr,
  2174. RowNumber = rouNumber,
  2175. Applicant = userDatas.Find(it => it.Id == payInfo.CreateUserId)?.CnName ?? "",
  2176. ApplicantDt = payInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
  2177. PayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "",
  2178. TransferMark = orbitalPrivateTransfer,
  2179. PriceName = priName,
  2180. ModuleName = setDatas.Find(it => it.Id == payInfo.CTable)?.Name ?? "",
  2181. PayCurrCode = setDatas.Find(it => it.Id == payInfo.PaymentCurrency)?.Name ?? "",
  2182. PaymentAmount = _PaymentAmount,
  2183. PayRate = payInfo.DayRate,
  2184. CNYSubTotalAmount = _CNYSubTotalAmount,
  2185. AuditStatus = payInfo.IsAuditGM
  2186. };
  2187. string remaksDescription = $"【{childInfo.PayType}】【{childInfo.ModuleName}】{rouNumber}、[申请人:{childInfo.Applicant}]{priName}[收款方:{childInfo.Payee}] {childInfo.PayCurrCode} {_PaymentAmount.ToString("#0.00")}、CNY:{childInfo.CNYSubTotalAmount.ToString("#0.00")}(团组:{groupInfo.TeamName})";
  2188. childInfo.RemaksDescription = remaksDescription;
  2189. childList.Add(childInfo);
  2190. rouNumber++;
  2191. }
  2192. }
  2193. CompanyInfo companyInfo = new CompanyInfo();
  2194. companyInfo = ExpenseCompanyByTeamId(groupInfo.TeamDid);
  2195. dataList.Add(new tree_Group_DailyFeePaymentPageListView()
  2196. {
  2197. Id = Guid.NewGuid().ToString("N"),
  2198. GroupName = groupInfo.TeamName,
  2199. CompanyId = companyInfo.Id,
  2200. ConpanyName = companyInfo.ConpanyName,
  2201. CNYTotalAmount = childList.Sum(it => it.CNYSubTotalAmount),
  2202. ChildList = childList,
  2203. });
  2204. }
  2205. _DailyFeePaymentResult.dataList = dataList;
  2206. return _DailyFeePaymentResult;
  2207. }
  2208. /// <summary>
  2209. /// 付款申请(日付申请相关)
  2210. /// 查询 根据日期范围
  2211. /// </summary>
  2212. /// <param name="_dailyIds"></param>
  2213. /// <param name="beginDt"></param>
  2214. /// <param name="endDt"></param>
  2215. /// <returns></returns>
  2216. private tree_Fin_DailyFeePaymentResult PayRequest_DailyByDateRange(int status, List<int> _dailyIds, string beginDt, string endDt)
  2217. {
  2218. #region sql条件处理
  2219. string sqlWhere = string.Format(@" And dfp.CreateTime between '{0} 00:00:00' And '{1} 23:59:59' ", beginDt, endDt);
  2220. if (status == 2)
  2221. {
  2222. if (_dailyIds.Count < 1)
  2223. {
  2224. return new tree_Fin_DailyFeePaymentResult() { childList = new List<Fin_DailyFeePaymentContentInfolView>() };
  2225. }
  2226. sqlWhere += string.Format(@" And dfp.Id In({0}) ", string.Join(",", _dailyIds));
  2227. }
  2228. string sql_1 = string.Format(@"Select * From (
  2229. Select row_number() over (order by dfp.Id Desc) as RowNumber,
  2230. dfp.Id,dfp.CompanyId,c.CompanyName,dfp.Instructions,dfp.SumPrice,
  2231. dfp.CreateUserId,u.CnName CreateUser,dfp.CreateTime,dfp.FAudit,dfp.MAudit,
  2232. dfp.PriceTypeId,dfp.TransferTypeId
  2233. From Fin_DailyFeePayment dfp
  2234. Inner Join Sys_Company c On dfp.CompanyId = c.Id
  2235. Left Join Sys_Users u On dfp.CreateUserId = u.Id
  2236. Where dfp.IsDel=0 {0} And dfp.FAudit = 1 And dfp.MAudit = 1 And dfp.IsPay = 0
  2237. ) temp ", sqlWhere);
  2238. #endregion
  2239. List<tree_Fin_DailyFeePaymentPageListView> DailyFeePaymentData = _sqlSugar.SqlQueryable<tree_Fin_DailyFeePaymentPageListView>(sql_1).ToList();
  2240. Dictionary<int, string> dic_setData = new Dictionary<int, string>();
  2241. Sys_SetDataType stGZ = _daiRep.Query<Sys_SetDataType>(s => s.Name == "公转").First();
  2242. Sys_SetDataType stSZ = _daiRep.Query<Sys_SetDataType>(s => s.Name == "私转").First();
  2243. foreach (var item in DailyFeePaymentData)
  2244. {
  2245. if (_dailyIds != null)
  2246. {
  2247. item.IsChecked = _dailyIds.Contains(item.Id);
  2248. }
  2249. if (dic_setData.ContainsKey(item.PriceTypeId))
  2250. {
  2251. item.priceTypeStr = dic_setData[item.PriceTypeId];
  2252. }
  2253. else
  2254. {
  2255. Sys_SetData sd_priceType = _daiRep.Query<Sys_SetData>(s => s.Id == item.PriceTypeId).First();
  2256. if (sd_priceType != null)
  2257. {
  2258. item.priceTypeStr = sd_priceType.Name;
  2259. dic_setData.Add(item.PriceTypeId, sd_priceType.Name);
  2260. }
  2261. }
  2262. if (dic_setData.ContainsKey(item.transferTypeId))
  2263. {
  2264. item.transferTypeIdStr = dic_setData[item.transferTypeId];
  2265. Sys_SetData sd_transfer = _daiRep.Query<Sys_SetData>(s => s.Id == item.transferTypeId).First();
  2266. if (sd_transfer != null)
  2267. {
  2268. item.transferParentId = sd_transfer.STid;
  2269. item.transferParentIdStr = sd_transfer.STid == stGZ.Id ? "公转" : sd_transfer.STid == stSZ.Id ? "私转" : "";
  2270. }
  2271. }
  2272. else
  2273. {
  2274. Sys_SetData sd_transfer = _daiRep.Query<Sys_SetData>(s => s.Id == item.transferTypeId).First();
  2275. if (sd_transfer != null)
  2276. {
  2277. item.transferTypeIdStr = sd_transfer.Name;
  2278. item.transferParentId = sd_transfer.STid;
  2279. item.transferParentIdStr = sd_transfer.STid == stGZ.Id ? "公转" : sd_transfer.STid == stSZ.Id ? "私转" : "";
  2280. dic_setData.Add(item.transferTypeId, sd_transfer.Name);
  2281. }
  2282. }
  2283. string feeContentSql = string.Format(@"Select * From Fin_DailyFeePaymentContent
  2284. Where IsDel=0 And DFPId = {0} ", item.Id);
  2285. item.childList = _sqlSugar.SqlQueryable<Fin_DailyFeePaymentContentInfolView>(feeContentSql).ToList();
  2286. int rowNumber = 1;
  2287. foreach (var subItem in item.childList)
  2288. {
  2289. string remaksDescription = $"{rowNumber}、【{item.priceTypeStr}】{item.Instructions}({subItem.PriceName}) CNY:{subItem.ItemTotal.ToString("#0.00")}(单价:{subItem.Price.ToString("#0.00")} * {subItem.Quantity})";
  2290. subItem.RemaksDescription = remaksDescription;
  2291. string excelRemaksDescription = $"【{item.priceTypeStr}】{item.Instructions}({subItem.PriceName}) CNY:{subItem.ItemTotal.ToString("#0.00")}(单价:{subItem.Price.ToString("#0.00")} * {subItem.Quantity})【申请人:{item.CreateUser} 申请时间:{item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")}】";
  2292. subItem.ExcelRemaksDescription = excelRemaksDescription;
  2293. rowNumber++;
  2294. }
  2295. }
  2296. decimal total_gz = DailyFeePaymentData.Where(s => s.transferParentId == stGZ.Id).Sum(d => d.SumPrice ?? 0M);
  2297. decimal total_sz = DailyFeePaymentData.Where(s => s.transferParentId == stSZ.Id).Sum(d => d.SumPrice ?? 0M);
  2298. var result = new tree_Fin_DailyFeePaymentResult() { gz = total_gz, sz = total_sz, dataList = DailyFeePaymentData };
  2299. return result;
  2300. }
  2301. /// <summary>
  2302. /// 付款申请 (PageId=51)
  2303. /// 团组,日付相关费用 选中状态变更
  2304. /// </summary>
  2305. /// <param name="dto"></param>
  2306. /// <returns></returns>
  2307. [HttpPost]
  2308. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2309. public async Task<IActionResult> PostPayRequestCheckedChange(PayRequestCheckedChangeDto dto)
  2310. {
  2311. #region 验证
  2312. if (dto.Type < 1 || dto.Type > 2)
  2313. {
  2314. return Ok(JsonView(false, "请传入有效的Type参数! 1 checked 2 清除上次勾选"));
  2315. }
  2316. #endregion
  2317. PaymentRequestCheckedView requestCheckedView = new PaymentRequestCheckedView();
  2318. List<int> groupIds = new List<int>();
  2319. List<int> dailyPaymentIds = new List<int>();
  2320. List<int> hotelIds = new List<int>();
  2321. #region 参数处理
  2322. if (!string.IsNullOrEmpty(dto.GroupIds))
  2323. {
  2324. if (dto.GroupIds.Contains(","))
  2325. {
  2326. groupIds = dto.GroupIds.Split(',').Select(int.Parse).ToList();
  2327. }
  2328. else
  2329. {
  2330. groupIds.Add(int.Parse(dto.GroupIds));
  2331. }
  2332. }
  2333. if (!string.IsNullOrEmpty(dto.HotelSubIds))
  2334. {
  2335. if (dto.HotelSubIds.Contains(","))
  2336. {
  2337. hotelIds = dto.HotelSubIds.Split(',').Select(int.Parse).ToList();
  2338. }
  2339. else
  2340. {
  2341. hotelIds.Add(int.Parse(dto.HotelSubIds));
  2342. }
  2343. }
  2344. if (!string.IsNullOrEmpty(dto.DailyPaymentIds))
  2345. {
  2346. if (dto.DailyPaymentIds.Contains(","))
  2347. {
  2348. dailyPaymentIds = dto.DailyPaymentIds.Split(',').Select(int.Parse).ToList();
  2349. }
  2350. else
  2351. {
  2352. dailyPaymentIds.Add(int.Parse(dto.DailyPaymentIds));
  2353. }
  2354. }
  2355. #endregion
  2356. requestCheckedView.GroupIds = groupIds;
  2357. requestCheckedView.HotelSubIds = hotelIds;
  2358. requestCheckedView.DailyPaymentIds = dailyPaymentIds;
  2359. if (dto.Type == 1)
  2360. {
  2361. TimeSpan ts = DateTime.Now.AddDays(180) - DateTime.Now; //设置redis 过期时间 半年(180)
  2362. var status = await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync<string>("paymentRequestCheckedData", JsonConvert.SerializeObject(requestCheckedView), ts);
  2363. if (status)
  2364. {
  2365. return Ok(JsonView(true, "操作成功!"));
  2366. }
  2367. }
  2368. else if (dto.Type == 2)
  2369. {
  2370. var status = await RedisRepository.RedisFactory.CreateRedisRepository().KeyDeleteAsync("paymentRequestCheckedData");
  2371. if (status)
  2372. {
  2373. return Ok(JsonView(true, "操作成功!"));
  2374. }
  2375. }
  2376. return Ok(JsonView(false, "操作失败!"));
  2377. }
  2378. /// <summary>
  2379. /// 付款申请 (PageId=51)
  2380. /// 团组,日付相关费用 汇率变更
  2381. /// </summary>
  2382. /// <param name="dto"></param>
  2383. /// <returns></returns>
  2384. [HttpPost]
  2385. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2386. public async Task<IActionResult> PostPayRequestRateChange(PayRequestRateChangeDto dto)
  2387. {
  2388. #region 验证
  2389. DateTime beginDt, endDt;
  2390. string format = "yyyy-MM-dd";
  2391. if (!DateTime.TryParseExact(dto.beginDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out beginDt))
  2392. {
  2393. return Ok(JsonView(false, "开始日期格式不正确!正确格式:yyyy-MM-dd"));
  2394. }
  2395. if (!DateTime.TryParseExact(dto.endDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDt))
  2396. {
  2397. return Ok(JsonView(false, "结束日期格式不正确!正确格式:yyyy-MM-dd"));
  2398. }
  2399. if (dto.UserId < 1) return Ok(JsonView(false, "请传入有效的UserId参数!"));
  2400. if (dto.Id < 1) return Ok(JsonView(false, "请传入有效的Id参数!"));
  2401. if (dto.Rate <= 0) return Ok(JsonView(false, "请传入有效的Rate参数!"));
  2402. #endregion
  2403. int hotelSubStatus = 0,status = 0;
  2404. int diid = 0, cTable = 0, currId = 0;
  2405. if (dto.HotelSubId > 0)
  2406. {
  2407. //更改酒店子表汇率
  2408. hotelSubStatus = _sqlSugar.Updateable<Grp_HotelReservationsContent>()
  2409. .SetColumns(it => it.Rate == dto.Rate)
  2410. .Where(it => it.Id == dto.HotelSubId)
  2411. .ExecuteCommand();
  2412. if (hotelSubStatus > 0)
  2413. {
  2414. var hotelSubInfo = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => it.Id == dto.HotelSubId).First();
  2415. if (hotelSubInfo != null)
  2416. {
  2417. diid = hotelSubInfo.DiId;
  2418. currId = hotelSubInfo.Currency;
  2419. }
  2420. //付款申请汇率更改成功;更改团组汇率对应币种
  2421. string currCode = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == currId).First()?.Name ?? "";
  2422. await _teamRateRep.UpdateGroupRateByDiIdAndCTableId(diid, 76, currCode, dto.Rate);
  2423. }
  2424. }
  2425. if (dto.Id > 0)
  2426. {
  2427. var ccpInfo = _sqlSugar.Queryable<Grp_CreditCardPayment>().Where(it => it.Id == dto.Id).First();
  2428. decimal cnyMoney = 0.00M;
  2429. if (ccpInfo != null) {
  2430. cnyMoney = ccpInfo.PayMoney * dto.Rate;
  2431. diid = ccpInfo.DIId;
  2432. cTable = ccpInfo.CTable;
  2433. currId = ccpInfo.PaymentCurrency;
  2434. }
  2435. status = _sqlSugar.Updateable<Grp_CreditCardPayment>()
  2436. .SetColumns(it => it.DayRate == dto.Rate)
  2437. .SetColumns(it => it.RMBPrice == cnyMoney)
  2438. .Where(it => it.Id == dto.Id)
  2439. .ExecuteCommand();
  2440. if (status > 0)
  2441. {
  2442. //付款申请汇率更改成功;更改团组汇率对应币种
  2443. if (cTable != 76)
  2444. {
  2445. string currCode = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == currId).First()?.Name ?? "";
  2446. await _teamRateRep.UpdateGroupRateByDiIdAndCTableId(diid, cTable, currCode, dto.Rate);
  2447. }
  2448. }
  2449. }
  2450. if (hotelSubStatus > 0 || status > 0)
  2451. {
  2452. PaymentRequestCheckedView checkedView = new PaymentRequestCheckedView();
  2453. var checkedStr = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>("paymentRequestCheckedData");
  2454. if (checkedStr != null)
  2455. {
  2456. checkedView = JsonConvert.DeserializeObject<PaymentRequestCheckedView>(checkedStr.ToString());
  2457. }
  2458. tree_Fin_DailyFeePaymentResult dailyResult = PayRequest_DailyByDateRange(1, checkedView.DailyPaymentIds, dto.beginDt, dto.endDt);
  2459. tree_Group_DailyFeePaymentResult groupResult = PayRequest_GroupPaymentByDateRange(1, checkedView.GroupIds, checkedView.HotelSubIds, dto.beginDt, dto.endDt);
  2460. decimal _gz = dailyResult.gz + groupResult.gz;
  2461. decimal _sz = dailyResult.sz + groupResult.sz;
  2462. return Ok(JsonView(true, "操作成功!", new { gz = dailyResult, sz = groupResult }));
  2463. }
  2464. return Ok(JsonView(false, "该项汇率修改失败!"));
  2465. }
  2466. /// <summary>
  2467. /// 付款申请 (PageId=51)
  2468. /// 团组,日付相关费用 付款状态变更
  2469. /// </summary>
  2470. /// <param name="dto"></param>
  2471. /// <returns></returns>
  2472. [HttpPost]
  2473. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2474. public async Task<IActionResult> PostPayRequestPayChange(PayRequestPayChangeDto dto)
  2475. {
  2476. if (dto.UserId < 1) return Ok(JsonView(false, "请传入有效的UserId参数!"));
  2477. //if (string.IsNullOrEmpty(dto.GroupIds))
  2478. //{
  2479. // return Ok(JsonView(false, "请传入有效的GroupIds参数!"));
  2480. //}
  2481. //if (string.IsNullOrEmpty(dto.DailyPaymentIds))
  2482. //{
  2483. // return Ok(JsonView(false, "请传入有效的DailyPaymentIds参数!"));
  2484. //}
  2485. List<int> groupIds = new List<int>();
  2486. List<int> dailyPaymentIds = new List<int>();
  2487. List<int> hotelSubIds = new List<int>();
  2488. #region 参数处理
  2489. if (!string.IsNullOrEmpty(dto.GroupIds))
  2490. {
  2491. if (dto.GroupIds.Contains(",")) groupIds = dto.GroupIds.Split(',').Select(int.Parse).ToList();
  2492. else groupIds.Add(int.Parse(dto.GroupIds));
  2493. }
  2494. if (!string.IsNullOrEmpty(dto.HotelSubIds))
  2495. {
  2496. if (dto.HotelSubIds.Contains(",")) hotelSubIds = dto.HotelSubIds.Split(',').Select(int.Parse).ToList();
  2497. else hotelSubIds.Add(int.Parse(dto.HotelSubIds));
  2498. if (hotelSubIds.Count > 0)
  2499. {
  2500. foreach (var item in hotelSubIds)
  2501. {
  2502. if (item < 1)
  2503. {
  2504. hotelSubIds.Remove(item);
  2505. }
  2506. }
  2507. }
  2508. }
  2509. if (!string.IsNullOrEmpty(dto.DailyPaymentIds))
  2510. {
  2511. if (dto.DailyPaymentIds.Contains(",")) dailyPaymentIds = dto.DailyPaymentIds.Split(',').Select(int.Parse).ToList();
  2512. else dailyPaymentIds.Add(int.Parse(dto.DailyPaymentIds));
  2513. }
  2514. #endregion
  2515. bool changeStatus = false;
  2516. _sqlSugar.BeginTran();
  2517. if (groupIds.Count > 0)
  2518. {
  2519. var ccpInfos = _sqlSugar.Queryable<Grp_CreditCardPayment>().Where(it => it.IsDel == 0 && groupIds.Contains(it.Id)).ToList();
  2520. var otherTypeCcpIds = ccpInfos.Where(it => it.CTable != 76).Select(it => it.Id).ToList();
  2521. var hotelTyprCcpIds = ccpInfos.Where(it => it.CTable == 76).Select(it => it.Id).ToList();
  2522. int groupStatus = 0;
  2523. if (otherTypeCcpIds.Count > 0) //其他费用类型 正常付款
  2524. {
  2525. groupStatus = _sqlSugar.Updateable<Grp_CreditCardPayment>()
  2526. .SetColumns(it => it.IsPay == 1)
  2527. .Where(it => otherTypeCcpIds.Contains(it.Id))
  2528. .ExecuteCommand();
  2529. changeStatus = true;
  2530. }
  2531. if (hotelTyprCcpIds.Count > 0) //酒店费用子项逻辑付款,酒店子项费用全部付完款,c表ispay=1
  2532. {
  2533. if (hotelSubIds.Count > 0)
  2534. {
  2535. List<int> hrPayIds = new List<int>();
  2536. var hrIspayStatus = _sqlSugar.Updateable<Grp_HotelReservationsContent>()
  2537. .SetColumns(it => it.IsPay == 1)
  2538. .Where(it => hotelSubIds.Contains(it.Id))
  2539. .ExecuteCommand();
  2540. changeStatus = true;
  2541. //酒店子项是否全部付完款
  2542. List<int> hrIds = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => it.IsDel == 0 && hotelSubIds.Contains(it.Id)).Select(it => it.HrId).Distinct().ToList();
  2543. if (hrIds.Count > 0 )
  2544. {
  2545. var hotelSubFeeData = _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => it.IsDel == 0 && hrIds.Contains(it.HrId)).ToList();
  2546. var hotelSubFeeGroupData = hotelSubFeeData.GroupBy(it => it.HrId).ToList();
  2547. foreach (var item in hotelSubFeeGroupData)
  2548. {
  2549. var allTotal = item.Where(it => it.Price > 0).ToList().Count;
  2550. var paymentTotal = item.Where(it => it.Price > 0 && it.IsPay == 1).ToList().Count;
  2551. if (allTotal == paymentTotal)
  2552. {
  2553. hrPayIds.Add(item.Key);
  2554. }
  2555. }
  2556. }
  2557. if (hrPayIds.Count > 0)
  2558. {
  2559. //c表更改全部付款的酒店费用
  2560. groupStatus = _sqlSugar.Updateable<Grp_CreditCardPayment>()
  2561. .SetColumns(it => it.IsPay == 1)
  2562. .Where(it => it.CTable == 76 && hrPayIds.Contains(it.CId))
  2563. .ExecuteCommand();
  2564. }
  2565. }
  2566. }
  2567. }
  2568. //if (hotelSubIds.Count > 0)
  2569. //{
  2570. // var groupStatus = _sqlSugar.Updateable<Grp_HotelReservationsContent>()
  2571. // .SetColumns(it => it.IsPay == 1)
  2572. // .Where(it => hotelSubIds.Contains(it.Id))
  2573. // .ExecuteCommand();
  2574. // if (groupStatus > 0)
  2575. // {
  2576. // changeStatus = true;
  2577. // }
  2578. //}
  2579. if (dailyPaymentIds.Count > 0)
  2580. {
  2581. var dailyPaymentStatus = _sqlSugar.Updateable<Fin_DailyFeePayment>()
  2582. .SetColumns(it => it.IsPay == 1)
  2583. .Where(it => dailyPaymentIds.Contains(it.Id))
  2584. .ExecuteCommand();
  2585. if (dailyPaymentStatus > 0)
  2586. {
  2587. changeStatus = true;
  2588. }
  2589. }
  2590. if (changeStatus)
  2591. {
  2592. _sqlSugar.CommitTran();
  2593. #region 应用推送
  2594. try
  2595. {
  2596. foreach (int ccpId in groupIds)
  2597. {
  2598. List<string> tempList = new List<string>() { ccpId.ToString() };
  2599. await AppNoticeLibrary.SendUserMsg_GroupStatus_PayResult(ccpId, tempList);
  2600. }
  2601. foreach (int dailyId in dailyPaymentIds)
  2602. {
  2603. List<string> tempList = new List<string>() { dailyId.ToString() };
  2604. await AppNoticeLibrary.DailyPayReminder_Pay_ToUser(dailyId, tempList);
  2605. }
  2606. }
  2607. catch (Exception ex)
  2608. {
  2609. }
  2610. #endregion
  2611. return Ok(JsonView(true, "操作成功!"));
  2612. }
  2613. _sqlSugar.RollbackTran();
  2614. return Ok(JsonView(false, "付款状态修改失败!"));
  2615. }
  2616. /// <summary>
  2617. /// 付款申请 (PageId=51)
  2618. /// File Download
  2619. /// </summary>
  2620. /// <param name="dto"></param>
  2621. /// <returns></returns>
  2622. [HttpPost]
  2623. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2624. public async Task<IActionResult> PostPayRequestFileDownload(PayRequestFileDownloadDto dto)
  2625. {
  2626. Stopwatch stopwatch = Stopwatch.StartNew();
  2627. #region 参数,权限 验证
  2628. if (dto.PortType < 1)
  2629. {
  2630. return Ok(JsonView(false, "请传入有效的PortType参数!"));
  2631. }
  2632. if (dto.UserId < 1)
  2633. {
  2634. return Ok(JsonView(false, "请传入有效的UserId参数!"));
  2635. }
  2636. if (dto.PageId < 1)
  2637. {
  2638. dto.PageId = 51;
  2639. return Ok(JsonView(false, "请传入有效的PageId参数!"));
  2640. }
  2641. if (dto.ConpanyId < 1 || dto.ConpanyId > 4)
  2642. {
  2643. return Ok(JsonView(false, "请传入有效的ConpanyId参数!"));
  2644. }
  2645. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2646. #region 页面操作权限验证
  2647. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  2648. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权限!"));
  2649. #endregion
  2650. #endregion
  2651. try
  2652. {
  2653. PaymentRequestCheckedView checkedView = new PaymentRequestCheckedView();
  2654. var checkedStr = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>("paymentRequestCheckedData");
  2655. if (checkedStr != null)
  2656. {
  2657. checkedView = JsonConvert.DeserializeObject<PaymentRequestCheckedView>(checkedStr.ToString());
  2658. }
  2659. if (checkedView == null)
  2660. {
  2661. return Ok(JsonView(false, "没有选中的数据!"));
  2662. }
  2663. if (checkedView.GroupIds == null && checkedView.DailyPaymentIds == null)
  2664. {
  2665. return Ok(JsonView(false, "没有选中的数据!"));
  2666. }
  2667. tree_Fin_DailyFeePaymentResult dailyResult = PayRequest_DailyByDateRange(2, checkedView.DailyPaymentIds, dto.beginDt, dto.endDt);
  2668. tree_Group_DailyFeePaymentResult groupResult = PayRequest_GroupPaymentByDateRange(2, checkedView.GroupIds, checkedView.HotelSubIds, dto.beginDt, dto.endDt);
  2669. if (dailyResult.childList == null)
  2670. {
  2671. dailyResult.childList = new List<Fin_DailyFeePaymentContentInfolView>();
  2672. }
  2673. List<tree_Group_DailyFeePaymentPageListView> _GroupData = new List<tree_Group_DailyFeePaymentPageListView>();
  2674. List<tree_Fin_DailyFeePaymentPageListView> _DailyData = new List<tree_Fin_DailyFeePaymentPageListView>();
  2675. //1 成都泛美商务有限公司
  2676. if (dto.ConpanyId == 1)
  2677. {
  2678. if (groupResult.dataList != null && groupResult.dataList.Count > 0) _GroupData = groupResult.dataList.Where(it => it.CompanyId == 1).ToList();
  2679. if (dailyResult.dataList != null && dailyResult.dataList.Count > 0) _DailyData = dailyResult.dataList.Where(it => it.CompanyId == 1).ToList();
  2680. }
  2681. //2 四川泛美交流有限公司
  2682. else if (dto.ConpanyId == 2)
  2683. {
  2684. if (groupResult.dataList != null && groupResult.dataList.Count > 0) _GroupData = groupResult.dataList.Where(it => it.CompanyId == 2).ToList();
  2685. if (dailyResult.dataList != null && dailyResult.dataList.Count > 0) _DailyData = dailyResult.dataList.Where(it => it.CompanyId == 2).ToList();
  2686. }
  2687. //3 成都纽茵教育科技有限公司
  2688. else if (dto.ConpanyId == 3)
  2689. {
  2690. if (groupResult.dataList != null && groupResult.dataList.Count > 0) _GroupData = groupResult.dataList.Where(it => it.CompanyId == 3).ToList();
  2691. if (dailyResult.dataList != null && dailyResult.dataList.Count > 0) _DailyData = dailyResult.dataList.Where(it => it.CompanyId == 3).ToList();
  2692. }
  2693. //4 成都鸿企中元科技有限公司
  2694. else if (dto.ConpanyId == 4)
  2695. {
  2696. return Ok(JsonView(false, "暂未开放该类型!"));
  2697. }
  2698. else
  2699. {
  2700. return Ok(JsonView(false, "参数ConpanyId不可使用!"));
  2701. }
  2702. string _requestPaymentDt = DateTime.Now.ToString("yyyy-MM-dd"),//申请付款日期
  2703. _appliedAmount = "", //申请付款金额
  2704. _GZStr = "", //公转价格描述
  2705. _SZStr = ""; //私转价格描述
  2706. decimal groupGZAmout = 0.00M, groupSZAmout = 0.00M;
  2707. decimal dailyGZAmout = 0.00M, dailySZAmout = 0.00M;
  2708. string dailyGZStr = "", dailySZStr = "", groupGZStr = "", groupSZStr = "";
  2709. #region 数据处理
  2710. //团组费用相关
  2711. foreach (var item in _GroupData)
  2712. {
  2713. string groupGZSubStr = "";
  2714. string groupSZSubStr = "";
  2715. foreach (var subItem in item.ChildList)
  2716. {
  2717. if (subItem.TransferMark.Equals("公转"))
  2718. {
  2719. groupGZAmout += subItem.CNYSubTotalAmount;
  2720. groupGZSubStr += $"{subItem.RemaksDescription}\r\n";
  2721. }
  2722. else if (subItem.TransferMark.Equals("私转"))
  2723. {
  2724. groupSZAmout += subItem.CNYSubTotalAmount;
  2725. groupSZSubStr += $"{subItem.RemaksDescription}\r\n";
  2726. }
  2727. //groupGZSubStr += $"\t";
  2728. }
  2729. //if (!string.IsNullOrEmpty(groupGZSubStr)) groupGZStr += $"团组:{item.GroupName}\r\n{groupGZSubStr}\r\n";
  2730. //if (!string.IsNullOrEmpty(groupSZSubStr)) groupSZStr += $"团组:{item.GroupName}\r\n{groupSZSubStr}\r\n";
  2731. if (!string.IsNullOrEmpty(groupGZSubStr)) groupGZStr += $"{groupGZSubStr}\r\n";
  2732. if (!string.IsNullOrEmpty(groupSZSubStr)) groupSZStr += $"{groupSZSubStr}\r\n";
  2733. }
  2734. //日常费用相关
  2735. foreach (var item in _DailyData)
  2736. {
  2737. foreach (var subItem in item.childList)
  2738. {
  2739. if (item.transferParentId == 62) //公转
  2740. {
  2741. dailyGZAmout += item.SumPrice ?? 0.00M;
  2742. dailyGZStr += $"{item.RowNumber}、【{item.CompanyName}】{subItem.ExcelRemaksDescription}\r\n";
  2743. }
  2744. else if (item.transferParentId == 63) //私转
  2745. {
  2746. dailySZAmout += item.SumPrice ?? 0.00M;
  2747. dailySZStr += $"{item.RowNumber}、【{item.CompanyName}】{subItem.ExcelRemaksDescription}\r\n";
  2748. }
  2749. }
  2750. }
  2751. _GZStr = $"【公转】团组相关费用(合计:CNY {groupGZAmout.ToString("#0.00")}):\r\n{groupGZStr}【公转】日常付款费用(合计:CNY {dailyGZAmout.ToString("#0.00")}):\r\n{dailyGZStr}";
  2752. _SZStr = $"【私转】团组相关费用(合计:CNY {groupSZAmout.ToString("#0.00")}):\r\n{groupSZStr}【私转】日常付款费用(合计:CNY {dailySZAmout.ToString("#0.00")}):\r\n{dailySZStr}";
  2753. _appliedAmount = $"公转:CNY {(groupGZAmout + dailyGZAmout).ToString("#0.00")}\r\n私转:CNY {(groupSZAmout + dailySZAmout).ToString("#0.00")}";
  2754. #endregion
  2755. WorkbookDesigner designer = new WorkbookDesigner();
  2756. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/付款申请书.xls");
  2757. designer.SetDataSource("Date", _requestPaymentDt);
  2758. designer.SetDataSource("Price", _appliedAmount);
  2759. designer.SetDataSource("Content", _GZStr);
  2760. designer.SetDataSource("Content1", _SZStr);
  2761. //根据数据源处理生成报表内容
  2762. designer.Process();
  2763. string fileName = ("PayRequest/付款申请(" + dto.beginDt + "~" + dto.endDt + ").xlsx");
  2764. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  2765. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  2766. stopwatch.Stop();
  2767. return Ok(JsonView(true, $"操作成功!{stopwatch.ElapsedMilliseconds / 1000}s", new { url = rst }));
  2768. }
  2769. catch (Exception ex)
  2770. {
  2771. return Ok(JsonView(false, ex.Message));
  2772. }
  2773. }
  2774. #endregion
  2775. #region 超支费用
  2776. /// <summary>
  2777. /// 超支费用
  2778. /// 1增、2改、3删
  2779. /// </summary>
  2780. /// <param name="dto"></param>
  2781. /// <returns></returns>
  2782. [HttpPost]
  2783. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2784. public async Task<IActionResult> PostGroupExtraCost_Operator(Fin_GroupExtraCostDto_OP dto)
  2785. {
  2786. #region 验证
  2787. #endregion
  2788. Fin_GroupExtraCost _entity = new Fin_GroupExtraCost();
  2789. _entity.DiId = dto.diId;
  2790. _entity.PriceName = dto.priceName;
  2791. _entity.Price = dto.price;
  2792. _entity.PriceCurrency = dto.currency;
  2793. _entity.PriceType = dto.priceType;
  2794. _entity.Coefficient = dto.coefficient;
  2795. _entity.PriceDetailType = dto.priceDetailType;
  2796. _entity.FilePath = dto.filePath;
  2797. _entity.Remark = dto.remark;
  2798. _entity.PriceCount = dto.PriceCount;
  2799. _entity.Area = dto.Area;
  2800. DateTime dt_PriceDt;
  2801. bool b_PriceDt = DateTime.TryParse(dto.PriceDt, out dt_PriceDt);
  2802. if (b_PriceDt)
  2803. {
  2804. _entity.PriceDt = dt_PriceDt;
  2805. }
  2806. else
  2807. {
  2808. _entity.PriceDt = DateTime.MinValue;
  2809. }
  2810. _entity.PriceSum = dto.price * dto.PriceCount;
  2811. _daiRep.BeginTran();
  2812. if (dto.editType == 1)
  2813. {
  2814. _entity.CreateUserId = dto.createUser;
  2815. _entity.CreateTime = DateTime.Now;
  2816. _entity.IsDel = 0;
  2817. int returnId = await _daiRep.AddAsyncReturnId<Fin_GroupExtraCost>(_entity);
  2818. if (returnId > 0)
  2819. {
  2820. dto.Id = returnId;
  2821. }
  2822. }
  2823. else if (dto.editType == 2)
  2824. {
  2825. bool res = await _daiRep.UpdateAsync<Fin_GroupExtraCost>(s => s.Id == dto.Id, s => new Fin_GroupExtraCost
  2826. {
  2827. PriceName = dto.priceName,
  2828. Price = dto.price,
  2829. PriceCurrency = dto.currency,
  2830. PriceType = dto.priceType,
  2831. PriceDetailType = dto.priceDetailType,
  2832. Coefficient = dto.coefficient,
  2833. FilePath = dto.filePath,
  2834. Remark = dto.remark,
  2835. PriceCount = dto.PriceCount,
  2836. PriceDt = _entity.PriceDt,
  2837. PriceSum = _entity.PriceSum,
  2838. Area = _entity.Area,
  2839. });
  2840. if (!res)
  2841. {
  2842. _daiRep.RollbackTran();
  2843. return Ok(JsonView(false, "2操作失败!"));
  2844. }
  2845. }
  2846. else if (dto.editType == 3)
  2847. {
  2848. string delTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
  2849. bool res = await _daiRep.UpdateAsync<Fin_GroupExtraCost>(s => s.Id == dto.Id, s => new Fin_GroupExtraCost
  2850. {
  2851. IsDel = 1,
  2852. DeleteTime = delTime,
  2853. DeleteUserId = dto.createUser
  2854. });
  2855. if (!res)
  2856. {
  2857. _daiRep.RollbackTran();
  2858. return Ok(JsonView(false, "3操作失败!"));
  2859. }
  2860. }
  2861. else
  2862. {
  2863. _daiRep.RollbackTran();
  2864. return Ok(JsonView(false, "未知的editType"));
  2865. }
  2866. if (!extraCost_editCreditCardPayment(dto))
  2867. {
  2868. return Ok(JsonView(false, "ccp操作失败"));
  2869. }
  2870. _daiRep.CommitTran();
  2871. return Ok(JsonView(true, "操作成功"));
  2872. }
  2873. private Result PostCurrencyByDiid_Sync(int diId, int CId, int currencyId)
  2874. {
  2875. if (diId == 0)
  2876. {
  2877. return new Result() { Code = -1, Msg = "请传入团组Id!" };
  2878. }
  2879. if (CId == 0)
  2880. {
  2881. return new Result() { Code = -1, Msg = "请传入类型Id!" };
  2882. }
  2883. if (currencyId == 0)
  2884. {
  2885. return new Result() { Code = -1, Msg = "请传入币种Id!" };
  2886. }
  2887. Grp_TeamRate _TeamRate = _sqlSugar.Queryable<Grp_TeamRate>().First(a => a.DiId == diId && a.IsDel == 0 && a.CTable == CId);
  2888. List<CurrencyInfo> currencyInfos = new List<CurrencyInfo>();
  2889. CurrencyInfo CurrencyRate = new CurrencyInfo();
  2890. try
  2891. {
  2892. if (_TeamRate != null)
  2893. {
  2894. Sys_SetData _SetData = _sqlSugar.Queryable<Sys_SetData>().First(a => a.IsDel == 0 && a.Id == currencyId);
  2895. if (_SetData != null)
  2896. {
  2897. currencyInfos = CommonFun.GetCurrencyChinaToList(_TeamRate.Remark);
  2898. CurrencyRate = currencyInfos.FirstOrDefault(a => a.CurrencyCode == _SetData.Name);
  2899. if (CurrencyRate != null)
  2900. {
  2901. return new Result() { Code = 0, Msg = "查询成功!", Data = CurrencyRate };
  2902. }
  2903. else
  2904. {
  2905. return new Result() { Code = -1, Msg = "暂无团组汇率,请前往设置!", Data = CurrencyRate };
  2906. }
  2907. }
  2908. else
  2909. {
  2910. return new Result() { Code = -1, Msg = "暂无团组汇率,请前往设置!", Data = CurrencyRate };
  2911. }
  2912. }
  2913. else
  2914. {
  2915. return new Result() { Code = -1, Msg = "暂无团组汇率,请前往设置!", Data = CurrencyRate };
  2916. }
  2917. }
  2918. catch (Exception)
  2919. {
  2920. return new Result() { Code = -1, Msg = "查询异常!", Data = CurrencyRate };
  2921. }
  2922. }
  2923. private bool extraCost_editCreditCardPayment(Fin_GroupExtraCostDto_OP costDto)
  2924. {
  2925. //设置团组汇率
  2926. decimal dcm_dayrate = 1M;
  2927. decimal dcm_rmbPrice = costDto.price;
  2928. int ispay = costDto.payType == 72 ? 1 : 0;
  2929. if (costDto.costSign != 3)
  2930. {
  2931. //获取新汇率 int diId,int CId, int currencyId
  2932. Result rate = this.PostCurrencyByDiid_Sync(costDto.diId, 1015, costDto.currency);
  2933. if (rate.Code == 0)
  2934. {
  2935. var rateInfo = (rate.Data as CurrencyInfo);
  2936. if (rateInfo is not null)
  2937. {
  2938. dcm_dayrate = rateInfo.Rate;
  2939. dcm_rmbPrice = rateInfo.Rate * dcm_rmbPrice;
  2940. }
  2941. else
  2942. {
  2943. dcm_dayrate = 1;
  2944. }
  2945. }
  2946. }
  2947. Grp_CreditCardPayment ccp = _daiRep.Query<Grp_CreditCardPayment>(s => s.CId == costDto.Id && s.CTable == 1015).First();
  2948. if (ccp == null)
  2949. {
  2950. ccp = new Grp_CreditCardPayment();
  2951. ccp.PayDId = costDto.payType;// dto
  2952. ccp.ConsumptionPatterns = "";
  2953. ccp.ConsumptionDate = "";
  2954. ccp.CTDId = costDto.payCardId;// dto
  2955. ccp.BankNo = "";
  2956. ccp.CardholderName = "";
  2957. ccp.PayMoney = costDto.price;// dto
  2958. ccp.PaymentCurrency = costDto.currency;// dto
  2959. ccp.CompanyBankNo = "";
  2960. ccp.OtherBankName = "";
  2961. ccp.OtherSideNo = "";
  2962. ccp.OtherSideName = "";
  2963. ccp.Remark = "";
  2964. ccp.CreateUserId = costDto.createUser;
  2965. ccp.CreateTime = DateTime.Now;
  2966. ccp.MFOperator = 0;
  2967. ccp.MFOperatorDate = "";
  2968. ccp.IsAuditDM = 0;
  2969. ccp.AuditDMOperate = 0;
  2970. ccp.AuditDMDate = "";
  2971. ccp.IsAuditMF = 0;
  2972. ccp.AuditMFOperate = 0;
  2973. ccp.AuditMFDate = "";
  2974. ccp.IsAuditGM = 0;
  2975. ccp.AuditGMOperate = 0;
  2976. ccp.AuditGMDate = "";
  2977. ccp.IsPay = ispay; // upd
  2978. ccp.DIId = costDto.diId;// dto
  2979. ccp.CId = costDto.Id;// dto
  2980. ccp.CTable = 1015; //超支费用指向id
  2981. ccp.IsDel = 0;
  2982. ccp.PayPercentage = 100M;
  2983. ccp.PayThenMoney = 0M;
  2984. ccp.PayPercentageOld = 100M;
  2985. ccp.PayThenMoneyOld = 0M;
  2986. ccp.UpdateDate = "";
  2987. ccp.Payee = costDto.payee;// dto
  2988. ccp.OrbitalPrivateTransfer = costDto.costSign;// dto
  2989. ccp.ExceedBudget = 0;
  2990. ccp.DayRate = dcm_dayrate; //upd
  2991. ccp.RMBPrice = dcm_rmbPrice; //upd
  2992. int ccpInsertId = _daiRep.AddReturnId<Grp_CreditCardPayment>(ccp);
  2993. if (ccpInsertId > 0)
  2994. {
  2995. return true;
  2996. }
  2997. }
  2998. else
  2999. {
  3000. if (costDto.editType == 2)
  3001. {
  3002. bool res = _daiRep.Update<Grp_CreditCardPayment>(s => s.Id == ccp.Id, s => new Grp_CreditCardPayment
  3003. {
  3004. PayDId = costDto.payType,
  3005. CTDId = costDto.payCardId,
  3006. PayMoney = costDto.price,
  3007. PaymentCurrency = costDto.currency,
  3008. IsPay = ispay,
  3009. Payee = costDto.payee,
  3010. OrbitalPrivateTransfer = costDto.costSign,
  3011. DayRate = dcm_dayrate,
  3012. RMBPrice = dcm_rmbPrice
  3013. });
  3014. return res;
  3015. }
  3016. else if (costDto.editType == 3)
  3017. {
  3018. string delTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
  3019. bool res2 = _daiRep.Update<Grp_CreditCardPayment>(s => s.Id == ccp.Id, s => new Grp_CreditCardPayment
  3020. {
  3021. IsDel = 1,
  3022. DeleteTime = delTime,
  3023. DeleteUserId = costDto.createUser
  3024. });
  3025. return res2;
  3026. }
  3027. }
  3028. return false;
  3029. }
  3030. /// <summary>
  3031. /// 超支费用
  3032. /// 详情查询
  3033. /// </summary>
  3034. /// <param name="dto"></param>
  3035. /// <returns></returns>
  3036. [HttpPost]
  3037. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3038. public async Task<IActionResult> PostGroupExtraCost_Detail(Fin_GroupExtraCostDto_Detail dto)
  3039. {
  3040. if (dto.Id < 1)
  3041. {
  3042. return Ok(JsonView(false, "查询失败"));
  3043. }
  3044. string sql = string.Format(@" Select
  3045. f.Id,f.DiId,
  3046. f.PriceName,f.Price,f.PriceCurrency,c.Payee,c.OrbitalPrivateTransfer,c.PayDId,f.area,
  3047. c.CTDId,f.PriceType,f.PriceDetailType,f.Coefficient,f.Remark,f.PriceCount,f.PriceDt
  3048. From Fin_GroupExtraCost f
  3049. Inner Join Grp_CreditCardPayment c On f.Id = c.CId
  3050. Left Join Sys_Users u On f.CreateUserId = u.Id
  3051. Where f.IsDel=0 And c.CTable = 1015
  3052. And f.Id = {0} ", dto.Id);
  3053. Fin_GroupExtraCostDetailView detailView = await _sqlSugar.SqlQueryable<Fin_GroupExtraCostDetailView>(sql).FirstAsync();
  3054. if (detailView == null)
  3055. {
  3056. return Ok(JsonView(false, "查询失败"));
  3057. }
  3058. return Ok(JsonView(true, "查询成功", detailView));
  3059. }
  3060. /// <summary>
  3061. /// 超支费用
  3062. /// 列表查询
  3063. /// </summary>
  3064. /// <param name="dto"></param>
  3065. /// <returns></returns>
  3066. [HttpPost]
  3067. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3068. public async Task<IActionResult> PostGroupExtraCost_Search(Fin_GroupExtraCostDto_Search dto)
  3069. {
  3070. string sqlWhere = string.Format(@" And f.DiId = {0} ", dto.diId);
  3071. int startIndex = (dto.PageIndex - 1) * dto.PageSize + 1;
  3072. int endIndex = startIndex + dto.PageSize - 1;
  3073. string sql_data = string.Format(@"Select * From (
  3074. Select row_number() over (order by f.Id Desc) as RowNumber,f.Id,f.DiId,
  3075. 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,
  3076. f.CreateUserId,f.PriceDt,c.IsAuditGM
  3077. From Fin_GroupExtraCost f
  3078. Inner Join Grp_CreditCardPayment c On f.Id = c.CId
  3079. Inner Join Sys_SetData s On f.PriceCurrency = s.Id
  3080. Left Join Sys_Users u On f.CreateUserId = u.Id
  3081. Where f.IsDel=0 And c.CTable = 1015 {0}
  3082. ) temp Where RowNumber Between {1} and {2}", sqlWhere, startIndex, endIndex);
  3083. string sql_count = string.Format(@"Select Count(1) as DataCount From (
  3084. Select row_number() over (order by f.Id Desc) as RowNumber,f.Id,f.DiId,
  3085. f.PriceName,f.PriceType,f.Price,f.FilePath,f.CreateUserId,f.CreateTime,c.IsAuditGM
  3086. From Fin_GroupExtraCost f
  3087. Inner Join Grp_CreditCardPayment c On f.Id = c.CId
  3088. Inner Join Sys_SetData s On f.PriceCurrency = s.Id
  3089. Left Join Sys_Users u On f.CreateUserId = u.Id
  3090. Where f.IsDel=0 And c.CTable = 1015 {0}
  3091. ) temp ", sqlWhere);
  3092. if (dto.PortType == 1 || dto.PortType == 2 || dto.PortType == 3) //web
  3093. {
  3094. //Fin_DailyFeePaymentPageCount
  3095. var count = await _sqlSugar.SqlQueryable<Fin_GroupExtraCostViewDataCount>(sql_count).FirstAsync();
  3096. List<Fin_GroupExtraCostView> dataList = await _sqlSugar.SqlQueryable<Fin_GroupExtraCostView>(sql_data).ToListAsync();
  3097. Dictionary<int, string> dic_setData = new Dictionary<int, string>();
  3098. Dictionary<int, string> dic_user = new Dictionary<int, string>();
  3099. foreach (var item in dataList)
  3100. {
  3101. DateTime dtTemp_PriceDt;
  3102. bool b_ct = DateTime.TryParse(item.PriceDt, out dtTemp_PriceDt);
  3103. if (b_ct)
  3104. {
  3105. item.PriceDt = dtTemp_PriceDt.ToString("yyyy-MM-dd");
  3106. }
  3107. //费用类型
  3108. if (dic_setData.ContainsKey(item.PriceType))
  3109. {
  3110. item.PriceTypeStr = dic_setData[item.PriceType];
  3111. }
  3112. else
  3113. {
  3114. Sys_SetData sd_priceTypeDetail = _daiRep.Query<Sys_SetData>(s => s.Id == item.PriceType).First();
  3115. if (sd_priceTypeDetail != null)
  3116. {
  3117. string tempName = sd_priceTypeDetail.Name.Replace("n", "");
  3118. item.PriceTypeStr = tempName;
  3119. dic_setData.Add(item.PriceType, tempName);
  3120. }
  3121. }
  3122. if (item.PriceDetailType > 0)
  3123. {
  3124. if (dic_setData.ContainsKey(item.PriceDetailType))
  3125. {
  3126. item.PriceTypeStr = item.PriceTypeStr + " - " + dic_setData[item.PriceDetailType];
  3127. }
  3128. else
  3129. {
  3130. Sys_SetData sd_priceTypeDetail = _daiRep.Query<Sys_SetData>(s => s.Id == item.PriceDetailType).First();
  3131. if (sd_priceTypeDetail != null)
  3132. {
  3133. string tempName = sd_priceTypeDetail.Name.Replace("n", "");
  3134. item.PriceTypeStr = item.PriceTypeStr + " - " + tempName;
  3135. dic_setData.Add(item.PriceDetailType, tempName);
  3136. }
  3137. }
  3138. }
  3139. //系统用户
  3140. if (dic_user.ContainsKey(item.CreateUserId))
  3141. {
  3142. item.CreateUserIdStr = dic_user[item.CreateUserId];
  3143. }
  3144. else
  3145. {
  3146. Sys_Users users = _daiRep.Query<Sys_Users>(s => s.Id == item.CreateUserId).First();
  3147. if (users != null)
  3148. {
  3149. item.CreateUserIdStr = users.CnName;
  3150. dic_user.Add(item.CreateUserId, users.CnName);
  3151. }
  3152. }
  3153. switch (item.IsAuditGM)
  3154. {
  3155. case 0: item.IsAuditGMStr = "未审核"; break;
  3156. case 1: item.IsAuditGMStr = "已通过"; break;
  3157. case 2: item.IsAuditGMStr = "未通过"; break;
  3158. default: item.IsAuditGMStr = "未知状态"; break;
  3159. }
  3160. }
  3161. var result = new ListViewBase<Fin_GroupExtraCostView>
  3162. {
  3163. CurrPageIndex = dto.PageIndex,
  3164. CurrPageSize = dto.PageSize,
  3165. DataCount = count.DataCount,
  3166. DataList = dataList
  3167. };
  3168. return Ok(JsonView(true, "查询成功", result));
  3169. }
  3170. return Ok(JsonView(false, "查询失败"));
  3171. }
  3172. /// <summary>
  3173. /// 超支费用
  3174. /// 数据集合配置
  3175. /// </summary>
  3176. /// <param name="dto"></param>
  3177. /// <returns></returns>
  3178. [HttpPost]
  3179. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3180. public async Task<IActionResult> PostGroupExtraCost_ListDataInit(Fin_GroupExtraCostDto_DataListInit dto)
  3181. {
  3182. //支付方式
  3183. List<Sys_SetData> Payment = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 14 && a.IsDel == 0).ToList();
  3184. List<SetDataInfoView> _Payment = _mapper.Map<List<SetDataInfoView>>(Payment);
  3185. //信用卡类型
  3186. List<Sys_SetData> Card = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 15 && a.IsDel == 0).ToList();
  3187. List<SetDataInfoView> _Card = _mapper.Map<List<SetDataInfoView>>(Card);
  3188. //超支费用类型
  3189. List<Sys_SetData> PriceType = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 79 && a.IsDel == 0).ToList();
  3190. List<SetDataInfoView> _PriceType = _mapper.Map<List<SetDataInfoView>>(PriceType);
  3191. //超支费用详细类型
  3192. List<Sys_SetData> PriceDetailType = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 80 && a.IsDel == 0).ToList();
  3193. PriceDetailType.ForEach(a => { a.Name = a.Name.Replace("n", ""); });
  3194. List<SetDataInfoView> _PriceDetailType = _mapper.Map<List<SetDataInfoView>>(PriceDetailType);
  3195. var data = new
  3196. {
  3197. Payment = _Payment,
  3198. Card = _Card,
  3199. PriceType = _PriceType,
  3200. PriceDetailType = _PriceDetailType
  3201. };
  3202. return Ok(JsonView(true, "", data));
  3203. }
  3204. /// <summary>
  3205. /// 超支费用
  3206. /// 导出团组超支费用Excel
  3207. /// </summary>
  3208. /// <param name="dto"></param>
  3209. /// <returns></returns>
  3210. [HttpPost]
  3211. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3212. public async Task<IActionResult> PostGroupExtraCost_OutputExcel(Fin_GroupExtraCostExcelDto dto)
  3213. {
  3214. string sqlGroup = string.Format(@" Select * From Grp_DelegationInfo WIth(Nolock) where Id = {0} ", dto.diId);
  3215. Grp_DelegationInfo grp_DelegationInfo = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sqlGroup).FirstAsync();
  3216. if (grp_DelegationInfo == null)
  3217. {
  3218. return Ok(JsonView(false, "导出失败,未查询到团组"));
  3219. }
  3220. Workbook workbook = new Workbook();
  3221. Worksheet sheet = workbook.Worksheets[0];
  3222. Cells cells = sheet.Cells;
  3223. //sheet.Protect(Aspose.Cells.ProtectionType.All, "123123", "");//保护工作表
  3224. //sheet.Protection.IsSelectingLockedCellsAllowed = true;//设置只能选择解锁单元格
  3225. //sheet.Protection.IsFormattingColumnsAllowed = true;//设置可以调整列
  3226. //sheet.Protection.IsFormattingRowsAllowed = true;//设置可以调整行
  3227. #region 数据源
  3228. string sqlData = string.Format(@" Select f.PriceType,REPLACE(s2.[Name],'超支费用','') as PriceTypeStr,'('+REPLACE(s3.[Name],'n','')+')' as PriceDetailTypeStr, PriceDt,PriceName,
  3229. Price,PriceCount,s.[Name] as Currency,PriceSum,f.Remark
  3230. From Fin_GroupExtraCost as f With(Nolock)
  3231. Inner Join Grp_CreditCardPayment as c With(Nolock) On f.Id = c.CId
  3232. Inner Join Sys_SetData as s With(Nolock) On f.PriceCurrency = s.Id
  3233. Inner Join Sys_SetData as s2 With(Nolock) On f.PriceType = s2.Id
  3234. Inner Join Sys_SetData as s3 With(Nolock) On f.PriceDetailType = s3.Id
  3235. Where f.DiId = {0} And f.IsDel=0 And c.CTable=1015
  3236. Order by PriceType ASC,PriceDt ASC ", dto.diId);
  3237. string sqlDataCount = string.Format(@" Select f.PriceType,COUNT(f.PriceType) as DataCount
  3238. From Fin_GroupExtraCost as f With(Nolock)
  3239. Inner Join Grp_CreditCardPayment as c With(Nolock) On f.Id = c.CId
  3240. Where f.DiId = {0} And f.IsDel=0 And c.CTable=1015
  3241. Group by PriceType ", dto.diId);
  3242. List<Fin_GroupExtraCost_ExcelView> dataList = await _sqlSugar.SqlQueryable<Fin_GroupExtraCost_ExcelView>(sqlData).ToListAsync();
  3243. List<Fin_GroupExtraCost_ExcelCountView> countList = await _sqlSugar.SqlQueryable<Fin_GroupExtraCost_ExcelCountView>(sqlDataCount).ToListAsync();
  3244. if (dataList.Count < 1 || countList.Count < 1)
  3245. {
  3246. return Ok(JsonView(false, "导出失败,未查询到数据"));
  3247. }
  3248. #endregion
  3249. #region 标题
  3250. string cellValue_Header = grp_DelegationInfo.TeamName;
  3251. //Aspose.Cells.Style style1 = workbook.Styles[workbook.Styles.Add()];//新增样式
  3252. Aspose.Cells.Style style_Header = workbook.CreateStyle();
  3253. style_Header.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  3254. style_Header.VerticalAlignment = TextAlignmentType.Center;
  3255. style_Header.Font.Name = "微软雅黑";//文字字体
  3256. style_Header.Font.Size = 18;//文字大小
  3257. style_Header.IsLocked = false;//单元格解锁
  3258. style_Header.Font.IsBold = false;//粗体
  3259. style_Header.Font.Color = Color.FromArgb(255, 0, 0);
  3260. //style1.ForegroundColor = Color.FromArgb(0x99, 0xcc, 0xff);//设置背景色
  3261. //style1.Pattern = BackgroundType.Solid; //设置背景样式
  3262. //style1.IsTextWrapped = true;//单元格内容自动换行
  3263. style_Header.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
  3264. style_Header.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
  3265. style_Header.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
  3266. style_Header.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
  3267. cells.Merge(1, 1, 1, 10);
  3268. Aspose.Cells.Range range_header = cells.CreateRange(1, 1, 1, 10);
  3269. range_header.PutValue(cellValue_Header, false, false);
  3270. range_header.SetStyle(style_Header);
  3271. cells.SetRowHeight(1, 35);
  3272. #endregion
  3273. #region 列名
  3274. Aspose.Cells.Style style_colName = workbook.CreateStyle();
  3275. style_colName.Name = "colName";
  3276. style_colName.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  3277. style_colName.VerticalAlignment = TextAlignmentType.Center;
  3278. style_colName.Font.Name = "微软雅黑";//文字字体
  3279. style_colName.Font.Size = 12;//文字大小
  3280. style_colName.IsLocked = false;//单元格解锁
  3281. style_colName.Font.IsBold = true;//粗体
  3282. style_colName.Font.Color = Color.FromArgb(0, 0, 0);
  3283. style_colName.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
  3284. style_colName.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
  3285. style_colName.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
  3286. style_colName.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
  3287. List<Fin_GroupExtraCostExcelColumnSetting> colNameSettingList = new List<Fin_GroupExtraCostExcelColumnSetting>()
  3288. {
  3289. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 1, columnName="类型", columnWidth= 25},
  3290. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 2, columnName="时间", columnWidth= 16},
  3291. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 3, columnName="内容", columnWidth= 35},
  3292. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 4, columnName="单价", columnWidth= 12},
  3293. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 5, columnName="数量", columnWidth= 12},
  3294. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 6, columnName="货币", columnWidth= 12},
  3295. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 7, columnName="费用", columnWidth= 12},
  3296. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 8, columnName="汇率", columnWidth= 12},
  3297. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 9, columnName="人民币", columnWidth= 12},
  3298. new Fin_GroupExtraCostExcelColumnSetting(){ columnIndex = 10, columnName="备注信息", columnWidth= 24}
  3299. };
  3300. foreach (var col in colNameSettingList)
  3301. {
  3302. cells[2, col.columnIndex].PutValue(col.columnName);
  3303. cells[2, col.columnIndex].SetStyle(style_colName);
  3304. cells.SetColumnWidth(col.columnIndex, col.columnWidth);
  3305. }
  3306. cells.SetRowHeight(2, 25);
  3307. #endregion
  3308. #region 数据填充
  3309. Aspose.Cells.Style style_dataCol = workbook.GetNamedStyle("colName");
  3310. style_dataCol.Font.IsBold = false;
  3311. style_dataCol.Name = "dataCol";
  3312. Aspose.Cells.Style style_dataBlue = workbook.CreateStyle();
  3313. style_dataBlue.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  3314. style_dataBlue.VerticalAlignment = TextAlignmentType.Center;
  3315. style_dataBlue.Font.Name = "微软雅黑";//文字字体
  3316. style_dataBlue.Font.Size = 12;//文字大小
  3317. style_dataBlue.IsLocked = false;//单元格解锁
  3318. style_dataBlue.Font.IsBold = false;//粗体
  3319. style_dataBlue.ForegroundColor = Color.FromArgb(189, 215, 238);
  3320. style_dataBlue.Pattern = BackgroundType.Solid;
  3321. style_dataBlue.Font.Color = Color.FromArgb(0, 0, 0);
  3322. style_dataBlue.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
  3323. style_dataBlue.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
  3324. style_dataBlue.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
  3325. style_dataBlue.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
  3326. Aspose.Cells.Style style_dataYellow = workbook.CreateStyle();
  3327. style_dataYellow.HorizontalAlignment = TextAlignmentType.Center;//文字居中
  3328. style_dataYellow.VerticalAlignment = TextAlignmentType.Center;
  3329. style_dataYellow.Font.Name = "微软雅黑";//文字字体
  3330. style_dataYellow.Font.Size = 12;//文字大小
  3331. style_dataYellow.IsLocked = false;//单元格解锁
  3332. style_dataYellow.Font.IsBold = false;//粗体
  3333. style_dataYellow.ForegroundColor = Color.FromArgb(255, 242, 204);
  3334. style_dataYellow.Pattern = BackgroundType.Solid;
  3335. style_dataYellow.Font.Color = Color.FromArgb(0, 0, 0);
  3336. style_dataYellow.Borders[Aspose.Cells.BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
  3337. style_dataYellow.Borders[Aspose.Cells.BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
  3338. style_dataYellow.Borders[Aspose.Cells.BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
  3339. style_dataYellow.Borders[Aspose.Cells.BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
  3340. int rowIndex = 4;
  3341. foreach (var d in dataList)
  3342. {
  3343. //内容
  3344. string typeStr = d.PriceDetailTypeStr + d.PriceName;
  3345. cells["B" + rowIndex.ToString()].PutValue(d.PriceTypeStr);
  3346. cells["C" + rowIndex.ToString()].PutValue(d.PriceDtStr);
  3347. cells["D" + rowIndex.ToString()].PutValue(typeStr);
  3348. cells["E" + rowIndex.ToString()].PutValue(d.Price.ToString("#0.00"));
  3349. cells["F" + rowIndex.ToString()].PutValue(d.PriceCount);
  3350. cells["G" + rowIndex.ToString()].PutValue(d.Currency);
  3351. cells["H" + rowIndex.ToString()].PutValue(d.PriceSum.ToString("#0.00"));
  3352. cells["K" + rowIndex.ToString()].PutValue(d.Remark);
  3353. //样式
  3354. cells["B" + rowIndex.ToString()].SetStyle(style_dataCol);
  3355. cells["C" + rowIndex.ToString()].SetStyle(style_dataCol);
  3356. cells["D" + rowIndex.ToString()].SetStyle(style_dataCol);
  3357. cells["E" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3358. cells["F" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3359. cells["G" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3360. cells["H" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3361. cells["I" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3362. cells["J" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3363. cells["K" + rowIndex.ToString()].SetStyle(style_dataYellow);
  3364. //公式
  3365. cells["H" + rowIndex.ToString()].Formula = string.Format(@"E{0}*F{0}", rowIndex);
  3366. cells["J" + rowIndex.ToString()].Formula = string.Format(@"H{0}*I{0}", rowIndex);
  3367. cells.SetRowHeight(rowIndex - 1, 25);
  3368. rowIndex++;
  3369. }
  3370. cells["B" + rowIndex.ToString()].SetStyle(style_dataCol);
  3371. cells["C" + rowIndex.ToString()].SetStyle(style_dataCol);
  3372. cells["D" + rowIndex.ToString()].SetStyle(style_dataCol);
  3373. cells["E" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3374. cells["F" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3375. cells["G" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3376. cells["H" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3377. cells["I" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3378. cells["J" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3379. cells["K" + rowIndex.ToString()].SetStyle(style_dataYellow);
  3380. rowIndex++;
  3381. cells["B" + rowIndex.ToString()].SetStyle(style_dataCol);
  3382. cells["C" + rowIndex.ToString()].SetStyle(style_dataCol);
  3383. cells["D" + rowIndex.ToString()].SetStyle(style_dataCol);
  3384. cells["E" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3385. cells["F" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3386. cells["G" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3387. cells["H" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3388. cells["I" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3389. cells["J" + rowIndex.ToString()].SetStyle(style_dataBlue);
  3390. cells["K" + rowIndex.ToString()].SetStyle(style_dataYellow);
  3391. rowIndex = 3;
  3392. int tempPriceType = 0;
  3393. foreach (var c in dataList)
  3394. {
  3395. if (tempPriceType == c.PriceType)
  3396. {
  3397. continue;
  3398. }
  3399. tempPriceType = c.PriceType;
  3400. int _rowCount = countList.First(s => s.PriceType == tempPriceType).DataCount;
  3401. cells.Merge(rowIndex, 1, _rowCount, 1);
  3402. Aspose.Cells.Range tempRange = cells.CreateRange(rowIndex, 1, _rowCount, 1);
  3403. rowIndex += _rowCount;
  3404. }
  3405. rowIndex = 4 + dataList.Count;
  3406. cells["D" + rowIndex.ToString()].PutValue("合计");
  3407. cells["J" + rowIndex.ToString()].Formula = string.Format(@"SUM(J4,J{0})", rowIndex - 1);
  3408. cells.SetRowHeight(rowIndex - 1, 25);
  3409. rowIndex++;
  3410. cells["D" + rowIndex.ToString()].PutValue("服务费10%开票税金8%");
  3411. cells["J" + rowIndex.ToString()].Formula = string.Format(@"J{0}*1.1*1.08", rowIndex - 1);
  3412. cells.SetRowHeight(rowIndex - 1, 25);
  3413. #endregion
  3414. #region IO
  3415. System.IO.MemoryStream ms = workbook.SaveToStream();//生成数据流
  3416. string fileName = ("GroupExtraCost/超支费用(" + cellValue_Header + ").xlsx");
  3417. byte[] bt = ms.ToArray();
  3418. workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  3419. #endregion
  3420. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  3421. return Ok(JsonView(true, "成功", new { url = rst }));
  3422. }
  3423. /// <summary>
  3424. /// 超支费用Excel导出
  3425. /// </summary>
  3426. /// <param name="dto"></param>
  3427. /// <returns></returns>
  3428. [HttpPost]
  3429. public IActionResult ExportOverspendExcel(Fin_GroupExtraCostExcelDto dto)
  3430. {
  3431. var jw = JsonView(false);
  3432. var grp_DelegationInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().First(x => x.Id == dto.diId && x.IsDel == 0);
  3433. if (grp_DelegationInfo == null)
  3434. {
  3435. return Ok(JsonView(false, "团组信息有误!"));
  3436. }
  3437. Dictionary<int, int> dicSoure = new Dictionary<int, int>()
  3438. {
  3439. {1077,1074 },
  3440. {1078,1075 },
  3441. {1079,1076 }
  3442. };
  3443. Dictionary<int, int> mealsDic = new Dictionary<int, int>()
  3444. {
  3445. {988,1074},
  3446. {93,1075},
  3447. {989,1076},
  3448. };
  3449. var checkBoxDataArr = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 17).ToList();
  3450. var CurrDataArr = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 66).ToList();
  3451. var joinTable = _sqlSugar.Queryable<Fin_GroupExtraCost, Grp_CreditCardPayment, Sys_SetData, Grp_NationalTravelFee ,
  3452. Fin_LocalGuideRelevancyOverspend , Grp_CarTouristGuideGroundReservations, Sys_SetData,Grp_DelegationInfo>(
  3453. (f, c, s, g, r ,l, s1,i) => new JoinQueryInfos(
  3454. JoinType.Left, f.Id == c.CId && c.CTable == 1015 && c.IsDel == 0,
  3455. JoinType.Left, c.PaymentCurrency == s.Id && s.IsDel == 0,
  3456. JoinType.Left, g.IsDel == 0 && g.Id == f.Area,
  3457. JoinType.Left, f.Id == r.OverspendId && r.IsDel == 0,
  3458. JoinType.Left, l.Id == r.LocalGuideId && l.IsDel == 0,
  3459. JoinType.Left, s1.Id == l.toCurr && s1.IsDel == 0,
  3460. JoinType.Left, i.Id == l.DiId && i.IsDel == 0
  3461. ))
  3462. .Where((f, c, s, g) => f.IsDel == 0 && f.DiId == dto.diId)
  3463. .Select((f, c, s, g, r, l,s1,i) => new
  3464. {
  3465. c.PaymentCurrency,
  3466. c.DayRate,
  3467. PaymentCurrencyStr = s.Name,
  3468. f.PriceName,
  3469. f.Remark,
  3470. f.PriceCount,
  3471. Price = f.Price * f.Coefficient,
  3472. c.PayMoney,
  3473. RMBPrice = c.RMBPrice * f.Coefficient,
  3474. Offer = c.RMBPrice * f.PriceCount * f.Coefficient,
  3475. c.CTable,
  3476. f.PriceDetailType,
  3477. Area = g.Country ?? "未选择地区!",
  3478. l.toCurr,
  3479. l.Rate,
  3480. toCurrStr = s1.Name,
  3481. g.FoodCost,
  3482. CarParentId = l.Id,
  3483. f.PriceDt,
  3484. i.VisitPNumber,
  3485. f.DiId,
  3486. f.PriceCurrency
  3487. })
  3488. .ToList()
  3489. .Select(x =>
  3490. {
  3491. var costPirce = x.Price;
  3492. decimal costRMBPrice = x.RMBPrice;
  3493. decimal costDayRate = x.DayRate;
  3494. string remake = x.Remark;
  3495. if (x.VisitPNumber > 0 && x.PriceDetailType != 1088)
  3496. {
  3497. decimal.TryParse(x.FoodCost, out decimal cost);
  3498. cost /= 2;
  3499. decimal oldPrice = costPirce;
  3500. costPirce *= x.Rate; //转换币种
  3501. if (x.toCurr != x.PaymentCurrency)
  3502. {
  3503. var rate = _setDataRep.PostCurrencyByDiid(x.DiId, 1015, x.toCurr).Result;
  3504. if (rate.Code == 0)
  3505. {
  3506. var rateData = rate.Data as CurrencyInfo;
  3507. if (rateData != null)
  3508. {
  3509. costDayRate = rateData.Rate;
  3510. }
  3511. }
  3512. }
  3513. if (dicSoure.Keys.Contains(x.PriceDetailType))
  3514. {
  3515. var CarCenter = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(x1 => x1.CTGGRId == x.CarParentId && x1.IsDel == 0
  3516. && x1.SId == mealsDic.First(x2 => x2.Value == dicSoure[x.PriceDetailType]).Key ).ToList().First(x1=> (DateTime.Compare(x1.DatePrice.ObjToDate(), x.PriceDt) == 0));
  3517. costPirce += (CarCenter.Price * CarCenter.Count * x.Rate);
  3518. oldPrice += (CarCenter.Price * CarCenter.Count);
  3519. var costResultPirce = costPirce - x.VisitPNumber * cost;
  3520. costResultPirce = Convert.ToInt32(Math.Round(costResultPirce));
  3521. var findCheck = checkBoxDataArr.Find(s => s.Id == CarCenter.SId);
  3522. if (x.toCurr != x.PaymentCurrency)
  3523. {
  3524. remake += $"{x.PriceDt.ToString("M/d")} {findCheck?.Name} {x.PaymentCurrencyStr} {(int)Math.Round(oldPrice)}( 折算{x.toCurrStr} {(int)Math.Round(costPirce)}) - 财政{cost} * {x.VisitPNumber} = {x.toCurrStr}{costResultPirce}";
  3525. }
  3526. else
  3527. {
  3528. remake += $"{x.PriceDt.ToString("M/d")} {findCheck?.Name}{x.PaymentCurrencyStr} {(int)Math.Round(costPirce)} - 财政{cost} * {x.VisitPNumber} = {x.PaymentCurrencyStr}{costResultPirce}";
  3529. }
  3530. costPirce = costResultPirce;
  3531. }
  3532. else
  3533. {
  3534. costPirce = Convert.ToInt32(Math.Round(costPirce));
  3535. }
  3536. costRMBPrice = Convert.ToInt32(Math.Round(costPirce * costDayRate));
  3537. }
  3538. return new
  3539. {
  3540. x.PaymentCurrency,
  3541. DayRate = costDayRate,
  3542. x.PaymentCurrencyStr,
  3543. x.PriceName,
  3544. Remark = remake,
  3545. x.PriceCount,
  3546. Price = costPirce,
  3547. x.PayMoney,
  3548. RMBPrice = costRMBPrice,
  3549. Offer = costRMBPrice * x.PriceCount,
  3550. x.CTable,
  3551. x.PriceDetailType,
  3552. x.Area,
  3553. x.toCurr,
  3554. x.toCurrStr,
  3555. ItemPrice = costPirce * x.PriceCount,
  3556. };
  3557. })
  3558. .ToList();
  3559. var PriceDetailTypeArr = new int[] { 1088 , 1074, 1075, 1076 };
  3560. var whereArr = joinTable.Where(x => PriceDetailTypeArr.Contains(x.PriceDetailType)).ToList();
  3561. _ = joinTable.RemoveAll(x => PriceDetailTypeArr.Contains(x.PriceDetailType));
  3562. foreach (var item in whereArr)
  3563. {
  3564. joinTable.Insert(0, item);
  3565. }
  3566. var dicClounm = new Dictionary<int, string>()
  3567. {
  3568. { 0,"Area" },
  3569. { 1,"PriceName" },
  3570. { 2,"Remark" },
  3571. { 3,"PriceCount" },
  3572. { 4,"Price" },
  3573. { 5,"ItemPrice" },
  3574. { 6,"DayRate" },
  3575. { 7,"Offer" },
  3576. };
  3577. var rowStartIndex = 2;
  3578. string filePath = AppSettingsHelper.Get("ExcelBasePath") + "\\Template\\超支费用表.xlsx";
  3579. IWorkbook workbook = new XSSFWorkbook(new FileStream(filePath, FileMode.Open, FileAccess.Read));
  3580. ISheet sheet = workbook.GetSheetAt(0);
  3581. var initStyleRow = sheet.GetRow(2);
  3582. var clounmCount = dicClounm.Count;
  3583. Action cloneRowFn = () =>
  3584. {
  3585. rowStartIndex++;
  3586. var cloneRow = sheet.CreateRow(rowStartIndex);
  3587. // 复制样式
  3588. for (int i = initStyleRow.FirstCellNum; i < initStyleRow.LastCellNum; i++)
  3589. {
  3590. ICell sourceCell = initStyleRow.GetCell(i);
  3591. ICell targetCell = cloneRow.GetCell(i) ?? cloneRow.CreateCell(i);
  3592. // 确保单元格存在样式
  3593. if (sourceCell.CellStyle != null)
  3594. {
  3595. targetCell.CellStyle = sourceCell.CellStyle;
  3596. }
  3597. }
  3598. };
  3599. sheet.GetRow(0).GetCell(0).SetCellValue($"{grp_DelegationInfo.TeamName}—超支费用");
  3600. foreach (var item in joinTable)
  3601. {
  3602. for (int i = 0; i < clounmCount; i++)
  3603. {
  3604. string property = dicClounm[i];
  3605. string value = item.GetType()!.GetProperty(property)!.GetValue(item)?.ToString() ?? "";
  3606. sheet.GetRow(rowStartIndex).GetCell(i).SetCellValue(value);
  3607. }
  3608. cloneRowFn();
  3609. }
  3610. sheet.GetRow(rowStartIndex).GetCell(2).SetCellValue($"小计:");
  3611. sheet.GetRow(rowStartIndex).GetCell(3).SetCellValue($"{joinTable.Sum(x=>x.RMBPrice)}元");
  3612. var path = $"GroupExtraCost/{grp_DelegationInfo.TeamName}_超支费用.xlsx";
  3613. using (var stream = new MemoryStream())
  3614. {
  3615. workbook.Write(stream, true);
  3616. stream.Flush();
  3617. stream.Seek(0, SeekOrigin.Begin);
  3618. var pathinfo = AppSettingsHelper.Get("ExcelBasePath") + path;
  3619. if (System.IO.File.Exists(pathinfo))
  3620. {
  3621. System.IO.File.Delete(pathinfo);
  3622. }
  3623. stream.SaveToFile(AppSettingsHelper.Get("ExcelBasePath") + path);
  3624. }
  3625. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + path;
  3626. jw = JsonView(true, "成功", new { url = rst });
  3627. return Ok(jw);
  3628. }
  3629. /// <summary>
  3630. /// 获取超支系数配置
  3631. /// </summary>
  3632. /// <returns></returns>
  3633. [HttpPost]
  3634. public IActionResult QueryCoefficientConfig()
  3635. {
  3636. var arr = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.STid == 80 && x.IsDel == 0).ToList();
  3637. var carCoefficient = new int[] { 1050 }; //2.4
  3638. var menpiaoCoefficient = new int[] { 1086 }; // 1.2
  3639. var airCoefficient = new int[] { 1035, 1036 }; // 2.0
  3640. var HotelCoefficient = new int[] { 1044, 1045, 1046, 1041, 1042, 1043, 1038 }; // 1.5
  3641. var fanyiCoefficient = new int[] { 1087 }; // 1.5
  3642. var resultArr = new
  3643. ArrayList();
  3644. foreach (var item in arr)
  3645. {
  3646. var a = new { coefficient = 1M, id = 0 };
  3647. if (carCoefficient.Contains(item.Id))
  3648. {
  3649. a = a with
  3650. {
  3651. coefficient = 2.4M,
  3652. id = item.Id
  3653. };
  3654. }
  3655. else if (menpiaoCoefficient.Contains(item.Id))
  3656. {
  3657. a = a with
  3658. {
  3659. coefficient = 1.2M,
  3660. id = item.Id
  3661. };
  3662. }
  3663. else if (airCoefficient.Contains(item.Id))
  3664. {
  3665. a = a with
  3666. {
  3667. coefficient = 2.0M,
  3668. id = item.Id
  3669. };
  3670. }
  3671. else if (HotelCoefficient.Contains(item.Id))
  3672. {
  3673. a = a with
  3674. {
  3675. coefficient = 1.5M,
  3676. id = item.Id
  3677. };
  3678. }
  3679. else if (fanyiCoefficient.Contains(item.Id))
  3680. {
  3681. a = a with
  3682. {
  3683. coefficient = 1.5M,
  3684. id = item.Id
  3685. };
  3686. }
  3687. else
  3688. {
  3689. a = a with
  3690. {
  3691. coefficient = 1M,
  3692. id = item.Id
  3693. };
  3694. }
  3695. resultArr.Add(a);
  3696. }
  3697. return Ok(JsonView(true, "获取成功!", resultArr));
  3698. }
  3699. #endregion
  3700. #region 信用卡对账
  3701. /// <summary>
  3702. ///将指定的Excel的文件转换成DataTable (Excel的第一个sheet)
  3703. /// </summary>
  3704. /// <param name="fullFielPath">文件的绝对路径</param>
  3705. /// <returns></returns>
  3706. private DataTable WorksheetToTable(string fullFielPath, string sheetName = null)
  3707. {
  3708. //如果是“EPPlus”,需要指定LicenseContext。
  3709. //EPPlus.Core 不需要指定。
  3710. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  3711. FileInfo existingFile = new FileInfo(fullFielPath);
  3712. ExcelPackage package = new ExcelPackage(existingFile);
  3713. ExcelWorksheet worksheet = null;
  3714. if (string.IsNullOrEmpty(sheetName))
  3715. {
  3716. //不传入 sheetName 默认取第1个sheet。
  3717. //EPPlus 索引是0
  3718. //EPPlus.Core 索引是1
  3719. worksheet = package.Workbook.Worksheets[0];
  3720. }
  3721. else
  3722. {
  3723. worksheet = package.Workbook.Worksheets[sheetName];
  3724. }
  3725. if (worksheet == null)
  3726. throw new Exception("指定的sheetName不存在");
  3727. return WorksheetToTable(worksheet);
  3728. }
  3729. /// <summary>
  3730. /// 将worksheet转成datatable
  3731. /// </summary>
  3732. /// <param name="worksheet">待处理的worksheet</param>
  3733. /// <returns>返回处理后的datatable</returns>
  3734. private DataTable WorksheetToTable(ExcelWorksheet worksheet)
  3735. {
  3736. //获取worksheet的行数
  3737. int rows = worksheet.Dimension.End.Row;
  3738. //获取worksheet的列数
  3739. int cols = worksheet.Dimension.End.Column;
  3740. DataTable dt = new DataTable(worksheet.Name);
  3741. DataRow dr = null;
  3742. for (int i = 1; i <= rows; i++)
  3743. {
  3744. if (i > 1)
  3745. dr = dt.Rows.Add();
  3746. for (int j = 1; j <= cols; j++)
  3747. {
  3748. //默认将第一行设置为datatable的标题
  3749. if (i == 1)
  3750. dt.Columns.Add(GetString(worksheet.Cells[i, j].Value));
  3751. //剩下的写入datatable
  3752. else
  3753. dr[j - 1] = GetString(worksheet.Cells[i, j].Value);
  3754. }
  3755. }
  3756. return dt;
  3757. }
  3758. private string GetString(object obj)
  3759. {
  3760. if (obj == null)
  3761. return "";
  3762. return obj.ToString();
  3763. }
  3764. private DataTable ExcelFileToDataTable(IFormFile file)
  3765. {
  3766. DataTable dtTest = null;
  3767. using (var stream = new MemoryStream())
  3768. {
  3769. file.CopyTo(stream);
  3770. using (var package = new ExcelPackage(stream))
  3771. {
  3772. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  3773. ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
  3774. dtTest = WorksheetToTable(worksheet);
  3775. }
  3776. }
  3777. return dtTest;
  3778. }
  3779. /// <summary>
  3780. /// 信用卡对账
  3781. /// </summary>
  3782. /// <param name="file"></param>
  3783. /// <param name="cardType"></param>
  3784. /// <param name="beginDt"></param>
  3785. /// <param name="endDt"></param>
  3786. /// <returns></returns>
  3787. [HttpPost]
  3788. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3789. public async Task<IActionResult> PostCreditCardBill(IFormFile file, int cardType, string beginDt, string endDt)
  3790. {
  3791. if (file == null || file.Length < 1)
  3792. {
  3793. return Ok(JsonView(false, "请上传文件!"));
  3794. }
  3795. string fileName = file.FileName;
  3796. if (!fileName.EndsWith(".xlsx") && !fileName.EndsWith(".xls"))
  3797. {
  3798. return Ok(JsonView(false, "请上传Excel文件!"));
  3799. }
  3800. if (cardType < 1) return Ok(JsonView(false, "请传入有效的卡类型!"));
  3801. if (string.IsNullOrEmpty(beginDt) || string.IsNullOrEmpty(endDt)) return Ok(JsonView(false, "请输入开始/结束日期!"));
  3802. var beginValid = DateTime.TryParse(beginDt, out _);
  3803. var endValid = DateTime.TryParse(endDt, out _);
  3804. if (!beginValid || !endValid) return Ok(JsonView(false, "请输入正确的日期格式"));
  3805. //读取ExcelFile
  3806. DataTable dt = ExcelFileToDataTable(file);
  3807. dt.TableName = "TB";
  3808. if (dt == null)
  3809. {
  3810. return Ok(JsonView(false, $"您上传的Excel工作表没有内容,请检查!!!"));
  3811. }
  3812. //信用卡信息
  3813. string sql = string.Format($"Select * From Grp_CreditCardPayment Where Isdel = 0 And CTDId = {cardType} And ConsumptionDate between '{beginDt}' and '{endDt}' ");
  3814. var List_ccp = await _sqlSugar.SqlQueryable<Grp_CreditCardPayment>(sql).ToListAsync();
  3815. if (List_ccp.Count < 1)
  3816. {
  3817. return Ok(JsonView(false, $"未查询到 {beginDt} 至 {endDt} 信用卡账单信息!!!!"));
  3818. }
  3819. //资源信息
  3820. var delegationInfos = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).ToList();
  3821. var users = _sqlSugar.Queryable<Sys_Users>().Where(it => it.IsDel == 0).ToList();
  3822. string url = string.Empty;
  3823. try
  3824. {
  3825. /*
  3826. * 卡类型
  3827. * 74 美元卡 1
  3828. * 75 欧元卡 1
  3829. * 86 招行卡 1
  3830. * 346 中信卡 1
  3831. * 363 交行卡 1
  3832. *
  3833. */
  3834. var ids = new List<int>();
  3835. if (cardType == 74) //美元卡
  3836. {
  3837. var AirGroupReuslt = List_ccp.Where(x => x.CTable == 85).GroupBy(x => x.DIId).ToList();
  3838. if (AirGroupReuslt != null && AirGroupReuslt.Count > 0)
  3839. {
  3840. foreach (var item in AirGroupReuslt)
  3841. {
  3842. if (item.Count() > 1)
  3843. {
  3844. var obj = item.FirstOrDefault();
  3845. obj.RMBPrice = item.Sum(x => x.PayMoney);//合计币种金额
  3846. obj.Remark = "团组机票总价(虚拟)";
  3847. List_ccp.Add(obj);
  3848. }
  3849. }
  3850. }
  3851. //dt.AcceptChanges(); //提交
  3852. //修改table列名
  3853. dt.Columns[0].ColumnName = "accountType"; // 账户类型
  3854. dt.Columns[1].ColumnName = "tradeDate"; //交易日期
  3855. dt.Columns[2].ColumnName = "BillingDate"; // 记账日期
  3856. dt.Columns[3].ColumnName = "CardNo"; // 卡号
  3857. dt.Columns[4].ColumnName = "deposit"; // 存入金额
  3858. dt.Columns[5].ColumnName = "SpendingAmount"; // 支出金额
  3859. dt.Columns[6].ColumnName = "TransactionDescription"; // 交易描述
  3860. dt.Columns[7].ColumnName = "TeamRemark"; // 团组备注描述
  3861. dt.Columns[8].ColumnName = "Handlers"; // 经手人
  3862. dt.Columns[9].ColumnName = "State"; // 状态
  3863. //删除第一行数据
  3864. if (dt.Rows.Count > 0)
  3865. {
  3866. string accountType = dt.Rows[0]["accountType"].ToString();
  3867. if (dt.Rows[0]["accountType"].ToString().Equals("账户类型"))
  3868. {
  3869. dt.Rows[0].Delete();
  3870. dt.AcceptChanges(); //提交
  3871. }
  3872. }
  3873. foreach (DataRow item in dt.Rows)
  3874. {
  3875. #region 匹配的金额
  3876. decimal ExcelAmount = 0.00M;
  3877. decimal deposit = 0.00M;
  3878. if (!string.IsNullOrEmpty(item["SpendingAmount"].ToString()))
  3879. {
  3880. var isParase = decimal.TryParse(item["SpendingAmount"].ToString(), out ExcelAmount);
  3881. if (isParase)
  3882. {
  3883. var CList = List_ccp.FindAll(x => x.PayMoney == ExcelAmount);
  3884. if (CList != null && CList.Count > 0)
  3885. {
  3886. item["TeamRemark"] = delegationInfos.Find(it => it.Id == CList.First().DIId)?.TeamName;
  3887. item["Handlers"] = users.Find(it => it.Id == CList.First().CreateUserId)?.CnName;
  3888. item["State"] = 1;
  3889. }
  3890. }
  3891. }
  3892. if (!string.IsNullOrEmpty(item["deposit"].ToString()))
  3893. {
  3894. var isParse = decimal.TryParse(item["deposit"].ToString(), out deposit);
  3895. if (isParse)
  3896. {
  3897. var CList = List_ccp.FindAll(x => x.PayMoney == deposit);
  3898. if (CList != null && CList.Count > 0)
  3899. {
  3900. item["TeamRemark"] = delegationInfos.Find(it => it.Id == CList.First().DIId)?.TeamName;
  3901. item["Handlers"] = users.Find(it => it.Id == CList.First().CreateUserId)?.CnName;
  3902. item["State"] = 1;
  3903. }
  3904. }
  3905. }
  3906. #endregion
  3907. //交易描述
  3908. if (!string.IsNullOrEmpty(item["TransactionDescription"].ToString()))
  3909. {
  3910. string TransactionDescription = item["TransactionDescription"].ToString();
  3911. var startIndex = TransactionDescription.LastIndexOf("[");
  3912. var endIndex = TransactionDescription.LastIndexOf("]");
  3913. if (startIndex != -1 && endIndex != -1)
  3914. {
  3915. var moenyList = TransactionDescription.Substring(startIndex + 1, endIndex - startIndex - 1).Split(' ').
  3916. Where(x => !string.IsNullOrEmpty(x)).ToList();
  3917. decimal money = 0.00M;
  3918. foreach (var itemMoeny in moenyList)
  3919. {
  3920. if (itemMoeny.Contains('.'))
  3921. {
  3922. string itemMoenyStr = itemMoeny.Replace(",", string.Empty);
  3923. bool istrue = decimal.TryParse(itemMoenyStr, out money);
  3924. if (istrue)
  3925. {
  3926. var CList = List_ccp.FindAll(x => x.PayMoney == money);
  3927. if (CList != null && CList.Count > 0)
  3928. {
  3929. item["TeamRemark"] = delegationInfos.Find(it => it.Id == CList.First().DIId)?.TeamName;
  3930. item["Handlers"] = users.Find(it => it.Id == CList.First().CreateUserId)?.CnName;
  3931. item["State"] = 1;
  3932. }
  3933. }
  3934. }
  3935. }
  3936. }
  3937. }
  3938. }
  3939. string fileName1 = $"信用卡账单(美元卡){DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  3940. Dictionary<string, object> pairs = new Dictionary<string, object>();
  3941. List<DataTable> datas = new List<DataTable>();
  3942. datas.Add(dt);
  3943. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-美元卡.xls", $"CreditCardBill", fileName1, pairs, datas);
  3944. }
  3945. else if (cardType == 75) //欧元卡
  3946. {
  3947. if (dt.Rows.Count > 0)
  3948. {
  3949. string accountType = dt.Rows[0][0].ToString();
  3950. if (accountType.Equals("账户类型"))
  3951. {
  3952. dt.Rows[0].Delete();
  3953. dt.AcceptChanges(); //提交
  3954. }
  3955. }
  3956. //dt.Columns[0].ColumnName = "All";
  3957. DataTable dt1 = new DataTable();
  3958. dt1.TableName = "TB";
  3959. dt1.Columns.Add("TradingDate", Type.GetType("System.String"));//交易日期
  3960. dt1.Columns.Add("TallyDate", Type.GetType("System.String")); //记账日期
  3961. dt1.Columns.Add("TradindDesc", Type.GetType("System.String"));//交易描述
  3962. dt1.Columns.Add("TradindMoney", Type.GetType("System.String"));//交易币种/金额
  3963. dt1.Columns.Add("ClearindMoney", Type.GetType("System.String"));// 清算币种/金额
  3964. dt1.Columns.Add("TeamRemark", Type.GetType("System.String")); //团组备注描述
  3965. dt1.Columns.Add("Handlers", Type.GetType("System.String")); //经手人
  3966. dt1.Columns.Add("State", Type.GetType("System.String")); //状态
  3967. for (int i = 0; i < dt.Rows.Count; i++)
  3968. {
  3969. string[] str = dt.Rows[i]["All"].ToString().Split(' ');
  3970. //string[] str = dt.Rows[i];
  3971. DataRow dr = dt1.NewRow();
  3972. dr["TradingDate"] = str[0].ToString();
  3973. dr["TallyDate"] = str[1].ToString();
  3974. dr["TradindDesc"] = str[2].ToString() + " " + str[3].ToString();
  3975. dr["TradindMoney"] = str[4].ToString() + " " + str[5].ToString();
  3976. dr["ClearindMoney"] = str[6].ToString() + " " + str[7].ToString();
  3977. dt1.Rows.Add(dr);
  3978. }
  3979. foreach (DataRow item in dt1.Rows)
  3980. {
  3981. for (int i = 0; i < List_ccp.Count; i++)
  3982. {
  3983. DateTime dtTime1 = Convert.ToDateTime(item["TradingDate"].ToString() == "" ? DateTime.Now.ToString("MM/dd") : item["TradingDate"].ToString()); //交易日期
  3984. string USDPrice = item["TradindMoney"].ToString(); //支出金额
  3985. USDPrice = USDPrice.Split(' ')[1].Trim(); //替换掉非数字
  3986. //USDPrice = USDPrice.Split('/')[1];
  3987. // 经手人 and excel行状态
  3988. if (!string.IsNullOrEmpty(List_ccp[i].ConsumptionDate) && !string.IsNullOrEmpty(USDPrice))
  3989. {
  3990. DateTime dtTime2 = Convert.ToDateTime(List_ccp[i].ConsumptionDate.ToString() == "" ? DateTime.Now.ToString("MM/dd") : List_ccp[i].ConsumptionDate.ToString());
  3991. float price1 = float.Parse(USDPrice);
  3992. float price2 = float.Parse(List_ccp[i].PayMoney.ToString("F2"));
  3993. if (dtTime1 == dtTime2 && price1 == price2)
  3994. {
  3995. item["TeamRemark"] = delegationInfos.Find(it => it.Id == List_ccp[i].DIId)?.TeamName;
  3996. item["Handlers"] = users.Find(it => it.Id == List_ccp[i].CreateUserId)?.CnName;
  3997. item["State"] = "1";
  3998. i = List_ccp.Count - 1;
  3999. }
  4000. else item["State"] = "0";
  4001. }
  4002. else item["State"] = "0";
  4003. }
  4004. if (item["TradindDesc"].ToString().Contains("财付通"))
  4005. item["State"] = "2";
  4006. else if (item["TradindDesc"].ToString().Contains("京东"))
  4007. item["State"] = "2";
  4008. else if (item["TradindDesc"].ToString().Contains("微信支付"))
  4009. item["State"] = "2";
  4010. else if (item["TradindDesc"].ToString().Contains("淘宝"))
  4011. item["State"] = "2";
  4012. }
  4013. string fileName1 = $"信用卡账单(欧元卡){DateTime.Now.ToString("yyyy.MM.dd")}.xls";
  4014. Dictionary<string, object> pairs = new Dictionary<string, object>();
  4015. List<DataTable> datas = new List<DataTable>();
  4016. datas.Add(dt);
  4017. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-欧元卡.xls", "TB", fileName1, pairs, datas);
  4018. }
  4019. else if (cardType == 86) //招行卡
  4020. {
  4021. var AirGroupReuslt1 = List_ccp.Where(x => x.CTable == 85).GroupBy(x => x.DIId).ToList();
  4022. if (AirGroupReuslt1 != null && AirGroupReuslt1.Count > 0)
  4023. {
  4024. foreach (var item in AirGroupReuslt1)
  4025. {
  4026. if (item.Count() > 1)
  4027. {
  4028. var di = delegationInfos.Find(it => it.Id == item.Key);
  4029. var obj = item.FirstOrDefault();
  4030. obj.Remark = "团组机票总价";
  4031. if (di != null)
  4032. {
  4033. obj.Remark = "团组机票总价(" + di.TeamName + ")";
  4034. }
  4035. obj.RMBPrice = item.Sum(x => x.RMBPrice);//合计人民币
  4036. List_ccp.Add(obj);
  4037. }
  4038. }
  4039. }
  4040. //查询所有刷卡的团组
  4041. //将刷卡团组内刷卡金额的金额存入ccp_list
  4042. //将excel作比较
  4043. //机票刷卡记录
  4044. var AirListAndPayID = List_ccp.Where(x => x.CTable == 85 && x.PayDId == 72).Select(x => x.DIId).Distinct().ToList();
  4045. var AirData = _sqlSugar.Queryable<Grp_AirTicketReservations>().Where(it => AirListAndPayID.Contains(it.DIId) && it.PrePrice != it.Price).ToList();
  4046. foreach (var item in AirData)
  4047. {
  4048. var DBwhere = List_ccp.Find(x => x.PayMoney == item.PrePrice);
  4049. if (DBwhere == null)
  4050. {
  4051. List_ccp.Add(new Grp_CreditCardPayment
  4052. {
  4053. PayMoney = item.PrePrice,
  4054. DIId = item.DIId,
  4055. CreateUserId = item.CreateUserId,
  4056. Remark = "(机票单价价格)",
  4057. });
  4058. }
  4059. }
  4060. var HotelGroupReuslt = List_ccp.Where(x => x.CTable == 76).GroupBy(x => x.DIId).ToList();
  4061. if (HotelGroupReuslt != null && HotelGroupReuslt.Count > 0)
  4062. {
  4063. foreach (var item in HotelGroupReuslt)
  4064. {
  4065. if (item.Count() > 1)
  4066. {
  4067. var di = delegationInfos.Find(it => it.Id == item.Key);
  4068. var obj = item.FirstOrDefault();
  4069. obj.Remark = "团组酒店总价";
  4070. if (di != null)
  4071. {
  4072. obj.Remark = "团组酒店总价(" + di.TeamName + ")";
  4073. }
  4074. obj.RMBPrice = item.Sum(x => x.RMBPrice);//合计人民币
  4075. List_ccp.Add(obj);
  4076. }
  4077. }
  4078. }
  4079. #region
  4080. dt.Rows[0].Delete();//删除列名行
  4081. dt.AcceptChanges();
  4082. DataTable dt1 = new DataTable();
  4083. dt1.TableName = "TB";
  4084. dt1.Columns.Add("TradingDay", Type.GetType("System.String")); // 交易日
  4085. dt1.Columns.Add("TallyDay", Type.GetType("System.String")); // 记账日
  4086. dt1.Columns.Add("TransactionDesc", Type.GetType("System.String")); // 交易描述
  4087. dt1.Columns.Add("RMBMoney", Type.GetType("System.String")); // 人名币金额
  4088. dt1.Columns.Add("CardNo", Type.GetType("System.String")); // 卡号
  4089. dt1.Columns.Add("TradingMoney", Type.GetType("System.String")); // 交易地金额
  4090. dt1.Columns.Add("Currency", Type.GetType("System.String")); // 币种
  4091. dt1.Columns.Add("TeamRemark", Type.GetType("System.String")); //团组备注描述
  4092. dt1.Columns.Add("Handlers", Type.GetType("System.String")); //经手人
  4093. dt1.Columns.Add("State", Type.GetType("System.String")); //状态
  4094. for (int j = 0; j < dt.Rows.Count; j++)//遍历行
  4095. {
  4096. DataRow dr = dt1.NewRow(); //获取每一行的数据
  4097. dr["TradingDay"] = dt.Rows[j][0].ToString();
  4098. dr["TallyDay"] = dt.Rows[j][1].ToString();
  4099. dr["TransactionDesc"] = dt.Rows[j][2].ToString();
  4100. dr["RMBMoney"] = dt.Rows[j][3].ToString();
  4101. dr["CardNo"] = dt.Rows[j][4].ToString();
  4102. string currency = "CN";
  4103. string money = dt.Rows[j][5].ToString();
  4104. if (money.Contains('('))
  4105. {
  4106. string[] strs = money.Split('(');
  4107. money = strs[0];
  4108. currency = strs[1].Replace(")", "");
  4109. }
  4110. dr["TradingMoney"] = money;
  4111. dr["Currency"] = currency;
  4112. if (string.IsNullOrEmpty(money))
  4113. {
  4114. continue;
  4115. }
  4116. dt1.Rows.Add(dr);
  4117. }
  4118. //datatable 排序
  4119. dt1.DefaultView.Sort = "TradingDay asc";
  4120. dt1 = dt1.DefaultView.ToTable();
  4121. foreach (DataRow item in dt1.Rows)
  4122. {
  4123. if (item["TradingDay"] == "" && item["RMBMoney"] == "")
  4124. {
  4125. continue;
  4126. }
  4127. //excel获取交易日期
  4128. string ExcelDt = string.Empty;
  4129. //C表交易日期
  4130. string DBDt = string.Empty;
  4131. //excel交易的金额
  4132. decimal TradingMoney = decimal.Parse(item["TradingMoney"].ToString());
  4133. if (item["TradingDay"] != null)
  4134. {
  4135. ExcelDt = DateTime.Parse(item["TradingDay"].ToString()).ToString("MMdd");
  4136. }
  4137. //加一获取金额区间
  4138. decimal MaxTradingMoney = TradingMoney + 1;
  4139. decimal MinTradingMoney = TradingMoney - 1;
  4140. //匹配C表金额相等的值
  4141. var CList = List_ccp.FindAll(x => x.PayMoney < MaxTradingMoney && x.PayMoney > MinTradingMoney);
  4142. if (CList != null && CList.Count > 0)
  4143. {
  4144. #region 日期匹配
  4145. foreach (var Citem in CList)
  4146. {
  4147. if (!string.IsNullOrWhiteSpace(Citem.ConsumptionDate))
  4148. {
  4149. DBDt = DateTime.Parse(Citem.ConsumptionDate).ToString("MMdd");
  4150. if (DBDt == ExcelDt)
  4151. {
  4152. item["TeamRemark"] = delegationInfos.Find(it => it.Id == Citem.DIId)?.TeamName;
  4153. item["Handlers"] = users.Find(it => it.Id == Citem.CreateUserId)?.CnName;
  4154. ids.Add(Citem.Id);
  4155. }
  4156. }
  4157. }
  4158. #endregion
  4159. }
  4160. if (item["TransactionDesc"].ToString().Contains("财付通"))
  4161. item["State"] = "2";
  4162. else if (item["TransactionDesc"].ToString().Contains("京东支付"))
  4163. item["State"] = "2";
  4164. else if (item["TransactionDesc"].ToString().Contains("微信支付"))
  4165. item["State"] = "2";
  4166. else if (item["TransactionDesc"].ToString().Contains("淘宝"))
  4167. item["State"] = "2";
  4168. else if (item["TransactionDesc"].ToString().Contains("支付宝"))
  4169. item["State"] = "2";
  4170. else if (item["TransactionDesc"].ToString().Contains("拼多多"))
  4171. item["State"] = "2";
  4172. else
  4173. item["State"] = "0";
  4174. if (!string.IsNullOrEmpty(item["TeamRemark"].ToString()) && !string.IsNullOrEmpty(item["Handlers"].ToString()))
  4175. item["State"] = "1";
  4176. }
  4177. //更改匹配项状态
  4178. if (ids.Count > 0)
  4179. {
  4180. var _CreditCardPayments = new List<Grp_CreditCardPayment>();
  4181. foreach (var item in ids)
  4182. {
  4183. _CreditCardPayments.Add(new Grp_CreditCardPayment() { Id = item, IsMatchCreditCard = 1.00M });
  4184. }
  4185. var updateStatus = _sqlSugar.Updateable<Grp_CreditCardPayment>(_CreditCardPayments)
  4186. .UpdateColumns(it => new { it.IsMatchCreditCard })
  4187. .Where(it => ids.Contains(it.Id))
  4188. .ExecuteCommand();
  4189. }
  4190. string fileName1 = $"信用卡账单(招行卡){DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  4191. Dictionary<string, object> pairs = new Dictionary<string, object>();
  4192. List<DataTable> datas = new List<DataTable>();
  4193. datas.Add(dt1);
  4194. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-招行卡.xls", "CreditCardBill", fileName1, pairs, datas);
  4195. #endregion
  4196. }
  4197. else if (cardType == 346) //中信卡
  4198. {
  4199. dt.Columns.Add("TeamRemark", Type.GetType("System.String")); //团组备注描述
  4200. dt.Columns.Add("Handlers", Type.GetType("System.String")); //经手人
  4201. dt.Columns.Add("State", Type.GetType("System.String")); //状态
  4202. //修改table列名
  4203. dt.Columns[0].ColumnName = "TransactionDesc"; // 交易描述
  4204. dt.Columns[1].ColumnName = "TradingCurrencyAndMoney"; // 交易币种和金额
  4205. dt.Columns[2].ColumnName = "TransactionDate"; // 交易日期
  4206. dt.Columns[3].ColumnName = "SettlementCurrencyAndMoney";// 结算币种和金额
  4207. dt.Columns[4].ColumnName = "BookedDate"; // 入账日期
  4208. foreach (DataRow item in dt.Rows)
  4209. {
  4210. for (int i = 0; i < List_ccp.Count; i++)
  4211. {
  4212. if (string.IsNullOrEmpty(item["TransactionDate"].ToString()))
  4213. break;
  4214. DateTime dtTime1 = Convert.ToDateTime(item["TransactionDate"].ToString()); //交易日期
  4215. string USDPrice = item["TradingCurrencyAndMoney"].ToString(); //支出金额
  4216. USDPrice = USDPrice.Split('/')[1];
  4217. //string USDPrice1 = USDPrice.ToString("0.00");
  4218. // 经手人 and excel行状态
  4219. if (!string.IsNullOrEmpty(List_ccp[i].ConsumptionDate) && !string.IsNullOrEmpty(USDPrice))
  4220. {
  4221. DateTime dtTime2 = Convert.ToDateTime(List_ccp[i].ConsumptionDate);
  4222. float price1 = float.Parse(USDPrice);
  4223. float price2 = float.Parse(List_ccp[i].PayMoney.ToString("F2"));
  4224. if (dtTime1 == dtTime2 && price1 == price2)
  4225. {
  4226. item["TeamRemark"] = delegationInfos.Find(it => it.Id == List_ccp[i].DIId)?.TeamName;
  4227. item["Handlers"] = users.Find(it => it.Id == List_ccp[i].CreateUserId)?.CnName;
  4228. item["State"] = "1";
  4229. i = List_ccp.Count - 1;
  4230. }
  4231. else
  4232. item["State"] = "0";
  4233. }
  4234. else
  4235. item["State"] = "0";
  4236. }
  4237. //判断是否是数字
  4238. //if (IsNumber(item["TradingCurrencyAndMoney"].ToString().Split('/')[1]) == false)
  4239. // item["State"] = "0";
  4240. if (item["TransactionDesc"].ToString().Contains("财付通"))
  4241. item["State"] = "2";
  4242. else if (item["TransactionDesc"].ToString().Contains("京东"))
  4243. item["State"] = "2";
  4244. else if (item["TransactionDesc"].ToString().Contains("微信支付"))
  4245. item["State"] = "2";
  4246. else if (item["TransactionDesc"].ToString().Contains("淘宝"))
  4247. item["State"] = "2";
  4248. }
  4249. #region DownExcel
  4250. string fileName1 = $"信用卡账单(中信卡){DateTime.Now.ToString("yyyy.MM.dd")}.xls";
  4251. Dictionary<string, object> pairs = new Dictionary<string, object>();
  4252. List<DataTable> datas = new List<DataTable>();
  4253. datas.Add(dt);
  4254. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-中信卡.xls", "TB", fileName1, pairs, datas);
  4255. #endregion
  4256. }
  4257. else if (cardType == 363) //交行卡
  4258. {
  4259. dt.Columns[0].ColumnName = "All";
  4260. DataTable dt1 = new DataTable();
  4261. dt1.Columns.Add("TradingDate", Type.GetType("System.String"));//交易日期
  4262. dt1.Columns.Add("TallyDate", Type.GetType("System.String")); //记账日期
  4263. dt1.Columns.Add("TradindDesc", Type.GetType("System.String"));//交易描述
  4264. dt1.Columns.Add("TradindMoney", Type.GetType("System.String"));//交易币种/金额
  4265. dt1.Columns.Add("ClearindMoney", Type.GetType("System.String"));// 清算币种/金额
  4266. dt1.Columns.Add("TeamRemark", Type.GetType("System.String")); //团组备注描述
  4267. dt1.Columns.Add("Handlers", Type.GetType("System.String")); //经手人
  4268. dt1.Columns.Add("State", Type.GetType("System.String")); //状态
  4269. for (int i = 0; i < dt.Rows.Count; i++)
  4270. {
  4271. string[] str = dt.Rows[i]["All"].ToString().Split(' ');
  4272. DataRow dr = dt1.NewRow();
  4273. dr["TradingDate"] = str[0].ToString();
  4274. dr["TallyDate"] = str[1].ToString();
  4275. dr["TradindDesc"] = str[2].ToString() + " " + str[3].ToString();
  4276. dr["TradindMoney"] = str[4].ToString() + " " + str[5].ToString();
  4277. dr["ClearindMoney"] = str[6].ToString() + " " + str[7].ToString();
  4278. dt1.Rows.Add(dr);
  4279. }
  4280. foreach (DataRow item in dt1.Rows)
  4281. {
  4282. for (int i = 0; i < List_ccp.Count; i++)
  4283. {
  4284. DateTime dtTime1 = Convert.ToDateTime(item["TradingDate"].ToString() == "" ? DateTime.Now.ToString("MM/dd") : item["TradingDate"].ToString()); //交易日期
  4285. string USDPrice = item["TradindMoney"].ToString(); //支出金额
  4286. USDPrice = USDPrice.Split(' ')[1].Trim(); //替换掉非数字
  4287. //USDPrice = USDPrice.Split('/')[1];
  4288. // 经手人 and excel行状态
  4289. if (!string.IsNullOrEmpty(List_ccp[i].ConsumptionDate) && !string.IsNullOrEmpty(USDPrice))
  4290. {
  4291. DateTime dtTime2 = Convert.ToDateTime(List_ccp[i].ConsumptionDate.ToString() == "" ? DateTime.Now.ToString("MM/dd") : List_ccp[i].ConsumptionDate.ToString());
  4292. float price1 = float.Parse(USDPrice);
  4293. float price2 = float.Parse(List_ccp[i].PayMoney.ToString("F2"));
  4294. if (dtTime1 == dtTime2 && price1 == price2)
  4295. {
  4296. item["TeamRemark"] = delegationInfos.Find(it => it.Id == List_ccp[i].DIId)?.TeamName;
  4297. item["Handlers"] = users.Find(it => it.Id == List_ccp[i].CreateUserId)?.CnName;
  4298. item["State"] = "1";
  4299. i = List_ccp.Count - 1;
  4300. }
  4301. else
  4302. item["State"] = "0";
  4303. }
  4304. else
  4305. item["State"] = "0";
  4306. }
  4307. if (item["TradindDesc"].ToString().Contains("财付通"))
  4308. item["State"] = "2";
  4309. else if (item["TradindDesc"].ToString().Contains("京东"))
  4310. item["State"] = "2";
  4311. else if (item["TradindDesc"].ToString().Contains("微信支付"))
  4312. item["State"] = "2";
  4313. else if (item["TradindDesc"].ToString().Contains("淘宝"))
  4314. item["State"] = "2";
  4315. }
  4316. string fileName1 = $"信用卡账单(交行卡){DateTime.Now.ToString("yyyy.MM.dd")}.xls";
  4317. Dictionary<string, object> pairs = new Dictionary<string, object>();
  4318. List<DataTable> datas = new List<DataTable>();
  4319. datas.Add(dt);
  4320. url = AsposeHelper.ExpertExcelToModel("信用卡对账模板-交行卡.xls", "TB", fileName1, pairs, datas);
  4321. }
  4322. }
  4323. catch (Exception ex)
  4324. {
  4325. return Ok(JsonView(false, $"匹配失败,{ex.Message}!"));
  4326. }
  4327. return Ok(JsonView(true, "操作成功", new { url = url }));
  4328. }
  4329. /// <summary>
  4330. /// 把数据从Excel装载到DataTable
  4331. /// </summary>
  4332. /// <param name="pathName">带路径的Excel文件名</param>
  4333. /// <param name="sheetName">工作表名</param>
  4334. /// <param name="tbContainer">将数据存入的DataTable</param>
  4335. /// <returns></returns>
  4336. public static DataTable ExcelToDataTable(string pathName, string sheetName)
  4337. {
  4338. DataTable tbContainer = new DataTable();
  4339. string strConn = string.Empty;
  4340. if (string.IsNullOrEmpty(sheetName)) { sheetName = "Sheet1"; }
  4341. FileInfo file = new FileInfo(pathName);
  4342. if (!file.Exists) { throw new Exception("文件不存在"); }
  4343. string extension = file.Extension;
  4344. switch (extension)
  4345. {
  4346. case ".xls":
  4347. strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
  4348. break;
  4349. case ".xlsx":
  4350. strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
  4351. break;
  4352. default:
  4353. strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
  4354. break;
  4355. }
  4356. //链接Excel
  4357. OleDbConnection cnnxls = new OleDbConnection(strConn);
  4358. //读取Excel里面有 表Sheet1
  4359. System.Data.OleDb.OleDbDataAdapter oda = new System.Data.OleDb.OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
  4360. DataSet ds = new DataSet();
  4361. //将Excel里面有表内容装载到内存表中!
  4362. oda.Fill(tbContainer);
  4363. return tbContainer;
  4364. }
  4365. #endregion
  4366. #region 提成计算
  4367. /// <summary>
  4368. /// 提成计算
  4369. /// </summary>
  4370. /// <param name="dto"></param>
  4371. /// <returns></returns>
  4372. [HttpPost]
  4373. public IActionResult ComputeRoyalties(ComputeRoyaltiesDto dto)
  4374. {
  4375. var jw = JsonView(false);
  4376. var userId = dto.UserId;
  4377. var user = _sqlSugar.Queryable<Sys_Users>().First(x=>x.Id == userId);
  4378. //jw.Data = System.Array.Empty<string>();
  4379. if (user == null)
  4380. {
  4381. jw.Msg = "暂无该用户!";
  4382. return Ok(jw);
  4383. }
  4384. if (!DateTime.TryParse(dto.StartDate,out DateTime StartDateTime))
  4385. {
  4386. jw.Msg = "开始时间格式有误!";
  4387. return Ok(jw);
  4388. }
  4389. if (!DateTime.TryParse(dto.EndDate, out DateTime EndDateTime))
  4390. {
  4391. jw.Msg = "结束时间格式有误!";
  4392. return Ok(jw);
  4393. }
  4394. if (DateTime.Compare(StartDateTime,EndDateTime) > 0)
  4395. {
  4396. jw.Msg = "开始时间大于结束时间!";
  4397. return Ok(jw);
  4398. }
  4399. //机票 职位表id 24
  4400. int[] AirTicket = _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.JobPostId == 24).Select(x => x.Id).ToArray();
  4401. //酒店 职位表id 25
  4402. int[] Hotel = _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.JobPostId == 25).Select(x => x.Id).ToArray();
  4403. //OP 职位表id 28
  4404. int [] OP = _sqlSugar.Queryable<Sys_Users>().Where(x=>x.IsDel == 0 && x.JobPostId == 28).Select(x=>x.Id).ToArray();
  4405. //商邀 职位表id 27
  4406. int [] Invitation = _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.JobPostId == 27).Select(x => x.Id).ToArray();
  4407. //签证 职位表id 26
  4408. int[] Visa = _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.JobPostId == 26 ).Select(x => x.Id).ToArray();
  4409. //主管职位
  4410. //string[] Manager = { "149", "283" };
  4411. List<ComputeRoyaltiesView> resultArr = new List<ComputeRoyaltiesView>();
  4412. var teamLv = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.STid == 56 && x.IsDel == 0).ToList();
  4413. var auditState = new int[] { 1 , 3 };
  4414. if (AirTicket.Contains(userId))
  4415. {
  4416. //提成方式:¥10/人×人数×段数(每个组团涉及的换机次数)
  4417. var listAir = _sqlSugar.Queryable<Grp_AirTicketReservations, Grp_DelegationInfo, Grp_CreditCardPayment>((x, a, b) => new
  4418. JoinQueryInfos(
  4419. JoinType.Left, a.Id == x.DIId ,
  4420. JoinType.Left, b.CTable == 85 && b.CId == x.Id )
  4421. ).Where((x, a, b) => x.IsDel == 0 && x.CreateUserId == userId && (b.IsAuditGM == 1 || b.IsAuditGM == 3)
  4422. && a.IsDel == 0 && a.VisitDate >= StartDateTime && a.VisitDate <= EndDateTime && b.IsDel == 0 && a.IsSure == 1 && auditState.Contains(b.IsAuditGM) )
  4423. .Select((x, a, b) => new
  4424. {
  4425. x.FlightsDescription,
  4426. a.Id,
  4427. a.TeamName,
  4428. a.VisitDate,
  4429. a.TeamLevSId,
  4430. a.VisitPNumber,
  4431. x.Price,
  4432. x.ClientName,
  4433. x.ClientNum,
  4434. x.FlightsCode,
  4435. }).ToList();
  4436. var groupByid = listAir.GroupBy(x => x.Id);
  4437. foreach (var airArr in groupByid)
  4438. {
  4439. var groupAirCount = 0; //团组航段数量
  4440. var infos = new List<string>();
  4441. foreach (var air in airArr)
  4442. {
  4443. var airCount = 0; // 单条航段数量
  4444. if (air.FlightsDescription.IsNullOrWhiteSpace())
  4445. {
  4446. continue;
  4447. }
  4448. if (air.ClientName.Contains("-1") || air.ClientName.Contains("行程单") || air.FlightsCode.Contains("行程单"))
  4449. {
  4450. continue;
  4451. }
  4452. string errMsg = string.Empty;
  4453. if (air.FlightsDescription.Contains("\r\n"))
  4454. {
  4455. var rowCode = Regex.Split(air.FlightsDescription, "\\d+\\.", RegexOptions.IgnoreCase).Where(x=>!string.IsNullOrWhiteSpace(x)).ToArray();
  4456. for (int i = 0; i < rowCode.Length; i++)
  4457. {
  4458. if (i != 0)
  4459. {
  4460. try
  4461. {
  4462. var columnValue = rowCode[i].Split(' ').Where(x => !string.IsNullOrEmpty(x)).ToList();
  4463. string day = columnValue[2].Substring(2, 2);//日
  4464. string monthAbbreviations = columnValue[2].Substring(4, 3).ToUpper();//月份
  4465. monthAbbreviations = GeneralMethod.GetLonger(monthAbbreviations);
  4466. string EndHHmm = columnValue[5].Substring(0, 2) + ":" + columnValue[5].Substring(2, 2);
  4467. DateTime EndData = DateTime.Parse($"{DateTime.Now.Year}-{monthAbbreviations}-{day} {EndHHmm}");//当前班次
  4468. var spDotandEmpty1 = rowCode[i - 1].Split(' ').Where(x => !string.IsNullOrEmpty(x)).ToList();
  4469. string day1 = spDotandEmpty1[2].Substring(2, 2);//日
  4470. string monthAbbreviations1 = spDotandEmpty1[2].Substring(4, 3).ToUpper();//月份
  4471. monthAbbreviations1 = GeneralMethod.GetLonger(monthAbbreviations1);
  4472. string HHmm = spDotandEmpty1[6].Substring(0, 2) + ":" + spDotandEmpty1[6].Substring(2, 2);
  4473. DateTime data = DateTime.Parse($"{DateTime.Now.Year}-{monthAbbreviations1}-{day1} {HHmm}");//上个班次
  4474. TimeSpan t3 = EndData - data; //两个时间相减 。默认得到的是 两个时间之间的天数 得到:365.00:00:00
  4475. double getHour = t3.TotalHours;
  4476. if (getHour >= 6)
  4477. {
  4478. if (air.Price > 0)
  4479. {
  4480. airCount += 1;
  4481. }
  4482. else
  4483. {
  4484. airCount -= 1;
  4485. }
  4486. }
  4487. }
  4488. catch (Exception ex)
  4489. {
  4490. errMsg = "机票行程代码格式有误!解析失败!" + $"({ex.Message})";
  4491. break;
  4492. }
  4493. }
  4494. else
  4495. {
  4496. if (air.Price > 0)
  4497. {
  4498. airCount += 1;
  4499. }
  4500. else
  4501. {
  4502. airCount -= 1;
  4503. }
  4504. }
  4505. }
  4506. }
  4507. else
  4508. {
  4509. if (air.Price > 0)
  4510. {
  4511. airCount++;
  4512. }
  4513. else
  4514. {
  4515. airCount--;
  4516. }
  4517. }
  4518. string info = $"航班{air.FlightsCode} {(air.Price > 0 ? "" : "此笔为退费!")} 人数为{air.ClientNum} 有效段数为{airCount} 总段数为{airCount * air.ClientNum}";
  4519. if (!string.IsNullOrWhiteSpace(errMsg))
  4520. {
  4521. info = $"航班{air.FlightsCode} " + errMsg ;
  4522. }
  4523. infos.Add(info);
  4524. groupAirCount += airCount * air.ClientNum;
  4525. }
  4526. var groupinfo = listAir.First(x => x.Id == airArr.Key);
  4527. string temp = "本团人数" + Convert.ToInt32(groupinfo.VisitPNumber) + ",该人员" + user.CnName + "共订航段数" + groupAirCount.ToString() + ",每程航班提成为10元," + user.CnName + "提成共" + (groupAirCount * 10).ToString("#0.00");
  4528. resultArr.Add(new ComputeRoyaltiesView
  4529. {
  4530. TeamName = groupinfo.TeamName,
  4531. TeamId = groupinfo.Id,
  4532. ChiArr = infos,
  4533. TeamLvStr = teamLv.Find(x=>x.Id == groupinfo.TeamLevSId)?.Name,
  4534. VisitDate = groupinfo.VisitDate,
  4535. Temp = temp,
  4536. Price = (groupAirCount * 10),
  4537. }) ;
  4538. }
  4539. }
  4540. else if (Hotel.Contains(userId))
  4541. {
  4542. //标准团组:¥10/间/晚 * 实际订房间数 * 实际订房晚数; setdata id 1001 客人房
  4543. var listHotel = _sqlSugar.Queryable<Grp_HotelReservations, Grp_DelegationInfo, Grp_CreditCardPayment>((x, a, b) => new JoinQueryInfos(
  4544. JoinType.Left,x.DiId == a.Id,
  4545. JoinType.Left,b.CTable == 76 && b.CId == x.Id ))
  4546. .Where((x, a, b) => x.IsDel == 0 && x.CreateUserId == userId && a.VisitDate >= StartDateTime
  4547. && a.VisitDate <= EndDateTime && a.IsDel == 0 && b.IsDel == 0 && x.CardPrice > 0 && a.IsSure == 1 && auditState.Contains(b.IsAuditGM) && x.CheckType == 1001).Select((x,a,b)=> new
  4548. {
  4549. a.Id,
  4550. a.TeamName,
  4551. a.VisitDate,
  4552. a.TeamLevSId,
  4553. a.VisitPNumber,
  4554. x.SingleRoomCount,
  4555. x.SuiteRoomCount,
  4556. x.DoubleRoomCount,
  4557. x.OtherRoomCount,
  4558. x.CheckInDate,
  4559. x.CheckOutDate,
  4560. x.HotelName
  4561. }).ToList();
  4562. var groupByid = listHotel.GroupBy(x => x.Id);
  4563. var propertys = new string[] { "SingleRoomCount", "SuiteRoomCount", "DoubleRoomCount", "OtherRoomCount" };
  4564. foreach (var group in groupByid)
  4565. {
  4566. var infos = new List<string>();
  4567. var totalPrice = 0.00M;
  4568. foreach (var item in group)
  4569. {
  4570. var hotelCount = 0;
  4571. foreach (var property in propertys)
  4572. {
  4573. var value = item.GetType().GetProperty(property).GetValue(item).ObjToInt();
  4574. if (value > 0)
  4575. {
  4576. hotelCount += value;
  4577. }
  4578. }
  4579. if (hotelCount > 0)
  4580. {
  4581. if (DateTime.TryParse(item.CheckInDate, out DateTime checkin) && DateTime.TryParse(item.CheckOutDate, out DateTime checkout))
  4582. {
  4583. var day = checkout - checkin;
  4584. infos.Add($"{item.HotelName} 共有 {hotelCount} 间房 , 入住时间{item.CheckInDate} - {item.CheckOutDate} 共 { day.TotalDays }晚 提成数量:{hotelCount * day.TotalDays} 提成金额:{hotelCount * day.TotalDays * 10}");
  4585. totalPrice += (decimal)(hotelCount * day.TotalDays * 10);
  4586. }
  4587. else
  4588. {
  4589. infos.Add(item.HotelName + " 时间有误!请检查 。");
  4590. }
  4591. }
  4592. }
  4593. var groupinfo = listHotel.First(x => x.Id == group.Key);
  4594. var temp = "本团人数" + groupinfo.VisitPNumber + ",该人员" + user.CnName + "共操作酒店晚数" + totalPrice / 10 + ",每间每晚提成10元," + user.CnName + "提成共" + totalPrice.ToString("#0.00") + "元";
  4595. resultArr.Add(new ComputeRoyaltiesView
  4596. {
  4597. TeamName = groupinfo.TeamName,
  4598. TeamId = groupinfo.Id,
  4599. ChiArr = infos,
  4600. TeamLvStr = teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name,
  4601. VisitDate = groupinfo.VisitDate,
  4602. Temp = temp,
  4603. Price = totalPrice,
  4604. });
  4605. }
  4606. }
  4607. else if (OP.Contains(userId))
  4608. {
  4609. var OPList = _sqlSugar.Queryable<Grp_DelegationInfo>().Where((a) => a.IsDel == 0
  4610. && a.VisitDate >= StartDateTime && a.VisitDate <= EndDateTime && a.IsSure == 1
  4611. ).ToList();
  4612. var LvArr = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.STid == 70 && x.IsDel == 0).ToList();
  4613. foreach (var groupinfo in OPList)
  4614. {
  4615. var price = LvArr.Find(x => x.Id == groupinfo.OpRoyaltyLv)?.Name.ObjToInt() ?? 0;
  4616. string temp = $"本团等级为{teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name} 提成金额为{price} {(string.IsNullOrWhiteSpace(groupinfo.OpRoyaltyRemark) ? "" : "提成说明:" + groupinfo.OpRoyaltyRemark )}";
  4617. if (price == 0)
  4618. {
  4619. temp = $"本团等级为{teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name} op提成选项未选择!" ;
  4620. }
  4621. resultArr.Add(new ComputeRoyaltiesView
  4622. {
  4623. TeamName = groupinfo.TeamName,
  4624. TeamId = groupinfo.Id,
  4625. ChiArr = new List<string>() { temp },
  4626. TeamLvStr = teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name,
  4627. VisitDate = groupinfo.VisitDate,
  4628. Temp = temp,
  4629. Price = price
  4630. });
  4631. }
  4632. }
  4633. else if (Invitation.Contains(userId))
  4634. {
  4635. //2)付费公务活动部分:¥50 / 团;
  4636. //4)不付费公务活动部分(自己联络)额外奖励:¥200 / 团(若公务活动方与邀请方为同一机构,奖励金额为¥100 / 团);
  4637. //5)只发邀请的团组不付费邀请额外奖励:¥100 / 团;
  4638. //邀请方已授权我司签发的邀请仍按照:¥100 / 团,无额外奖励。
  4639. var officialList = _sqlSugar.Queryable<Res_OfficialActivities, Grp_DelegationInfo>((x,a)=>
  4640. new JoinQueryInfos(JoinType.Left,a.Id == x.DiId)
  4641. ).Where((x,a) => x.IsSubmitApproval == 0 && x.IsDel == 0 && a.IsDel == 0
  4642. && a.VisitDate >= StartDateTime && a.VisitDate <= EndDateTime && a.IsSure == 1
  4643. )
  4644. .Select((x, a) => new
  4645. {
  4646. a.Id,
  4647. a.TeamName,
  4648. a.VisitDate,
  4649. x.CreateUserId,
  4650. x.Type,
  4651. a.TeamLevSId,
  4652. x.Country,
  4653. x.Area,
  4654. x.Date,
  4655. x.Client
  4656. })
  4657. .ToList();
  4658. var groups = officialList.GroupBy(x => x.Id);
  4659. foreach (var group in groups)
  4660. {
  4661. var groupinfo = officialList.First(x => x.Id == group.Key);
  4662. var officialGroupList = group.GroupBy(d => d.CreateUserId);
  4663. int operUserMax = 0, operMaxCount = 0;
  4664. foreach (var item in officialGroupList)
  4665. {
  4666. if (item.Count() > operMaxCount)
  4667. {
  4668. operUserMax = item.Key;
  4669. operMaxCount = item.Count();
  4670. }
  4671. }
  4672. string temp = string.Empty;
  4673. bool isBasics = operUserMax == userId;
  4674. var money = 0;
  4675. var infos = new List<string>();
  4676. foreach (var item in group)
  4677. {
  4678. if (item.CreateUserId != user.Id)
  4679. {
  4680. continue;
  4681. }
  4682. string info = string.Empty;
  4683. if (item.Type == 0)
  4684. {
  4685. money += (100 + 300);
  4686. info = $"{item.Country} - {item.Area} - {item.Client} - {item.Date} 提成金额为 400";
  4687. }
  4688. else if (item.Type == 1)
  4689. {
  4690. money += 300;
  4691. info = $"{item.Country} - {item.Area} - {item.Client} - {item.Date} 提成金额为 300";
  4692. }
  4693. else if (item.Type == 2)
  4694. {
  4695. money += 200;
  4696. info = $"{item.Country} - {item.Area} - {item.Client} - {item.Date} 提成金额为 200";
  4697. }
  4698. infos.Add(info);
  4699. }
  4700. if (isBasics)
  4701. {
  4702. infos.Add($"{groupinfo.TeamName} 该人员{user.CnName}操作场数最多,基本提成为{150}");
  4703. }
  4704. else
  4705. {
  4706. infos.Add($"{groupinfo.TeamName} 操作场数不是最多人员,所以无基本提成");
  4707. }
  4708. resultArr.Add(new ComputeRoyaltiesView
  4709. {
  4710. TeamName = groupinfo.TeamName,
  4711. TeamId = groupinfo.Id,
  4712. ChiArr = infos,
  4713. TeamLvStr = teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name,
  4714. VisitDate = groupinfo.VisitDate,
  4715. Temp = temp,
  4716. Price = money,
  4717. });
  4718. }
  4719. }
  4720. else if (Visa.Contains(userId)) //签证
  4721. {
  4722. // 1)办理英国、加拿大、美国签证¥50元 / 人 / 团;
  4723. // 申根国家及其他所有国家¥30元 / 人 / 团;
  4724. // setdata id 974 客人
  4725. var existsCountry = new string[] { "英国", "加拿大", "美国" };
  4726. var whereExpression = Expressionable.Create<Grp_VisaInfo, Grp_DelegationInfo, Grp_CreditCardPayment>()
  4727. .And(
  4728. (x, a, b) => x.IsDel == 0 && x.CreateUserId == userId && (b.IsAuditGM == 1 || b.IsAuditGM == 3)
  4729. && a.IsDel == 0 && a.VisitDate >= StartDateTime && a.VisitDate <= EndDateTime && b.IsDel == 0 && x.IsThird == 0 && x.PassengerType == 974
  4730. && a.IsSure == 1 && auditState.Contains(b.IsAuditGM)
  4731. );
  4732. var listVisa = _sqlSugar.Queryable<Grp_VisaInfo, Grp_DelegationInfo, Grp_CreditCardPayment>((x, a, b) => new
  4733. JoinQueryInfos(
  4734. JoinType.Left, a.Id == x.DIId,
  4735. JoinType.Left, b.CTable == 80 && b.CId == x.Id)
  4736. )
  4737. .Where(whereExpression.ToExpression())
  4738. .Select((x, a, b) => new
  4739. {
  4740. a.Id,
  4741. a.TeamName,
  4742. a.VisitDate,
  4743. a.TeamLevSId,
  4744. a.VisitPNumber,
  4745. a.VisitCountry,
  4746. x.VisaDescription,
  4747. x.VisaFreeNumber,
  4748. x.VisaNumber,
  4749. x.VisaPrice
  4750. })
  4751. .ToList();
  4752. var groupByid = listVisa.GroupBy(x => x.Id);
  4753. foreach (var visaArr in groupByid)
  4754. {
  4755. var groupinfo = listVisa.First(x => x.Id == visaArr.Key);
  4756. var singlePrice = existsCountry.Where(x => groupinfo.VisitCountry.Contains(x)).Count() > 0 ? 50 : 30;
  4757. int count = 0, money = 0;
  4758. var arr = new List<string>();
  4759. foreach (var visa in visaArr)
  4760. {
  4761. if (visa.VisaPrice > 0)
  4762. {
  4763. count += visa.VisaFreeNumber + visa.VisaNumber;
  4764. money += singlePrice * (visa.VisaFreeNumber + visa.VisaNumber);
  4765. }
  4766. else
  4767. {
  4768. count -= visa.VisaFreeNumber + visa.VisaNumber;
  4769. money -= singlePrice * (visa.VisaFreeNumber + visa.VisaNumber);
  4770. }
  4771. string info = $"签证 {visa.VisaDescription} {(visa.VisaPrice > 0 ? "" : "此笔为退费!")} 人数为{visa.VisaFreeNumber + visa.VisaNumber} 单价为{singlePrice} 金额为{singlePrice * (visa.VisaFreeNumber + visa.VisaNumber)}";
  4772. arr.Add(info);
  4773. }
  4774. string temp = "本团人数" + groupinfo.VisitPNumber + ",该人员" + user.CnName + "共办理英国、加拿大、美国签证" + (singlePrice == 50 ? count : 0).ToString() + "本护照(包含免签人员),申根国家及其他所有国家" + (singlePrice == 30 ? count : 0).ToString() + "本。" + user.CnName + "提成共" + money.ToString("#0.00") + "元";
  4775. resultArr.Add(new ComputeRoyaltiesView
  4776. {
  4777. TeamName = groupinfo.TeamName,
  4778. TeamId = groupinfo.Id,
  4779. ChiArr = arr,
  4780. TeamLvStr = teamLv.Find(x => x.Id == groupinfo.TeamLevSId)?.Name,
  4781. VisitDate = groupinfo.VisitDate,
  4782. Temp = temp,
  4783. Price = money,
  4784. });
  4785. }
  4786. }
  4787. if (resultArr.Count > 0)
  4788. {
  4789. jw.Code = 200;
  4790. jw.Msg = "success!";
  4791. decimal total = 0;
  4792. foreach (var item in resultArr)
  4793. {
  4794. //var number = item.GetType().GetProperty("price")?.GetValue(item)?.ToString();
  4795. //total += decimal.TryParse(number,out decimal numberInt) ? numberInt : 0.00M;
  4796. total += item.Price;
  4797. }
  4798. jw.Data = new
  4799. {
  4800. resultArr,
  4801. totalPrice = total,
  4802. };
  4803. }
  4804. else
  4805. {
  4806. jw.Msg = "暂无数据!";
  4807. }
  4808. return Ok(jw);
  4809. }
  4810. /// <summary>
  4811. /// 导出提成表格
  4812. /// </summary>
  4813. /// <returns></returns>
  4814. [HttpPost]
  4815. public IActionResult ExportRoyaltyExcel(ExportRoyaltyExcelDto dto)
  4816. {
  4817. var jw = JsonView(false);
  4818. var apiResult = ComputeRoyalties(new
  4819. ComputeRoyaltiesDto
  4820. {
  4821. EndDate = dto.EndDate,
  4822. StartDate = dto.StartDate,
  4823. UserId = dto.UserId,
  4824. });
  4825. var parseApiResult = ((apiResult as OkObjectResult)?.Value) as OASystem.Domain.ViewModels.JsonView;
  4826. if (parseApiResult != null && parseApiResult.Code == 200)
  4827. {
  4828. var apiArr = (parseApiResult.Data?.GetType().GetProperty("resultArr")?.GetValue(parseApiResult.Data)) as List<ComputeRoyaltiesView>;
  4829. var user = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == dto.UserId);
  4830. if (apiArr != null && apiArr.Count > 0)
  4831. {
  4832. Dictionary<string, string> dic = new Dictionary<string, string>();
  4833. //dic.Add("Name", "人员:" + user.CnName);
  4834. dic.Add("startTime", dto.StartDate);
  4835. dic.Add("endTime", dto.EndDate);
  4836. dic.Add("operName", user.CnName);
  4837. dic.Add("timeNow", DateTime.Now.ToString("yyyy年MM月dd日"));
  4838. //dic.Add("DowntimeNow", DateTime.Now.ToString("yyyy年MM月dd日"));
  4839. dic.Add("totalPrice",( "总金额:" + parseApiResult.Data?.GetType().GetProperty("totalPrice")?.GetValue(parseApiResult.Data).ObjToDecimal().ToString() ?? "0") +" 元");
  4840. ArrayList ToTableArr = new ArrayList();
  4841. int No = 1;
  4842. //打开excel模板
  4843. foreach (var item in apiArr)
  4844. {
  4845. //载入数据
  4846. ToTableArr.Add(new
  4847. {
  4848. No,
  4849. item.TeamName,
  4850. item.VisitDate,
  4851. item.TeamLvStr,
  4852. item.Temp,
  4853. infos = string.Join("\r\n",item.ChiArr),
  4854. price = item.Price + "元",
  4855. });
  4856. No++;
  4857. }
  4858. DataTable TbData =CommonFun.ToDataTableArray(ToTableArr);
  4859. TbData.TableName = "TbData";
  4860. WorkbookDesigner designer = new WorkbookDesigner();
  4861. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/提成结算template.xlsx");
  4862. foreach (var key in dic.Keys)
  4863. {
  4864. designer.SetDataSource(key, dic[key]);
  4865. }
  4866. //数据源
  4867. designer.SetDataSource(TbData);
  4868. designer.Process();
  4869. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "RoyaltyExcel/" + user.CnName + "_提成结算.xlsx" );
  4870. jw = JsonView(true, "success!", new
  4871. {
  4872. Url = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath")+ "RoyaltyExcel/" + user.CnName + "_提成结算.xlsx",
  4873. });
  4874. }
  4875. }
  4876. else
  4877. {
  4878. jw.Msg = "获取提成信息error " + jw.Msg;
  4879. }
  4880. return Ok(jw);
  4881. }
  4882. /// <summary>
  4883. /// 提成财务确认通知
  4884. /// </summary>
  4885. /// <returns></returns>
  4886. [HttpPost]
  4887. public async Task<IActionResult> RoyaltyConfirmByFin(RoyaltyConfirmDto dto)
  4888. {
  4889. var jw = JsonView(false);
  4890. if (!DateTime.TryParse(dto.StartData, out DateTime StartDateTime))
  4891. {
  4892. jw.Msg = "开始时间格式有误!";
  4893. return Ok(jw);
  4894. }
  4895. if (!DateTime.TryParse(dto.EndData, out DateTime EndDateTime))
  4896. {
  4897. jw.Msg = "结束时间格式有误!";
  4898. return Ok(jw);
  4899. }
  4900. if (DateTime.Compare(StartDateTime, EndDateTime) > 0)
  4901. {
  4902. jw.Msg = "开始时间大于结束时间!";
  4903. return Ok(jw);
  4904. }
  4905. if (dto.ComputeRoyaltiesList.Count != 0)
  4906. {
  4907. var user = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id == dto.UserId);
  4908. if (user == null) { return Ok(JsonView(false, "通知失败! 人员信息有误!")); }
  4909. //保存提成信息
  4910. //消息通知对应人员(公司 部门 人员 时间段 团组id 是否确定 )
  4911. List<Fin_RoyaltyConfirm> entitys = dto.ComputeRoyaltiesList.Select(x => new Fin_RoyaltyConfirm
  4912. {
  4913. UserId = dto.UserId,
  4914. ChiArr = JsonConvert.SerializeObject(x.ChiArr),
  4915. CreateTime = DateTime.Now,
  4916. CreateUserId = dto.UserId,
  4917. IsConfirm = 0,
  4918. TeamId = x.TeamId,
  4919. TeamLvStr = x.TeamLvStr,
  4920. Price = x.Price,
  4921. VisitDate = x.VisitDate,
  4922. TeamName = x.TeamName,
  4923. Temp = x.Temp,
  4924. IsSeed = 0
  4925. }).ToList();
  4926. var expressionSoftDeleteWhere = Expressionable.Create<Fin_RoyaltyConfirm>()
  4927. .And(it => it.VisitDate >= StartDateTime)
  4928. .And(it => it.VisitDate <= EndDateTime)
  4929. .And(it => it.IsDel == 0)
  4930. .And(it => it.UserId == dto.UserId)
  4931. .And(it => it.IsSeed == 0)
  4932. .ToExpression();
  4933. var expressionSelectWhere = Expressionable.Create<Fin_RoyaltyConfirm>()
  4934. .And(it => it.VisitDate >= StartDateTime)
  4935. .And(it => it.VisitDate <= EndDateTime)
  4936. .And(it => it.IsDel == 0)
  4937. .And(it => it.UserId == dto.UserId)
  4938. .And(it => it.IsSeed == 1)
  4939. .ToExpression();
  4940. _sqlSugar.BeginTran();
  4941. try
  4942. {
  4943. _ = _sqlSugar.Updateable<Fin_RoyaltyConfirm>().SetColumns(it => new Fin_RoyaltyConfirm() { IsDel = 1, DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm"), DeleteUserId = dto.UserId })
  4944. .Where(expressionSoftDeleteWhere)
  4945. .ExecuteCommand();
  4946. var confirmYes = _sqlSugar.Queryable<Fin_RoyaltyConfirm>().Where(expressionSelectWhere).Select(x => x.TeamId).ToList();
  4947. entitys = entitys.Where(x => !confirmYes.Contains(x.TeamId)).ToList();
  4948. _ = _sqlSugar.Insertable<Fin_RoyaltyConfirm>(entitys).ExecuteCommand();
  4949. _sqlSugar.CommitTran();
  4950. //调用通知
  4951. var title = "提成确认";
  4952. var center = $"【{dto.StartData}-{dto.EndData}】 提成财务已确认,请尽快查看!";
  4953. //【{dto.StartData}-{dto.EndData}-{dto.CompanyId}-{dto.DeparId}-{dto.UserId}】";
  4954. var ids = new List<int> { 235 , 233 }; //dto.UserId
  4955. await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations,title, center, ids);
  4956. jw = JsonView(true, $"人员:{user.CnName} {dto.StartData}-{dto.EndData} 通知成功!");
  4957. }
  4958. catch (Exception ex)
  4959. {
  4960. _sqlSugar.RollbackTran();
  4961. jw = JsonView(false, "保存失败!" + ex.Message);
  4962. }
  4963. }
  4964. else
  4965. {
  4966. jw = JsonView(false,"保存失败! 无提成信息");
  4967. }
  4968. return Ok(jw);
  4969. }
  4970. /// <summary>
  4971. /// 查询提成信息
  4972. /// </summary>
  4973. /// <param name="dto"></param>
  4974. /// <returns></returns>
  4975. [HttpPost]
  4976. public IActionResult QueryRoyaltyInfo(QueryRoyaltyInfoDto dto)
  4977. {
  4978. var jw = JsonView(false);
  4979. var stateArr = new int[] { -1, 0, 1 };
  4980. if (!DateTime.TryParse(dto.StartDate, out DateTime StartDateTime))
  4981. {
  4982. jw.Msg = "开始时间格式有误!";
  4983. return Ok(jw);
  4984. }
  4985. if (!DateTime.TryParse(dto.EndDate, out DateTime EndDateTime))
  4986. {
  4987. jw.Msg = "结束时间格式有误!";
  4988. return Ok(jw);
  4989. }
  4990. if (DateTime.Compare(StartDateTime, EndDateTime) > 0)
  4991. {
  4992. jw.Msg = "开始时间大于结束时间!";
  4993. return Ok(jw);
  4994. }
  4995. if (!stateArr.Contains(dto.Send) || !stateArr.Contains(dto.Confirm))
  4996. {
  4997. jw.Msg = "状态标识有误!";
  4998. return Ok(jw);
  4999. }
  5000. var expressionSelectWhere = Expressionable.Create<Fin_RoyaltyConfirm>()
  5001. .And(it => it.VisitDate >= StartDateTime)
  5002. .And(it => it.VisitDate <= EndDateTime)
  5003. .And(it => it.IsDel == 0)
  5004. .And(it => it.UserId == dto.UserId)
  5005. .AndIF(dto.Confirm != -1,it => it.IsConfirm == dto.Confirm)
  5006. .AndIF(dto.Send != -1, it => it.IsSeed == dto.Send)
  5007. .ToExpression();
  5008. try
  5009. {
  5010. var query = _sqlSugar.Queryable<Fin_RoyaltyConfirm>().Where(expressionSelectWhere).ToList().Select(x => new
  5011. {
  5012. x.Price,
  5013. ChiArr = JsonConvert.DeserializeObject<List<string>>(x.ChiArr),
  5014. x.IsConfirm,
  5015. x.Id,
  5016. x.TeamId,
  5017. x.TeamName,
  5018. x.TeamLvStr,
  5019. x.Temp,
  5020. x.VisitDate,
  5021. x.IsSeed
  5022. });
  5023. jw = JsonView(true, "获取成功!", new
  5024. {
  5025. List = query,
  5026. CostPrice = query.Sum(x=>x.Price),
  5027. ConfirmPrice = query.Where(x=>x.IsConfirm == 1).Sum(x=>x.Price),
  5028. NoConfirmPrice = query.Where(x => x.IsConfirm == 0).Sum(x => x.Price),
  5029. SeedPrice = query.Where(x => x.IsSeed == 1).Sum(x => x.Price),
  5030. NoSeedPrice = query.Where(x => x.IsSeed == 0).Sum(x => x.Price),
  5031. });
  5032. }
  5033. catch (Exception ex)
  5034. {
  5035. jw = JsonView(true, "获取失败!" + ex.Message);
  5036. }
  5037. return Ok(jw);
  5038. }
  5039. /// <summary>
  5040. /// 个人提成确认
  5041. /// </summary>
  5042. /// <param name="dto"></param>
  5043. /// <returns></returns>
  5044. [HttpPost]
  5045. public IActionResult RoyaltyConfirmByUser(RoyaltyConfirmByUserDto dto)
  5046. {
  5047. var jw = JsonView(false);
  5048. var stateArr = new int[] {0 , 1};
  5049. if (!stateArr.Contains(dto.State))
  5050. {
  5051. return Ok(JsonView(false,"状态标识有误!"));
  5052. }
  5053. if (dto.Data != null && dto.Data.Count != 0)
  5054. {
  5055. var expressionUpdateWhere = Expressionable.Create<Fin_RoyaltyConfirm>()
  5056. .And(it => dto.Data.Contains (it.Id))
  5057. .And(it => it.IsDel == 0)
  5058. .ToExpression();
  5059. var count = _sqlSugar.Updateable<Fin_RoyaltyConfirm>().SetColumns(x => new Fin_RoyaltyConfirm
  5060. {
  5061. IsConfirm = dto.State,
  5062. })
  5063. .Where(expressionUpdateWhere).ExecuteCommand();
  5064. jw.Msg = $"{count}个团组确认成功!";
  5065. jw.Code = 200;
  5066. }
  5067. else
  5068. {
  5069. jw.Msg = "Data为空!";
  5070. }
  5071. return Ok(jw);
  5072. }
  5073. /// <summary>
  5074. /// 提成发放
  5075. /// </summary>
  5076. /// <param name="dto"></param>
  5077. /// <returns></returns>
  5078. [HttpPost]
  5079. public IActionResult RoyaltySeed(RoyaltySeedDto dto)
  5080. {
  5081. var jw = JsonView(false);
  5082. if (dto.Data != null && dto.Data.Count > 0)
  5083. {
  5084. var updateCount = _sqlSugar.Updateable<Fin_RoyaltyConfirm>().SetColumns(x => new Fin_RoyaltyConfirm
  5085. { IsSeed = 1 }).Where(x => dto.Data.Contains(x.Id) && x.IsDel == 0 && x.IsConfirm == 1).ExecuteCommand();
  5086. var info = $"{updateCount}个团组提成发放成功!";
  5087. if (dto.Data.Count > updateCount)
  5088. {
  5089. info += $"/r/n{dto.Data.Count - updateCount}个团组未确认!";
  5090. }
  5091. jw = JsonView(true, info);
  5092. }
  5093. else
  5094. {
  5095. jw.Msg = "发放的数据为空!";
  5096. }
  5097. return Ok(jw);
  5098. }
  5099. /// <summary>
  5100. /// 提成确认信息
  5101. /// </summary>
  5102. /// <returns></returns>
  5103. [HttpPost]
  5104. public IActionResult RoyaltyConfirmInfo()
  5105. {
  5106. var jw = JsonView(false);
  5107. var queryExpression = Expressionable.Create<Fin_RoyaltyConfirm>()
  5108. .And(r => r.IsDel == 0)
  5109. .And(r => r.IsConfirm == 1)
  5110. .And(r => r.IsSeed == 0)
  5111. .ToExpression();
  5112. var DbQueryConfirmInfo = _sqlSugar.Queryable<Fin_RoyaltyConfirm>()
  5113. .LeftJoin<Sys_Users>((r,s) => s.IsDel == 0 && s.Id == r.UserId)
  5114. .LeftJoin<Sys_JobPost>((r, s , p) => p.IsDel == 0 && p.Id == s.JobPostId)
  5115. .LeftJoin<Sys_Department>((r, s, p , d) => d.IsDel == 0 && d.Id == p.DepId)
  5116. .LeftJoin<Sys_Company>((r, s, p, d, c) => c.IsDel == 0 && c.Id == d.CompanyId)
  5117. .Where(queryExpression)
  5118. .Select((r, s, p, d, c) => new
  5119. {
  5120. r.UserId,
  5121. r.TeamId,
  5122. r.Id,
  5123. r.TeamName,
  5124. r.Price,
  5125. s.CnName,
  5126. p.JobName,
  5127. d.DepName,
  5128. c.CompanyName
  5129. })
  5130. .ToList();
  5131. var groupConfirmInfoByUser = DbQueryConfirmInfo.GroupBy(x => x.UserId);
  5132. ArrayList returnData = new ArrayList();
  5133. foreach (var item in groupConfirmInfoByUser)
  5134. {
  5135. var first = item.First();
  5136. returnData.Add(new
  5137. {
  5138. UserId = item.Key,
  5139. Count = item.Count(),
  5140. first.CompanyName,
  5141. first.DepName,
  5142. first.JobName,
  5143. first.CnName,
  5144. SumPrice = item.Sum(x=>x.Price),
  5145. RoyaltyIdArr = item.Select(x=>x.Id)
  5146. });
  5147. }
  5148. jw = JsonView(true,"获取成功!",returnData);
  5149. return Ok(jw);
  5150. }
  5151. /// <summary>
  5152. /// 提交到日付申请
  5153. /// </summary>
  5154. /// <returns></returns>
  5155. [HttpPost]
  5156. public async Task<IActionResult> RoyaltyFormPrice(RoyaltyFromPriceDto dto)
  5157. {
  5158. var jw = JsonView(false,"用户ID为空!");
  5159. var User = _sqlSugar.Queryable<Sys_Users>().First(x => x.Id
  5160. == dto.CreateId && x.IsDel == 0);
  5161. if (User == null)
  5162. {
  5163. JsonView(false, "createid 不存在!");
  5164. }
  5165. if (dto.Items.Count > 0)
  5166. {
  5167. var queryExpression = Expressionable.Create<Fin_RoyaltyConfirm>()
  5168. .And(r => r.IsDel == 0)
  5169. .And(r => r.IsConfirm == 1)
  5170. .And(r => dto.Items.Select(x=>x.UserId).Contains(r.UserId))
  5171. .ToExpression();
  5172. var DbQueryConfirmInfo = _sqlSugar.Queryable<Fin_RoyaltyConfirm>()
  5173. .LeftJoin<Sys_Users>((r, s) => s.IsDel == 0 && s.Id == r.UserId)
  5174. .LeftJoin<Sys_JobPost>((r, s, p) => p.IsDel == 0 && p.Id == s.JobPostId)
  5175. .LeftJoin<Sys_Department>((r, s, p, d) => d.IsDel == 0 && d.Id == p.DepId)
  5176. .LeftJoin<Sys_Company>((r, s, p, d, c) => c.IsDel == 0 && c.Id == d.CompanyId)
  5177. .Where(queryExpression)
  5178. .Select((r, s, p, d, c) => new
  5179. {
  5180. r.UserId,
  5181. r.TeamId,
  5182. r.Id,
  5183. r.TeamName,
  5184. r.Price,
  5185. s.CnName,
  5186. p.JobName,
  5187. d.DepName,
  5188. c.CompanyName,
  5189. CompanyId = c.Id,
  5190. UserName = s.CnName,
  5191. })
  5192. .ToList();
  5193. //已经提交到日付的用户提成信息
  5194. var existsDb = _sqlSugar.Queryable<Fin_RoyaltyForm>()
  5195. .Where(x => dto.Items
  5196. .Select(x => x.UserId).Contains(x.UserId) && x.IsDel == 0 )
  5197. .ToList();
  5198. var GroupByConfirmInfo = DbQueryConfirmInfo.GroupBy(x => x.UserId ).ToList();
  5199. //关联信息
  5200. List<Fin_RoyaltyForm> relevanceSoure = new List<Fin_RoyaltyForm>();
  5201. AddDailyFeePaymentDto dayPrice = new AddDailyFeePaymentDto()
  5202. {
  5203. UserId = dto.CreateId,
  5204. Instructions = DateTime.Now.ToString("yyyy-MM-dd HH:mm") + " 提成导入日付!",
  5205. PortType = 1,
  5206. CompanyId = 2,
  5207. PriceTypeId = 668,
  5208. TransferTypeId = 798,
  5209. };
  5210. List<AddDailyFeePaymentContentDto> ChiDayPrice = new List<AddDailyFeePaymentContentDto>();
  5211. _sqlSugar.BeginTran();
  5212. try
  5213. {
  5214. string message = string.Empty;
  5215. foreach (var item in GroupByConfirmInfo)
  5216. {
  5217. var first = item.First();
  5218. var reqBody = dto.Items.Find(x => x.UserId == item.Key);
  5219. var exists = item.Where(x => reqBody!.ChiArr.Contains(x.Id));
  5220. var existsDbByUser = existsDb.Where(x => x.UserId == item.Key);
  5221. var idsByUser = string.Join(',',existsDbByUser.Select(x=>x.ConfirmIdArr));
  5222. var idsByUserList = idsByUser.Split(',')
  5223. .Select(x=>
  5224. {
  5225. if (!string.IsNullOrWhiteSpace(x) && int.TryParse(x, out int intx))
  5226. {
  5227. return intx;
  5228. }
  5229. return 0;
  5230. })
  5231. .Where(x => x != 0)
  5232. .ToList();
  5233. var saveArr = exists.Where(x => !idsByUserList.Contains(x.Id));
  5234. var existsYes = exists.Where(x => idsByUserList.Contains(x.Id));
  5235. var yesPrice = existsYes.Sum(x => x.Price);
  5236. var savePrice = saveArr.Sum(x => x.Price);
  5237. if (saveArr.Count() > 0) {
  5238. ChiDayPrice.Add(new
  5239. AddDailyFeePaymentContentDto
  5240. {
  5241. ItemTotal = savePrice,
  5242. Price = savePrice,
  5243. Quantity = 1,
  5244. PriceName = first.CnName + "提成金额!",
  5245. });
  5246. relevanceSoure.Add(new
  5247. Fin_RoyaltyForm
  5248. {
  5249. CreateUserId = dto.CreateId,
  5250. ConfirmIdArr = string.Join(',', saveArr.Select(x => x.Id)),
  5251. CreateTime = DateTime.Now,
  5252. IsDel = 0,
  5253. UserId = item.Key,
  5254. });
  5255. }
  5256. if (yesPrice > 0 ) {
  5257. message += $"{first.CnName} 提成 {savePrice}元已导入日付申请 , {yesPrice} 元已经存在 ! \r\n";
  5258. }
  5259. else {
  5260. message += $"{first.CnName} 提成 {savePrice}元已导入日付申请 ! \r\n";
  5261. }
  5262. }
  5263. dayPrice.FeeContents = ChiDayPrice;
  5264. dayPrice.SumPrice = ChiDayPrice.Sum(x => x.ItemTotal);
  5265. if (dayPrice.SumPrice != 0)
  5266. {
  5267. var ApiResult = await _daiRep.Add(dayPrice);
  5268. int dailyId = Convert.ToInt32(ApiResult?.Data?.GetType().GetProperty("dailyId").GetValue(ApiResult.Data));
  5269. int sign = Convert.ToInt32(ApiResult?.Data?.GetType().GetProperty("sign").GetValue(ApiResult.Data));
  5270. relevanceSoure.ForEach(x => x.DayOverhead = dailyId);
  5271. var addCount = _sqlSugar.Insertable<Fin_RoyaltyForm>(relevanceSoure).ExecuteCommand();
  5272. }
  5273. _sqlSugar.CommitTran();
  5274. //消息通知
  5275. //await AppNoticeLibrary.DailyPayReminders_Create_ToCaiwuChat(dailyId, sign, QiyeWeChatEnum.CaiWuChat);
  5276. jw = JsonView(true, message);
  5277. }
  5278. catch (Exception ex)
  5279. {
  5280. _sqlSugar.RollbackTran();
  5281. jw = JsonView(false, $" Api Error ({ex.Message})");
  5282. }
  5283. }
  5284. return Ok(jw);
  5285. }
  5286. #endregion
  5287. #region 团组未审核数据
  5288. /// <summary>
  5289. /// 团组未审核费用数据
  5290. /// </summary>
  5291. /// <param name="beginDt"></param>
  5292. /// <param name="endDt"></param>
  5293. /// <returns></returns>
  5294. [HttpGet]
  5295. public async Task<IActionResult> GroupUnAuditFeeList(string beginDt,string endDt)
  5296. {
  5297. var jw = JsonView(false);
  5298. bool beginDtBool = DateTime.TryParse(beginDt, out DateTime _beginDt),
  5299. endDtBool = DateTime.TryParse(endDt, out DateTime _endDt);
  5300. if (!beginDtBool && !endDtBool)
  5301. {
  5302. jw.Msg = $"开始或者结束时间格式不正确!";
  5303. return Ok(jw);
  5304. }
  5305. var _groupDatas = _sqlSugar.Queryable<Grp_DelegationInfo>()
  5306. .Where(x => x.IsDel == 0 &&
  5307. x.VisitDate >= _beginDt &&
  5308. x.VisitDate <= _endDt
  5309. )
  5310. .ToList();
  5311. var _groupIds = _groupDatas.Select(x => x.Id).ToList();
  5312. if (_groupIds.Count < 1)
  5313. {
  5314. jw.Msg = $"该时间段暂无出访的团组!";
  5315. return Ok(jw);
  5316. }
  5317. var _DailyFeePaymentResult = new tree_Group_DailyFeePaymentResult();
  5318. var dataList = new List<tree_Group_DailyFeePaymentPageListView>();
  5319. var _paymentDatas = _sqlSugar.Queryable<Grp_CreditCardPayment>()
  5320. .Where(x => x.IsDel == 0 &&
  5321. _groupIds.Contains(x.DIId) &&
  5322. x.IsAuditGM == 0
  5323. )
  5324. .ToList();
  5325. _DailyFeePaymentResult.gz = _paymentDatas.Where(it => it.OrbitalPrivateTransfer == 0).Sum(it => ((it.PayMoney * it.DayRate) / 100) * it.PayPercentage); //公转
  5326. _DailyFeePaymentResult.sz = _paymentDatas.Where(it => it.OrbitalPrivateTransfer == 1).Sum(it => ((it.PayMoney * it.DayRate) / 100) * it.PayPercentage); ; //私转
  5327. #region 相关基础数据源
  5328. var userDatas = _sqlSugar.Queryable<Sys_Users>().ToList();
  5329. var setDatas = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
  5330. var countryFeeDatas = _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(it => it.IsDel == 0).ToList();
  5331. //76 酒店预订
  5332. var hotelDatas = _sqlSugar.Queryable<Grp_HotelReservations>()
  5333. .InnerJoin<Grp_CreditCardPayment>((hr,ccp) => hr.Id == ccp.CId &&
  5334. ccp.CTable == 76 &&
  5335. ccp.IsDel == 0
  5336. )
  5337. .Where((hr, ccp) => hr.IsDel == 0 && _groupIds.Contains(hr.DiId) && ccp.IsAuditGM == 0)
  5338. .ToList();
  5339. var hotelContentDatas = _sqlSugar.Queryable<Grp_HotelReservationsContent>()
  5340. .Where(it => it.IsDel == 0 &&
  5341. it.IsPay == 0 &&
  5342. it.Price != 0 &&
  5343. _groupIds.Contains(it.DiId)
  5344. )
  5345. .ToList();
  5346. //79 车/导游地接
  5347. var opDatas = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>()
  5348. .InnerJoin<Grp_CreditCardPayment>((ctggr, ccp) => ctggr.Id == ccp.CId &&
  5349. ccp.CTable == 79 &&
  5350. ccp.IsDel == 0
  5351. )
  5352. .Where((ctggr, ccp) => ctggr.IsDel == 0 && _groupIds.Contains(ctggr.DiId) && ccp.IsAuditGM == 0)
  5353. .ToList();
  5354. // 80 签证
  5355. var visaDatas = _sqlSugar.Queryable<Grp_VisaInfo>()
  5356. .InnerJoin<Grp_CreditCardPayment>((vi, ccp) => vi.Id == ccp.CId &&
  5357. ccp.CTable == 80 &&
  5358. ccp.IsDel == 0
  5359. )
  5360. .Where((vi, ccp) => vi.IsDel == 0 && _groupIds.Contains(vi.DIId) && ccp.IsAuditGM == 0)
  5361. .ToList();
  5362. // 81 邀请/公务活动
  5363. var ioaDatas = _sqlSugar.Queryable<Grp_InvitationOfficialActivities>()
  5364. .InnerJoin<Grp_CreditCardPayment>((ioa, ccp) => ioa.Id == ccp.CId &&
  5365. ccp.CTable == 81 &&
  5366. ccp.IsDel == 0
  5367. )
  5368. .Where((ioa, ccp) => ioa.IsDel == 0 && _groupIds.Contains(ioa.DiId) && ccp.IsAuditGM == 0)
  5369. .ToList();
  5370. // 82 团组客户保险
  5371. var insureDatas = _sqlSugar.Queryable<Grp_Customers>()
  5372. .InnerJoin<Grp_CreditCardPayment>((c, ccp) => c.Id == ccp.CId &&
  5373. ccp.CTable == 82 &&
  5374. ccp.IsDel == 0
  5375. )
  5376. .Where((c, ccp) => c.IsDel == 0 && _groupIds.Contains(c.DiId) && ccp.IsAuditGM == 0)
  5377. .ToList();
  5378. // 85 机票预订
  5379. var airDatas = _sqlSugar.Queryable<Grp_AirTicketReservations>()
  5380. .InnerJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId &&
  5381. ccp.CTable == 85 &&
  5382. ccp.IsDel == 0
  5383. )
  5384. .Where((atr, ccp) => atr.IsDel == 0 && _groupIds.Contains(atr.DIId) && ccp.IsAuditGM == 0)
  5385. .ToList();
  5386. // 98 其他款项
  5387. var otherMoneyDatas = _sqlSugar.Queryable<Grp_DecreasePayments>()
  5388. .InnerJoin<Grp_CreditCardPayment>((dp, ccp) => dp.Id == ccp.CId &&
  5389. ccp.CTable == 98 &&
  5390. ccp.IsDel == 0
  5391. )
  5392. .Where((dp, ccp) => dp.IsDel == 0 && _groupIds.Contains(dp.DiId) && ccp.IsAuditGM == 0)
  5393. .ToList();
  5394. // 285 收款退还
  5395. var refundPaymentDatas = _sqlSugar.Queryable<Fin_PaymentRefundAndOtherMoney>()
  5396. .InnerJoin<Grp_CreditCardPayment>((prom, ccp) => prom.Id == ccp.CId &&
  5397. ccp.CTable == 285 &&
  5398. ccp.IsDel == 0
  5399. )
  5400. .Where((prom, ccp) => prom.IsDel == 0 && _groupIds.Contains(prom.DiId) && ccp.IsAuditGM == 0)
  5401. .ToList();
  5402. // 1015 超支费用
  5403. var extraCostDatas = _sqlSugar.Queryable<Fin_GroupExtraCost>()
  5404. .InnerJoin<Grp_CreditCardPayment>((gec, ccp) => gec.Id == ccp.CId &&
  5405. ccp.CTable == 1015 &&
  5406. ccp.IsDel == 0
  5407. )
  5408. .Where((gec, ccp) => gec.IsDel == 0 && _groupIds.Contains(gec.DiId) && ccp.IsAuditGM == 0)
  5409. .ToList();
  5410. #endregion
  5411. //Expense company
  5412. foreach (var groupInfo in _groupDatas)
  5413. {
  5414. var childList = new List<Group_DailyFeePaymentContentInfolView>();
  5415. var groupPaymentDatas = _paymentDatas.Where(it => groupInfo.Id == it.DIId).ToList();
  5416. if (groupPaymentDatas.Count > 0)
  5417. {
  5418. int rouNumber = 1;
  5419. foreach (var payInfo in groupPaymentDatas)
  5420. {
  5421. string priName = "-";
  5422. string orbitalPrivateTransfer = payInfo.OrbitalPrivateTransfer == 0 ? "公转" : payInfo.OrbitalPrivateTransfer == 1 ? "私转" : "-";
  5423. switch (payInfo.CTable)
  5424. {
  5425. case 76: //76 酒店预订
  5426. priName = $"[费用名称:{hotelDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.HotelName ?? ""}]";
  5427. break;
  5428. case 79: //79 车/导游地接
  5429. var opData = opDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id);
  5430. if (opData != null)
  5431. {
  5432. string area = "";
  5433. bool b = int.TryParse(opData.Area, out int areaId);
  5434. if (b)
  5435. {
  5436. string area1 = countryFeeDatas.Find(it => it.Id == areaId)?.Country ?? "-";
  5437. area = $"{area1}({setDatas.Find(it => it.Id == opData.PriceType)?.Name ?? "-"})";
  5438. }
  5439. else area = opData.Area;
  5440. string opPriName = "-";
  5441. if (!string.IsNullOrEmpty(opData.PriceName)) opPriName = opData.PriceName;
  5442. area += $"({opPriName})";
  5443. if (payInfo.OrbitalPrivateTransfer == 0) //公转
  5444. {
  5445. priName = $"【{orbitalPrivateTransfer}】【导游: {opData.ServiceGuide} 】[费用名称:{area}]";
  5446. }
  5447. else if (payInfo.OrbitalPrivateTransfer == 1) //私转
  5448. {
  5449. priName = $"【{orbitalPrivateTransfer}】【导游:{opData.ServiceGuide}】[费用名称:{area}]";
  5450. }
  5451. }
  5452. break;
  5453. case 80: // 80 签证
  5454. 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);
  5455. List<SimplClientInfo> arr = _sqlSugar.SqlQueryable<SimplClientInfo>(sql).ToList();
  5456. string visaClientName = visaDatas.Find(it => payInfo.DIId == it.DIId && payInfo.CId == it.Id)?.VisaClient ?? "";
  5457. string clientName = "-";
  5458. if (Regex.Match(visaClientName, @"\d+,?").Value.Length > 0)
  5459. {
  5460. string[] temparr = visaClientName.Split(',');
  5461. string fistrStr = temparr[0];
  5462. int count = temparr.Count();
  5463. int tempId;
  5464. bool success = int.TryParse(fistrStr, out tempId);
  5465. if (success)
  5466. {
  5467. SimplClientInfo tempInfo = arr.FirstOrDefault(s => s.Id == tempId);
  5468. if (tempInfo != null)
  5469. {
  5470. if (count > 1)
  5471. {
  5472. clientName = string.Format(@"{0}{1}等{2}人", tempInfo.LastName, tempInfo.FirstName, count);
  5473. }
  5474. else
  5475. {
  5476. clientName = string.Format(@"{0}{1}", tempInfo.LastName, tempInfo.FirstName);
  5477. }
  5478. }
  5479. }
  5480. else
  5481. {
  5482. clientName = fistrStr;
  5483. }
  5484. }
  5485. priName = $"[费用名称:{clientName}]";
  5486. break;
  5487. case 81: // 81 邀请/公务活动
  5488. priName = $"[费用名称:{ioaDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.Inviter ?? " -"}]";
  5489. break;
  5490. case 82: // 82 团组客户保险
  5491. priName = $"[费用名称:{insureDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.ClientName ?? " -"}]";
  5492. break;
  5493. case 85: // 85 机票预订
  5494. string flightsCode = airDatas.Find(it => payInfo.DIId == it.DIId && payInfo.CId == it.Id)?.FlightsCode ?? "-";
  5495. string airPayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "-";
  5496. priName = $"{flightsCode}【{airPayType}】";
  5497. break;
  5498. case 98: // 98 其他款项
  5499. priName = $"[费用名称:{otherMoneyDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  5500. break;
  5501. case 285: // 285 收款退还
  5502. priName = $"[费用名称:{refundPaymentDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  5503. break;
  5504. case 1015: // 1015 超支费用
  5505. priName = $"[费用名称:{extraCostDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
  5506. break;
  5507. default:
  5508. priName = "";
  5509. break;
  5510. }
  5511. if (payInfo.CTable == 76) //酒店单独处理
  5512. {
  5513. var hotelContents = hotelContentDatas.Where(it => it.HrId == payInfo.CId);
  5514. List<Group_DailyFeePaymentContentInfolView> childInfos = new List<Group_DailyFeePaymentContentInfolView>();
  5515. foreach (var hotelContent in hotelContents)
  5516. {
  5517. string subPriceName = "";
  5518. if (hotelContent.PriceType == 1) subPriceName = "房费";
  5519. else if (hotelContent.PriceType == 2) subPriceName = "早餐";
  5520. else if (hotelContent.PriceType == 3) subPriceName = "地税";
  5521. else if (hotelContent.PriceType == 4) subPriceName = "城市税";
  5522. if (string.IsNullOrEmpty(subPriceName)) subPriceName = priName;
  5523. else subPriceName = $"{priName.Replace("]", "")}-{subPriceName}]";
  5524. string payeeStr1 = string.Format(@" {0},开户行:{1},银行卡号:{2} ",
  5525. string.IsNullOrEmpty(hotelContent.Payee) ? "-" : hotelContent.Payee,
  5526. string.IsNullOrEmpty(hotelContent.OtherBankName) ? "-" : hotelContent.OtherBankName,
  5527. string.IsNullOrEmpty(hotelContent.OtherSideNo) ? "-" : hotelContent.OtherSideNo);
  5528. decimal _PaymentAmount1 = hotelContent.Price;//此次付款金额
  5529. decimal _CNYSubTotalAmount1 = _PaymentAmount1 * hotelContent.Rate;//此次付款金额
  5530. _CNYSubTotalAmount1 = Convert.ToDecimal(_CNYSubTotalAmount1.ToString("#0.00"));
  5531. var childInfo1 = new Group_DailyFeePaymentContentInfolView()
  5532. {
  5533. Id = payInfo.Id,
  5534. HotelSubId = hotelContent.Id,
  5535. Payee = payeeStr1,
  5536. RowNumber = rouNumber,
  5537. Applicant = userDatas.Find(it => it.Id == payInfo.CreateUserId)?.CnName ?? "",
  5538. ApplicantDt = payInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
  5539. PayType = setDatas.Find(it => it.Id == hotelContent.PayDId)?.Name ?? "",
  5540. TransferMark = orbitalPrivateTransfer,
  5541. PriceName = subPriceName,
  5542. ModuleName = setDatas.Find(it => it.Id == payInfo.CTable)?.Name ?? "",
  5543. PayCurrCode = setDatas.Find(it => it.Id == hotelContent.Currency)?.Name ?? "",
  5544. PaymentAmount = _PaymentAmount1,
  5545. PayRate = hotelContent.Rate,
  5546. CNYSubTotalAmount = _CNYSubTotalAmount1,
  5547. AuditStatus = payInfo.IsAuditGM
  5548. };
  5549. string remaksDescription1 = $"【{childInfo1.PayType}】【{childInfo1.ModuleName}】{rouNumber}、[申请人:{childInfo1.Applicant}]{subPriceName}[收款方:{childInfo1.Payee}] {childInfo1.PayCurrCode} {_PaymentAmount1.ToString("#0.00")}、CNY:{childInfo1.CNYSubTotalAmount.ToString("#0.00")}(团组:{groupInfo.TeamName})";
  5550. childInfo1.RemaksDescription = remaksDescription1;
  5551. childInfos.Add(childInfo1);
  5552. rouNumber++;
  5553. }
  5554. childList.AddRange(childInfos);
  5555. }
  5556. else
  5557. {
  5558. string payeeStr = string.Format(@" {0},开户行:{1},银行卡号:{2} ",
  5559. string.IsNullOrEmpty(payInfo.Payee) ? "-" : payInfo.Payee,
  5560. string.IsNullOrEmpty(payInfo.OtherBankName) ? "-" : payInfo.OtherBankName,
  5561. string.IsNullOrEmpty(payInfo.OtherSideNo) ? "-" : payInfo.OtherSideNo);
  5562. decimal _PaymentAmount = (payInfo.PayMoney / 100) * payInfo.PayPercentage;//此次付款金额
  5563. decimal _CNYSubTotalAmount = _PaymentAmount * payInfo.DayRate;//此次付款金额
  5564. _CNYSubTotalAmount = Convert.ToDecimal(_CNYSubTotalAmount.ToString("#0.00"));
  5565. var childInfo = new Group_DailyFeePaymentContentInfolView()
  5566. {
  5567. Id = payInfo.Id,
  5568. Payee = payeeStr,
  5569. RowNumber = rouNumber,
  5570. Applicant = userDatas.Find(it => it.Id == payInfo.CreateUserId)?.CnName ?? "",
  5571. ApplicantDt = payInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
  5572. PayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "",
  5573. TransferMark = orbitalPrivateTransfer,
  5574. PriceName = priName,
  5575. ModuleName = setDatas.Find(it => it.Id == payInfo.CTable)?.Name ?? "",
  5576. PayCurrCode = setDatas.Find(it => it.Id == payInfo.PaymentCurrency)?.Name ?? "",
  5577. PaymentAmount = _PaymentAmount,
  5578. PayRate = payInfo.DayRate,
  5579. CNYSubTotalAmount = _CNYSubTotalAmount,
  5580. AuditStatus = payInfo.IsAuditGM
  5581. };
  5582. string remaksDescription = $"【{childInfo.PayType}】【{childInfo.ModuleName}】{rouNumber}、[申请人:{childInfo.Applicant}]{priName}[收款方:{childInfo.Payee}] {childInfo.PayCurrCode} {_PaymentAmount.ToString("#0.00")}、CNY:{childInfo.CNYSubTotalAmount.ToString("#0.00")}(团组:{groupInfo.TeamName})";
  5583. childInfo.RemaksDescription = remaksDescription;
  5584. childList.Add(childInfo);
  5585. rouNumber++;
  5586. }
  5587. }
  5588. CompanyInfo companyInfo = new CompanyInfo();
  5589. companyInfo = ExpenseCompanyByTeamId(groupInfo.TeamDid);
  5590. dataList.Add(new tree_Group_DailyFeePaymentPageListView()
  5591. {
  5592. Id = Guid.NewGuid().ToString("N"),
  5593. GroupName = groupInfo.TeamName,
  5594. CompanyId = companyInfo.Id,
  5595. ConpanyName = companyInfo.ConpanyName,
  5596. CNYTotalAmount = childList.Sum(it => it.CNYSubTotalAmount),
  5597. ChildList = childList,
  5598. });
  5599. }
  5600. }
  5601. var dataList1 = new List<tree_Group_DailyFeePaymentPageListView>();
  5602. //移除没有数据的团
  5603. foreach (var item in dataList)
  5604. {
  5605. if (item.CNYTotalAmount > 0 && item.ChildList.Count >0)
  5606. {
  5607. dataList1.Add(item);
  5608. }
  5609. }
  5610. _DailyFeePaymentResult.dataList = dataList1;
  5611. jw.Code = StatusCodes.Status200OK;
  5612. jw.Msg = $"操作成功!";
  5613. jw.Data = _DailyFeePaymentResult;
  5614. return Ok(jw);
  5615. }
  5616. #endregion
  5617. }
  5618. }