Compare commits

...

4 Commits

17 changed files with 569 additions and 74 deletions

View File

@@ -27,7 +27,7 @@
<div class="d-flex justify-content-end gap-2">
<button class="btn btn-success" @onclick="Save"
disabled="@(!CanSave)"><i class="bi bi-arrow-left-right"></i> @(EditEntry != null ? "Speichern" : "Umbuchen")</button>
disabled="@(!CanSave)"><i class="bi bi-arrow-left-right"></i> @(EditEntry != null ? "Speichern" : "Hinzufügen")</button>
<button class="btn btn-outline-secondary" @onclick="Cancel"><i class="bi bi-x-lg"></i> Abbrechen</button>
</div>
</div>

View File

@@ -22,7 +22,7 @@
<div class="dialog-content" @onclick:stopPropagation="true">
<h5>Über Dümpelkas &middot; Version @AppVersion</h5>
<p class="mb-2">Entwickler: Andre Beging</p>
<p class="mb-3">E-Mail: <a href="mailto:mail@beging.de" style="color: white;">mail@beging.de</a></p>
<p class="mb-3">E-Mail: <a href="mailto:mail@beging.de" style="color: var(--color-text);">mail@beging.de</a></p>
<div class="d-flex justify-content-end">
<button type="button" class="btn btn-outline-secondary" @onclick="CloseAboutDialog">
<i class="bi bi-x-lg"></i> Schließen

View File

@@ -39,8 +39,8 @@
<i class="bi bi-file-earmark-pdf"></i> PDF
</button>
|
<button class="btn btn-nav @(showCurrentYearOnly ? "btn-primary" : "btn-outline-secondary")" @onclick="ToggleYearFilter">
<i class="bi bi-funnel"></i> @(showCurrentYearOnly ? $"Nur {DateTime.Now.Year}" : "Alle Buchungen")
<button class="btn btn-nav btn-primary" @onclick="OpenYearFilterDialog">
<i class="bi bi-funnel"></i> Ansicht<br>@GetFilterLabel()
</button>
</div>
@@ -56,21 +56,21 @@
</div>
<div class="text-end">
<small class="text-muted">Einnahmen</small>
<div class="amount-positive">@FormatAmount(showCurrentYearOnly ? balance.CurrentYearIncome : balance.TotalIncome)</div>
<div class="amount-positive">@FormatAmount(selectedYear.HasValue ? balance.CurrentYearIncome : balance.TotalIncome)</div>
</div>
<div class="text-end">
<small class="text-muted">Ausgaben</small>
<div class="amount-negative">@FormatAmount(showCurrentYearOnly ? balance.CurrentYearExpense : balance.TotalExpense)</div>
<div class="amount-negative">@FormatAmount(selectedYear.HasValue ? balance.CurrentYearExpense : balance.TotalExpense)</div>
</div>
</div>
</div>
@if (showCurrentYearOnly)
@if (selectedYear.HasValue)
{
<div class="summary-section">
<div class="summary-flex">
<div>
<small class="text-muted">Übertrag von @(DateTime.Now.Year - 1)</small>
<small class="text-muted">Übertrag von @(selectedYear.Value - 1)</small>
<div class="d-flex align-items-center gap-1">
<span class="fw-bold">@FormatAmount(balance.CarryoverBalance)</span>
<button class="btn-edit-pen" @onclick="() => showEditCarryover = true" title="Übertrag bearbeiten">
@@ -79,7 +79,7 @@
</div>
</div>
<div class="text-end">
<small class="text-muted">Umsätze @DateTime.Now.Year</small>
<small class="text-muted">Umsätze @selectedYear.Value</small>
<div class="fw-bold @(balance.CurrentYearIncome - balance.CurrentYearExpense >= 0 ? "amount-positive" : "amount-negative")">
@FormatAmount(balance.CurrentYearIncome - balance.CurrentYearExpense)
</div>
@@ -179,3 +179,29 @@
OnCancel="() => editingTransferEntry = null" />
}
@if (showYearFilterDialog)
{
<div class="dialog-backdrop" @onclick="CloseYearFilterDialog">
<div class="dialog-content" @onclick:stopPropagation="true">
<h5>Filter auswählen</h5>
<p class="text-muted mb-3">Wähle ein Jahr oder alle Buchungen.</p>
<div class="filter-options-grid">
<button class="btn @(selectedYear.HasValue ? "btn-outline-secondary" : "btn-primary")" @onclick="() => SelectFilterYear(null)">
Alle Buchungen
</button>
@foreach (var year in availableYears)
{
<button class="btn @(selectedYear == year ? "btn-primary" : "btn-outline-secondary")" @onclick="() => SelectFilterYear(year)">
@year
</button>
}
</div>
<div class="d-flex justify-content-end mt-3">
<button class="btn btn-outline-secondary" @onclick="CloseYearFilterDialog">
<i class="bi bi-x-lg"></i> Schließen
</button>
</div>
</div>
</div>
}

View File

@@ -21,7 +21,9 @@ public partial class AccountDetail
private bool showAddTransfer;
private bool showEditName;
private bool showEditCarryover;
private bool showCurrentYearOnly = true;
private bool showYearFilterDialog;
private int? selectedYear = DateTime.Now.Year;
private List<int> availableYears = [];
private int? confirmDeleteEntryId;
private string? confirmDeleteEntryTitle;
@@ -56,14 +58,26 @@ public partial class AccountDetail
private async Task LoadAll()
{
account = await AccountService.GetAccountAsync(AccountId);
balance = await BalanceQueryService.GetAccountBalanceAsync(AccountId);
entries = await EntryService.GetEntriesAsync(AccountId, showCurrentYearOnly);
balance = await BalanceQueryService.GetAccountBalanceAsync(AccountId, selectedYear);
entries = await EntryService.GetEntriesAsync(AccountId, selectedYear);
availableYears = await EntryService.GetEntryYearsAsync(AccountId);
}
private async Task ToggleYearFilter()
private void OpenYearFilterDialog()
{
showCurrentYearOnly = !showCurrentYearOnly;
entries = await EntryService.GetEntriesAsync(AccountId, showCurrentYearOnly);
showYearFilterDialog = true;
}
private void CloseYearFilterDialog()
{
showYearFilterDialog = false;
}
private async Task SelectFilterYear(int? year)
{
selectedYear = year;
showYearFilterDialog = false;
await LoadAll();
}
#endregion
@@ -79,7 +93,7 @@ public partial class AccountDetail
private async Task HandleSaveCarryover(decimal newAmount)
{
await AccountService.UpdateCarryoverAsync(AccountId, newAmount);
await AccountService.UpdateCarryoverAsync(AccountId, newAmount, selectedYear);
showEditCarryover = false;
await LoadAll();
}
@@ -164,8 +178,8 @@ public partial class AccountDetail
private async Task HandleExport()
{
var pdf = await PdfStatementService.GenerateStatementAsync(AccountId, showCurrentYearOnly);
var suffix = showCurrentYearOnly ? $"_{DateTime.Now.Year}" : "_Gesamt";
var pdf = await PdfStatementService.GenerateStatementAsync(AccountId, selectedYear);
var suffix = selectedYear.HasValue ? $"_{selectedYear.Value}" : "_Gesamt";
savedPdfPath = await FileSaveService.SaveFileAsync(pdf, $"{account?.Name}{suffix}.pdf");
}
@@ -190,5 +204,7 @@ public partial class AccountDetail
private static string FormatAmount(decimal amount) => $"{amount:N2} €";
private string GetFilterLabel() => selectedYear?.ToString() ?? "Alle";
#endregion
}

View File

@@ -4,6 +4,7 @@
@inject ISettingsService SettingsService
@inject IPdfStatementService PdfStatementService
@inject IFileSaveService FileSaveService
@inject IEntryService EntryService
@inject NavigationManager NavigationManager
<div class="container-fluid">
@@ -34,6 +35,13 @@
<button class="btn-nav btn-dark" @onclick="HandleDashboardExportAsync">
<i class="bi bi-file-earmark-pdf"></i> PDF
</button>
|
<button class="btn btn-nav btn-primary" @onclick="OpenYearFilterDialog">
<i class="bi bi-funnel"></i> Ansicht<br>@GetFilterLabel()
</button>
<button class="btn btn-nav btn-secondary" @onclick="ToggleThemeAsync" title="Farbmodus wechseln">
<i class="@ThemeButtonIconClass"></i> Modus<br>@ThemeButtonLabel
</button>
</div>
@if (accounts != null && accounts.Any())
@@ -107,3 +115,29 @@
OnCancel="CancelRestoreConfirm" />
}
@if (showYearFilterDialog)
{
<div class="dialog-backdrop" @onclick="CloseYearFilterDialog">
<div class="dialog-content" @onclick:stopPropagation="true">
<h5>Filter auswählen</h5>
<p class="text-muted mb-3">Wähle ein Jahr oder alle Buchungen.</p>
<div class="filter-options-grid">
<button class="btn @(selectedYear.HasValue ? "btn-outline-secondary" : "btn-primary")" @onclick="() => SelectFilterYear(null)">
Alle Buchungen
</button>
@foreach (var year in availableYears)
{
<button class="btn @(selectedYear == year ? "btn-primary" : "btn-outline-secondary")" @onclick="() => SelectFilterYear(year)">
@year
</button>
}
</div>
<div class="d-flex justify-content-end mt-3">
<button class="btn btn-outline-secondary" @onclick="CloseYearFilterDialog">
<i class="bi bi-x-lg"></i> Schließen
</button>
</div>
</div>
</div>
}

View File

@@ -1,5 +1,7 @@
using System.Globalization;
using Duempelkas.App.Services.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
namespace Duempelkas.App.Pages;
@@ -11,10 +13,14 @@ public partial class Dashboard
private bool showAddAccount;
private bool showEditClubName;
private bool showRestoreConfirm;
private bool showYearFilterDialog;
private int? selectedYear = DateTime.Now.Year;
private List<int> availableYears = [];
private string clubName = string.Empty;
private string? operationMessage;
private string operationMessageClass = "alert-info";
private string? savedPdfPath;
private string currentTheme = "light";
#endregion
@@ -31,16 +37,42 @@ public partial class Dashboard
protected override async Task OnInitializedAsync()
{
await LoadClubName();
await LoadAccounts();
await LoadAll();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender)
{
return;
}
try
{
currentTheme = await JS.InvokeAsync<string>("duempelkasThemeGetCurrentTheme");
}
catch (JSException)
{
// Keep default light mode when JS interop is not ready or unavailable.
currentTheme = "light";
}
StateHasChanged();
}
#endregion
#region Data Loading
private async Task LoadAll()
{
await LoadAccounts();
availableYears = await EntryService.GetAllEntryYearsAsync();
}
private async Task LoadAccounts()
{
accounts = await AccountService.GetAllAccountsAsync();
accounts = await AccountService.GetAllAccountsAsync(selectedYear);
}
private async Task LoadClubName()
@@ -56,7 +88,7 @@ public partial class Dashboard
{
await AccountService.CreateAccountAsync(name);
showAddAccount = false;
await LoadAccounts();
await LoadAll();
}
private async Task HandleSaveClubName(string newName)
@@ -104,8 +136,26 @@ public partial class Dashboard
private async Task HandleDashboardExportAsync()
{
var pdf = await PdfStatementService.GenerateDashboardStatementAsync();
savedPdfPath = await FileSaveService.SaveFileAsync(pdf, $"{DisplayClubName}_Übersicht.pdf");
var pdf = await PdfStatementService.GenerateDashboardStatementAsync(selectedYear);
var suffix = selectedYear.HasValue ? $"_{selectedYear.Value}" : "_Gesamt";
savedPdfPath = await FileSaveService.SaveFileAsync(pdf, $"{DisplayClubName}_Übersicht{suffix}.pdf");
}
private void OpenYearFilterDialog()
{
showYearFilterDialog = true;
}
private void CloseYearFilterDialog()
{
showYearFilterDialog = false;
}
private async Task SelectFilterYear(int? year)
{
selectedYear = year;
showYearFilterDialog = false;
await LoadAll();
}
private async Task HandleOpenSavedPdf()
@@ -138,5 +188,26 @@ public partial class Dashboard
return amount.ToString("N2", CultureInfo.GetCultureInfo("de-DE")) + " €";
}
private string GetFilterLabel() => selectedYear?.ToString() ?? "Alle";
private string ThemeButtonLabel => currentTheme == "dark" ? "Hell" : "Dunkel";
private string ThemeButtonIconClass => currentTheme == "dark" ? "bi bi-sun" : "bi bi-moon-stars";
private async Task ToggleThemeAsync()
{
try
{
currentTheme = await JS.InvokeAsync<string>("duempelkasThemeToggleTheme");
}
catch (JSException)
{
currentTheme = currentTheme == "dark" ? "light" : "dark";
}
}
[Inject]
private IJSRuntime JS { get; set; } = default!;
#endregion
}

View File

@@ -5,9 +5,11 @@ namespace Duempelkas.App.Services;
public interface IAccountService
{
Task<List<AccountSummaryDto>> GetAllAccountsAsync();
Task<List<AccountSummaryDto>> GetAllAccountsAsync(int? year);
Task<AccountSummaryDto> GetAccountAsync(int accountId);
Task<AccountSummaryDto> CreateAccountAsync(string name);
Task RenameAccountAsync(int accountId, string newName);
Task UpdateCarryoverAsync(int accountId, decimal carryoverBalance);
Task UpdateCarryoverAsync(int accountId, decimal carryoverBalance, int? year);
Task DeleteAccountAsync(int accountId);
}

View File

@@ -4,5 +4,5 @@ namespace Duempelkas.App.Services;
public interface IBalanceQueryService
{
Task<AccountBalanceDto> GetAccountBalanceAsync(int accountId);
Task<AccountBalanceDto> GetAccountBalanceAsync(int accountId, int? year = null);
}

View File

@@ -5,7 +5,10 @@ namespace Duempelkas.App.Services;
public interface IEntryService
{
Task<List<EntryDto>> GetEntriesAsync(int accountId, int? year);
Task<List<EntryDto>> GetEntriesAsync(int accountId, bool currentYearOnly);
Task<List<int>> GetEntryYearsAsync(int accountId);
Task<List<int>> GetAllEntryYearsAsync();
Task<EntryDto> CreateEntryAsync(int accountId, EntryType type, DateTime date, string title, decimal amount);
Task CreateTransferAsync(int sourceAccountId, int targetAccountId, DateTime date, string title, decimal amount);
Task DeleteEntryAsync(int entryId);

View File

@@ -2,6 +2,8 @@ namespace Duempelkas.App.Services;
public interface IPdfStatementService
{
Task<byte[]> GenerateStatementAsync(int accountId, int? year);
Task<byte[]> GenerateStatementAsync(int accountId, bool currentYearOnly);
Task<byte[]> GenerateDashboardStatementAsync();
Task<byte[]> GenerateDashboardStatementAsync(int? year);
}

View File

@@ -1,9 +1,19 @@
/* Duempelkas App Styles Dark Mode */
/* Duempelkas App Styles */
:root {
--color-income: #4ade80;
--color-expense: #f87171;
--color-transfer: #60a5fa;
--color-bg: #ddd;
--color-surface: #ffffff;
--color-surface-hover: #f1f5f9;
--color-border: #d9e2ef;
--color-text: #0f172a;
--color-text-muted: #64748b;
--color-accent: #4f46e5;
}
html[data-ui-theme="dark"] {
--color-bg: #1a1a2e;
--color-surface: #16213e;
--color-surface-hover: #1e2d4a;
@@ -138,6 +148,16 @@ html, body {
margin-bottom: 0.5rem !important;
}
.filter-options-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
gap: 0.5rem;
}
.filter-options-grid .btn {
justify-content: center;
}
/* Navbar */
.app-navbar {
background-color: var(--color-surface);
@@ -301,7 +321,7 @@ html, body {
.btn-dark {
background-color: #334155;
border-color: #475569;
color: var(--color-text);
color: #f8fafc;
}
.btn-dark:hover {
@@ -309,6 +329,12 @@ html, body {
border-color: #64748b;
}
html[data-ui-theme="light"] .btn-dark {
background-color: #334155;
border-color: #334155;
color: #f8fafc;
}
/* Table */
.table {
--bs-table-bg: transparent;

View File

@@ -1,9 +1,113 @@
<!DOCTYPE html>
<html lang="de" data-bs-theme="dark">
<html lang="de">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="/" />
<script>
(function () {
function getCookie(name) {
var parts = document.cookie ? document.cookie.split(';') : [];
for (var i = 0; i < parts.length; i++) {
var part = parts[i].trim();
if (part.indexOf(name + '=') === 0) {
return decodeURIComponent(part.substring(name.length + 1));
}
}
return null;
}
function setCookie(name, value) {
document.cookie = name + '=' + encodeURIComponent(value) + '; path=/; max-age=31536000; samesite=lax';
}
function getStoredTheme() {
try {
var fromStorage = localStorage.getItem('duempelkas-theme');
if (fromStorage === 'light' || fromStorage === 'dark') {
return fromStorage;
}
} catch (_) {
// Ignore storage access issues and fall back to cookies/system.
}
var fromCookie = getCookie('duempelkas-theme');
if (fromCookie === 'light' || fromCookie === 'dark') {
return fromCookie;
}
return null;
}
function detectSystemTheme() {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark';
}
return 'light';
}
function normalizeTheme(value) {
return value === 'dark' ? 'dark' : 'light';
}
function applyTheme(theme, persist) {
var resolved = normalizeTheme(theme);
document.documentElement.setAttribute('data-ui-theme', resolved);
document.documentElement.setAttribute('data-bs-theme', resolved);
if (document.body) {
document.body.setAttribute('data-ui-theme', resolved);
document.body.setAttribute('data-bs-theme', resolved);
}
if (persist) {
try {
localStorage.setItem('duempelkas-theme', resolved);
} catch (_) {
// Ignore storage access issues and keep cookie as fallback.
}
setCookie('duempelkas-theme', resolved);
}
return resolved;
}
var initialTheme = getStoredTheme() || detectSystemTheme() || 'light';
applyTheme(initialTheme, false);
var duempelkasThemeGetCurrentTheme = function () {
var current = document.documentElement.getAttribute('data-ui-theme');
return normalizeTheme(current);
};
var duempelkasThemeSetTheme = function (theme) {
return applyTheme(theme, true);
};
var duempelkasThemeToggleTheme = function () {
var current = document.documentElement.getAttribute('data-ui-theme');
var next = current === 'dark' ? 'light' : 'dark';
return applyTheme(next, true);
};
globalThis.duempelkasThemeGetCurrentTheme = duempelkasThemeGetCurrentTheme;
globalThis.duempelkasThemeSetTheme = duempelkasThemeSetTheme;
globalThis.duempelkasThemeToggleTheme = duempelkasThemeToggleTheme;
window.duempelkasThemeGetCurrentTheme = duempelkasThemeGetCurrentTheme;
window.duempelkasThemeSetTheme = duempelkasThemeSetTheme;
window.duempelkasThemeToggleTheme = duempelkasThemeToggleTheme;
// Keep object-style API for compatibility with older calls.
window.duempelkasTheme = {
getCurrentTheme: duempelkasThemeGetCurrentTheme,
setTheme: duempelkasThemeSetTheme,
toggleTheme: duempelkasThemeToggleTheme
};
})();
</script>
<title>Dümpelkas Kassenbuch</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet"

View File

@@ -12,6 +12,8 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="QuestPDF" Version="*" />
<PackageReference Include="SkiaSharp" Version="2.88.9" />
<PackageReference Include="SkiaSharp.HarfBuzz" Version="2.88.9" />
</ItemGroup>
<ItemGroup>

View File

@@ -13,16 +13,60 @@ public class AccountService : IAccountService
public AccountService(IDbContextFactory<FinanceDbContext> dbFactory) => _dbFactory = dbFactory;
public async Task<List<AccountSummaryDto>> GetAllAccountsAsync()
public Task<List<AccountSummaryDto>> GetAllAccountsAsync()
{
return GetAllAccountsAsync(null);
}
public async Task<List<AccountSummaryDto>> GetAllAccountsAsync(int? year)
{
await using var db = await _dbFactory.CreateDbContextAsync();
var accounts = await db.Accounts
.Include(a => a.Entries)
.OrderBy(a => a.Name)
.ToListAsync();
return accounts.Select(MapToSummary).ToList();
var entries = db.Entries.Where(e => !e.IsDeleted);
if (year.HasValue)
{
var movementBeforeYearByAccountId = await entries
.Where(e => e.Date.Year < year.Value)
.GroupBy(e => e.AccountId)
.ToDictionaryAsync(
g => g.Key,
g => g.Sum(e => e.Type == EntryType.Income ? e.Amount : -e.Amount));
var movementInYearByAccountId = await entries
.Where(e => e.Date.Year == year.Value)
.GroupBy(e => e.AccountId)
.ToDictionaryAsync(
g => g.Key,
g => g.Sum(e => e.Type == EntryType.Income ? e.Amount : -e.Amount));
return accounts
.Select(account =>
{
var carryoverForYear = account.CarryoverBalance + movementBeforeYearByAccountId.GetValueOrDefault(account.Id);
var totalBalance = carryoverForYear + movementInYearByAccountId.GetValueOrDefault(account.Id);
return new AccountSummaryDto(account.Id, account.Name, carryoverForYear, totalBalance, account.CreatedUtc);
})
.ToList();
}
var movementAllByAccountId = await entries
.GroupBy(e => e.AccountId)
.ToDictionaryAsync(
g => g.Key,
g => g.Sum(e => e.Type == EntryType.Income ? e.Amount : -e.Amount));
return accounts
.Select(account =>
{
var totalBalance = account.CarryoverBalance + movementAllByAccountId.GetValueOrDefault(account.Id);
return new AccountSummaryDto(account.Id, account.Name, account.CarryoverBalance, totalBalance, account.CreatedUtc);
})
.ToList();
}
public async Task<AccountSummaryDto> GetAccountAsync(int accountId)
@@ -34,7 +78,11 @@ public class AccountService : IAccountService
.FirstOrDefaultAsync(a => a.Id == accountId)
?? throw new InvalidOperationException($"Account {accountId} not found.");
return MapToSummary(account);
var totalIncome = account.Entries.Where(e => !e.IsDeleted && e.Type == EntryType.Income).Sum(e => e.Amount);
var totalExpense = account.Entries.Where(e => !e.IsDeleted && e.Type == EntryType.Expense).Sum(e => e.Amount);
var totalBalance = account.CarryoverBalance + totalIncome - totalExpense;
return new AccountSummaryDto(account.Id, account.Name, account.CarryoverBalance, totalBalance, account.CreatedUtc);
}
public async Task<AccountSummaryDto> CreateAccountAsync(string name)
@@ -67,6 +115,27 @@ public class AccountService : IAccountService
await db.SaveChangesAsync();
}
public async Task UpdateCarryoverAsync(int accountId, decimal carryoverBalance, int? year)
{
if (!year.HasValue)
{
await UpdateCarryoverAsync(accountId, carryoverBalance);
return;
}
await using var db = await _dbFactory.CreateDbContextAsync();
var account = await db.Accounts.FindAsync(accountId)
?? throw new InvalidOperationException($"Account {accountId} not found.");
var movementBeforeYear = await db.Entries
.Where(e => e.AccountId == accountId && !e.IsDeleted && e.Date.Year < year.Value)
.SumAsync(e => e.Type == EntryType.Income ? e.Amount : -e.Amount);
account.CarryoverBalance = carryoverBalance - movementBeforeYear;
await db.SaveChangesAsync();
}
public async Task DeleteAccountAsync(int accountId)
{
await using var db = await _dbFactory.CreateDbContextAsync();
@@ -94,12 +163,4 @@ public class AccountService : IAccountService
await db.SaveChangesAsync();
}
private static AccountSummaryDto MapToSummary(Account account)
{
var totalIncome = account.Entries.Where(e => e.Type == EntryType.Income).Sum(e => e.Amount);
var totalExpense = account.Entries.Where(e => e.Type == EntryType.Expense).Sum(e => e.Amount);
var totalBalance = account.CarryoverBalance + totalIncome - totalExpense;
return new AccountSummaryDto(account.Id, account.Name, account.CarryoverBalance, totalBalance, account.CreatedUtc);
}
}

View File

@@ -12,7 +12,7 @@ public class BalanceQueryService : IBalanceQueryService
public BalanceQueryService(IDbContextFactory<FinanceDbContext> dbFactory) => _dbFactory = dbFactory;
public async Task<AccountBalanceDto> GetAccountBalanceAsync(int accountId)
public async Task<AccountBalanceDto> GetAccountBalanceAsync(int accountId, int? year = null)
{
await using var db = await _dbFactory.CreateDbContextAsync();
@@ -21,21 +21,33 @@ public class BalanceQueryService : IBalanceQueryService
.FirstOrDefaultAsync(a => a.Id == accountId)
?? throw new InvalidOperationException($"Konto {accountId} nicht gefunden.");
var currentYear = DateTime.Now.Year;
var selectedYear = year ?? DateTime.Now.Year;
var activeEntries = account.Entries.Where(e => !e.IsDeleted).ToList();
var totalIncome = activeEntries.Where(e => e.Type == EntryType.Income).Sum(e => e.Amount);
var totalExpense = activeEntries.Where(e => e.Type == EntryType.Expense).Sum(e => e.Amount);
var currentYearIncome = activeEntries.Where(e => e.Type == EntryType.Income && e.Date.Year == currentYear).Sum(e => e.Amount);
var currentYearExpense = activeEntries.Where(e => e.Type == EntryType.Expense && e.Date.Year == currentYear).Sum(e => e.Amount);
var totalBalance = account.CarryoverBalance + totalIncome - totalExpense;
var selectedYearIncome = activeEntries
.Where(e => e.Type == EntryType.Income && e.Date.Year == selectedYear)
.Sum(e => e.Amount);
var selectedYearExpense = activeEntries
.Where(e => e.Type == EntryType.Expense && e.Date.Year == selectedYear)
.Sum(e => e.Amount);
var selectedYearCarryover = account.CarryoverBalance + activeEntries
.Where(e => e.Date.Year < selectedYear)
.Sum(e => e.Type == EntryType.Income ? e.Amount : -e.Amount);
var totalBalance = year.HasValue
? selectedYearCarryover + selectedYearIncome - selectedYearExpense
: account.CarryoverBalance + totalIncome - totalExpense;
return new AccountBalanceDto(
account.CarryoverBalance,
year.HasValue ? selectedYearCarryover : account.CarryoverBalance,
totalIncome,
totalExpense,
currentYearIncome,
currentYearExpense,
selectedYearIncome,
selectedYearExpense,
totalBalance);
}
}

View File

@@ -13,14 +13,20 @@ public class EntryService : IEntryService
public EntryService(IDbContextFactory<FinanceDbContext> dbFactory) => _dbFactory = dbFactory;
public async Task<List<EntryDto>> GetEntriesAsync(int accountId, bool currentYearOnly)
public Task<List<EntryDto>> GetEntriesAsync(int accountId, bool currentYearOnly)
{
var year = currentYearOnly ? DateTime.Now.Year : (int?)null;
return GetEntriesAsync(accountId, year);
}
public async Task<List<EntryDto>> GetEntriesAsync(int accountId, int? year)
{
await using var db = await _dbFactory.CreateDbContextAsync();
var query = db.Entries.Where(e => e.AccountId == accountId);
if (currentYearOnly)
query = query.Where(e => e.Date.Year == DateTime.Now.Year);
if (year.HasValue)
query = query.Where(e => e.Date.Year == year.Value);
var entries = await query
.OrderBy(e => e.Date)
@@ -59,6 +65,29 @@ public class EntryService : IEntryService
}).ToList();
}
public async Task<List<int>> GetEntryYearsAsync(int accountId)
{
await using var db = await _dbFactory.CreateDbContextAsync();
return await db.Entries
.Where(e => e.AccountId == accountId)
.Select(e => e.Date.Year)
.Distinct()
.OrderByDescending(y => y)
.ToListAsync();
}
public async Task<List<int>> GetAllEntryYearsAsync()
{
await using var db = await _dbFactory.CreateDbContextAsync();
return await db.Entries
.Select(e => e.Date.Year)
.Distinct()
.OrderByDescending(y => y)
.ToListAsync();
}
public async Task<EntryDto> CreateEntryAsync(int accountId, EntryType type, DateTime date, string title, decimal amount)
{
await using var db = await _dbFactory.CreateDbContextAsync();

View File

@@ -27,19 +27,25 @@ public class PdfStatementService : IPdfStatementService
_settingsService = settingsService;
}
public async Task<byte[]> GenerateStatementAsync(int accountId, bool currentYearOnly)
public Task<byte[]> GenerateStatementAsync(int accountId, bool currentYearOnly)
{
var year = currentYearOnly ? DateTime.Now.Year : (int?)null;
return GenerateStatementAsync(accountId, year);
}
public async Task<byte[]> GenerateStatementAsync(int accountId, int? year)
{
await using var db = await _dbFactory.CreateDbContextAsync();
var account = await db.Accounts.FindAsync(accountId)
?? throw new InvalidOperationException($"Konto {accountId} nicht gefunden.");
var entries = await _entryService.GetEntriesAsync(accountId, currentYearOnly);
var balance = await _balanceQueryService.GetAccountBalanceAsync(accountId);
var entries = await _entryService.GetEntriesAsync(accountId, year);
var balance = await _balanceQueryService.GetAccountBalanceAsync(accountId, year);
var clubName = await _settingsService.GetClubNameAsync() ?? "Mein Verein";
var title = currentYearOnly
? $"{account.Name} Auszug {DateTime.Now.Year}"
var title = year.HasValue
? $"{account.Name} Auszug {year.Value}"
: $"{account.Name} Gesamtauszug";
var document = Document.Create(container =>
@@ -61,12 +67,6 @@ public class PdfStatementService : IPdfStatementService
page.Content().PaddingTop(15).Column(col =>
{
col.Item().PaddingBottom(10).Row(row =>
{
row.RelativeItem().Text("Übertrag:").SemiBold();
row.AutoItem().Text(FormatCurrency(balance.CarryoverBalance)).SemiBold();
});
col.Item().Table(table =>
{
table.ColumnsDefinition(columns =>
@@ -114,9 +114,16 @@ public class PdfStatementService : IPdfStatementService
col.Item().PaddingTop(20).LineHorizontal(1).LineColor(Colors.Grey.Lighten2);
col.Item().PaddingTop(10).Column(summaryCol =>
{
SummaryRow(summaryCol, "Übertrag:", balance.CarryoverBalance);
SummaryRow(summaryCol, "Einnahmen gesamt:", balance.TotalIncome);
SummaryRow(summaryCol, "Ausgaben gesamt:", -balance.TotalExpense);
var incomeValue = year.HasValue ? balance.CurrentYearIncome : balance.TotalIncome;
var expenseValue = year.HasValue ? balance.CurrentYearExpense : balance.TotalExpense;
if (year.HasValue)
{
SummaryRow(summaryCol, $"Übertrag von {year.Value - 1}:", balance.CarryoverBalance);
}
SummaryRow(summaryCol, year.HasValue ? "Einnahmen:" : "Einnahmen gesamt:", incomeValue);
SummaryRow(summaryCol, year.HasValue ? "Ausgaben:" : "Ausgaben gesamt:", -expenseValue);
summaryCol.Item().PaddingTop(5).Row(row =>
{
row.RelativeItem().Text("Saldo:").Bold().FontSize(12);
@@ -139,7 +146,12 @@ public class PdfStatementService : IPdfStatementService
return document.GeneratePdf();
}
public async Task<byte[]> GenerateDashboardStatementAsync()
public Task<byte[]> GenerateDashboardStatementAsync()
{
return GenerateDashboardStatementAsync(null);
}
public async Task<byte[]> GenerateDashboardStatementAsync(int? year)
{
await using var db = await _dbFactory.CreateDbContextAsync();
@@ -162,20 +174,65 @@ public class PdfStatementService : IPdfStatementService
transferByEntryId[transfer.TargetEntryId] = transfer;
}
var entries = await db.Entries
var entriesQuery = db.Entries
.Include(e => e.Account)
.Where(e => !e.IsDeleted)
.Where(e => !e.IsDeleted);
if (year.HasValue)
{
entriesQuery = entriesQuery.Where(e => e.Date.Year == year.Value);
}
var entries = await entriesQuery
.OrderBy(e => e.Date)
.ThenBy(e => e.CreatedUtc)
.ToListAsync();
Dictionary<int, decimal> balanceByAccountId;
Dictionary<int, decimal>? carryoverByAccountId = null;
if (year.HasValue)
{
var movementBeforeYearByAccountId = await db.Entries
.Where(e => !e.IsDeleted && e.Date.Year < year.Value)
.GroupBy(e => e.AccountId)
.ToDictionaryAsync(
g => g.Key,
g => g.Sum(e => e.Type == EntryType.Income ? e.Amount : -e.Amount));
var movementInYearByAccountId = entries
.GroupBy(e => e.AccountId)
.ToDictionary(
g => g.Key,
g => g.Sum(e => e.Type == EntryType.Income ? e.Amount : -e.Amount));
carryoverByAccountId = accounts
.ToDictionary(
a => a.Id,
a => a.CarryoverBalance + movementBeforeYearByAccountId.GetValueOrDefault(a.Id));
balanceByAccountId = accounts
.ToDictionary(
a => a.Id,
a => a.CarryoverBalance
+ movementBeforeYearByAccountId.GetValueOrDefault(a.Id)
+ movementInYearByAccountId.GetValueOrDefault(a.Id));
}
else
{
var movementByAccountId = entries
.GroupBy(e => e.AccountId)
.ToDictionary(
g => g.Key,
g => g.Sum(e => e.Type == EntryType.Income ? e.Amount : -e.Amount));
var totalClubBalance = accounts.Sum(a => a.CarryoverBalance + movementByAccountId.GetValueOrDefault(a.Id));
balanceByAccountId = accounts
.ToDictionary(
a => a.Id,
a => a.CarryoverBalance + movementByAccountId.GetValueOrDefault(a.Id));
}
var totalClubBalance = balanceByAccountId.Values.Sum();
var processedTransferIds = new HashSet<int>();
var rows = new List<DashboardStatementRow>();
@@ -236,7 +293,10 @@ public class PdfStatementService : IPdfStatementService
page.Header().Column(col =>
{
col.Item().Text(clubName).Bold().FontSize(18);
col.Item().Text("Übersicht aller Konten").FontSize(13).FontColor(Colors.Grey.Darken1);
var headerTitle = year.HasValue
? $"Übersicht aller Konten ({year.Value})"
: "Übersicht aller Konten";
col.Item().Text(headerTitle).FontSize(13).FontColor(Colors.Grey.Darken1);
col.Item().PaddingTop(2).Text($"Gesamtvermögen: {FormatCurrency(totalClubBalance)}")
.FontSize(10)
.SemiBold()
@@ -273,6 +333,18 @@ public class PdfStatementService : IPdfStatementService
}
});
if (year.HasValue && carryoverByAccountId is not null)
{
BodyCell(table, string.Empty);
BodyCell(table, string.Empty);
BodyCell(table, $"Übertrag von {year.Value - 1}", alignRight: true);
foreach (var account in accounts)
{
BodyAmountCell(table, carryoverByAccountId.GetValueOrDefault(account.Id));
}
}
foreach (var row in rows)
{
BodyCell(table, row.DisplayId);
@@ -291,6 +363,16 @@ public class PdfStatementService : IPdfStatementService
}
}
}
// Add one summary line with the final balance for each account column.
FooterCell(table, string.Empty);
FooterCell(table, string.Empty);
FooterCell(table, "Kontostand", alignRight: true);
foreach (var account in accounts)
{
FooterAmountCell(table, balanceByAccountId.GetValueOrDefault(account.Id));
}
});
content.Item().PaddingTop(8).AlignRight().Text(text =>
@@ -352,6 +434,31 @@ public class PdfStatementService : IPdfStatementService
.FontColor(amount >= 0 ? Colors.Green.Darken1 : Colors.Red.Darken1);
}
private static void FooterCell(TableDescriptor table, string text, bool alignRight = false)
{
var cell = table.Cell()
.BorderTop(1)
.BorderColor(Colors.Grey.Darken1)
.PaddingTop(5)
.PaddingBottom(2);
var content = alignRight ? cell.AlignRight() : cell;
content.Text(text).SemiBold();
}
private static void FooterAmountCell(TableDescriptor table, decimal amount)
{
table.Cell()
.BorderTop(1)
.BorderColor(Colors.Grey.Darken1)
.PaddingTop(5)
.PaddingBottom(2)
.AlignRight()
.Text(FormatCurrency(amount))
.SemiBold()
.FontColor(amount >= 0 ? Colors.Green.Darken1 : Colors.Red.Darken1);
}
private static int ParseDisplayIdYear(string displayId)
{
var parts = displayId.Split('-');