btcpayserver/BTCPayServer/Controllers/UIPullPaymentController.cs

305 lines
13 KiB
C#
Raw Normal View History

2020-06-29 04:44:35 +02:00
using System;
using System.Collections.Generic;
2020-06-24 03:34:09 +02:00
using System.Linq;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Threading;
2020-06-24 03:34:09 +02:00
using System.Threading.Tasks;
using Amazon.S3.Model;
using BTCPayServer.Abstractions.Constants;
using BTCPayServer.Abstractions.Extensions;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.Client;
using BTCPayServer.Client.Models;
using BTCPayServer.Controllers.Greenfield;
2020-06-24 03:34:09 +02:00
using BTCPayServer.Data;
using BTCPayServer.HostedServices;
using BTCPayServer.Lightning;
using BTCPayServer.ModelBinders;
2020-06-24 03:34:09 +02:00
using BTCPayServer.Models;
using BTCPayServer.Models.WalletViewModels;
using BTCPayServer.NTag424;
2020-06-24 03:34:09 +02:00
using BTCPayServer.Payments;
using BTCPayServer.Payouts;
2020-06-24 03:34:09 +02:00
using BTCPayServer.Services;
using BTCPayServer.Services.Rates;
using BTCPayServer.Services.Stores;
using Dapper;
2020-06-24 06:44:26 +02:00
using Microsoft.AspNetCore.Authorization;
2020-06-24 03:34:09 +02:00
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NBitcoin;
using NBitcoin.DataEncoders;
using NdefLibrary.Ndef;
using Newtonsoft.Json.Linq;
2020-06-24 03:34:09 +02:00
namespace BTCPayServer.Controllers
{
public partial class UIPullPaymentController : Controller
2020-06-24 03:34:09 +02:00
{
private readonly ApplicationDbContextFactory _dbContextFactory;
private readonly CurrencyNameTable _currencyNameTable;
private readonly DisplayFormatter _displayFormatter;
private readonly UriResolver _uriResolver;
2020-06-24 03:34:09 +02:00
private readonly PullPaymentHostedService _pullPaymentHostedService;
private readonly BTCPayNetworkProvider _networkProvider;
2020-06-24 03:34:09 +02:00
private readonly BTCPayNetworkJsonSerializerSettings _serializerSettings;
private readonly PayoutMethodHandlerDictionary _payoutHandlers;
private readonly StoreRepository _storeRepository;
private readonly BTCPayServerEnvironment _env;
private readonly SettingsRepository _settingsRepository;
2020-06-24 03:34:09 +02:00
2022-01-07 04:32:00 +01:00
public UIPullPaymentController(ApplicationDbContextFactory dbContextFactory,
2020-06-24 03:34:09 +02:00
CurrencyNameTable currencyNameTable,
DisplayFormatter displayFormatter,
UriResolver uriResolver,
2020-06-24 03:34:09 +02:00
PullPaymentHostedService pullPaymentHostedService,
BTCPayNetworkProvider networkProvider,
BTCPayNetworkJsonSerializerSettings serializerSettings,
PayoutMethodHandlerDictionary payoutHandlers,
StoreRepository storeRepository,
BTCPayServerEnvironment env,
SettingsRepository settingsRepository)
2020-06-24 03:34:09 +02:00
{
_dbContextFactory = dbContextFactory;
_currencyNameTable = currencyNameTable;
_displayFormatter = displayFormatter;
_uriResolver = uriResolver;
2020-06-24 03:34:09 +02:00
_pullPaymentHostedService = pullPaymentHostedService;
_serializerSettings = serializerSettings;
_payoutHandlers = payoutHandlers;
_storeRepository = storeRepository;
_env = env;
_settingsRepository = settingsRepository;
_networkProvider = networkProvider;
2020-06-24 03:34:09 +02:00
}
2021-12-31 08:59:02 +01:00
[AllowAnonymous]
[HttpGet("pull-payments/{pullPaymentId}")]
2020-06-24 03:34:09 +02:00
public async Task<IActionResult> ViewPullPayment(string pullPaymentId)
{
using var ctx = _dbContextFactory.CreateContext();
var pp = await ctx.PullPayments.FindAsync(pullPaymentId);
if (pp is null)
return NotFound();
var blob = pp.GetBlob();
var store = await _storeRepository.FindStore(pp.StoreId);
if (store is null)
return NotFound();
2023-04-10 04:07:03 +02:00
var storeBlob = store.GetStoreBlob();
var payouts = (await ctx.Payouts.Where(p => p.PullPaymentDataId == pp.Id)
.OrderByDescending(o => o.Date)
.ToListAsync())
.Select(o => new
{
Entity = o,
Blob = o.GetBlob(_serializerSettings),
ProofBlob = _payoutHandlers.TryGet(o.GetPayoutMethodId())?.ParseProof(o)
});
2020-06-24 03:34:09 +02:00
var cd = _currencyNameTable.GetCurrencyData(blob.Currency, false);
var totalPaid = payouts.Where(p => p.Entity.State != PayoutState.Cancelled).Select(p => p.Blob.Amount).Sum();
var amountDue = blob.Limit - totalPaid;
ViewPullPaymentModel vm = new(pp, DateTimeOffset.UtcNow)
2020-06-24 03:34:09 +02:00
{
AmountCollected = totalPaid,
AmountDue = amountDue,
ClaimedAmount = amountDue,
CurrencyData = cd,
StartDate = pp.StartDate,
LastRefreshed = DateTime.UtcNow,
Payouts = payouts.Select(entity => new ViewPullPaymentModel.PayoutLine
{
Id = entity.Entity.Id,
Amount = entity.Blob.Amount,
AmountFormatted = _displayFormatter.Currency(entity.Blob.Amount, blob.Currency),
Currency = blob.Currency,
Status = entity.Entity.State,
Destination = entity.Blob.Destination,
PaymentMethod = PaymentMethodId.Parse(entity.Entity.PaymentMethodId),
Link = entity.ProofBlob?.Link,
TransactionId = entity.ProofBlob?.Id
}).ToList()
2020-06-24 03:34:09 +02:00
};
vm.IsPending &= vm.AmountDue > 0.0m;
vm.StoreBranding = await StoreBrandingViewModel.CreateAsync(Request, _uriResolver, storeBlob);
if (_pullPaymentHostedService.SupportsLNURL(blob))
{
var url = Url.Action(nameof(UILNURLController.GetLNURLForPullPayment), "UILNURL", new { cryptoCode = _networkProvider.DefaultNetwork.CryptoCode, pullPaymentId = vm.Id }, Request.Scheme, Request.Host.ToString());
vm.LnurlEndpoint = url != null ? new Uri(url) : null;
vm.SetupDeepLink = $"boltcard://program?url={GetBoltcardDeeplinkUrl(vm, OnExistingBehavior.UpdateVersion)}";
vm.ResetDeepLink = $"boltcard://reset?url={GetBoltcardDeeplinkUrl(vm, OnExistingBehavior.KeepVersion)}";
}
2020-06-24 03:34:09 +02:00
return View(nameof(ViewPullPayment), vm);
}
private string GetBoltcardDeeplinkUrl(ViewPullPaymentModel vm, OnExistingBehavior onExisting)
{
var registerUrl = Url.Action(nameof(GreenfieldPullPaymentController.RegisterBoltcard), "GreenfieldPullPayment",
new
{
pullPaymentId = vm.Id,
onExisting = onExisting.ToString()
}, Request.Scheme, Request.Host.ToString());
registerUrl = Uri.EscapeDataString(registerUrl);
return registerUrl;
}
[HttpGet("stores/{storeId}/pull-payments/edit/{pullPaymentId}")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> EditPullPayment(string storeId, string pullPaymentId)
{
using var ctx = _dbContextFactory.CreateContext();
Data.PullPaymentData pp = await ctx.PullPayments.FindAsync(pullPaymentId);
if (pp == null && !string.IsNullOrEmpty(pullPaymentId))
{
return NotFound();
}
var vm = new UpdatePullPaymentModel(pp);
return View(vm);
}
[HttpPost("stores/{storeId}/pull-payments/edit/{pullPaymentId}")]
[Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
public async Task<IActionResult> EditPullPayment(string storeId, string pullPaymentId, UpdatePullPaymentModel viewModel)
{
using var ctx = _dbContextFactory.CreateContext();
var pp = await ctx.PullPayments.FindAsync(pullPaymentId);
if (pp == null && !string.IsNullOrEmpty(pullPaymentId))
{
return NotFound();
}
if (!ModelState.IsValid)
{
return View(viewModel);
}
var blob = pp.GetBlob();
blob.Description = viewModel.Description ?? string.Empty;
blob.Name = viewModel.Name ?? string.Empty;
blob.View = new PullPaymentBlob.PullPaymentView
{
Title = viewModel.Name ?? string.Empty,
Description = viewModel.Description ?? string.Empty,
Email = null
};
pp.SetBlob(blob);
ctx.PullPayments.Update(pp);
await ctx.SaveChangesAsync();
TempData.SetStatusMessageModel(new StatusMessageModel
{
Message = "Pull payment updated successfully",
Severity = StatusMessageModel.StatusSeverity.Success
});
return RedirectToAction(nameof(UIStorePullPaymentsController.PullPayments), "UIStorePullPayments", new { storeId, pullPaymentId });
}
[AllowAnonymous]
[HttpPost("pull-payments/{pullPaymentId}/claim")]
public async Task<IActionResult> ClaimPullPayment(string pullPaymentId, ViewPullPaymentModel vm, CancellationToken cancellationToken)
2020-06-24 03:34:09 +02:00
{
await using var ctx = _dbContextFactory.CreateContext();
2020-06-24 03:34:09 +02:00
var pp = await ctx.PullPayments.FindAsync(pullPaymentId);
if (pp is null)
{
ModelState.AddModelError(nameof(pullPaymentId), "This pull payment does not exists");
}
2021-12-31 08:59:02 +01:00
if (string.IsNullOrEmpty(vm.Destination))
2020-06-24 03:34:09 +02:00
{
ModelState.AddModelError(nameof(vm.Destination), "Please provide a destination");
return await ViewPullPayment(pullPaymentId);
}
var ppBlob = pp.GetBlob();
var supported = ppBlob.SupportedPaymentMethods;
PayoutMethodId payoutMethodId = null;
IClaimDestination destination = null;
IPayoutHandler payoutHandler = null;
string error = null;
if (string.IsNullOrEmpty(vm.SelectedPayoutMethod))
{
foreach (var pmId in supported)
{
var handler = _payoutHandlers.TryGet(pmId);
(IClaimDestination dst, string err) = handler == null
? (null, "No payment handler found for this payment method")
: await handler.ParseAndValidateClaimDestination(vm.Destination, ppBlob, cancellationToken);
error = err;
if (dst is not null && err is null)
{
payoutMethodId = pmId;
destination = dst;
payoutHandler = handler;
break;
}
}
}
else
{
payoutMethodId = supported.FirstOrDefault(id => vm.SelectedPayoutMethod == id.ToString());
payoutHandler = payoutMethodId is null ? null : _payoutHandlers.TryGet(payoutMethodId);
if (payoutHandler is not null)
{
(destination, error) = await payoutHandler.ParseAndValidateClaimDestination(vm.Destination, ppBlob, cancellationToken);
}
}
if (destination is null)
{
ModelState.AddModelError(nameof(vm.Destination), error ?? "Invalid destination or payment method");
return await ViewPullPayment(pullPaymentId);
}
var amtError = ClaimRequest.IsPayoutAmountOk(destination, vm.ClaimedAmount == 0 ? null : vm.ClaimedAmount, payoutHandler.Currency, ppBlob.Currency);
if (amtError.error is not null)
{
ModelState.AddModelError(nameof(vm.ClaimedAmount), amtError.error);
}
else if (amtError.amount is not null)
{
vm.ClaimedAmount = amtError.amount.Value;
2020-06-24 03:34:09 +02:00
}
if (!ModelState.IsValid)
{
return await ViewPullPayment(pullPaymentId);
}
var result = await _pullPaymentHostedService.Claim(new ClaimRequest
2020-06-24 03:34:09 +02:00
{
Destination = destination,
2020-06-24 03:34:09 +02:00
PullPaymentId = pullPaymentId,
Value = vm.ClaimedAmount,
PayoutMethodId = payoutMethodId,
StoreId = pp.StoreId
2020-06-24 03:34:09 +02:00
});
if (result.Result != ClaimRequest.ClaimResult.Ok)
{
ModelState.AddModelError(
result.Result == ClaimRequest.ClaimResult.AmountTooLow ? nameof(vm.ClaimedAmount) : string.Empty,
ClaimRequest.GetErrorMessage(result.Result));
2020-06-24 03:34:09 +02:00
return await ViewPullPayment(pullPaymentId);
}
TempData.SetStatusMessageModel(new StatusMessageModel
2020-06-24 03:34:09 +02:00
{
Message = $"Your claim request of {_displayFormatter.Currency(vm.ClaimedAmount, ppBlob.Currency, DisplayFormatter.CurrencyFormat.Symbol)} to {vm.Destination} has been submitted and is awaiting {(result.PayoutData.State == PayoutState.AwaitingApproval ? "approval" : "payment")}.",
Severity = StatusMessageModel.StatusSeverity.Success
});
return RedirectToAction(nameof(ViewPullPayment), new { pullPaymentId });
2020-06-24 03:34:09 +02:00
}
}
}