FinancialController.cs 229 KB

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