FinancialController.cs 255 KB

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