Address feedback from code review

Thanks @kukks
This commit is contained in:
Dennis Reimann 2021-12-20 15:15:32 +01:00 committed by Andrew Camilleri
parent 3a59e2a5c4
commit 8e5a9251d6
6 changed files with 96 additions and 109 deletions

View file

@ -27,16 +27,17 @@ namespace BTCPayServer.Controllers
[HttpGet("{appId}/settings/crowdfund")]
public IActionResult UpdateCrowdfund(string appId)
{
if (CurrentApp == null)
var app = GetCurrentApp();
if (app == null)
return NotFound();
var settings = CurrentApp.GetSettings<CrowdfundSettings>();
var settings = app.GetSettings<CrowdfundSettings>();
var vm = new UpdateCrowdfundViewModel
{
Title = settings.Title,
StoreId = CurrentApp.StoreDataId,
StoreName = CurrentApp.StoreData?.StoreName,
AppName = CurrentApp.Name,
StoreId = app.StoreDataId,
StoreName = app.StoreData?.StoreName,
AppName = app.Name,
Enabled = settings.Enabled,
EnforceTargetAmount = settings.EnforceTargetAmount,
StartDate = settings.StartDate,
@ -56,9 +57,9 @@ namespace BTCPayServer.Controllers
AnimationsEnabled = settings.AnimationsEnabled,
ResetEveryAmount = settings.ResetEveryAmount,
ResetEvery = Enum.GetName(typeof(CrowdfundResetEvery), settings.ResetEvery),
UseAllStoreInvoices = CurrentApp.TagAllInvoices,
UseAllStoreInvoices = app.TagAllInvoices,
AppId = appId,
SearchTerm = CurrentApp.TagAllInvoices ? $"storeid:{CurrentApp.StoreDataId}" : $"orderid:{AppService.GetCrowdfundOrderId(appId)}",
SearchTerm = app.TagAllInvoices ? $"storeid:{app.StoreDataId}" : $"orderid:{AppService.GetCrowdfundOrderId(appId)}",
DisplayPerksRanking = settings.DisplayPerksRanking,
DisplayPerksValue = settings.DisplayPerksValue,
SortPerksByPopularity = settings.SortPerksByPopularity,
@ -71,10 +72,11 @@ namespace BTCPayServer.Controllers
[HttpPost("{appId}/settings/crowdfund")]
public async Task<IActionResult> UpdateCrowdfund(string appId, UpdateCrowdfundViewModel vm, string command)
{
if (CurrentApp == null)
var app = GetCurrentApp();
if (app == null)
return NotFound();
vm.TargetCurrency = await GetStoreDefaultCurrentIfEmpty(CurrentApp.StoreDataId, vm.TargetCurrency);
vm.TargetCurrency = await GetStoreDefaultCurrentIfEmpty(app.StoreDataId, vm.TargetCurrency);
if (_currencies.GetCurrencyData(vm.TargetCurrency, false) == null)
ModelState.AddModelError(nameof(vm.TargetCurrency), "Invalid currency");
@ -125,7 +127,7 @@ namespace BTCPayServer.Controllers
return View(vm);
}
CurrentApp.Name = vm.AppName;
app.Name = vm.AppName;
var newSettings = new CrowdfundSettings
{
Title = vm.Title,
@ -155,15 +157,15 @@ namespace BTCPayServer.Controllers
AnimationColors = parsedAnimationColors
};
CurrentApp.TagAllInvoices = vm.UseAllStoreInvoices;
CurrentApp.SetSettings(newSettings);
app.TagAllInvoices = vm.UseAllStoreInvoices;
app.SetSettings(newSettings);
await _appService.UpdateOrCreateApp(CurrentApp);
await _appService.UpdateOrCreateApp(app);
_eventAggregator.Publish(new AppUpdated()
{
AppId = appId,
StoreId = CurrentApp.StoreDataId,
StoreId = app.StoreDataId,
Settings = newSettings
});
TempData[WellKnownTempData.SuccessMessage] = "App updated";

View file

@ -89,18 +89,19 @@ namespace BTCPayServer.Controllers
[HttpGet("{appId}/settings/pos")]
public IActionResult UpdatePointOfSale(string appId)
{
if (CurrentApp == null)
var app = GetCurrentApp();
if (app == null)
return NotFound();
var settings = CurrentApp.GetSettings<PointOfSaleSettings>();
var settings = app.GetSettings<PointOfSaleSettings>();
settings.DefaultView = settings.EnableShoppingCart ? PosViewType.Cart : settings.DefaultView;
settings.EnableShoppingCart = false;
var vm = new UpdatePointOfSaleViewModel
{
Id = appId,
StoreId = CurrentApp.StoreDataId,
StoreName = CurrentApp.StoreData?.StoreName,
AppName = CurrentApp.Name,
StoreId = app.StoreDataId,
StoreName = app.StoreData?.StoreName,
AppName = app.Name,
Title = settings.Title,
DefaultView = settings.DefaultView,
ShowCustomAmount = settings.ShowCustomAmount,
@ -117,7 +118,7 @@ namespace BTCPayServer.Controllers
Description = settings.Description,
NotificationUrl = settings.NotificationUrl,
RedirectUrl = settings.RedirectUrl,
SearchTerm = $"storeid:{CurrentApp.StoreDataId}",
SearchTerm = $"storeid:{app.StoreDataId}",
RedirectAutomatically = settings.RedirectAutomatically.HasValue ? settings.RedirectAutomatically.Value ? "true" : "false" : "",
RequiresRefundEmail = settings.RequiresRefundEmail
};
@ -161,14 +162,15 @@ namespace BTCPayServer.Controllers
[HttpPost("{appId}/settings/pos")]
public async Task<IActionResult> UpdatePointOfSale(string appId, UpdatePointOfSaleViewModel vm)
{
if (CurrentApp == null)
{
var app = GetCurrentApp();
if (app == null)
return NotFound();
if (!ModelState.IsValid)
return View(vm);
vm.Currency = await GetStoreDefaultCurrentIfEmpty(CurrentApp.StoreDataId, vm.Currency);
vm.Currency = await GetStoreDefaultCurrentIfEmpty(app.StoreDataId, vm.Currency);
if (_currencies.GetCurrencyData(vm.Currency, false) == null)
ModelState.AddModelError(nameof(vm.Currency), "Invalid currency");
try
@ -184,8 +186,8 @@ namespace BTCPayServer.Controllers
return View(vm);
}
CurrentApp.Name = vm.AppName;
CurrentApp.SetSettings(new PointOfSaleSettings
app.Name = vm.AppName;
app.SetSettings(new PointOfSaleSettings
{
Title = vm.Title,
DefaultView = vm.DefaultView,
@ -206,7 +208,7 @@ namespace BTCPayServer.Controllers
RedirectAutomatically = string.IsNullOrEmpty(vm.RedirectAutomatically) ? (bool?)null : bool.Parse(vm.RedirectAutomatically),
RequiresRefundEmail = vm.RequiresRefundEmail,
});
await _appService.UpdateOrCreateApp(CurrentApp);
await _appService.UpdateOrCreateApp(app);
TempData[WellKnownTempData.SuccessMessage] = "App updated";
return RedirectToAction(nameof(UpdatePointOfSale), new { appId });
}

View file

@ -49,7 +49,8 @@ namespace BTCPayServer.Controllers
string sortOrderColumn = null
)
{
var apps = await _appService.GetAllApps(GetUserId(), false, CurrentStore.Id);
var store = GetCurrentStore();
var apps = await _appService.GetAllApps(GetUserId(), false, store.Id);
if (sortOrder != null && sortOrderColumn != null)
{
@ -91,14 +92,15 @@ namespace BTCPayServer.Controllers
{
return View(new CreateAppViewModel
{
StoreId = CurrentStore.Id
StoreId = GetCurrentStore().Id
});
}
[HttpPost("/stores/{storeId}/apps/create")]
public async Task<IActionResult> CreateApp(string storeId, CreateAppViewModel vm)
{
vm.StoreId = CurrentStore.Id;
var store = GetCurrentStore();
vm.StoreId = store.Id;
if (!Enum.TryParse(vm.SelectedAppType, out AppType appType))
ModelState.AddModelError(nameof(vm.SelectedAppType), "Invalid App Type");
@ -110,7 +112,7 @@ namespace BTCPayServer.Controllers
var appData = new AppData
{
StoreDataId = CurrentStore.Id,
StoreDataId = store.Id,
Name = vm.AppName,
AppType = appType.ToString()
};
@ -146,22 +148,24 @@ namespace BTCPayServer.Controllers
[HttpGet("{appId}/delete")]
public IActionResult DeleteApp(string appId)
{
if (CurrentApp == null)
var app = GetCurrentApp();
if (app == null)
return NotFound();
return View("Confirm", new ConfirmModel("Delete app", $"The app <strong>{CurrentApp.Name}</strong> and its settings will be permanently deleted. Are you sure?", "Delete"));
return View("Confirm", new ConfirmModel("Delete app", $"The app <strong>{app.Name}</strong> and its settings will be permanently deleted. Are you sure?", "Delete"));
}
[HttpPost("{appId}/delete")]
public async Task<IActionResult> DeleteAppPost(string appId)
{
if (CurrentApp == null)
var app = GetCurrentApp();
if (app == null)
return NotFound();
if (await _appService.DeleteApp(CurrentApp))
if (await _appService.DeleteApp(app))
TempData[WellKnownTempData.SuccessMessage] = "App deleted successfully.";
return RedirectToAction(nameof(ListApps), new { storeId = CurrentApp.StoreDataId });
return RedirectToAction(nameof(ListApps), new { storeId = app.StoreDataId });
}
async Task<string> GetStoreDefaultCurrentIfEmpty(string storeId, string currency)
@ -173,19 +177,10 @@ namespace BTCPayServer.Controllers
return currency.Trim().ToUpperInvariant();
}
private string GetUserId()
{
return _userManager.GetUserId(User);
}
private string GetUserId() => _userManager.GetUserId(User);
private StoreData CurrentStore
{
get => HttpContext.GetStoreData();
}
private StoreData GetCurrentStore() => HttpContext.GetStoreData();
private AppData CurrentApp
{
get => HttpContext.GetAppData();
}
private AppData GetCurrentApp() => HttpContext.GetAppData();
}
}

View file

@ -224,14 +224,16 @@ namespace BTCPayServer.Controllers
{
using var ctx = _dbContextFactory.CreateContext();
if (CurrentInvoice == null)
var invoice = GetCurrentInvoice();
if (invoice == null)
return NotFound();
if (!CanRefund(CurrentInvoice.GetInvoiceState()))
if (!CanRefund(invoice.GetInvoiceState()))
return NotFound();
var store = GetCurrentStore();
var paymentMethodId = PaymentMethodId.Parse(model.SelectedPaymentMethod);
var cdCurrency = _CurrencyNameTable.GetCurrencyData(CurrentInvoice.Currency, true);
var cdCurrency = _CurrencyNameTable.GetCurrencyData(invoice.Currency, true);
var paymentMethodDivisibility = _CurrencyNameTable.GetCurrencyData(paymentMethodId.CryptoCode, false)?.Divisibility ?? 8;
RateRules rules;
RateResult rateResult;
@ -241,7 +243,7 @@ namespace BTCPayServer.Controllers
case RefundSteps.SelectPaymentMethod:
model.RefundStep = RefundSteps.SelectRate;
model.Title = "What to refund?";
var pms = CurrentInvoice.GetPaymentMethods();
var pms = invoice.GetPaymentMethods();
var paymentMethod = pms.SingleOrDefault(method => method.GetId() == paymentMethodId);
//TODO: Make this clean
@ -257,9 +259,9 @@ namespace BTCPayServer.Controllers
model.CryptoAmountThen = cryptoPaid.RoundToSignificant(paymentMethodDivisibility);
model.RateThenText =
_CurrencyNameTable.DisplayFormatCurrency(model.CryptoAmountThen, paymentMethodId.CryptoCode);
rules = CurrentStore.GetStoreBlob().GetRateRules(_NetworkProvider);
rules = store.GetStoreBlob().GetRateRules(_NetworkProvider);
rateResult = await _RateProvider.FetchRate(
new CurrencyPair(paymentMethodId.CryptoCode, CurrentInvoice.Currency), rules,
new CurrencyPair(paymentMethodId.CryptoCode, invoice.Currency), rules,
cancellationToken);
//TODO: What if fetching rate failed?
if (rateResult.BidAsk is null)
@ -275,13 +277,14 @@ namespace BTCPayServer.Controllers
model.FiatAmount = paidCurrency;
}
model.FiatText = _CurrencyNameTable.DisplayFormatCurrency(model.FiatAmount, CurrentInvoice.Currency);
model.FiatText = _CurrencyNameTable.DisplayFormatCurrency(model.FiatAmount, invoice.Currency);
return View(model);
case RefundSteps.SelectRate:
createPullPayment = new CreatePullPayment
{
Name = $"Refund {CurrentInvoice.Id}", PaymentMethodIds = new[] { paymentMethodId },
StoreId = CurrentInvoice.StoreId
Name = $"Refund {invoice.Id}", PaymentMethodIds = new[] { paymentMethodId },
StoreId = invoice.StoreId
};
switch (model.SelectedRefundOption)
{
@ -294,12 +297,12 @@ namespace BTCPayServer.Controllers
createPullPayment.Amount = model.CryptoAmountNow;
break;
case "Fiat":
createPullPayment.Currency = CurrentInvoice.Currency;
createPullPayment.Currency = invoice.Currency;
createPullPayment.Amount = model.FiatAmount;
break;
case "Custom":
model.Title = "How much to refund?";
model.CustomCurrency = CurrentInvoice.Currency;
model.CustomCurrency = invoice.Currency;
model.CustomAmount = model.FiatAmount;
model.RefundStep = RefundSteps.SelectCustomAmount;
return View(model);
@ -325,7 +328,8 @@ namespace BTCPayServer.Controllers
{
return View(model);
}
rules = CurrentStore.GetStoreBlob().GetRateRules(_NetworkProvider);
rules = store.GetStoreBlob().GetRateRules(_NetworkProvider);
rateResult = await _RateProvider.FetchRate(
new CurrencyPair(paymentMethodId.CryptoCode, model.CustomCurrency), rules,
cancellationToken);
@ -339,8 +343,8 @@ namespace BTCPayServer.Controllers
createPullPayment = new CreatePullPayment
{
Name = $"Refund {CurrentInvoice.Id}", PaymentMethodIds = new[] { paymentMethodId },
StoreId = CurrentInvoice.StoreId,
Name = $"Refund {invoice.Id}", PaymentMethodIds = new[] { paymentMethodId },
StoreId = invoice.StoreId,
Currency = model.CustomCurrency,
Amount = model.CustomAmount
};
@ -355,10 +359,10 @@ namespace BTCPayServer.Controllers
Html = "Refund successfully created!<br />Share the link to this page with a customer.<br />The customer needs to enter their address and claim the refund.<br />Once a customer claims the refund, you will get a notification and would need to approve and initiate it from your Store > Payouts.",
Severity = StatusMessageModel.StatusSeverity.Success
});
(await ctx.Invoices.FindAsync(new[] { CurrentInvoice.Id }, cancellationToken)).CurrentRefundId = ppId;
(await ctx.Invoices.FindAsync(new[] { invoice.Id }, cancellationToken)).CurrentRefundId = ppId;
ctx.Refunds.Add(new RefundData()
{
InvoiceDataId = CurrentInvoice.Id,
InvoiceDataId = invoice.Id,
PullPaymentDataId = ppId
});
await ctx.SaveChangesAsync(cancellationToken);
@ -976,20 +980,11 @@ namespace BTCPayServer.Controllers
public string? StatusString { get; set; }
}
private StoreData CurrentStore
{
get => HttpContext.GetStoreData();
}
private StoreData GetCurrentStore() => HttpContext.GetStoreData();
private InvoiceEntity CurrentInvoice
{
get => HttpContext.GetInvoiceData();
}
private InvoiceEntity GetCurrentInvoice() => HttpContext.GetInvoiceData();
private string GetUserId()
{
return _UserManager.GetUserId(User);
}
private string GetUserId() => _UserManager.GetUserId(User);
public class PosDataParser
{

View file

@ -62,11 +62,12 @@ namespace BTCPayServer.Controllers
{
model = this.ParseListQuery(model ?? new ListPaymentRequestsViewModel());
var store = GetCurrentStore();
var includeArchived = new SearchString(model.SearchTerm).GetFilterBool("includearchived") == true;
var result = await _PaymentRequestRepository.FindPaymentRequests(new PaymentRequestQuery
{
UserId = GetUserId(),
StoreId = CurrentStore.Id,
StoreId = store.Id,
Skip = model.Skip,
Count = model.Count,
IncludeArchived = includeArchived
@ -80,14 +81,16 @@ namespace BTCPayServer.Controllers
[HttpGet("/stores/{storeId}/payment-requests/edit/{payReqId?}")]
public IActionResult EditPaymentRequest(string storeId, string payReqId)
{
if (CurrentPaymentRequest == null && !string.IsNullOrEmpty(payReqId))
var store = GetCurrentStore();
var paymentRequest = GetCurrentPaymentRequest();
if (paymentRequest == null && !string.IsNullOrEmpty(payReqId))
{
return NotFound();
}
return View(nameof(EditPaymentRequest), new UpdatePaymentRequestViewModel(CurrentPaymentRequest)
return View(nameof(EditPaymentRequest), new UpdatePaymentRequestViewModel(paymentRequest)
{
StoreId = CurrentStore.Id
StoreId = store.Id
});
}
@ -98,12 +101,14 @@ namespace BTCPayServer.Controllers
_Currencies.GetCurrencyData(viewModel.Currency, false) == null)
ModelState.AddModelError(nameof(viewModel.Currency), "Invalid currency");
if (CurrentPaymentRequest == null && !string.IsNullOrEmpty(payReqId))
var store = GetCurrentStore();
var paymentRequest = GetCurrentPaymentRequest();
if (paymentRequest == null && !string.IsNullOrEmpty(payReqId))
{
return NotFound();
}
if (CurrentPaymentRequest?.Archived is true && viewModel.Archived)
if (paymentRequest?.Archived is true && viewModel.Archived)
{
ModelState.AddModelError(string.Empty, "You cannot edit an archived payment request.");
}
@ -113,7 +118,7 @@ namespace BTCPayServer.Controllers
return View(nameof(EditPaymentRequest), viewModel);
}
var data = CurrentPaymentRequest ?? new PaymentRequestData();
var data = paymentRequest ?? new PaymentRequestData();
data.StoreDataId = viewModel.StoreId;
data.Archived = viewModel.Archived;
@ -138,7 +143,7 @@ namespace BTCPayServer.Controllers
_EventAggregator.Publish(new PaymentRequestUpdated { Data = data, PaymentRequestId = data.Id, });
TempData[WellKnownTempData.SuccessMessage] = "Saved";
return RedirectToAction(nameof(EditPaymentRequest), new { storeId = CurrentStore.Id, payReqId = data.Id });
return RedirectToAction(nameof(EditPaymentRequest), new { storeId = store.Id, payReqId = data.Id });
}
[HttpGet("{payReqId}")]
@ -303,7 +308,8 @@ namespace BTCPayServer.Controllers
[HttpGet("{payReqId}/clone")]
public IActionResult ClonePaymentRequest(string payReqId)
{
var result = EditPaymentRequest(CurrentStore.Id, payReqId);
var store = GetCurrentStore();
var result = EditPaymentRequest(store.Id, payReqId);
if (result is ViewResult viewResult)
{
var model = (UpdatePaymentRequestViewModel)viewResult.Model;
@ -320,7 +326,8 @@ namespace BTCPayServer.Controllers
[HttpGet("{payReqId}/archive")]
public async Task<IActionResult> TogglePaymentRequestArchival(string payReqId)
{
var result = EditPaymentRequest(CurrentStore.Id, payReqId);
var store = GetCurrentStore();
var result = EditPaymentRequest(store.Id, payReqId);
if (result is ViewResult viewResult)
{
var model = (UpdatePaymentRequestViewModel)viewResult.Model;
@ -335,19 +342,10 @@ namespace BTCPayServer.Controllers
return NotFound();
}
private string GetUserId()
{
return _UserManager.GetUserId(User);
}
private string GetUserId() => _UserManager.GetUserId(User);
private StoreData CurrentStore
{
get => HttpContext.GetStoreData();
}
private StoreData GetCurrentStore() => HttpContext.GetStoreData();
private PaymentRequestData CurrentPaymentRequest
{
get => HttpContext.GetPaymentRequestData();
}
private PaymentRequestData GetCurrentPaymentRequest() => HttpContext.GetPaymentRequestData();
}
}

View file

@ -368,8 +368,9 @@ namespace BTCPayServer.Controllers
var network = NetworkProvider.GetNetwork<BTCPayNetwork>(walletId?.CryptoCode);
if (network == null)
return NotFound();
var store = GetCurrentStore();
var address = _walletReceiveService.Get(walletId)?.Address;
var allowedPayjoin = paymentMethod.IsHotWallet && CurrentStore.GetStoreBlob().PayJoinEnabled;
var allowedPayjoin = paymentMethod.IsHotWallet && store.GetStoreBlob().PayJoinEnabled;
var bip21 = network.GenerateBIP21(address?.ToString(), null);
if (allowedPayjoin)
{
@ -1030,14 +1031,9 @@ namespace BTCPayServer.Controllers
return RedirectToAction();
}
private StoreData CurrentStore
{
get => HttpContext.GetStoreData();
}
internal DerivationSchemeSettings GetDerivationSchemeSettings(WalletId walletId)
{
return CurrentStore.GetDerivationSchemeSettings(NetworkProvider, walletId.CryptoCode);
return GetCurrentStore().GetDerivationSchemeSettings(NetworkProvider, walletId.CryptoCode);
}
private static async Task<IMoney> GetBalanceAsMoney(BTCPayWallet wallet, DerivationStrategyBase derivationStrategy)
@ -1065,11 +1061,6 @@ namespace BTCPayServer.Controllers
return "--";
}
}
private string GetUserId()
{
return _userManager.GetUserId(User);
}
[HttpPost("{walletId}/actions")]
public async Task<IActionResult> WalletActions(
@ -1125,6 +1116,10 @@ namespace BTCPayServer.Controllers
: Url.Content(network.LightningImagePath);
return Request.GetRelativePathOrAbsolute(res);
}
private string GetUserId() => _userManager.GetUserId(User);
private StoreData GetCurrentStore() => HttpContext.GetStoreData();
}
public class WalletReceiveViewModel