FinancialController.cs 258 KB

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