FinancialController.cs 236 KB

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