Implemented cart hydration and refactored paynow flow
continuous-integration/drone/pr Build is passing
continuous-integration/drone/pr Build is passing
This commit is contained in:
@@ -1,13 +1,10 @@
|
||||
using LiteCharms.Features.Api.Configuration;
|
||||
using LiteCharms.Features.Hasher;
|
||||
using LiteCharms.Features.MidrandBooks.AuthorBooks;
|
||||
using LiteCharms.Features.MidrandBooks.Customers;
|
||||
using LiteCharms.Features.MidrandBooks.Customers.Models;
|
||||
using LiteCharms.Features.MidrandBooks.Orders;
|
||||
using LiteCharms.Features.MidrandBooks.Orders.Models;
|
||||
using LiteCharms.Features.MidrandBooks.Payments;
|
||||
using LiteCharms.Features.MidrandBooks.Payments.Models;
|
||||
using LiteCharms.Features.MidrandBooks.Products;
|
||||
|
||||
namespace MidrandBookshop.Components.Pages;
|
||||
|
||||
@@ -19,14 +16,13 @@ public partial class Checkout()
|
||||
[Inject] public BooksService BooksService { get; set; } = default!;
|
||||
[Inject] public CartService CartService { get; set; } = default!;
|
||||
[Inject] public PayfastService PayfastService { get; set; } = default!;
|
||||
[Inject] public CustomerService CustomerService { get; set; } = default!;
|
||||
[Inject] public ProductService ProductService { get; set; } = default!;
|
||||
[Inject] public IOptions<PayfastSettings> PayfastOptions { get; set; } = default!;
|
||||
[Inject] private AuthenticationStateProvider AuthStateProvider { get; set; } = default!;
|
||||
[Inject] public IJSRuntime JSRuntime { get; set; } = default!;
|
||||
[Inject] private HydrationService HydrationService { get; set; } = default!;
|
||||
[Inject] private CancellationToken CancellationToken { get; set; } = default!;
|
||||
|
||||
private Cart ShoppingCart => CartService.ShoppingCart;
|
||||
private AuthenticationState? AuthState { get; set; }
|
||||
private ClaimsPrincipal? User { get; set; }
|
||||
private bool IsProcessing { get; set; }
|
||||
|
||||
@@ -37,18 +33,31 @@ public partial class Checkout()
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
AuthState = await AuthStateProvider.GetAuthenticationStateAsync();
|
||||
User = AuthState!.User;
|
||||
var authState = await AuthStateProvider.GetAuthenticationStateAsync();
|
||||
User = authState!.User;
|
||||
|
||||
Navigation.LocationChanged += OnLocationChanged;
|
||||
CartService.OnCartChanged += CartService_OnCartChanged;
|
||||
|
||||
await CartService.LoadCartFromStorageAsync();
|
||||
}
|
||||
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (firstRender == false && HydrationService.CartHydrated == false)
|
||||
{
|
||||
await HydrationService.EnsureCustomerExistsAsync(CancellationToken);
|
||||
await HydrationService.RehydrateCartFromPendingOrderAsync(CancellationToken);
|
||||
|
||||
CartService.NotifyStateChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private async void CartService_OnCartChanged() => await InvokeAsync(StateHasChanged);
|
||||
|
||||
private void OnLocationChanged(object? sender, LocationChangedEventArgs e) => StateHasChanged();
|
||||
|
||||
private async void ChangeQuantity(CartItem item, int delta)
|
||||
private async Task ChangeQuantity(CartItem item, int delta)
|
||||
{
|
||||
var peekQuantity = item.Quantity + delta;
|
||||
|
||||
@@ -59,7 +68,7 @@ public partial class Checkout()
|
||||
await CartService.SaveCartToStorageAsync();
|
||||
}
|
||||
|
||||
private async void RemoveFromCart(CartItem item)
|
||||
private async Task RemoveFromCart(CartItem item)
|
||||
{
|
||||
CartService.RemoveOneItem(item.Price!.Id);
|
||||
|
||||
@@ -72,37 +81,31 @@ public partial class Checkout()
|
||||
|
||||
try
|
||||
{
|
||||
// 1. Instantly disable the button to prevent duplicate click submissions
|
||||
IsProcessing = true;
|
||||
StateHasChanged(); // Force Blazor Server to push the disabled state over SignalR immediately
|
||||
|
||||
var customerEmail = User?.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)!.Value!;
|
||||
StateHasChanged();
|
||||
|
||||
// 2. Create customer if ShoppingCart.CustomerId is null
|
||||
if (ShoppingCart.CustomerId == null)
|
||||
Result<long> orderResult;
|
||||
|
||||
var customerId = (long)ShoppingCart.CustomerId!;
|
||||
|
||||
if (!ShoppingCart.OrderId.HasValue)
|
||||
{
|
||||
var existingCustomer = await CustomerService.GetCustomerAsync(customerEmail);
|
||||
CreateOrder request = new(ShoppingCart.TotalAmount, null);
|
||||
|
||||
if (existingCustomer.IsSuccess)
|
||||
ShoppingCart.CustomerId = existingCustomer.Value.Id;
|
||||
|
||||
if (existingCustomer.IsFailed)
|
||||
{
|
||||
var customerCreate = await CustomerService.CreateCustomerAsync(new CreateCustomer { Email = customerEmail });
|
||||
|
||||
if (customerCreate.IsSuccess)
|
||||
ShoppingCart.CustomerId = customerCreate.Value;
|
||||
}
|
||||
orderResult = await OrderService.CreateOrderAsync(customerId, request, CancellationToken);
|
||||
ShoppingCart.OrderId = orderResult.Value;
|
||||
}
|
||||
|
||||
// 3. Create order using shopping cart and assign the ShoppingCart.OrderId
|
||||
|
||||
var order = await OrderService.CreateOrderAsync(ShoppingCart.CustomerId!.Value, new CreateOrder(ShoppingCart.TotalAmount, null));
|
||||
List<CreateOrderItem> orderItems = [];
|
||||
|
||||
var orderId = (long)ShoppingCart.OrderId;
|
||||
|
||||
await OrderService.ClearOrderItemsAsync(orderId, CancellationToken);
|
||||
|
||||
foreach (var item in ShoppingCart.Items)
|
||||
{
|
||||
var bookRequest = await BooksService.GetBookByProductIdAsync(item.Price!.Id);
|
||||
var bookRequest = await BooksService.GetBookByProductIdAsync(item.Price!.Id, CancellationToken);
|
||||
|
||||
if (bookRequest.IsSuccess)
|
||||
{
|
||||
@@ -111,22 +114,21 @@ public partial class Checkout()
|
||||
}
|
||||
}
|
||||
|
||||
var paymentGen = await PaymentService.CreatePaymentAsync(ShoppingCart.TotalAmount, order.Value, HashService.HashEncodeLongId(order.Value).Value);
|
||||
var merchantPaymentId = HashService.HashEncodeLongId(order.Value).Value;
|
||||
var orderHash = HashService.HashEncodeLongId(orderId).Value;
|
||||
var paymentGen = await PaymentService.CreatePaymentAsync(ShoppingCart.TotalAmount, orderId, orderHash, CancellationToken);
|
||||
|
||||
await PaymentService.WriteLedgerEntryAsync(new CreateLedgerEntry
|
||||
CreateLedgerEntry ledgerRequest = new()
|
||||
{
|
||||
OrderId = order.Value,
|
||||
CustomerId = ShoppingCart.CustomerId.Value,
|
||||
PaymentGatewayId = 1,
|
||||
PaymentGatewayReference = merchantPaymentId,
|
||||
OrderId = orderId,
|
||||
CustomerId = customerId,
|
||||
PaymentGatewayId = 1, // TODO: lookup value to match user selection
|
||||
PaymentGatewayReference = orderHash,
|
||||
PaymentId = paymentGen.Value,
|
||||
Status = LiteCharms.Features.LedgerStatuses.Sent,
|
||||
});
|
||||
};
|
||||
await PaymentService.WriteLedgerEntryAsync(ledgerRequest, CancellationToken);
|
||||
|
||||
var addItemsResult = await OrderService.AddItemsToOrderAsync(order.Value, [.. orderItems]);
|
||||
|
||||
// 4. Generate the signed Payfast form payload using your backend service
|
||||
var addItemsResult = await OrderService.AddItemsToOrderAsync(orderId, [.. orderItems], CancellationToken);
|
||||
var hostAddress = Navigation.BaseUri.TrimEnd('/');
|
||||
|
||||
CheckoutPayload = new Dictionary<string, string>
|
||||
@@ -136,8 +138,8 @@ public partial class Checkout()
|
||||
{ "return_url", $"{hostAddress}/payment-success" },
|
||||
{ "cancel_url", $"{hostAddress}/payment-failed" },
|
||||
{ "notify_url", "https://api.uat.midrandbooks.co.za/v1/payments/payfast/confirm" },
|
||||
{ "email_address", customerEmail },
|
||||
{ "m_payment_id", merchantPaymentId },
|
||||
{ "email_address", User?.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)!.Value! },
|
||||
{ "m_payment_id", orderHash },
|
||||
{ "amount", ShoppingCart.TotalAmount.ToString("F2", CultureInfo.InvariantCulture) },
|
||||
{ "item_name", "MidrandBooks Sale" },
|
||||
};
|
||||
@@ -147,7 +149,6 @@ public partial class Checkout()
|
||||
|
||||
StateHasChanged();
|
||||
|
||||
// 6. Execute programmatic submit directly into the sandbox
|
||||
await JSRuntime.InvokeVoidAsync("eval", "document.getElementById('payfastForm').submit();");
|
||||
}
|
||||
catch
|
||||
|
||||
Reference in New Issue
Block a user