Farbpalette vorladen lassen

Bootstraper läd jetzt die farbeinstellung sofort und nicht nachträglich

cleanup and rework

PDF switch to HTML

export fix

Colorsystem

Farben für knöpfe hinzugefügt als anpassung

button color

button color primary and secondary change
This commit is contained in:
2026-03-23 22:42:52 +01:00
parent d5649dc189
commit d85f2e0fb3
84 changed files with 4216 additions and 1814 deletions
+26 -36
View File
@@ -1,54 +1,44 @@
<?xml version="1.0" encoding="UTF-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<Application <Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
x:Class="cfs_tracker.App" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui" x:Class="cfs_tracker.App">
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<Application.Resources> <Application.Resources>
<ResourceDictionary> <ResourceDictionary>
<Color x:Key="AppBackground">#0B1A2A</Color>
<Color x:Key="SurfaceBackground">#132235</Color>
<Color x:Key="SurfaceBackgroundAlt">#1A2B40</Color>
<Color x:Key="Border">#2A3E55</Color>
<Color x:Key="TextPrimary">#DCE7F3</Color>
<Color x:Key="TextMuted">#8FA6BC</Color>
<!-- Grundfarben --> <Color x:Key="StateGreen">#4E8B69</Color>
<Color x:Key="AppBackground">#0B1620</Color>
<Color x:Key="PanelBackground">#162330</Color>
<Color x:Key="PanelBackground2">#203041</Color>
<Color x:Key="PanelBorder">#2B3E52</Color>
<Color x:Key="TextPrimary">#D9E6F2</Color>
<Color x:Key="TextMuted">#94A8BC</Color>
<!-- Statusfarben -->
<Color x:Key="StateGreen">#4D8B68</Color>
<Color x:Key="StateYellow">#B89A42</Color> <Color x:Key="StateYellow">#B89A42</Color>
<Color x:Key="StateRed">#A85C5C</Color> <Color x:Key="StateRed">#A85C5C</Color>
<Color x:Key="StateGray">#5C6670</Color> <Color x:Key="StateGray">#1F242B</Color>
<!-- Statustexte -->
<x:String x:Key="StatusGreenText">Grün</x:String> <x:String x:Key="StatusGreenText">Grün</x:String>
<x:String x:Key="StatusYellowText">Gelb</x:String> <x:String x:Key="StatusYellowText">Gelb</x:String>
<x:String x:Key="StatusRedText">Rot</x:String> <x:String x:Key="StatusRedText">Rot</x:String>
<x:String x:Key="StatusGrayText">Grau</x:String> <x:String x:Key="StatusGrayText">Schwarz</x:String>
<Style TargetType="ContentPage"> <Color x:Key="ButtonPrimaryBackground">#355066</Color>
<Setter Property="BackgroundColor" Value="{DynamicResource AppBackground}" /> <Color x:Key="ButtonPrimaryText">#FFFFFF</Color>
</Style> <Color x:Key="ButtonSecondaryBackground">#355055</Color>
<Color x:Key="ButtonSecondaryText">#DCE7F3</Color>
<Style TargetType="Label"> <Style x:Key="PrimaryButtonStyle" TargetType="Button">
<Setter Property="TextColor" Value="{DynamicResource TextPrimary}" /> <Setter Property="BackgroundColor" Value="{DynamicResource ButtonPrimaryBackground}" />
</Style> <Setter Property="TextColor" Value="{DynamicResource ButtonPrimaryText}" />
<Style TargetType="Button">
<Setter Property="CornerRadius" Value="12" /> <Setter Property="CornerRadius" Value="12" />
<Setter Property="Padding" Value="12,10" /> <Setter Property="Padding" Value="14,10" />
<Setter Property="BackgroundColor" Value="{DynamicResource PanelBackground2}" />
<Setter Property="TextColor" Value="{DynamicResource TextPrimary}" />
</Style> </Style>
<Style TargetType="Border"> <Style x:Key="SecondaryButtonStyle" TargetType="Button">
<Setter Property="BackgroundColor" Value="{DynamicResource PanelBackground}" /> <Setter Property="BackgroundColor" Value="{DynamicResource ButtonSecondaryBackground}" />
<Setter Property="Stroke" Value="{DynamicResource PanelBorder}" /> <Setter Property="TextColor" Value="{DynamicResource ButtonSecondaryText}" />
<Setter Property="StrokeThickness" Value="1" /> <Setter Property="CornerRadius" Value="12" />
<Setter Property="StrokeShape" Value="RoundRectangle 12" /> <Setter Property="Padding" Value="14,10" />
</Style> </Style>
</ResourceDictionary> </ResourceDictionary>
</Application.Resources> </Application.Resources>
</Application> </Application>
+106 -9
View File
@@ -1,34 +1,131 @@
using cfs_tracker.Services; using cfs_tracker.Services;
using System.Diagnostics;
namespace cfs_tracker; namespace cfs_tracker;
public partial class App : Application public partial class App : Application
{ {
private readonly IServiceProvider _serviceProvider; private readonly IServiceProvider _serviceProvider;
private readonly AppBootstrapService _bootstrapService;
public App(IServiceProvider serviceProvider) private bool _startupTriggered;
public App(IServiceProvider serviceProvider, AppBootstrapService bootstrapService)
{ {
InitializeComponent(); InitializeComponent();
_serviceProvider = serviceProvider; _serviceProvider = serviceProvider;
_bootstrapService = bootstrapService;
UserAppTheme = AppTheme.Dark;
} }
protected override Window CreateWindow(IActivationState? activationState) protected override Window CreateWindow(IActivationState? activationState)
{ {
var shell = _serviceProvider.GetRequiredService<AppShell>(); var window = new Window(CreateLoadingPage());
var appearanceService = _serviceProvider.GetRequiredService<AppearanceService>();
MainThread.BeginInvokeOnMainThread(async () => if (!_startupTriggered)
{
_startupTriggered = true;
_ = InitializeAppAsync(window);
}
return window;
}
private async Task InitializeAppAsync(Window window)
{ {
try try
{ {
await appearanceService.InitializeAsync(); await _bootstrapService.InitializeAsync();
var shell = _serviceProvider.GetRequiredService<AppShell>();
await MainThread.InvokeOnMainThreadAsync(() =>
{
window.Page = shell;
});
} }
catch (Exception ex) catch (Exception ex)
{ {
System.Diagnostics.Debug.WriteLine(ex); Debug.WriteLine($"App bootstrap failed: {ex}");
}
});
return new Window(shell); await MainThread.InvokeOnMainThreadAsync(() =>
{
window.Page = CreateErrorPage(ex);
});
}
}
private static Page CreateLoadingPage()
{
return new ContentPage
{
Title = "Laden",
BackgroundColor = Color.FromArgb("#0B1A2A"),
Content = new Grid
{
Padding = 24,
Children =
{
new VerticalStackLayout
{
Spacing = 16,
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center,
Children =
{
new ActivityIndicator
{
IsRunning = true,
WidthRequest = 48,
HeightRequest = 48,
Color = Color.FromArgb("#DCE7F3")
},
new Label
{
Text = "App wird geladen ...",
FontSize = 20,
HorizontalTextAlignment = TextAlignment.Center,
TextColor = Color.FromArgb("#DCE7F3")
}
}
}
}
}
};
}
private static Page CreateErrorPage(Exception ex)
{
return new ContentPage
{
Title = "Startfehler",
BackgroundColor = Color.FromArgb("#0B1A2A"),
Content = new ScrollView
{
Content = new VerticalStackLayout
{
Padding = 24,
Spacing = 16,
Children =
{
new Label
{
Text = "Fehler beim Starten der App",
FontSize = 24,
FontAttributes = FontAttributes.Bold,
TextColor = Color.FromArgb("#FFB4B4")
},
new Label
{
Text = ex.ToString(),
FontSize = 14,
TextColor = Color.FromArgb("#DCE7F3")
}
}
}
}
};
} }
} }
+20 -20
View File
@@ -1,37 +1,37 @@
<?xml version="1.0" encoding="UTF-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<Shell <Shell
x:Class="cfs_tracker.AppShell" x:Class="cfs_tracker.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:views="clr-namespace:cfs_tracker.Views" xmlns:views="clr-namespace:cfs_tracker.Views"
BackgroundColor="{StaticResource AppBackground}"> Shell.BackgroundColor="{DynamicResource ShellBackground}"
Shell.ForegroundColor="{DynamicResource ShellForeground}"
Shell.TitleColor="{DynamicResource ShellTitle}"
Shell.UnselectedColor="{DynamicResource ShellUnselected}"
Shell.TabBarBackgroundColor="{DynamicResource TabBarBackground}"
Shell.TabBarForegroundColor="{DynamicResource TabBarForeground}"
Shell.TabBarTitleColor="{DynamicResource TabBarTitle}"
Shell.TabBarUnselectedColor="{DynamicResource TabBarUnselected}">
<TabBar Route="MainTabs"> <TabBar>
<ShellContent Title="Tag"
<ShellContent Route="day"
Title="Tag"
Route="DayTab"
ContentTemplate="{DataTemplate views:DayPage}" /> ContentTemplate="{DataTemplate views:DayPage}" />
<ShellContent <ShellContent Title="Woche"
Title="Woche" Route="week"
Route="WeekTab"
ContentTemplate="{DataTemplate views:WeekPage}" /> ContentTemplate="{DataTemplate views:WeekPage}" />
<ShellContent <ShellContent Title="Monat"
Title="Monat" Route="month"
Route="MonthTab"
ContentTemplate="{DataTemplate views:MonthPage}" /> ContentTemplate="{DataTemplate views:MonthPage}" />
<ShellContent <ShellContent Title="Jahr"
Title="Jahr" Route="year"
Route="YearTab"
ContentTemplate="{DataTemplate views:YearPage}" /> ContentTemplate="{DataTemplate views:YearPage}" />
<ShellContent <ShellContent Title="Optionen"
Title="Optionen" Route="options"
Route="OptionsTab"
ContentTemplate="{DataTemplate views:OptionsPage}" /> ContentTemplate="{DataTemplate views:OptionsPage}" />
</TabBar> </TabBar>
</Shell> </Shell>
-48
View File
@@ -1,48 +0,0 @@
using System.Globalization;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Graphics;
namespace cfs_tracker.Converters;
public class HexToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string hex && !string.IsNullOrWhiteSpace(hex))
{
try
{
return Color.FromArgb(hex);
}
catch
{
}
}
return Color.FromArgb("#203041");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is Color color)
return color.ToArgbHex();
return "#203041";
}
}
public static class ColorExtensions
{
public static string ToArgbHex(this Color color)
{
byte a = (byte)(color.Alpha * 255);
byte r = (byte)(color.Red * 255);
byte g = (byte)(color.Green * 255);
byte b = (byte)(color.Blue * 255);
if (a < 255)
return $"#{a:X2}{r:X2}{g:X2}{b:X2}";
return $"#{r:X2}{g:X2}{b:X2}";
}
}
+79 -54
View File
@@ -11,10 +11,41 @@ public class ActivityRepository
_database = database; _database = database;
} }
public async Task<List<ActivityItem>> GetAllAsync() public async Task EnsureDefaultsAsync()
{ {
await _database.InitAsync(); await _database.InitAsync();
if (await _database.Connection.Table<ActivityItem>().CountAsync() > 0)
return;
var defaults = new[]
{
"Keine Tätigkeit",
"Ruhen / Liegen",
"Lesen",
"Haushalt",
"Einkaufen",
"Gespräch",
"Spazieren",
"Computer / Handy",
"Arzt / Termin",
"Verwaltung"
};
for (var i = 0; i < defaults.Length; i++)
{
await _database.Connection.InsertAsync(new ActivityItem
{
Name = defaults[i],
SortOrder = i,
IsActive = true
});
}
}
public async Task<List<ActivityItem>> GetAllAsync()
{
await _database.InitAsync();
return await _database.Connection.Table<ActivityItem>() return await _database.Connection.Table<ActivityItem>()
.OrderBy(x => x.SortOrder) .OrderBy(x => x.SortOrder)
.ThenBy(x => x.Name) .ThenBy(x => x.Name)
@@ -24,7 +55,6 @@ public class ActivityRepository
public async Task<List<ActivityItem>> GetActiveAsync() public async Task<List<ActivityItem>> GetActiveAsync()
{ {
await _database.InitAsync(); await _database.InitAsync();
return await _database.Connection.Table<ActivityItem>() return await _database.Connection.Table<ActivityItem>()
.Where(x => x.IsActive) .Where(x => x.IsActive)
.OrderBy(x => x.SortOrder) .OrderBy(x => x.SortOrder)
@@ -32,75 +62,61 @@ public class ActivityRepository
.ToListAsync(); .ToListAsync();
} }
public async Task<ActivityItem?> GetByIdAsync(int id)
{
await _database.InitAsync();
return await _database.Connection.Table<ActivityItem>()
.FirstOrDefaultAsync(x => x.Id == id);
}
public async Task<Dictionary<int, string>> GetNameMapAsync() public async Task<Dictionary<int, string>> GetNameMapAsync()
{ {
var all = await GetAllAsync(); var items = await GetAllAsync();
return all.ToDictionary(x => x.Id, x => x.Name); return items.ToDictionary(x => x.Id, x => x.Name);
} }
public async Task EnsureDefaultsAsync() public async Task<int> AddAsync(string name)
{ {
await _database.InitAsync(); await _database.InitAsync();
var cleanName = NormalizeName(name);
if ((await _database.Connection.Table<ActivityItem>().CountAsync()) > 0) var existing = await _database.Connection.Table<ActivityItem>().ToListAsync();
return; if (existing.Any(x => string.Equals(x.Name, cleanName, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"Die Tätigkeit '{cleanName}' existiert bereits.");
var defaults = new List<ActivityItem> var nextSort = existing.Count == 0 ? 0 : existing.Max(x => x.SortOrder) + 1;
var item = new ActivityItem
{ {
new() { Name = "Lesen", SortOrder = 0, IsActive = true }, Name = cleanName,
new() { Name = "Sport", SortOrder = 1, IsActive = true }, SortOrder = nextSort,
new() { Name = "Haushalt", SortOrder = 2, IsActive = true }, IsActive = true
new() { Name = "Einkaufen", SortOrder = 3, IsActive = true },
new() { Name = "Ausgehen", SortOrder = 4, IsActive = true },
new() { Name = "Verwaltung", SortOrder = 5, IsActive = true },
new() { Name = "Gespräch", SortOrder = 6, IsActive = true },
new() { Name = "Spazieren gehen", SortOrder = 7, IsActive = true },
new() { Name = "Fernsehen", SortOrder = 8, IsActive = true },
new() { Name = "Ruhen / Liegen", SortOrder = 9, IsActive = true }
}; };
foreach (var item in defaults)
await _database.Connection.InsertAsync(item); await _database.Connection.InsertAsync(item);
} return item.Id;
public async Task AddAsync(string name)
{
await _database.InitAsync();
var maxSort = 0;
var all = await _database.Connection.Table<ActivityItem>().ToListAsync();
if (all.Count > 0)
maxSort = all.Max(x => x.SortOrder) + 1;
await _database.Connection.InsertAsync(new ActivityItem
{
Name = name.Trim(),
SortOrder = maxSort,
IsActive = true
});
} }
public async Task RenameAsync(int id, string newName) public async Task RenameAsync(int id, string newName)
{ {
await _database.InitAsync(); await _database.InitAsync();
var cleanName = NormalizeName(newName);
var item = await _database.Connection.Table<ActivityItem>() var all = await _database.Connection.Table<ActivityItem>().ToListAsync();
.FirstOrDefaultAsync(x => x.Id == id); if (all.Any(x => x.Id != id && string.Equals(x.Name, cleanName, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"Die Tätigkeit '{cleanName}' existiert bereits.");
var item = all.FirstOrDefault(x => x.Id == id);
if (item is null) if (item is null)
return; return;
item.Name = newName.Trim(); item.Name = cleanName;
await _database.Connection.UpdateAsync(item); await _database.Connection.UpdateAsync(item);
} }
public async Task SetActiveAsync(int id, bool isActive) public async Task SetActiveAsync(int id, bool isActive)
{ {
await _database.InitAsync(); await _database.InitAsync();
var item = await GetByIdAsync(id);
var item = await _database.Connection.Table<ActivityItem>()
.FirstOrDefaultAsync(x => x.Id == id);
if (item is null) if (item is null)
return; return;
@@ -111,25 +127,34 @@ public class ActivityRepository
public async Task<bool> HasUsageAsync(int activityId) public async Task<bool> HasUsageAsync(int activityId)
{ {
await _database.InitAsync(); await _database.InitAsync();
return await _database.Connection.Table<HealthEntry>()
var count = await _database.Connection.Table<HealthEntry>()
.Where(x => x.ActivityId == activityId) .Where(x => x.ActivityId == activityId)
.CountAsync(); .CountAsync() > 0;
return count > 0;
} }
public async Task DeleteIfUnusedAsync(int activityId) public async Task DeleteOrDeactivateAsync(int activityId)
{ {
await _database.InitAsync(); await _database.InitAsync();
var item = await GetByIdAsync(activityId);
if (await HasUsageAsync(activityId)) if (item is null)
return; return;
var item = await _database.Connection.Table<ActivityItem>() if (await HasUsageAsync(activityId))
.FirstOrDefaultAsync(x => x.Id == activityId); {
item.IsActive = false;
await _database.Connection.UpdateAsync(item);
return;
}
if (item is not null)
await _database.Connection.DeleteAsync(item); await _database.Connection.DeleteAsync(item);
} }
private static string NormalizeName(string? name)
{
var cleanName = (name ?? string.Empty).Trim();
if (string.IsNullOrWhiteSpace(cleanName))
throw new ArgumentException("Der Tätigkeitsname darf nicht leer sein.", nameof(name));
return cleanName;
}
} }
+58 -14
View File
@@ -1,30 +1,74 @@
using SQLite;
using cfs_tracker.Models; using cfs_tracker.Models;
using Microsoft.Maui.Storage; using cfs_tracker.Services;
using SQLite;
using System.Threading;
namespace cfs_tracker.Data; namespace cfs_tracker.Data;
public class AppDatabase public sealed class AppDatabase
{ {
private SQLiteAsyncConnection? _database; private readonly DatabaseLocationService _databaseLocationService;
private readonly SemaphoreSlim _initLock = new(1, 1);
private SQLiteAsyncConnection? _connection;
private bool _initialized; private bool _initialized;
public AppDatabase(DatabaseLocationService databaseLocationService)
{
_databaseLocationService = databaseLocationService;
}
public async Task InitAsync() public async Task InitAsync()
{ {
if (_initialized) return; if (_initialized)
return;
var dbPath = Path.Combine(FileSystem.Current.AppDataDirectory, "cfs_tracker.db3"); await _initLock.WaitAsync();
_database = new SQLiteAsyncConnection(dbPath); try
{
if (_initialized)
return;
await _database.CreateTableAsync<ActivityItem>(); var dbPath = _databaseLocationService.ResolveDatabasePath();
await _database.CreateTableAsync<SymptomItem>(); var directory = Path.GetDirectoryName(dbPath);
await _database.CreateTableAsync<HealthEntry>();
await _database.CreateTableAsync<HealthEntrySymptom>(); if (!string.IsNullOrWhiteSpace(directory))
await _database.CreateTableAsync<ThemeSettingItem>(); Directory.CreateDirectory(directory);
await _database.CreateTableAsync<AppearanceSetting>();
_connection = new SQLiteAsyncConnection(dbPath);
await _connection.ExecuteAsync("PRAGMA foreign_keys = ON;");
await _connection.CreateTableAsync<ActivityItem>();
await _connection.CreateTableAsync<SymptomItem>();
await _connection.CreateTableAsync<HealthEntry>();
await _connection.CreateTableAsync<HealthEntrySymptom>();
await _connection.CreateTableAsync<AppearanceSetting>();
await _connection.CreateTableAsync<NotificationSchedule>();
await _connection.ExecuteAsync(@"
CREATE TABLE IF NOT EXISTS HealthEntrySymptom (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
HealthEntryId INTEGER NOT NULL,
SymptomItemId INTEGER NOT NULL
);");
await _connection.ExecuteAsync(
"CREATE INDEX IF NOT EXISTS IX_HealthEntrySymptom_HealthEntryId ON HealthEntrySymptom(HealthEntryId);");
await _connection.ExecuteAsync(
"CREATE INDEX IF NOT EXISTS IX_HealthEntrySymptom_SymptomItemId ON HealthEntrySymptom(SymptomItemId);");
_initialized = true; _initialized = true;
} }
finally
{
_initLock.Release();
}
}
public SQLiteAsyncConnection Connection => _database ?? throw new InvalidOperationException("Database not initialized."); public string CurrentPath => _databaseLocationService.ResolveDatabasePath();
public SQLiteAsyncConnection Connection =>
_connection ?? throw new InvalidOperationException("Database has not been initialized yet.");
} }
+70 -67
View File
@@ -1,3 +1,4 @@
using cfs_tracker.Helpers;
using cfs_tracker.Models; using cfs_tracker.Models;
namespace cfs_tracker.Data; namespace cfs_tracker.Data;
@@ -11,6 +12,27 @@ public class AppearanceRepository
_database = database; _database = database;
} }
public async Task EnsureDefaultsAsync()
{
await _database.InitAsync();
foreach (var pair in AppearanceDefaults.All)
await InsertIfMissingAsync(pair.Key, pair.Value);
}
public async Task ResetAsync()
{
await _database.InitAsync();
await _database.Connection.DeleteAllAsync<AppearanceSetting>();
await EnsureDefaultsAsync();
}
public async Task ResetToDefaultsAsync()
{
await ResetAsync();
}
public async Task<List<AppearanceSetting>> GetAllAsync() public async Task<List<AppearanceSetting>> GetAllAsync()
{ {
await _database.InitAsync(); await _database.InitAsync();
@@ -20,90 +42,71 @@ public class AppearanceRepository
.ToListAsync(); .ToListAsync();
} }
public async Task<AppearanceSetting?> GetByKeyAsync(string key) public async Task<Dictionary<string, string>> GetMapAsync()
{
var items = await GetAllAsync();
return items.ToDictionary(x => x.Key, x => x.Value);
}
public async Task SaveAsync(string key, string value)
{ {
await _database.InitAsync(); await _database.InitAsync();
return await _database.Connection.Table<AppearanceSetting>() var cleanKey = NormalizeKey(key);
.FirstOrDefaultAsync(x => x.Key == key); var cleanValue = NormalizeValue(value);
var existing = await _database.Connection.Table<AppearanceSetting>()
.FirstOrDefaultAsync(x => x.Key == cleanKey);
if (existing is null)
{
await _database.Connection.InsertAsync(new AppearanceSetting
{
Key = cleanKey,
Value = cleanValue
});
return;
}
existing.Value = cleanValue;
await _database.Connection.UpdateAsync(existing);
} }
public async Task UpsertAsync(string key, string value) public async Task UpsertAsync(string key, string value)
{ {
await _database.InitAsync(); await SaveAsync(key, value);
}
private async Task InsertIfMissingAsync(string key, string value)
{
var cleanKey = NormalizeKey(key);
var cleanValue = NormalizeValue(value);
var existing = await _database.Connection.Table<AppearanceSetting>() var existing = await _database.Connection.Table<AppearanceSetting>()
.FirstOrDefaultAsync(x => x.Key == key); .FirstOrDefaultAsync(x => x.Key == cleanKey);
if (existing is not null)
return;
if (existing is null)
{
await _database.Connection.InsertAsync(new AppearanceSetting await _database.Connection.InsertAsync(new AppearanceSetting
{ {
Key = key, Key = cleanKey,
Value = value Value = cleanValue
}); });
} }
else
private static string NormalizeKey(string key)
{ {
existing.Value = value; var cleanKey = (key ?? string.Empty).Trim();
await _database.Connection.UpdateAsync(existing);
} if (string.IsNullOrWhiteSpace(cleanKey))
throw new ArgumentException("Appearance key must not be empty.", nameof(key));
return cleanKey;
} }
public async Task EnsureDefaultsAsync() private static string NormalizeValue(string value)
{ {
await _database.InitAsync(); return (value ?? string.Empty).Trim();
await EnsureDefaultAsync("AppBackground", "#0B1620");
await EnsureDefaultAsync("PanelBackground", "#162330");
await EnsureDefaultAsync("PanelBackground2", "#203041");
await EnsureDefaultAsync("PanelBorder", "#2B3E52");
await EnsureDefaultAsync("TextPrimary", "#D9E6F2");
await EnsureDefaultAsync("TextMuted", "#94A8BC");
await EnsureDefaultAsync("StateGreen", "#4D8B68");
await EnsureDefaultAsync("StateYellow", "#B89A42");
await EnsureDefaultAsync("StateRed", "#A85C5C");
await EnsureDefaultAsync("StateGray", "#5C6670");
await EnsureDefaultAsync("StatusGreenText", "Grün");
await EnsureDefaultAsync("StatusYellowText", "Gelb");
await EnsureDefaultAsync("StatusRedText", "Rot");
await EnsureDefaultAsync("StatusGrayText", "Grau");
}
public async Task ResetToDefaultsAsync()
{
await _database.InitAsync();
await UpsertAsync("AppBackground", "#0B1620");
await UpsertAsync("PanelBackground", "#162330");
await UpsertAsync("PanelBackground2", "#203041");
await UpsertAsync("PanelBorder", "#2B3E52");
await UpsertAsync("TextPrimary", "#D9E6F2");
await UpsertAsync("TextMuted", "#94A8BC");
await UpsertAsync("StateGreen", "#4D8B68");
await UpsertAsync("StateYellow", "#B89A42");
await UpsertAsync("StateRed", "#A85C5C");
await UpsertAsync("StateGray", "#5C6670");
await UpsertAsync("StatusGreenText", "Grün");
await UpsertAsync("StatusYellowText", "Gelb");
await UpsertAsync("StatusRedText", "Rot");
await UpsertAsync("StatusGrayText", "Grau");
}
private async Task EnsureDefaultAsync(string key, string value)
{
var existing = await _database.Connection.Table<AppearanceSetting>()
.FirstOrDefaultAsync(x => x.Key == key);
if (existing is null)
{
await _database.Connection.InsertAsync(new AppearanceSetting
{
Key = key,
Value = value
});
}
} }
} }
+5
View File
@@ -0,0 +1,5 @@
public sealed class ExportResult
{
public string FilePath { get; init; } = string.Empty;
public string FileName { get; init; } = string.Empty;
}
+113 -40
View File
@@ -5,101 +5,171 @@ namespace cfs_tracker.Data;
public class HealthEntryRepository public class HealthEntryRepository
{ {
private readonly AppDatabase _database; private readonly AppDatabase _database;
private readonly SymptomRepository _symptomRepository;
public HealthEntryRepository(AppDatabase database) => _database = database; public HealthEntryRepository(AppDatabase database, SymptomRepository symptomRepository)
public async Task AddEntryAsync(HealthState state, EntrySource source, DateTime? timestamp = null, int? activityId = null)
{ {
await _database.InitAsync(); _database = database;
var entry = new HealthEntry _symptomRepository = symptomRepository;
{
Timestamp = timestamp ?? DateTime.Now,
State = state,
Source = source,
ActivityId = activityId,
UpdatedAt = DateTime.Now
};
await _database.Connection.InsertAsync(entry);
} }
public async Task<int> AddEntryAndReturnIdAsync(HealthState state, EntrySource source, DateTime? timestamp = null, int? activityId = null) public async Task<int> AddQuickEntryAsync(
HealthState state,
int? activityId = null,
IEnumerable<int>? symptomIds = null,
DateTime? timestamp = null,
EntrySource source = EntrySource.App)
{ {
await _database.InitAsync(); await _database.InitAsync();
var effectiveTimestamp = timestamp ?? DateTime.Now;
var entry = new HealthEntry var entry = new HealthEntry
{ {
Timestamp = timestamp ?? DateTime.Now, EntryDate = effectiveTimestamp.Date,
Timestamp = effectiveTimestamp,
State = state, State = state,
Source = source, Source = source,
ActivityId = activityId, DayPart = null,
ActivityId = NormalizeActivityId(activityId),
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now UpdatedAt = DateTime.Now
}; };
await _database.Connection.InsertAsync(entry); await _database.Connection.InsertAsync(entry);
await _symptomRepository.SetSymptomsForEntryAsync(entry.Id, symptomIds);
return entry.Id; return entry.Id;
} }
public async Task UpsertBackfillAsync(DateTime date, DayPart part, HealthState state, EntrySource source, int? activityId = null) public async Task<int> UpsertBackfillAsync(
DateTime date,
DayPart part = DayPart.Morning,
HealthState state = HealthState.Gray,
int? activityId = null,
IEnumerable<int>? symptomIds = null,
EntrySource source = EntrySource.Backfill)
{ {
await _database.InitAsync(); await _database.InitAsync();
var slotTimestamp = BuildSlotTimestamp(date, part);
var slotTimestamp = BuildBackfillTimestamp(date, part);
var existing = await _database.Connection.Table<HealthEntry>() var existing = await _database.Connection.Table<HealthEntry>()
.FirstOrDefaultAsync(x => x.Timestamp == slotTimestamp); .FirstOrDefaultAsync(x => x.Timestamp == slotTimestamp);
if (existing is null) if (existing is null)
{ {
await _database.Connection.InsertAsync(new HealthEntry var entry = new HealthEntry
{ {
EntryDate = date.Date,
Timestamp = slotTimestamp, Timestamp = slotTimestamp,
State = state, State = state,
Source = source, Source = source,
ActivityId = activityId, DayPart = part,
ActivityId = NormalizeActivityId(activityId),
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now UpdatedAt = DateTime.Now
}); };
}
else await _database.Connection.InsertAsync(entry);
{ await _symptomRepository.SetSymptomsForEntryAsync(entry.Id, symptomIds);
existing.State = state; return entry.Id;
existing.Source = source;
existing.ActivityId = activityId;
existing.UpdatedAt = DateTime.Now;
await _database.Connection.UpdateAsync(existing);
}
} }
public async Task<HealthEntry?> GetBackfillEntryAsync(DateTime date, DayPart part) existing.EntryDate = date.Date;
existing.Timestamp = slotTimestamp;
existing.State = state;
existing.Source = source;
existing.DayPart = part;
existing.ActivityId = NormalizeActivityId(activityId);
existing.UpdatedAt = DateTime.Now;
await _database.Connection.UpdateAsync(existing);
await _symptomRepository.SetSymptomsForEntryAsync(existing.Id, symptomIds);
return existing.Id;
}
public async Task UpdateEntryAsync(
int entryId,
DateTime date,
HealthState state,
int? activityId = null,
IEnumerable<int>? symptomIds = null,
DayPart? part = null,
EntrySource? source = null)
{ {
await _database.InitAsync(); await _database.InitAsync();
var slotTimestamp = BuildSlotTimestamp(date, part);
var entry = await _database.Connection.Table<HealthEntry>()
.FirstOrDefaultAsync(x => x.Id == entryId);
if (entry is null)
return;
entry.EntryDate = date.Date;
entry.State = state;
entry.ActivityId = NormalizeActivityId(activityId);
entry.Source = source ?? entry.Source;
entry.DayPart = part;
if (part.HasValue)
entry.Timestamp = BuildBackfillTimestamp(date, part.Value);
else if (date.Date != entry.EntryDate.Date)
entry.Timestamp = date.Date + entry.Timestamp.TimeOfDay;
entry.UpdatedAt = DateTime.Now;
await _database.Connection.UpdateAsync(entry);
await _symptomRepository.SetSymptomsForEntryAsync(entry.Id, symptomIds);
}
public async Task<HealthEntry?> GetByIdAsync(int id)
{
await _database.InitAsync();
return await _database.Connection.Table<HealthEntry>() return await _database.Connection.Table<HealthEntry>()
.FirstOrDefaultAsync(x => x.Timestamp == slotTimestamp); .FirstOrDefaultAsync(x => x.Id == id);
} }
public async Task<List<HealthEntry>> GetEntriesForDateAsync(DateTime date) public async Task<List<HealthEntry>> GetEntriesForDateAsync(DateTime date)
{ {
await _database.InitAsync(); await _database.InitAsync();
var start = date.Date; var start = date.Date;
var end = start.AddDays(1); var end = start.AddDays(1);
var list = await _database.Connection.Table<HealthEntry>() var list = await _database.Connection.Table<HealthEntry>()
.Where(x => x.Timestamp >= start && x.Timestamp < end) .Where(x => x.Timestamp >= start && x.Timestamp < end)
.ToListAsync(); .ToListAsync();
return list.OrderBy(x => x.Timestamp).ToList();
return list.OrderBy(x => x.Timestamp).ThenBy(x => x.Id).ToList();
} }
public async Task<List<HealthEntry>> GetEntriesBetweenAsync(DateTime startDate, DateTime endDate) public async Task<List<HealthEntry>> GetEntriesBetweenAsync(DateTime startDateInclusive, DateTime endDateExclusive)
{ {
await _database.InitAsync(); await _database.InitAsync();
var start = startDate.Date;
var end = endDate.Date; var start = startDateInclusive.Date;
var end = endDateExclusive.Date;
var list = await _database.Connection.Table<HealthEntry>() var list = await _database.Connection.Table<HealthEntry>()
.Where(x => x.Timestamp >= start && x.Timestamp < end) .Where(x => x.Timestamp >= start && x.Timestamp < end)
.ToListAsync(); .ToListAsync();
return list.OrderBy(x => x.Timestamp).ToList();
return list.OrderBy(x => x.Timestamp).ThenBy(x => x.Id).ToList();
} }
public async Task DeleteEntryAsync(int id) public async Task DeleteEntryAsync(int id)
{ {
await _database.InitAsync(); await _database.InitAsync();
var item = await _database.Connection.Table<HealthEntry>().FirstOrDefaultAsync(x => x.Id == id);
var links = await _database.Connection.Table<HealthEntrySymptom>()
.Where(x => x.HealthEntryId == id)
.ToListAsync();
foreach (var link in links)
await _database.Connection.DeleteAsync(link);
var item = await _database.Connection.Table<HealthEntry>()
.FirstOrDefaultAsync(x => x.Id == id);
if (item is not null) if (item is not null)
await _database.Connection.DeleteAsync(item); await _database.Connection.DeleteAsync(item);
} }
@@ -111,10 +181,13 @@ public class HealthEntryRepository
await _database.Connection.DeleteAllAsync<HealthEntrySymptom>(); await _database.Connection.DeleteAllAsync<HealthEntrySymptom>();
} }
private static DateTime BuildSlotTimestamp(DateTime date, DayPart part) => part switch public static DateTime BuildBackfillTimestamp(DateTime date, DayPart part) => part switch
{ {
DayPart.Morning => date.Date.AddHours(9), DayPart.Morning => date.Date.AddHours(9),
DayPart.Afternoon => date.Date.AddHours(15), DayPart.Afternoon => date.Date.AddHours(15),
_ => date.Date.AddHours(9) _ => date.Date.AddHours(9)
}; };
private static int? NormalizeActivityId(int? activityId) =>
activityId.HasValue && activityId.Value > 0 ? activityId : null;
} }
+45
View File
@@ -0,0 +1,45 @@
using cfs_tracker.Models;
namespace cfs_tracker.Data;
public class NotificationScheduleRepository
{
private readonly AppDatabase _database;
public NotificationScheduleRepository(AppDatabase database)
{
_database = database;
}
public async Task<List<NotificationSchedule>> GetAllAsync()
{
await _database.InitAsync();
return await _database.Connection.Table<NotificationSchedule>()
.OrderBy(x => x.DayOfWeekValue)
.ThenBy(x => x.Hour)
.ThenBy(x => x.Minute)
.ToListAsync();
}
public async Task ReplaceAllAsync(IEnumerable<NotificationSchedule> schedules)
{
await _database.InitAsync();
await _database.Connection.DeleteAllAsync<NotificationSchedule>();
foreach (var schedule in schedules
.OrderBy(x => x.DayOfWeekValue)
.ThenBy(x => x.Hour)
.ThenBy(x => x.Minute))
{
await _database.Connection.InsertAsync(new NotificationSchedule
{
DayOfWeekValue = schedule.DayOfWeekValue,
Hour = schedule.Hour,
Minute = schedule.Minute,
IsEnabled = schedule.IsEnabled
});
}
}
}
+106 -65
View File
@@ -1,4 +1,5 @@
using cfs_tracker.Models; using cfs_tracker.Models;
using System.Linq;
namespace cfs_tracker.Data; namespace cfs_tracker.Data;
@@ -11,10 +12,41 @@ public class SymptomRepository
_database = database; _database = database;
} }
public async Task<List<SymptomItem>> GetAllAsync() public async Task EnsureDefaultsAsync()
{ {
await _database.InitAsync(); await _database.InitAsync();
if (await _database.Connection.Table<SymptomItem>().CountAsync() > 0)
return;
var defaults = new[]
{
"Fatigue",
"PEM",
"Kopfschmerzen",
"Schwindel",
"Kognitive Probleme",
"Schlafprobleme",
"Reizempfindlichkeit",
"Herzrasen",
"Schmerzen",
"Atemprobleme"
};
for (var i = 0; i < defaults.Length; i++)
{
await _database.Connection.InsertAsync(new SymptomItem
{
Name = defaults[i],
SortOrder = i,
IsActive = true
});
}
}
public async Task<List<SymptomItem>> GetAllAsync()
{
await _database.InitAsync();
return await _database.Connection.Table<SymptomItem>() return await _database.Connection.Table<SymptomItem>()
.OrderBy(x => x.SortOrder) .OrderBy(x => x.SortOrder)
.ThenBy(x => x.Name) .ThenBy(x => x.Name)
@@ -24,7 +56,6 @@ public class SymptomRepository
public async Task<List<SymptomItem>> GetActiveAsync() public async Task<List<SymptomItem>> GetActiveAsync()
{ {
await _database.InitAsync(); await _database.InitAsync();
return await _database.Connection.Table<SymptomItem>() return await _database.Connection.Table<SymptomItem>()
.Where(x => x.IsActive) .Where(x => x.IsActive)
.OrderBy(x => x.SortOrder) .OrderBy(x => x.SortOrder)
@@ -32,64 +63,61 @@ public class SymptomRepository
.ToListAsync(); .ToListAsync();
} }
public async Task EnsureDefaultsAsync() public async Task<SymptomItem?> GetByIdAsync(int id)
{ {
await _database.InitAsync(); await _database.InitAsync();
return await _database.Connection.Table<SymptomItem>()
if ((await _database.Connection.Table<SymptomItem>().CountAsync()) > 0) .FirstOrDefaultAsync(x => x.Id == id);
return;
var defaults = new List<SymptomItem>
{
new() { Name = "Kopfschmerzen", SortOrder = 0, IsActive = true },
new() { Name = "Kopfnebel", SortOrder = 1, IsActive = true },
new() { Name = "Tinnitus", SortOrder = 2, IsActive = true },
new() { Name = "Schwere / Müdigkeit", SortOrder = 3, IsActive = true },
new() { Name = "Überforderung", SortOrder = 4, IsActive = true }
};
foreach (var item in defaults)
await _database.Connection.InsertAsync(item);
} }
public async Task AddAsync(string name) public async Task<Dictionary<int, string>> GetNameMapAsync()
{
var items = await GetAllAsync();
return items.ToDictionary(x => x.Id, x => x.Name);
}
public async Task<int> AddAsync(string name)
{ {
await _database.InitAsync(); await _database.InitAsync();
var cleanName = NormalizeName(name);
var maxSort = 0; var existing = await _database.Connection.Table<SymptomItem>().ToListAsync();
var all = await _database.Connection.Table<SymptomItem>().ToListAsync(); if (existing.Any(x => string.Equals(x.Name, cleanName, StringComparison.OrdinalIgnoreCase)))
if (all.Count > 0) throw new InvalidOperationException($"Das Symptom '{cleanName}' existiert bereits.");
maxSort = all.Max(x => x.SortOrder) + 1;
await _database.Connection.InsertAsync(new SymptomItem var nextSort = existing.Count == 0 ? 0 : existing.Max(x => x.SortOrder) + 1;
var item = new SymptomItem
{ {
Name = name.Trim(), Name = cleanName,
SortOrder = maxSort, SortOrder = nextSort,
IsActive = true IsActive = true
}); };
await _database.Connection.InsertAsync(item);
return item.Id;
} }
public async Task RenameAsync(int id, string newName) public async Task RenameAsync(int id, string newName)
{ {
await _database.InitAsync(); await _database.InitAsync();
var cleanName = NormalizeName(newName);
var item = await _database.Connection.Table<SymptomItem>() var all = await _database.Connection.Table<SymptomItem>().ToListAsync();
.FirstOrDefaultAsync(x => x.Id == id); if (all.Any(x => x.Id != id && string.Equals(x.Name, cleanName, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"Das Symptom '{cleanName}' existiert bereits.");
var item = all.FirstOrDefault(x => x.Id == id);
if (item is null) if (item is null)
return; return;
item.Name = newName.Trim(); item.Name = cleanName;
await _database.Connection.UpdateAsync(item); await _database.Connection.UpdateAsync(item);
} }
public async Task SetActiveAsync(int id, bool isActive) public async Task SetActiveAsync(int id, bool isActive)
{ {
await _database.InitAsync(); await _database.InitAsync();
var item = await GetByIdAsync(id);
var item = await _database.Connection.Table<SymptomItem>()
.FirstOrDefaultAsync(x => x.Id == id);
if (item is null) if (item is null)
return; return;
@@ -100,40 +128,29 @@ public class SymptomRepository
public async Task<bool> HasUsageAsync(int symptomId) public async Task<bool> HasUsageAsync(int symptomId)
{ {
await _database.InitAsync(); await _database.InitAsync();
return await _database.Connection.Table<HealthEntrySymptom>()
var count = await _database.Connection.Table<HealthEntrySymptom>()
.Where(x => x.SymptomItemId == symptomId) .Where(x => x.SymptomItemId == symptomId)
.CountAsync(); .CountAsync() > 0;
return count > 0;
} }
public async Task DeleteIfUnusedAsync(int symptomId) public async Task DeleteOrDeactivateAsync(int symptomId)
{ {
await _database.InitAsync(); await _database.InitAsync();
var item = await GetByIdAsync(symptomId);
if (await HasUsageAsync(symptomId)) if (item is null)
return; return;
var item = await _database.Connection.Table<SymptomItem>() if (await HasUsageAsync(symptomId))
.FirstOrDefaultAsync(x => x.Id == symptomId); {
item.IsActive = false;
await _database.Connection.UpdateAsync(item);
return;
}
if (item is not null)
await _database.Connection.DeleteAsync(item); await _database.Connection.DeleteAsync(item);
} }
public async Task<List<int>> GetSymptomIdsForEntryAsync(int entryId) public async Task SetSymptomsForEntryAsync(int entryId, IEnumerable<int>? symptomIds)
{
await _database.InitAsync();
var links = await _database.Connection.Table<HealthEntrySymptom>()
.Where(x => x.HealthEntryId == entryId)
.ToListAsync();
return links.Select(x => x.SymptomItemId).ToList();
}
public async Task SetSymptomsForEntryAsync(int entryId, IEnumerable<int> symptomIds)
{ {
await _database.InitAsync(); await _database.InitAsync();
@@ -144,7 +161,12 @@ public class SymptomRepository
foreach (var item in existing) foreach (var item in existing)
await _database.Connection.DeleteAsync(item); await _database.Connection.DeleteAsync(item);
foreach (var symptomId in symptomIds.Distinct()) var ids = symptomIds?
.Distinct()
.Where(x => x > 0)
.ToList() ?? new List<int>();
foreach (var symptomId in ids)
{ {
await _database.Connection.InsertAsync(new HealthEntrySymptom await _database.Connection.InsertAsync(new HealthEntrySymptom
{ {
@@ -154,24 +176,34 @@ public class SymptomRepository
} }
} }
public async Task<List<int>> GetSymptomIdsForEntryAsync(int entryId)
{
await _database.InitAsync();
return await _database.Connection.QueryScalarsAsync<int>(
$"SELECT {nameof(HealthEntrySymptom.SymptomItemId)} " +
$"FROM {nameof(HealthEntrySymptom)} " +
$"WHERE {nameof(HealthEntrySymptom.HealthEntryId)} = ?",
entryId);
}
public async Task<Dictionary<int, List<string>>> GetSymptomsByEntryIdsAsync(IEnumerable<int> entryIds) public async Task<Dictionary<int, List<string>>> GetSymptomsByEntryIdsAsync(IEnumerable<int> entryIds)
{ {
await _database.InitAsync(); await _database.InitAsync();
var ids = entryIds.Distinct().ToHashSet();
var result = new Dictionary<int, List<string>>(); var result = new Dictionary<int, List<string>>();
var idSet = entryIds.Distinct().ToHashSet();
if (ids.Count == 0) if (idSet.Count == 0)
return result; return result;
var allLinks = await _database.Connection.Table<HealthEntrySymptom>().ToListAsync(); var links = await _database.Connection.Table<HealthEntrySymptom>().ToListAsync();
var relevantLinks = allLinks.Where(x => ids.Contains(x.HealthEntryId)).ToList(); var relevantLinks = links.Where(x => idSet.Contains(x.HealthEntryId)).ToList();
if (relevantLinks.Count == 0) if (relevantLinks.Count == 0)
return result; return result;
var allSymptoms = await _database.Connection.Table<SymptomItem>().ToListAsync(); var symptoms = await _database.Connection.Table<SymptomItem>().ToListAsync();
var symptomMap = allSymptoms.ToDictionary(x => x.Id, x => x.Name); var symptomMap = symptoms.ToDictionary(x => x.Id, x => x.Name);
foreach (var group in relevantLinks.GroupBy(x => x.HealthEntryId)) foreach (var group in relevantLinks.GroupBy(x => x.HealthEntryId))
{ {
@@ -185,4 +217,13 @@ public class SymptomRepository
return result; return result;
} }
private static string NormalizeName(string? name)
{
var cleanName = (name ?? string.Empty).Trim();
if (string.IsNullOrWhiteSpace(cleanName))
throw new ArgumentException("Der Symptomname darf nicht leer sein.", nameof(name));
return cleanName;
}
} }
-47
View File
@@ -1,47 +0,0 @@
using cfs_tracker.Models;
namespace cfs_tracker.Data;
public class ThemeSettingsRepository
{
private readonly AppDatabase _database;
private static readonly Dictionary<string, string> DefaultValues = new()
{
["AppBackground"] = "#0B1620",
["PanelBackground"] = "#162330",
["PanelBackground2"] = "#203041",
["PanelBorder"] = "#2B3E52",
["TextPrimary"] = "#D9E6F2",
["TextMuted"] = "#94A8BC",
["StateGreen"] = "#4D8B68",
["StateYellow"] = "#B89A42",
["StateRed"] = "#A85C5C",
["StateGray"] = "#5C6670",
};
public ThemeSettingsRepository(AppDatabase database) => _database = database;
public async Task EnsureDefaultsAsync()
{
await _database.InitAsync();
foreach (var pair in DefaultValues)
{
var existing = await _database.Connection.Table<ThemeSettingItem>().FirstOrDefaultAsync(x => x.Key == pair.Key);
if (existing is null)
await _database.Connection.InsertAsync(new ThemeSettingItem { Key = pair.Key, Value = pair.Value });
}
}
public async Task<List<ThemeSettingItem>> GetAllAsync()
{
await EnsureDefaultsAsync();
return await _database.Connection.Table<ThemeSettingItem>().OrderBy(x => x.Key).ToListAsync();
}
public async Task SaveAsync(ThemeSettingItem item)
{
await _database.InitAsync();
await _database.Connection.InsertOrReplaceAsync(item);
}
}
+37
View File
@@ -0,0 +1,37 @@
namespace cfs_tracker.Helpers;
public static class AppearanceDefaults
{
public static IReadOnlyDictionary<string, string> All { get; } = new Dictionary<string, string>
{
[AppearanceKeys.AppBackground] = "#0B1A2A",
[AppearanceKeys.SurfaceBackground] = "#132235",
[AppearanceKeys.SurfaceBackgroundAlt] = "#1A2B40",
[AppearanceKeys.Border] = "#2A3E55",
[AppearanceKeys.TextPrimary] = "#DCE7F3",
[AppearanceKeys.TextMuted] = "#8FA6BC",
[AppearanceKeys.StateGreen] = "#4E8B69",
[AppearanceKeys.StateYellow] = "#B89A42",
[AppearanceKeys.StateRed] = "#A85C5C",
[AppearanceKeys.StateGray] = "#1F242B",
[AppearanceKeys.StatusGreenText] = "Grün",
[AppearanceKeys.StatusYellowText] = "Gelb",
[AppearanceKeys.StatusRedText] = "Rot",
[AppearanceKeys.StatusGrayText] = "Schwarz",
[AppearanceKeys.ButtonPrimaryBackground] = "#355066",
[AppearanceKeys.ButtonPrimaryText] = "#FFFFFF",
[AppearanceKeys.ButtonSecondaryBackground] = "#355055",
[AppearanceKeys.ButtonSecondaryText] = "#DCE7F3",
[AppearanceKeys.ShellBackground] = "#10293F",
[AppearanceKeys.ShellForeground] = "#DCE7F3",
[AppearanceKeys.ShellTitle] = "#FFFFFF",
[AppearanceKeys.ShellUnselected] = "#8FA6BC",
[AppearanceKeys.TabBarBackground] = "#10293F",
[AppearanceKeys.TabBarForeground] = "#DCE7F3",
[AppearanceKeys.TabBarTitle] = "#FFFFFF",
[AppearanceKeys.TabBarUnselected] = "#8FA6BC",
};
}
+36
View File
@@ -0,0 +1,36 @@
namespace cfs_tracker.Helpers;
public static class AppearanceKeys
{
public const string AppBackground = nameof(AppBackground);
public const string SurfaceBackground = nameof(SurfaceBackground);
public const string SurfaceBackgroundAlt = nameof(SurfaceBackgroundAlt);
public const string Border = nameof(Border);
public const string TextPrimary = nameof(TextPrimary);
public const string TextMuted = nameof(TextMuted);
public const string StateGreen = nameof(StateGreen);
public const string StateYellow = nameof(StateYellow);
public const string StateRed = nameof(StateRed);
public const string StateGray = nameof(StateGray);
public const string StatusGreenText = nameof(StatusGreenText);
public const string StatusYellowText = nameof(StatusYellowText);
public const string StatusRedText = nameof(StatusRedText);
public const string StatusGrayText = nameof(StatusGrayText);
public const string ButtonPrimaryBackground = "ButtonPrimaryBackground";
public const string ButtonPrimaryText = "ButtonPrimaryText";
public const string ButtonSecondaryBackground = "ButtonSecondaryBackground";
public const string ButtonSecondaryText = "ButtonSecondaryText";
public const string ShellBackground = "ShellBackground";
public const string ShellForeground = "ShellForeground";
public const string ShellTitle = "ShellTitle";
public const string ShellUnselected = "ShellUnselected";
public const string TabBarBackground = "TabBarBackground";
public const string TabBarForeground = "TabBarForeground";
public const string TabBarTitle = "TabBarTitle";
public const string TabBarUnselected = "TabBarUnselected";
}
+46
View File
@@ -0,0 +1,46 @@
using Microsoft.Maui.Graphics;
namespace cfs_tracker.Helpers;
public static class ColorUtility
{
public static bool IsHexColor(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return false;
try
{
_ = Color.FromArgb(NormalizeHex(value));
return true;
}
catch
{
return false;
}
}
public static Color ParseColor(string? value, string fallbackHex)
{
try
{
return Color.FromArgb(NormalizeHex(value));
}
catch
{
return Color.FromArgb(NormalizeHex(fallbackHex));
}
}
public static string NormalizeHex(string? value)
{
var text = (value ?? string.Empty).Trim();
if (string.IsNullOrWhiteSpace(text))
return "#000000";
if (!text.StartsWith('#'))
text = "#" + text;
return text.ToUpperInvariant();
}
}
+27
View File
@@ -0,0 +1,27 @@
using System.Globalization;
namespace cfs_tracker.Helpers;
public static class DateHelper
{
public static readonly CultureInfo GermanCulture = new("de-DE");
public static DateTime StartOfWeekMonday(DateTime date)
{
var normalized = date.Date;
var diff = (7 + (normalized.DayOfWeek - DayOfWeek.Monday)) % 7;
return normalized.AddDays(-diff);
}
public static string ToGermanDateText(DateTime date) =>
date.ToString("dddd, dd. MMMM yyyy", GermanCulture);
public static string ToGermanShortDay(DateTime date) =>
date.ToString("ddd dd.MM.", GermanCulture);
public static string ToGermanMonthYear(DateTime date) =>
date.ToString("MMMM yyyy", GermanCulture);
public static string ToGermanYear(DateTime date) =>
date.ToString("yyyy", GermanCulture);
}
+42
View File
@@ -0,0 +1,42 @@
using cfs_tracker.Models;
namespace cfs_tracker.Helpers;
public static class HealthStateExtensions
{
public static string ToAppearanceColorKey(this HealthState state) => state switch
{
HealthState.Green => AppearanceKeys.StateGreen,
HealthState.Yellow => AppearanceKeys.StateYellow,
HealthState.Red => AppearanceKeys.StateRed,
HealthState.Gray => AppearanceKeys.StateGray,
_ => AppearanceKeys.StateGray
};
public static string ToAppearanceTextKey(this HealthState state) => state switch
{
HealthState.Green => AppearanceKeys.StatusGreenText,
HealthState.Yellow => AppearanceKeys.StatusYellowText,
HealthState.Red => AppearanceKeys.StatusRedText,
HealthState.Gray => AppearanceKeys.StatusGrayText,
_ => AppearanceKeys.StatusGrayText
};
public static string ToFallbackText(this HealthState state) => state switch
{
HealthState.Green => "Grün",
HealthState.Yellow => "Gelb",
HealthState.Red => "Rot",
HealthState.Gray => "Schwarz",
_ => "Schwarz"
};
public static int ToScore(this HealthState state) => state switch
{
HealthState.Green => 3,
HealthState.Yellow => 2,
HealthState.Red => 1,
HealthState.Gray => 0,
_ => 0
};
}
-21
View File
@@ -1,21 +0,0 @@
namespace cfs_tracker.Helpers;
public static class ThemeKeys
{
public const string AppBackground = "AppBackground";
public const string PanelBackground = "PanelBackground";
public const string PanelBackground2 = "PanelBackground2";
public const string PanelBorder = "PanelBorder";
public const string TextPrimary = "TextPrimary";
public const string TextMuted = "TextMuted";
public const string StateGreen = "StateGreen";
public const string StateYellow = "StateYellow";
public const string StateRed = "StateRed";
public const string StateGray = "StateGray";
public const string StatusGreenText = "StatusGreenText";
public const string StatusYellowText = "StatusYellowText";
public const string StatusRedText = "StatusRedText";
public const string StatusGrayText = "StatusGrayText";
}
-23
View File
@@ -1,23 +0,0 @@
using Microsoft.Maui.Controls;
using Microsoft.Maui.Graphics;
namespace cfs_tracker.Helpers;
public static class ThemeResourceHelper
{
public static Color GetColor(string key, string fallbackHex = "#FFFFFF")
{
if (Application.Current?.Resources.TryGetValue(key, out var value) == true && value is Color color)
return color;
return Color.FromArgb(fallbackHex);
}
public static string GetString(string key, string fallback = "")
{
if (Application.Current?.Resources.TryGetValue(key, out var value) == true && value is string text)
return text;
return fallback;
}
}
+44 -28
View File
@@ -3,6 +3,8 @@ using cfs_tracker.Services;
using cfs_tracker.ViewModels; using cfs_tracker.ViewModels;
using cfs_tracker.Views; using cfs_tracker.Views;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SQLitePCL;
using System.Text;
namespace cfs_tracker; namespace cfs_tracker;
@@ -10,42 +12,56 @@ public static class MauiProgram
{ {
public static MauiApp CreateMauiApp() public static MauiApp CreateMauiApp()
{ {
var builder = MauiApp.CreateBuilder(); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Batteries_V2.Init();
var builder = MauiApp.CreateBuilder();
builder builder
.UseMauiApp<App>() .UseMauiApp<App>()
.ConfigureFonts(fonts => { }); .ConfigureFonts(fonts =>
{
builder.Services.AddSingleton<AppDatabase>(); fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
builder.Services.AddSingleton<HealthEntryRepository>(); fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
builder.Services.AddSingleton<ActivityRepository>(); });
builder.Services.AddSingleton<SymptomRepository>();
builder.Services.AddSingleton<ThemeSettingsRepository>();
builder.Services.AddSingleton<AggregationService>();
builder.Services.AddSingleton<CalendarStateService>();
builder.Services.AddSingleton<AppearanceService>();
builder.Services.AddTransient<DayViewModel>();
builder.Services.AddTransient<WeekViewModel>();
builder.Services.AddTransient<MonthViewModel>();
builder.Services.AddTransient<YearViewModel>();
builder.Services.AddTransient<QuickEntryViewModel>();
builder.Services.AddTransient<OptionsViewModel>();
builder.Services.AddTransient<DayPage>();
builder.Services.AddTransient<WeekPage>();
builder.Services.AddTransient<MonthPage>();
builder.Services.AddTransient<YearPage>();
builder.Services.AddTransient<QuickEntryPage>();
builder.Services.AddTransient<OptionsPage>();
builder.Services.AddSingleton<AppShell>();
builder.Services.AddSingleton<AppearanceRepository>();
builder.Services.AddSingleton<AppearanceService>();
#if DEBUG #if DEBUG
builder.Logging.AddDebug(); builder.Logging.AddDebug();
#endif #endif
// Daten / Repositories
builder.Services.AddSingleton<AppDatabase>();
builder.Services.AddSingleton<DatabaseLocationService>();
builder.Services.AddSingleton<AppearanceRepository>();
builder.Services.AddSingleton<ActivityRepository>();
builder.Services.AddSingleton<SymptomRepository>();
builder.Services.AddSingleton<HealthEntryRepository>();
builder.Services.AddSingleton<NotificationScheduleRepository>();
// Services
builder.Services.AddSingleton<CalendarStateService>();
builder.Services.AddSingleton<AppearanceService>();
builder.Services.AddSingleton<AggregationService>();
builder.Services.AddSingleton<INotificationScheduler, NoOpNotificationScheduler>();
builder.Services.AddSingleton<IPdfExportService, PdfExportService>();
builder.Services.AddSingleton<AppBootstrapService>();
// Shell / Pages
builder.Services.AddSingleton<AppShell>();
builder.Services.AddTransient<DayPage>();
builder.Services.AddTransient<QuickEntryPage>();
builder.Services.AddTransient<WeekPage>();
builder.Services.AddTransient<MonthPage>();
builder.Services.AddTransient<YearPage>();
builder.Services.AddTransient<OptionsPage>();
// ViewModels
builder.Services.AddTransient<DayViewModel>();
builder.Services.AddTransient<QuickEntryViewModel>();
builder.Services.AddTransient<WeekViewModel>();
builder.Services.AddTransient<MonthViewModel>();
builder.Services.AddTransient<YearViewModel>();
builder.Services.AddTransient<OptionsViewModel>();
return builder.Build(); return builder.Build();
} }
} }
+11 -3
View File
@@ -1,9 +1,17 @@
using SQLite; using SQLite;
namespace cfs_tracker.Models; namespace cfs_tracker.Models;
[Table("Activities")]
public class ActivityItem public class ActivityItem
{ {
[PrimaryKey, AutoIncrement] public int Id { get; set; } [PrimaryKey, AutoIncrement]
[Unique] public string Name { get; set; } = string.Empty; public int Id { get; set; }
public bool IsActive { get; set; } = true;
[MaxLength(120), Unique]
public string Name { get; set; } = string.Empty;
public int SortOrder { get; set; } public int SortOrder { get; set; }
public bool IsActive { get; set; } = true;
} }
+6 -2
View File
@@ -1,10 +1,14 @@
using SQLite; using SQLite;
namespace cfs_tracker.Models; namespace cfs_tracker.Models;
[Table("AppearanceSettings")]
public class AppearanceSetting public class AppearanceSetting
{ {
[PrimaryKey] [PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(80), Unique]
public string Key { get; set; } = string.Empty; public string Key { get; set; } = string.Empty;
public string Value { get; set; } = string.Empty; public string Value { get; set; } = string.Empty;
+8
View File
@@ -0,0 +1,8 @@
namespace cfs_tracker.Models;
public sealed class AverageStateResult
{
public bool HasValue { get; init; }
public double AverageScore { get; init; }
public HealthState State { get; init; }
}
-8
View File
@@ -1,8 +0,0 @@
namespace cfs_tracker.Models;
public class CalendarDaySummary
{
public DateTime Date { get; set; }
public double? Average { get; set; }
public int EntryCount { get; set; }
public HealthState? DisplayState { get; set; }
}
-10
View File
@@ -1,10 +0,0 @@
namespace cfs_tracker.Models;
public class DayDetailSummary
{
public DateTime Date { get; set; }
public int GreenCount { get; set; }
public int YellowCount { get; set; }
public int RedCount { get; set; }
public int GrayCount { get; set; }
public List<HealthEntry> Entries { get; set; } = new();
}
-2
View File
@@ -1,2 +0,0 @@
namespace cfs_tracker.Models;
public enum DayPart { Morning=0, Afternoon=1 }
-2
View File
@@ -1,2 +0,0 @@
namespace cfs_tracker.Models;
public enum EntrySource { App=0, Notification=1 }
+31 -3
View File
@@ -1,11 +1,39 @@
using SQLite; using SQLite;
namespace cfs_tracker.Models; namespace cfs_tracker.Models;
[Table("HealthEntries")]
public class HealthEntry public class HealthEntry
{ {
[PrimaryKey, AutoIncrement] public int Id { get; set; } [PrimaryKey, AutoIncrement]
[Indexed] public DateTime Timestamp { get; set; } public int Id { get; set; }
[Indexed]
public DateTime EntryDate { get; set; }
[Indexed]
public DateTime Timestamp { get; set; }
[Indexed]
public HealthState State { get; set; } public HealthState State { get; set; }
[Indexed]
public EntrySource Source { get; set; } public EntrySource Source { get; set; }
[Indexed] public int? ActivityId { get; set; }
[Indexed]
public int? DayPartValue { get; set; }
[Indexed]
public int? ActivityId { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; } public DateTime UpdatedAt { get; set; }
[Ignore]
public DayPart? DayPart
{
get => DayPartValue.HasValue ? (DayPart)DayPartValue.Value : null;
set => DayPartValue = value.HasValue ? (int)value.Value : null;
}
} }
+11 -3
View File
@@ -1,8 +1,16 @@
using SQLite; using SQLite;
namespace cfs_tracker.Models; namespace cfs_tracker.Models;
[Table("HealthEntrySymptom")]
public class HealthEntrySymptom public class HealthEntrySymptom
{ {
[PrimaryKey, AutoIncrement] public int Id { get; set; } [PrimaryKey, AutoIncrement]
[Indexed] public int HealthEntryId { get; set; } public int Id { get; set; }
[Indexed] public int SymptomItemId { get; set; }
[Indexed]
public int HealthEntryId { get; set; }
[Indexed]
public int SymptomItemId { get; set; }
} }
-2
View File
@@ -1,2 +0,0 @@
namespace cfs_tracker.Models;
public enum HealthState { Gray=0, Red=1, Yellow=2, Green=3 }
-42
View File
@@ -1,42 +0,0 @@
using cfs_tracker.Helpers;
namespace cfs_tracker.Models;
public static class HealthStateExtensions
{
public static string ToColorKey(this HealthState state)
{
return state switch
{
HealthState.Green => ThemeKeys.StateGreen,
HealthState.Yellow => ThemeKeys.StateYellow,
HealthState.Red => ThemeKeys.StateRed,
HealthState.Gray => ThemeKeys.StateGray,
_ => ThemeKeys.PanelBackground2
};
}
public static string ToTextKey(this HealthState state)
{
return state switch
{
HealthState.Green => ThemeKeys.StatusGreenText,
HealthState.Yellow => ThemeKeys.StatusYellowText,
HealthState.Red => ThemeKeys.StatusRedText,
HealthState.Gray => ThemeKeys.StatusGrayText,
_ => ""
};
}
public static string ToFallbackText(this HealthState state)
{
return state switch
{
HealthState.Green => "Grün",
HealthState.Yellow => "Gelb",
HealthState.Red => "Rot",
HealthState.Gray => "Grau",
_ => ""
};
}
}
+25
View File
@@ -0,0 +1,25 @@
using SQLite;
namespace cfs_tracker.Models;
[Table("NotificationSchedules")]
public class NotificationSchedule
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public int DayOfWeekValue { get; set; }
public int Hour { get; set; }
public int Minute { get; set; }
public bool IsEnabled { get; set; } = true;
[Ignore]
public DayOfWeek DayOfWeek
{
get => (DayOfWeek)DayOfWeekValue;
set => DayOfWeekValue = (int)value;
}
}
-2
View File
@@ -1,2 +0,0 @@
namespace cfs_tracker.Models;
public enum OptionsTab { Database, Activities, Symptoms, Appearance }
+11 -3
View File
@@ -1,9 +1,17 @@
using SQLite; using SQLite;
namespace cfs_tracker.Models; namespace cfs_tracker.Models;
[Table("Symptoms")]
public class SymptomItem public class SymptomItem
{ {
[PrimaryKey, AutoIncrement] public int Id { get; set; } [PrimaryKey, AutoIncrement]
[Unique] public string Name { get; set; } = string.Empty; public int Id { get; set; }
public bool IsActive { get; set; } = true;
[MaxLength(120), Unique]
public string Name { get; set; } = string.Empty;
public int SortOrder { get; set; } public int SortOrder { get; set; }
public bool IsActive { get; set; } = true;
} }
-7
View File
@@ -1,7 +0,0 @@
using SQLite;
namespace cfs_tracker.Models;
public class ThemeSettingItem
{
[PrimaryKey] public string Key { get; set; } = string.Empty;
public string Value { get; set; } = string.Empty;
}
+23
View File
@@ -0,0 +1,23 @@
namespace cfs_tracker.Models;
public enum HealthState : byte
{
Green = 0,
Yellow = 1,
Red = 2,
Gray = 3
}
public enum DayPart : byte
{
Morning = 0,
Afternoon = 1
}
public enum EntrySource : byte
{
App = 0,
Backfill = 1,
Notification = 2,
Import = 3
}
-9
View File
@@ -1,9 +0,0 @@
namespace cfs_tracker.Models;
public class WeekDaySummary
{
public DateTime Date { get; set; }
public double? MorningAverage { get; set; }
public double? AfternoonAverage { get; set; }
public int MorningCount { get; set; }
public int AfternoonCount { get; set; }
}
+14 -14
View File
@@ -1,25 +1,25 @@
using Microsoft.UI.Xaml; using Microsoft.UI.Xaml;
using System.Diagnostics;
// To learn more about WinUI, the WinUI project structure, namespace cfs_tracker.WinUI;
// and more about our project templates, see: http://aka.ms/winui-project-info.
namespace cfs_tracker.WinUI public partial class App : MauiWinUIApplication
{ {
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public partial class App : MauiWinUIApplication
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App() public App()
{ {
this.InitializeComponent(); this.InitializeComponent();
UnhandledException += OnUnhandledException;
}
private void OnUnhandledException(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e)
{
Debug.WriteLine("WINUI UNHANDLED EXCEPTION:");
Debug.WriteLine(e.Message);
if (e.Exception is not null)
Debug.WriteLine(e.Exception.ToString());
} }
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(); protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
}
} }
+18 -1
View File
@@ -1,2 +1,19 @@
# cfs-Tracker # CFS Tracker – kompletter gemeinsamer Neuaufbau
Enthalten sind alle gemeinsamen `.cs`- und `.xaml`-Dateien für den sauberen Neuaufbau der App:
- Tag / Woche / Monat / Jahr
- Optionen / Aussehen
- Tätigkeiten und Symptome in Optionen verwaltbar
- Nachträge für vergangene Tage mit Standard `Vormittag`
- Schnellstatus nur auf `Heute`
- PDF-Export für Tag / Woche / Monat / Jahr
- lokale Datenbank mit optionalem externem Datenbankpfad
- Benachrichtigungs-Zeitpläne im Shared-Code
## Wichtige Hinweise
- Die gemeinsame Logik für Benachrichtigungen ist enthalten.
- Die tatsächliche Android-Planung bleibt absichtlich hinter `INotificationScheduler`, weil plattformspezifischer Code nicht Teil dieses Pakets ist.
- Die PDF-Erzeugung ist ohne zusätzliche Bibliothek umgesetzt und schreibt eine einfache, kompatible PDF-Datei.
- Die App nutzt `CommunityToolkit.Mvvm`, `CommunityToolkit.Maui` und `sqlite-net-pcl`.
+66 -54
View File
@@ -1,74 +1,86 @@
using cfs_tracker.Helpers;
using cfs_tracker.Models; using cfs_tracker.Models;
namespace cfs_tracker.Services; namespace cfs_tracker.Services;
public class AggregationService public class AggregationService
{ {
public List<WeekDaySummary> BuildWeekSummary(DateTime weekStart, IEnumerable<HealthEntry> entries) public AverageStateResult CalculateAverage(IEnumerable<HealthEntry> entries)
{ {
var result = new List<WeekDaySummary>(); var list = entries?.ToList() ?? new List<HealthEntry>();
for (int i = 0; i < 7; i++) if (list.Count == 0)
{ {
var date = weekStart.Date.AddDays(i); return new AverageStateResult
var dayEntries = entries.Where(x => x.Timestamp.Date == date).ToList();
var morning = dayEntries.Where(x => x.Timestamp.Hour < 12).ToList();
var afternoon = dayEntries.Where(x => x.Timestamp.Hour >= 12).ToList();
result.Add(new WeekDaySummary
{ {
Date = date, HasValue = false,
MorningAverage = AverageOrNull(morning), AverageScore = 0,
AfternoonAverage = AverageOrNull(afternoon), State = HealthState.Gray
MorningCount = morning.Count, };
AfternoonCount = afternoon.Count }
var average = list.Average(x => x.State.ToScore());
return new AverageStateResult
{
HasValue = true,
AverageScore = average,
State = average switch
{
>= 2.5 => HealthState.Green,
>= 1.5 => HealthState.Yellow,
>= 0.5 => HealthState.Red,
_ => HealthState.Gray
}
};
}
public IEnumerable<HealthEntry> FilterForDayPart(IEnumerable<HealthEntry> entries, DayPart part)
{
return entries.Where(x =>
{
if (x.DayPart.HasValue)
return x.DayPart == part;
return part == DayPart.Morning
? x.Timestamp.Hour < 12
: x.Timestamp.Hour >= 12;
}); });
} }
return result;
public string BuildDistinctActivityText(IEnumerable<HealthEntry> entries, IReadOnlyDictionary<int, string> activityMap)
{
var names = entries
.Where(x => x.ActivityId.HasValue)
.Select(x => x.ActivityId!.Value)
.Where(activityMap.ContainsKey)
.Select(x => activityMap[x])
.Where(x => !string.Equals(x, "Keine Tätigkeit", StringComparison.OrdinalIgnoreCase))
.Distinct()
.OrderBy(x => x)
.ToList();
return names.Count == 0 ? string.Empty : string.Join(", ", names);
} }
public List<CalendarDaySummary> BuildMonthSummary(DateTime month, IEnumerable<HealthEntry> entries) public string BuildDistinctSymptomText(IEnumerable<HealthEntry> entries, IReadOnlyDictionary<int, List<string>> symptomsByEntryId)
{ {
var first = new DateTime(month.Year, month.Month, 1); var names = entries
int days = DateTime.DaysInMonth(month.Year, month.Month); .Where(x => symptomsByEntryId.ContainsKey(x.Id))
var result = new List<CalendarDaySummary>(); .SelectMany(x => symptomsByEntryId[x.Id])
for (int i = 0; i < days; i++) .Distinct()
{ .OrderBy(x => x)
var date = first.AddDays(i); .ToList();
var dayEntries = entries.Where(x => x.Timestamp.Date == date.Date).ToList();
var avg = AverageOrNull(dayEntries); return names.Count == 0 ? string.Empty : string.Join(", ", names);
result.Add(new CalendarDaySummary { Date = date, Average = avg, EntryCount = dayEntries.Count, DisplayState = ToDisplayState(avg) });
}
return result;
} }
public List<CalendarDaySummary> BuildYearSummary(int year, IEnumerable<HealthEntry> entries) public string ToDisplayText(AverageStateResult averageResult, AppearanceService appearanceService)
{ {
var result = new List<CalendarDaySummary>(); if (!averageResult.HasValue)
for (int month = 1; month <= 12; month++) return "-";
{
int days = DateTime.DaysInMonth(year, month);
for (int day = 1; day <= days; day++)
{
var date = new DateTime(year, month, day);
var dayEntries = entries.Where(x => x.Timestamp.Date == date.Date).ToList();
var avg = AverageOrNull(dayEntries);
result.Add(new CalendarDaySummary { Date = date, Average = avg, EntryCount = dayEntries.Count, DisplayState = ToDisplayState(avg) });
}
}
return result;
}
public HealthState? ToDisplayState(double? average) return appearanceService.GetText(
{ averageResult.State.ToAppearanceTextKey(),
if (average is null) return null; averageResult.State.ToFallbackText());
if (average >= 2.5) return HealthState.Green;
if (average >= 1.5) return HealthState.Yellow;
if (average >= 0.5) return HealthState.Red;
return HealthState.Gray;
}
private static double? AverageOrNull(IEnumerable<HealthEntry> entries)
{
var list = entries.ToList();
return list.Count == 0 ? null : list.Average(x => (int)x.State);
} }
} }
+50
View File
@@ -0,0 +1,50 @@
using cfs_tracker.Data;
namespace cfs_tracker.Services;
public class AppBootstrapService
{
private readonly AppDatabase _database;
private readonly ActivityRepository _activityRepository;
private readonly SymptomRepository _symptomRepository;
private readonly AppearanceRepository _appearanceRepository;
private readonly AppearanceService _appearanceService;
private readonly INotificationScheduler _notificationScheduler;
private bool _initialized;
public AppBootstrapService(
AppDatabase database,
ActivityRepository activityRepository,
SymptomRepository symptomRepository,
AppearanceRepository appearanceRepository,
AppearanceService appearanceService,
INotificationScheduler notificationScheduler)
{
_database = database;
_activityRepository = activityRepository;
_symptomRepository = symptomRepository;
_appearanceRepository = appearanceRepository;
_appearanceService = appearanceService;
_notificationScheduler = notificationScheduler;
}
public async Task InitializeAsync()
{
if (_initialized)
return;
await _database.InitAsync();
await _activityRepository.EnsureDefaultsAsync();
await _symptomRepository.EnsureDefaultsAsync();
await _appearanceRepository.EnsureDefaultsAsync();
// Wichtig: gespeicherte Appearance-Werte direkt beim Start
// auf die App-Ressourcen anwenden.
await _appearanceService.ApplyAsync();
await _notificationScheduler.SyncAsync();
_initialized = true;
}
}
+111 -29
View File
@@ -7,55 +7,137 @@ namespace cfs_tracker.Services;
public class AppearanceService public class AppearanceService
{ {
private readonly AppearanceRepository _repository; private readonly AppearanceRepository _appearanceRepository;
public event Action? AppearanceChanged; public AppearanceService(AppearanceRepository appearanceRepository)
public AppearanceService(AppearanceRepository repository)
{ {
_repository = repository; _appearanceRepository = appearanceRepository;
}
public async Task InitializeAsync()
{
await _repository.EnsureDefaultsAsync();
await ApplyAsync();
} }
public async Task ApplyAsync() public async Task ApplyAsync()
{ {
var items = await _repository.GetAllAsync(); var map = await _appearanceRepository.GetMapAsync();
var resources = Application.Current?.Resources;
foreach (var item in items) if (resources is null)
{ return;
if (item.Key.StartsWith("Status", StringComparison.Ordinal))
{
Application.Current!.Resources[item.Key] = item.Value;
}
else
{
Application.Current!.Resources[item.Key] = Color.FromArgb(item.Value);
}
}
AppearanceChanged?.Invoke(); foreach (var pair in AppearanceDefaults.All)
{
var key = pair.Key;
var fallback = pair.Value;
var value = map.TryGetValue(key, out var stored) && !string.IsNullOrWhiteSpace(stored)
? stored
: fallback;
ApplyValue(resources, key, value, fallback);
}
} }
public async Task SaveColorAsync(string key, string value) public async Task SaveColorAsync(string key, string value)
{ {
await _repository.UpsertAsync(key, value); var fallback = AppearanceDefaults.All.TryGetValue(key, out var defaultValue)
await ApplyAsync(); ? defaultValue
: "#FFFFFF";
var safeValue = string.IsNullOrWhiteSpace(value) ? fallback : value;
await _appearanceRepository.SaveAsync(key, safeValue);
var resources = Application.Current?.Resources;
if (resources is not null)
resources[key] = ColorUtility.ParseColor(safeValue, fallback);
} }
public async Task SaveTextAsync(string key, string value) public async Task SaveTextAsync(string key, string value)
{ {
await _repository.UpsertAsync(key, value); var fallback = AppearanceDefaults.All.TryGetValue(key, out var defaultValue)
await ApplyAsync(); ? defaultValue
: string.Empty;
var safeValue = string.IsNullOrWhiteSpace(value) ? fallback : value;
await _appearanceRepository.SaveAsync(key, safeValue);
var resources = Application.Current?.Resources;
if (resources is not null)
resources[key] = safeValue;
} }
public async Task ResetAsync() public async Task ResetAsync()
{ {
await _repository.ResetToDefaultsAsync(); await _appearanceRepository.ResetAsync();
await _appearanceRepository.EnsureDefaultsAsync();
await ApplyAsync(); await ApplyAsync();
} }
public Color GetColor(string key, string fallback)
{
var resources = Application.Current?.Resources;
if (resources is not null && resources.TryGetValue(key, out var value))
{
if (value is Color color)
return color;
if (value is string text)
return ColorUtility.ParseColor(text, fallback);
}
return ColorUtility.ParseColor(fallback, fallback);
}
public string GetText(string key, string fallback)
{
var resources = Application.Current?.Resources;
if (resources is not null && resources.TryGetValue(key, out var value))
{
if (value is string text && !string.IsNullOrWhiteSpace(text))
return text;
}
return fallback;
}
private static void ApplyValue(ResourceDictionary resources, string key, string value, string fallback)
{
if (IsColorKey(key))
{
resources[key] = ColorUtility.ParseColor(value, fallback);
return;
}
resources[key] = string.IsNullOrWhiteSpace(value) ? fallback : value;
}
private static bool IsColorKey(string key) => key switch
{
AppearanceKeys.AppBackground => true,
AppearanceKeys.SurfaceBackground => true,
AppearanceKeys.SurfaceBackgroundAlt => true,
AppearanceKeys.Border => true,
AppearanceKeys.TextPrimary => true,
AppearanceKeys.TextMuted => true,
AppearanceKeys.StateGreen => true,
AppearanceKeys.StateYellow => true,
AppearanceKeys.StateRed => true,
AppearanceKeys.StateGray => true,
AppearanceKeys.ButtonPrimaryBackground => true,
AppearanceKeys.ButtonPrimaryText => true,
AppearanceKeys.ButtonSecondaryBackground => true,
AppearanceKeys.ButtonSecondaryText => true,
AppearanceKeys.ShellBackground => true,
AppearanceKeys.ShellForeground => true,
AppearanceKeys.ShellTitle => true,
AppearanceKeys.ShellUnselected => true,
AppearanceKeys.TabBarBackground => true,
AppearanceKeys.TabBarForeground => true,
AppearanceKeys.TabBarTitle => true,
AppearanceKeys.TabBarUnselected => true,
_ => false
};
} }
+8 -16
View File
@@ -4,29 +4,21 @@ public class CalendarStateService
{ {
private DateTime _selectedDate = DateTime.Today; private DateTime _selectedDate = DateTime.Today;
public event Action<DateTime>? SelectedDateChanged;
public DateTime SelectedDate public DateTime SelectedDate
{ {
get => _selectedDate; get => _selectedDate;
set set
{ {
var newValue = value.Date; var normalized = value.Date;
if (_selectedDate != newValue) if (_selectedDate == normalized)
{ return;
_selectedDate = newValue;
_selectedDate = normalized;
SelectedDateChanged?.Invoke(_selectedDate); SelectedDateChanged?.Invoke(_selectedDate);
} }
} }
}
public event Action<DateTime>? SelectedDateChanged; public void ResetToToday() => SelectedDate = DateTime.Today;
public async Task ShowDayTabAsync(DateTime date)
{
SelectedDate = date.Date;
if (Shell.Current is null)
return;
await Shell.Current.GoToAsync("//MainTabs/DayTab");
}
} }
+38
View File
@@ -0,0 +1,38 @@
using Microsoft.Maui.Storage;
namespace cfs_tracker.Services;
public class DatabaseLocationService
{
private const string UseExternalDatabaseKey = "db_use_external";
private const string ExternalDatabasePathKey = "db_external_path";
public bool UseExternalDatabase
{
get => Preferences.Default.Get(UseExternalDatabaseKey, false);
set => Preferences.Default.Set(UseExternalDatabaseKey, value);
}
public string ExternalDatabasePath
{
get => Preferences.Default.Get(ExternalDatabasePathKey, string.Empty);
set => Preferences.Default.Set(ExternalDatabasePathKey, value ?? string.Empty);
}
public string ResolveDatabasePath()
{
if (UseExternalDatabase)
{
var configured = (ExternalDatabasePath ?? string.Empty).Trim();
if (!string.IsNullOrWhiteSpace(configured))
{
if (Path.HasExtension(configured))
return configured;
return Path.Combine(configured, "cfs_tracker.db3");
}
}
return Path.Combine(FileSystem.Current.AppDataDirectory, "cfs_tracker.db3");
}
}
+31
View File
@@ -0,0 +1,31 @@
using Microsoft.Maui.ApplicationModel;
namespace cfs_tracker.Services;
public static class ExportUiHelper
{
public static async Task ShowExportSavedActionsAsync(ExportResult result)
{
var action = await Shell.Current.DisplayActionSheetAsync(
$"Export gespeichert:\n{result.FileName}",
"Schließen",
null,
"Öffnen",
"Teilen");
if (action == "Öffnen")
{
await Launcher.Default.OpenAsync(new OpenFileRequest(
"Export öffnen",
new ReadOnlyFile(result.FilePath)));
}
else if (action == "Teilen")
{
await Share.Default.RequestAsync(new ShareFileRequest
{
Title = "Export teilen",
File = new ShareFile(result.FilePath)
});
}
}
}
+6
View File
@@ -0,0 +1,6 @@
namespace cfs_tracker.Services;
public interface INotificationScheduler
{
Task SyncAsync(CancellationToken cancellationToken = default);
}
+13
View File
@@ -0,0 +1,13 @@
namespace cfs_tracker.Services;
public interface IPdfExportService
{
Task<ExportResult> ExportDayAsync(DateTime date);
Task<ExportResult> ExportWeekAsync(DateTime date);
Task<ExportResult> ExportMonthAsync(DateTime date);
Task<ExportResult> ExportMonthAsync(int year, int month);
Task<ExportResult> ExportYearAsync(DateTime date);
Task<ExportResult> ExportYearAsync(int year);
Task<int> ClearExportsAsync();
}
+9
View File
@@ -0,0 +1,9 @@
namespace cfs_tracker.Services;
public sealed class NoOpNotificationScheduler : INotificationScheduler
{
public Task SyncAsync(CancellationToken cancellationToken = default)
{
return Task.CompletedTask;
}
}
+524
View File
@@ -0,0 +1,524 @@
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Models;
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Storage;
using System.Net;
using System.Text;
namespace cfs_tracker.Services;
public sealed class PdfExportService : IPdfExportService
{
private readonly AppDatabase _database;
private readonly HealthEntryRepository _healthEntryRepository;
private readonly AppearanceService _appearanceService;
public PdfExportService(
AppDatabase database,
HealthEntryRepository healthEntryRepository,
AppearanceService appearanceService)
{
_database = database;
_healthEntryRepository = healthEntryRepository;
_appearanceService = appearanceService;
}
public Task<ExportResult> ExportDayAsync(DateTime date)
=> ExportDayHtmlAsync(date.Date);
public Task<ExportResult> ExportWeekAsync(DateTime date)
=> ExportWeekHtmlAsync(date.Date);
public Task<ExportResult> ExportMonthAsync(DateTime date)
=> ExportMonthHtmlAsync(date.Year, date.Month);
public Task<ExportResult> ExportMonthAsync(int year, int month)
=> ExportMonthHtmlAsync(year, month);
public Task<ExportResult> ExportYearAsync(DateTime date)
=> ExportYearHtmlAsync(date.Year);
public Task<ExportResult> ExportYearAsync(int year)
=> ExportYearHtmlAsync(year);
private async Task<ExportResult> ExportDayHtmlAsync(DateTime date)
{
var entries = await _healthEntryRepository.GetEntriesForDateAsync(date);
var activityNames = await GetActivityNamesAsync();
var symptomNamesByEntry = await GetSymptomNamesByEntryAsync(entries.Select(x => x.Id));
var sb = new StringBuilder();
sb.AppendLine($"<h1>Tagesübersicht – {Encode(date.ToString("dd.MM.yyyy"))}</h1>");
sb.AppendLine("<table>");
sb.AppendLine("<thead><tr><th>Uhrzeit</th><th>Status</th><th>Tätigkeit</th><th>Symptome</th></tr></thead>");
sb.AppendLine("<tbody>");
foreach (var entry in entries.OrderBy(x => x.Timestamp).ThenBy(x => x.Id))
{
var symptoms = symptomNamesByEntry.TryGetValue(entry.Id, out var symptomList)
? string.Join(", ", symptomList)
: "—";
var activity = entry.ActivityId.HasValue && activityNames.TryGetValue(entry.ActivityId.Value, out var activityName)
? activityName
: "—";
sb.AppendLine("<tr>");
sb.AppendLine($"<td>{Encode(entry.Timestamp.ToString("HH:mm"))}</td>");
sb.AppendLine(StateCell(entry.State, GetStateText(entry.State)));
sb.AppendLine($"<td>{Encode(activity)}</td>");
sb.AppendLine($"<td>{Encode(symptoms)}</td>");
sb.AppendLine("</tr>");
}
if (entries.Count == 0)
sb.AppendLine("<tr><td colspan=\"4\">Keine Einträge vorhanden.</td></tr>");
sb.AppendLine("</tbody></table>");
return await SaveHtmlAsync(
fileName: $"tag-{date:yyyy-MM-dd}.html",
title: $"Tag {date:dd.MM.yyyy}",
bodyHtml: sb.ToString());
}
private async Task<ExportResult> ExportWeekHtmlAsync(DateTime date)
{
var weekStart = StartOfWeekMonday(date);
var weekEnd = weekStart.AddDays(7);
var entries = await _healthEntryRepository.GetEntriesBetweenAsync(weekStart, weekEnd);
var activityNames = await GetActivityNamesAsync();
var symptomNamesByEntry = await GetSymptomNamesByEntryAsync(entries.Select(x => x.Id));
var sb = new StringBuilder();
sb.AppendLine($"<h1>Wochenübersicht – {Encode(weekStart.ToString("dd.MM.yyyy"))} bis {Encode(weekStart.AddDays(6).ToString("dd.MM.yyyy"))}</h1>");
sb.AppendLine("<table>");
sb.AppendLine("<thead><tr><th>Tag</th><th>Anzahl</th><th>Status</th><th>Tätigkeiten</th><th>Symptome</th></tr></thead>");
sb.AppendLine("<tbody>");
for (var i = 0; i < 7; i++)
{
var currentDay = weekStart.AddDays(i).Date;
var dayEntries = entries.Where(x => x.EntryDate.Date == currentDay).OrderBy(x => x.Timestamp).ToList();
var averageState = CalculateAverageState(dayEntries);
var statusText = dayEntries.Count == 0
? "—"
: $"{GetStateText(averageState!.Value)} ({dayEntries.Count})";
var activities = dayEntries
.Where(x => x.ActivityId.HasValue)
.Select(x => activityNames.TryGetValue(x.ActivityId!.Value, out var name) ? name : null)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Cast<string>()
.Distinct()
.ToList();
var symptoms = dayEntries
.SelectMany(x => symptomNamesByEntry.TryGetValue(x.Id, out var list) ? list : Enumerable.Empty<string>())
.Distinct()
.ToList();
sb.AppendLine("<tr>");
sb.AppendLine($"<td>{Encode(currentDay.ToString("ddd, dd.MM.yyyy"))}</td>");
sb.AppendLine($"<td>{dayEntries.Count}</td>");
sb.AppendLine(averageState.HasValue
? StateCell(averageState.Value, statusText)
: "<td>—</td>");
sb.AppendLine($"<td>{Encode(activities.Count > 0 ? string.Join(", ", activities) : "—")}</td>");
sb.AppendLine($"<td>{Encode(symptoms.Count > 0 ? string.Join(", ", symptoms) : "—")}</td>");
sb.AppendLine("</tr>");
}
sb.AppendLine("</tbody></table>");
return await SaveHtmlAsync(
fileName: $"woche-{weekStart:yyyy-MM-dd}.html",
title: $"Woche {weekStart:dd.MM.yyyy}",
bodyHtml: sb.ToString());
}
private async Task<ExportResult> ExportMonthHtmlAsync(int year, int month)
{
var monthStart = new DateTime(year, month, 1);
var monthEnd = monthStart.AddMonths(1);
var entries = await _healthEntryRepository.GetEntriesBetweenAsync(monthStart, monthEnd);
var activityNames = await GetActivityNamesAsync();
var symptomNamesByEntry = await GetSymptomNamesByEntryAsync(entries.Select(x => x.Id));
var sb = new StringBuilder();
sb.AppendLine($"<h1>Monatsübersicht – {Encode(monthStart.ToString("MMMM yyyy"))}</h1>");
sb.AppendLine("<table>");
sb.AppendLine("""
<thead>
<tr>
<th class="compact-day">Tag</th>
<th class="compact-count">Anzahl</th>
<th>Status</th>
<th class="compact-activity">Tätigkeiten</th>
<th class="compact-symptoms">Symptome</th>
</tr>
</thead>
<tbody>
""");
var daysInMonth = DateTime.DaysInMonth(year, month);
for (var day = 1; day <= daysInMonth; day++)
{
var currentDay = new DateTime(year, month, day);
var dayEntries = entries.Where(x => x.EntryDate.Date == currentDay.Date).OrderBy(x => x.Timestamp).ToList();
var averageState = CalculateAverageState(dayEntries);
var statusText = dayEntries.Count == 0
? "—"
: GetStateText(averageState!.Value);
var activities = dayEntries
.Where(x => x.ActivityId.HasValue)
.Select(x => activityNames.TryGetValue(x.ActivityId!.Value, out var name) ? name : null)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Cast<string>()
.Distinct()
.ToList();
var symptoms = dayEntries
.SelectMany(x => symptomNamesByEntry.TryGetValue(x.Id, out var list) ? list : Enumerable.Empty<string>())
.Distinct()
.ToList();
sb.AppendLine("<tr>");
sb.AppendLine($"<td class=\"compact-day\">{Encode(currentDay.ToString("dd.MM."))}</td>");
sb.AppendLine($"<td class=\"compact-count\">{dayEntries.Count}</td>");
sb.AppendLine(averageState.HasValue
? StateCellCompact(averageState.Value, statusText)
: "<td>—</td>");
sb.AppendLine($"<td class=\"compact-activity\">{Encode(activities.Count > 0 ? string.Join(", ", activities) : "—")}</td>");
sb.AppendLine($"<td class=\"compact-symptoms\">{Encode(symptoms.Count > 0 ? string.Join(", ", symptoms) : "—")}</td>");
sb.AppendLine("</tr>");
}
sb.AppendLine("</tbody></table>");
return await SaveHtmlAsync(
fileName: $"monat-{year}-{month:00}.html",
title: $"Monat {monthStart:MMMM yyyy}",
bodyHtml: sb.ToString(),
compactA4: true);
}
private async Task<ExportResult> ExportYearHtmlAsync(int year)
{
var yearStart = new DateTime(year, 1, 1);
var yearEnd = yearStart.AddYears(1);
var entries = await _healthEntryRepository.GetEntriesBetweenAsync(yearStart, yearEnd);
var activityNames = await GetActivityNamesAsync();
var symptomNamesByEntry = await GetSymptomNamesByEntryAsync(entries.Select(x => x.Id));
var sb = new StringBuilder();
sb.AppendLine($"<h1>Jahresübersicht – {year}</h1>");
sb.AppendLine("<table>");
sb.AppendLine("<thead><tr><th>Monat</th><th>Anzahl Einträge</th><th>Status</th><th>Tätigkeiten</th><th>Symptome</th></tr></thead>");
sb.AppendLine("<tbody>");
for (var month = 1; month <= 12; month++)
{
var monthEntries = entries
.Where(x => x.EntryDate.Year == year && x.EntryDate.Month == month)
.OrderBy(x => x.Timestamp)
.ToList();
var monthDate = new DateTime(year, month, 1);
var averageState = CalculateAverageState(monthEntries);
var statusText = monthEntries.Count == 0
? "—"
: $"{GetStateText(averageState!.Value)} ({monthEntries.Count})";
var activities = monthEntries
.Where(x => x.ActivityId.HasValue)
.Select(x => activityNames.TryGetValue(x.ActivityId!.Value, out var name) ? name : null)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Cast<string>()
.Distinct()
.ToList();
var symptoms = monthEntries
.SelectMany(x => symptomNamesByEntry.TryGetValue(x.Id, out var list) ? list : Enumerable.Empty<string>())
.Distinct()
.ToList();
sb.AppendLine("<tr>");
sb.AppendLine($"<td>{Encode(monthDate.ToString("MMMM"))}</td>");
sb.AppendLine($"<td>{monthEntries.Count}</td>");
sb.AppendLine(averageState.HasValue
? StateCell(averageState.Value, statusText)
: "<td>—</td>");
sb.AppendLine($"<td>{Encode(activities.Count > 0 ? string.Join(", ", activities) : "—")}</td>");
sb.AppendLine($"<td>{Encode(symptoms.Count > 0 ? string.Join(", ", symptoms) : "—")}</td>");
sb.AppendLine("</tr>");
}
sb.AppendLine("</tbody></table>");
return await SaveHtmlAsync(
fileName: $"jahr-{year}.html",
title: $"Jahr {year}",
bodyHtml: sb.ToString());
}
private async Task<Dictionary<int, string>> GetActivityNamesAsync()
{
await _database.InitAsync();
var rows = await _database.Connection.Table<ActivityItem>().ToListAsync();
return rows
.GroupBy(x => x.Id)
.ToDictionary(g => g.Key, g => g.First().Name);
}
private async Task<Dictionary<int, List<string>>> GetSymptomNamesByEntryAsync(IEnumerable<int> entryIds)
{
await _database.InitAsync();
var ids = entryIds.Distinct().ToList();
if (ids.Count == 0)
return new Dictionary<int, List<string>>();
var links = await _database.Connection.Table<HealthEntrySymptom>().ToListAsync();
var filteredLinks = links.Where(x => ids.Contains(x.HealthEntryId)).ToList();
if (filteredLinks.Count == 0)
return new Dictionary<int, List<string>>();
var symptomIds = filteredLinks.Select(x => x.SymptomItemId).Distinct().ToList();
var symptomMap = (await _database.Connection.Table<SymptomItem>().ToListAsync())
.Where(x => symptomIds.Contains(x.Id))
.GroupBy(x => x.Id)
.ToDictionary(g => g.Key, g => g.First().Name);
return filteredLinks
.GroupBy(x => x.HealthEntryId)
.ToDictionary(
g => g.Key,
g => g.Select(x => symptomMap.TryGetValue(x.SymptomItemId, out var name) ? name : null)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Cast<string>()
.Distinct()
.ToList());
}
private async Task<ExportResult> SaveHtmlAsync(
string fileName,
string title,
string bodyHtml,
bool compactA4 = false)
{
var folder = GetExportFolderPath();
Directory.CreateDirectory(folder);
var path = Path.Combine(folder, fileName);
var html = WrapHtml(title, bodyHtml, compactA4);
await File.WriteAllTextAsync(path, html, Encoding.UTF8);
return new ExportResult
{
FilePath = path,
FileName = fileName
};
}
private string StateCell(HealthState state, string text)
{
var background = GetStateBackgroundCss(state);
var foreground = GetStateForegroundCss(state);
return $"<td style=\"background:{background};color:{foreground};font-weight:bold;\">{Encode(text)}</td>";
}
private string StateCellCompact(HealthState state, string text)
{
var background = GetStateBackgroundCss(state);
var foreground = GetStateForegroundCss(state);
return $"<td class=\"compact-status\" style=\"background:{background};color:{foreground};\">{Encode(text)}</td>";
}
private string GetStateBackgroundCss(HealthState state) => state switch
{
HealthState.Green => ToCssHex(_appearanceService.GetColor(AppearanceKeys.StateGreen, "#4E8B69")),
HealthState.Yellow => ToCssHex(_appearanceService.GetColor(AppearanceKeys.StateYellow, "#B89A42")),
HealthState.Red => ToCssHex(_appearanceService.GetColor(AppearanceKeys.StateRed, "#A85C5C")),
HealthState.Gray => ToCssHex(_appearanceService.GetColor(AppearanceKeys.StateGray, "#1F242B")),
_ => "#FFFFFF"
};
private static string GetStateForegroundCss(HealthState state) => state switch
{
HealthState.Yellow => "#000000",
_ => "#FFFFFF"
};
private string GetStateText(HealthState state) => state switch
{
HealthState.Green => _appearanceService.GetText(AppearanceKeys.StatusGreenText, "Grün"),
HealthState.Yellow => _appearanceService.GetText(AppearanceKeys.StatusYellowText, "Gelb"),
HealthState.Red => _appearanceService.GetText(AppearanceKeys.StatusRedText, "Rot"),
HealthState.Gray => _appearanceService.GetText(AppearanceKeys.StatusGrayText, "Schwarz"),
_ => string.Empty
};
private static DateTime StartOfWeekMonday(DateTime date)
{
var diff = ((int)date.DayOfWeek + 6) % 7;
return date.Date.AddDays(-diff);
}
private static HealthState? CalculateAverageState(IReadOnlyCollection<HealthEntry> entries)
{
if (entries.Count == 0)
return null;
var average = entries.Average(x => StateToNumber(x.State));
var rounded = (int)Math.Round(average, MidpointRounding.AwayFromZero);
return rounded switch
{
<= 0 => HealthState.Green,
1 => HealthState.Yellow,
2 => HealthState.Red,
_ => HealthState.Gray
};
}
private static int StateToNumber(HealthState state) => state switch
{
HealthState.Green => 0,
HealthState.Yellow => 1,
HealthState.Red => 2,
HealthState.Gray => 3,
_ => 0
};
private static string ToCssHex(Color color)
{
var r = (int)Math.Round(color.Red * 255);
var g = (int)Math.Round(color.Green * 255);
var b = (int)Math.Round(color.Blue * 255);
return $"#{r:X2}{g:X2}{b:X2}";
}
private static string Encode(string value) => WebUtility.HtmlEncode(value);
private static string GetExportFolderPath()
{
return Path.Combine(FileSystem.Current.AppDataDirectory, "exports");
}
public Task<int> ClearExportsAsync()
{
var folder = GetExportFolderPath();
if (!Directory.Exists(folder))
return Task.FromResult(0);
var files = Directory.GetFiles(folder);
var deleted = 0;
foreach (var file in files)
{
try
{
File.Delete(file);
deleted++;
}
catch
{
// absichtlich ignorieren, damit eine einzelne blockierte Datei
// nicht den ganzen Vorgang abbricht
}
}
return Task.FromResult(deleted);
}
private static string WrapHtml(string title, string body, bool compactA4 = false) => $$"""
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<title>{{Encode(title)}}</title>
<style>
@page {
size: {{(compactA4 ? "A4 landscape" : "A4 portrait")}};
margin: {{(compactA4 ? "8mm" : "14mm")}};
}
body {
font-family: Arial, Helvetica, sans-serif;
background: #ffffff;
color: #000000;
margin: {{(compactA4 ? "8px" : "24px")}};
font-size: {{(compactA4 ? "11px" : "14px")}};
line-height: {{(compactA4 ? "1.15" : "1.35")}};
}
h1 {
margin: 0 0 {{(compactA4 ? "8px" : "16px")}} 0;
font-size: {{(compactA4 ? "18px" : "28px")}};
}
table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
background: #ffffff;
}
th, td {
border: 1px solid #000000;
padding: {{(compactA4 ? "3px 4px" : "8px")}};
text-align: left;
vertical-align: top;
overflow-wrap: anywhere;
word-break: break-word;
}
th {
background: #f3f3f3;
}
.compact-status {
text-align: center;
font-weight: bold;
white-space: nowrap;
}
.compact-day {
width: 12%;
white-space: nowrap;
}
.compact-count {
width: 10%;
text-align: center;
white-space: nowrap;
}
.compact-activity {
width: 26%;
}
.compact-symptoms {
width: 32%;
}
</style>
</head>
<body>
{{body}}
</body>
</html>
""";
}
+20
View File
@@ -0,0 +1,20 @@
using CommunityToolkit.Mvvm.ComponentModel;
namespace cfs_tracker.ViewModels;
public partial class ActivityManageItemViewModel : ObservableObject
{
public int Id { get; init; }
[ObservableProperty]
private string name = string.Empty;
[ObservableProperty]
private bool isActive;
public bool IsUsed { get; init; }
public string UsageHint => IsUsed
? "Bereits verwendet – kann nur deaktiviert werden."
: "Kann gelöscht werden, solange unbenutzt.";
}
@@ -0,0 +1,7 @@
namespace cfs_tracker.ViewModels;
public class ActivityPickerItemViewModel
{
public int? Id { get; init; }
public string Name { get; init; } = string.Empty;
}
+13 -4
View File
@@ -1,14 +1,23 @@
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using cfs_tracker.Helpers;
using Microsoft.Maui.Graphics;
namespace cfs_tracker.ViewModels; namespace cfs_tracker.ViewModels;
public partial class AppearanceColorItemViewModel : ObservableObject public partial class AppearanceColorItemViewModel : ObservableObject
{ {
public string Key { get; init; } = string.Empty; public string Key { get; init; } = string.Empty;
public string Title { get; init; } = string.Empty;
[ObservableProperty] public string Fallback { get; init; } = "#000000";
private string title = string.Empty;
[ObservableProperty] [ObservableProperty]
private string value = string.Empty; private string value = string.Empty;
[ObservableProperty]
private Color previewColor = Colors.Transparent;
partial void OnValueChanged(string value)
{
PreviewColor = ColorUtility.ParseColor(value, Fallback);
}
} }
+2 -4
View File
@@ -1,13 +1,11 @@
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
namespace cfs_tracker.ViewModels; namespace cfs_tracker.ViewModels;
public partial class AppearanceTextItemViewModel : ObservableObject public partial class AppearanceTextItemViewModel : ObservableObject
{ {
public string Key { get; init; } = string.Empty; public string Key { get; init; } = string.Empty;
public string Title { get; init; } = string.Empty;
[ObservableProperty]
private string title = string.Empty;
[ObservableProperty] [ObservableProperty]
private string value = string.Empty; private string value = string.Empty;
+11 -9
View File
@@ -7,21 +7,19 @@ namespace cfs_tracker.ViewModels;
public partial class DayEntryItemViewModel : ObservableObject public partial class DayEntryItemViewModel : ObservableObject
{ {
public int Id { get; init; } public int Id { get; init; }
public DateTime Date { get; init; }
public string TimeText { get; init; } = string.Empty; public string SlotText { get; init; } = string.Empty;
public string StateText { get; init; } = string.Empty; public string StateText { get; init; } = string.Empty;
public string ActivityText { get; init; } = string.Empty; public string ActivityText { get; init; } = string.Empty;
public string SymptomsText { get; init; } = string.Empty; public string SymptomsText { get; init; } = string.Empty;
public bool IsBackfill { get; init; }
public Color StateColor { get; init; } = Colors.Transparent;
public Color ForegroundColor { get; init; } = Colors.White;
public bool HasActivity => !string.IsNullOrWhiteSpace(ActivityText); public bool HasActivity => !string.IsNullOrWhiteSpace(ActivityText);
public bool HasSymptoms => !string.IsNullOrWhiteSpace(SymptomsText); public bool HasSymptoms => !string.IsNullOrWhiteSpace(SymptomsText);
public bool HasDetails => HasActivity || HasSymptoms; public bool HasDetails => HasActivity || HasSymptoms;
public string DetailsButtonText => IsExpanded ? "Details ausblenden" : "Details anzeigen";
public string FoldoutText => IsExpanded ? "Details ausblenden" : "Details anzeigen";
public Color BackgroundColor { get; init; } = Colors.Transparent;
public Color TextColor { get; init; } = Colors.White;
[ObservableProperty] [ObservableProperty]
private bool isExpanded; private bool isExpanded;
@@ -33,12 +31,16 @@ public partial class DayEntryItemViewModel : ObservableObject
ToggleExpandedCommand = new RelayCommand(ToggleExpanded); ToggleExpandedCommand = new RelayCommand(ToggleExpanded);
} }
partial void OnIsExpandedChanged(bool value)
{
OnPropertyChanged(nameof(DetailsButtonText));
}
private void ToggleExpanded() private void ToggleExpanded()
{ {
if (!HasDetails) if (!HasDetails)
return; return;
IsExpanded = !IsExpanded; IsExpanded = !IsExpanded;
OnPropertyChanged(nameof(FoldoutText));
} }
} }
+9
View File
@@ -0,0 +1,9 @@
using cfs_tracker.Models;
namespace cfs_tracker.ViewModels;
public class DayPartOptionItemViewModel
{
public DayPart Value { get; init; }
public string Name { get; init; } = string.Empty;
}
+222 -82
View File
@@ -1,28 +1,40 @@
using System.Collections.ObjectModel;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data; using cfs_tracker.Data;
using cfs_tracker.Helpers; using cfs_tracker.Helpers;
using cfs_tracker.Models; using cfs_tracker.Models;
using cfs_tracker.Services; using cfs_tracker.Services;
using cfs_tracker.Views; using System.Collections.ObjectModel;
using System.Globalization;
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Storage;
namespace cfs_tracker.ViewModels; namespace cfs_tracker.ViewModels;
public partial class DayViewModel : ObservableObject public partial class DayViewModel : ObservableObject
{ {
private readonly HealthEntryRepository _repository; private readonly HealthEntryRepository _healthEntryRepository;
private readonly ActivityRepository _activityRepository; private readonly ActivityRepository _activityRepository;
private readonly SymptomRepository _symptomRepository; private readonly SymptomRepository _symptomRepository;
private readonly CalendarStateService _calendarState; private readonly AppearanceService _appearanceService;
private readonly CalendarStateService _calendarStateService;
private readonly IPdfExportService _pdfExportService;
[ObservableProperty] [ObservableProperty]
private DateTime selectedDate = DateTime.Today; private DateTime selectedDate;
[ObservableProperty] [ObservableProperty]
private string selectedDateText = string.Empty; private string selectedDateText = string.Empty;
[ObservableProperty]
private bool isToday;
[ObservableProperty]
private bool isPastDate;
[ObservableProperty]
private bool isFutureDate;
[ObservableProperty] [ObservableProperty]
private int greenCount; private int greenCount;
@@ -36,76 +48,129 @@ public partial class DayViewModel : ObservableObject
private int grayCount; private int grayCount;
[ObservableProperty] [ObservableProperty]
private string greenStatusText = ThemeResourceHelper.GetString(ThemeKeys.StatusGreenText, "Grün"); private string greenStatusText = "Grün";
[ObservableProperty] [ObservableProperty]
private string yellowStatusText = ThemeResourceHelper.GetString(ThemeKeys.StatusYellowText, "Gelb"); private string yellowStatusText = "Gelb";
[ObservableProperty] [ObservableProperty]
private string redStatusText = ThemeResourceHelper.GetString(ThemeKeys.StatusRedText, "Rot"); private string redStatusText = "Rot";
[ObservableProperty] [ObservableProperty]
private string grayStatusText = ThemeResourceHelper.GetString(ThemeKeys.StatusGrayText, "Grau"); private string grayStatusText = "Schwarz";
[ObservableProperty]
private Color greenStateColor = Color.FromArgb("#4E8B69");
[ObservableProperty]
private Color yellowStateColor = Color.FromArgb("#B89A42");
[ObservableProperty]
private Color redStateColor = Color.FromArgb("#A85C5C");
[ObservableProperty]
private Color grayStateColor = Color.FromArgb("#1F242B");
[ObservableProperty]
private Color primaryTextColor = Color.FromArgb("#DCE7F3");
[ObservableProperty]
private bool hasEntries;
public ObservableCollection<DayEntryItemViewModel> Entries { get; } = new(); public ObservableCollection<DayEntryItemViewModel> Entries { get; } = new();
public string GreenCounterText => BuildCounterText(GreenStatusText, GreenCount);
public string YellowCounterText => BuildCounterText(YellowStatusText, YellowCount);
public string RedCounterText => BuildCounterText(RedStatusText, RedCount);
public string GrayCounterText => BuildCounterText(GrayStatusText, GrayCount);
public string AddEntryButtonText => IsPastDate ? "+ Nachtrag" : "+ Eintrag";
public bool CanAddEntry => !IsFutureDate;
public bool HasNoEntries => !HasEntries;
public string DayHintText => IsToday
? "Heute kannst du Schnellstatus oder einen Eintrag mit Tätigkeit und Symptomen setzen."
: IsPastDate
? "Für vergangene Tage legst du einen Nachtrag für Vormittag oder Nachmittag an."
: "Für zukünftige Tage sind keine Einträge möglich.";
public IAsyncRelayCommand PreviousDayCommand { get; } public IAsyncRelayCommand PreviousDayCommand { get; }
public IAsyncRelayCommand NextDayCommand { get; } public IAsyncRelayCommand NextDayCommand { get; }
public IAsyncRelayCommand TodayCommand { get; } public IAsyncRelayCommand TodayCommand { get; }
public IAsyncRelayCommand AddEntryCommand { get; } public IAsyncRelayCommand AddEntryCommand { get; }
public IAsyncRelayCommand<DayEntryItemViewModel> DeleteEntryCommand { get; }
public IAsyncRelayCommand SaveGreenQuickCommand { get; } public IAsyncRelayCommand SaveGreenQuickCommand { get; }
public IAsyncRelayCommand SaveYellowQuickCommand { get; } public IAsyncRelayCommand SaveYellowQuickCommand { get; }
public IAsyncRelayCommand SaveRedQuickCommand { get; } public IAsyncRelayCommand SaveRedQuickCommand { get; }
public IAsyncRelayCommand SaveGrayQuickCommand { get; } public IAsyncRelayCommand SaveGrayQuickCommand { get; }
public IAsyncRelayCommand<DayEntryItemViewModel> EditEntryCommand { get; }
public IAsyncRelayCommand<DayEntryItemViewModel> DeleteEntryCommand { get; }
public IAsyncRelayCommand ExportPdfCommand { get; }
public DayViewModel( public DayViewModel(
HealthEntryRepository repository, HealthEntryRepository healthEntryRepository,
ActivityRepository activityRepository, ActivityRepository activityRepository,
SymptomRepository symptomRepository, SymptomRepository symptomRepository,
CalendarStateService calendarState) AppearanceService appearanceService,
CalendarStateService calendarStateService,
IPdfExportService pdfExportService)
{ {
_repository = repository; _healthEntryRepository = healthEntryRepository;
_activityRepository = activityRepository; _activityRepository = activityRepository;
_symptomRepository = symptomRepository; _symptomRepository = symptomRepository;
_calendarState = calendarState; _appearanceService = appearanceService;
_calendarStateService = calendarStateService;
_pdfExportService = pdfExportService;
SelectedDate = _calendarState.SelectedDate; SelectedDate = _calendarStateService.SelectedDate;
_calendarState.SelectedDateChanged += OnSharedSelectedDateChanged; UpdateDateState();
UpdateSelectedDateText();
PreviousDayCommand = new AsyncRelayCommand(PreviousDayAsync); PreviousDayCommand = new AsyncRelayCommand(PreviousDayAsync);
NextDayCommand = new AsyncRelayCommand(NextDayAsync); NextDayCommand = new AsyncRelayCommand(NextDayAsync);
TodayCommand = new AsyncRelayCommand(SetTodayAsync); TodayCommand = new AsyncRelayCommand(TodayAsync);
AddEntryCommand = new AsyncRelayCommand(OpenQuickEntryAsync); AddEntryCommand = new AsyncRelayCommand(AddEntryAsync);
DeleteEntryCommand = new AsyncRelayCommand<DayEntryItemViewModel>(DeleteEntryAsync);
SaveGreenQuickCommand = new AsyncRelayCommand(() => QuickSaveAsync(HealthState.Green)); SaveGreenQuickCommand = new AsyncRelayCommand(() => QuickSaveAsync(HealthState.Green));
SaveYellowQuickCommand = new AsyncRelayCommand(() => QuickSaveAsync(HealthState.Yellow)); SaveYellowQuickCommand = new AsyncRelayCommand(() => QuickSaveAsync(HealthState.Yellow));
SaveRedQuickCommand = new AsyncRelayCommand(() => QuickSaveAsync(HealthState.Red)); SaveRedQuickCommand = new AsyncRelayCommand(() => QuickSaveAsync(HealthState.Red));
SaveGrayQuickCommand = new AsyncRelayCommand(() => QuickSaveAsync(HealthState.Gray)); SaveGrayQuickCommand = new AsyncRelayCommand(() => QuickSaveAsync(HealthState.Gray));
EditEntryCommand = new AsyncRelayCommand<DayEntryItemViewModel>(EditEntryAsync);
DeleteEntryCommand = new AsyncRelayCommand<DayEntryItemViewModel>(DeleteEntryAsync);
ExportPdfCommand = new AsyncRelayCommand(ExportAsync);
UpdateDateText(); _calendarStateService.SelectedDateChanged += HandleSharedDateChanged;
RefreshStatusTexts(); Entries.CollectionChanged += (_, _) =>
{
HasEntries = Entries.Count > 0;
OnPropertyChanged(nameof(HasNoEntries));
};
} }
partial void OnSelectedDateChanged(DateTime value) partial void OnSelectedDateChanged(DateTime value)
{ {
UpdateDateText(); UpdateDateState();
UpdateSelectedDateText();
} }
private async void OnSharedSelectedDateChanged(DateTime date) partial void OnGreenCountChanged(int value) => RaiseCounterTextChanged();
{ partial void OnYellowCountChanged(int value) => RaiseCounterTextChanged();
SelectedDate = date; partial void OnRedCountChanged(int value) => RaiseCounterTextChanged();
await RefreshAsync(); partial void OnGrayCountChanged(int value) => RaiseCounterTextChanged();
} partial void OnGreenStatusTextChanged(string value) => RaiseCounterTextChanged();
partial void OnYellowStatusTextChanged(string value) => RaiseCounterTextChanged();
partial void OnRedStatusTextChanged(string value) => RaiseCounterTextChanged();
partial void OnGrayStatusTextChanged(string value) => RaiseCounterTextChanged();
partial void OnIsPastDateChanged(bool value) => RaiseDayModeChanged();
partial void OnIsTodayChanged(bool value) => RaiseDayModeChanged();
partial void OnIsFutureDateChanged(bool value) => RaiseDayModeChanged();
public async Task RefreshAsync() public async Task RefreshAsync()
{ {
SelectedDate = _calendarState.SelectedDate; SelectedDate = _calendarStateService.SelectedDate;
RefreshStatusTexts(); LoadAppearance();
var entries = await _repository.GetEntriesForDateAsync(SelectedDate); var entries = await _healthEntryRepository.GetEntriesForDateAsync(SelectedDate);
var activityMap = await _activityRepository.GetNameMapAsync();
var symptomsByEntryId = await _symptomRepository.GetSymptomsByEntryIdsAsync(entries.Select(x => x.Id));
GreenCount = entries.Count(x => x.State == HealthState.Green); GreenCount = entries.Count(x => x.State == HealthState.Green);
YellowCount = entries.Count(x => x.State == HealthState.Yellow); YellowCount = entries.Count(x => x.State == HealthState.Yellow);
@@ -114,76 +179,81 @@ public partial class DayViewModel : ObservableObject
Entries.Clear(); Entries.Clear();
var activityMap = await _activityRepository.GetNameMapAsync(); foreach (var entry in entries.OrderBy(x => x.Timestamp).ThenBy(x => x.Id))
var symptomMapByEntry = await _symptomRepository.GetSymptomsByEntryIdsAsync(entries.Select(x => x.Id));
foreach (var entry in entries.OrderBy(x => x.Timestamp))
{ {
string activityText = string.Empty; var slotText = entry.DayPart switch
if (entry.ActivityId.HasValue && activityMap.TryGetValue(entry.ActivityId.Value, out var activityName)) {
activityText = activityName; DayPart.Morning => "Vormittag",
DayPart.Afternoon => "Nachmittag",
_ => entry.Timestamp.ToString("HH:mm", CultureInfo.InvariantCulture)
};
symptomMapByEntry.TryGetValue(entry.Id, out var symptoms); var activityText = string.Empty;
string symptomsText = symptoms is { Count: > 0 } if (entry.ActivityId.HasValue && activityMap.TryGetValue(entry.ActivityId.Value, out var activityName) &&
!string.Equals(activityName, "Keine Tätigkeit", StringComparison.OrdinalIgnoreCase))
{
activityText = activityName;
}
symptomsByEntryId.TryGetValue(entry.Id, out var symptoms);
var symptomText = symptoms is { Count: > 0 }
? string.Join(", ", symptoms) ? string.Join(", ", symptoms)
: string.Empty; : string.Empty;
Entries.Add(new DayEntryItemViewModel Entries.Add(new DayEntryItemViewModel
{ {
Id = entry.Id, Id = entry.Id,
TimeText = entry.Timestamp.ToString("HH:mm"), Date = entry.EntryDate,
StateText = ThemeResourceHelper.GetString( SlotText = slotText,
entry.State.ToTextKey(), StateText = _appearanceService.GetText(
entry.State.ToAppearanceTextKey(),
entry.State.ToFallbackText()), entry.State.ToFallbackText()),
ActivityText = activityText, ActivityText = activityText,
SymptomsText = symptomsText, SymptomsText = symptomText,
BackgroundColor = ThemeResourceHelper.GetColor(entry.State.ToColorKey(), "#203041"), IsBackfill = entry.DayPart.HasValue,
TextColor = ThemeResourceHelper.GetColor(ThemeKeys.TextPrimary, "#D9E6F2") StateColor = _appearanceService.GetColor(entry.State.ToAppearanceColorKey(), "#1F242B"),
ForegroundColor = PrimaryTextColor
}); });
} }
HasEntries = Entries.Count > 0;
OnPropertyChanged(nameof(HasNoEntries));
} }
private async Task QuickSaveAsync(HealthState state) private async Task QuickSaveAsync(HealthState state)
{ {
if (SelectedDate.Date == DateTime.Today) if (!IsToday)
{ {
await _repository.AddEntryAsync( await AddEntryAsync();
state,
EntrySource.App,
DateTime.Now);
await RefreshAsync();
return; return;
} }
await OpenQuickEntryAsync(); await _healthEntryRepository.AddQuickEntryAsync(
} state: state,
activityId: null,
symptomIds: null,
timestamp: DateTime.Now,
source: EntrySource.App);
private async Task PreviousDayAsync()
{
_calendarState.SelectedDate = SelectedDate.AddDays(-1);
SelectedDate = _calendarState.SelectedDate;
await RefreshAsync(); await RefreshAsync();
} }
private async Task NextDayAsync() private async Task AddEntryAsync()
{ {
_calendarState.SelectedDate = SelectedDate.AddDays(1); if (IsFutureDate)
SelectedDate = _calendarState.SelectedDate; return;
await RefreshAsync();
var date = Uri.EscapeDataString(SelectedDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
await Shell.Current.GoToAsync($"{nameof(Views.QuickEntryPage)}?date={date}");
} }
private async Task SetTodayAsync() private async Task EditEntryAsync(DayEntryItemViewModel? item)
{ {
_calendarState.SelectedDate = DateTime.Today; if (item is null)
SelectedDate = _calendarState.SelectedDate; return;
await RefreshAsync();
}
private async Task OpenQuickEntryAsync() var date = Uri.EscapeDataString(item.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
{ await Shell.Current.GoToAsync($"{nameof(Views.QuickEntryPage)}?date={date}&entryId={item.Id}");
string date = SelectedDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
await Shell.Current.GoToAsync($"{nameof(QuickEntryPage)}?date={date}");
} }
private async Task DeleteEntryAsync(DayEntryItemViewModel? item) private async Task DeleteEntryAsync(DayEntryItemViewModel? item)
@@ -191,20 +261,90 @@ public partial class DayViewModel : ObservableObject
if (item is null) if (item is null)
return; return;
await _repository.DeleteEntryAsync(item.Id); var accepted = await Application.Current!.Windows[0].Page!.DisplayAlertAsync(
"Eintrag löschen",
"Soll dieser Eintrag wirklich gelöscht werden?",
"Ja",
"Nein");
if (!accepted)
return;
await _healthEntryRepository.DeleteEntryAsync(item.Id);
await RefreshAsync(); await RefreshAsync();
} }
private void UpdateDateText() private async Task ExportAsync()
{ {
SelectedDateText = SelectedDate.ToString("dddd, dd. MMMM yyyy", new CultureInfo("de-DE")); var result = await _pdfExportService.ExportDayAsync(SelectedDate);
await ExportUiHelper.ShowExportSavedActionsAsync(result);
} }
private void RefreshStatusTexts() private async Task PreviousDayAsync()
{ {
GreenStatusText = ThemeResourceHelper.GetString(ThemeKeys.StatusGreenText, "Grün"); _calendarStateService.SelectedDate = SelectedDate.AddDays(-1);
YellowStatusText = ThemeResourceHelper.GetString(ThemeKeys.StatusYellowText, "Gelb"); await RefreshAsync();
RedStatusText = ThemeResourceHelper.GetString(ThemeKeys.StatusRedText, "Rot");
GrayStatusText = ThemeResourceHelper.GetString(ThemeKeys.StatusGrayText, "Grau");
} }
private async Task NextDayAsync()
{
_calendarStateService.SelectedDate = SelectedDate.AddDays(1);
await RefreshAsync();
}
private async Task TodayAsync()
{
_calendarStateService.ResetToToday();
await RefreshAsync();
}
private async void HandleSharedDateChanged(DateTime date)
{
SelectedDate = date;
await RefreshAsync();
}
private void UpdateDateState()
{
var today = DateTime.Today;
IsToday = SelectedDate.Date == today;
IsPastDate = SelectedDate.Date < today;
IsFutureDate = SelectedDate.Date > today;
}
private void UpdateSelectedDateText()
{
SelectedDateText = DateHelper.ToGermanDateText(SelectedDate);
}
private void LoadAppearance()
{
GreenStatusText = _appearanceService.GetText(AppearanceKeys.StatusGreenText, "Grün");
YellowStatusText = _appearanceService.GetText(AppearanceKeys.StatusYellowText, "Gelb");
RedStatusText = _appearanceService.GetText(AppearanceKeys.StatusRedText, "Rot");
GrayStatusText = _appearanceService.GetText(AppearanceKeys.StatusGrayText, "Schwarz");
GreenStateColor = _appearanceService.GetColor(AppearanceKeys.StateGreen, "#4E8B69");
YellowStateColor = _appearanceService.GetColor(AppearanceKeys.StateYellow, "#B89A42");
RedStateColor = _appearanceService.GetColor(AppearanceKeys.StateRed, "#A85C5C");
GrayStateColor = _appearanceService.GetColor(AppearanceKeys.StateGray, "#1F242B");
PrimaryTextColor = _appearanceService.GetColor(AppearanceKeys.TextPrimary, "#DCE7F3");
}
private void RaiseCounterTextChanged()
{
OnPropertyChanged(nameof(GreenCounterText));
OnPropertyChanged(nameof(YellowCounterText));
OnPropertyChanged(nameof(RedCounterText));
OnPropertyChanged(nameof(GrayCounterText));
}
private void RaiseDayModeChanged()
{
OnPropertyChanged(nameof(AddEntryButtonText));
OnPropertyChanged(nameof(CanAddEntry));
OnPropertyChanged(nameof(DayHintText));
}
private static string BuildCounterText(string label, int count) => $"{label}\n{count}";
} }
+11 -7
View File
@@ -1,13 +1,17 @@
using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.Maui.Graphics; using Microsoft.Maui.Graphics;
namespace cfs_tracker.ViewModels; namespace cfs_tracker.ViewModels;
public class MonthCellViewModel
public partial class MonthCellViewModel : ObservableObject
{ {
public bool IsRealDay { get; init; }
public DateTime Date { get; init; } public DateTime Date { get; init; }
public string DayNumberText { get; init; } = ""; public string DayNumberText { get; init; } = string.Empty;
public string CountText { get; init; } = ""; public bool IsCurrentMonth { get; init; }
public Color BackgroundColor { get; init; } = Colors.Transparent; public bool IsToday { get; init; }
public bool HasEntries { get; init; }
public string AverageStateText { get; init; } = string.Empty;
public Color StateColor { get; init; } = Colors.Transparent;
public Color TextColor { get; init; } = Colors.White;
public Color BorderColor { get; init; } = Colors.Transparent; public Color BorderColor { get; init; } = Colors.Transparent;
public Color TextColor { get; init; } = Colors.Black;
public static MonthCellViewModel Placeholder() => new() { IsRealDay = false };
} }
+9
View File
@@ -0,0 +1,9 @@
using System.Collections.ObjectModel;
namespace cfs_tracker.ViewModels;
public class MonthSectionViewModel
{
public string Title { get; init; } = string.Empty;
public ObservableCollection<MonthCellViewModel> Cells { get; } = new();
}
+70 -55
View File
@@ -1,114 +1,129 @@
using System.Collections.ObjectModel;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data; using cfs_tracker.Data;
using cfs_tracker.Helpers; using cfs_tracker.Helpers;
using cfs_tracker.Models;
using cfs_tracker.Services; using cfs_tracker.Services;
using Microsoft.Maui.Storage;
using System.Collections.ObjectModel;
namespace cfs_tracker.ViewModels; namespace cfs_tracker.ViewModels;
public partial class MonthViewModel : ObservableObject public partial class MonthViewModel : ObservableObject
{ {
private readonly HealthEntryRepository _repository; private readonly HealthEntryRepository _healthEntryRepository;
private readonly AppearanceService _appearanceService;
private readonly AggregationService _aggregationService; private readonly AggregationService _aggregationService;
private readonly CalendarStateService _calendarState; private readonly CalendarStateService _calendarStateService;
private readonly CultureInfo _culture = new("de-DE"); private readonly IPdfExportService _pdfExportService;
private DateTime _currentMonth = new(DateTime.Today.Year, DateTime.Today.Month, 1);
[ObservableProperty] [ObservableProperty]
private string selectedMonthText = string.Empty; private DateTime selectedDate;
public ObservableCollection<MonthCellViewModel> Days { get; } = new(); [ObservableProperty]
private string headerText = string.Empty;
public ObservableCollection<MonthCellViewModel> Cells { get; } = new();
public IAsyncRelayCommand PreviousMonthCommand { get; } public IAsyncRelayCommand PreviousMonthCommand { get; }
public IAsyncRelayCommand NextMonthCommand { get; } public IAsyncRelayCommand NextMonthCommand { get; }
public IAsyncRelayCommand TodayCommand { get; } public IAsyncRelayCommand TodayCommand { get; }
public IAsyncRelayCommand ExportPdfCommand { get; }
public IAsyncRelayCommand<MonthCellViewModel> OpenDayCommand { get; } public IAsyncRelayCommand<MonthCellViewModel> OpenDayCommand { get; }
public MonthViewModel( public MonthViewModel(
HealthEntryRepository repository, HealthEntryRepository healthEntryRepository,
AppearanceService appearanceService,
AggregationService aggregationService, AggregationService aggregationService,
CalendarStateService calendarState) CalendarStateService calendarStateService,
IPdfExportService pdfExportService)
{ {
_repository = repository; _healthEntryRepository = healthEntryRepository;
_appearanceService = appearanceService;
_aggregationService = aggregationService; _aggregationService = aggregationService;
_calendarState = calendarState; _calendarStateService = calendarStateService;
_pdfExportService = pdfExportService;
PreviousMonthCommand = new AsyncRelayCommand(PreviousMonthAsync); PreviousMonthCommand = new AsyncRelayCommand(PreviousMonthAsync);
NextMonthCommand = new AsyncRelayCommand(NextMonthAsync); NextMonthCommand = new AsyncRelayCommand(NextMonthAsync);
TodayCommand = new AsyncRelayCommand(SetTodayAsync); TodayCommand = new AsyncRelayCommand(TodayAsync);
ExportPdfCommand = new AsyncRelayCommand(ExportAsync);
OpenDayCommand = new AsyncRelayCommand<MonthCellViewModel>(OpenDayAsync); OpenDayCommand = new AsyncRelayCommand<MonthCellViewModel>(OpenDayAsync);
_calendarStateService.SelectedDateChanged += HandleSharedDateChanged;
SelectedDate = _calendarStateService.SelectedDate;
} }
public async Task RefreshAsync() public async Task RefreshAsync()
{ {
_currentMonth = new DateTime(_currentMonth.Year, _currentMonth.Month, 1); SelectedDate = _calendarStateService.SelectedDate;
SelectedMonthText = _currentMonth.ToString("MMMM yyyy", _culture); var month = new DateTime(SelectedDate.Year, SelectedDate.Month, 1);
HeaderText = DateHelper.ToGermanMonthYear(month);
var monthStart = _currentMonth; var monthEnd = month.AddMonths(1);
var monthEnd = monthStart.AddMonths(1);
var entries = await _repository.GetEntriesBetweenAsync(monthStart, monthEnd); var entries = await _healthEntryRepository.GetEntriesBetweenAsync(month, monthEnd);
var summaries = _aggregationService.BuildMonthSummary(monthStart, entries); Cells.Clear();
Days.Clear(); var daysInMonth = DateTime.DaysInMonth(month.Year, month.Month);
int leadingEmptyDays = ((int)monthStart.DayOfWeek + 6) % 7; for (var day = 1; day <= daysInMonth; day++)
{
var date = new DateTime(month.Year, month.Month, day);
var dayEntries = entries.Where(x => x.EntryDate.Date == date.Date).ToList();
var average = _aggregationService.CalculateAverage(dayEntries);
for (int i = 0; i < leadingEmptyDays; i++) Cells.Add(new MonthCellViewModel
Days.Add(MonthCellViewModel.Placeholder()); {
Date = date,
DayNumberText = date.Day.ToString(),
IsCurrentMonth = true,
IsToday = date.Date == DateTime.Today,
HasEntries = dayEntries.Count > 0,
AverageStateText = _aggregationService.ToDisplayText(average, _appearanceService),
StateColor = _appearanceService.GetColor(average.State.ToAppearanceColorKey(), "#1F242B"),
TextColor = _appearanceService.GetColor(AppearanceKeys.TextPrimary, "#DCE7F3"),
BorderColor = date.Date == DateTime.Today
? _appearanceService.GetColor(AppearanceKeys.StateYellow, "#B89A42")
: _appearanceService.GetColor(AppearanceKeys.Border, "#2A3E55")
});
}
}
private async Task OpenDayAsync(MonthCellViewModel? item)
{
if (item is null)
return;
foreach (var summary in summaries) _calendarStateService.SelectedDate = item.Date;
Days.Add(BuildCell(summary)); await Shell.Current.GoToAsync("//day");
while (Days.Count % 7 != 0)
Days.Add(MonthCellViewModel.Placeholder());
} }
private MonthCellViewModel BuildCell(CalendarDaySummary summary) private async Task ExportAsync()
{ {
var colorKey = summary.DisplayState?.ToColorKey() ?? ThemeKeys.PanelBackground2; var result = await _pdfExportService.ExportMonthAsync(SelectedDate);
bool isToday = summary.Date.Date == DateTime.Today.Date; await ExportUiHelper.ShowExportSavedActionsAsync(result);
return new MonthCellViewModel
{
IsRealDay = true,
Date = summary.Date,
DayNumberText = summary.Date.Day.ToString(),
CountText = summary.EntryCount > 0 ? $"{summary.EntryCount}x" : string.Empty,
BackgroundColor = ThemeResourceHelper.GetColor(colorKey, "#203041"),
BorderColor = isToday
? ThemeResourceHelper.GetColor(ThemeKeys.TextPrimary, "#D9E6F2")
: ThemeResourceHelper.GetColor(ThemeKeys.PanelBorder, "#2B3E52"),
TextColor = ThemeResourceHelper.GetColor(ThemeKeys.TextPrimary, "#D9E6F2")
};
} }
private async Task PreviousMonthAsync() private async Task PreviousMonthAsync()
{ {
_currentMonth = _currentMonth.AddMonths(-1); _calendarStateService.SelectedDate = new DateTime(SelectedDate.Year, SelectedDate.Month, 1).AddMonths(-1);
await RefreshAsync(); await RefreshAsync();
} }
private async Task NextMonthAsync() private async Task NextMonthAsync()
{ {
_currentMonth = _currentMonth.AddMonths(1); _calendarStateService.SelectedDate = new DateTime(SelectedDate.Year, SelectedDate.Month, 1).AddMonths(1);
await RefreshAsync(); await RefreshAsync();
} }
private async Task SetTodayAsync() private async Task TodayAsync()
{ {
await _calendarState.ShowDayTabAsync(DateTime.Today); _calendarStateService.ResetToToday();
await RefreshAsync();
} }
private async Task OpenDayAsync(MonthCellViewModel? cell) private async void HandleSharedDateChanged(DateTime date)
{ {
if (cell is null || !cell.IsRealDay) SelectedDate = date;
return; await RefreshAsync();
await _calendarState.ShowDayTabAsync(cell.Date);
} }
} }
@@ -0,0 +1,20 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.ObjectModel;
namespace cfs_tracker.ViewModels;
public partial class NotificationScheduleItemViewModel : ObservableObject
{
public int Id { get; init; }
public ObservableCollection<WeekdayOptionItemViewModel> WeekdayOptions { get; } = new();
[ObservableProperty]
private WeekdayOptionItemViewModel? selectedWeekday;
[ObservableProperty]
private TimeSpan selectedTime = new(9, 0, 0);
[ObservableProperty]
private bool isEnabled = true;
}
+382 -34
View File
@@ -1,16 +1,25 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data; using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Models;
using cfs_tracker.Services; using cfs_tracker.Services;
using System.Collections.ObjectModel;
namespace cfs_tracker.ViewModels; namespace cfs_tracker.ViewModels;
public partial class OptionsViewModel : ObservableObject public partial class OptionsViewModel : ObservableObject
{ {
private readonly HealthEntryRepository _healthRepository; private readonly HealthEntryRepository _healthEntryRepository;
private readonly AppearanceRepository _appearanceRepository; private readonly AppearanceRepository _appearanceRepository;
private readonly AppearanceService _appearanceService; private readonly AppearanceService _appearanceService;
private readonly ActivityRepository _activityRepository;
private readonly SymptomRepository _symptomRepository;
private readonly NotificationScheduleRepository _notificationScheduleRepository;
private readonly INotificationScheduler _notificationScheduler;
private readonly DatabaseLocationService _databaseLocationService;
private readonly AppDatabase _appDatabase;
private readonly IPdfExportService _pdfExportService;
[ObservableProperty] [ObservableProperty]
private string deleteConfirmationText = string.Empty; private string deleteConfirmationText = string.Empty;
@@ -18,25 +27,83 @@ public partial class OptionsViewModel : ObservableObject
[ObservableProperty] [ObservableProperty]
private string statusText = string.Empty; private string statusText = string.Empty;
[ObservableProperty]
private string newActivityName = string.Empty;
[ObservableProperty]
private string newSymptomName = string.Empty;
[ObservableProperty]
private bool useExternalDatabase;
[ObservableProperty]
private string externalDatabasePath = string.Empty;
[ObservableProperty]
private string currentDatabasePath = string.Empty;
public ObservableCollection<AppearanceColorItemViewModel> AppearanceColors { get; } = new(); public ObservableCollection<AppearanceColorItemViewModel> AppearanceColors { get; } = new();
public ObservableCollection<AppearanceTextItemViewModel> StatusTexts { get; } = new(); public ObservableCollection<AppearanceTextItemViewModel> StatusTexts { get; } = new();
public ObservableCollection<ActivityManageItemViewModel> Activities { get; } = new();
public ObservableCollection<SymptomManageItemViewModel> Symptoms { get; } = new();
public ObservableCollection<NotificationScheduleItemViewModel> NotificationSchedules { get; } = new();
public IAsyncRelayCommand DeleteAllDataCommand { get; } public IAsyncRelayCommand DeleteAllDataCommand { get; }
public IAsyncRelayCommand SaveAppearanceCommand { get; } public IAsyncRelayCommand SaveAppearanceCommand { get; }
public IAsyncRelayCommand ResetAppearanceCommand { get; } public IAsyncRelayCommand ResetAppearanceCommand { get; }
public IAsyncRelayCommand AddActivityCommand { get; }
public IAsyncRelayCommand<ActivityManageItemViewModel> SaveActivityCommand { get; }
public IAsyncRelayCommand<ActivityManageItemViewModel> ToggleActivityActiveCommand { get; }
public IAsyncRelayCommand<ActivityManageItemViewModel> DeleteActivityCommand { get; }
public IAsyncRelayCommand AddSymptomCommand { get; }
public IAsyncRelayCommand<SymptomManageItemViewModel> SaveSymptomCommand { get; }
public IAsyncRelayCommand<SymptomManageItemViewModel> ToggleSymptomActiveCommand { get; }
public IAsyncRelayCommand<SymptomManageItemViewModel> DeleteSymptomCommand { get; }
public IAsyncRelayCommand AddScheduleCommand { get; }
public IAsyncRelayCommand SaveSchedulesCommand { get; }
public IAsyncRelayCommand<NotificationScheduleItemViewModel> DeleteScheduleCommand { get; }
public IAsyncRelayCommand SaveDatabaseLocationCommand { get; }
public IAsyncRelayCommand ClearExportsCommand { get; }
public OptionsViewModel( public OptionsViewModel(
HealthEntryRepository healthRepository, HealthEntryRepository healthEntryRepository,
AppearanceRepository appearanceRepository, AppearanceRepository appearanceRepository,
AppearanceService appearanceService) AppearanceService appearanceService,
ActivityRepository activityRepository,
SymptomRepository symptomRepository,
NotificationScheduleRepository notificationScheduleRepository,
INotificationScheduler notificationScheduler,
DatabaseLocationService databaseLocationService,
AppDatabase appDatabase,
IPdfExportService pdfExportService)
{ {
_healthRepository = healthRepository; _healthEntryRepository = healthEntryRepository;
_appearanceRepository = appearanceRepository; _appearanceRepository = appearanceRepository;
_appearanceService = appearanceService; _appearanceService = appearanceService;
_activityRepository = activityRepository;
_symptomRepository = symptomRepository;
_notificationScheduleRepository = notificationScheduleRepository;
_notificationScheduler = notificationScheduler;
_databaseLocationService = databaseLocationService;
_appDatabase = appDatabase;
_pdfExportService = pdfExportService;
DeleteAllDataCommand = new AsyncRelayCommand(DeleteAllDataAsync, CanDeleteAllData); DeleteAllDataCommand = new AsyncRelayCommand(DeleteAllDataAsync, CanDeleteAllData);
SaveAppearanceCommand = new AsyncRelayCommand(SaveAppearanceAsync); SaveAppearanceCommand = new AsyncRelayCommand(SaveAppearanceAsync);
ResetAppearanceCommand = new AsyncRelayCommand(ResetAppearanceAsync); ResetAppearanceCommand = new AsyncRelayCommand(ResetAppearanceAsync);
AddActivityCommand = new AsyncRelayCommand(AddActivityAsync);
SaveActivityCommand = new AsyncRelayCommand<ActivityManageItemViewModel>(SaveActivityAsync);
ToggleActivityActiveCommand = new AsyncRelayCommand<ActivityManageItemViewModel>(ToggleActivityActiveAsync);
DeleteActivityCommand = new AsyncRelayCommand<ActivityManageItemViewModel>(DeleteActivityAsync);
AddSymptomCommand = new AsyncRelayCommand(AddSymptomAsync);
SaveSymptomCommand = new AsyncRelayCommand<SymptomManageItemViewModel>(SaveSymptomAsync);
ToggleSymptomActiveCommand = new AsyncRelayCommand<SymptomManageItemViewModel>(ToggleSymptomActiveAsync);
DeleteSymptomCommand = new AsyncRelayCommand<SymptomManageItemViewModel>(DeleteSymptomAsync);
AddScheduleCommand = new AsyncRelayCommand(AddScheduleAsync);
SaveSchedulesCommand = new AsyncRelayCommand(SaveSchedulesAsync);
DeleteScheduleCommand = new AsyncRelayCommand<NotificationScheduleItemViewModel>(DeleteScheduleAsync);
SaveDatabaseLocationCommand = new AsyncRelayCommand(SaveDatabaseLocationAsync);
ClearExportsCommand = new AsyncRelayCommand(ClearExportsAsync);
} }
partial void OnDeleteConfirmationTextChanged(string value) partial void OnDeleteConfirmationTextChanged(string value)
@@ -47,18 +114,24 @@ public partial class OptionsViewModel : ObservableObject
public async Task LoadAsync() public async Task LoadAsync()
{ {
await LoadAppearanceAsync(); await LoadAppearanceAsync();
await LoadActivitiesAsync();
await LoadSymptomsAsync();
await LoadSchedulesAsync();
UseExternalDatabase = _databaseLocationService.UseExternalDatabase;
ExternalDatabasePath = _databaseLocationService.ExternalDatabasePath;
CurrentDatabasePath = _appDatabase.CurrentPath;
StatusText = string.Empty;
} }
private bool CanDeleteAllData() private bool CanDeleteAllData() =>
{ string.Equals(DeleteConfirmationText?.Trim(), "löschen", StringComparison.OrdinalIgnoreCase);
return string.Equals(DeleteConfirmationText?.Trim(), "löschen", StringComparison.OrdinalIgnoreCase);
}
private async Task DeleteAllDataAsync() private async Task DeleteAllDataAsync()
{ {
await _healthRepository.DeleteAllAsync(); await _healthEntryRepository.DeleteAllAsync();
DeleteConfirmationText = string.Empty; DeleteConfirmationText = string.Empty;
StatusText = "Alle gespeicherten Einträge wurden gelöscht."; StatusText = "Alle Einträge wurden gelöscht.";
} }
private async Task LoadAppearanceAsync() private async Task LoadAppearanceAsync()
@@ -66,40 +139,59 @@ public partial class OptionsViewModel : ObservableObject
AppearanceColors.Clear(); AppearanceColors.Clear();
StatusTexts.Clear(); StatusTexts.Clear();
var all = await _appearanceRepository.GetAllAsync(); var map = await _appearanceRepository.GetMapAsync();
AddColor(all, "AppBackground", "App-Hintergrund"); AddColor(AppearanceKeys.AppBackground, "App-Hintergrund");
AddColor(all, "PanelBackground", "Panel-Hintergrund"); AddColor(AppearanceKeys.SurfaceBackground, "Karten-Hintergrund");
AddColor(all, "PanelBackground2", "Sekundäre Fläche"); AddColor(AppearanceKeys.SurfaceBackgroundAlt, "Sekundäre Fläche");
AddColor(all, "PanelBorder", "Panel-Rand"); AddColor(AppearanceKeys.Border, "Rahmen");
AddColor(all, "TextPrimary", "Haupttext"); AddColor(AppearanceKeys.TextPrimary, "Haupttext");
AddColor(all, "TextMuted", "Gedimmter Text"); AddColor(AppearanceKeys.TextMuted, "Nebentext");
AddColor(all, "StateGreen", "Statusfarbe Grün");
AddColor(all, "StateYellow", "Statusfarbe Gelb");
AddColor(all, "StateRed", "Statusfarbe Rot");
AddColor(all, "StateGray", "Statusfarbe Grau");
AddText(all, "StatusGreenText", "Text für Grün"); AddColor(AppearanceKeys.StateGreen, "Statusfarbe Grün");
AddText(all, "StatusYellowText", "Text für Gelb"); AddColor(AppearanceKeys.StateYellow, "Statusfarbe Gelb");
AddText(all, "StatusRedText", "Text für Rot"); AddColor(AppearanceKeys.StateRed, "Statusfarbe Rot");
AddText(all, "StatusGrayText", "Text für Grau"); AddColor(AppearanceKeys.StateGray, "Statusfarbe Schwarz / Grau");
}
private void AddColor(List<Models.AppearanceSetting> all, string key, string title) AddColor(AppearanceKeys.ButtonPrimaryBackground, "Button Primär Hintergrund");
AddColor(AppearanceKeys.ButtonPrimaryText, "Button Primär Text");
AddColor(AppearanceKeys.ButtonSecondaryBackground, "Button Sekundär Hintergrund");
AddColor(AppearanceKeys.ButtonSecondaryText, "Button Sekundär Text");
AddColor(AppearanceKeys.ShellBackground, "App-Leiste Hintergrund");
AddColor(AppearanceKeys.ShellForeground, "App-Leiste Vordergrund");
AddColor(AppearanceKeys.ShellTitle, "App-Leiste Titel");
AddColor(AppearanceKeys.ShellUnselected, "App-Leiste Inaktiv");
AddColor(AppearanceKeys.TabBarBackground, "Tableiste Hintergrund");
AddColor(AppearanceKeys.TabBarForeground, "Tableiste Aktiv");
AddColor(AppearanceKeys.TabBarTitle, "Tableiste Titel");
AddColor(AppearanceKeys.TabBarUnselected, "Tableiste Inaktiv");
AddText(AppearanceKeys.StatusGreenText, "Text für Grün");
AddText(AppearanceKeys.StatusYellowText, "Text für Gelb");
AddText(AppearanceKeys.StatusRedText, "Text für Rot");
AddText(AppearanceKeys.StatusGrayText, "Text für Schwarz / Grau");
void AddColor(string key, string title)
{ {
var value = all.FirstOrDefault(x => x.Key == key)?.Value ?? string.Empty; var fallback = AppearanceDefaults.All[key];
var value = map.TryGetValue(key, out var stored) ? stored : fallback;
AppearanceColors.Add(new AppearanceColorItemViewModel AppearanceColors.Add(new AppearanceColorItemViewModel
{ {
Key = key, Key = key,
Title = title, Title = title,
Value = value Fallback = fallback,
Value = value,
PreviewColor = ColorUtility.ParseColor(value, fallback)
}); });
} }
private void AddText(List<Models.AppearanceSetting> all, string key, string title) void AddText(string key, string title)
{ {
var value = all.FirstOrDefault(x => x.Key == key)?.Value ?? string.Empty; var fallback = AppearanceDefaults.All[key];
var value = map.TryGetValue(key, out var stored) ? stored : fallback;
StatusTexts.Add(new AppearanceTextItemViewModel StatusTexts.Add(new AppearanceTextItemViewModel
{ {
@@ -108,22 +200,278 @@ public partial class OptionsViewModel : ObservableObject
Value = value Value = value
}); });
} }
}
private async Task LoadActivitiesAsync()
{
Activities.Clear();
var all = await _activityRepository.GetAllAsync();
foreach (var item in all)
{
Activities.Add(new ActivityManageItemViewModel
{
Id = item.Id,
Name = item.Name,
IsActive = item.IsActive,
IsUsed = await _activityRepository.HasUsageAsync(item.Id)
});
}
}
private async Task LoadSymptomsAsync()
{
Symptoms.Clear();
var all = await _symptomRepository.GetAllAsync();
foreach (var item in all)
{
Symptoms.Add(new SymptomManageItemViewModel
{
Id = item.Id,
Name = item.Name,
IsActive = item.IsActive,
IsUsed = await _symptomRepository.HasUsageAsync(item.Id)
});
}
}
private async Task LoadSchedulesAsync()
{
NotificationSchedules.Clear();
var schedules = await _notificationScheduleRepository.GetAllAsync();
foreach (var schedule in schedules)
NotificationSchedules.Add(CreateScheduleVm(schedule.Id, schedule.DayOfWeek, new TimeSpan(schedule.Hour, schedule.Minute, 0), schedule.IsEnabled));
}
private async Task SaveAppearanceAsync() private async Task SaveAppearanceAsync()
{ {
foreach (var item in AppearanceColors) foreach (var item in AppearanceColors)
{
item.PreviewColor = ColorUtility.ParseColor(item.Value, item.Fallback);
await _appearanceService.SaveColorAsync(item.Key, item.Value); await _appearanceService.SaveColorAsync(item.Key, item.Value);
}
foreach (var item in StatusTexts) foreach (var item in StatusTexts)
await _appearanceService.SaveTextAsync(item.Key, item.Value); await _appearanceService.SaveTextAsync(item.Key, item.Value);
StatusText = "Aussehen wurde gespeichert."; StatusText = "Aussehen gespeichert.";
} }
private async Task ResetAppearanceAsync() private async Task ResetAppearanceAsync()
{ {
await _appearanceService.ResetAsync(); await _appearanceService.ResetAsync();
await LoadAppearanceAsync(); await LoadAppearanceAsync();
StatusText = "Aussehen wurde auf Standard zurückgesetzt."; StatusText = "Aussehen auf Standard zurückgesetzt.";
}
private async Task AddActivityAsync()
{
if (string.IsNullOrWhiteSpace(NewActivityName))
{
StatusText = "Bitte zuerst einen Tätigkeitsnamen eingeben.";
return;
}
try
{
await _activityRepository.AddAsync(NewActivityName);
NewActivityName = string.Empty;
await LoadActivitiesAsync();
StatusText = "Tätigkeit hinzugefügt.";
}
catch (Exception ex)
{
StatusText = ex.Message;
}
}
private async Task SaveActivityAsync(ActivityManageItemViewModel? item)
{
if (item is null)
return;
try
{
await _activityRepository.RenameAsync(item.Id, item.Name);
await LoadActivitiesAsync();
StatusText = "Tätigkeit gespeichert.";
}
catch (Exception ex)
{
StatusText = ex.Message;
}
}
private async Task ToggleActivityActiveAsync(ActivityManageItemViewModel? item)
{
if (item is null)
return;
await _activityRepository.SetActiveAsync(item.Id, !item.IsActive);
await LoadActivitiesAsync();
StatusText = "Tätigkeit aktualisiert.";
}
private async Task DeleteActivityAsync(ActivityManageItemViewModel? item)
{
if (item is null)
return;
await _activityRepository.DeleteOrDeactivateAsync(item.Id);
await LoadActivitiesAsync();
StatusText = item.IsUsed ? "Tätigkeit wurde deaktiviert." : "Tätigkeit wurde gelöscht.";
}
private async Task AddSymptomAsync()
{
if (string.IsNullOrWhiteSpace(NewSymptomName))
{
StatusText = "Bitte zuerst einen Symptomnamen eingeben.";
return;
}
try
{
await _symptomRepository.AddAsync(NewSymptomName);
NewSymptomName = string.Empty;
await LoadSymptomsAsync();
StatusText = "Symptom hinzugefügt.";
}
catch (Exception ex)
{
StatusText = ex.Message;
}
}
private async Task SaveSymptomAsync(SymptomManageItemViewModel? item)
{
if (item is null)
return;
try
{
await _symptomRepository.RenameAsync(item.Id, item.Name);
await LoadSymptomsAsync();
StatusText = "Symptom gespeichert.";
}
catch (Exception ex)
{
StatusText = ex.Message;
}
}
private async Task ToggleSymptomActiveAsync(SymptomManageItemViewModel? item)
{
if (item is null)
return;
await _symptomRepository.SetActiveAsync(item.Id, !item.IsActive);
await LoadSymptomsAsync();
StatusText = "Symptom aktualisiert.";
}
private async Task DeleteSymptomAsync(SymptomManageItemViewModel? item)
{
if (item is null)
return;
await _symptomRepository.DeleteOrDeactivateAsync(item.Id);
await LoadSymptomsAsync();
StatusText = item.IsUsed ? "Symptom wurde deaktiviert." : "Symptom wurde gelöscht.";
}
private Task AddScheduleAsync()
{
NotificationSchedules.Add(CreateScheduleVm(0, DayOfWeek.Monday, new TimeSpan(9, 0, 0), true));
StatusText = "Benachrichtigungszeit hinzugefügt.";
return Task.CompletedTask;
}
private async Task SaveSchedulesAsync()
{
var items = NotificationSchedules.Select(x => new NotificationSchedule
{
Id = x.Id,
DayOfWeek = x.SelectedWeekday?.Value ?? DayOfWeek.Monday,
Hour = x.SelectedTime.Hours,
Minute = x.SelectedTime.Minutes,
IsEnabled = x.IsEnabled
}).ToList();
await _notificationScheduleRepository.ReplaceAllAsync(items);
await _notificationScheduler.SyncAsync();
await LoadSchedulesAsync();
StatusText = "Benachrichtigungszeiten gespeichert. Text: 'Wie geht es dir?' mit Gelb/Rot/Grau als Schnellwahl.";
}
private Task DeleteScheduleAsync(NotificationScheduleItemViewModel? item)
{
if (item is not null)
NotificationSchedules.Remove(item);
StatusText = "Benachrichtigungszeit entfernt.";
return Task.CompletedTask;
}
private Task SaveDatabaseLocationAsync()
{
_databaseLocationService.UseExternalDatabase = UseExternalDatabase;
_databaseLocationService.ExternalDatabasePath = ExternalDatabasePath?.Trim() ?? string.Empty;
CurrentDatabasePath = _databaseLocationService.ResolveDatabasePath();
StatusText = "Datenbankpfad gespeichert. Bitte App neu starten, damit der Pfad aktiv wird.";
return Task.CompletedTask;
}
private static NotificationScheduleItemViewModel CreateScheduleVm(int id, DayOfWeek dayOfWeek, TimeSpan time, bool isEnabled)
{
var vm = new NotificationScheduleItemViewModel
{
Id = id,
SelectedTime = time,
IsEnabled = isEnabled
};
foreach (var option in BuildWeekdayOptions())
vm.WeekdayOptions.Add(option);
vm.SelectedWeekday = vm.WeekdayOptions.FirstOrDefault(x => x.Value == dayOfWeek)
?? vm.WeekdayOptions.First();
return vm;
}
private async Task ClearExportsAsync()
{
var confirm = await Shell.Current.DisplayAlertAsync(
"Export entleeren",
"Möchtest du wirklich alle lokal gespeicherten Exporte löschen?",
"Ja",
"Nein");
if (!confirm)
return;
var deleted = await _pdfExportService.ClearExportsAsync();
await Shell.Current.DisplayAlertAsync(
"Export entleeren",
deleted > 0
? $"{deleted} Export-Datei(en) wurden gelöscht."
: "Es waren keine Export-Dateien vorhanden.",
"OK");
}
private static IEnumerable<WeekdayOptionItemViewModel> BuildWeekdayOptions()
{
yield return new WeekdayOptionItemViewModel { Value = DayOfWeek.Monday, Name = "Montag" };
yield return new WeekdayOptionItemViewModel { Value = DayOfWeek.Tuesday, Name = "Dienstag" };
yield return new WeekdayOptionItemViewModel { Value = DayOfWeek.Wednesday, Name = "Mittwoch" };
yield return new WeekdayOptionItemViewModel { Value = DayOfWeek.Thursday, Name = "Donnerstag" };
yield return new WeekdayOptionItemViewModel { Value = DayOfWeek.Friday, Name = "Freitag" };
yield return new WeekdayOptionItemViewModel { Value = DayOfWeek.Saturday, Name = "Samstag" };
yield return new WeekdayOptionItemViewModel { Value = DayOfWeek.Sunday, Name = "Sonntag" };
} }
} }
+315 -47
View File
@@ -1,92 +1,360 @@
using System.Collections.ObjectModel;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data; using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Models; using cfs_tracker.Models;
using cfs_tracker.Services;
using Microsoft.Maui.Graphics;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
namespace cfs_tracker.ViewModels; namespace cfs_tracker.ViewModels;
public partial class QuickEntryViewModel : ObservableObject public partial class QuickEntryViewModel : ObservableObject
{ {
private readonly HealthEntryRepository _repo; private readonly HealthEntryRepository _healthEntryRepository;
private readonly ActivityRepository _activityRepo; private readonly ActivityRepository _activityRepository;
private readonly SymptomRepository _symptomRepo; private readonly SymptomRepository _symptomRepository;
private readonly AppearanceService _appearanceService;
private readonly CalendarStateService _calendarStateService;
[ObservableProperty] private DateTime selectedDate = DateTime.Today; private string _dateQuery = string.Empty;
[ObservableProperty] private string selectedDateText = ""; private int? _entryId;
[ObservableProperty] private bool isPastDate;
[ObservableProperty] private bool isFutureDate;
[ObservableProperty] private string selectedPartText = "Vormittag";
[ObservableProperty] private SelectableItemViewModel? selectedActivity;
public ObservableCollection<string> AvailableParts { get; } = new() { "Vormittag", "Nachmittag" }; [ObservableProperty]
public ObservableCollection<SelectableItemViewModel> Activities { get; } = new(); private DateTime selectedDate = DateTime.Today;
public ObservableCollection<SelectableItemViewModel> Symptoms { get; } = new();
[ObservableProperty]
private string selectedDateText = string.Empty;
[ObservableProperty]
private bool isToday;
[ObservableProperty]
private bool isPastDate;
[ObservableProperty]
private bool isFutureDate;
[ObservableProperty]
private bool isEditing;
[ObservableProperty]
private string greenStatusText = "Grün";
[ObservableProperty]
private string yellowStatusText = "Gelb";
[ObservableProperty]
private string redStatusText = "Rot";
[ObservableProperty]
private string grayStatusText = "Schwarz";
[ObservableProperty]
private Color greenStateColor = Color.FromArgb("#4E8B69");
[ObservableProperty]
private Color yellowStateColor = Color.FromArgb("#B89A42");
[ObservableProperty]
private Color redStateColor = Color.FromArgb("#A85C5C");
[ObservableProperty]
private Color grayStateColor = Color.FromArgb("#1F242B");
[ObservableProperty]
private ActivityPickerItemViewModel? selectedActivity;
[ObservableProperty]
private DayPartOptionItemViewModel? selectedPart;
[ObservableProperty]
private HealthState? selectedState;
public ObservableCollection<ActivityPickerItemViewModel> Activities { get; } = new();
public ObservableCollection<SelectableSymptomItemViewModel> Symptoms { get; } = new();
public ObservableCollection<DayPartOptionItemViewModel> Parts { get; } = new();
public string ModeText => IsFutureDate
? "Zukünftige Tage können nicht gespeichert werden."
: string.Empty;
public bool CanSave => !IsFutureDate;
public bool ShowSaveButton => IsEditing;
public bool CanExplicitSave => IsEditing && SelectedState.HasValue && !IsFutureDate;
public string SelectedStateSummaryText => SelectedState.HasValue
? $"Gewählter Status: {GetStateText(SelectedState.Value)}"
: "Bitte Status wählen";
public IAsyncRelayCommand SaveGreenCommand { get; } public IAsyncRelayCommand SaveGreenCommand { get; }
public IAsyncRelayCommand SaveYellowCommand { get; } public IAsyncRelayCommand SaveYellowCommand { get; }
public IAsyncRelayCommand SaveRedCommand { get; } public IAsyncRelayCommand SaveRedCommand { get; }
public IAsyncRelayCommand SaveGrayCommand { get; } public IAsyncRelayCommand SaveGrayCommand { get; }
public IAsyncRelayCommand SaveCommand { get; }
public IAsyncRelayCommand CancelCommand { get; }
public QuickEntryViewModel(HealthEntryRepository repo, ActivityRepository activityRepo, SymptomRepository symptomRepo) public QuickEntryViewModel(
HealthEntryRepository healthEntryRepository,
ActivityRepository activityRepository,
SymptomRepository symptomRepository,
AppearanceService appearanceService,
CalendarStateService calendarStateService)
{ {
_repo=repo; _activityRepo=activityRepo; _symptomRepo=symptomRepo; _healthEntryRepository = healthEntryRepository;
SaveGreenCommand = new AsyncRelayCommand(()=>SaveAsync(HealthState.Green)); _activityRepository = activityRepository;
SaveYellowCommand = new AsyncRelayCommand(()=>SaveAsync(HealthState.Yellow)); _symptomRepository = symptomRepository;
SaveRedCommand = new AsyncRelayCommand(()=>SaveAsync(HealthState.Red)); _appearanceService = appearanceService;
SaveGrayCommand = new AsyncRelayCommand(()=>SaveAsync(HealthState.Gray)); _calendarStateService = calendarStateService;
SaveGreenCommand = new AsyncRelayCommand(() => SelectOrSaveAsync(HealthState.Green));
SaveYellowCommand = new AsyncRelayCommand(() => SelectOrSaveAsync(HealthState.Yellow));
SaveRedCommand = new AsyncRelayCommand(() => SelectOrSaveAsync(HealthState.Red));
SaveGrayCommand = new AsyncRelayCommand(() => SelectOrSaveAsync(HealthState.Gray));
SaveCommand = new AsyncRelayCommand(SaveSelectedAsync);
CancelCommand = new AsyncRelayCommand(CancelAsync);
} }
public async Task LoadLookupsAsync() partial void OnIsTodayChanged(bool value) => RaiseModeChanged();
partial void OnIsPastDateChanged(bool value) => RaiseModeChanged();
partial void OnIsFutureDateChanged(bool value) => RaiseModeChanged();
partial void OnIsEditingChanged(bool value)
{
OnPropertyChanged(nameof(ShowSaveButton));
OnPropertyChanged(nameof(CanExplicitSave));
OnPropertyChanged(nameof(SelectedStateSummaryText));
}
partial void OnSelectedStateChanged(HealthState? value)
{
OnPropertyChanged(nameof(CanExplicitSave));
OnPropertyChanged(nameof(SelectedStateSummaryText));
}
public void ApplyQuery(string date, string entryId)
{
_dateQuery = date ?? string.Empty;
_entryId = int.TryParse(entryId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedId)
? parsedId
: null;
}
public async Task InitializeAsync()
{
SelectedDate = DateTime.TryParseExact(
_dateQuery,
"yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out var parsedDate)
? parsedDate.Date
: _calendarStateService.SelectedDate;
UpdateDateMode();
SelectedDateText = DateHelper.ToGermanDateText(SelectedDate);
LoadAppearance();
await LoadActivitiesAsync();
await LoadSymptomsAsync();
LoadDayParts();
if (_entryId.HasValue)
await LoadExistingEntryAsync();
else
SelectedPart = Parts.FirstOrDefault(x => x.Value == DayPart.Morning);
OnPropertyChanged(nameof(ModeText));
OnPropertyChanged(nameof(CanSave));
OnPropertyChanged(nameof(ShowSaveButton));
OnPropertyChanged(nameof(CanExplicitSave));
OnPropertyChanged(nameof(SelectedStateSummaryText));
}
private async Task LoadActivitiesAsync()
{ {
Activities.Clear(); Activities.Clear();
Symptoms.Clear();
Activities.Add(new SelectableItemViewModel { Id = 0, Name = "Keine Angabe" }); Activities.Add(new ActivityPickerItemViewModel
foreach (var a in await _activityRepo.GetActiveAsync()) Activities.Add(new SelectableItemViewModel { Id = a.Id, Name = a.Name }); {
foreach (var s in await _symptomRepo.GetActiveAsync()) Symptoms.Add(new SelectableItemViewModel { Id = s.Id, Name = s.Name }); Id = null,
Name = "Keine Tätigkeit"
});
var items = await _activityRepository.GetActiveAsync();
foreach (var item in items.Where(x => !string.Equals(x.Name, "Keine Tätigkeit", StringComparison.OrdinalIgnoreCase)))
{
Activities.Add(new ActivityPickerItemViewModel
{
Id = item.Id,
Name = item.Name
});
}
SelectedActivity ??= Activities.FirstOrDefault(); SelectedActivity ??= Activities.FirstOrDefault();
} }
public void SetDateFromQuery(string? dateText) private async Task LoadSymptomsAsync()
{ {
if (!string.IsNullOrWhiteSpace(dateText) && DateTime.TryParseExact(dateText, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed)) Symptoms.Clear();
SelectedDate = parsed.Date;
else var items = await _symptomRepository.GetActiveAsync();
SelectedDate = DateTime.Today; foreach (var item in items)
UpdateState(); {
Symptoms.Add(new SelectableSymptomItemViewModel
{
Id = item.Id,
Name = item.Name
});
}
} }
partial void OnSelectedDateChanged(DateTime value) => UpdateState(); private void LoadDayParts()
{
if (Parts.Count > 0)
return;
Parts.Add(new DayPartOptionItemViewModel
{
Value = DayPart.Morning,
Name = "Vormittag"
});
Parts.Add(new DayPartOptionItemViewModel
{
Value = DayPart.Afternoon,
Name = "Nachmittag"
});
}
private async Task LoadExistingEntryAsync()
{
var entry = await _healthEntryRepository.GetByIdAsync(_entryId!.Value);
if (entry is null)
return;
IsEditing = true;
SelectedDate = entry.EntryDate.Date;
UpdateDateMode();
SelectedDateText = DateHelper.ToGermanDateText(SelectedDate);
SelectedPart = Parts.FirstOrDefault(x => x.Value == (entry.DayPart ?? DayPart.Morning))
?? Parts.First();
SelectedActivity = Activities.FirstOrDefault(x => x.Id == entry.ActivityId)
?? Activities.FirstOrDefault();
SelectedState = entry.State;
var symptomIds = await _symptomRepository.GetSymptomIdsForEntryAsync(entry.Id);
foreach (var symptom in Symptoms)
symptom.IsSelected = symptomIds.Contains(symptom.Id);
}
private async Task SelectOrSaveAsync(HealthState state)
{
if (IsFutureDate)
return;
SelectedState = state;
if (IsEditing)
return;
await SaveAsync(state);
}
private async Task SaveSelectedAsync()
{
if (!IsEditing || !SelectedState.HasValue || IsFutureDate)
return;
await SaveAsync(SelectedState.Value);
}
private async Task SaveAsync(HealthState state) private async Task SaveAsync(HealthState state)
{ {
if (IsFutureDate) return; if (IsFutureDate)
int? activityId = SelectedActivity is not null && SelectedActivity.Id > 0 ? SelectedActivity.Id : null; return;
int entryId;
if (IsPastDate) var activityId = SelectedActivity?.Id;
var symptomIds = Symptoms.Where(x => x.IsSelected).Select(x => x.Id).ToList();
if (IsEditing && _entryId.HasValue)
{ {
await _repo.UpsertBackfillAsync(SelectedDate, SelectedPartText == "Nachmittag" ? DayPart.Afternoon : DayPart.Morning, state, EntrySource.App, activityId); await _healthEntryRepository.UpdateEntryAsync(
var saved = await _repo.GetBackfillEntryAsync(SelectedDate, SelectedPartText == "Nachmittag" ? DayPart.Afternoon : DayPart.Morning); entryId: _entryId.Value,
entryId = saved?.Id ?? 0; date: SelectedDate,
state: state,
activityId: activityId,
symptomIds: symptomIds,
part: IsPastDate ? SelectedPart?.Value ?? DayPart.Morning : null,
source: IsPastDate ? EntrySource.Backfill : EntrySource.App);
}
else if (IsPastDate)
{
await _healthEntryRepository.UpsertBackfillAsync(
date: SelectedDate,
part: SelectedPart?.Value ?? DayPart.Morning,
state: state,
activityId: activityId,
symptomIds: symptomIds,
source: EntrySource.Backfill);
} }
else else
{ {
entryId = await _repo.AddEntryAndReturnIdAsync(state, EntrySource.App, DateTime.Now, activityId); await _healthEntryRepository.AddQuickEntryAsync(
} state: state,
if (entryId > 0) activityId: activityId,
{ symptomIds: symptomIds,
await _symptomRepo.SetSymptomsForEntryAsync(entryId, Symptoms.Where(x=>x.IsSelected).Select(x=>x.Id)); timestamp: DateTime.Now,
source: EntrySource.App);
} }
_calendarStateService.SelectedDate = SelectedDate;
await Shell.Current.GoToAsync(".."); await Shell.Current.GoToAsync("..");
} }
private void UpdateState() private Task CancelAsync() => Shell.Current.GoToAsync("..");
private void UpdateDateMode()
{ {
var today = DateTime.Today; var today = DateTime.Today;
IsToday = SelectedDate.Date == today;
IsPastDate = SelectedDate.Date < today; IsPastDate = SelectedDate.Date < today;
IsFutureDate = SelectedDate.Date > today; IsFutureDate = SelectedDate.Date > today;
SelectedDateText = SelectedDate.ToString("dddd, dd. MMMM yyyy", new CultureInfo("de-DE"));
if (!IsPastDate) SelectedPartText = "Vormittag";
} }
private void LoadAppearance()
{
GreenStatusText = _appearanceService.GetText(AppearanceKeys.StatusGreenText, "Grün");
YellowStatusText = _appearanceService.GetText(AppearanceKeys.StatusYellowText, "Gelb");
RedStatusText = _appearanceService.GetText(AppearanceKeys.StatusRedText, "Rot");
GrayStatusText = _appearanceService.GetText(AppearanceKeys.StatusGrayText, "Schwarz");
GreenStateColor = _appearanceService.GetColor(AppearanceKeys.StateGreen, "#4E8B69");
YellowStateColor = _appearanceService.GetColor(AppearanceKeys.StateYellow, "#B89A42");
RedStateColor = _appearanceService.GetColor(AppearanceKeys.StateRed, "#A85C5C");
GrayStateColor = _appearanceService.GetColor(AppearanceKeys.StateGray, "#1F242B");
OnPropertyChanged(nameof(SelectedStateSummaryText));
}
private void RaiseModeChanged()
{
OnPropertyChanged(nameof(ModeText));
OnPropertyChanged(nameof(CanSave));
OnPropertyChanged(nameof(CanExplicitSave));
}
private string GetStateText(HealthState state) => state switch
{
HealthState.Green => GreenStatusText,
HealthState.Yellow => YellowStatusText,
HealthState.Red => RedStatusText,
HealthState.Gray => GrayStatusText,
_ => string.Empty
};
} }
-8
View File
@@ -1,8 +0,0 @@
using CommunityToolkit.Mvvm.ComponentModel;
namespace cfs_tracker.ViewModels;
public partial class SelectableItemViewModel : ObservableObject
{
public int Id { get; init; }
public string Name { get; init; } = "";
[ObservableProperty] private bool isSelected;
}
@@ -0,0 +1,12 @@
using CommunityToolkit.Mvvm.ComponentModel;
namespace cfs_tracker.ViewModels;
public partial class SelectableSymptomItemViewModel : ObservableObject
{
public int Id { get; init; }
public string Name { get; init; } = string.Empty;
[ObservableProperty]
private bool isSelected;
}
+20
View File
@@ -0,0 +1,20 @@
using CommunityToolkit.Mvvm.ComponentModel;
namespace cfs_tracker.ViewModels;
public partial class SymptomManageItemViewModel : ObservableObject
{
public int Id { get; init; }
[ObservableProperty]
private string name = string.Empty;
[ObservableProperty]
private bool isActive;
public bool IsUsed { get; init; }
public string UsageHint => IsUsed
? "Bereits verwendet – kann nur deaktiviert werden."
: "Kann gelöscht werden, solange unbenutzt.";
}
-25
View File
@@ -1,25 +0,0 @@
using Microsoft.Maui.Graphics;
namespace cfs_tracker.ViewModels;
public class WeekCellViewModel
{
public DateTime Date { get; init; }
public string DayText { get; init; } = string.Empty;
public string DateText { get; init; } = string.Empty;
public string MorningText { get; init; } = string.Empty;
public string AfternoonText { get; init; } = string.Empty;
public string MorningCountText { get; init; } = string.Empty;
public string AfternoonCountText { get; init; } = string.Empty;
public Color MorningBackgroundColor { get; init; } = Colors.Transparent;
public Color AfternoonBackgroundColor { get; init; } = Colors.Transparent;
public Color MorningTextColor { get; init; } = Colors.White;
public Color AfternoonTextColor { get; init; } = Colors.White;
public bool IsToday { get; init; }
}
+42
View File
@@ -0,0 +1,42 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Maui.Graphics;
namespace cfs_tracker.ViewModels;
public partial class WeekDaySummaryViewModel : ObservableObject
{
public DateTime Date { get; init; }
public string DateText { get; init; } = string.Empty;
public string MorningText { get; init; } = "-";
public string AfternoonText { get; init; } = "-";
public Color MorningColor { get; init; } = Colors.Transparent;
public Color AfternoonColor { get; init; } = Colors.Transparent;
public string ActivitiesText { get; init; } = string.Empty;
public string SymptomsText { get; init; } = string.Empty;
public bool HasDetails => !string.IsNullOrWhiteSpace(ActivitiesText) || !string.IsNullOrWhiteSpace(SymptomsText);
public bool HasActivities => !string.IsNullOrWhiteSpace(ActivitiesText);
public bool HasSymptoms => !string.IsNullOrWhiteSpace(SymptomsText);
public string DetailsButtonText => IsExpanded ? "Zusammenfassung ausblenden" : "Zusammenfassung anzeigen";
[ObservableProperty]
private bool isExpanded;
public IRelayCommand ToggleExpandedCommand { get; }
public WeekDaySummaryViewModel()
{
ToggleExpandedCommand = new RelayCommand(() =>
{
if (!HasDetails)
return;
IsExpanded = !IsExpanded;
});
}
partial void OnIsExpandedChanged(bool value)
{
OnPropertyChanged(nameof(DetailsButtonText));
}
}
+78 -71
View File
@@ -1,131 +1,138 @@
using System.Collections.ObjectModel;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data; using cfs_tracker.Data;
using cfs_tracker.Helpers; using cfs_tracker.Helpers;
using cfs_tracker.Models; using cfs_tracker.Models;
using cfs_tracker.Services; using cfs_tracker.Services;
using Microsoft.Maui.Graphics; using Microsoft.Maui.Storage;
using System.Collections.ObjectModel;
namespace cfs_tracker.ViewModels; namespace cfs_tracker.ViewModels;
public partial class WeekViewModel : ObservableObject public partial class WeekViewModel : ObservableObject
{ {
private readonly HealthEntryRepository _repository; private readonly HealthEntryRepository _healthEntryRepository;
private readonly ActivityRepository _activityRepository;
private readonly SymptomRepository _symptomRepository;
private readonly AppearanceService _appearanceService;
private readonly AggregationService _aggregationService; private readonly AggregationService _aggregationService;
private readonly CalendarStateService _calendarState; private readonly CalendarStateService _calendarStateService;
private readonly IPdfExportService _pdfExportService;
[ObservableProperty] [ObservableProperty]
private DateTime anchorDate = DateTime.Today; private DateTime selectedDate;
[ObservableProperty] [ObservableProperty]
private string weekText = string.Empty; private DateTime weekStart;
public ObservableCollection<WeekCellViewModel> Days { get; } = new(); [ObservableProperty]
private string headerText = string.Empty;
public ObservableCollection<WeekDaySummaryViewModel> Days { get; } = new();
public IAsyncRelayCommand PreviousWeekCommand { get; } public IAsyncRelayCommand PreviousWeekCommand { get; }
public IAsyncRelayCommand NextWeekCommand { get; } public IAsyncRelayCommand NextWeekCommand { get; }
public IAsyncRelayCommand TodayCommand { get; } public IAsyncRelayCommand TodayCommand { get; }
public IAsyncRelayCommand<WeekCellViewModel> OpenDayCommand { get; } public IAsyncRelayCommand ExportPdfCommand { get; }
public IAsyncRelayCommand<WeekDaySummaryViewModel> OpenDayCommand { get; }
public WeekViewModel( public WeekViewModel(
HealthEntryRepository repository, HealthEntryRepository healthEntryRepository,
ActivityRepository activityRepository,
SymptomRepository symptomRepository,
AppearanceService appearanceService,
AggregationService aggregationService, AggregationService aggregationService,
CalendarStateService calendarState) CalendarStateService calendarStateService,
IPdfExportService pdfExportService)
{ {
_repository = repository; _healthEntryRepository = healthEntryRepository;
_activityRepository = activityRepository;
_symptomRepository = symptomRepository;
_appearanceService = appearanceService;
_aggregationService = aggregationService; _aggregationService = aggregationService;
_calendarState = calendarState; _calendarStateService = calendarStateService;
_pdfExportService = pdfExportService;
PreviousWeekCommand = new AsyncRelayCommand(PreviousWeekAsync); PreviousWeekCommand = new AsyncRelayCommand(PreviousWeekAsync);
NextWeekCommand = new AsyncRelayCommand(NextWeekAsync); NextWeekCommand = new AsyncRelayCommand(NextWeekAsync);
TodayCommand = new AsyncRelayCommand(SetTodayAsync); TodayCommand = new AsyncRelayCommand(TodayAsync);
OpenDayCommand = new AsyncRelayCommand<WeekCellViewModel>(OpenDayAsync); ExportPdfCommand = new AsyncRelayCommand(ExportAsync);
OpenDayCommand = new AsyncRelayCommand<WeekDaySummaryViewModel>(OpenDayAsync);
_calendarStateService.SelectedDateChanged += HandleSharedDateChanged;
SelectedDate = _calendarStateService.SelectedDate;
} }
public async Task RefreshAsync() public async Task RefreshAsync()
{ {
var weekStart = StartOfWeek(AnchorDate); SelectedDate = _calendarStateService.SelectedDate;
var weekEnd = weekStart.AddDays(7); WeekStart = DateHelper.StartOfWeekMonday(SelectedDate);
HeaderText = $"Woche {WeekStart:dd.MM.yyyy} - {WeekStart.AddDays(6):dd.MM.yyyy}";
WeekText = $"{weekStart:dd.MM.yyyy} - {weekEnd.AddDays(-1):dd.MM.yyyy}"; var entries = await _healthEntryRepository.GetEntriesBetweenAsync(WeekStart, WeekStart.AddDays(7));
var activityMap = await _activityRepository.GetNameMapAsync();
var entries = await _repository.GetEntriesBetweenAsync(weekStart, weekEnd); var symptomsMap = await _symptomRepository.GetSymptomsByEntryIdsAsync(entries.Select(x => x.Id));
var summaries = _aggregationService.BuildWeekSummary(weekStart, entries);
Days.Clear(); Days.Clear();
foreach (var summary in summaries) for (var i = 0; i < 7; i++)
Days.Add(BuildCell(summary)); {
var date = WeekStart.AddDays(i);
var dayEntries = entries.Where(x => x.EntryDate.Date == date.Date).ToList();
var morningAverage = _aggregationService.CalculateAverage(_aggregationService.FilterForDayPart(dayEntries, DayPart.Morning));
var afternoonAverage = _aggregationService.CalculateAverage(_aggregationService.FilterForDayPart(dayEntries, DayPart.Afternoon));
Days.Add(new WeekDaySummaryViewModel
{
Date = date,
DateText = DateHelper.ToGermanShortDay(date),
MorningText = _aggregationService.ToDisplayText(morningAverage, _appearanceService),
AfternoonText = _aggregationService.ToDisplayText(afternoonAverage, _appearanceService),
MorningColor = _appearanceService.GetColor(morningAverage.State.ToAppearanceColorKey(), "#1F242B"),
AfternoonColor = _appearanceService.GetColor(afternoonAverage.State.ToAppearanceColorKey(), "#1F242B"),
ActivitiesText = _aggregationService.BuildDistinctActivityText(dayEntries, activityMap),
SymptomsText = _aggregationService.BuildDistinctSymptomText(dayEntries, symptomsMap)
});
}
} }
private WeekCellViewModel BuildCell(WeekDaySummary summary) private async Task OpenDayAsync(WeekDaySummaryViewModel? item)
{ {
var morningState = _aggregationService.ToDisplayState(summary.MorningAverage); if (item is null)
var afternoonState = _aggregationService.ToDisplayState(summary.AfternoonAverage); return;
return new WeekCellViewModel _calendarStateService.SelectedDate = item.Date;
await Shell.Current.GoToAsync("//day");
}
private async Task ExportAsync()
{ {
Date = summary.Date, var result = await _pdfExportService.ExportWeekAsync(SelectedDate);
DayText = summary.Date.ToString("ddd", new CultureInfo("de-DE")), await ExportUiHelper.ShowExportSavedActionsAsync(result);
DateText = summary.Date.ToString("dd.MM"),
MorningText = StateLabel(morningState),
AfternoonText = StateLabel(afternoonState),
MorningCountText = summary.MorningCount > 0 ? $"{summary.MorningCount}x" : string.Empty,
AfternoonCountText = summary.AfternoonCount > 0 ? $"{summary.AfternoonCount}x" : string.Empty,
MorningBackgroundColor = StateColor(morningState),
AfternoonBackgroundColor = StateColor(afternoonState),
MorningTextColor = ThemeResourceHelper.GetColor(ThemeKeys.TextPrimary, "#D9E6F2"),
AfternoonTextColor = ThemeResourceHelper.GetColor(ThemeKeys.TextPrimary, "#D9E6F2"),
IsToday = summary.Date.Date == DateTime.Today.Date
};
} }
private async Task PreviousWeekAsync() private async Task PreviousWeekAsync()
{ {
AnchorDate = AnchorDate.AddDays(-7); _calendarStateService.SelectedDate = DateHelper.StartOfWeekMonday(SelectedDate).AddDays(-7);
await RefreshAsync(); await RefreshAsync();
} }
private async Task NextWeekAsync() private async Task NextWeekAsync()
{ {
AnchorDate = AnchorDate.AddDays(7); _calendarStateService.SelectedDate = DateHelper.StartOfWeekMonday(SelectedDate).AddDays(7);
await RefreshAsync(); await RefreshAsync();
} }
private async Task SetTodayAsync() private async Task TodayAsync()
{ {
await _calendarState.ShowDayTabAsync(DateTime.Today); _calendarStateService.ResetToToday();
await RefreshAsync();
} }
private async Task OpenDayAsync(WeekCellViewModel? cell) private async void HandleSharedDateChanged(DateTime date)
{ {
if (cell is null) SelectedDate = date;
return; await RefreshAsync();
await _calendarState.ShowDayTabAsync(cell.Date);
}
private static DateTime StartOfWeek(DateTime date)
{
int diff = ((int)date.DayOfWeek + 6) % 7;
return date.Date.AddDays(-diff);
}
private static string StateLabel(HealthState? state)
{
if (state is null)
return "—";
return ThemeResourceHelper.GetString(
state.Value.ToTextKey(),
state.Value.ToFallbackText());
}
private static Color StateColor(HealthState? state)
{
var key = state?.ToColorKey() ?? ThemeKeys.PanelBackground2;
return ThemeResourceHelper.GetColor(key, "#203041");
} }
} }
+7
View File
@@ -0,0 +1,7 @@
namespace cfs_tracker.ViewModels;
public class WeekdayOptionItemViewModel
{
public DayOfWeek Value { get; init; }
public string Name { get; init; } = string.Empty;
}
-8
View File
@@ -1,8 +0,0 @@
using System.Collections.ObjectModel;
namespace cfs_tracker.ViewModels;
public class YearMonthViewModel
{
public int MonthNumber { get; init; }
public string MonthText { get; init; } = "";
public ObservableCollection<MonthCellViewModel> Days { get; } = new();
}
+76 -61
View File
@@ -1,125 +1,140 @@
using System.Collections.ObjectModel;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data; using cfs_tracker.Data;
using cfs_tracker.Helpers; using cfs_tracker.Helpers;
using cfs_tracker.Models;
using cfs_tracker.Services; using cfs_tracker.Services;
using Microsoft.Maui.Storage;
using System.Collections.ObjectModel;
namespace cfs_tracker.ViewModels; namespace cfs_tracker.ViewModels;
public partial class YearViewModel : ObservableObject public partial class YearViewModel : ObservableObject
{ {
private readonly HealthEntryRepository _repository; private readonly HealthEntryRepository _healthEntryRepository;
private readonly AppearanceService _appearanceService;
private readonly AggregationService _aggregationService; private readonly AggregationService _aggregationService;
private readonly CalendarStateService _calendarState; private readonly CalendarStateService _calendarStateService;
private readonly CultureInfo _culture = new("de-DE"); private readonly IPdfExportService _pdfExportService;
private int _currentYear = DateTime.Today.Year;
[ObservableProperty] [ObservableProperty]
private string selectedYearText = string.Empty; private DateTime selectedDate;
public ObservableCollection<YearMonthViewModel> Months { get; } = new(); [ObservableProperty]
private string headerText = string.Empty;
public ObservableCollection<MonthSectionViewModel> Months { get; } = new();
public IAsyncRelayCommand PreviousYearCommand { get; } public IAsyncRelayCommand PreviousYearCommand { get; }
public IAsyncRelayCommand NextYearCommand { get; } public IAsyncRelayCommand NextYearCommand { get; }
public IAsyncRelayCommand TodayCommand { get; } public IAsyncRelayCommand TodayCommand { get; }
public IAsyncRelayCommand ExportPdfCommand { get; }
public IAsyncRelayCommand<MonthCellViewModel> OpenDayCommand { get; } public IAsyncRelayCommand<MonthCellViewModel> OpenDayCommand { get; }
public YearViewModel( public YearViewModel(
HealthEntryRepository repository, HealthEntryRepository healthEntryRepository,
AppearanceService appearanceService,
AggregationService aggregationService, AggregationService aggregationService,
CalendarStateService calendarState) CalendarStateService calendarStateService,
IPdfExportService pdfExportService)
{ {
_repository = repository; _healthEntryRepository = healthEntryRepository;
_appearanceService = appearanceService;
_aggregationService = aggregationService; _aggregationService = aggregationService;
_calendarState = calendarState; _calendarStateService = calendarStateService;
_pdfExportService = pdfExportService;
PreviousYearCommand = new AsyncRelayCommand(PreviousYearAsync); PreviousYearCommand = new AsyncRelayCommand(PreviousYearAsync);
NextYearCommand = new AsyncRelayCommand(NextYearAsync); NextYearCommand = new AsyncRelayCommand(NextYearAsync);
TodayCommand = new AsyncRelayCommand(SetTodayAsync); TodayCommand = new AsyncRelayCommand(TodayAsync);
ExportPdfCommand = new AsyncRelayCommand(ExportAsync);
OpenDayCommand = new AsyncRelayCommand<MonthCellViewModel>(OpenDayAsync); OpenDayCommand = new AsyncRelayCommand<MonthCellViewModel>(OpenDayAsync);
_calendarStateService.SelectedDateChanged += HandleSharedDateChanged;
SelectedDate = _calendarStateService.SelectedDate;
} }
public async Task RefreshAsync() public async Task RefreshAsync()
{ {
SelectedYearText = _currentYear.ToString(); SelectedDate = _calendarStateService.SelectedDate;
HeaderText = DateHelper.ToGermanYear(SelectedDate);
var start = new DateTime(_currentYear, 1, 1); var yearStart = new DateTime(SelectedDate.Year, 1, 1);
var end = start.AddYears(1); var yearEnd = yearStart.AddYears(1);
var entries = await _repository.GetEntriesBetweenAsync(start, end);
var summaries = _aggregationService.BuildYearSummary(_currentYear, entries);
var entries = await _healthEntryRepository.GetEntriesBetweenAsync(yearStart, yearEnd);
Months.Clear(); Months.Clear();
for (int month = 1; month <= 12; month++) for (var monthNumber = 1; monthNumber <= 12; monthNumber++)
{ {
var monthVm = new YearMonthViewModel var monthStart = new DateTime(SelectedDate.Year, monthNumber, 1);
var daysInMonth = DateTime.DaysInMonth(monthStart.Year, monthStart.Month);
var section = new MonthSectionViewModel
{ {
MonthNumber = month, Title = DateHelper.ToGermanMonthYear(monthStart)
MonthText = new DateTime(_currentYear, month, 1).ToString("MMMM", _culture)
}; };
var monthStart = new DateTime(_currentYear, month, 1); for (var day = 1; day <= daysInMonth; day++)
int leadingEmptyDays = ((int)monthStart.DayOfWeek + 6) % 7; {
var date = new DateTime(monthStart.Year, monthStart.Month, day);
var dayEntries = entries.Where(x => x.EntryDate.Date == date.Date).ToList();
var average = _aggregationService.CalculateAverage(dayEntries);
for (int i = 0; i < leadingEmptyDays; i++) section.Cells.Add(new MonthCellViewModel
monthVm.Days.Add(MonthCellViewModel.Placeholder()); {
Date = date,
foreach (var summary in summaries.Where(x => x.Date.Month == month)) DayNumberText = date.Day.ToString(),
monthVm.Days.Add(BuildCell(summary)); IsCurrentMonth = true,
IsToday = date.Date == DateTime.Today,
while (monthVm.Days.Count % 7 != 0) HasEntries = dayEntries.Count > 0,
monthVm.Days.Add(MonthCellViewModel.Placeholder()); AverageStateText = _aggregationService.ToDisplayText(average, _appearanceService),
StateColor = _appearanceService.GetColor(average.State.ToAppearanceColorKey(), "#1F242B"),
Months.Add(monthVm); TextColor = _appearanceService.GetColor(AppearanceKeys.TextPrimary, "#DCE7F3"),
} BorderColor = date.Date == DateTime.Today
? _appearanceService.GetColor(AppearanceKeys.StateYellow, "#B89A42")
: _appearanceService.GetColor(AppearanceKeys.Border, "#2A3E55")
});
} }
private MonthCellViewModel BuildCell(CalendarDaySummary summary) Months.Add(section);
}
}
private async Task OpenDayAsync(MonthCellViewModel? item)
{ {
var colorKey = summary.DisplayState?.ToColorKey() ?? ThemeKeys.PanelBackground2; if (item is null)
bool isToday = summary.Date.Date == DateTime.Today.Date; return;
return new MonthCellViewModel _calendarStateService.SelectedDate = item.Date;
await Shell.Current.GoToAsync("//day");
}
private async Task ExportAsync()
{ {
IsRealDay = true, var result = await _pdfExportService.ExportYearAsync(SelectedDate);
Date = summary.Date, await ExportUiHelper.ShowExportSavedActionsAsync(result);
DayNumberText = summary.Date.Day.ToString(),
CountText = summary.EntryCount > 0 ? $"{summary.EntryCount}x" : string.Empty,
BackgroundColor = ThemeResourceHelper.GetColor(colorKey, "#203041"),
BorderColor = isToday
? ThemeResourceHelper.GetColor(ThemeKeys.TextPrimary, "#D9E6F2")
: ThemeResourceHelper.GetColor(ThemeKeys.PanelBorder, "#2B3E52"),
TextColor = ThemeResourceHelper.GetColor(ThemeKeys.TextPrimary, "#D9E6F2")
};
} }
private async Task PreviousYearAsync() private async Task PreviousYearAsync()
{ {
_currentYear--; _calendarStateService.SelectedDate = new DateTime(SelectedDate.Year - 1, SelectedDate.Month, 1);
await RefreshAsync(); await RefreshAsync();
} }
private async Task NextYearAsync() private async Task NextYearAsync()
{ {
_currentYear++; _calendarStateService.SelectedDate = new DateTime(SelectedDate.Year + 1, SelectedDate.Month, 1);
await RefreshAsync(); await RefreshAsync();
} }
private async Task SetTodayAsync() private async Task TodayAsync()
{ {
await _calendarState.ShowDayTabAsync(DateTime.Today); _calendarStateService.ResetToToday();
await RefreshAsync();
} }
private async Task OpenDayAsync(MonthCellViewModel? cell) private async void HandleSharedDateChanged(DateTime date)
{ {
if (cell is null || !cell.IsRealDay) SelectedDate = date;
return; await RefreshAsync();
await _calendarState.ShowDayTabAsync(cell.Date);
} }
} }
+121 -177
View File
@@ -1,210 +1,154 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<ContentPage <ContentPage x:Class="cfs_tracker.Views.DayPage"
x:Class="cfs_tracker.Views.DayPage" x:Name="RootPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="ThisPage" xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels"
Title="Tag"> x:DataType="viewModels:DayViewModel"
Title="Tag"
BackgroundColor="{DynamicResource AppBackground}">
<ScrollView> <ScrollView>
<VerticalStackLayout Padding="16" Spacing="14"> <VerticalStackLayout Padding="16" Spacing="16">
<Grid ColumnDefinitions="Auto,*,Auto"
<Grid ColumnDefinitions="Auto,*,Auto,Auto"> VerticalOptions="Center">
<Button <Button Text="←"
Grid.Column="0" Style="{StaticResource PrimaryButtonStyle}"
Text="◀"
WidthRequest="52"
HeightRequest="44"
Command="{Binding PreviousDayCommand}" /> Command="{Binding PreviousDayCommand}" />
<Label Grid.Column="1"
<Label
Grid.Column="1"
Text="{Binding SelectedDateText}" Text="{Binding SelectedDateText}"
HorizontalTextAlignment="Center" HorizontalTextAlignment="Center"
VerticalTextAlignment="Center" VerticalTextAlignment="Center"
FontSize="22"
FontAttributes="Bold" />
<Button
Grid.Column="2"
Text="Heute"
Margin="8,0,0,0"
Command="{Binding TodayCommand}" />
<Button
Grid.Column="3"
Text="+"
Margin="8,0,0,0"
WidthRequest="52"
HeightRequest="44"
Command="{Binding AddEntryCommand}" />
</Grid>
<Grid ColumnDefinitions="*,*" RowDefinitions="Auto,Auto" ColumnSpacing="10" RowSpacing="10">
<Border
Grid.Row="0"
Grid.Column="0"
BackgroundColor="{DynamicResource StateGreen}"
StrokeThickness="0"
StrokeShape="RoundRectangle 12"
Padding="12">
<Border.GestureRecognizers>
<TapGestureRecognizer Command="{Binding SaveGreenQuickCommand}" />
</Border.GestureRecognizers>
<VerticalStackLayout>
<Label Text="{Binding GreenStatusText}" TextColor="White" FontAttributes="Bold" />
<Label Text="{Binding GreenCount}" TextColor="White" FontSize="22" />
</VerticalStackLayout>
</Border>
<Border
Grid.Row="0"
Grid.Column="1"
BackgroundColor="{DynamicResource StateYellow}"
StrokeThickness="0"
StrokeShape="RoundRectangle 12"
Padding="12">
<Border.GestureRecognizers>
<TapGestureRecognizer Command="{Binding SaveYellowQuickCommand}" />
</Border.GestureRecognizers>
<VerticalStackLayout>
<Label Text="{Binding YellowStatusText}" TextColor="White" FontAttributes="Bold" />
<Label Text="{Binding YellowCount}" TextColor="White" FontSize="22" />
</VerticalStackLayout>
</Border>
<Border
Grid.Row="1"
Grid.Column="0"
BackgroundColor="{DynamicResource StateRed}"
StrokeThickness="0"
StrokeShape="RoundRectangle 12"
Padding="12">
<Border.GestureRecognizers>
<TapGestureRecognizer Command="{Binding SaveRedQuickCommand}" />
</Border.GestureRecognizers>
<VerticalStackLayout>
<Label Text="{Binding RedStatusText}" TextColor="White" FontAttributes="Bold" />
<Label Text="{Binding RedCount}" TextColor="White" FontSize="22" />
</VerticalStackLayout>
</Border>
<Border
Grid.Row="1"
Grid.Column="1"
BackgroundColor="{DynamicResource StateGray}"
StrokeThickness="0"
StrokeShape="RoundRectangle 12"
Padding="12">
<Border.GestureRecognizers>
<TapGestureRecognizer Command="{Binding SaveGrayQuickCommand}" />
</Border.GestureRecognizers>
<VerticalStackLayout>
<Label Text="{Binding GrayStatusText}" TextColor="White" FontAttributes="Bold" />
<Label Text="{Binding GrayCount}" TextColor="White" FontSize="22" />
</VerticalStackLayout>
</Border>
</Grid>
<Label
Text="Einträge"
FontSize="20" FontSize="20"
FontAttributes="Bold" FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" /> TextColor="{DynamicResource TextPrimary}" />
<Button Grid.Column="2"
Text="→"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding NextDayCommand}" />
</Grid>
<CollectionView <Grid ColumnDefinitions="*,*"
ItemsSource="{Binding Entries}" ColumnSpacing="12">
<Button Text="Heute"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding TodayCommand}" />
<Button Grid.Column="1"
Text="Export"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding ExportPdfCommand}" />
</Grid>
<Grid ColumnDefinitions="*,*"
RowDefinitions="Auto,Auto"
ColumnSpacing="12"
RowSpacing="12">
<Button Grid.Row="0"
Grid.Column="0"
Text="{Binding GreenCounterText}"
HeightRequest="92"
Command="{Binding SaveGreenQuickCommand}"
BackgroundColor="{Binding GreenStateColor}"
TextColor="White" />
<Button Grid.Row="0"
Grid.Column="1"
Text="{Binding YellowCounterText}"
HeightRequest="92"
Command="{Binding SaveYellowQuickCommand}"
BackgroundColor="{Binding YellowStateColor}"
TextColor="Black" />
<Button Grid.Row="1"
Grid.Column="0"
Text="{Binding RedCounterText}"
HeightRequest="92"
Command="{Binding SaveRedQuickCommand}"
BackgroundColor="{Binding RedStateColor}"
TextColor="White" />
<Button Grid.Row="1"
Grid.Column="1"
Text="{Binding GrayCounterText}"
HeightRequest="92"
Command="{Binding SaveGrayQuickCommand}"
BackgroundColor="{Binding GrayStateColor}"
TextColor="White" />
</Grid>
<Button Text="{Binding AddEntryButtonText}"
Command="{Binding AddEntryCommand}"
Style="{StaticResource PrimaryButtonStyle}"
IsEnabled="{Binding CanAddEntry}" />
<Label Text="Noch keine Einträge vorhanden."
IsVisible="{Binding HasNoEntries}"
HorizontalTextAlignment="Center"
TextColor="{DynamicResource TextMuted}" />
<CollectionView ItemsSource="{Binding Entries}"
SelectionMode="None"> SelectionMode="None">
<CollectionView.ItemTemplate> <CollectionView.ItemTemplate>
<DataTemplate> <DataTemplate x:DataType="viewModels:DayEntryItemViewModel">
<Border <Border Margin="0,0,0,12"
Margin="0,0,0,8"
Padding="12" Padding="12"
BackgroundColor="{Binding BackgroundColor}" Stroke="{DynamicResource Border}"
StrokeThickness="0" BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 12"> StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="10">
<VerticalStackLayout Spacing="8"> <Grid ColumnDefinitions="*,Auto,Auto"
ColumnSpacing="10">
<Grid ColumnDefinitions="Auto,*,Auto" ColumnSpacing="12"> <VerticalStackLayout Spacing="4">
<Label <Label Text="{Binding SlotText}"
Grid.Column="0"
Text="{Binding TimeText}"
TextColor="{Binding TextColor}"
FontAttributes="Bold" FontAttributes="Bold"
VerticalOptions="Center" /> TextColor="{DynamicResource TextMuted}" />
<Label Text="{Binding StateText}"
<VerticalStackLayout Grid.Column="1" Spacing="2"> FontSize="18"
<Label FontAttributes="Bold"
Text="{Binding StateText}" TextColor="{Binding ForegroundColor}" />
TextColor="{Binding TextColor}"
FontAttributes="Bold" />
<Button
Text="{Binding FoldoutText}"
Command="{Binding ToggleExpandedCommand}"
IsVisible="{Binding HasDetails}"
Padding="0"
FontSize="12"
BackgroundColor="Transparent"
TextColor="{Binding TextColor}"
HorizontalOptions="Start" />
</VerticalStackLayout> </VerticalStackLayout>
<Button <Button Grid.Column="1"
Grid.Column="2" Text="Bearbeiten"
Text="X" Style="{StaticResource PrimaryButtonStyle}"
WidthRequest="44" Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.EditEntryCommand}"
HeightRequest="44" CommandParameter="{Binding .}" />
Command="{Binding Source={x:Reference ThisPage}, Path=BindingContext.DeleteEntryCommand}"
<Button Grid.Column="2"
Text="Löschen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.DeleteEntryCommand}"
CommandParameter="{Binding .}" /> CommandParameter="{Binding .}" />
</Grid> </Grid>
<Border <Border Padding="8"
IsVisible="{Binding IsExpanded}" StrokeThickness="0"
Padding="10" StrokeShape="RoundRectangle 10"
BackgroundColor="{DynamicResource PanelBackground2}" BackgroundColor="{Binding StateColor}">
Stroke="{DynamicResource PanelBorder}" <Label Text="{Binding StateText}"
StrokeThickness="1"
StrokeShape="RoundRectangle 10">
<VerticalStackLayout Spacing="6">
<VerticalStackLayout IsVisible="{Binding HasActivity}" Spacing="2">
<Label
Text="Tätigkeit"
FontAttributes="Bold" FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" /> TextColor="{Binding ForegroundColor}" />
<Label
Text="{Binding ActivityText}"
TextColor="{DynamicResource TextMuted}" />
</VerticalStackLayout>
<VerticalStackLayout IsVisible="{Binding HasSymptoms}" Spacing="2">
<Label
Text="Symptome"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label
Text="{Binding SymptomsText}"
TextColor="{DynamicResource TextMuted}" />
</VerticalStackLayout>
</VerticalStackLayout>
</Border> </Border>
<Button Text="{Binding DetailsButtonText}"
IsVisible="{Binding HasDetails}"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding ToggleExpandedCommand}" />
<VerticalStackLayout IsVisible="{Binding IsExpanded}"
Spacing="6">
<Label Text="{Binding ActivityText, StringFormat='Tätigkeit: {0}'}"
IsVisible="{Binding HasActivity}"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="{Binding SymptomsText, StringFormat='Symptome: {0}'}"
IsVisible="{Binding HasSymptoms}"
TextColor="{DynamicResource TextPrimary}" />
</VerticalStackLayout>
</VerticalStackLayout> </VerticalStackLayout>
</Border> </Border>
</DataTemplate> </DataTemplate>
</CollectionView.ItemTemplate> </CollectionView.ItemTemplate>
</CollectionView> </CollectionView>
</VerticalStackLayout> </VerticalStackLayout>
</ScrollView> </ScrollView>
</ContentPage> </ContentPage>
+64 -72
View File
@@ -1,100 +1,92 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<ContentPage <ContentPage x:Class="cfs_tracker.Views.MonthPage"
x:Class="cfs_tracker.Views.MonthPage" x:Name="RootPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="ThisPage" xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels"
Title="Monat"> x:DataType="viewModels:MonthViewModel"
Title="Monat"
BackgroundColor="{DynamicResource AppBackground}">
<Grid RowDefinitions="Auto,Auto,*" Padding="16"> <ScrollView>
<VerticalStackLayout Padding="16" Spacing="16">
<Grid Grid.Row="0" ColumnDefinitions="Auto,*,Auto,Auto" Margin="0,0,0,12"> <Grid ColumnDefinitions="Auto,*,Auto"
<Button VerticalOptions="Center">
Grid.Column="0" <Button Text="←"
Text="◀" Style="{StaticResource PrimaryButtonStyle}"
WidthRequest="52"
HeightRequest="44"
Command="{Binding PreviousMonthCommand}" /> Command="{Binding PreviousMonthCommand}" />
<Label Grid.Column="1"
<Label Text="{Binding HeaderText}"
Grid.Column="1"
Text="{Binding SelectedMonthText}"
HorizontalTextAlignment="Center" HorizontalTextAlignment="Center"
VerticalTextAlignment="Center" VerticalTextAlignment="Center"
FontSize="24" FontSize="20"
FontAttributes="Bold" /> FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Button <Button Grid.Column="2"
Grid.Column="2" Text="→"
Text="Heute" Style="{StaticResource PrimaryButtonStyle}"
Margin="8,0,0,0"
Command="{Binding TodayCommand}" />
<Button
Grid.Column="3"
Text="▶"
WidthRequest="52"
HeightRequest="44"
Margin="8,0,0,0"
Command="{Binding NextMonthCommand}" /> Command="{Binding NextMonthCommand}" />
</Grid> </Grid>
<Grid Grid.Row="1" ColumnDefinitions="*,*,*,*,*,*,*" Margin="0,0,0,8"> <Grid ColumnDefinitions="*,*"
<Label Grid.Column="0" Text="Mo" HorizontalTextAlignment="Center" FontAttributes="Bold" /> ColumnSpacing="12">
<Label Grid.Column="1" Text="Di" HorizontalTextAlignment="Center" FontAttributes="Bold" /> <Button Text="Heute"
<Label Grid.Column="2" Text="Mi" HorizontalTextAlignment="Center" FontAttributes="Bold" /> Style="{StaticResource PrimaryButtonStyle}"
<Label Grid.Column="3" Text="Do" HorizontalTextAlignment="Center" FontAttributes="Bold" /> Command="{Binding TodayCommand}" />
<Label Grid.Column="4" Text="Fr" HorizontalTextAlignment="Center" FontAttributes="Bold" /> <Button Grid.Column="1"
<Label Grid.Column="5" Text="Sa" HorizontalTextAlignment="Center" FontAttributes="Bold" /> Text="Export"
<Label Grid.Column="6" Text="So" HorizontalTextAlignment="Center" FontAttributes="Bold" /> Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding ExportPdfCommand}" />
</Grid> </Grid>
<CollectionView <Grid ColumnDefinitions="*,*,*,*,*,*,*"
Grid.Row="2" ColumnSpacing="4">
ItemsSource="{Binding Days}" <Label Text="Mo" HorizontalTextAlignment="Center" TextColor="{DynamicResource TextMuted}" />
<Label Grid.Column="1" Text="Di" HorizontalTextAlignment="Center" TextColor="{DynamicResource TextMuted}" />
<Label Grid.Column="2" Text="Mi" HorizontalTextAlignment="Center" TextColor="{DynamicResource TextMuted}" />
<Label Grid.Column="3" Text="Do" HorizontalTextAlignment="Center" TextColor="{DynamicResource TextMuted}" />
<Label Grid.Column="4" Text="Fr" HorizontalTextAlignment="Center" TextColor="{DynamicResource TextMuted}" />
<Label Grid.Column="5" Text="Sa" HorizontalTextAlignment="Center" TextColor="{DynamicResource TextMuted}" />
<Label Grid.Column="6" Text="So" HorizontalTextAlignment="Center" TextColor="{DynamicResource TextMuted}" />
</Grid>
<CollectionView ItemsSource="{Binding Cells}"
SelectionMode="None"> SelectionMode="None">
<CollectionView.ItemsLayout> <CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="7" /> <GridItemsLayout Orientation="Vertical"
Span="7" />
</CollectionView.ItemsLayout> </CollectionView.ItemsLayout>
<CollectionView.ItemTemplate> <CollectionView.ItemTemplate>
<DataTemplate> <DataTemplate x:DataType="viewModels:MonthCellViewModel">
<Grid Padding="3"> <Border Margin="2"
<Border Padding="6"
HeightRequest="74"
BackgroundColor="{Binding BackgroundColor}"
Stroke="{Binding BorderColor}" Stroke="{Binding BorderColor}"
StrokeThickness="1" BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 10"> StrokeShape="RoundRectangle 10">
<Border.GestureRecognizers>
<Grid Padding="6">
<Grid.GestureRecognizers>
<TapGestureRecognizer <TapGestureRecognizer
Command="{Binding Source={x:Reference ThisPage}, Path=BindingContext.OpenDayCommand}" Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.OpenDayCommand}"
CommandParameter="{Binding .}" /> CommandParameter="{Binding .}" />
</Grid.GestureRecognizers> </Border.GestureRecognizers>
<VerticalStackLayout <VerticalStackLayout Spacing="4">
IsVisible="{Binding IsRealDay}" <Label Text="{Binding DayNumberText}"
Spacing="4">
<Label
Text="{Binding DayNumberText}"
TextColor="{Binding TextColor}"
FontAttributes="Bold" FontAttributes="Bold"
FontSize="16" /> TextColor="{Binding TextColor}" />
<Border Padding="4"
<Label StrokeThickness="0"
Text="{Binding CountText}" StrokeShape="RoundRectangle 8"
TextColor="{Binding TextColor}" BackgroundColor="{Binding StateColor}">
FontSize="12" /> <Label Text="{Binding AverageStateText}"
FontSize="11"
HorizontalTextAlignment="Center"
TextColor="White" />
</Border>
</VerticalStackLayout> </VerticalStackLayout>
</Grid>
</Border> </Border>
</Grid>
</DataTemplate> </DataTemplate>
</CollectionView.ItemTemplate> </CollectionView.ItemTemplate>
</CollectionView> </CollectionView>
</VerticalStackLayout>
</Grid> </ScrollView>
</ContentPage> </ContentPage>
+15 -3
View File
@@ -1,8 +1,20 @@
using cfs_tracker.ViewModels; using cfs_tracker.ViewModels;
namespace cfs_tracker.Views; namespace cfs_tracker.Views;
public partial class MonthPage : ContentPage public partial class MonthPage : ContentPage
{ {
private readonly MonthViewModel _vm; private readonly MonthViewModel _viewModel;
public MonthPage(MonthViewModel vm){ InitializeComponent(); BindingContext = _vm = vm; }
protected override async void OnAppearing(){ base.OnAppearing(); await _vm.RefreshAsync(); } public MonthPage(MonthViewModel viewModel)
{
InitializeComponent();
BindingContext = _viewModel = viewModel;
}
protected override async void OnAppearing()
{
base.OnAppearing();
await _viewModel.RefreshAsync();
}
} }
+288 -99
View File
@@ -1,129 +1,318 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<ContentPage <ContentPage x:Class="cfs_tracker.Views.OptionsPage"
x:Class="cfs_tracker.Views.OptionsPage" x:Name="RootPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:conv="clr-namespace:cfs_tracker.Converters" xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels"
Title="Optionen"> x:DataType="viewModels:OptionsViewModel"
Title="Optionen"
<ContentPage.Resources> BackgroundColor="{DynamicResource AppBackground}">
<ResourceDictionary>
<conv:HexToColorConverter x:Key="HexToColorConverter" />
</ResourceDictionary>
</ContentPage.Resources>
<ScrollView> <ScrollView>
<VerticalStackLayout Padding="16" Spacing="16"> <VerticalStackLayout Padding="16" Spacing="16">
<Label Text="Optionen"
FontSize="28"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label <Label Text="{Binding StatusText}"
Text="Optionen" TextColor="{DynamicResource TextMuted}" />
FontSize="26"
FontAttributes="Bold" />
<Label <Border Padding="12"
Text="Aussehen" Stroke="{DynamicResource Border}"
FontSize="22" BackgroundColor="{DynamicResource SurfaceBackground}"
FontAttributes="Bold" /> StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="12">
<Label Text="Aussehen"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label <VerticalStackLayout BindableLayout.ItemsSource="{Binding AppearanceColors}"
Text="Farben" Spacing="10">
FontSize="18" <BindableLayout.ItemTemplate>
FontAttributes="Bold" /> <DataTemplate x:DataType="viewModels:AppearanceColorItemViewModel">
<Grid ColumnDefinitions="*,120"
ColumnSpacing="10"
Padding="0,6">
<VerticalStackLayout>
<Label Text="{Binding Title}"
TextColor="{DynamicResource TextPrimary}" />
<Entry Text="{Binding Value}"
Placeholder="#112233" />
</VerticalStackLayout>
<CollectionView ItemsSource="{Binding AppearanceColors}" SelectionMode="None"> <Border Grid.Column="1"
<CollectionView.ItemTemplate> Padding="8"
<DataTemplate> Stroke="{DynamicResource Border}"
<Border Padding="12" Margin="0,0,0,8">
<VerticalStackLayout Spacing="8">
<Label
Text="{Binding Title}"
FontAttributes="Bold" />
<Grid ColumnDefinitions="*,60" ColumnSpacing="10">
<Entry
Grid.Column="0"
Text="{Binding Value}"
Placeholder="#RRGGBB" />
<Border
Grid.Column="1"
HeightRequest="42"
WidthRequest="42"
Padding="0"
Stroke="{DynamicResource PanelBorder}"
StrokeThickness="1"
StrokeShape="RoundRectangle 8" StrokeShape="RoundRectangle 8"
BackgroundColor="{Binding Value, Converter={StaticResource HexToColorConverter}}" /> BackgroundColor="{Binding PreviewColor}">
<Label Text="{Binding Value}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
TextColor="{DynamicResource TextPrimary}" />
</Border>
</Grid>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
<VerticalStackLayout BindableLayout.ItemsSource="{Binding StatusTexts}"
Spacing="10">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:AppearanceTextItemViewModel">
<VerticalStackLayout Spacing="4"
Padding="0,6">
<Label Text="{Binding Title}"
TextColor="{DynamicResource TextPrimary}" />
<Entry Text="{Binding Value}" />
</VerticalStackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
<Grid ColumnDefinitions="*,*"
ColumnSpacing="12">
<Button Text="Speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding SaveAppearanceCommand}" />
<Button Grid.Column="1"
Text="Zurücksetzen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding ResetAppearanceCommand}" />
</Grid>
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="12">
<Label Text="Tätigkeiten"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Grid ColumnDefinitions="*,Auto"
ColumnSpacing="10">
<Entry Text="{Binding NewActivityName}"
Placeholder="Neue Tätigkeit" />
<Button Grid.Column="1"
Text="Hinzufügen"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding AddActivityCommand}" />
</Grid> </Grid>
<VerticalStackLayout BindableLayout.ItemsSource="{Binding Activities}"
Spacing="10">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:ActivityManageItemViewModel">
<Border Padding="10"
Stroke="{DynamicResource Border}"
StrokeShape="RoundRectangle 10"
BackgroundColor="{DynamicResource SurfaceBackgroundAlt}">
<VerticalStackLayout Spacing="8">
<Entry Text="{Binding Name}" />
<Label Text="{Binding UsageHint}"
FontSize="12"
TextColor="{DynamicResource TextMuted}" />
<Grid ColumnDefinitions="*,*,*"
ColumnSpacing="8">
<Button Text="Speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.SaveActivityCommand}"
CommandParameter="{Binding .}" />
<Button Grid.Column="1"
Text="Aktiv/Inaktiv"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.ToggleActivityActiveCommand}"
CommandParameter="{Binding .}" />
<Button Grid.Column="2"
Text="Entfernen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.DeleteActivityCommand}"
CommandParameter="{Binding .}" />
</Grid>
</VerticalStackLayout> </VerticalStackLayout>
</Border> </Border>
</DataTemplate> </DataTemplate>
</CollectionView.ItemTemplate> </BindableLayout.ItemTemplate>
</CollectionView> </VerticalStackLayout>
<Label
Text="Status-Texte"
FontSize="18"
FontAttributes="Bold" />
<CollectionView ItemsSource="{Binding StatusTexts}" SelectionMode="None">
<CollectionView.ItemTemplate>
<DataTemplate>
<Border Padding="12" Margin="0,0,0,8">
<VerticalStackLayout Spacing="6">
<Label
Text="{Binding Title}"
FontAttributes="Bold" />
<Entry
Text="{Binding Value}" />
</VerticalStackLayout> </VerticalStackLayout>
</Border> </Border>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<HorizontalStackLayout Spacing="10"> <Border Padding="12"
<Button Stroke="{DynamicResource Border}"
Text="Aussehen speichern" BackgroundColor="{DynamicResource SurfaceBackground}"
Command="{Binding SaveAppearanceCommand}" /> StrokeShape="RoundRectangle 14">
<Button
Text="Standard wiederherstellen"
Command="{Binding ResetAppearanceCommand}" />
</HorizontalStackLayout>
<Label
Text="Datenbank"
FontSize="22"
FontAttributes="Bold" />
<Border Padding="14">
<VerticalStackLayout Spacing="12"> <VerticalStackLayout Spacing="12">
<Label <Label Text="Symptome"
Text="Alle Einträge löschen" FontSize="20"
FontSize="18" FontAttributes="Bold"
FontAttributes="Bold" /> TextColor="{DynamicResource TextPrimary}" />
<Label <Grid ColumnDefinitions="*,Auto"
Text="Zur Bestätigung das Wort 'löschen' eingeben." /> ColumnSpacing="10">
<Entry Text="{Binding NewSymptomName}"
Placeholder="Neues Symptom" />
<Button Grid.Column="1"
Text="Hinzufügen"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding AddSymptomCommand}" />
</Grid>
<Entry <VerticalStackLayout BindableLayout.ItemsSource="{Binding Symptoms}"
Placeholder="löschen" Spacing="10">
Text="{Binding DeleteConfirmationText}" /> <BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:SymptomManageItemViewModel">
<Border Padding="10"
Stroke="{DynamicResource Border}"
StrokeShape="RoundRectangle 10"
BackgroundColor="{DynamicResource SurfaceBackgroundAlt}">
<VerticalStackLayout Spacing="8">
<Entry Text="{Binding Name}" />
<Label Text="{Binding UsageHint}"
FontSize="12"
TextColor="{DynamicResource TextMuted}" />
<Grid ColumnDefinitions="*,*,*"
ColumnSpacing="8">
<Button Text="Speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.SaveSymptomCommand}"
CommandParameter="{Binding .}" />
<Button Grid.Column="1"
Text="Aktiv/Inaktiv"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.ToggleSymptomActiveCommand}"
CommandParameter="{Binding .}" />
<Button Grid.Column="2"
Text="Entfernen"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.DeleteSymptomCommand}"
CommandParameter="{Binding .}" />
</Grid>
</VerticalStackLayout>
</Border>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
</VerticalStackLayout>
</Border>
<Button <Border Padding="12"
Text="Alle Daten löschen" Stroke="{DynamicResource Border}"
BackgroundColor="#A85C5C" BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="12">
<Label Text="Push-Benachrichtigungen"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="Text: 'Wie geht es dir?' mit Schnellwahl für Gelb, Rot und Grau/Schwarz."
TextColor="{DynamicResource TextMuted}" />
<Button Text="Zeit hinzufügen"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding AddScheduleCommand}" />
<VerticalStackLayout BindableLayout.ItemsSource="{Binding NotificationSchedules}"
Spacing="10">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:NotificationScheduleItemViewModel">
<Border Padding="10"
Stroke="{DynamicResource Border}"
StrokeShape="RoundRectangle 10"
BackgroundColor="{DynamicResource SurfaceBackgroundAlt}">
<VerticalStackLayout Spacing="8">
<Picker Title="Wochentag"
ItemsSource="{Binding WeekdayOptions}"
ItemDisplayBinding="{Binding Name}"
SelectedItem="{Binding SelectedWeekday}" />
<TimePicker Time="{Binding SelectedTime}" />
<Grid ColumnDefinitions="Auto,*"
ColumnSpacing="8">
<CheckBox IsChecked="{Binding IsEnabled}" />
<Label Grid.Column="1"
Text="Aktiv"
VerticalOptions="Center"
TextColor="{DynamicResource TextPrimary}" />
</Grid>
<Button Text="Entfernen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.DeleteScheduleCommand}"
CommandParameter="{Binding .}" />
</VerticalStackLayout>
</Border>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
<Button Text="Benachrichtigungszeiten speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding SaveSchedulesCommand}" />
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="12">
<Label Text="Datenbank"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="{Binding CurrentDatabasePath, StringFormat='Aktiver Pfad: {0}'}"
TextColor="{DynamicResource TextMuted}" />
<Grid ColumnDefinitions="Auto,*"
ColumnSpacing="8">
<CheckBox IsChecked="{Binding UseExternalDatabase}" />
<Label Grid.Column="1"
Text="Externe Datenbank verwenden"
VerticalOptions="Center"
TextColor="{DynamicResource TextPrimary}" />
</Grid>
<Entry Text="{Binding ExternalDatabasePath}"
Placeholder="Ordner oder Dateipfad für externe DB" />
<Button Text="Datenbankpfad speichern"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding SaveDatabaseLocationCommand}" />
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="12">
<Label Text="Alle Einträge löschen"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="Zum Bestätigen 'löschen' eingeben."
TextColor="{DynamicResource TextMuted}" />
<Entry Text="{Binding DeleteConfirmationText}"
Placeholder="löschen" />
<Button Text="Alles löschen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding DeleteAllDataCommand}" /> Command="{Binding DeleteAllDataCommand}" />
</VerticalStackLayout> </VerticalStackLayout>
</Border> </Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="10">
<Label Text="Export"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label <Button Text="Export entleeren"
Text="{Binding StatusText}" Style="{StaticResource SecondaryButtonStyle}"
FontSize="13" /> Command="{Binding ClearExportsCommand}" />
</VerticalStackLayout>
</Border>
</VerticalStackLayout> </VerticalStackLayout>
</ScrollView> </ScrollView>
</ContentPage> </ContentPage>
+151 -17
View File
@@ -1,23 +1,157 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="cfs_tracker.Views.QuickEntryPage" <ContentPage
xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
Title="Eintrag"> xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels"
<ScrollView><VerticalStackLayout Padding="20" Spacing="18"> x:DataType="viewModels:QuickEntryViewModel"
<Label Text="Wie geht es dir?" FontSize="28" FontAttributes="Bold" HorizontalTextAlignment="Center" /> x:Class="cfs_tracker.Views.QuickEntryPage"
<Label Text="{Binding SelectedDateText}" FontSize="16" HorizontalTextAlignment="Center" /> Title="Eintrag"
<VerticalStackLayout IsVisible="{Binding IsPastDate}" Spacing="8"> BackgroundColor="{DynamicResource AppBackground}">
<Label Text="Tageszeit" FontAttributes="Bold" HorizontalTextAlignment="Center" />
<Picker Title="Tageszeit" ItemsSource="{Binding AvailableParts}" SelectedItem="{Binding SelectedPartText}" /> <ScrollView>
<VerticalStackLayout Padding="16" Spacing="16">
<Label Text="{Binding SelectedDateText}"
FontSize="20"
FontAttributes="Bold"
HorizontalTextAlignment="Center"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="{Binding ModeText}"
IsVisible="{Binding IsFutureDate}"
HorizontalTextAlignment="Center"
TextColor="IndianRed" />
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14"
IsVisible="{Binding IsPastDate}">
<VerticalStackLayout Spacing="8">
<Label Text="Nachtrag"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Picker Title="Tageszeit"
ItemsSource="{Binding Parts}"
ItemDisplayBinding="{Binding Name}"
SelectedItem="{Binding SelectedPart}" />
</VerticalStackLayout> </VerticalStackLayout>
<Border Padding="12"><VerticalStackLayout Spacing="8"><Label Text="Tätigkeit" FontAttributes="Bold" /><Picker Title="Tätigkeit" ItemsSource="{Binding Activities}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding SelectedActivity}" /></VerticalStackLayout></Border> </Border>
<Border Padding="12"><VerticalStackLayout Spacing="8"><Label Text="Symptome" FontAttributes="Bold" /><CollectionView ItemsSource="{Binding Symptoms}" SelectionMode="None"><CollectionView.ItemTemplate><DataTemplate><Grid ColumnDefinitions="Auto,*" Padding="0,4"><CheckBox IsChecked="{Binding IsSelected}" /><Label Grid.Column="1" Text="{Binding Name}" VerticalOptions="Center" /></Grid></DataTemplate></CollectionView.ItemTemplate></CollectionView></VerticalStackLayout></Border>
<Label IsVisible="{Binding IsFutureDate}" Text="Für zukünftige Tage können keine Einträge gesetzt werden." TextColor="{StaticResource StateRed}" HorizontalTextAlignment="Center" /> <Border Padding="12"
<Grid ColumnDefinitions="*,*" RowDefinitions="Auto,Auto" ColumnSpacing="12" RowSpacing="12"> Stroke="{DynamicResource Border}"
<Button Grid.Row="0" Grid.Column="0" Text="Grün&#10;Gut" FontSize="22" FontAttributes="Bold" HeightRequest="120" BackgroundColor="{StaticResource StateGreen}" TextColor="White" Command="{Binding SaveGreenCommand}" /> BackgroundColor="{DynamicResource SurfaceBackground}"
<Button Grid.Row="0" Grid.Column="1" Text="Gelb&#10;So lala" FontSize="22" FontAttributes="Bold" HeightRequest="120" BackgroundColor="{StaticResource StateYellow}" TextColor="Black" Command="{Binding SaveYellowCommand}" /> StrokeShape="RoundRectangle 14">
<Button Grid.Row="1" Grid.Column="0" Text="Rot&#10;Schlecht" FontSize="22" FontAttributes="Bold" HeightRequest="120" BackgroundColor="{StaticResource StateRed}" TextColor="White" Command="{Binding SaveRedCommand}" /> <VerticalStackLayout Spacing="8">
<Button Grid.Row="1" Grid.Column="1" Text="Grau&#10;Totalausfall" FontSize="22" FontAttributes="Bold" HeightRequest="120" BackgroundColor="{StaticResource StateGray}" TextColor="White" Command="{Binding SaveGrayCommand}" /> <Label Text="Tätigkeit"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Picker Title="Tätigkeit"
ItemsSource="{Binding Activities}"
ItemDisplayBinding="{Binding Name}"
SelectedItem="{Binding SelectedActivity}" />
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="8">
<Label Text="Symptome"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<VerticalStackLayout BindableLayout.ItemsSource="{Binding Symptoms}"
Spacing="6">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:SelectableSymptomItemViewModel">
<Grid ColumnDefinitions="Auto,*"
ColumnSpacing="10"
Padding="0,4">
<CheckBox IsChecked="{Binding IsSelected}" />
<Label Grid.Column="1"
Text="{Binding Name}"
VerticalOptions="Center"
TextColor="{DynamicResource TextPrimary}" />
</Grid> </Grid>
</VerticalStackLayout></ScrollView> </DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
</VerticalStackLayout>
</Border>
<Grid ColumnDefinitions="*,*"
RowDefinitions="Auto,Auto"
ColumnSpacing="12"
RowSpacing="12">
<Button Grid.Row="0"
Grid.Column="0"
Text="{Binding GreenStatusText}"
FontSize="22"
FontAttributes="Bold"
HeightRequest="110"
BackgroundColor="{Binding GreenStateColor}"
TextColor="White"
Command="{Binding SaveGreenCommand}"
IsEnabled="{Binding CanSave}" />
<Button Grid.Row="0"
Grid.Column="1"
Text="{Binding YellowStatusText}"
FontSize="22"
FontAttributes="Bold"
HeightRequest="110"
BackgroundColor="{Binding YellowStateColor}"
TextColor="Black"
Command="{Binding SaveYellowCommand}"
IsEnabled="{Binding CanSave}" />
<Button Grid.Row="1"
Grid.Column="0"
Text="{Binding RedStatusText}"
FontSize="22"
FontAttributes="Bold"
HeightRequest="110"
BackgroundColor="{Binding RedStateColor}"
TextColor="White"
Command="{Binding SaveRedCommand}"
IsEnabled="{Binding CanSave}" />
<Button Grid.Row="1"
Grid.Column="1"
Text="{Binding GrayStatusText}"
FontSize="22"
FontAttributes="Bold"
HeightRequest="110"
BackgroundColor="{Binding GrayStateColor}"
TextColor="White"
Command="{Binding SaveGrayCommand}"
IsEnabled="{Binding CanSave}" />
</Grid>
<Border Padding="12"
IsVisible="{Binding ShowSaveButton}"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="10">
<Label Text="{Binding SelectedStateSummaryText}"
HorizontalTextAlignment="Center"
TextColor="{DynamicResource TextPrimary}" />
<Button Text="Eintrag speichern"
Command="{Binding SaveCommand}"
IsEnabled="{Binding CanExplicitSave}"
Style="{StaticResource PrimaryButtonStyle}"
HorizontalOptions="Fill" />
</VerticalStackLayout>
</Border>
<Button Text="Abbrechen"
Command="{Binding CancelCommand}"
Style="{StaticResource SecondaryButtonStyle}"
HorizontalOptions="Fill" />
</VerticalStackLayout>
</ScrollView>
</ContentPage> </ContentPage>
+30 -4
View File
@@ -1,10 +1,36 @@
using Microsoft.Maui.Controls;
using cfs_tracker.ViewModels; using cfs_tracker.ViewModels;
namespace cfs_tracker.Views; namespace cfs_tracker.Views;
public partial class QuickEntryPage : ContentPage, IQueryAttributable public partial class QuickEntryPage : ContentPage, IQueryAttributable
{ {
private readonly QuickEntryViewModel _vm; private readonly QuickEntryViewModel _vm;
public QuickEntryPage(QuickEntryViewModel vm){ InitializeComponent(); BindingContext = _vm = vm; } private bool _initialized;
protected override async void OnAppearing(){ base.OnAppearing(); await _vm.LoadLookupsAsync(); }
public void ApplyQueryAttributes(IDictionary<string, object> query){ query.TryGetValue("date", out var value); _vm.SetDateFromQuery(value?.ToString()); } public QuickEntryPage(QuickEntryViewModel vm)
{
InitializeComponent();
BindingContext = _vm = vm;
}
protected override async void OnAppearing()
{
base.OnAppearing();
if (_initialized)
return;
_initialized = true;
await _vm.InitializeAsync();
}
public void ApplyQueryAttributes(IDictionary<string, object> query)
{
query.TryGetValue("date", out var dateValue);
query.TryGetValue("entryId", out var entryIdValue);
_vm.ApplyQuery(
dateValue?.ToString() ?? string.Empty,
entryIdValue?.ToString());
}
} }
+79 -104
View File
@@ -1,142 +1,117 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<ContentPage <ContentPage x:Class="cfs_tracker.Views.WeekPage"
x:Class="cfs_tracker.Views.WeekPage" x:Name="RootPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="ThisPage" xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels"
Title="Woche"> x:DataType="viewModels:WeekViewModel"
Title="Woche"
BackgroundColor="{DynamicResource AppBackground}">
<Grid RowDefinitions="Auto,*" Padding="16"> <ScrollView>
<VerticalStackLayout Padding="16" Spacing="16">
<Grid Grid.Row="0" ColumnDefinitions="Auto,*,Auto,Auto" Margin="0,0,0,12"> <Grid ColumnDefinitions="Auto,*,Auto"
<Button VerticalOptions="Center">
Grid.Column="0" <Button Text="←"
Text="◀" Style="{StaticResource PrimaryButtonStyle}"
WidthRequest="52"
HeightRequest="44"
Command="{Binding PreviousWeekCommand}" /> Command="{Binding PreviousWeekCommand}" />
<Label Grid.Column="1"
<Label Text="{Binding HeaderText}"
Grid.Column="1"
Text="{Binding WeekText}"
HorizontalTextAlignment="Center" HorizontalTextAlignment="Center"
VerticalTextAlignment="Center" VerticalTextAlignment="Center"
FontSize="22" FontSize="20"
FontAttributes="Bold" /> FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Button <Button Grid.Column="2"
Grid.Column="2" Text="→"
Text="Heute" Style="{StaticResource PrimaryButtonStyle}"
Margin="8,0,0,0"
Command="{Binding TodayCommand}" />
<Button
Grid.Column="3"
Text="▶"
WidthRequest="52"
HeightRequest="44"
Margin="8,0,0,0"
Command="{Binding NextWeekCommand}" /> Command="{Binding NextWeekCommand}" />
</Grid> </Grid>
<CollectionView <Grid ColumnDefinitions="*,*"
Grid.Row="1" ColumnSpacing="12">
ItemsSource="{Binding Days}" <Button Text="Heute"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding TodayCommand}" />
<Button Grid.Column="1"
Text="Export"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding ExportPdfCommand}" />
</Grid>
<CollectionView ItemsSource="{Binding Days}"
SelectionMode="None"> SelectionMode="None">
<CollectionView.ItemsLayout>
<LinearItemsLayout Orientation="Vertical" ItemSpacing="10" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate> <CollectionView.ItemTemplate>
<DataTemplate> <DataTemplate x:DataType="viewModels:WeekDaySummaryViewModel">
<Border <Border Margin="0,0,0,12"
Padding="12" Padding="12"
BackgroundColor="{DynamicResource PanelBackground}" Stroke="{DynamicResource Border}"
Stroke="{DynamicResource PanelBorder}" BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeThickness="1" StrokeShape="RoundRectangle 14">
StrokeShape="RoundRectangle 12"> <Border.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.OpenDayCommand}"
CommandParameter="{Binding .}" />
</Border.GestureRecognizers>
<VerticalStackLayout Spacing="10"> <VerticalStackLayout Spacing="10">
<Grid ColumnDefinitions="*"
<Grid ColumnDefinitions="*,Auto"> ColumnSpacing="10">
<VerticalStackLayout> <Label Text="{Binding DateText}"
<Label
Text="{Binding DayText}"
FontAttributes="Bold" FontAttributes="Bold"
FontSize="18" FontSize="18"
TextColor="{DynamicResource TextPrimary}" /> TextColor="{DynamicResource TextPrimary}" />
<Label
Text="{Binding DateText}"
FontSize="13"
TextColor="{DynamicResource TextMuted}" />
</VerticalStackLayout>
</Grid> </Grid>
<Grid ColumnDefinitions="*,*" ColumnSpacing="10"> <Grid ColumnDefinitions="*,*"
ColumnSpacing="12">
<Border <Border Padding="10"
Grid.Column="0"
BackgroundColor="{Binding MorningBackgroundColor}"
StrokeThickness="0" StrokeThickness="0"
StrokeShape="RoundRectangle 10" StrokeShape="RoundRectangle 10"
Padding="10"> BackgroundColor="{Binding MorningColor}">
<Border.GestureRecognizers> <VerticalStackLayout Spacing="4">
<TapGestureRecognizer <Label Text="Vormittag"
Command="{Binding Source={x:Reference ThisPage}, Path=BindingContext.OpenDayCommand}"
CommandParameter="{Binding .}" />
</Border.GestureRecognizers>
<VerticalStackLayout>
<Label
Text="Vormittag"
FontAttributes="Bold" FontAttributes="Bold"
TextColor="{Binding MorningTextColor}" /> TextColor="White" />
<Label <Label Text="{Binding MorningText}"
Text="{Binding MorningText}" TextColor="White" />
FontSize="18"
TextColor="{Binding MorningTextColor}" />
<Label
Text="{Binding MorningCountText}"
FontSize="12"
TextColor="{Binding MorningTextColor}" />
</VerticalStackLayout> </VerticalStackLayout>
</Border> </Border>
<Border <Border Grid.Column="1"
Grid.Column="1" Padding="10"
BackgroundColor="{Binding AfternoonBackgroundColor}"
StrokeThickness="0" StrokeThickness="0"
StrokeShape="RoundRectangle 10" StrokeShape="RoundRectangle 10"
Padding="10"> BackgroundColor="{Binding AfternoonColor}">
<Border.GestureRecognizers> <VerticalStackLayout Spacing="4">
<TapGestureRecognizer <Label Text="Nachmittag"
Command="{Binding Source={x:Reference ThisPage}, Path=BindingContext.OpenDayCommand}"
CommandParameter="{Binding .}" />
</Border.GestureRecognizers>
<VerticalStackLayout>
<Label
Text="Nachmittag"
FontAttributes="Bold" FontAttributes="Bold"
TextColor="{Binding AfternoonTextColor}" /> TextColor="White" />
<Label <Label Text="{Binding AfternoonText}"
Text="{Binding AfternoonText}" TextColor="White" />
FontSize="18"
TextColor="{Binding AfternoonTextColor}" />
<Label
Text="{Binding AfternoonCountText}"
FontSize="12"
TextColor="{Binding AfternoonTextColor}" />
</VerticalStackLayout> </VerticalStackLayout>
</Border> </Border>
</Grid> </Grid>
<Button Text="{Binding DetailsButtonText}"
IsVisible="{Binding HasDetails}"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding ToggleExpandedCommand}" />
<VerticalStackLayout IsVisible="{Binding IsExpanded}"
Spacing="6">
<Label Text="{Binding ActivitiesText, StringFormat='Tätigkeiten: {0}'}"
IsVisible="{Binding HasActivities}"
TextColor="{DynamicResource TextPrimary}" />
<Label Text="{Binding SymptomsText, StringFormat='Symptome: {0}'}"
IsVisible="{Binding HasSymptoms}"
TextColor="{DynamicResource TextPrimary}" />
</VerticalStackLayout>
</VerticalStackLayout> </VerticalStackLayout>
</Border> </Border>
</DataTemplate> </DataTemplate>
</CollectionView.ItemTemplate> </CollectionView.ItemTemplate>
</CollectionView> </CollectionView>
</VerticalStackLayout>
</Grid> </ScrollView>
</ContentPage> </ContentPage>
+15 -3
View File
@@ -1,8 +1,20 @@
using cfs_tracker.ViewModels; using cfs_tracker.ViewModels;
namespace cfs_tracker.Views; namespace cfs_tracker.Views;
public partial class WeekPage : ContentPage public partial class WeekPage : ContentPage
{ {
private readonly WeekViewModel _vm; private readonly WeekViewModel _viewModel;
public WeekPage(WeekViewModel vm){ InitializeComponent(); BindingContext = _vm = vm; }
protected override async void OnAppearing(){ base.OnAppearing(); await _vm.RefreshAsync(); } public WeekPage(WeekViewModel viewModel)
{
InitializeComponent();
BindingContext = _viewModel = viewModel;
}
protected override async void OnAppearing()
{
base.OnAppearing();
await _viewModel.RefreshAsync();
}
} }
+81 -94
View File
@@ -1,128 +1,115 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8" ?>
<ContentPage <ContentPage x:Class="cfs_tracker.Views.YearPage"
x:Class="cfs_tracker.Views.YearPage" x:Name="RootPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="ThisPage" xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels"
Title="Jahr"> x:DataType="viewModels:YearViewModel"
Title="Jahr"
BackgroundColor="{DynamicResource AppBackground}">
<Grid RowDefinitions="Auto,*" Padding="16"> <Grid Padding="16"
RowSpacing="16"
RowDefinitions="Auto,Auto,*">
<Grid Grid.Row="0" ColumnDefinitions="Auto,*,Auto,Auto" Margin="0,0,0,12"> <Grid ColumnDefinitions="Auto,*,Auto"
<Button VerticalOptions="Center">
Grid.Column="0" <Button Text="←"
Text="◀" Style="{StaticResource PrimaryButtonStyle}"
WidthRequest="52"
HeightRequest="44"
Command="{Binding PreviousYearCommand}" /> Command="{Binding PreviousYearCommand}" />
<Label Grid.Column="1"
<Label Text="{Binding HeaderText}"
Grid.Column="1"
Text="{Binding SelectedYearText}"
HorizontalTextAlignment="Center" HorizontalTextAlignment="Center"
VerticalTextAlignment="Center" VerticalTextAlignment="Center"
FontSize="24"
FontAttributes="Bold" />
<Button
Grid.Column="2"
Text="Heute"
Margin="8,0,0,0"
Command="{Binding TodayCommand}" />
<Button
Grid.Column="3"
Text="▶"
WidthRequest="52"
HeightRequest="44"
Margin="8,0,0,0"
Command="{Binding NextYearCommand}" />
</Grid>
<ScrollView Grid.Row="1">
<VerticalStackLayout
Spacing="12"
BindableLayout.ItemsSource="{Binding Months}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Border
Padding="12"
BackgroundColor="{DynamicResource PanelBackground}"
Stroke="{DynamicResource PanelBorder}"
StrokeThickness="1"
StrokeShape="RoundRectangle 12">
<VerticalStackLayout Spacing="10">
<Label
Text="{Binding MonthText}"
FontSize="20" FontSize="20"
FontAttributes="Bold" FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" /> TextColor="{DynamicResource TextPrimary}" />
<Button Grid.Column="2"
Text="→"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding NextYearCommand}" />
</Grid>
<HorizontalStackLayout Spacing="4"> <Grid Grid.Row="1"
<Label Text="Mo" WidthRequest="44" HorizontalTextAlignment="Center" FontSize="12" /> ColumnDefinitions="*,*"
<Label Text="Di" WidthRequest="44" HorizontalTextAlignment="Center" FontSize="12" /> ColumnSpacing="12">
<Label Text="Mi" WidthRequest="44" HorizontalTextAlignment="Center" FontSize="12" /> <Button Text="Heute"
<Label Text="Do" WidthRequest="44" HorizontalTextAlignment="Center" FontSize="12" /> Style="{StaticResource PrimaryButtonStyle}"
<Label Text="Fr" WidthRequest="44" HorizontalTextAlignment="Center" FontSize="12" /> Command="{Binding TodayCommand}" />
<Label Text="Sa" WidthRequest="44" HorizontalTextAlignment="Center" FontSize="12" /> <Button Grid.Column="1"
<Label Text="So" WidthRequest="44" HorizontalTextAlignment="Center" FontSize="12" /> Text="Export"
</HorizontalStackLayout> Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding ExportPdfCommand}" />
</Grid>
<FlexLayout <CollectionView Grid.Row="2"
Direction="Row" ItemsSource="{Binding Months}"
SelectionMode="None"
VerticalOptions="Fill"
HorizontalOptions="Fill"
ItemSizingStrategy="MeasureFirstItem">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="viewModels:MonthSectionViewModel">
<Border Padding="12"
Margin="0,0,0,12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="10">
<Label Text="{Binding Title}"
FontSize="18"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<FlexLayout Direction="Row"
Wrap="Wrap" Wrap="Wrap"
JustifyContent="Start"
AlignItems="Start" AlignItems="Start"
BindableLayout.ItemsSource="{Binding Days}"> JustifyContent="Start"
BindableLayout.ItemsSource="{Binding Cells}">
<BindableLayout.ItemTemplate> <BindableLayout.ItemTemplate>
<DataTemplate> <DataTemplate x:DataType="viewModels:MonthCellViewModel">
<Border <Border Margin="2"
WidthRequest="44" Padding="4"
HeightRequest="44" WidthRequest="46"
Margin="2" HeightRequest="46"
BackgroundColor="{Binding BackgroundColor}"
Stroke="{Binding BorderColor}" Stroke="{Binding BorderColor}"
StrokeThickness="1" BackgroundColor="{DynamicResource SurfaceBackgroundAlt}"
StrokeShape="RoundRectangle 8"> StrokeShape="RoundRectangle 8">
<Border.GestureRecognizers>
<Grid Padding="4">
<Grid.GestureRecognizers>
<TapGestureRecognizer <TapGestureRecognizer
Command="{Binding Source={x:Reference ThisPage}, Path=BindingContext.OpenDayCommand}" Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.OpenDayCommand}"
CommandParameter="{Binding .}" /> CommandParameter="{Binding .}" />
</Grid.GestureRecognizers> </Border.GestureRecognizers>
<VerticalStackLayout <Grid RowDefinitions="Auto,*">
IsVisible="{Binding IsRealDay}" <Label Text="{Binding DayNumberText}"
Spacing="1">
<Label
Text="{Binding DayNumberText}"
TextColor="{Binding TextColor}"
FontSize="11" FontSize="11"
FontAttributes="Bold" FontAttributes="Bold"
HorizontalTextAlignment="Center" /> HorizontalTextAlignment="Center"
<Label TextColor="{Binding TextColor}" />
Text="{Binding CountText}"
TextColor="{Binding TextColor}" <Border Grid.Row="1"
Margin="0,4,0,0"
Padding="2"
StrokeThickness="0"
StrokeShape="RoundRectangle 5"
BackgroundColor="{Binding StateColor}">
<Label Text="{Binding AverageStateText}"
FontSize="9" FontSize="9"
HorizontalTextAlignment="Center" /> LineBreakMode="TailTruncation"
</VerticalStackLayout> MaxLines="1"
HorizontalTextAlignment="Center"
TextColor="White" />
</Border>
</Grid> </Grid>
</Border> </Border>
</DataTemplate> </DataTemplate>
</BindableLayout.ItemTemplate> </BindableLayout.ItemTemplate>
</FlexLayout> </FlexLayout>
</VerticalStackLayout> </VerticalStackLayout>
</Border> </Border>
</DataTemplate> </DataTemplate>
</BindableLayout.ItemTemplate> </CollectionView.ItemTemplate>
</VerticalStackLayout> </CollectionView>
</ScrollView>
</Grid> </Grid>
</ContentPage> </ContentPage>
+26 -3
View File
@@ -1,8 +1,31 @@
using System.Diagnostics;
using cfs_tracker.ViewModels; using cfs_tracker.ViewModels;
namespace cfs_tracker.Views; namespace cfs_tracker.Views;
public partial class YearPage : ContentPage public partial class YearPage : ContentPage
{ {
private readonly YearViewModel _vm; private readonly YearViewModel _viewModel;
public YearPage(YearViewModel vm){ InitializeComponent(); BindingContext = _vm = vm; }
protected override async void OnAppearing(){ base.OnAppearing(); await _vm.RefreshAsync(); } public YearPage(YearViewModel viewModel)
{
InitializeComponent();
BindingContext = _viewModel = viewModel;
}
protected override async void OnAppearing()
{
base.OnAppearing();
try
{
await _viewModel.RefreshAsync();
}
catch (Exception ex)
{
Debug.WriteLine("YearPage crash:");
Debug.WriteLine(ex.ToString());
await DisplayAlertAsync("Fehler", ex.ToString(), "OK");
}
}
} }
+7
View File
@@ -20,6 +20,9 @@
<SupportedOSPlatformVersion>10.0.17763.0</SupportedOSPlatformVersion> <SupportedOSPlatformVersion>10.0.17763.0</SupportedOSPlatformVersion>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion> <TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup>
<MauiEnableXamlCBindingWithSourceCompilation>true</MauiEnableXamlCBindingWithSourceCompilation>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<MauiIcon Include="Resources\AppIcon\appicon.svg" Color="#0B1620" /> <MauiIcon Include="Resources\AppIcon\appicon.svg" Color="#0B1620" />
<MauiSplashScreen Include="Resources\Splash\splash.svg" Color="#0B1620" BaseSize="128,128" /> <MauiSplashScreen Include="Resources\Splash\splash.svg" Color="#0B1620" BaseSize="128,128" />
@@ -32,5 +35,9 @@
<PackageReference Include="Microsoft.Maui.Controls" Version="10.0.50" /> <PackageReference Include="Microsoft.Maui.Controls" Version="10.0.50" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="10.0.5" /> <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="10.0.5" />
<PackageReference Include="sqlite-net-pcl" Version="1.9.172" /> <PackageReference Include="sqlite-net-pcl" Version="1.9.172" />
<PackageReference Include="SQLitePCLRaw.bundle_green" Version="2.1.11" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="SQLitePCLRaw.lib.e_sqlite3.android" Version="2.1.11" />
</ItemGroup> </ItemGroup>
</Project> </Project>