Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ACL-242] Add CreditableAt in GetPaymentResult #237

Merged
merged 2 commits into from
Dec 11, 2024
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
9 changes: 6 additions & 3 deletions src/TrueLayer/Payments/Model/GetPaymentResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,19 +76,21 @@ public record Authorizing : PaymentDetails;

/// <summary>
/// Represents a payment that has been authorized by the end user
/// <param name="CreditableAt">The date and time that TrueLayer determined that the payment was ready to be credited</param>
/// </summary>
/// <returns></returns>
[JsonDiscriminator("authorized")]
public record Authorized : PaymentDetails;
public record Authorized(DateTime? CreditableAt) : PaymentDetails;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this correct? It does not seems so based on our public docs? I can't see the field on the authorized payment details on the API ref

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, it's quite new, probably the docs are not updated, I'm checking with Risk

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's confirmed, we need to update docs


/// <summary>
/// Represents a payment that has been executed
/// For open loop payments this state is terminal. For closed-loop payments, wait for Settled.
/// </summary>
/// <param name="ExecutedAt">The date and time the payment executed</param>
/// <param name="CreditableAt">The date and time that TrueLayer determined that the payment was ready to be credited</param>
/// <returns></returns>
[JsonDiscriminator("executed")]
public record Executed(DateTime ExecutedAt) : PaymentDetails;
public record Executed(DateTime ExecutedAt, DateTime? CreditableAt) : PaymentDetails;

/// <summary>
/// Represents a payment that has settled
Expand All @@ -97,9 +99,10 @@ public record Executed(DateTime ExecutedAt) : PaymentDetails;
/// <param name="ExecutedAt">The date and time the payment executed</param>
/// <param name="SettledAt">The date and time the payment was settled</param>
/// <param name="PaymentSource">Details of the source of funds for the payment</param>
/// <param name="CreditableAt">The date and time that TrueLayer determined that the payment was ready to be credited</param>
/// <returns></returns>
[JsonDiscriminator("settled")]
public record Settled(DateTime ExecutedAt, DateTime SettledAt, PaymentSource PaymentSource) : PaymentDetails;
public record Settled(DateTime ExecutedAt, DateTime SettledAt, PaymentSource PaymentSource, DateTime? CreditableAt) : PaymentDetails;

/// <summary>
/// Represents a payment that failed to complete. This is a terminal state.
Expand Down
34 changes: 34 additions & 0 deletions test/TrueLayer.AcceptanceTests/Helpers/Waiter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace TrueLayer.AcceptanceTests.Helpers;

public static class Waiter
{
public static Task<T> WaitAsync<T>(
Func<Task<T>> action,
Predicate<T> predicate,
TimeSpan? pause = null,
TimeSpan? timeout = null)
=> WaitAsync(action, x => Task.FromResult(predicate(x)), pause, timeout);

public static async Task<T> WaitAsync<T>(
Func<Task<T>> action,
Func<T, Task<bool>> predicate,
TimeSpan? pause = null,
TimeSpan? timeout = null)
{
var stopwatch = Stopwatch.StartNew();

T result;

do
{
result = await action();
await Task.Delay(pause.GetValueOrDefault(TimeSpan.FromSeconds(1)));
} while (!await predicate(result) && stopwatch.Elapsed < timeout.GetValueOrDefault(TimeSpan.FromSeconds(20)));

return result;
}
}
9 changes: 9 additions & 0 deletions test/TrueLayer.AcceptanceTests/MockBank/MockBankAction.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace TrueLayer.AcceptanceTests.MockBank;

public enum MockBankAction
{
Cancel,
RejectAuthorisation,
Execute,
RejectExecution,
}
41 changes: 41 additions & 0 deletions test/TrueLayer.AcceptanceTests/MockBank/MockBankClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;

namespace TrueLayer.AcceptanceTests.MockBank;

public class MockBankClient
{
private readonly HttpClient _httpClient;

public MockBankClient(HttpClient httpClient)
{
_httpClient = httpClient;
}

public async Task<Uri> AuthorisePaymentAsync(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we do something hacky already for similar purposes, for payments and mandates

Could we make this function usable for every resource type (mandates and payments) and reuse this everywhere?
Not needed now, we can do this in another PR

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, I was planning to do a refactor later, we can optimise several part of the tests.
The problem with this method was that returns a GetPaymentResponse.PaymentDetails and we need the specific type of the GetPaymentResponse for this test.

Uri authUri,
MockBankAction action,
int settlementDelayInSeconds = 0)
{
var mockPaymentId = authUri.Segments.Last();
var token = authUri.Fragment[7..];

var requestBody = $@"{{ ""action"": ""{action}"", ""settlement_delay_in_seconds"": {settlementDelayInSeconds} }}";

var request = new HttpRequestMessage(HttpMethod.Post, $"api/single-immediate-payments/{mockPaymentId}/action")
{
Headers = { { "Authorization", $"Bearer {token}" } },
Content = new StringContent(requestBody, Encoding.UTF8, MediaTypeNames.Application.Json),
};
var response = await _httpClient.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
response.StatusCode.Should().Be(HttpStatusCode.Accepted, "submit mock payment response should be 202");
return new Uri(responseBody);
}
}
42 changes: 42 additions & 0 deletions test/TrueLayer.AcceptanceTests/PayApiClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace TrueLayer.AcceptanceTests;

public class PayApiClient
{
private readonly HttpClient _httpClient;

public PayApiClient(HttpClient httpClient)
{
_httpClient = httpClient;
}

public async Task<HttpResponseMessage> GetJwksAsync()
{
var request = new HttpRequestMessage(HttpMethod.Get, "/.well-known/jwks.json");
var response = await _httpClient.SendAsync(request);
return response;
}

public async Task<HttpResponseMessage> SubmitProviderReturnParametersAsync(string query, string fragment)
{
var requestBody = new SubmitProviderReturnParametersRequest { Query = query, Fragment = fragment };

var request = new HttpRequestMessage(HttpMethod.Post, "/spa/submit-provider-return-parameters")
{
Content = JsonContent.Create(requestBody)
};
var response = await _httpClient.SendAsync(request);
return response;
}
}

public class SubmitProviderReturnParametersRequest
{
[JsonPropertyName("query")] public string? Query { get; set; }
[JsonPropertyName("fragment")] public string? Fragment { get; set; }
}

69 changes: 63 additions & 6 deletions test/TrueLayer.AcceptanceTests/PaymentTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using OneOf;
using TrueLayer.AcceptanceTests.Helpers;
using TrueLayer.AcceptanceTests.MockBank;
using TrueLayer.Common;
using TrueLayer.Payments.Model;
using TrueLayer.Payments.Model.AuthorizationFlow;
Expand Down Expand Up @@ -46,6 +48,8 @@
private readonly TrueLayerOptions _configuration;
private readonly string _gbpMerchantAccountId;
private readonly string _eurMerchantSecretKey;
private readonly MockBankClient _mockBankClient;
private readonly PayApiClient _payApiClient;

public PaymentTests(ApiTestFixture fixture)
{
Expand All @@ -54,11 +58,19 @@
(string gbpMerchantAccountId, string eurMerchantAccountId) = GetMerchantBeneficiaryAccountsAsync().Result;
_gbpMerchantAccountId = gbpMerchantAccountId;
_eurMerchantSecretKey = eurMerchantAccountId;
_mockBankClient = new MockBankClient(new HttpClient
{
BaseAddress = new Uri("https://pay-mock-connect.truelayer-sandbox.com/")
});
_payApiClient = new PayApiClient(new HttpClient
{
BaseAddress = new Uri("https://pay-api.truelayer-sandbox.com")
});
}

[Theory]
[MemberData(nameof(ExternalAccountPaymentRequests))]
public async Task can_create_external_account_payment(CreatePaymentRequest paymentRequest)
public async Task Can_Create_External_Account_Payment(CreatePaymentRequest paymentRequest)
{
var response = await _fixture.Client.Payments.CreatePayment(
paymentRequest, idempotencyKey: Guid.NewGuid().ToString());
Expand All @@ -77,7 +89,7 @@
}

[Fact]
public async Task can_create_merchant_account_gbp_Payment()
public async Task Can_Create_Merchant_Account_Gbp_Payment()
{
var paymentRequest = CreateTestPaymentRequest(
new Provider.UserSelected
Expand Down Expand Up @@ -139,7 +151,7 @@
}

[Fact]
public async Task can_create_merchant_account_eur_Payment()
public async Task Can_Create_Merchant_Account_Eur_Payment()
{
var paymentRequest = CreateTestPaymentRequest(
new Provider.Preselected("mock-payments-fr-redirect",
Expand Down Expand Up @@ -169,7 +181,7 @@
}

[Fact]
public async Task Can_create_payment_with_auth_flow()
public async Task Can_Create_Payment_With_Auth_Flow()
{
var sortCodeAccountNumber = new AccountIdentifier.SortCodeAccountNumber("567890", "12345678");
var providerSelection = new Provider.Preselected("mock-payments-gb-redirect", "faster_payments_service")
Expand Down Expand Up @@ -202,9 +214,42 @@
hppUri.Should().NotBeNullOrWhiteSpace();
}

[Fact]
public async Task GetPayment_Should_Return_Settled_Payment()
{
var providerSelection = new Provider.Preselected("mock-payments-gb-redirect", "faster_payments_service");

var paymentRequest = CreateTestPaymentRequest(
beneficiary: new Beneficiary.MerchantAccount(_gbpMerchantAccountId),
providerSelection: providerSelection,
initAuthorizationFlow: true);

var response = await _fixture.Client.Payments.CreatePayment(paymentRequest, idempotencyKey: Guid.NewGuid().ToString());

response.StatusCode.Should().Be(HttpStatusCode.Created);
var authorizing = response.Data.AsT3;
var paymentId = authorizing.Id;

var providerReturnUri = await _mockBankClient.AuthorisePaymentAsync(
authorizing.AuthorizationFlow!.Actions.Next.AsT2.Uri,
MockBankAction.Execute);

await _payApiClient.SubmitProviderReturnParametersAsync(providerReturnUri.Query, providerReturnUri.Fragment);

var getPaymentResponse = await PollPaymentForTerminalStatusAsync(paymentId, typeof(GetPaymentResponse.Settled));

var executed = getPaymentResponse.AsT4;
executed.AmountInMinor.Should().Be(paymentRequest.AmountInMinor);
executed.Currency.Should().Be(paymentRequest.Currency);
executed.Id.Should().NotBeNullOrWhiteSpace();
executed.CreatedAt.Should().NotBe(default);
executed.PaymentMethod.AsT0.Should().NotBeNull();
executed.CreditableAt.Should().NotBeNull();
}

[Theory]
[MemberData(nameof(ExternalAccountPaymentRequests))]
public async Task Can_get_authorization_required_payment(CreatePaymentRequest paymentRequest)
public async Task Can_Get_Authorization_Required_Payment(CreatePaymentRequest paymentRequest)
{
var response = await _fixture.Client.Payments.CreatePayment(
paymentRequest, idempotencyKey: Guid.NewGuid().ToString());
Expand Down Expand Up @@ -233,12 +278,12 @@
userSelected.Filter.Should().BeEquivalentTo(providerSelectionReq.Filter);
// Provider selection hasn't happened yet
userSelected.ProviderId.Should().BeNullOrEmpty();
userSelected.SchemeId.Should().BeNullOrEmpty();

Check warning on line 281 in test/TrueLayer.AcceptanceTests/PaymentTests.cs

View workflow job for this annotation

GitHub Actions / build

'Provider.UserSelected.SchemeId' is obsolete: 'The field will be removed soon. Please start using the new <see cref="SchemeSelection"/> field.'
},
preselected =>
{
Provider.Preselected providerSelectionReq = paymentRequest.PaymentMethod.AsT0.ProviderSelection.AsT1;
AssertSchemeSelection(preselected.SchemeSelection, providerSelectionReq.SchemeSelection, preselected.SchemeId, providerSelectionReq.SchemeId);

Check warning on line 286 in test/TrueLayer.AcceptanceTests/PaymentTests.cs

View workflow job for this annotation

GitHub Actions / build

'Provider.Preselected.SchemeId' is obsolete: 'The field will be removed soon. Please start using the new <see cref="SchemeSelection"/> field.'

Check warning on line 286 in test/TrueLayer.AcceptanceTests/PaymentTests.cs

View workflow job for this annotation

GitHub Actions / build

'Provider.Preselected.SchemeId' is obsolete: 'The field will be removed soon. Please start using the new <see cref="SchemeSelection"/> field.'
preselected.ProviderId.Should().Be(providerSelectionReq.ProviderId);
preselected.Remitter.Should().Be(providerSelectionReq.Remitter);
});
Expand All @@ -250,7 +295,7 @@
}

[Fact]
public async Task Can_create_payment_with_retry_option_and_get_attemptFailed_error()
public async Task Can_Create_Payment_With_Retry_Option_And_Get_AttemptFailed_Error()
{
// Arrange
var paymentRequest = CreateTestPaymentRequest(
Expand Down Expand Up @@ -702,4 +747,16 @@

return (payment.Value as GetPaymentResponse.PaymentDetails)!;
}

private async Task<GetPaymentUnion> PollPaymentForTerminalStatusAsync(
string paymentId,
Type expectedStatus)
{
var getPaymentResponseBody = await Waiter.WaitAsync(
() => _fixture.Client.Payments.GetPayment(paymentId),
r => r.Data.GetType() == expectedStatus);

getPaymentResponseBody.IsSuccessful.Should().BeTrue();
return getPaymentResponseBody.Data;
}
}
Loading