remove NodaTime dependency and refactor to System.DateTimeOffset

This commit is contained in:
2022-12-06 15:17:44 +01:00
parent 430967e2c3
commit 637fd70cb2
20 changed files with 75 additions and 76 deletions
@@ -18,11 +18,11 @@ public record Account
public Guid Id { get; set; }
/// <summary>Gets or sets the point in time when the account object was created.</summary>
public Instant Created { get; set; }
public DateTimeOffset Created { get; set; }
/// <summary>Gets or sets the point in time when the account object was last accessed.</summary>
[JsonPropertyName("last_accessed")]
public Instant LastAccessed { get; set; }
public DateTimeOffset LastAccessed { get; set; }
/// <summary>Gets or sets the account IBAN.</summary>
public string Iban { get; set; } = null!;
@@ -60,11 +60,12 @@ public sealed class AccountClient : IAccountClient
/// <inheritdoc />
public async Task<Transactions> GetTransactions(
Guid id,
Interval? interval = null,
DateTimeOffset? dateFrom = null,
DateTimeOffset? dateTo = null,
CancellationToken cancellationToken = default)
{
var transactions = await _httpClient
.GetFromJsonAsync(Routes.Accounts.TransactionsUri(id, interval), _context.TransactionsWrapper, cancellationToken)
.GetFromJsonAsync(Routes.Accounts.TransactionsUri(id, dateFrom, dateTo), _context.TransactionsWrapper, cancellationToken)
.ConfigureAwait(false);
return transactions!.Transactions;
@@ -2,6 +2,7 @@
// Licensed under the Apache License 2.0.
// See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using NodaTime;
@@ -21,7 +22,7 @@ public record Balance
public bool CreditLimitIncluded { get; set; }
/// <summary>Gets or sets the date on which the balance was calculated.</summary>
public LocalDate? ReferenceDate { get; set; }
public DateTimeOffset? ReferenceDate { get; set; }
}
internal class BalancesWrapper
@@ -2,6 +2,8 @@
// Licensed under the Apache License 2.0.
// See LICENSE file in the project root for full license information.
using System;
using NodaTime;
using VMelnalksnis.NordigenDotNet.Institutions;
@@ -15,7 +17,7 @@ public record BookedTransaction : Transaction
public string TransactionId { get; set; } = null!;
/// <summary>Gets or sets the date when an entry is posted to an account on the account servicer's books.</summary>
public LocalDate BookingDate { get; set; }
public DateTimeOffset BookingDate { get; set; }
/// <summary>Gets or sets the name of the counterparty that sends <see cref="Transaction.TransactionAmount"/> during the transaction.</summary>
public string? DebtorName { get; set; }
@@ -34,8 +34,9 @@ public interface IAccountClient
/// <summary>Gets all transactions for the account within the specified interval.</summary>
/// <param name="id">The id of the account.</param>
/// <param name="interval">The interval for which to get the transactions.</param>
/// <param name="dateFrom">The start date for which to get the transactions.</param>
/// <param name="dateTo">The end date for which to get the transactions.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>All transactions for the specified account and interval.</returns>
Task<Transactions> GetTransactions(Guid id, Interval? interval = null, CancellationToken cancellationToken = default);
Task<Transactions> GetTransactions(Guid id, DateTimeOffset? dateFrom = null, DateTimeOffset? dateTo = null, CancellationToken cancellationToken = default);
}
@@ -2,6 +2,7 @@
// Licensed under the Apache License 2.0.
// See LICENSE file in the project root for full license information.
using System;
using System.Text.Json.Serialization;
using NodaTime;
@@ -19,5 +20,5 @@ public abstract record Transaction
public string UnstructuredInformation { get; set; } = null!;
/// <summary>Gets or sets the date when the transaction was valued at.</summary>
public LocalDate? ValueDate { get; set; }
public DateTimeOffset? ValueDate { get; set; }
}
@@ -19,7 +19,7 @@ public record EndUserAgreement
public Guid Id { get; set; }
/// <summary>Gets or sets the point in time when the agreement was created.</summary>
public Instant Created { get; set; }
public DateTimeOffset Created { get; set; }
/// <summary>Gets or sets maximum number of days of transaction data to retrieve.</summary>
[JsonPropertyName("max_historical_days")]
@@ -37,6 +37,6 @@ public record EndUserAgreement
[JsonPropertyName("institution_id")]
public string InstitutionId { get; set; } = null!;
/// <summary>Gets or sets the point int time when the end user accepted the agreement.</summary>
public Instant? Accepted { get; set; }
/// <summary>Gets or sets the point in time when the end user accepted the agreement.</summary>
public DateTimeOffset? Accepted { get; set; }
}
@@ -17,7 +17,7 @@ public record Requisition
public Guid Id { get; set; }
/// <summary>Gets or sets the point in time when the requisition was created.</summary>
public Instant Created { get; set; }
public DateTimeOffset Created { get; set; }
/// <summary>Gets or sets the URI to which the user will be redirected after authorizing access.</summary>
public Uri Redirect { get; set; } = null!;
+15 -5
View File
@@ -4,8 +4,6 @@
using System;
using NodaTime;
namespace VMelnalksnis.NordigenDotNet;
internal static class Routes
@@ -33,9 +31,21 @@ internal static class Routes
internal static string DetailsUri(Guid id) => $"{IdUri(id)}details/";
internal static string TransactionsUri(Guid id, Interval? interval) => interval is null
? TransactionsUri(id)
: $"{TransactionsUri(id)}?date_from={interval.Value.Start:yyyy-MM-dd}&date_to={interval.Value.End:yyyy-MM-dd}";
internal static string TransactionsUri(Guid id, DateTimeOffset? dateFrom, DateTimeOffset? dateTo)
{
var uri = TransactionsUri(id);
if (dateFrom.HasValue)
{
uri += $"?date_from={dateFrom.Value:yyyy-MM-dd}";
}
if (dateTo.HasValue)
{
uri += $"{(dateFrom.HasValue ? '&' : '?')}date_to={dateTo.Value:yyyy-MM-dd}";
}
return uri;
}
private static string TransactionsUri(Guid id) => $"{IdUri(id)}transactions/";
}
@@ -5,22 +5,18 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using NodaTime;
using NodaTime.Serialization.SystemTextJson;
namespace VMelnalksnis.NordigenDotNet.Serialization;
/// <summary><see cref="JsonSerializerOptions"/> for <see cref="INordigenClient"/>.</summary>
public sealed class NordigenJsonSerializerOptions
{
/// <summary>Initializes a new instance of the <see cref="NordigenJsonSerializerOptions"/> class.</summary>
/// <param name="dateTimeZoneProvider">Time zone provider for date and time serialization.</param>
public NordigenJsonSerializerOptions(IDateTimeZoneProvider dateTimeZoneProvider)
public NordigenJsonSerializerOptions()
{
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
Converters = { new JsonStringEnumConverter() },
}.ConfigureForNodaTime(dateTimeZoneProvider);
};
Context = new(options);
}
@@ -6,7 +6,7 @@ using System.Text.Json.Serialization;
namespace VMelnalksnis.NordigenDotNet.Tokens;
internal class AccessToken
public class AccessToken
{
[JsonConstructor]
public AccessToken(string access, int accessExpires)
@@ -2,6 +2,8 @@
// Licensed under the Apache License 2.0.
// See LICENSE file in the project root for full license information.
using System;
using NodaTime;
namespace VMelnalksnis.NordigenDotNet.Tokens;
@@ -10,50 +12,47 @@ namespace VMelnalksnis.NordigenDotNet.Tokens;
public class NordigenTokenCache
{
private readonly NordigenOptions _nordigenOptions;
private readonly IClock _clock;
/// <summary>Initializes a new instance of the <see cref="NordigenTokenCache"/> class.</summary>
/// <param name="nordigenOptions">Options for connection to the Nordigen API.</param>
/// <param name="clock">Clock for accessing the current time.</param>
public NordigenTokenCache(NordigenOptions nordigenOptions, IClock clock)
public NordigenTokenCache(NordigenOptions nordigenOptions)
{
_nordigenOptions = nordigenOptions;
_clock = clock;
}
internal AccessToken? AccessToken { get; private set; }
public AccessToken? AccessToken { get; private set; }
internal bool IsAccessExpired =>
public bool IsAccessExpired =>
AccessToken is not null &&
AccessExpiresAt is not null &&
_clock.GetCurrentInstant() > AccessExpiresAt;
DateTimeOffset.Now > AccessExpiresAt;
internal Token? Token { get; private set; }
public Token? Token { get; private set; }
internal bool IsRefreshExpired =>
public bool IsRefreshExpired =>
Token is not null &&
RefreshExpiresAt is not null &&
_clock.GetCurrentInstant() > RefreshExpiresAt;
DateTimeOffset.Now > RefreshExpiresAt;
private Instant? AccessExpiresAt { get; set; }
public DateTimeOffset? AccessExpiresAt { get; set; }
private Instant? RefreshExpiresAt { get; set; }
public DateTimeOffset? RefreshExpiresAt { get; set; }
internal void SetToken(Token token)
public void SetToken(Token token)
{
Token = token;
AccessToken = token;
var currentInstant = _clock.GetCurrentInstant();
var now = DateTimeOffset.Now;
var factor = _nordigenOptions.ExpirationFactor;
AccessExpiresAt = currentInstant + Duration.FromSeconds(token.AccessExpires / factor);
RefreshExpiresAt = currentInstant + Duration.FromSeconds(token.RefreshExpires / factor);
AccessExpiresAt = now.AddSeconds(token.AccessExpires / factor);
RefreshExpiresAt = now.AddSeconds(token.RefreshExpires / factor);
}
internal void SetAccessToken(AccessToken accessToken)
public void SetAccessToken(AccessToken accessToken)
{
AccessToken = accessToken;
var currentInstant = _clock.GetCurrentInstant();
var now = DateTimeOffset.Now;
var factor = _nordigenOptions.ExpirationFactor;
AccessExpiresAt = currentInstant + Duration.FromSeconds(accessToken.AccessExpires / factor);
AccessExpiresAt = now.AddSeconds(accessToken.AccessExpires / factor);
}
}
@@ -6,7 +6,7 @@ using System.Text.Json.Serialization;
namespace VMelnalksnis.NordigenDotNet.Tokens;
internal class Token : AccessToken
public class Token : AccessToken
{
[JsonConstructor]
public Token(string access, int accessExpires, string refresh, int refreshExpires)
@@ -13,11 +13,6 @@
<AssemblyOriginatorKeyFile>key.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NodaTime"/>
<PackageReference Include="NodaTime.Serialization.SystemTextJson"/>
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces"/>
<PackageReference Include="System.ComponentModel.Annotations"/>
@@ -28,8 +28,6 @@ public sealed class ServiceCollectionExtensionsTests
var serviceCollection = new ServiceCollection();
serviceCollection
.AddSingleton<IClock>(SystemClock.Instance)
.AddSingleton(DateTimeZoneProviders.Tzdb)
.AddNordigenDotNet(configuration);
var serviceProvider = serviceCollection.BuildServiceProvider();
@@ -6,8 +6,6 @@ using System;
using System.Linq;
using System.Threading.Tasks;
using NodaTime;
using VMelnalksnis.NordigenDotNet.Requisitions;
using Xunit.Abstractions;
@@ -41,12 +39,12 @@ public sealed class AccountClientTests : IClassFixture<ServiceProviderFixture>,
_requisition.Accounts.Should().HaveCount(2);
var account = await _nordigenClient.Accounts.Get(_accountId);
var currentInstant = SystemClock.Instance.GetCurrentInstant();
var now = DateTimeOffset.Now;
using (new AssertionScope())
{
account.Id.Should().Be(_accountId);
account.Created.Should().BeLessThan(account.LastAccessed).And.BeLessThan(currentInstant);
account.LastAccessed.Should().BeGreaterThan(currentInstant - Duration.FromMinutes(1));
account.Created.Should().BeBefore(account.LastAccessed).And.BeBefore(now);
account.LastAccessed.Should().BeAfter(now.AddMinutes(-1));
account.Iban.Should().Be("GL3343697694912188");
account.InstitutionId.Should().Be(IntegrationInstitutionId);
account.Status.Should().BeDefined();
@@ -90,13 +88,11 @@ public sealed class AccountClientTests : IClassFixture<ServiceProviderFixture>,
[Fact]
public async Task GetTransactions_ShouldReturnExpected()
{
var currentInstant = SystemClock.Instance.GetCurrentInstant();
var currentZone = DateTimeZoneProviders.Tzdb.GetSystemDefault();
var currentDate = currentInstant.InZone(currentZone).Date;
var now = DateTimeOffset.Now;
var dateTo = currentInstant;
var dateFrom = dateTo - Duration.FromDays(7);
var transactions = await _nordigenClient.Accounts.GetTransactions(_accountId, new Interval(dateFrom, dateTo));
var dateTo = now;
var dateFrom = dateTo.AddDays(-7);
var transactions = await _nordigenClient.Accounts.GetTransactions(_accountId, dateFrom, dateTo);
var allTransactions = await _nordigenClient.Accounts.GetTransactions(_accountId);
using (new AssertionScope())
@@ -109,9 +105,9 @@ public sealed class AccountClientTests : IClassFixture<ServiceProviderFixture>,
pendingTransaction.TransactionAmount.Currency.Should().Be("EUR");
pendingTransaction.TransactionAmount.Amount.Should().Be(10m);
pendingTransaction.UnstructuredInformation.Should().Be("Reserved PAYMENT Emperor's Burgers");
pendingTransaction.ValueDate.Should().Be(currentDate - Period.FromDays(2));
pendingTransaction.ValueDate.Should().Be(now.AddDays(-2));
var date = currentDate - Period.FromDays(1);
var date = now.AddDays(-1);
var transactionId = $"{date:yyyyMMdd}01927908-1";
var bookedTransaction = transactions.Booked.First(transaction => transaction.TransactionId == transactionId);
bookedTransaction.TransactionAmount.Currency.Should().Be("EUR");
@@ -2,12 +2,11 @@
// Licensed under the Apache License 2.0.
// See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using NodaTime;
using VMelnalksnis.NordigenDotNet.Agreements;
using Xunit.Abstractions;
@@ -39,7 +38,7 @@ public sealed class AgreementClientTests : IClassFixture<ServiceProviderFixture>
using (new AssertionScope())
{
createdAgreement.Created.Should().BeGreaterThan(SystemClock.Instance.GetCurrentInstant() - Duration.FromSeconds(5));
createdAgreement.Created.Should().BeAfter(DateTimeOffset.Now.AddSeconds(-5));
createdAgreement.Accepted.Should().BeNull();
createdAgreement.MaxHistoricalDays.Should().Be(90);
createdAgreement.AccessValidForDays.Should().Be(90);
@@ -2,14 +2,13 @@
// Licensed under the Apache License 2.0.
// See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using NodaTime;
using VMelnalksnis.NordigenDotNet.Requisitions;
using Xunit.Abstractions;
@@ -66,7 +65,7 @@ public sealed class RequisitionsClientTests : IClassFixture<ServiceProviderFixtu
using (new AssertionScope())
{
requisition.Should().BeEquivalentTo(createdRequisition);
requisition.Created.Should().BeGreaterThan(SystemClock.Instance.GetCurrentInstant() - Duration.FromSeconds(5));
requisition.Created.Should().BeAfter(DateTimeOffset.Now.AddSeconds(5));
requisition.Redirect.Should().Be(creation.Redirect);
requisition.Status.Should().Be(RequisitionStatus.Cr);
requisition.InstitutionId.Should().BeEquivalentTo(creation.InstitutionId);
@@ -16,10 +16,11 @@ public sealed class RoutesTests
[ClassData(typeof(TransactionsUriTestData))]
public void TransactionsUri_ShouldHaveExpectedQueryParameters(
Guid id,
Interval? interval,
DateTimeOffset? dateFrom,
DateTimeOffset? dateTo,
NameValueCollection expectedParameters)
{
var uriValue = Routes.Accounts.TransactionsUri(id, interval);
var uriValue = Routes.Accounts.TransactionsUri(id, dateFrom, dateTo);
var uriBuilder = new UriBuilder(uriValue);
var queryDictionary = HttpUtility.ParseQueryString(uriBuilder.Query);
@@ -17,15 +17,15 @@ internal sealed class TransactionsUriTestData : IEnumerable<object?[]>
{
yield return new object?[] { Guid.NewGuid(), null, new NameValueCollection() };
var dateFrom = Instant.FromUtc(2022, 05, 01, 12, 00);
var dateTo = Instant.FromUtc(2022, 05, 12, 13, 00);
var dateFrom = new DateTimeOffset(2022, 05, 01, 12, 00, 00, TimeSpan.Zero);
var dateTo = new DateTimeOffset(2022, 05, 12, 13, 00, 00, TimeSpan.Zero);
var collection = new NameValueCollection
{
{ "date_from", "2022-05-01" },
{ "date_to", "2022-05-12" },
};
yield return new object?[] { Guid.NewGuid(), new Interval(dateFrom, dateTo), collection };
yield return new object?[] { Guid.NewGuid(), dateFrom, dateTo, collection };
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();