FinancialController.cs 236 KB

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