Skip to content

Commit

Permalink
pit-stop
Browse files Browse the repository at this point in the history
  • Loading branch information
VMelnalksnis committed Aug 21, 2024
1 parent 5a2cbc5 commit b78e025
Show file tree
Hide file tree
Showing 29 changed files with 996 additions and 43 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ public sealed class DesignTimeGnomeshadeClient : IGnomeshadeClient
private static readonly List<Loan> _loans;
private static readonly List<LoanPayment> _loanPayments;

private static readonly List<PlannedTransaction> _plannedTransactions;
private static readonly List<PlannedTransfer> _plannedTransfers;
private static readonly List<PlannedPurchase> _plannedPurchases;
private static readonly List<PlannedLoanPayment> _plannedLoanPayments;

static DesignTimeGnomeshadeClient()
{
var euro = new Currency { Id = Guid.NewGuid(), Name = "Euro", AlphabeticCode = "EUR" };
Expand All @@ -53,7 +58,8 @@ static DesignTimeGnomeshadeClient()

var counterparty = new Counterparty { Id = Guid.Empty, Name = "John Doe" };
var otherCounterparty = new Counterparty { Id = Guid.NewGuid(), Name = "Jane Doe" };
_counterparties = [counterparty, otherCounterparty];
var bankCounterparty = new Counterparty { Id = Guid.NewGuid(), Name = "Bank" };
_counterparties = [counterparty, otherCounterparty, bankCounterparty];

var cash = new Account
{
Expand All @@ -67,27 +73,39 @@ static DesignTimeGnomeshadeClient()
new() { Id = Guid.NewGuid(), CurrencyId = usd.Id, CurrencyAlphabeticCode = usd.AlphabeticCode }
],
};

var spending = new Account
{
Id = Guid.NewGuid(),
Name = "Spending",
CounterpartyId = counterparty.Id,
PreferredCurrencyId = euro.Id,
Currencies =
[new() { Id = Guid.NewGuid(), CurrencyId = euro.Id, CurrencyAlphabeticCode = euro.AlphabeticCode }],
Currencies = [new() { Id = Guid.NewGuid(), CurrencyId = euro.Id, CurrencyAlphabeticCode = euro.AlphabeticCode }],
};
_accounts = [cash, spending];

var bankAccount = new Account
{
Id = Guid.NewGuid(),
Name = "Bank",
CounterpartyId = bankCounterparty.Id,
PreferredCurrencyId = euro.Id,
Currencies = [new() { Id = Guid.NewGuid(), CurrencyId = euro.Id, CurrencyAlphabeticCode = euro.AlphabeticCode }],
};

_accounts = [cash, spending, bankAccount];

var kilogram = new Unit { Id = Guid.NewGuid(), Name = "Kilogram" };
var gram = new Unit { Id = Guid.NewGuid(), Name = "Gram", ParentUnitId = kilogram.Id, Multiplier = 1000m };
_units = [kilogram, gram];

var food = new Category { Id = Guid.Empty, Name = "Food" };
_categories = [food];
var liabilities = new Category { Id = Guid.NewGuid(), Name = "Liabilities" };
_categories = [food, liabilities];

var bread = new Product { Id = Guid.NewGuid(), Name = "Bread", CategoryId = food.Id, UnitId = kilogram.Id };
var milk = new Product { Id = Guid.NewGuid(), Name = "Milk", CategoryId = food.Id };
_products = [bread, milk];
var loan = new Product { Id = Guid.NewGuid(), Name = "Loan", CategoryId = liabilities.Id };
_products = [bread, milk, loan];

var transaction = new Transaction
{
Expand Down Expand Up @@ -206,10 +224,68 @@ static DesignTimeGnomeshadeClient()
Interest = 150m,
}
];

var plannedTransaction = new PlannedTransaction
{
Id = Guid.Empty,
StartTime = SystemClock.Instance.GetCurrentInstant() + Duration.FromDays(15),
Period = Period.FromMonths(1),
Count = 12,
};

var plannedPrincipalTransfer = new PlannedTransfer
{
Id = Guid.Empty,
PlannedTransactionId = plannedTransaction.Id,
SourceAmount = 500,
SourceAccountId = spending.Currencies.Single(account => account.CurrencyId == euro.Id).Id,
TargetAmount = 500,
TargetCounterpartyId = bankCounterparty.Id,
TargetCurrencyId = euro.Id,
BookedAt = new(09, 00),
Order = 1,
};

var plannedInterestTransfer = new PlannedTransfer
{
Id = Guid.Empty,
PlannedTransactionId = plannedTransaction.Id,
SourceAmount = 150,
SourceAccountId = spending.Currencies.Single(account => account.CurrencyId == euro.Id).Id,
TargetAmount = 150,
TargetCounterpartyId = bankCounterparty.Id,
TargetCurrencyId = euro.Id,
BookedAt = new(09, 00),
Order = 2,
};

var plannedPurchase = new PlannedPurchase
{
Id = Guid.Empty,
PlannedTransactionId = plannedTransaction.Id,
Price = plannedPrincipalTransfer.SourceAmount + plannedInterestTransfer.SourceAmount,
CurrencyId = euro.Id,
ProductId = loan.Id,
Amount = 1,
};

var plannedLoanPayment = new PlannedLoanPayment
{
Id = Guid.Empty,
LoanId = _loans.Single().Id,
PlannedTransactionId = plannedTransaction.Id,
Amount = plannedPrincipalTransfer.SourceAmount,
Interest = plannedInterestTransfer.SourceAmount,
};

_plannedTransactions = [plannedTransaction];
_plannedTransfers = [plannedPrincipalTransfer, plannedInterestTransfer];
_plannedPurchases = [plannedPurchase];
_plannedLoanPayments = [plannedLoanPayment];
}

/// <inheritdoc />
public Task<LoginResult> LogInAsync(Login login) => throw new NotImplementedException();
public Task<LoginResult> LogInAsync(Login login) => Task.FromResult<LoginResult>(new SuccessfulLogin());

/// <inheritdoc />
public Task<ExternalLoginResult> SocialRegister() => throw new NotImplementedException();
Expand Down Expand Up @@ -460,6 +536,34 @@ public Task AddRelatedTransactionAsync(Guid id, Guid relatedId) =>
public Task RemoveRelatedTransactionAsync(Guid id, Guid relatedId) =>
throw new NotImplementedException();

/// <inheritdoc />
public Task<List<PlannedTransaction>> GetPlannedTransactions(CancellationToken cancellationToken = default) =>
Task.FromResult(_plannedTransactions.ToList());

/// <inheritdoc />
public Task<List<PlannedTransfer>> GetPlannedTransfers(CancellationToken cancellationToken = default) =>
Task.FromResult(_plannedTransfers.ToList());

/// <inheritdoc />
public Task<List<PlannedTransfer>> GetPlannedTransfers(Guid transactionId, CancellationToken cancellationToken = default) =>
Task.FromResult(_plannedTransfers.Where(transfer => transfer.PlannedTransactionId == transactionId).ToList());

/// <inheritdoc />
public Task<List<PlannedPurchase>> GetPlannedPurchases(CancellationToken cancellationToken = default) =>
Task.FromResult(_plannedPurchases.ToList());

/// <inheritdoc />
public Task<List<PlannedPurchase>> GetPlannedPurchases(Guid transactionId, CancellationToken cancellationToken = default) =>
Task.FromResult(_plannedPurchases.Where(transfer => transfer.PlannedTransactionId == transactionId).ToList());

/// <inheritdoc />
public Task<List<PlannedLoanPayment>> GetPlannedLoanPayments(CancellationToken cancellationToken = default) =>
Task.FromResult(_plannedLoanPayments.ToList());

/// <inheritdoc />
public Task<List<PlannedLoanPayment>> GetPlannedLoanPayments(Guid transactionId, CancellationToken cancellationToken = default) =>
Task.FromResult(_plannedLoanPayments.Where(transfer => transfer.PlannedTransactionId == transactionId).ToList());

/// <inheritdoc />
[Obsolete]
public Task<List<LegacyLoan>> GetLegacyLoans(CancellationToken cancellationToken = default) =>
Expand Down
1 change: 1 addition & 0 deletions source/Gnomeshade.Avalonia.Core/MainWindowViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ private static Exception CurrentLifetimeIsNull()
private async Task InitializeActiveViewAsync()
{
// The first notification does not show up, and subsequent calls work after some delay
// todo if the app starts too fast the first notification still does not show up
ActivityService.ShowNotification(new(null, null, expiration: TimeSpan.FromMilliseconds(1)));

if (ActiveView is not null)
Expand Down
84 changes: 78 additions & 6 deletions source/Gnomeshade.Avalonia.Core/Reports/BalanceReportViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

using Gnomeshade.Avalonia.Core.Reports.Splits;
using Gnomeshade.WebApi.Client;
using Gnomeshade.WebApi.Models.Accounts;
using Gnomeshade.WebApi.Models.Transactions;

using LiveChartsCore.Defaults;
using LiveChartsCore.Kernel.Sketches;
Expand Down Expand Up @@ -54,6 +56,9 @@ public sealed partial class BalanceReportViewModel : ViewModelBase
[Notify]
private IReportSplit? _selectedSplit = SplitProvider.MonthlySplit;

[Notify]
private bool _includeProjections = true;

/// <summary>Gets the y axes for <see cref="Series"/>.</summary>
[Notify(Setter.Private)]
private List<ICartesianAxis> _yAxes;
Expand Down Expand Up @@ -103,11 +108,17 @@ public void ResetZoom()
/// <inheritdoc />
protected override async Task Refresh()
{
var transfersTask = _gnomeshadeClient.GetTransfersAsync();
var cancellation = new CancellationTokenSource();
var task =
(_gnomeshadeClient.GetTransfersAsync(cancellation.Token),
_gnomeshadeClient.GetPlannedTransactions(cancellation.Token),
_gnomeshadeClient.GetPlannedTransfers(cancellation.Token))
.WhenAll();

var (counterparty, allAccounts, currencies) = await
(_gnomeshadeClient.GetMyCounterpartyAsync(),
_gnomeshadeClient.GetAccountsAsync(),
_gnomeshadeClient.GetCurrenciesAsync())
(_gnomeshadeClient.GetMyCounterpartyAsync(cancellation.Token),
_gnomeshadeClient.GetAccountsAsync(cancellation.Token),
_gnomeshadeClient.GetCurrenciesAsync(cancellation.Token))
.WhenAll();

var selected = SelectedAccounts.Select(account => account.Id).ToArray();
Expand All @@ -123,6 +134,7 @@ protected override async Task Refresh()

if (SelectedSplit is not { } reportSplit)
{
await cancellation.CancelAsync();
return;
}

Expand All @@ -132,7 +144,22 @@ protected override async Task Refresh()
.SelectMany(account => account.Currencies.Where(aic => aic.CurrencyId == (SelectedCurrency?.Id ?? account.PreferredCurrencyId)).Select(aic => aic.Id))
.ToArray();

var transfers = (await transfersTask)
var (actualTransfers, plannedTransactions, plannedTransfers) = await task;
var timeZone = _dateTimeZoneProvider.GetSystemDefault();

IEnumerable<Transfer> allTransfers = actualTransfers;
if (IncludeProjections)
{
var x = plannedTransfers
.SelectMany(plannedTransfer => PlannedTransferSelector(plannedTransfer, plannedTransactions, timeZone))
.Where(tuple =>
(tuple.Planned.SourceAccountId is { } sourceId && inCurrencyIds.Contains(sourceId)) ||
(tuple.Planned.TargetAccountId is { } targetId && inCurrencyIds.Contains(targetId)))
.Select(tuple => tuple.Transfer);
allTransfers = allTransfers.Concat(x);
}

var transfers = allTransfers
.Where(transfer =>
inCurrencyIds.Contains(transfer.SourceAccountId) ||
inCurrencyIds.Contains(transfer.TargetAccountId))
Expand All @@ -141,7 +168,6 @@ protected override async Task Refresh()
.ThenBy(transfer => transfer.ModifiedAt)
.ToArray();

var timeZone = _dateTimeZoneProvider.GetSystemDefault();
var currentTime = _clock.GetCurrentInstant();
var dates = transfers
.Select(transfer => transfer.ValuedAt ?? transfer.BookedAt!.Value)
Expand Down Expand Up @@ -185,6 +211,47 @@ protected override async Task Refresh()
XAxes = [reportSplit.GetXAxis(startTime, endTime)];
}

private static IEnumerable<(PlannedTransfer Planned, Transfer Transfer)> PlannedTransferSelector(PlannedTransfer plannedTransfer, List<PlannedTransaction> plannedTransactions, DateTimeZone timeZone)
{
var plannedTransaction = plannedTransactions.Single(transaction => transaction.Id == plannedTransfer.PlannedTransactionId);

for (var index = 0; index < plannedTransaction.Count; index++)
{
var startDate = plannedTransaction.StartTime.InZone(timeZone);
var startTime = plannedTransfer.BookedAt;
var startDateTime = new LocalDateTime(startDate.Year, startDate.Month, startDate.Day, startTime.Hour, startTime.Minute);
for (var i = 0; i <= index; i++)
{
startDateTime += plannedTransaction.Period;
}

var instant = startDateTime.InZoneStrictly(timeZone).ToInstant();

var transfer = new Transfer
{
Id = plannedTransfer.Id,
CreatedAt = plannedTransfer.CreatedAt,
OwnerId = plannedTransfer.OwnerId,
CreatedByUserId = plannedTransfer.CreatedByUserId,
ModifiedAt = plannedTransfer.ModifiedAt,
ModifiedByUserId = plannedTransfer.ModifiedByUserId,
TransactionId = plannedTransfer.PlannedTransactionId,
SourceAmount = plannedTransfer.SourceAmount,
SourceAccountId = plannedTransfer.SourceAccountId ?? default,
TargetAmount = plannedTransfer.TargetAmount,
TargetAccountId = plannedTransfer.TargetAccountId ?? default,
BankReference = null,
ExternalReference = null,
InternalReference = null,
Order = plannedTransfer.Order,
BookedAt = instant,
ValuedAt = null,
};

yield return (plannedTransfer, transfer);
}
}

private void OnPropertyChanging(object? sender, PropertyChangingEventArgs e)
{
if (e.PropertyName is nameof(SelectedAccounts))
Expand All @@ -205,6 +272,11 @@ private async void OnPropertyChanged(object? sender, PropertyChangedEventArgs e)
await RefreshAsync();
}

if (e.PropertyName is nameof(IncludeProjections))
{
await RefreshAsync();
}

if (!IsBusy && e.PropertyName is nameof(SelectedCurrency))
{
await RefreshAsync();
Expand Down
Loading

0 comments on commit b78e025

Please sign in to comment.