FinancialController.cs 255 KB

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