Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,10 @@ public async Task<PlaceOrderResult> Handle(PlaceOrderCommand command, Cancellati

var orderHeader = PrepareOrderHeader(paymentTransaction, paymentResult, details);

//the payment is recorded before the order is written: if saving the order fails, the transaction
//still shows what the gateway did and is no longer taken for an abandoned checkout
await UpdatePaymentTransaction(paymentTransaction, orderHeader, paymentResult);

result.PlacedOrder = await SaveOrderDetails(details, orderHeader, orderItems);
//from here on what was claimed belongs to the order
orderInserted = true;
Expand All @@ -250,12 +254,6 @@ public async Task<PlaceOrderResult> Handle(PlaceOrderCommand command, Cancellati

#endregion

#region Payment transaction

await UpdatePaymentTransaction(paymentTransaction, result.PlacedOrder, paymentResult);

#endregion

#region Events & notes

await _mediator.Send(new OrderNotificationCommand {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ public async Task<bool> Handle(CanDeletePaymentTransactionQuery request, Cancell
return false;

var lastChangedUtc = paymentTransaction.UpdatedOnUtc ?? paymentTransaction.CreatedOnUtc;
if (paymentTransaction.Temp && lastChangedUtc > DateTime.UtcNow - CheckoutInProgress)
//the payment is recorded just before the order is written, so a recent change may still be getting one
if (lastChangedUtc > DateTime.UtcNow - CheckoutInProgress)
return false;

//a deleted order is gone from the panel, and the placeholders reserving order numbers are deleted ones
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ public async Task<IPagedList<PaymentTransaction>> Handle(GetPaymentTransactionQu
if (request.CreatedToUtc.HasValue)
query = query.Where(rr => request.CreatedToUtc.Value >= rr.CreatedOnUtc);

if (!request.IncludeTemp)
query = query.Where(rr => !rr.Temp);

query = query.OrderByDescending(rr => rr.CreatedOnUtc);

return await _paymentTransactionRepository.PagedAsync(query, request.PageIndex, request.PageSize, cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ public class GetPaymentTransactionQuery : IRequest<IPagedList<PaymentTransaction
public int PageSize { get; set; } = int.MaxValue;
public DateTime? CreatedFromUtc { get; set; } = null;
public DateTime? CreatedToUtc { get; set; } = null;

/// <summary>False leaves out transactions of a checkout that never got a payment through: still in progress,
/// failed or abandoned.</summary>
public bool IncludeTemp { get; set; } = true;
}
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,19 @@ public async Task Handle_ExceptionBeforeOrderInsert_ReleasesClaim()
claims.Verify(x => x.Release(It.IsAny<CheckoutClaim>()), Times.Once);
}

[TestMethod]
public async Task Handle_ExceptionBeforeOrderInsert_PaymentAlreadyRecorded()
{
var (handler, _, orders, _, _, _, details, _) = ClaimSetup();
orders.Setup(x => x.InsertOrder(It.IsAny<Order>())).ThrowsAsync(new Exception("database down"));

await handler.Handle(ClaimCommand(details), CancellationToken.None);

//what the gateway did stays visible, and the transaction is not taken for an abandoned checkout
_paymentTransactions.Verify(x => x.UpdatePaymentTransaction(It.Is<PaymentTransaction>(t =>
t.Id == "tx" && !t.Temp && t.TransactionAmount == details.OrderTotal)), Times.Once);
}

[TestMethod]
public async Task Handle_ExceptionAfterOrderInsert_KeepsClaim()
{
Expand Down Expand Up @@ -367,7 +380,7 @@ protected override Task<PaymentTransaction> PreparePaymentTransaction(PlaceOrder
{
return Task.FromResult(new PaymentTransaction {
Id = "tx", StoreId = "store", OrderCode = "CODE1",
PaymentMethodSystemName = details.PaymentMethodSystemName
PaymentMethodSystemName = details.PaymentMethodSystemName, Temp = true
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,17 @@ public async Task CheckoutStillInProgress_CannotDelete()
Assert.IsFalse(await Handle(retried));
}

[TestMethod]
public async Task PaymentJustRecorded_CannotDelete()
{
//the payment is recorded just before the order is written
var recorded = Abandoned();
recorded.Temp = false;
recorded.UpdatedOnUtc = DateTime.UtcNow.AddSeconds(-1);

Assert.IsFalse(await Handle(recorded));
}

[TestMethod]
public async Task NullTransaction_Throws()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using Grand.Business.Checkout.Queries.Handlers.Orders;
using Grand.Business.Core.Queries.Checkout.Orders;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Payments;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Grand.Business.Checkout.Tests.Queries.Handlers.Orders;

[TestClass]
public class GetPaymentTransactionQueryHandlerTests
{
private GetPaymentTransactionQueryHandler _handler;
private MongoDBRepositoryTest<PaymentTransaction> _repository;

[TestInitialize]
public void Init()
{
_repository = new MongoDBRepositoryTest<PaymentTransaction>();
_handler = new GetPaymentTransactionQueryHandler(_repository);
}

[TestMethod]
public async Task Handle_WithoutTemp_LeavesOutAbandonedCheckouts()
{
await _repository.Collection.InsertOneAsync(new PaymentTransaction { OrderCode = "ORDER", Temp = false });
await _repository.Collection.InsertOneAsync(new PaymentTransaction { OrderCode = "ABANDONED", Temp = true });

var result = await _handler.Handle(new GetPaymentTransactionQuery { IncludeTemp = false }, CancellationToken.None);

Assert.AreEqual(1, result.Count);
Assert.AreEqual("ORDER", result[0].OrderCode);
}

[TestMethod]
public async Task Handle_ByDefault_IncludesAbandonedCheckouts()
{
await _repository.Collection.InsertOneAsync(new PaymentTransaction { OrderCode = "ORDER", Temp = false });
await _repository.Collection.InsertOneAsync(new PaymentTransaction { OrderCode = "ABANDONED", Temp = true });

var result = await _handler.Handle(new GetPaymentTransactionQuery(), CancellationToken.None);

Assert.AreEqual(2, result.Count);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -104,28 +104,60 @@ public void List_ReturnsViewWithPreparedModel()
public async Task List_Post_AdminScope_DoesNotForceStoreId()
{
_scopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);
_paymentTransactionServiceMock
.Setup(s => s.SearchPaymentTransactions(null, null, null, null, 0, int.MaxValue, null, null))
.ReturnsAsync(new PagedList<PaymentTransaction>(new List<PaymentTransaction>(), 0, 10));
SetupSearch();

var model = new PaymentTransactionListModel();
await _controller.List(new DataSourceRequest { Page = 1, PageSize = int.MaxValue }, model);

Assert.IsNull(model.StoreId);
}

private void SetupSearch()
{
_mediatorMock
.Setup(m => m.Send(It.IsAny<GetPaymentTransactionQuery>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new PagedList<PaymentTransaction>(new List<PaymentTransaction>(), 0, 10));
}

[TestMethod]
public async Task List_Post_LeavesOutAbandonedUnlessAsked()
{
SetupSearch();
var command = new DataSourceRequest { Page = 1, PageSize = int.MaxValue };

await _controller.List(command, new PaymentTransactionListModel());
await _controller.List(command, new PaymentTransactionListModel { ShowAbandoned = true });

_mediatorMock.Verify(m => m.Send(It.Is<GetPaymentTransactionQuery>(q => !q.IncludeTemp), It.IsAny<CancellationToken>()), Times.Once);
_mediatorMock.Verify(m => m.Send(It.Is<GetPaymentTransactionQuery>(q => q.IncludeTemp), It.IsAny<CancellationToken>()), Times.Once);
}

[TestMethod]
public async Task List_Post_ByOrderNumber_IncludesAbandoned()
{
SetupSearch();
var orderGuid = Guid.NewGuid();
_orderServiceMock.Setup(s => s.GetOrderByNumber(1001)).ReturnsAsync(new Order { OrderGuid = orderGuid });

await _controller.List(new DataSourceRequest { Page = 1, PageSize = int.MaxValue },
new PaymentTransactionListModel { OrderNumber = "1001" });

_mediatorMock.Verify(m => m.Send(It.Is<GetPaymentTransactionQuery>(q => q.OrderGuid == orderGuid && q.IncludeTemp),
It.IsAny<CancellationToken>()), Times.Once);
}

[TestMethod]
public async Task List_Post_StoreScope_ForcesStoreId()
{
_scopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");
_paymentTransactionServiceMock
.Setup(s => s.SearchPaymentTransactions(null, "store-1", It.IsAny<string>(), null, 0, int.MaxValue, null, null))
.ReturnsAsync(new PagedList<PaymentTransaction>(new List<PaymentTransaction>(), 0, 10));
SetupSearch();

var model = new PaymentTransactionListModel { StoreId = "some-other-store" };
await _controller.List(new DataSourceRequest { Page = 1, PageSize = int.MaxValue }, model);

Assert.AreEqual("store-1", model.StoreId);
_mediatorMock.Verify(m => m.Send(It.Is<GetPaymentTransactionQuery>(q => q.StoreId == "store-1"),
It.IsAny<CancellationToken>()), Times.Once);
}

[TestMethod]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,15 +103,18 @@ public async Task<IActionResult> List(DataSourceRequest command, PaymentTransact
orderGuid = order.OrderGuid;
}

var paymentTransactions = await paymentTransactionService.SearchPaymentTransactions(
customerEmail: model.SearchCustomerEmail,
ts: model.SearchTransactionStatus >= 0 ? (TransactionStatus)model.SearchTransactionStatus : null,
createdFromUtc: startDateValue,
createdToUtc: endDateValue,
storeId: model.StoreId,
orderGuid: orderGuid,
pageIndex: command.Page - 1,
pageSize: command.PageSize);
var paymentTransactions = await mediator.Send(new GetPaymentTransactionQuery {
CustomerEmail = model.SearchCustomerEmail,
Ts = model.SearchTransactionStatus >= 0 ? (TransactionStatus)model.SearchTransactionStatus : null,
CreatedFromUtc = startDateValue,
CreatedToUtc = endDateValue,
StoreId = model.StoreId,
OrderGuid = orderGuid,
PageIndex = command.Page - 1,
PageSize = command.PageSize,
//the payment of an order searched for by its number is shown whatever state its checkout left it in
IncludeTemp = model.ShowAbandoned || orderGuid.HasValue
});

var dataModel = new List<PaymentTransactionModel>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ public class PaymentTransactionListModel : BaseModel
[UIHint("DateNullable")]
public DateTime? EndDate { get; set; }

[GrandResourceDisplayName("Admin.Orders.PaymentTransaction.List.ShowAbandoned")]
public bool ShowAbandoned { get; set; }

public string StoreId { get; set; }

public IList<SelectListItem> PaymentTransactionStatus { get; set; } = new List<SelectListItem>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
<admin-field asp-for="SearchTransactionStatus" asp-items="Model.PaymentTransactionStatus"/>
<admin-field asp-for="StartDate"/>
<admin-field asp-for="EndDate"/>
<admin-field asp-for="ShowAbandoned"/>
</admin-filters>

<admin-card flush>
Expand Down Expand Up @@ -77,7 +78,8 @@
SearchCustomerEmail: $('#@Html.IdFor(model => model.SearchCustomerEmail)').val(),
OrderNumber: $('#@Html.IdFor(model => model.OrderNumber)').val(),
StartDate: $('#@Html.IdFor(model => model.StartDate)').val(),
EndDate: $('#@Html.IdFor(model => model.EndDate)').val()
EndDate: $('#@Html.IdFor(model => model.EndDate)').val(),
ShowAbandoned: $('#@Html.IdFor(model => model.ShowAbandoned)').is(':checked')
};
addAntiForgeryToken(data);
return data;
Expand Down
Binary file modified src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml
Binary file not shown.
6 changes: 6 additions & 0 deletions src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2499,4 +2499,10 @@
<Resource Name="Admin.Orders.PaymentTransaction.CannotDelete" Area="Admin">
<Value>Only a payment transaction left behind by an abandoned checkout can be deleted: still pending, nothing paid or authorized, no order, and not changed in the last hour. Close the payment of an order with Refund, Void or by cancelling the order.</Value>
</Resource>
<Resource Name="Admin.Orders.PaymentTransaction.List.ShowAbandoned" Area="Admin">
<Value>Show abandoned checkouts</Value>
</Resource>
<Resource Name="Admin.Orders.PaymentTransaction.List.ShowAbandoned.Hint" Area="Admin">
<Value>Also show transactions of a checkout whose payment never went through, e.g. it failed or was left unfinished.</Value>
</Resource>
</Language>
Loading