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
+27 -37
View File
@@ -1,54 +1,44 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Application
x:Class="cfs_tracker.App"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="cfs_tracker.App">
<Application.Resources>
<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="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="StateGreen">#4E8B69</Color>
<Color x:Key="StateYellow">#B89A42</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="StatusYellowText">Gelb</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">
<Setter Property="BackgroundColor" Value="{DynamicResource AppBackground}" />
</Style>
<Color x:Key="ButtonPrimaryBackground">#355066</Color>
<Color x:Key="ButtonPrimaryText">#FFFFFF</Color>
<Color x:Key="ButtonSecondaryBackground">#355055</Color>
<Color x:Key="ButtonSecondaryText">#DCE7F3</Color>
<Style TargetType="Label">
<Setter Property="TextColor" Value="{DynamicResource TextPrimary}" />
</Style>
<Style TargetType="Button">
<Style x:Key="PrimaryButtonStyle" TargetType="Button">
<Setter Property="BackgroundColor" Value="{DynamicResource ButtonPrimaryBackground}" />
<Setter Property="TextColor" Value="{DynamicResource ButtonPrimaryText}" />
<Setter Property="CornerRadius" Value="12" />
<Setter Property="Padding" Value="12,10" />
<Setter Property="BackgroundColor" Value="{DynamicResource PanelBackground2}" />
<Setter Property="TextColor" Value="{DynamicResource TextPrimary}" />
<Setter Property="Padding" Value="14,10" />
</Style>
<Style TargetType="Border">
<Setter Property="BackgroundColor" Value="{DynamicResource PanelBackground}" />
<Setter Property="Stroke" Value="{DynamicResource PanelBorder}" />
<Setter Property="StrokeThickness" Value="1" />
<Setter Property="StrokeShape" Value="RoundRectangle 12" />
<Style x:Key="SecondaryButtonStyle" TargetType="Button">
<Setter Property="BackgroundColor" Value="{DynamicResource ButtonSecondaryBackground}" />
<Setter Property="TextColor" Value="{DynamicResource ButtonSecondaryText}" />
<Setter Property="CornerRadius" Value="12" />
<Setter Property="Padding" Value="14,10" />
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
</Application>
+111 -14
View File
@@ -1,34 +1,131 @@
using cfs_tracker.Services;
using System.Diagnostics;
namespace cfs_tracker;
public partial class App : Application
{
private readonly IServiceProvider _serviceProvider;
private readonly AppBootstrapService _bootstrapService;
public App(IServiceProvider serviceProvider)
private bool _startupTriggered;
public App(IServiceProvider serviceProvider, AppBootstrapService bootstrapService)
{
InitializeComponent();
_serviceProvider = serviceProvider;
_bootstrapService = bootstrapService;
UserAppTheme = AppTheme.Dark;
}
protected override Window CreateWindow(IActivationState? activationState)
{
var shell = _serviceProvider.GetRequiredService<AppShell>();
var appearanceService = _serviceProvider.GetRequiredService<AppearanceService>();
var window = new Window(CreateLoadingPage());
MainThread.BeginInvokeOnMainThread(async () =>
if (!_startupTriggered)
{
try
{
await appearanceService.InitializeAsync();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
});
_startupTriggered = true;
_ = InitializeAppAsync(window);
}
return new Window(shell);
return window;
}
private async Task InitializeAppAsync(Window window)
{
try
{
await _bootstrapService.InitializeAsync();
var shell = _serviceProvider.GetRequiredService<AppShell>();
await MainThread.InvokeOnMainThreadAsync(() =>
{
window.Page = shell;
});
}
catch (Exception ex)
{
Debug.WriteLine($"App bootstrap failed: {ex}");
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")
}
}
}
}
};
}
}
+25 -25
View File
@@ -1,37 +1,37 @@
<?xml version="1.0" encoding="UTF-8" ?>
<?xml version="1.0" encoding="utf-8" ?>
<Shell
x:Class="cfs_tracker.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
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"
Route="day"
ContentTemplate="{DataTemplate views:DayPage}" />
<ShellContent
Title="Tag"
Route="DayTab"
ContentTemplate="{DataTemplate views:DayPage}" />
<ShellContent Title="Woche"
Route="week"
ContentTemplate="{DataTemplate views:WeekPage}" />
<ShellContent
Title="Woche"
Route="WeekTab"
ContentTemplate="{DataTemplate views:WeekPage}" />
<ShellContent Title="Monat"
Route="month"
ContentTemplate="{DataTemplate views:MonthPage}" />
<ShellContent
Title="Monat"
Route="MonthTab"
ContentTemplate="{DataTemplate views:MonthPage}" />
<ShellContent
Title="Jahr"
Route="YearTab"
ContentTemplate="{DataTemplate views:YearPage}" />
<ShellContent
Title="Optionen"
Route="OptionsTab"
ContentTemplate="{DataTemplate views:OptionsPage}" />
<ShellContent Title="Jahr"
Route="year"
ContentTemplate="{DataTemplate views:YearPage}" />
<ShellContent Title="Optionen"
Route="options"
ContentTemplate="{DataTemplate views:OptionsPage}" />
</TabBar>
</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}";
}
}
+82 -57
View File
@@ -11,10 +11,41 @@ public class ActivityRepository
_database = database;
}
public async Task<List<ActivityItem>> GetAllAsync()
public async Task EnsureDefaultsAsync()
{
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>()
.OrderBy(x => x.SortOrder)
.ThenBy(x => x.Name)
@@ -24,7 +55,6 @@ public class ActivityRepository
public async Task<List<ActivityItem>> GetActiveAsync()
{
await _database.InitAsync();
return await _database.Connection.Table<ActivityItem>()
.Where(x => x.IsActive)
.OrderBy(x => x.SortOrder)
@@ -32,75 +62,61 @@ public class ActivityRepository
.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()
{
var all = await GetAllAsync();
return all.ToDictionary(x => x.Id, x => x.Name);
var items = await GetAllAsync();
return items.ToDictionary(x => x.Id, x => x.Name);
}
public async Task EnsureDefaultsAsync()
public async Task<int> AddAsync(string name)
{
await _database.InitAsync();
var cleanName = NormalizeName(name);
if ((await _database.Connection.Table<ActivityItem>().CountAsync()) > 0)
return;
var existing = await _database.Connection.Table<ActivityItem>().ToListAsync();
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 },
new() { Name = "Sport", SortOrder = 1, IsActive = true },
new() { Name = "Haushalt", SortOrder = 2, 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 }
Name = cleanName,
SortOrder = nextSort,
IsActive = true
};
foreach (var item in defaults)
await _database.Connection.InsertAsync(item);
}
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
});
await _database.Connection.InsertAsync(item);
return item.Id;
}
public async Task RenameAsync(int id, string newName)
{
await _database.InitAsync();
var cleanName = NormalizeName(newName);
var item = await _database.Connection.Table<ActivityItem>()
.FirstOrDefaultAsync(x => x.Id == id);
var all = await _database.Connection.Table<ActivityItem>().ToListAsync();
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)
return;
item.Name = newName.Trim();
item.Name = cleanName;
await _database.Connection.UpdateAsync(item);
}
public async Task SetActiveAsync(int id, bool isActive)
{
await _database.InitAsync();
var item = await _database.Connection.Table<ActivityItem>()
.FirstOrDefaultAsync(x => x.Id == id);
var item = await GetByIdAsync(id);
if (item is null)
return;
@@ -111,25 +127,34 @@ public class ActivityRepository
public async Task<bool> HasUsageAsync(int activityId)
{
await _database.InitAsync();
var count = await _database.Connection.Table<HealthEntry>()
return await _database.Connection.Table<HealthEntry>()
.Where(x => x.ActivityId == activityId)
.CountAsync();
return count > 0;
.CountAsync() > 0;
}
public async Task DeleteIfUnusedAsync(int activityId)
public async Task DeleteOrDeactivateAsync(int activityId)
{
await _database.InitAsync();
if (await HasUsageAsync(activityId))
var item = await GetByIdAsync(activityId);
if (item is null)
return;
var item = await _database.Connection.Table<ActivityItem>()
.FirstOrDefaultAsync(x => x.Id == activityId);
if (await HasUsageAsync(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;
}
}
+60 -16
View File
@@ -1,30 +1,74 @@
using SQLite;
using cfs_tracker.Models;
using Microsoft.Maui.Storage;
using cfs_tracker.Services;
using SQLite;
using System.Threading;
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;
public AppDatabase(DatabaseLocationService databaseLocationService)
{
_databaseLocationService = databaseLocationService;
}
public async Task InitAsync()
{
if (_initialized) return;
if (_initialized)
return;
var dbPath = Path.Combine(FileSystem.Current.AppDataDirectory, "cfs_tracker.db3");
_database = new SQLiteAsyncConnection(dbPath);
await _initLock.WaitAsync();
try
{
if (_initialized)
return;
await _database.CreateTableAsync<ActivityItem>();
await _database.CreateTableAsync<SymptomItem>();
await _database.CreateTableAsync<HealthEntry>();
await _database.CreateTableAsync<HealthEntrySymptom>();
await _database.CreateTableAsync<ThemeSettingItem>();
await _database.CreateTableAsync<AppearanceSetting>();
var dbPath = _databaseLocationService.ResolveDatabasePath();
var directory = Path.GetDirectoryName(dbPath);
_initialized = true;
if (!string.IsNullOrWhiteSpace(directory))
Directory.CreateDirectory(directory);
_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;
}
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.");
}
+69 -66
View File
@@ -1,3 +1,4 @@
using cfs_tracker.Helpers;
using cfs_tracker.Models;
namespace cfs_tracker.Data;
@@ -11,6 +12,27 @@ public class AppearanceRepository
_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()
{
await _database.InitAsync();
@@ -20,90 +42,71 @@ public class AppearanceRepository
.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();
return await _database.Connection.Table<AppearanceSetting>()
.FirstOrDefaultAsync(x => x.Key == key);
var cleanKey = NormalizeKey(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)
{
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>()
.FirstOrDefaultAsync(x => x.Key == key);
.FirstOrDefaultAsync(x => x.Key == cleanKey);
if (existing is null)
if (existing is not null)
return;
await _database.Connection.InsertAsync(new AppearanceSetting
{
await _database.Connection.InsertAsync(new AppearanceSetting
{
Key = key,
Value = value
});
}
else
{
existing.Value = value;
await _database.Connection.UpdateAsync(existing);
}
Key = cleanKey,
Value = cleanValue
});
}
public async Task EnsureDefaultsAsync()
private static string NormalizeKey(string key)
{
await _database.InitAsync();
var cleanKey = (key ?? 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");
if (string.IsNullOrWhiteSpace(cleanKey))
throw new ArgumentException("Appearance key must not be empty.", nameof(key));
await EnsureDefaultAsync("StatusGreenText", "Grün");
await EnsureDefaultAsync("StatusYellowText", "Gelb");
await EnsureDefaultAsync("StatusRedText", "Rot");
await EnsureDefaultAsync("StatusGrayText", "Grau");
return cleanKey;
}
public async Task ResetToDefaultsAsync()
private static string NormalizeValue(string value)
{
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
});
}
return (value ?? string.Empty).Trim();
}
}
+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;
}
+112 -39
View File
@@ -5,101 +5,171 @@ namespace cfs_tracker.Data;
public class HealthEntryRepository
{
private readonly AppDatabase _database;
private readonly SymptomRepository _symptomRepository;
public HealthEntryRepository(AppDatabase database) => _database = database;
public async Task AddEntryAsync(HealthState state, EntrySource source, DateTime? timestamp = null, int? activityId = null)
public HealthEntryRepository(AppDatabase database, SymptomRepository symptomRepository)
{
await _database.InitAsync();
var entry = new HealthEntry
{
Timestamp = timestamp ?? DateTime.Now,
State = state,
Source = source,
ActivityId = activityId,
UpdatedAt = DateTime.Now
};
await _database.Connection.InsertAsync(entry);
_database = database;
_symptomRepository = symptomRepository;
}
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();
var effectiveTimestamp = timestamp ?? DateTime.Now;
var entry = new HealthEntry
{
Timestamp = timestamp ?? DateTime.Now,
EntryDate = effectiveTimestamp.Date,
Timestamp = effectiveTimestamp,
State = state,
Source = source,
ActivityId = activityId,
DayPart = null,
ActivityId = NormalizeActivityId(activityId),
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now
};
await _database.Connection.InsertAsync(entry);
await _symptomRepository.SetSymptomsForEntryAsync(entry.Id, symptomIds);
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();
var slotTimestamp = BuildSlotTimestamp(date, part);
var slotTimestamp = BuildBackfillTimestamp(date, part);
var existing = await _database.Connection.Table<HealthEntry>()
.FirstOrDefaultAsync(x => x.Timestamp == slotTimestamp);
if (existing is null)
{
await _database.Connection.InsertAsync(new HealthEntry
var entry = new HealthEntry
{
EntryDate = date.Date,
Timestamp = slotTimestamp,
State = state,
Source = source,
ActivityId = activityId,
DayPart = part,
ActivityId = NormalizeActivityId(activityId),
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now
});
}
else
{
existing.State = state;
existing.Source = source;
existing.ActivityId = activityId;
existing.UpdatedAt = DateTime.Now;
await _database.Connection.UpdateAsync(existing);
};
await _database.Connection.InsertAsync(entry);
await _symptomRepository.SetSymptomsForEntryAsync(entry.Id, symptomIds);
return entry.Id;
}
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<HealthEntry?> GetBackfillEntryAsync(DateTime date, DayPart part)
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();
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>()
.FirstOrDefaultAsync(x => x.Timestamp == slotTimestamp);
.FirstOrDefaultAsync(x => x.Id == id);
}
public async Task<List<HealthEntry>> GetEntriesForDateAsync(DateTime date)
{
await _database.InitAsync();
var start = date.Date;
var end = start.AddDays(1);
var list = await _database.Connection.Table<HealthEntry>()
.Where(x => x.Timestamp >= start && x.Timestamp < end)
.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();
var start = startDate.Date;
var end = endDate.Date;
var start = startDateInclusive.Date;
var end = endDateExclusive.Date;
var list = await _database.Connection.Table<HealthEntry>()
.Where(x => x.Timestamp >= start && x.Timestamp < end)
.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)
{
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)
await _database.Connection.DeleteAsync(item);
}
@@ -111,10 +181,13 @@ public class HealthEntryRepository
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.Afternoon => date.Date.AddHours(15),
_ => 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
});
}
}
}
+108 -67
View File
@@ -1,4 +1,5 @@
using cfs_tracker.Models;
using System.Linq;
namespace cfs_tracker.Data;
@@ -11,10 +12,41 @@ public class SymptomRepository
_database = database;
}
public async Task<List<SymptomItem>> GetAllAsync()
public async Task EnsureDefaultsAsync()
{
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>()
.OrderBy(x => x.SortOrder)
.ThenBy(x => x.Name)
@@ -24,7 +56,6 @@ public class SymptomRepository
public async Task<List<SymptomItem>> GetActiveAsync()
{
await _database.InitAsync();
return await _database.Connection.Table<SymptomItem>()
.Where(x => x.IsActive)
.OrderBy(x => x.SortOrder)
@@ -32,64 +63,61 @@ public class SymptomRepository
.ToListAsync();
}
public async Task EnsureDefaultsAsync()
public async Task<SymptomItem?> GetByIdAsync(int id)
{
await _database.InitAsync();
if ((await _database.Connection.Table<SymptomItem>().CountAsync()) > 0)
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);
return await _database.Connection.Table<SymptomItem>()
.FirstOrDefaultAsync(x => x.Id == id);
}
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();
var cleanName = NormalizeName(name);
var maxSort = 0;
var all = await _database.Connection.Table<SymptomItem>().ToListAsync();
if (all.Count > 0)
maxSort = all.Max(x => x.SortOrder) + 1;
var existing = await _database.Connection.Table<SymptomItem>().ToListAsync();
if (existing.Any(x => string.Equals(x.Name, cleanName, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"Das Symptom '{cleanName}' existiert bereits.");
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(),
SortOrder = maxSort,
Name = cleanName,
SortOrder = nextSort,
IsActive = true
});
};
await _database.Connection.InsertAsync(item);
return item.Id;
}
public async Task RenameAsync(int id, string newName)
{
await _database.InitAsync();
var cleanName = NormalizeName(newName);
var item = await _database.Connection.Table<SymptomItem>()
.FirstOrDefaultAsync(x => x.Id == id);
var all = await _database.Connection.Table<SymptomItem>().ToListAsync();
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)
return;
item.Name = newName.Trim();
item.Name = cleanName;
await _database.Connection.UpdateAsync(item);
}
public async Task SetActiveAsync(int id, bool isActive)
{
await _database.InitAsync();
var item = await _database.Connection.Table<SymptomItem>()
.FirstOrDefaultAsync(x => x.Id == id);
var item = await GetByIdAsync(id);
if (item is null)
return;
@@ -100,40 +128,29 @@ public class SymptomRepository
public async Task<bool> HasUsageAsync(int symptomId)
{
await _database.InitAsync();
var count = await _database.Connection.Table<HealthEntrySymptom>()
return await _database.Connection.Table<HealthEntrySymptom>()
.Where(x => x.SymptomItemId == symptomId)
.CountAsync();
return count > 0;
.CountAsync() > 0;
}
public async Task DeleteIfUnusedAsync(int symptomId)
public async Task DeleteOrDeactivateAsync(int symptomId)
{
await _database.InitAsync();
if (await HasUsageAsync(symptomId))
var item = await GetByIdAsync(symptomId);
if (item is null)
return;
var item = await _database.Connection.Table<SymptomItem>()
.FirstOrDefaultAsync(x => x.Id == symptomId);
if (await HasUsageAsync(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)
{
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)
public async Task SetSymptomsForEntryAsync(int entryId, IEnumerable<int>? symptomIds)
{
await _database.InitAsync();
@@ -144,7 +161,12 @@ public class SymptomRepository
foreach (var item in existing)
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
{
@@ -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)
{
await _database.InitAsync();
var ids = entryIds.Distinct().ToHashSet();
var result = new Dictionary<int, List<string>>();
var idSet = entryIds.Distinct().ToHashSet();
if (ids.Count == 0)
if (idSet.Count == 0)
return result;
var allLinks = await _database.Connection.Table<HealthEntrySymptom>().ToListAsync();
var relevantLinks = allLinks.Where(x => ids.Contains(x.HealthEntryId)).ToList();
var links = await _database.Connection.Table<HealthEntrySymptom>().ToListAsync();
var relevantLinks = links.Where(x => idSet.Contains(x.HealthEntryId)).ToList();
if (relevantLinks.Count == 0)
return result;
var allSymptoms = await _database.Connection.Table<SymptomItem>().ToListAsync();
var symptomMap = allSymptoms.ToDictionary(x => x.Id, x => x.Name);
var symptoms = await _database.Connection.Table<SymptomItem>().ToListAsync();
var symptomMap = symptoms.ToDictionary(x => x.Id, x => x.Name);
foreach (var group in relevantLinks.GroupBy(x => x.HealthEntryId))
{
@@ -185,4 +217,13 @@ public class SymptomRepository
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;
}
}
+45 -29
View File
@@ -3,6 +3,8 @@ using cfs_tracker.Services;
using cfs_tracker.ViewModels;
using cfs_tracker.Views;
using Microsoft.Extensions.Logging;
using SQLitePCL;
using System.Text;
namespace cfs_tracker;
@@ -10,42 +12,56 @@ public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Batteries_V2.Init();
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureFonts(fonts => { });
builder.Services.AddSingleton<AppDatabase>();
builder.Services.AddSingleton<HealthEntryRepository>();
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>();
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});
#if DEBUG
builder.Logging.AddDebug();
#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();
}
}
}
+11 -3
View File
@@ -1,9 +1,17 @@
using SQLite;
namespace cfs_tracker.Models;
[Table("Activities")]
public class ActivityItem
{
[PrimaryKey, AutoIncrement] public int Id { get; set; }
[Unique] public string Name { get; set; } = string.Empty;
public bool IsActive { get; set; } = true;
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(120), Unique]
public string Name { get; set; } = string.Empty;
public int SortOrder { get; set; }
public bool IsActive { get; set; } = true;
}
+7 -3
View File
@@ -1,11 +1,15 @@
using SQLite;
using SQLite;
namespace cfs_tracker.Models;
[Table("AppearanceSettings")]
public class AppearanceSetting
{
[PrimaryKey]
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(80), Unique]
public string Key { 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;
namespace cfs_tracker.Models;
[Table("HealthEntries")]
public class HealthEntry
{
[PrimaryKey, AutoIncrement] public int Id { get; set; }
[Indexed] public DateTime Timestamp { get; set; }
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[Indexed]
public DateTime EntryDate { get; set; }
[Indexed]
public DateTime Timestamp { get; set; }
[Indexed]
public HealthState State { get; set; }
[Indexed]
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; }
[Ignore]
public DayPart? DayPart
{
get => DayPartValue.HasValue ? (DayPart)DayPartValue.Value : null;
set => DayPartValue = value.HasValue ? (int)value.Value : null;
}
}
+12 -4
View File
@@ -1,8 +1,16 @@
using SQLite;
namespace cfs_tracker.Models;
[Table("HealthEntrySymptom")]
public class HealthEntrySymptom
{
[PrimaryKey, AutoIncrement] public int Id { get; set; }
[Indexed] public int HealthEntryId { get; set; }
[Indexed] public int SymptomItemId { get; set; }
}
[PrimaryKey, AutoIncrement]
public int Id { 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;
namespace cfs_tracker.Models;
[Table("Symptoms")]
public class SymptomItem
{
[PrimaryKey, AutoIncrement] public int Id { get; set; }
[Unique] public string Name { get; set; } = string.Empty;
public bool IsActive { get; set; } = true;
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(120), Unique]
public string Name { get; set; } = string.Empty;
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; }
}
+17 -17
View File
@@ -1,25 +1,25 @@
using Microsoft.UI.Xaml;
using System.Diagnostics;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
namespace cfs_tracker.WinUI;
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
public App()
{
/// <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()
{
this.InitializeComponent();
}
this.InitializeComponent();
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
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();
}
+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`.
+63 -51
View File
@@ -1,74 +1,86 @@
using cfs_tracker.Helpers;
using cfs_tracker.Models;
namespace cfs_tracker.Services;
public class AggregationService
{
public List<WeekDaySummary> BuildWeekSummary(DateTime weekStart, IEnumerable<HealthEntry> entries)
public AverageStateResult CalculateAverage(IEnumerable<HealthEntry> entries)
{
var result = new List<WeekDaySummary>();
for (int i = 0; i < 7; i++)
var list = entries?.ToList() ?? new List<HealthEntry>();
if (list.Count == 0)
{
var date = weekStart.Date.AddDays(i);
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
return new AverageStateResult
{
Date = date,
MorningAverage = AverageOrNull(morning),
AfternoonAverage = AverageOrNull(afternoon),
MorningCount = morning.Count,
AfternoonCount = afternoon.Count
});
HasValue = false,
AverageScore = 0,
State = HealthState.Gray
};
}
return result;
}
public List<CalendarDaySummary> BuildMonthSummary(DateTime month, IEnumerable<HealthEntry> entries)
{
var first = new DateTime(month.Year, month.Month, 1);
int days = DateTime.DaysInMonth(month.Year, month.Month);
var result = new List<CalendarDaySummary>();
for (int i = 0; i < days; i++)
{
var date = first.AddDays(i);
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;
}
var average = list.Average(x => x.State.ToScore());
public List<CalendarDaySummary> BuildYearSummary(int year, IEnumerable<HealthEntry> entries)
{
var result = new List<CalendarDaySummary>();
for (int month = 1; month <= 12; month++)
return new AverageStateResult
{
int days = DateTime.DaysInMonth(year, month);
for (int day = 1; day <= days; day++)
HasValue = true,
AverageScore = average,
State = average switch
{
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) });
>= 2.5 => HealthState.Green,
>= 1.5 => HealthState.Yellow,
>= 0.5 => HealthState.Red,
_ => HealthState.Gray
}
}
return result;
};
}
public HealthState? ToDisplayState(double? average)
public IEnumerable<HealthEntry> FilterForDayPart(IEnumerable<HealthEntry> entries, DayPart part)
{
if (average is null) return null;
if (average >= 2.5) return HealthState.Green;
if (average >= 1.5) return HealthState.Yellow;
if (average >= 0.5) return HealthState.Red;
return HealthState.Gray;
return entries.Where(x =>
{
if (x.DayPart.HasValue)
return x.DayPart == part;
return part == DayPart.Morning
? x.Timestamp.Hour < 12
: x.Timestamp.Hour >= 12;
});
}
private static double? AverageOrNull(IEnumerable<HealthEntry> entries)
public string BuildDistinctActivityText(IEnumerable<HealthEntry> entries, IReadOnlyDictionary<int, string> activityMap)
{
var list = entries.ToList();
return list.Count == 0 ? null : list.Average(x => (int)x.State);
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 string BuildDistinctSymptomText(IEnumerable<HealthEntry> entries, IReadOnlyDictionary<int, List<string>> symptomsByEntryId)
{
var names = entries
.Where(x => symptomsByEntryId.ContainsKey(x.Id))
.SelectMany(x => symptomsByEntryId[x.Id])
.Distinct()
.OrderBy(x => x)
.ToList();
return names.Count == 0 ? string.Empty : string.Join(", ", names);
}
public string ToDisplayText(AverageStateResult averageResult, AppearanceService appearanceService)
{
if (!averageResult.HasValue)
return "-";
return appearanceService.GetText(
averageResult.State.ToAppearanceTextKey(),
averageResult.State.ToFallbackText());
}
}
+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;
}
}
+110 -28
View File
@@ -7,55 +7,137 @@ namespace cfs_tracker.Services;
public class AppearanceService
{
private readonly AppearanceRepository _repository;
private readonly AppearanceRepository _appearanceRepository;
public event Action? AppearanceChanged;
public AppearanceService(AppearanceRepository repository)
public AppearanceService(AppearanceRepository appearanceRepository)
{
_repository = repository;
}
public async Task InitializeAsync()
{
await _repository.EnsureDefaultsAsync();
await ApplyAsync();
_appearanceRepository = appearanceRepository;
}
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;
foreach (var pair in AppearanceDefaults.All)
{
if (item.Key.StartsWith("Status", StringComparison.Ordinal))
{
Application.Current!.Resources[item.Key] = item.Value;
}
else
{
Application.Current!.Resources[item.Key] = Color.FromArgb(item.Value);
}
}
var key = pair.Key;
var fallback = pair.Value;
var value = map.TryGetValue(key, out var stored) && !string.IsNullOrWhiteSpace(stored)
? stored
: fallback;
AppearanceChanged?.Invoke();
ApplyValue(resources, key, value, fallback);
}
}
public async Task SaveColorAsync(string key, string value)
{
await _repository.UpsertAsync(key, value);
await ApplyAsync();
var fallback = AppearanceDefaults.All.TryGetValue(key, out var defaultValue)
? 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)
{
await _repository.UpsertAsync(key, value);
await ApplyAsync();
var fallback = AppearanceDefaults.All.TryGetValue(key, out var defaultValue)
? 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()
{
await _repository.ResetToDefaultsAsync();
await _appearanceRepository.ResetAsync();
await _appearanceRepository.EnsureDefaultsAsync();
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
};
}
+10 -18
View File
@@ -4,29 +4,21 @@ public class CalendarStateService
{
private DateTime _selectedDate = DateTime.Today;
public event Action<DateTime>? SelectedDateChanged;
public DateTime SelectedDate
{
get => _selectedDate;
set
{
var newValue = value.Date;
if (_selectedDate != newValue)
{
_selectedDate = newValue;
SelectedDateChanged?.Invoke(_selectedDate);
}
var normalized = value.Date;
if (_selectedDate == normalized)
return;
_selectedDate = normalized;
SelectedDateChanged?.Invoke(_selectedDate);
}
}
public event Action<DateTime>? SelectedDateChanged;
public async Task ShowDayTabAsync(DateTime date)
{
SelectedDate = date.Date;
if (Shell.Current is null)
return;
await Shell.Current.GoToAsync("//MainTabs/DayTab");
}
}
public void ResetToToday() => SelectedDate = DateTime.Today;
}
+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;
}
+14 -5
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;
public partial class AppearanceColorItemViewModel : ObservableObject
{
public string Key { get; init; } = string.Empty;
[ObservableProperty]
private string title = string.Empty;
public string Title { get; init; } = string.Empty;
public string Fallback { get; init; } = "#000000";
[ObservableProperty]
private string value = string.Empty;
}
[ObservableProperty]
private Color previewColor = Colors.Transparent;
partial void OnValueChanged(string value)
{
PreviewColor = ColorUtility.ParseColor(value, Fallback);
}
}
+3 -5
View File
@@ -1,14 +1,12 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.ComponentModel;
namespace cfs_tracker.ViewModels;
public partial class AppearanceTextItemViewModel : ObservableObject
{
public string Key { get; init; } = string.Empty;
[ObservableProperty]
private string title = string.Empty;
public string Title { get; init; } = string.Empty;
[ObservableProperty]
private string value = string.Empty;
}
}
+12 -10
View File
@@ -7,21 +7,19 @@ namespace cfs_tracker.ViewModels;
public partial class DayEntryItemViewModel : ObservableObject
{
public int Id { get; init; }
public string TimeText { get; init; } = string.Empty;
public DateTime Date { get; init; }
public string SlotText { get; init; } = string.Empty;
public string StateText { get; init; } = string.Empty;
public string ActivityText { 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 HasSymptoms => !string.IsNullOrWhiteSpace(SymptomsText);
public bool HasDetails => HasActivity || HasSymptoms;
public string FoldoutText => IsExpanded ? "Details ausblenden" : "Details anzeigen";
public Color BackgroundColor { get; init; } = Colors.Transparent;
public Color TextColor { get; init; } = Colors.White;
public string DetailsButtonText => IsExpanded ? "Details ausblenden" : "Details anzeigen";
[ObservableProperty]
private bool isExpanded;
@@ -33,12 +31,16 @@ public partial class DayEntryItemViewModel : ObservableObject
ToggleExpandedCommand = new RelayCommand(ToggleExpanded);
}
partial void OnIsExpandedChanged(bool value)
{
OnPropertyChanged(nameof(DetailsButtonText));
}
private void ToggleExpanded()
{
if (!HasDetails)
return;
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;
}
+223 -83
View File
@@ -1,28 +1,40 @@
using System.Collections.ObjectModel;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Models;
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;
public partial class DayViewModel : ObservableObject
{
private readonly HealthEntryRepository _repository;
private readonly HealthEntryRepository _healthEntryRepository;
private readonly ActivityRepository _activityRepository;
private readonly SymptomRepository _symptomRepository;
private readonly CalendarStateService _calendarState;
private readonly AppearanceService _appearanceService;
private readonly CalendarStateService _calendarStateService;
private readonly IPdfExportService _pdfExportService;
[ObservableProperty]
private DateTime selectedDate = DateTime.Today;
private DateTime selectedDate;
[ObservableProperty]
private string selectedDateText = string.Empty;
[ObservableProperty]
private bool isToday;
[ObservableProperty]
private bool isPastDate;
[ObservableProperty]
private bool isFutureDate;
[ObservableProperty]
private int greenCount;
@@ -36,76 +48,129 @@ public partial class DayViewModel : ObservableObject
private int grayCount;
[ObservableProperty]
private string greenStatusText = ThemeResourceHelper.GetString(ThemeKeys.StatusGreenText, "Grün");
private string greenStatusText = "Grün";
[ObservableProperty]
private string yellowStatusText = ThemeResourceHelper.GetString(ThemeKeys.StatusYellowText, "Gelb");
private string yellowStatusText = "Gelb";
[ObservableProperty]
private string redStatusText = ThemeResourceHelper.GetString(ThemeKeys.StatusRedText, "Rot");
private string redStatusText = "Rot";
[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 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 NextDayCommand { get; }
public IAsyncRelayCommand TodayCommand { get; }
public IAsyncRelayCommand AddEntryCommand { get; }
public IAsyncRelayCommand<DayEntryItemViewModel> DeleteEntryCommand { get; }
public IAsyncRelayCommand SaveGreenQuickCommand { get; }
public IAsyncRelayCommand SaveYellowQuickCommand { get; }
public IAsyncRelayCommand SaveRedQuickCommand { get; }
public IAsyncRelayCommand SaveGrayQuickCommand { get; }
public IAsyncRelayCommand<DayEntryItemViewModel> EditEntryCommand { get; }
public IAsyncRelayCommand<DayEntryItemViewModel> DeleteEntryCommand { get; }
public IAsyncRelayCommand ExportPdfCommand { get; }
public DayViewModel(
HealthEntryRepository repository,
HealthEntryRepository healthEntryRepository,
ActivityRepository activityRepository,
SymptomRepository symptomRepository,
CalendarStateService calendarState)
AppearanceService appearanceService,
CalendarStateService calendarStateService,
IPdfExportService pdfExportService)
{
_repository = repository;
_healthEntryRepository = healthEntryRepository;
_activityRepository = activityRepository;
_symptomRepository = symptomRepository;
_calendarState = calendarState;
_appearanceService = appearanceService;
_calendarStateService = calendarStateService;
_pdfExportService = pdfExportService;
SelectedDate = _calendarState.SelectedDate;
_calendarState.SelectedDateChanged += OnSharedSelectedDateChanged;
SelectedDate = _calendarStateService.SelectedDate;
UpdateDateState();
UpdateSelectedDateText();
PreviousDayCommand = new AsyncRelayCommand(PreviousDayAsync);
NextDayCommand = new AsyncRelayCommand(NextDayAsync);
TodayCommand = new AsyncRelayCommand(SetTodayAsync);
AddEntryCommand = new AsyncRelayCommand(OpenQuickEntryAsync);
DeleteEntryCommand = new AsyncRelayCommand<DayEntryItemViewModel>(DeleteEntryAsync);
TodayCommand = new AsyncRelayCommand(TodayAsync);
AddEntryCommand = new AsyncRelayCommand(AddEntryAsync);
SaveGreenQuickCommand = new AsyncRelayCommand(() => QuickSaveAsync(HealthState.Green));
SaveYellowQuickCommand = new AsyncRelayCommand(() => QuickSaveAsync(HealthState.Yellow));
SaveRedQuickCommand = new AsyncRelayCommand(() => QuickSaveAsync(HealthState.Red));
SaveGrayQuickCommand = new AsyncRelayCommand(() => QuickSaveAsync(HealthState.Gray));
EditEntryCommand = new AsyncRelayCommand<DayEntryItemViewModel>(EditEntryAsync);
DeleteEntryCommand = new AsyncRelayCommand<DayEntryItemViewModel>(DeleteEntryAsync);
ExportPdfCommand = new AsyncRelayCommand(ExportAsync);
UpdateDateText();
RefreshStatusTexts();
_calendarStateService.SelectedDateChanged += HandleSharedDateChanged;
Entries.CollectionChanged += (_, _) =>
{
HasEntries = Entries.Count > 0;
OnPropertyChanged(nameof(HasNoEntries));
};
}
partial void OnSelectedDateChanged(DateTime value)
{
UpdateDateText();
UpdateDateState();
UpdateSelectedDateText();
}
private async void OnSharedSelectedDateChanged(DateTime date)
{
SelectedDate = date;
await RefreshAsync();
}
partial void OnGreenCountChanged(int value) => RaiseCounterTextChanged();
partial void OnYellowCountChanged(int value) => RaiseCounterTextChanged();
partial void OnRedCountChanged(int value) => RaiseCounterTextChanged();
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()
{
SelectedDate = _calendarState.SelectedDate;
RefreshStatusTexts();
SelectedDate = _calendarStateService.SelectedDate;
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);
YellowCount = entries.Count(x => x.State == HealthState.Yellow);
@@ -114,76 +179,81 @@ public partial class DayViewModel : ObservableObject
Entries.Clear();
var activityMap = await _activityRepository.GetNameMapAsync();
var symptomMapByEntry = await _symptomRepository.GetSymptomsByEntryIdsAsync(entries.Select(x => x.Id));
foreach (var entry in entries.OrderBy(x => x.Timestamp))
foreach (var entry in entries.OrderBy(x => x.Timestamp).ThenBy(x => x.Id))
{
string activityText = string.Empty;
if (entry.ActivityId.HasValue && activityMap.TryGetValue(entry.ActivityId.Value, out var activityName))
activityText = activityName;
var slotText = entry.DayPart switch
{
DayPart.Morning => "Vormittag",
DayPart.Afternoon => "Nachmittag",
_ => entry.Timestamp.ToString("HH:mm", CultureInfo.InvariantCulture)
};
symptomMapByEntry.TryGetValue(entry.Id, out var symptoms);
string symptomsText = symptoms is { Count: > 0 }
var activityText = string.Empty;
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.Empty;
Entries.Add(new DayEntryItemViewModel
{
Id = entry.Id,
TimeText = entry.Timestamp.ToString("HH:mm"),
StateText = ThemeResourceHelper.GetString(
entry.State.ToTextKey(),
Date = entry.EntryDate,
SlotText = slotText,
StateText = _appearanceService.GetText(
entry.State.ToAppearanceTextKey(),
entry.State.ToFallbackText()),
ActivityText = activityText,
SymptomsText = symptomsText,
BackgroundColor = ThemeResourceHelper.GetColor(entry.State.ToColorKey(), "#203041"),
TextColor = ThemeResourceHelper.GetColor(ThemeKeys.TextPrimary, "#D9E6F2")
SymptomsText = symptomText,
IsBackfill = entry.DayPart.HasValue,
StateColor = _appearanceService.GetColor(entry.State.ToAppearanceColorKey(), "#1F242B"),
ForegroundColor = PrimaryTextColor
});
}
HasEntries = Entries.Count > 0;
OnPropertyChanged(nameof(HasNoEntries));
}
private async Task QuickSaveAsync(HealthState state)
{
if (SelectedDate.Date == DateTime.Today)
if (!IsToday)
{
await _repository.AddEntryAsync(
state,
EntrySource.App,
DateTime.Now);
await RefreshAsync();
await AddEntryAsync();
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();
}
private async Task NextDayAsync()
private async Task AddEntryAsync()
{
_calendarState.SelectedDate = SelectedDate.AddDays(1);
SelectedDate = _calendarState.SelectedDate;
await RefreshAsync();
if (IsFutureDate)
return;
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;
SelectedDate = _calendarState.SelectedDate;
await RefreshAsync();
}
if (item is null)
return;
private async Task OpenQuickEntryAsync()
{
string date = SelectedDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
await Shell.Current.GoToAsync($"{nameof(QuickEntryPage)}?date={date}");
var date = Uri.EscapeDataString(item.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
await Shell.Current.GoToAsync($"{nameof(Views.QuickEntryPage)}?date={date}&entryId={item.Id}");
}
private async Task DeleteEntryAsync(DayEntryItemViewModel? item)
@@ -191,20 +261,90 @@ public partial class DayViewModel : ObservableObject
if (item is null)
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();
}
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");
YellowStatusText = ThemeResourceHelper.GetString(ThemeKeys.StatusYellowText, "Gelb");
RedStatusText = ThemeResourceHelper.GetString(ThemeKeys.StatusRedText, "Rot");
GrayStatusText = ThemeResourceHelper.GetString(ThemeKeys.StatusGrayText, "Grau");
_calendarStateService.SelectedDate = SelectedDate.AddDays(-1);
await RefreshAsync();
}
}
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;
namespace cfs_tracker.ViewModels;
public class MonthCellViewModel
public partial class MonthCellViewModel : ObservableObject
{
public bool IsRealDay { get; init; }
public DateTime Date { get; init; }
public string DayNumberText { get; init; } = "";
public string CountText { get; init; } = "";
public Color BackgroundColor { get; init; } = Colors.Transparent;
public string DayNumberText { get; init; } = string.Empty;
public bool IsCurrentMonth { get; init; }
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 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();
}
+71 -56
View File
@@ -1,114 +1,129 @@
using System.Collections.ObjectModel;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Models;
using cfs_tracker.Services;
using Microsoft.Maui.Storage;
using System.Collections.ObjectModel;
namespace cfs_tracker.ViewModels;
public partial class MonthViewModel : ObservableObject
{
private readonly HealthEntryRepository _repository;
private readonly HealthEntryRepository _healthEntryRepository;
private readonly AppearanceService _appearanceService;
private readonly AggregationService _aggregationService;
private readonly CalendarStateService _calendarState;
private readonly CultureInfo _culture = new("de-DE");
private DateTime _currentMonth = new(DateTime.Today.Year, DateTime.Today.Month, 1);
private readonly CalendarStateService _calendarStateService;
private readonly IPdfExportService _pdfExportService;
[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 NextMonthCommand { get; }
public IAsyncRelayCommand TodayCommand { get; }
public IAsyncRelayCommand ExportPdfCommand { get; }
public IAsyncRelayCommand<MonthCellViewModel> OpenDayCommand { get; }
public MonthViewModel(
HealthEntryRepository repository,
HealthEntryRepository healthEntryRepository,
AppearanceService appearanceService,
AggregationService aggregationService,
CalendarStateService calendarState)
CalendarStateService calendarStateService,
IPdfExportService pdfExportService)
{
_repository = repository;
_healthEntryRepository = healthEntryRepository;
_appearanceService = appearanceService;
_aggregationService = aggregationService;
_calendarState = calendarState;
_calendarStateService = calendarStateService;
_pdfExportService = pdfExportService;
PreviousMonthCommand = new AsyncRelayCommand(PreviousMonthAsync);
NextMonthCommand = new AsyncRelayCommand(NextMonthAsync);
TodayCommand = new AsyncRelayCommand(SetTodayAsync);
TodayCommand = new AsyncRelayCommand(TodayAsync);
ExportPdfCommand = new AsyncRelayCommand(ExportAsync);
OpenDayCommand = new AsyncRelayCommand<MonthCellViewModel>(OpenDayAsync);
_calendarStateService.SelectedDateChanged += HandleSharedDateChanged;
SelectedDate = _calendarStateService.SelectedDate;
}
public async Task RefreshAsync()
{
_currentMonth = new DateTime(_currentMonth.Year, _currentMonth.Month, 1);
SelectedMonthText = _currentMonth.ToString("MMMM yyyy", _culture);
SelectedDate = _calendarStateService.SelectedDate;
var month = new DateTime(SelectedDate.Year, SelectedDate.Month, 1);
HeaderText = DateHelper.ToGermanMonthYear(month);
var monthStart = _currentMonth;
var monthEnd = monthStart.AddMonths(1);
var monthEnd = month.AddMonths(1);
var entries = await _repository.GetEntriesBetweenAsync(monthStart, monthEnd);
var summaries = _aggregationService.BuildMonthSummary(monthStart, entries);
var entries = await _healthEntryRepository.GetEntriesBetweenAsync(month, monthEnd);
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++)
Days.Add(MonthCellViewModel.Placeholder());
Cells.Add(new MonthCellViewModel
{
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)
Days.Add(BuildCell(summary));
while (Days.Count % 7 != 0)
Days.Add(MonthCellViewModel.Placeholder());
_calendarStateService.SelectedDate = item.Date;
await Shell.Current.GoToAsync("//day");
}
private MonthCellViewModel BuildCell(CalendarDaySummary summary)
private async Task ExportAsync()
{
var colorKey = summary.DisplayState?.ToColorKey() ?? ThemeKeys.PanelBackground2;
bool isToday = summary.Date.Date == DateTime.Today.Date;
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")
};
var result = await _pdfExportService.ExportMonthAsync(SelectedDate);
await ExportUiHelper.ShowExportSavedActionsAsync(result);
}
private async Task PreviousMonthAsync()
{
_currentMonth = _currentMonth.AddMonths(-1);
_calendarStateService.SelectedDate = new DateTime(SelectedDate.Year, SelectedDate.Month, 1).AddMonths(-1);
await RefreshAsync();
}
private async Task NextMonthAsync()
{
_currentMonth = _currentMonth.AddMonths(1);
_calendarStateService.SelectedDate = new DateTime(SelectedDate.Year, SelectedDate.Month, 1).AddMonths(1);
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)
return;
await _calendarState.ShowDayTabAsync(cell.Date);
SelectedDate = date;
await RefreshAsync();
}
}
}
@@ -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;
}
+390 -42
View File
@@ -1,16 +1,25 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Models;
using cfs_tracker.Services;
using System.Collections.ObjectModel;
namespace cfs_tracker.ViewModels;
public partial class OptionsViewModel : ObservableObject
{
private readonly HealthEntryRepository _healthRepository;
private readonly HealthEntryRepository _healthEntryRepository;
private readonly AppearanceRepository _appearanceRepository;
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]
private string deleteConfirmationText = string.Empty;
@@ -18,25 +27,83 @@ public partial class OptionsViewModel : ObservableObject
[ObservableProperty]
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<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 SaveAppearanceCommand { 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(
HealthEntryRepository healthRepository,
HealthEntryRepository healthEntryRepository,
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;
_appearanceService = appearanceService;
_activityRepository = activityRepository;
_symptomRepository = symptomRepository;
_notificationScheduleRepository = notificationScheduleRepository;
_notificationScheduler = notificationScheduler;
_databaseLocationService = databaseLocationService;
_appDatabase = appDatabase;
_pdfExportService = pdfExportService;
DeleteAllDataCommand = new AsyncRelayCommand(DeleteAllDataAsync, CanDeleteAllData);
SaveAppearanceCommand = new AsyncRelayCommand(SaveAppearanceAsync);
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)
@@ -47,18 +114,24 @@ public partial class OptionsViewModel : ObservableObject
public async Task LoadAsync()
{
await LoadAppearanceAsync();
await LoadActivitiesAsync();
await LoadSymptomsAsync();
await LoadSchedulesAsync();
UseExternalDatabase = _databaseLocationService.UseExternalDatabase;
ExternalDatabasePath = _databaseLocationService.ExternalDatabasePath;
CurrentDatabasePath = _appDatabase.CurrentPath;
StatusText = string.Empty;
}
private bool CanDeleteAllData()
{
return string.Equals(DeleteConfirmationText?.Trim(), "löschen", StringComparison.OrdinalIgnoreCase);
}
private bool CanDeleteAllData() =>
string.Equals(DeleteConfirmationText?.Trim(), "löschen", StringComparison.OrdinalIgnoreCase);
private async Task DeleteAllDataAsync()
{
await _healthRepository.DeleteAllAsync();
await _healthEntryRepository.DeleteAllAsync();
DeleteConfirmationText = string.Empty;
StatusText = "Alle gespeicherten Einträge wurden gelöscht.";
StatusText = "Alle Einträge wurden gelöscht.";
}
private async Task LoadAppearanceAsync()
@@ -66,64 +139,339 @@ public partial class OptionsViewModel : ObservableObject
AppearanceColors.Clear();
StatusTexts.Clear();
var all = await _appearanceRepository.GetAllAsync();
var map = await _appearanceRepository.GetMapAsync();
AddColor(all, "AppBackground", "App-Hintergrund");
AddColor(all, "PanelBackground", "Panel-Hintergrund");
AddColor(all, "PanelBackground2", "Sekundäre Fläche");
AddColor(all, "PanelBorder", "Panel-Rand");
AddColor(all, "TextPrimary", "Haupttext");
AddColor(all, "TextMuted", "Gedimmter Text");
AddColor(all, "StateGreen", "Statusfarbe Grün");
AddColor(all, "StateYellow", "Statusfarbe Gelb");
AddColor(all, "StateRed", "Statusfarbe Rot");
AddColor(all, "StateGray", "Statusfarbe Grau");
AddColor(AppearanceKeys.AppBackground, "App-Hintergrund");
AddColor(AppearanceKeys.SurfaceBackground, "Karten-Hintergrund");
AddColor(AppearanceKeys.SurfaceBackgroundAlt, "Sekundäre Fläche");
AddColor(AppearanceKeys.Border, "Rahmen");
AddColor(AppearanceKeys.TextPrimary, "Haupttext");
AddColor(AppearanceKeys.TextMuted, "Nebentext");
AddText(all, "StatusGreenText", "Text für Grün");
AddText(all, "StatusYellowText", "Text für Gelb");
AddText(all, "StatusRedText", "Text für Rot");
AddText(all, "StatusGrayText", "Text für Grau");
AddColor(AppearanceKeys.StateGreen, "Statusfarbe Grün");
AddColor(AppearanceKeys.StateYellow, "Statusfarbe Gelb");
AddColor(AppearanceKeys.StateRed, "Statusfarbe Rot");
AddColor(AppearanceKeys.StateGray, "Statusfarbe Schwarz / Grau");
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 fallback = AppearanceDefaults.All[key];
var value = map.TryGetValue(key, out var stored) ? stored : fallback;
AppearanceColors.Add(new AppearanceColorItemViewModel
{
Key = key,
Title = title,
Fallback = fallback,
Value = value,
PreviewColor = ColorUtility.ParseColor(value, fallback)
});
}
void AddText(string key, string title)
{
var fallback = AppearanceDefaults.All[key];
var value = map.TryGetValue(key, out var stored) ? stored : fallback;
StatusTexts.Add(new AppearanceTextItemViewModel
{
Key = key,
Title = title,
Value = value
});
}
}
private void AddColor(List<Models.AppearanceSetting> all, string key, string title)
private async Task LoadActivitiesAsync()
{
var value = all.FirstOrDefault(x => x.Key == key)?.Value ?? string.Empty;
Activities.Clear();
var all = await _activityRepository.GetAllAsync();
AppearanceColors.Add(new AppearanceColorItemViewModel
foreach (var item in all)
{
Key = key,
Title = title,
Value = value
});
Activities.Add(new ActivityManageItemViewModel
{
Id = item.Id,
Name = item.Name,
IsActive = item.IsActive,
IsUsed = await _activityRepository.HasUsageAsync(item.Id)
});
}
}
private void AddText(List<Models.AppearanceSetting> all, string key, string title)
private async Task LoadSymptomsAsync()
{
var value = all.FirstOrDefault(x => x.Key == key)?.Value ?? string.Empty;
Symptoms.Clear();
var all = await _symptomRepository.GetAllAsync();
StatusTexts.Add(new AppearanceTextItemViewModel
foreach (var item in all)
{
Key = key,
Title = title,
Value = value
});
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()
{
foreach (var item in AppearanceColors)
{
item.PreviewColor = ColorUtility.ParseColor(item.Value, item.Fallback);
await _appearanceService.SaveColorAsync(item.Key, item.Value);
}
foreach (var item in StatusTexts)
await _appearanceService.SaveTextAsync(item.Key, item.Value);
StatusText = "Aussehen wurde gespeichert.";
StatusText = "Aussehen gespeichert.";
}
private async Task ResetAppearanceAsync()
{
await _appearanceService.ResetAsync();
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" };
}
}
+316 -48
View File
@@ -1,92 +1,360 @@
using System.Collections.ObjectModel;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data;
using cfs_tracker.Helpers;
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;
public partial class QuickEntryViewModel : ObservableObject
{
private readonly HealthEntryRepository _repo;
private readonly ActivityRepository _activityRepo;
private readonly SymptomRepository _symptomRepo;
private readonly HealthEntryRepository _healthEntryRepository;
private readonly ActivityRepository _activityRepository;
private readonly SymptomRepository _symptomRepository;
private readonly AppearanceService _appearanceService;
private readonly CalendarStateService _calendarStateService;
[ObservableProperty] private DateTime selectedDate = DateTime.Today;
[ObservableProperty] private string selectedDateText = "";
[ObservableProperty] private bool isPastDate;
[ObservableProperty] private bool isFutureDate;
[ObservableProperty] private string selectedPartText = "Vormittag";
[ObservableProperty] private SelectableItemViewModel? selectedActivity;
private string _dateQuery = string.Empty;
private int? _entryId;
public ObservableCollection<string> AvailableParts { get; } = new() { "Vormittag", "Nachmittag" };
public ObservableCollection<SelectableItemViewModel> Activities { get; } = new();
public ObservableCollection<SelectableItemViewModel> Symptoms { get; } = new();
[ObservableProperty]
private DateTime selectedDate = DateTime.Today;
[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 SaveYellowCommand { get; }
public IAsyncRelayCommand SaveRedCommand { 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;
SaveGreenCommand = new AsyncRelayCommand(()=>SaveAsync(HealthState.Green));
SaveYellowCommand = new AsyncRelayCommand(()=>SaveAsync(HealthState.Yellow));
SaveRedCommand = new AsyncRelayCommand(()=>SaveAsync(HealthState.Red));
SaveGrayCommand = new AsyncRelayCommand(()=>SaveAsync(HealthState.Gray));
_healthEntryRepository = healthEntryRepository;
_activityRepository = activityRepository;
_symptomRepository = symptomRepository;
_appearanceService = appearanceService;
_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();
Symptoms.Clear();
Activities.Add(new SelectableItemViewModel { Id = 0, Name = "Keine Angabe" });
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 });
Activities.Add(new ActivityPickerItemViewModel
{
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();
}
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))
SelectedDate = parsed.Date;
else
SelectedDate = DateTime.Today;
UpdateState();
Symptoms.Clear();
var items = await _symptomRepository.GetActiveAsync();
foreach (var item in items)
{
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)
{
if (IsFutureDate) return;
int? activityId = SelectedActivity is not null && SelectedActivity.Id > 0 ? SelectedActivity.Id : null;
int entryId;
if (IsPastDate)
if (IsFutureDate)
return;
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);
var saved = await _repo.GetBackfillEntryAsync(SelectedDate, SelectedPartText == "Nachmittag" ? DayPart.Afternoon : DayPart.Morning);
entryId = saved?.Id ?? 0;
await _healthEntryRepository.UpdateEntryAsync(
entryId: _entryId.Value,
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
{
entryId = await _repo.AddEntryAndReturnIdAsync(state, EntrySource.App, DateTime.Now, activityId);
}
if (entryId > 0)
{
await _symptomRepo.SetSymptomsForEntryAsync(entryId, Symptoms.Where(x=>x.IsSelected).Select(x=>x.Id));
await _healthEntryRepository.AddQuickEntryAsync(
state: state,
activityId: activityId,
symptomIds: symptomIds,
timestamp: DateTime.Now,
source: EntrySource.App);
}
_calendarStateService.SelectedDate = SelectedDate;
await Shell.Current.GoToAsync("..");
}
private void UpdateState()
private Task CancelAsync() => Shell.Current.GoToAsync("..");
private void UpdateDateMode()
{
var today = DateTime.Today;
IsToday = SelectedDate.Date == today;
IsPastDate = 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));
}
}
+80 -73
View File
@@ -1,131 +1,138 @@
using System.Collections.ObjectModel;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Models;
using cfs_tracker.Services;
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Storage;
using System.Collections.ObjectModel;
namespace cfs_tracker.ViewModels;
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 CalendarStateService _calendarState;
private readonly CalendarStateService _calendarStateService;
private readonly IPdfExportService _pdfExportService;
[ObservableProperty]
private DateTime anchorDate = DateTime.Today;
private DateTime selectedDate;
[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 NextWeekCommand { get; }
public IAsyncRelayCommand TodayCommand { get; }
public IAsyncRelayCommand<WeekCellViewModel> OpenDayCommand { get; }
public IAsyncRelayCommand ExportPdfCommand { get; }
public IAsyncRelayCommand<WeekDaySummaryViewModel> OpenDayCommand { get; }
public WeekViewModel(
HealthEntryRepository repository,
HealthEntryRepository healthEntryRepository,
ActivityRepository activityRepository,
SymptomRepository symptomRepository,
AppearanceService appearanceService,
AggregationService aggregationService,
CalendarStateService calendarState)
CalendarStateService calendarStateService,
IPdfExportService pdfExportService)
{
_repository = repository;
_healthEntryRepository = healthEntryRepository;
_activityRepository = activityRepository;
_symptomRepository = symptomRepository;
_appearanceService = appearanceService;
_aggregationService = aggregationService;
_calendarState = calendarState;
_calendarStateService = calendarStateService;
_pdfExportService = pdfExportService;
PreviousWeekCommand = new AsyncRelayCommand(PreviousWeekAsync);
NextWeekCommand = new AsyncRelayCommand(NextWeekAsync);
TodayCommand = new AsyncRelayCommand(SetTodayAsync);
OpenDayCommand = new AsyncRelayCommand<WeekCellViewModel>(OpenDayAsync);
TodayCommand = new AsyncRelayCommand(TodayAsync);
ExportPdfCommand = new AsyncRelayCommand(ExportAsync);
OpenDayCommand = new AsyncRelayCommand<WeekDaySummaryViewModel>(OpenDayAsync);
_calendarStateService.SelectedDateChanged += HandleSharedDateChanged;
SelectedDate = _calendarStateService.SelectedDate;
}
public async Task RefreshAsync()
{
var weekStart = StartOfWeek(AnchorDate);
var weekEnd = weekStart.AddDays(7);
SelectedDate = _calendarStateService.SelectedDate;
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 _repository.GetEntriesBetweenAsync(weekStart, weekEnd);
var summaries = _aggregationService.BuildWeekSummary(weekStart, entries);
var entries = await _healthEntryRepository.GetEntriesBetweenAsync(WeekStart, WeekStart.AddDays(7));
var activityMap = await _activityRepository.GetNameMapAsync();
var symptomsMap = await _symptomRepository.GetSymptomsByEntryIdsAsync(entries.Select(x => x.Id));
Days.Clear();
foreach (var summary in summaries)
Days.Add(BuildCell(summary));
for (var i = 0; i < 7; i++)
{
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);
var afternoonState = _aggregationService.ToDisplayState(summary.AfternoonAverage);
if (item is null)
return;
return new WeekCellViewModel
{
Date = summary.Date,
DayText = summary.Date.ToString("ddd", new CultureInfo("de-DE")),
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
};
_calendarStateService.SelectedDate = item.Date;
await Shell.Current.GoToAsync("//day");
}
private async Task ExportAsync()
{
var result = await _pdfExportService.ExportWeekAsync(SelectedDate);
await ExportUiHelper.ShowExportSavedActionsAsync(result);
}
private async Task PreviousWeekAsync()
{
AnchorDate = AnchorDate.AddDays(-7);
_calendarStateService.SelectedDate = DateHelper.StartOfWeekMonday(SelectedDate).AddDays(-7);
await RefreshAsync();
}
private async Task NextWeekAsync()
{
AnchorDate = AnchorDate.AddDays(7);
_calendarStateService.SelectedDate = DateHelper.StartOfWeekMonday(SelectedDate).AddDays(7);
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)
return;
await _calendarState.ShowDayTabAsync(cell.Date);
SelectedDate = date;
await RefreshAsync();
}
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();
}
+77 -62
View File
@@ -1,125 +1,140 @@
using System.Collections.ObjectModel;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using cfs_tracker.Data;
using cfs_tracker.Helpers;
using cfs_tracker.Models;
using cfs_tracker.Services;
using Microsoft.Maui.Storage;
using System.Collections.ObjectModel;
namespace cfs_tracker.ViewModels;
public partial class YearViewModel : ObservableObject
{
private readonly HealthEntryRepository _repository;
private readonly HealthEntryRepository _healthEntryRepository;
private readonly AppearanceService _appearanceService;
private readonly AggregationService _aggregationService;
private readonly CalendarStateService _calendarState;
private readonly CultureInfo _culture = new("de-DE");
private int _currentYear = DateTime.Today.Year;
private readonly CalendarStateService _calendarStateService;
private readonly IPdfExportService _pdfExportService;
[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 NextYearCommand { get; }
public IAsyncRelayCommand TodayCommand { get; }
public IAsyncRelayCommand ExportPdfCommand { get; }
public IAsyncRelayCommand<MonthCellViewModel> OpenDayCommand { get; }
public YearViewModel(
HealthEntryRepository repository,
HealthEntryRepository healthEntryRepository,
AppearanceService appearanceService,
AggregationService aggregationService,
CalendarStateService calendarState)
CalendarStateService calendarStateService,
IPdfExportService pdfExportService)
{
_repository = repository;
_healthEntryRepository = healthEntryRepository;
_appearanceService = appearanceService;
_aggregationService = aggregationService;
_calendarState = calendarState;
_calendarStateService = calendarStateService;
_pdfExportService = pdfExportService;
PreviousYearCommand = new AsyncRelayCommand(PreviousYearAsync);
NextYearCommand = new AsyncRelayCommand(NextYearAsync);
TodayCommand = new AsyncRelayCommand(SetTodayAsync);
TodayCommand = new AsyncRelayCommand(TodayAsync);
ExportPdfCommand = new AsyncRelayCommand(ExportAsync);
OpenDayCommand = new AsyncRelayCommand<MonthCellViewModel>(OpenDayAsync);
_calendarStateService.SelectedDateChanged += HandleSharedDateChanged;
SelectedDate = _calendarStateService.SelectedDate;
}
public async Task RefreshAsync()
{
SelectedYearText = _currentYear.ToString();
SelectedDate = _calendarStateService.SelectedDate;
HeaderText = DateHelper.ToGermanYear(SelectedDate);
var start = new DateTime(_currentYear, 1, 1);
var end = start.AddYears(1);
var entries = await _repository.GetEntriesBetweenAsync(start, end);
var summaries = _aggregationService.BuildYearSummary(_currentYear, entries);
var yearStart = new DateTime(SelectedDate.Year, 1, 1);
var yearEnd = yearStart.AddYears(1);
var entries = await _healthEntryRepository.GetEntriesBetweenAsync(yearStart, yearEnd);
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,
MonthText = new DateTime(_currentYear, month, 1).ToString("MMMM", _culture)
Title = DateHelper.ToGermanMonthYear(monthStart)
};
var monthStart = new DateTime(_currentYear, month, 1);
int leadingEmptyDays = ((int)monthStart.DayOfWeek + 6) % 7;
for (var day = 1; day <= daysInMonth; day++)
{
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++)
monthVm.Days.Add(MonthCellViewModel.Placeholder());
section.Cells.Add(new MonthCellViewModel
{
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")
});
}
foreach (var summary in summaries.Where(x => x.Date.Month == month))
monthVm.Days.Add(BuildCell(summary));
while (monthVm.Days.Count % 7 != 0)
monthVm.Days.Add(MonthCellViewModel.Placeholder());
Months.Add(monthVm);
Months.Add(section);
}
}
private MonthCellViewModel BuildCell(CalendarDaySummary summary)
private async Task OpenDayAsync(MonthCellViewModel? item)
{
var colorKey = summary.DisplayState?.ToColorKey() ?? ThemeKeys.PanelBackground2;
bool isToday = summary.Date.Date == DateTime.Today.Date;
if (item is null)
return;
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")
};
_calendarStateService.SelectedDate = item.Date;
await Shell.Current.GoToAsync("//day");
}
private async Task ExportAsync()
{
var result = await _pdfExportService.ExportYearAsync(SelectedDate);
await ExportUiHelper.ShowExportSavedActionsAsync(result);
}
private async Task PreviousYearAsync()
{
_currentYear--;
_calendarStateService.SelectedDate = new DateTime(SelectedDate.Year - 1, SelectedDate.Month, 1);
await RefreshAsync();
}
private async Task NextYearAsync()
{
_currentYear++;
_calendarStateService.SelectedDate = new DateTime(SelectedDate.Year + 1, SelectedDate.Month, 1);
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)
return;
await _calendarState.ShowDayTabAsync(cell.Date);
SelectedDate = date;
await RefreshAsync();
}
}
}
+132 -188
View File
@@ -1,210 +1,154 @@
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="cfs_tracker.Views.DayPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="ThisPage"
Title="Tag">
<ContentPage x:Class="cfs_tracker.Views.DayPage"
x:Name="RootPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels"
x:DataType="viewModels:DayViewModel"
Title="Tag"
BackgroundColor="{DynamicResource AppBackground}">
<ScrollView>
<VerticalStackLayout Padding="16" Spacing="14">
<Grid ColumnDefinitions="Auto,*,Auto,Auto">
<Button
Grid.Column="0"
Text="◀"
WidthRequest="52"
HeightRequest="44"
Command="{Binding PreviousDayCommand}" />
<Label
Grid.Column="1"
Text="{Binding SelectedDateText}"
HorizontalTextAlignment="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}" />
<VerticalStackLayout Padding="16" Spacing="16">
<Grid ColumnDefinitions="Auto,*,Auto"
VerticalOptions="Center">
<Button Text="←"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding PreviousDayCommand}" />
<Label Grid.Column="1"
Text="{Binding SelectedDateText}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Button Grid.Column="2"
Text="→"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding NextDayCommand}" />
</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 ColumnDefinitions="*,*"
ColumnSpacing="12">
<Button Text="Heute"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding TodayCommand}" />
<Button Grid.Column="1"
Text="Export"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding ExportPdfCommand}" />
</Grid>
<Label
Text="Einträge"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<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" />
<CollectionView
ItemsSource="{Binding Entries}"
SelectionMode="None">
<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">
<CollectionView.ItemTemplate>
<DataTemplate>
<Border
Margin="0,0,0,8"
Padding="12"
BackgroundColor="{Binding BackgroundColor}"
StrokeThickness="0"
StrokeShape="RoundRectangle 12">
<VerticalStackLayout Spacing="8">
<Grid ColumnDefinitions="Auto,*,Auto" ColumnSpacing="12">
<Label
Grid.Column="0"
Text="{Binding TimeText}"
TextColor="{Binding TextColor}"
FontAttributes="Bold"
VerticalOptions="Center" />
<VerticalStackLayout Grid.Column="1" Spacing="2">
<Label
Text="{Binding StateText}"
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" />
<DataTemplate x:DataType="viewModels:DayEntryItemViewModel">
<Border Margin="0,0,0,12"
Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="10">
<Grid ColumnDefinitions="*,Auto,Auto"
ColumnSpacing="10">
<VerticalStackLayout Spacing="4">
<Label Text="{Binding SlotText}"
FontAttributes="Bold"
TextColor="{DynamicResource TextMuted}" />
<Label Text="{Binding StateText}"
FontSize="18"
FontAttributes="Bold"
TextColor="{Binding ForegroundColor}" />
</VerticalStackLayout>
<Button
Grid.Column="2"
Text="X"
WidthRequest="44"
HeightRequest="44"
Command="{Binding Source={x:Reference ThisPage}, Path=BindingContext.DeleteEntryCommand}"
CommandParameter="{Binding .}" />
<Button Grid.Column="1"
Text="Bearbeiten"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.EditEntryCommand}"
CommandParameter="{Binding .}" />
<Button Grid.Column="2"
Text="Löschen"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.DeleteEntryCommand}"
CommandParameter="{Binding .}" />
</Grid>
<Border
IsVisible="{Binding IsExpanded}"
Padding="10"
BackgroundColor="{DynamicResource PanelBackground2}"
Stroke="{DynamicResource PanelBorder}"
StrokeThickness="1"
StrokeShape="RoundRectangle 10">
<VerticalStackLayout Spacing="6">
<VerticalStackLayout IsVisible="{Binding HasActivity}" Spacing="2">
<Label
Text="Tätigkeit"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<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 Padding="8"
StrokeThickness="0"
StrokeShape="RoundRectangle 10"
BackgroundColor="{Binding StateColor}">
<Label Text="{Binding StateText}"
FontAttributes="Bold"
TextColor="{Binding ForegroundColor}" />
</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>
</Border>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</VerticalStackLayout>
</ScrollView>
</ContentPage>
</ContentPage>
+1 -1
View File
@@ -17,4 +17,4 @@ public partial class DayPage : ContentPage
base.OnAppearing();
await _viewModel.RefreshAsync();
}
}
}
+86 -94
View File
@@ -1,100 +1,92 @@
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="cfs_tracker.Views.MonthPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="ThisPage"
Title="Monat">
<ContentPage x:Class="cfs_tracker.Views.MonthPage"
x:Name="RootPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels"
x:DataType="viewModels:MonthViewModel"
Title="Monat"
BackgroundColor="{DynamicResource AppBackground}">
<Grid RowDefinitions="Auto,Auto,*" Padding="16">
<ScrollView>
<VerticalStackLayout Padding="16" Spacing="16">
<Grid ColumnDefinitions="Auto,*,Auto"
VerticalOptions="Center">
<Button Text="←"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding PreviousMonthCommand}" />
<Label Grid.Column="1"
Text="{Binding HeaderText}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Button Grid.Column="2"
Text="→"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding NextMonthCommand}" />
</Grid>
<Grid Grid.Row="0" ColumnDefinitions="Auto,*,Auto,Auto" Margin="0,0,0,12">
<Button
Grid.Column="0"
Text="◀"
WidthRequest="52"
HeightRequest="44"
Command="{Binding PreviousMonthCommand}" />
<Grid ColumnDefinitions="*,*"
ColumnSpacing="12">
<Button Text="Heute"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding TodayCommand}" />
<Button Grid.Column="1"
Text="Export"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding ExportPdfCommand}" />
</Grid>
<Label
Grid.Column="1"
Text="{Binding SelectedMonthText}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
FontSize="24"
FontAttributes="Bold" />
<Grid ColumnDefinitions="*,*,*,*,*,*,*"
ColumnSpacing="4">
<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>
<Button
Grid.Column="2"
Text="Heute"
Margin="8,0,0,0"
Command="{Binding TodayCommand}" />
<CollectionView ItemsSource="{Binding Cells}"
SelectionMode="None">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical"
Span="7" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="viewModels:MonthCellViewModel">
<Border Margin="2"
Padding="6"
Stroke="{Binding BorderColor}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 10">
<Border.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.OpenDayCommand}"
CommandParameter="{Binding .}" />
</Border.GestureRecognizers>
<Button
Grid.Column="3"
Text="▶"
WidthRequest="52"
HeightRequest="44"
Margin="8,0,0,0"
Command="{Binding NextMonthCommand}" />
</Grid>
<Grid Grid.Row="1" ColumnDefinitions="*,*,*,*,*,*,*" Margin="0,0,0,8">
<Label Grid.Column="0" Text="Mo" HorizontalTextAlignment="Center" FontAttributes="Bold" />
<Label Grid.Column="1" Text="Di" HorizontalTextAlignment="Center" FontAttributes="Bold" />
<Label Grid.Column="2" Text="Mi" HorizontalTextAlignment="Center" FontAttributes="Bold" />
<Label Grid.Column="3" Text="Do" HorizontalTextAlignment="Center" FontAttributes="Bold" />
<Label Grid.Column="4" Text="Fr" HorizontalTextAlignment="Center" FontAttributes="Bold" />
<Label Grid.Column="5" Text="Sa" HorizontalTextAlignment="Center" FontAttributes="Bold" />
<Label Grid.Column="6" Text="So" HorizontalTextAlignment="Center" FontAttributes="Bold" />
</Grid>
<CollectionView
Grid.Row="2"
ItemsSource="{Binding Days}"
SelectionMode="None">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="7" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="3">
<Border
HeightRequest="74"
BackgroundColor="{Binding BackgroundColor}"
Stroke="{Binding BorderColor}"
StrokeThickness="1"
StrokeShape="RoundRectangle 10">
<Grid Padding="6">
<Grid.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding Source={x:Reference ThisPage}, Path=BindingContext.OpenDayCommand}"
CommandParameter="{Binding .}" />
</Grid.GestureRecognizers>
<VerticalStackLayout
IsVisible="{Binding IsRealDay}"
Spacing="4">
<Label
Text="{Binding DayNumberText}"
TextColor="{Binding TextColor}"
FontAttributes="Bold"
FontSize="16" />
<Label
Text="{Binding CountText}"
TextColor="{Binding TextColor}"
FontSize="12" />
</VerticalStackLayout>
</Grid>
</Border>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</Grid>
</ContentPage>
<VerticalStackLayout Spacing="4">
<Label Text="{Binding DayNumberText}"
FontAttributes="Bold"
TextColor="{Binding TextColor}" />
<Border Padding="4"
StrokeThickness="0"
StrokeShape="RoundRectangle 8"
BackgroundColor="{Binding StateColor}">
<Label Text="{Binding AverageStateText}"
FontSize="11"
HorizontalTextAlignment="Center"
TextColor="White" />
</Border>
</VerticalStackLayout>
</Border>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</VerticalStackLayout>
</ScrollView>
</ContentPage>
+15 -3
View File
@@ -1,8 +1,20 @@
using cfs_tracker.ViewModels;
namespace cfs_tracker.Views;
public partial class MonthPage : ContentPage
{
private readonly MonthViewModel _vm;
public MonthPage(MonthViewModel vm){ InitializeComponent(); BindingContext = _vm = vm; }
protected override async void OnAppearing(){ base.OnAppearing(); await _vm.RefreshAsync(); }
private readonly MonthViewModel _viewModel;
public MonthPage(MonthViewModel viewModel)
{
InitializeComponent();
BindingContext = _viewModel = viewModel;
}
protected override async void OnAppearing()
{
base.OnAppearing();
await _viewModel.RefreshAsync();
}
}
+302 -113
View File
@@ -1,129 +1,318 @@
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="cfs_tracker.Views.OptionsPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:conv="clr-namespace:cfs_tracker.Converters"
Title="Optionen">
<ContentPage.Resources>
<ResourceDictionary>
<conv:HexToColorConverter x:Key="HexToColorConverter" />
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage x:Class="cfs_tracker.Views.OptionsPage"
x:Name="RootPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels"
x:DataType="viewModels:OptionsViewModel"
Title="Optionen"
BackgroundColor="{DynamicResource AppBackground}">
<ScrollView>
<VerticalStackLayout Padding="16" Spacing="16">
<Label Text="Optionen"
FontSize="28"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label
Text="Optionen"
FontSize="26"
FontAttributes="Bold" />
<Label Text="{Binding StatusText}"
TextColor="{DynamicResource TextMuted}" />
<Label
Text="Aussehen"
FontSize="22"
FontAttributes="Bold" />
<Label
Text="Farben"
FontSize="18"
FontAttributes="Bold" />
<CollectionView ItemsSource="{Binding AppearanceColors}" SelectionMode="None">
<CollectionView.ItemTemplate>
<DataTemplate>
<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"
BackgroundColor="{Binding Value, Converter={StaticResource HexToColorConverter}}" />
</Grid>
</VerticalStackLayout>
</Border>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<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>
</Border>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<HorizontalStackLayout Spacing="10">
<Button
Text="Aussehen speichern"
Command="{Binding SaveAppearanceCommand}" />
<Button
Text="Standard wiederherstellen"
Command="{Binding ResetAppearanceCommand}" />
</HorizontalStackLayout>
<Label
Text="Datenbank"
FontSize="22"
FontAttributes="Bold" />
<Border Padding="14">
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="12">
<Label
Text="Alle Einträge löschen"
FontSize="18"
FontAttributes="Bold" />
<Label Text="Aussehen"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Label
Text="Zur Bestätigung das Wort 'löschen' eingeben." />
<VerticalStackLayout BindableLayout.ItemsSource="{Binding AppearanceColors}"
Spacing="10">
<BindableLayout.ItemTemplate>
<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>
<Entry
Placeholder="löschen"
Text="{Binding DeleteConfirmationText}" />
<Border Grid.Column="1"
Padding="8"
Stroke="{DynamicResource Border}"
StrokeShape="RoundRectangle 8"
BackgroundColor="{Binding PreviewColor}">
<Label Text="{Binding Value}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
TextColor="{DynamicResource TextPrimary}" />
</Border>
</Grid>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
<Button
Text="Alle Daten löschen"
BackgroundColor="#A85C5C"
Command="{Binding DeleteAllDataCommand}" />
<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>
<Label
Text="{Binding StatusText}"
FontSize="13" />
<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>
<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>
</Border>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="12">
<Label Text="Symptome"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Grid ColumnDefinitions="*,Auto"
ColumnSpacing="10">
<Entry Text="{Binding NewSymptomName}"
Placeholder="Neues Symptom" />
<Button Grid.Column="1"
Text="Hinzufügen"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding AddSymptomCommand}" />
</Grid>
<VerticalStackLayout BindableLayout.ItemsSource="{Binding Symptoms}"
Spacing="10">
<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>
<Border Padding="12"
Stroke="{DynamicResource Border}"
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}" />
</VerticalStackLayout>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="10">
<Label Text="Export"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Button Text="Export entleeren"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding ClearExportsCommand}" />
</VerticalStackLayout>
</Border>
</VerticalStackLayout>
</ScrollView>
</ContentPage>
</ContentPage>
+1 -1
View File
@@ -17,4 +17,4 @@ public partial class OptionsPage : ContentPage
base.OnAppearing();
await _viewModel.LoadAsync();
}
}
}
+153 -19
View File
@@ -1,23 +1,157 @@
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="cfs_tracker.Views.QuickEntryPage"
<ContentPage
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
Title="Eintrag">
<ScrollView><VerticalStackLayout Padding="20" Spacing="18">
<Label Text="Wie geht es dir?" FontSize="28" FontAttributes="Bold" HorizontalTextAlignment="Center" />
<Label Text="{Binding SelectedDateText}" FontSize="16" HorizontalTextAlignment="Center" />
<VerticalStackLayout IsVisible="{Binding IsPastDate}" Spacing="8">
<Label Text="Tageszeit" FontAttributes="Bold" HorizontalTextAlignment="Center" />
<Picker Title="Tageszeit" ItemsSource="{Binding AvailableParts}" SelectedItem="{Binding SelectedPartText}" />
xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels"
x:DataType="viewModels:QuickEntryViewModel"
x:Class="cfs_tracker.Views.QuickEntryPage"
Title="Eintrag"
BackgroundColor="{DynamicResource AppBackground}">
<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>
</Border>
<Border Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<VerticalStackLayout Spacing="8">
<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>
</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>
<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 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" />
<Grid ColumnDefinitions="*,*" RowDefinitions="Auto,Auto" ColumnSpacing="12" RowSpacing="12">
<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}" />
<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}" />
<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}" />
<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}" />
</Grid>
</VerticalStackLayout></ScrollView>
</ContentPage>
</ScrollView>
</ContentPage>
+31 -5
View File
@@ -1,10 +1,36 @@
using Microsoft.Maui.Controls;
using cfs_tracker.ViewModels;
namespace cfs_tracker.Views;
public partial class QuickEntryPage : ContentPage, IQueryAttributable
{
private readonly QuickEntryViewModel _vm;
public QuickEntryPage(QuickEntryViewModel vm){ InitializeComponent(); BindingContext = _vm = vm; }
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()); }
}
private bool _initialized;
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());
}
}
+107 -132
View File
@@ -1,142 +1,117 @@
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="cfs_tracker.Views.WeekPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="ThisPage"
Title="Woche">
<ContentPage x:Class="cfs_tracker.Views.WeekPage"
x:Name="RootPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels"
x:DataType="viewModels:WeekViewModel"
Title="Woche"
BackgroundColor="{DynamicResource AppBackground}">
<Grid RowDefinitions="Auto,*" Padding="16">
<ScrollView>
<VerticalStackLayout Padding="16" Spacing="16">
<Grid ColumnDefinitions="Auto,*,Auto"
VerticalOptions="Center">
<Button Text="←"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding PreviousWeekCommand}" />
<Label Grid.Column="1"
Text="{Binding HeaderText}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Button Grid.Column="2"
Text="→"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding NextWeekCommand}" />
</Grid>
<Grid Grid.Row="0" ColumnDefinitions="Auto,*,Auto,Auto" Margin="0,0,0,12">
<Button
Grid.Column="0"
Text="◀"
WidthRequest="52"
HeightRequest="44"
Command="{Binding PreviousWeekCommand}" />
<Grid ColumnDefinitions="*,*"
ColumnSpacing="12">
<Button Text="Heute"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding TodayCommand}" />
<Button Grid.Column="1"
Text="Export"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding ExportPdfCommand}" />
</Grid>
<Label
Grid.Column="1"
Text="{Binding WeekText}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
FontSize="22"
FontAttributes="Bold" />
<CollectionView ItemsSource="{Binding Days}"
SelectionMode="None">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="viewModels:WeekDaySummaryViewModel">
<Border Margin="0,0,0,12"
Padding="12"
Stroke="{DynamicResource Border}"
BackgroundColor="{DynamicResource SurfaceBackground}"
StrokeShape="RoundRectangle 14">
<Border.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.OpenDayCommand}"
CommandParameter="{Binding .}" />
</Border.GestureRecognizers>
<Button
Grid.Column="2"
Text="Heute"
Margin="8,0,0,0"
Command="{Binding TodayCommand}" />
<VerticalStackLayout Spacing="10">
<Grid ColumnDefinitions="*"
ColumnSpacing="10">
<Label Text="{Binding DateText}"
FontAttributes="Bold"
FontSize="18"
TextColor="{DynamicResource TextPrimary}" />
</Grid>
<Button
Grid.Column="3"
Text="▶"
WidthRequest="52"
HeightRequest="44"
Margin="8,0,0,0"
Command="{Binding NextWeekCommand}" />
</Grid>
<Grid ColumnDefinitions="*,*"
ColumnSpacing="12">
<Border Padding="10"
StrokeThickness="0"
StrokeShape="RoundRectangle 10"
BackgroundColor="{Binding MorningColor}">
<VerticalStackLayout Spacing="4">
<Label Text="Vormittag"
FontAttributes="Bold"
TextColor="White" />
<Label Text="{Binding MorningText}"
TextColor="White" />
</VerticalStackLayout>
</Border>
<CollectionView
Grid.Row="1"
ItemsSource="{Binding Days}"
SelectionMode="None">
<Border Grid.Column="1"
Padding="10"
StrokeThickness="0"
StrokeShape="RoundRectangle 10"
BackgroundColor="{Binding AfternoonColor}">
<VerticalStackLayout Spacing="4">
<Label Text="Nachmittag"
FontAttributes="Bold"
TextColor="White" />
<Label Text="{Binding AfternoonText}"
TextColor="White" />
</VerticalStackLayout>
</Border>
</Grid>
<CollectionView.ItemsLayout>
<LinearItemsLayout Orientation="Vertical" ItemSpacing="10" />
</CollectionView.ItemsLayout>
<Button Text="{Binding DetailsButtonText}"
IsVisible="{Binding HasDetails}"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding ToggleExpandedCommand}" />
<CollectionView.ItemTemplate>
<DataTemplate>
<Border
Padding="12"
BackgroundColor="{DynamicResource PanelBackground}"
Stroke="{DynamicResource PanelBorder}"
StrokeThickness="1"
StrokeShape="RoundRectangle 12">
<VerticalStackLayout Spacing="10">
<Grid ColumnDefinitions="*,Auto">
<VerticalStackLayout>
<Label
Text="{Binding DayText}"
FontAttributes="Bold"
FontSize="18"
TextColor="{DynamicResource TextPrimary}" />
<Label
Text="{Binding DateText}"
FontSize="13"
TextColor="{DynamicResource TextMuted}" />
<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>
</Grid>
<Grid ColumnDefinitions="*,*" ColumnSpacing="10">
<Border
Grid.Column="0"
BackgroundColor="{Binding MorningBackgroundColor}"
StrokeThickness="0"
StrokeShape="RoundRectangle 10"
Padding="10">
<Border.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding Source={x:Reference ThisPage}, Path=BindingContext.OpenDayCommand}"
CommandParameter="{Binding .}" />
</Border.GestureRecognizers>
<VerticalStackLayout>
<Label
Text="Vormittag"
FontAttributes="Bold"
TextColor="{Binding MorningTextColor}" />
<Label
Text="{Binding MorningText}"
FontSize="18"
TextColor="{Binding MorningTextColor}" />
<Label
Text="{Binding MorningCountText}"
FontSize="12"
TextColor="{Binding MorningTextColor}" />
</VerticalStackLayout>
</Border>
<Border
Grid.Column="1"
BackgroundColor="{Binding AfternoonBackgroundColor}"
StrokeThickness="0"
StrokeShape="RoundRectangle 10"
Padding="10">
<Border.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding Source={x:Reference ThisPage}, Path=BindingContext.OpenDayCommand}"
CommandParameter="{Binding .}" />
</Border.GestureRecognizers>
<VerticalStackLayout>
<Label
Text="Nachmittag"
FontAttributes="Bold"
TextColor="{Binding AfternoonTextColor}" />
<Label
Text="{Binding AfternoonText}"
FontSize="18"
TextColor="{Binding AfternoonTextColor}" />
<Label
Text="{Binding AfternoonCountText}"
FontSize="12"
TextColor="{Binding AfternoonTextColor}" />
</VerticalStackLayout>
</Border>
</Grid>
</VerticalStackLayout>
</Border>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</Grid>
</ContentPage>
</VerticalStackLayout>
</Border>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</VerticalStackLayout>
</ScrollView>
</ContentPage>
+15 -3
View File
@@ -1,8 +1,20 @@
using cfs_tracker.ViewModels;
namespace cfs_tracker.Views;
public partial class WeekPage : ContentPage
{
private readonly WeekViewModel _vm;
public WeekPage(WeekViewModel vm){ InitializeComponent(); BindingContext = _vm = vm; }
protected override async void OnAppearing(){ base.OnAppearing(); await _vm.RefreshAsync(); }
private readonly WeekViewModel _viewModel;
public WeekPage(WeekViewModel viewModel)
{
InitializeComponent();
BindingContext = _viewModel = viewModel;
}
protected override async void OnAppearing()
{
base.OnAppearing();
await _viewModel.RefreshAsync();
}
}
+102 -115
View File
@@ -1,128 +1,115 @@
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="cfs_tracker.Views.YearPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="ThisPage"
Title="Jahr">
<ContentPage x:Class="cfs_tracker.Views.YearPage"
x:Name="RootPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:cfs_tracker.ViewModels"
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">
<Button
Grid.Column="0"
Text="◀"
WidthRequest="52"
HeightRequest="44"
Command="{Binding PreviousYearCommand}" />
<Label
Grid.Column="1"
Text="{Binding SelectedYearText}"
HorizontalTextAlignment="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 ColumnDefinitions="Auto,*,Auto"
VerticalOptions="Center">
<Button Text="←"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding PreviousYearCommand}" />
<Label Grid.Column="1"
Text="{Binding HeaderText}"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<Button Grid.Column="2"
Text="→"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding NextYearCommand}" />
</Grid>
<ScrollView Grid.Row="1">
<VerticalStackLayout
Spacing="12"
BindableLayout.ItemsSource="{Binding Months}">
<Grid Grid.Row="1"
ColumnDefinitions="*,*"
ColumnSpacing="12">
<Button Text="Heute"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding TodayCommand}" />
<Button Grid.Column="1"
Text="Export"
Style="{StaticResource PrimaryButtonStyle}"
Command="{Binding ExportPdfCommand}" />
</Grid>
<BindableLayout.ItemTemplate>
<DataTemplate>
<Border
Padding="12"
BackgroundColor="{DynamicResource PanelBackground}"
Stroke="{DynamicResource PanelBorder}"
StrokeThickness="1"
StrokeShape="RoundRectangle 12">
<CollectionView Grid.Row="2"
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}" />
<VerticalStackLayout Spacing="10">
<Label
Text="{Binding MonthText}"
FontSize="20"
FontAttributes="Bold"
TextColor="{DynamicResource TextPrimary}" />
<HorizontalStackLayout Spacing="4">
<Label Text="Mo" WidthRequest="44" HorizontalTextAlignment="Center" FontSize="12" />
<Label Text="Di" WidthRequest="44" HorizontalTextAlignment="Center" FontSize="12" />
<Label Text="Mi" WidthRequest="44" HorizontalTextAlignment="Center" FontSize="12" />
<Label Text="Do" WidthRequest="44" HorizontalTextAlignment="Center" FontSize="12" />
<Label Text="Fr" WidthRequest="44" HorizontalTextAlignment="Center" FontSize="12" />
<Label Text="Sa" WidthRequest="44" HorizontalTextAlignment="Center" FontSize="12" />
<Label Text="So" WidthRequest="44" HorizontalTextAlignment="Center" FontSize="12" />
</HorizontalStackLayout>
<FlexLayout
Direction="Row"
Wrap="Wrap"
JustifyContent="Start"
AlignItems="Start"
BindableLayout.ItemsSource="{Binding Days}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Border
WidthRequest="44"
HeightRequest="44"
Margin="2"
BackgroundColor="{Binding BackgroundColor}"
<FlexLayout Direction="Row"
Wrap="Wrap"
AlignItems="Start"
JustifyContent="Start"
BindableLayout.ItemsSource="{Binding Cells}">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="viewModels:MonthCellViewModel">
<Border Margin="2"
Padding="4"
WidthRequest="46"
HeightRequest="46"
Stroke="{Binding BorderColor}"
StrokeThickness="1"
BackgroundColor="{DynamicResource SurfaceBackgroundAlt}"
StrokeShape="RoundRectangle 8">
<Border.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding Source={x:Reference RootPage}, Path=BindingContext.OpenDayCommand}"
CommandParameter="{Binding .}" />
</Border.GestureRecognizers>
<Grid Padding="4">
<Grid.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding Source={x:Reference ThisPage}, Path=BindingContext.OpenDayCommand}"
CommandParameter="{Binding .}" />
</Grid.GestureRecognizers>
<VerticalStackLayout
IsVisible="{Binding IsRealDay}"
Spacing="1">
<Label
Text="{Binding DayNumberText}"
TextColor="{Binding TextColor}"
FontSize="11"
FontAttributes="Bold"
HorizontalTextAlignment="Center" />
<Label
Text="{Binding CountText}"
TextColor="{Binding TextColor}"
FontSize="9"
HorizontalTextAlignment="Center" />
</VerticalStackLayout>
</Grid>
</Border>
</DataTemplate>
</BindableLayout.ItemTemplate>
</FlexLayout>
</VerticalStackLayout>
</Border>
</DataTemplate>
</BindableLayout.ItemTemplate>
</VerticalStackLayout>
</ScrollView>
<Grid RowDefinitions="Auto,*">
<Label Text="{Binding DayNumberText}"
FontSize="11"
FontAttributes="Bold"
HorizontalTextAlignment="Center"
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"
LineBreakMode="TailTruncation"
MaxLines="1"
HorizontalTextAlignment="Center"
TextColor="White" />
</Border>
</Grid>
</Border>
</DataTemplate>
</BindableLayout.ItemTemplate>
</FlexLayout>
</VerticalStackLayout>
</Border>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</Grid>
</ContentPage>
+27 -4
View File
@@ -1,8 +1,31 @@
using System.Diagnostics;
using cfs_tracker.ViewModels;
namespace cfs_tracker.Views;
public partial class YearPage : ContentPage
{
private readonly YearViewModel _vm;
public YearPage(YearViewModel vm){ InitializeComponent(); BindingContext = _vm = vm; }
protected override async void OnAppearing(){ base.OnAppearing(); await _vm.RefreshAsync(); }
}
private readonly YearViewModel _viewModel;
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>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
</PropertyGroup>
<PropertyGroup>
<MauiEnableXamlCBindingWithSourceCompilation>true</MauiEnableXamlCBindingWithSourceCompilation>
</PropertyGroup>
<ItemGroup>
<MauiIcon Include="Resources\AppIcon\appicon.svg" Color="#0B1620" />
<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.Extensions.Logging.Debug" Version="10.0.5" />
<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>
</Project>