FinancialController.cs 250 KB

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