Refactoring logic for referencing server model in js script

Will keep removing unnecessary boilerplate "assign variable" code and try to streamline it as much as possible
This commit is contained in:
lepipele
2017-10-20 22:06:42 -05:00
parent 0f603ffb0a
commit 2beae1dcd3
5 changed files with 83 additions and 166 deletions

View File

@@ -133,28 +133,30 @@ namespace BTCPayServer.Controllers
var model = new PaymentModel()
{
ServerUrl = HttpContext.Request.GetAbsoluteRoot(),
serverUrl = HttpContext.Request.GetAbsoluteRoot(),
OrderId = invoice.OrderId,
InvoiceId = invoice.Id,
BTCAddress = invoice.DepositAddress.ToString(),
invoiceId = invoice.Id,
btcAddress = invoice.DepositAddress.ToString(),
BTCAmount = (invoice.GetTotalCryptoDue() - invoice.TxFee).ToString(),
BTCTotalDue = invoice.GetTotalCryptoDue().ToString(),
BTCDue = invoice.GetCryptoDue().ToString(),
CustomerEmail = invoice.RefundMail,
ExpirationSeconds = Math.Max(0, (int)(invoice.ExpirationTime - DateTimeOffset.UtcNow).TotalSeconds),
MaxTimeSeconds = (int)(invoice.ExpirationTime - invoice.InvoiceTime).TotalSeconds,
btcDue = invoice.GetCryptoDue().ToString(),
customerEmail = invoice.RefundMail,
expirationSeconds = Math.Max(0, (int)(invoice.ExpirationTime - DateTimeOffset.UtcNow).TotalSeconds),
maxTimeSeconds = (int)(invoice.ExpirationTime - invoice.InvoiceTime).TotalSeconds,
ItemDesc = invoice.ProductInformation.ItemDesc,
Rate = invoice.Rate.ToString("C", GetCurrencyProvider(invoice.ProductInformation.Currency)),
RedirectUrl = invoice.RedirectURL,
merchantRefLink = invoice.RedirectURL,
StoreName = store.StoreName,
TxFees = invoice.TxFee.ToString(),
InvoiceBitcoinUrl = dto.PaymentUrls.BIP72,
TxCount = invoice.GetTxCount(),
BTCPaid = invoice.GetTotalPaid().ToString(),
Status = invoice.Status
status = invoice.Status
};
var expiration = TimeSpan.FromSeconds((double)model.ExpirationSeconds);
var expiration = TimeSpan.FromSeconds((double)model.expirationSeconds);
model.TimeLeft = PrettyPrint(expiration);
return View(nameof(Checkout), model);
}

View File

@@ -5,106 +5,38 @@ using System.Threading.Tasks;
namespace BTCPayServer.Models.InvoicingModels
{
public class PaymentModel
{
public string InvoiceId
{
get; set;
}
public string ServerUrl
{
get; set;
}
// going with lowercase for property names to enable easy ToJson conversion
// down the road I can look into mapper who transforms capital into lower case
// because of different conventions between server and client side
public class PaymentModel
{
public string serverUrl { get; set; }
public string invoiceId { get; set; }
public string btcAddress { get; set; }
public string btcDue { get; set; }
public string customerEmail { get; set; }
public int expirationSeconds { get; set; }
public string status { get; set; }
public string merchantRefLink { get; set; }
public int maxTimeSeconds { get; set; }
// These properties are still not used in client side code
// so will stick with C# notation for now
public string StoreName { get; set; }
public string ItemDesc { get; set; }
public string TimeLeft { get; set; }
public string Rate { get; set; }
public string BTCAmount { get; set; }
public string TxFees { get; set; }
public string InvoiceBitcoinUrl { get; set; }
public string BTCTotalDue { get; set; }
public int TxCount { get; set; }
public string BTCPaid { get; set; }
public string StoreEmail { get; set; }
public string OrderId
{
get; set;
}
public string BTCAddress
{
get; set;
}
public string BTCDue
{
get; set;
}
public string CustomerEmail
{
get; set;
}
public int ExpirationSeconds
{
get; set;
}
public int MaxTimeSeconds
{
get; set;
}
public string TimeLeft
{
get; set;
}
public string RedirectUrl
{
get; set;
}
public string StoreName
{
get; set;
}
public string ItemDesc
{
get; set;
}
public string Rate
{
get; set;
}
public string BTCAmount
{
get; set;
}
public string TxFees
{
get; set;
}
public string InvoiceBitcoinUrl
{
get;
internal set;
}
public string BTCTotalDue
{
get;
set;
}
public int TxCount
{
get; set;
}
public string BTCPaid
{
get; set;
}
public string StoreEmail
{
get; set;
}
public string Status
{
get;
set;
}
}
}

View File

@@ -27,23 +27,7 @@
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>
<script type="text/javascript">
var serverUrl = "@Model.ServerUrl";
var invoiceId = "@Model.InvoiceId";
var btcAddress = "@Model.BTCAddress";
var btcDue = "@Model.BTCDue"; //must be a string
var customerEmail = "@Model.CustomerEmail"; // Place holder
var expirationTime = @Model.ExpirationSeconds; // Can be calculted server-side, or fixed
var isArchieved = false; // Preferably Bool
var status = "@Model.Status"; // Tx listener
var merchantRefLink = "@Model.RedirectUrl"; // Merchant link to redect the user
var merchantName = "@Model.StoreName";
var merchantDesc = "@Model.ItemDesc";
var btcRate = "@Model.Rate";
var btcAmount = "@Model.BTCAmount";
var itemAmount = 1;
var txFees = "@Model.TxFees";
var noMock = true;
var maxTime = @Model.MaxTimeSeconds;
var srvModel = @Html.Raw(JsonConvert.SerializeObject(Model));
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.7.1/clipboard.min.js"></script>
<script src="~/js/core.js" type="text/javascript" defer="defer"></script>
@@ -160,7 +144,7 @@
</div>
<div class="line-items__item line-items__item--total">
<div class="line-items__item__label" i18n="">Due </div>
<div class="line-items__item__value">@Model.BTCDue BTC</div>
<div class="line-items__item__value">@Model.btcDue BTC</div>
</div>
<!---->
</div>
@@ -379,7 +363,7 @@
<div class="manual-box__amount__label label" i18n="">Amount</div>
<!---->
<div class="manual-box__amount__value copy-cursor" ngxclipboard="">
<span>@Model.BTCDue</span> BTC
<span>@Model.btcDue</span> BTC
<div class="copied-label">
<span i18n="">Copied</span>
</div>
@@ -398,7 +382,7 @@
<div class="manual-box__address__wrapper__logo">
<img src="~/img/bitcoin-symbol.svg">
</div>
<div class="manual-box__address__wrapper__value">@Model.BTCAddress</div>
<div class="manual-box__address__wrapper__value">@Model.btcAddress</div>
</div>
<div class="copied-label" style="top: 5px;">
<span i18n="">Copied</span>
@@ -536,7 +520,7 @@
hours.
</div>
<div class="expired__text">
<span class="expired__text__bullet" i18n="">Invoice ID:</span> @Model.InvoiceId<br>
<span class="expired__text__bullet" i18n="">Invoice ID:</span> @Model.invoiceId<br>
<!---->
<span>
<span class="expired__text__bullet" i18n="">Order ID:</span> @Model.OrderId

View File

@@ -5,4 +5,5 @@
@using BTCPayServer.Models.InvoicingModels
@using BTCPayServer.Models.ManageViewModels
@using BTCPayServer.Models.StoreViewModels
@using Newtonsoft.Json;
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

@@ -33,12 +33,12 @@
var display = $(".timer-row__time-left"); // Timer container
// check if the Document expired
if (expirationTime > 0) {
if (srvModel.expirationSeconds > 0) {
progressStart(maxTime); // Progress bar
startTimer(expirationTime, display); // Timer
progressStart(srvModel.maxTimeSeconds); // Progress bar
startTimer(srvModel.expirationSeconds, display); // Timer
if (!validateEmail(customerEmail))
if (!validateEmail(srvModel.customerEmail))
emailForm(); // Email form Display
else
hideEmailForm();
@@ -48,9 +48,9 @@ if (expirationTime > 0) {
function hideEmailForm() {
$("[role=document]").removeClass("enter-purchaser-email");
$("#emailAddressView").removeClass("active");
$("placeholder-refundEmail").html(customerEmail);
$("placeholder-refundEmail").html(srvModel.customerEmail);
// to generate a QR-Code : $(<selector>).qrcode("1Dut19quHiJrXEwfmig4hB8RyLss5aTRTC");
$('.qr-codes').qrcode(btcAddress);
$('.qr-codes').qrcode(srvModel.btcAddress);
// Remove Email mode
$(".modal-dialog").removeClass("enter-purchaser-email");
@@ -67,14 +67,14 @@ function emailForm() {
if (validateEmail(emailAddress)) {
$("#emailAddressForm .input-wrapper bp-loading-button .action-button").addClass("loading");
// Push the email to a server, once the reception is confirmed move on
customerEmail = emailAddress;
srvModel.customerEmail = emailAddress;
var path = serverUrl + "/i/" + invoiceId + "/UpdateCustomer";
var path = srvModel.serverUrl + "/i/" + srvModel.invoiceId + "/UpdateCustomer";
$.ajax({
url: path,
type: "POST",
data: JSON.stringify({ Email: customerEmail }),
data: JSON.stringify({ Email: srvModel.customerEmail }),
contentType: "application/json; charset=utf-8"
}).done(function () {
hideEmailForm();
@@ -94,7 +94,7 @@ function emailForm() {
}
// Copy Tab Info
$("#copy .manual__step-two__instructions span").html("To complete your payment, please send " + btcDue + " BTC to the address below.");
$("#copy .manual__step-two__instructions span").html("To complete your payment, please send " + srvModel.btcDue + " BTC to the address below.");
/* =============== Even listeners =============== */
@@ -155,30 +155,28 @@ $("#copy-tab").click(function () {
// Should connect using webhook ?
// If notification received
var oldStatus = status;
updateState(status);
var oldStat = srvModel.status;
onDataCallback(srvModel.status);
function updateState(status) {
if (oldStatus != status)
{
oldStatus = status;
window.parent.postMessage({ "invoiceId": invoiceId, "status": status }, "*");
function onDataCallback(newStatus) {
if (oldStat != newStatus) {
oldStat = newStatus;
window.parent.postMessage({ "invoiceId": srvModel.invoiceId, "status": newStatus }, "*");
}
if (status == "complete" ||
status == "paidOver" ||
status == "confirmed" ||
status =="paid") {
if (newStatus == "complete" ||
newStatus == "paidOver" ||
newStatus == "confirmed" ||
newStatus == "paid") {
if ($(".modal-dialog").hasClass("expired")) {
$(".modal-dialog").removeClass("expired");
}
if (merchantRefLink != "") {
if (srvModel.merchantRefLink != "") {
$(".action-button").click(function () {
window.location.href = merchantRefLink;
window.location.href = srvModel.merchantRefLink;
});
}
else
{
else {
$(".action-button").hide();
}
@@ -192,7 +190,7 @@ function updateState(status) {
$("#paid").addClass("active");
}
if (status == "invalid") {
if (newStatus == "invalid") {
$(".timer-row").removeClass("expiring-soon");
$(".timer-row__message span").html("Invoice expired.");
$(".timer-row__spinner").html("");
@@ -203,17 +201,16 @@ function updateState(status) {
}
var watcher = setInterval(function () {
var path = serverUrl + "/i/" + invoiceId + "/status";
var path = srvModel.serverUrl + "/i/" + srvModel.invoiceId + "/status";
$.ajax({
url: path,
type: "GET"
}).done(function (data) {
status = data;
updateState(status);
})
.fail(function (jqXHR, textStatus, errorThrown) {
onDataCallback(status);
}).fail(function (jqXHR, textStatus, errorThrown) {
});
});
}, 2000);
$(".menu__item").click(function () {
@@ -255,11 +252,11 @@ function startTimer(duration, display) {
}
// Progress bar
function progressStart(maxTime) {
function progressStart(timerMax) {
var end = new Date(); // Setup Time Variable, should come from server
end.setSeconds(end.getSeconds() + expirationTime);
maxTime *= 1000; // Usually 15 minutes = 9000 second= 900000 ms
var timeoutVal = Math.floor(maxTime / 100); // Timeout calc
end.setSeconds(end.getSeconds() + srvModel.expirationSeconds);
timerMax *= 1000; // Usually 15 minutes = 9000 second= 900000 ms
var timeoutVal = Math.floor(timerMax / 100); // Timeout calc
animateUpdate(); //Launch it
function updateProgress(percentage) {
@@ -270,7 +267,7 @@ function progressStart(maxTime) {
var now = new Date();
var timeDiff = end.getTime() - now.getTime();
var perc = 100 - Math.round((timeDiff / maxTime) * 100);
var perc = 100 - Math.round((timeDiff / timerMax) * 100);
if (perc === 75 && (status == "paidPartial" || status == "new")) {
$(".timer-row").addClass("expiring-soon");
@@ -282,7 +279,7 @@ function progressStart(maxTime) {
setTimeout(animateUpdate, timeoutVal);
}
if (perc >= 100 && status == "expired") {
updateState(status);
onDataCallback(status);
}
}
}
@@ -313,4 +310,5 @@ $(document).keypress(
if (event.which === '13') {
event.preventDefault();
}
});
}
);