diff --git a/App.xaml.cs b/App.xaml.cs index c5e5d92..80d03a7 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -45,6 +45,9 @@ public partial class App : Application { window.Page = shell; }); + + var navigator = _serviceProvider.GetRequiredService(); + await navigator.FlushAsync(); } catch (Exception ex) { @@ -56,7 +59,6 @@ public partial class App : Application }); } } - private static Page CreateLoadingPage() { return new ContentPage diff --git a/Data/AppDatabase.cs b/Data/AppDatabase.cs index 7607c49..83d493e 100644 --- a/Data/AppDatabase.cs +++ b/Data/AppDatabase.cs @@ -1,7 +1,6 @@ using cfs_tracker.Models; using cfs_tracker.Services; using SQLite; -using System.Threading; namespace cfs_tracker.Data; diff --git a/Data/HealthEntryRepository.cs b/Data/HealthEntryRepository.cs index 3c99d61..a487d65 100644 --- a/Data/HealthEntryRepository.cs +++ b/Data/HealthEntryRepository.cs @@ -16,6 +16,7 @@ public class HealthEntryRepository public async Task AddQuickEntryAsync( HealthState state, int? activityId = null, + int? activityDurationMinutes = null, IEnumerable? symptomIds = null, DateTime? timestamp = null, EntrySource source = EntrySource.App) @@ -23,6 +24,7 @@ public class HealthEntryRepository await _database.InitAsync(); var effectiveTimestamp = timestamp ?? DateTime.Now; + var entry = new HealthEntry { EntryDate = effectiveTimestamp.Date, @@ -31,12 +33,14 @@ public class HealthEntryRepository Source = source, DayPart = null, ActivityId = NormalizeActivityId(activityId), + ActivityDurationMinutes = NormalizeActivityDuration(activityDurationMinutes), CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now }; await _database.Connection.InsertAsync(entry); await _symptomRepository.SetSymptomsForEntryAsync(entry.Id, symptomIds); + return entry.Id; } @@ -45,12 +49,14 @@ public class HealthEntryRepository DayPart part = DayPart.Morning, HealthState state = HealthState.Gray, int? activityId = null, + int? activityDurationMinutes = null, IEnumerable? symptomIds = null, EntrySource source = EntrySource.Backfill) { await _database.InitAsync(); var slotTimestamp = BuildBackfillTimestamp(date, part); + var existing = await _database.Connection.Table() .FirstOrDefaultAsync(x => x.Timestamp == slotTimestamp); @@ -64,12 +70,14 @@ public class HealthEntryRepository Source = source, DayPart = part, ActivityId = NormalizeActivityId(activityId), + ActivityDurationMinutes = NormalizeActivityDuration(activityDurationMinutes), CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now }; await _database.Connection.InsertAsync(entry); await _symptomRepository.SetSymptomsForEntryAsync(entry.Id, symptomIds); + return entry.Id; } @@ -79,10 +87,12 @@ public class HealthEntryRepository existing.Source = source; existing.DayPart = part; existing.ActivityId = NormalizeActivityId(activityId); + existing.ActivityDurationMinutes = NormalizeActivityDuration(activityDurationMinutes); existing.UpdatedAt = DateTime.Now; await _database.Connection.UpdateAsync(existing); await _symptomRepository.SetSymptomsForEntryAsync(existing.Id, symptomIds); + return existing.Id; } @@ -91,6 +101,7 @@ public class HealthEntryRepository DateTime date, HealthState state, int? activityId = null, + int? activityDurationMinutes = null, IEnumerable? symptomIds = null, DayPart? part = null, EntrySource? source = null) @@ -103,16 +114,23 @@ public class HealthEntryRepository if (entry is null) return; + var originalTimestamp = entry.Timestamp; + entry.EntryDate = date.Date; entry.State = state; entry.ActivityId = NormalizeActivityId(activityId); + entry.ActivityDurationMinutes = NormalizeActivityDuration(activityDurationMinutes); 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; + } + else if (originalTimestamp.Date != date.Date) + { + entry.Timestamp = date.Date + originalTimestamp.TimeOfDay; + } entry.UpdatedAt = DateTime.Now; @@ -189,5 +207,12 @@ public class HealthEntryRepository }; private static int? NormalizeActivityId(int? activityId) => - activityId.HasValue && activityId.Value > 0 ? activityId : null; -} + activityId.HasValue && activityId.Value > 0 + ? activityId + : null; + + private static int? NormalizeActivityDuration(int? activityDurationMinutes) => + activityDurationMinutes.HasValue && activityDurationMinutes.Value > 0 + ? activityDurationMinutes + : null; +} \ No newline at end of file diff --git a/Data/NotificationScheduleRepository.cs b/Data/NotificationScheduleRepository.cs index 2942b36..7d84a56 100644 --- a/Data/NotificationScheduleRepository.cs +++ b/Data/NotificationScheduleRepository.cs @@ -15,31 +15,160 @@ public class NotificationScheduleRepository { await _database.InitAsync(); - return await _database.Connection.Table() - .OrderBy(x => x.DayOfWeekValue) - .ThenBy(x => x.Hour) - .ThenBy(x => x.Minute) + var list = await _database.Connection.Table() .ToListAsync(); + + return list + .OrderBy(x => x.Hour) + .ThenBy(x => x.Minute) + .ThenBy(x => x.Id) + .ToList(); } - public async Task ReplaceAllAsync(IEnumerable schedules) + public async Task GetByIdAsync(int id) { await _database.InitAsync(); - await _database.Connection.DeleteAllAsync(); - - 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 - }); - } + return await _database.Connection.Table() + .FirstOrDefaultAsync(x => x.Id == id); } -} + + public async Task AddAsync( + int weekdayMask, + int hour, + int minute, + bool isEnabled = true) + { + await _database.InitAsync(); + + var item = new NotificationSchedule + { + WeekdayMask = NormalizeWeekdayMask(weekdayMask), + Hour = NormalizeHour(hour), + Minute = NormalizeMinute(minute), + IsEnabled = isEnabled + }; + + await _database.Connection.InsertAsync(item); + return item.Id; + } + + public async Task SaveAsync(NotificationSchedule item) + { + await _database.InitAsync(); + + if (item is null) + return; + + item.WeekdayMask = NormalizeWeekdayMask(item.WeekdayMask); + item.Hour = NormalizeHour(item.Hour); + item.Minute = NormalizeMinute(item.Minute); + + if (item.Id <= 0) + { + await _database.Connection.InsertAsync(item); + return; + } + + var existing = await _database.Connection.Table() + .FirstOrDefaultAsync(x => x.Id == item.Id); + + if (existing is null) + { + await _database.Connection.InsertAsync(item); + return; + } + + existing.WeekdayMask = item.WeekdayMask; + existing.Hour = item.Hour; + existing.Minute = item.Minute; + existing.IsEnabled = item.IsEnabled; + + await _database.Connection.UpdateAsync(existing); + } + + public async Task DeleteAsync(int id) + { + await _database.InitAsync(); + + var existing = await _database.Connection.Table() + .FirstOrDefaultAsync(x => x.Id == id); + + if (existing is not null) + await _database.Connection.DeleteAsync(existing); + } + + public async Task DeleteAllAsync() + { + await _database.InitAsync(); + await _database.Connection.DeleteAllAsync(); + } + + public async Task ReplaceAllAsync(IEnumerable? items) + { + await _database.InitAsync(); + + var normalized = (items ?? Enumerable.Empty()) + .Select(x => new NotificationSchedule + { + Id = x.Id, + WeekdayMask = NormalizeWeekdayMask(x.WeekdayMask), + Hour = NormalizeHour(x.Hour), + Minute = NormalizeMinute(x.Minute), + IsEnabled = x.IsEnabled + }) + .Where(x => x.WeekdayMask != 0) + .OrderBy(x => x.Hour) + .ThenBy(x => x.Minute) + .ThenBy(x => x.Id) + .ToList(); + + await _database.Connection.RunInTransactionAsync(connection => + { + connection.DeleteAll(); + + foreach (var item in normalized) + { + item.Id = 0; + connection.Insert(item); + } + }); + } + + private static int NormalizeWeekdayMask(int mask) + { + const int allDaysMask = + (int)( + NotificationWeekdays.Monday | + NotificationWeekdays.Tuesday | + NotificationWeekdays.Wednesday | + NotificationWeekdays.Thursday | + NotificationWeekdays.Friday | + NotificationWeekdays.Saturday | + NotificationWeekdays.Sunday); + + return mask & allDaysMask; + } + + private static int NormalizeHour(int hour) + { + if (hour < 0) + return 0; + + if (hour > 23) + return 23; + + return hour; + } + + private static int NormalizeMinute(int minute) + { + if (minute < 0) + return 0; + + if (minute > 59) + return 59; + + return minute; + } +} \ No newline at end of file diff --git a/Data/SymptomRepository.cs b/Data/SymptomRepository.cs index e8c0b38..d5e1f2f 100644 --- a/Data/SymptomRepository.cs +++ b/Data/SymptomRepository.cs @@ -1,5 +1,4 @@ using cfs_tracker.Models; -using System.Linq; namespace cfs_tracker.Data; diff --git a/Helpers/ColorUtility.cs b/Helpers/ColorUtility.cs index 8526a76..d5dec6e 100644 --- a/Helpers/ColorUtility.cs +++ b/Helpers/ColorUtility.cs @@ -1,5 +1,3 @@ -using Microsoft.Maui.Graphics; - namespace cfs_tracker.Helpers; public static class ColorUtility diff --git a/Helpers/NotificationWeekdayHelper.cs b/Helpers/NotificationWeekdayHelper.cs new file mode 100644 index 0000000..ca1967d --- /dev/null +++ b/Helpers/NotificationWeekdayHelper.cs @@ -0,0 +1,24 @@ +using cfs_tracker.Models; + +namespace cfs_tracker.Helpers; + +public static class NotificationWeekdayHelper +{ + public static NotificationWeekdays ToFlag(DayOfWeek day) => day switch + { + DayOfWeek.Monday => NotificationWeekdays.Monday, + DayOfWeek.Tuesday => NotificationWeekdays.Tuesday, + DayOfWeek.Wednesday => NotificationWeekdays.Wednesday, + DayOfWeek.Thursday => NotificationWeekdays.Thursday, + DayOfWeek.Friday => NotificationWeekdays.Friday, + DayOfWeek.Saturday => NotificationWeekdays.Saturday, + DayOfWeek.Sunday => NotificationWeekdays.Sunday, + _ => NotificationWeekdays.None + }; + + public static bool ContainsDay(int mask, DayOfWeek day) + { + var flags = (NotificationWeekdays)mask; + return (flags & ToFlag(day)) != 0; + } +} \ No newline at end of file diff --git a/MauiProgram.cs b/MauiProgram.cs index 6f947ab..67a3a61 100644 --- a/MauiProgram.cs +++ b/MauiProgram.cs @@ -2,9 +2,9 @@ using cfs_tracker.Data; using cfs_tracker.Services; using cfs_tracker.ViewModels; using cfs_tracker.Views; -using Microsoft.Extensions.Logging; using SQLitePCL; using System.Text; +using Microsoft.Extensions.Logging; namespace cfs_tracker; @@ -41,9 +41,16 @@ public static class MauiProgram builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); +#if ANDROID + builder.Services.AddSingleton(); +#elif WINDOWS + builder.Services.AddSingleton(); +#else builder.Services.AddSingleton(); +#endif builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); // Shell / Pages builder.Services.AddSingleton(); diff --git a/Models/HealthEntry.cs b/Models/HealthEntry.cs index b4fe18d..a0f49f3 100644 --- a/Models/HealthEntry.cs +++ b/Models/HealthEntry.cs @@ -25,6 +25,7 @@ public class HealthEntry [Indexed] public int? ActivityId { get; set; } + public int? ActivityDurationMinutes { get; set; } public DateTime CreatedAt { get; set; } diff --git a/Models/NotificationSchedule.cs b/Models/NotificationSchedule.cs index ad811f4..1d49c7e 100644 --- a/Models/NotificationSchedule.cs +++ b/Models/NotificationSchedule.cs @@ -2,24 +2,16 @@ 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 WeekdayMask { 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; - } -} + public bool IsEnabled { get; set; } +} \ No newline at end of file diff --git a/Models/NotificationWeekdays.cs b/Models/NotificationWeekdays.cs new file mode 100644 index 0000000..162be2c --- /dev/null +++ b/Models/NotificationWeekdays.cs @@ -0,0 +1,14 @@ +namespace cfs_tracker.Models; + +[Flags] +public enum NotificationWeekdays +{ + None = 0, + Monday = 1 << 0, + Tuesday = 1 << 1, + Wednesday = 1 << 2, + Thursday = 1 << 3, + Friday = 1 << 4, + Saturday = 1 << 5, + Sunday = 1 << 6 +} \ No newline at end of file diff --git a/Platforms/Android/AndroidManifest.xml b/Platforms/Android/AndroidManifest.xml index e9937ad..d1ba07f 100644 --- a/Platforms/Android/AndroidManifest.xml +++ b/Platforms/Android/AndroidManifest.xml @@ -1,6 +1,7 @@  - + + \ No newline at end of file diff --git a/Platforms/Android/AndroidNotificationScheduler.cs b/Platforms/Android/AndroidNotificationScheduler.cs new file mode 100644 index 0000000..b8868e5 --- /dev/null +++ b/Platforms/Android/AndroidNotificationScheduler.cs @@ -0,0 +1,297 @@ +using Android.App; +using Android.Content; +using AndroidX.Core.App; +using cfs_tracker.Data; +using cfs_tracker.Helpers; +using cfs_tracker.Models; +using cfs_tracker.Services; + +namespace cfs_tracker.Platforms.Android; + +public sealed class AndroidNotificationScheduler : INotificationScheduler +{ + private const string ChannelId = "cfs_tracker_reminders"; + private const string ChannelName = "Erinnerungen"; + private const string ChannelDescription = "Wie geht es dir? Erinnerungen"; + private const string PrefScheduledIds = "notification_schedule_ids"; + + private const string PrefYellowLabel = "notification_label_yellow"; + private const string PrefRedLabel = "notification_label_red"; + private const string PrefGrayLabel = "notification_label_gray"; + + public const string ExtraScheduleId = "schedule_id"; + public const string ExtraDayOfWeek = "day_of_week"; + public const string ExtraHour = "hour"; + public const string ExtraMinute = "minute"; + + public const string ExtraRoute = "route"; + public const string ExtraDate = "date"; + public const string ExtraStatus = "status"; + public const string ExtraCommit = "commit"; + + private readonly NotificationScheduleRepository _notificationScheduleRepository; + private readonly AppearanceService _appearanceService; + + public AndroidNotificationScheduler( + NotificationScheduleRepository notificationScheduleRepository, + AppearanceService appearanceService) + { + _notificationScheduleRepository = notificationScheduleRepository; + _appearanceService = appearanceService; + } + + public async Task EnsurePermissionAsync() + { + var permission = await Permissions.RequestAsync(); + return permission == PermissionStatus.Granted; + } + + public async Task SyncAsync() + { + var context = Platform.AppContext; + EnsureChannel(context); + + var granted = await EnsurePermissionAsync(); + if (!granted) + return; + + SaveActionLabelsToPreferences(); + CancelAllScheduled(context); + + var schedules = await _notificationScheduleRepository.GetAllAsync(); + var requestKeys = new List(); + + foreach (var item in schedules.Where(x => x.IsEnabled && x.WeekdayMask != 0)) + { + foreach (var day in GetScheduledDays(item.WeekdayMask)) + { + ScheduleNextAlarm(context, item.Id, day, item.Hour, item.Minute); + requestKeys.Add($"{item.Id}:{(int)day}"); + } + } + + Preferences.Default.Set(PrefScheduledIds, string.Join(",", requestKeys)); + } + + private void SaveActionLabelsToPreferences() + { + Preferences.Default.Set( + PrefYellowLabel, + _appearanceService.GetText(AppearanceKeys.StatusYellowText, "Gelb")); + + Preferences.Default.Set( + PrefRedLabel, + _appearanceService.GetText(AppearanceKeys.StatusRedText, "Rot")); + + Preferences.Default.Set( + PrefGrayLabel, + _appearanceService.GetText(AppearanceKeys.StatusGrayText, "Schwarz")); + } + + internal static void ScheduleNextAlarm( + Context context, + int scheduleId, + DayOfWeek dayOfWeek, + int hour, + int minute) + { + var triggerAt = ComputeNextOccurrence(dayOfWeek, hour, minute); + var alarmManager = (AlarmManager?)context.GetSystemService(Context.AlarmService); + if (alarmManager is null) + return; + + var intent = new Intent(context, typeof(CfsNotificationReceiver)); + intent.PutExtra(ExtraScheduleId, scheduleId); + intent.PutExtra(ExtraDayOfWeek, (int)dayOfWeek); + intent.PutExtra(ExtraHour, hour); + intent.PutExtra(ExtraMinute, minute); + + var requestCode = BuildAlarmRequestCode(scheduleId, dayOfWeek); + + var pendingIntent = PendingIntent.GetBroadcast( + context, + requestCode, + intent, + BuildPendingIntentFlags()); + + var when = triggerAt.ToUnixTimeMilliseconds(); + + if (OperatingSystem.IsAndroidVersionAtLeast(23)) + alarmManager.SetAndAllowWhileIdle(AlarmType.RtcWakeup, when, pendingIntent); + else + alarmManager.Set(AlarmType.RtcWakeup, when, pendingIntent); + } + + internal static void ShowNotification( + Context context, + int scheduleId, + string title, + string message) + { + EnsureChannel(context); + + var today = DateTime.Today.ToString("yyyy-MM-dd"); + + var openQuickEntryIntent = BuildLaunchIntent(context, today, null, false); + var yellowIntent = BuildLaunchIntent(context, today, "yellow", true); + var redIntent = BuildLaunchIntent(context, today, "red", true); + var grayIntent = BuildLaunchIntent(context, today, "gray", true); + + var openPendingIntent = PendingIntent.GetActivity( + context, + scheduleId * 10 + 1, + openQuickEntryIntent, + BuildPendingIntentFlags()); + + var yellowPendingIntent = PendingIntent.GetActivity( + context, + scheduleId * 10 + 2, + yellowIntent, + BuildPendingIntentFlags()); + + var redPendingIntent = PendingIntent.GetActivity( + context, + scheduleId * 10 + 3, + redIntent, + BuildPendingIntentFlags()); + + var grayPendingIntent = PendingIntent.GetActivity( + context, + scheduleId * 10 + 4, + grayIntent, + BuildPendingIntentFlags()); + + var yellowLabel = Preferences.Default.Get(PrefYellowLabel, "Gelb"); + var redLabel = Preferences.Default.Get(PrefRedLabel, "Rot"); + var grayLabel = Preferences.Default.Get(PrefGrayLabel, "Schwarz"); + + var smallIcon = context.ApplicationInfo?.Icon ?? global::Android.Resource.Drawable.IcDialogInfo; + + var builder = new NotificationCompat.Builder(context, ChannelId) + .SetSmallIcon(smallIcon) + .SetContentTitle(title) + .SetContentText(message) + .SetPriority((int)NotificationPriority.High) + .SetAutoCancel(true) + .SetContentIntent(openPendingIntent) + .AddAction(0, yellowLabel, yellowPendingIntent) + .AddAction(0, redLabel, redPendingIntent) + .AddAction(0, grayLabel, grayPendingIntent); + + NotificationManagerCompat.From(context).Notify(scheduleId, builder.Build()); + } + + private static Intent BuildLaunchIntent(Context context, string date, string? status, bool commit) + { + var launchIntent = context.PackageManager?.GetLaunchIntentForPackage(context.PackageName) + ?? new Intent(context, typeof(MainActivity)); + + launchIntent.AddFlags(ActivityFlags.SingleTop | ActivityFlags.ClearTop | ActivityFlags.NewTask); + launchIntent.PutExtra(ExtraRoute, "quickentry"); + launchIntent.PutExtra(ExtraDate, date); + + if (!string.IsNullOrWhiteSpace(status)) + launchIntent.PutExtra(ExtraStatus, status); + + launchIntent.PutExtra(ExtraCommit, commit); + + return launchIntent; + } + + internal static void EnsureChannel(Context context) + { + if (!OperatingSystem.IsAndroidVersionAtLeast(26)) + return; + + var manager = (NotificationManager?)context.GetSystemService(Context.NotificationService); + if (manager is null) + return; + + var channel = new NotificationChannel(ChannelId, ChannelName, NotificationImportance.Default) + { + Description = ChannelDescription + }; + + manager.CreateNotificationChannel(channel); + } + + private void CancelAllScheduled(Context context) + { + var stored = Preferences.Default.Get(PrefScheduledIds, string.Empty); + if (string.IsNullOrWhiteSpace(stored)) + return; + + var alarmManager = (AlarmManager?)context.GetSystemService(Context.AlarmService); + if (alarmManager is null) + return; + + foreach (var raw in stored.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + var parts = raw.Split(':', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + if (parts.Length != 2) + continue; + + if (!int.TryParse(parts[0], out var scheduleId)) + continue; + + if (!int.TryParse(parts[1], out var dayValue)) + continue; + + var day = (DayOfWeek)dayValue; + var requestCode = BuildAlarmRequestCode(scheduleId, day); + + var intent = new Intent(context, typeof(CfsNotificationReceiver)); + var pendingIntent = PendingIntent.GetBroadcast( + context, + requestCode, + intent, + BuildPendingIntentFlags()); + + alarmManager.Cancel(pendingIntent); + NotificationManagerCompat.From(context).Cancel(scheduleId); + } + + Preferences.Default.Remove(PrefScheduledIds); + } + + private static PendingIntentFlags BuildPendingIntentFlags() + { + var flags = PendingIntentFlags.UpdateCurrent; + if (OperatingSystem.IsAndroidVersionAtLeast(23)) + flags |= PendingIntentFlags.Immutable; + + return flags; + } + + private static DateTimeOffset ComputeNextOccurrence(DayOfWeek targetDay, int hour, int minute) + { + var now = DateTimeOffset.Now; + var todayAtTime = new DateTimeOffset(now.Year, now.Month, now.Day, hour, minute, 0, now.Offset); + + var days = ((int)targetDay - (int)now.DayOfWeek + 7) % 7; + var target = todayAtTime.AddDays(days); + + if (target <= now) + target = target.AddDays(7); + + return target; + } + + private static int BuildAlarmRequestCode(int scheduleId, DayOfWeek day) + { + return scheduleId * 10 + (int)day; + } + + private static IEnumerable GetScheduledDays(int mask) + { + var flags = (NotificationWeekdays)mask; + + if (flags.HasFlag(NotificationWeekdays.Monday)) yield return DayOfWeek.Monday; + if (flags.HasFlag(NotificationWeekdays.Tuesday)) yield return DayOfWeek.Tuesday; + if (flags.HasFlag(NotificationWeekdays.Wednesday)) yield return DayOfWeek.Wednesday; + if (flags.HasFlag(NotificationWeekdays.Thursday)) yield return DayOfWeek.Thursday; + if (flags.HasFlag(NotificationWeekdays.Friday)) yield return DayOfWeek.Friday; + if (flags.HasFlag(NotificationWeekdays.Saturday)) yield return DayOfWeek.Saturday; + if (flags.HasFlag(NotificationWeekdays.Sunday)) yield return DayOfWeek.Sunday; + } +} \ No newline at end of file diff --git a/Platforms/Android/CfsNotificationReceiver.cs b/Platforms/Android/CfsNotificationReceiver.cs new file mode 100644 index 0000000..0fcb10f --- /dev/null +++ b/Platforms/Android/CfsNotificationReceiver.cs @@ -0,0 +1,31 @@ +using Android.Content; + +namespace cfs_tracker.Platforms.Android; + +[BroadcastReceiver(Enabled = true, Exported = false)] +public sealed class CfsNotificationReceiver : BroadcastReceiver +{ + public override void OnReceive(Context? context, Intent? intent) + { + if (context is null || intent is null) + return; + + var scheduleId = intent.GetIntExtra(AndroidNotificationScheduler.ExtraScheduleId, 0); + var dayOfWeek = (DayOfWeek)intent.GetIntExtra(AndroidNotificationScheduler.ExtraDayOfWeek, (int)DayOfWeek.Monday); + var hour = intent.GetIntExtra(AndroidNotificationScheduler.ExtraHour, 9); + var minute = intent.GetIntExtra(AndroidNotificationScheduler.ExtraMinute, 0); + + AndroidNotificationScheduler.ShowNotification( + context, + scheduleId, + "Wie geht es dir?", + "Tippe, um deinen Status einzutragen."); + + AndroidNotificationScheduler.ScheduleNextAlarm( + context, + scheduleId, + dayOfWeek, + hour, + minute); + } +} \ No newline at end of file diff --git a/Platforms/Android/MainActivity.cs b/Platforms/Android/MainActivity.cs index 43607f9..a3b17f9 100644 --- a/Platforms/Android/MainActivity.cs +++ b/Platforms/Android/MainActivity.cs @@ -1,9 +1,57 @@ using Android.App; using Android.Content.PM; using Android.OS; +using cfs_tracker.Services; + namespace cfs_tracker; -[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)] + +[Activity( + Theme = "@style/Maui.SplashTheme", + MainLauncher = true, + LaunchMode = LaunchMode.SingleTop, + ConfigurationChanges = ConfigChanges.ScreenSize + | ConfigChanges.Orientation + | ConfigChanges.UiMode + | ConfigChanges.ScreenLayout + | ConfigChanges.SmallestScreenSize + | ConfigChanges.Density)] public class MainActivity : MauiAppCompatActivity { - protected override void OnCreate(Bundle? savedInstanceState){ base.OnCreate(savedInstanceState); } -} + protected override void OnCreate(Bundle? savedInstanceState) + { + base.OnCreate(savedInstanceState); + HandleNotificationIntent(Intent); + } + + protected override void OnNewIntent(Android.Content.Intent? intent) + { + base.OnNewIntent(intent); + if (intent is not null) + HandleNotificationIntent(intent); + } + + private static void HandleNotificationIntent(Android.Content.Intent? intent) + { + if (intent is null) + return; + + var route = intent.GetStringExtra(Platforms.Android.AndroidNotificationScheduler.ExtraRoute); + if (!string.Equals(route, "quickentry", StringComparison.OrdinalIgnoreCase)) + return; + + var dateText = intent.GetStringExtra(Platforms.Android.AndroidNotificationScheduler.ExtraDate); + var status = intent.GetStringExtra(Platforms.Android.AndroidNotificationScheduler.ExtraStatus); + var commit = intent.GetBooleanExtra(Platforms.Android.AndroidNotificationScheduler.ExtraCommit, false); + + if (!DateTime.TryParse(dateText, out var date)) + date = DateTime.Today; + + var services = IPlatformApplication.Current?.Services; + var navigator = services?.GetService(typeof(NotificationNavigationService)) as NotificationNavigationService; + if (navigator is null) + return; + + navigator.QueueQuickEntry(date, status, commit); + _ = navigator.FlushAsync(); + } +} \ No newline at end of file diff --git a/Platforms/Android/NotificationPermission.cs b/Platforms/Android/NotificationPermission.cs new file mode 100644 index 0000000..e99997c --- /dev/null +++ b/Platforms/Android/NotificationPermission.cs @@ -0,0 +1,19 @@ +using Android; + +namespace cfs_tracker.Platforms.Android; + +public class NotificationPermission : Permissions.BasePlatformPermission +{ + public override (string androidPermission, bool isRuntime)[] RequiredPermissions + { + get + { + var result = new List<(string androidPermission, bool isRuntime)>(); + + if (OperatingSystem.IsAndroidVersionAtLeast(33)) + result.Add((Manifest.Permission.PostNotifications, true)); + + return result.ToArray(); + } + } +} \ No newline at end of file diff --git a/Platforms/Windows/App.xaml.cs b/Platforms/Windows/App.xaml.cs index 82caca3..3df2161 100644 --- a/Platforms/Windows/App.xaml.cs +++ b/Platforms/Windows/App.xaml.cs @@ -1,5 +1,4 @@ -using Microsoft.UI.Xaml; -using System.Diagnostics; +using System.Diagnostics; namespace cfs_tracker.WinUI; diff --git a/Platforms/Windows/WindowsNotificationScheduler.cs b/Platforms/Windows/WindowsNotificationScheduler.cs new file mode 100644 index 0000000..e1932a8 --- /dev/null +++ b/Platforms/Windows/WindowsNotificationScheduler.cs @@ -0,0 +1,112 @@ +using cfs_tracker.Data; +using cfs_tracker.Models; +using cfs_tracker.Services; +using Microsoft.Toolkit.Uwp.Notifications; +using Windows.UI.Notifications; + +namespace cfs_tracker.Platforms.Windows; + +public sealed class WindowsNotificationScheduler : INotificationScheduler +{ + private const string GroupName = "cfs_tracker_weekly"; + private readonly NotificationScheduleRepository _notificationScheduleRepository; + + public WindowsNotificationScheduler(NotificationScheduleRepository notificationScheduleRepository) + { + _notificationScheduleRepository = notificationScheduleRepository; + } + + public Task EnsurePermissionAsync() + { + return Task.FromResult(true); + } + + public async Task SyncAsync() + { + try + { + CancelExisting(); + + var schedules = await _notificationScheduleRepository.GetAllAsync(); + var notifier = ToastNotificationManagerCompat.CreateToastNotifier(); + + foreach (var item in schedules.Where(x => x.IsEnabled && x.WeekdayMask != 0)) + { + foreach (var day in GetScheduledDays(item.WeekdayMask)) + { + var when = ComputeNextOccurrence(day, item.Hour, item.Minute); + + var content = new ToastContentBuilder() + .AddArgument("route", "day") + .AddText("Wie geht es dir?") + .AddText("Tippe, um deinen Status einzutragen.") + .GetToastContent(); + + var scheduled = new ScheduledToastNotification(content.GetXml(), when) + { + Tag = BuildTag(item.Id, day), + Group = GroupName + }; + + notifier.AddToSchedule(scheduled); + } + } + } + catch + { + // Windows darf hier still ins Leere laufen. + } + } + + private static string BuildTag(int id, DayOfWeek day) => $"schedule-{id}-{(int)day}"; + + private static DateTimeOffset ComputeNextOccurrence(DayOfWeek targetDay, int hour, int minute) + { + var now = DateTimeOffset.Now; + var todayAtTime = new DateTimeOffset( + now.Year, + now.Month, + now.Day, + hour, + minute, + 0, + now.Offset); + + var days = ((int)targetDay - (int)now.DayOfWeek + 7) % 7; + var target = todayAtTime.AddDays(days); + + if (target <= now) + target = target.AddDays(7); + + return target; + } + + private static void CancelExisting() + { + try + { + var notifier = ToastNotificationManagerCompat.CreateToastNotifier(); + var scheduled = notifier.GetScheduledToastNotifications(); + + foreach (var toast in scheduled.Where(x => x.Group == GroupName).ToList()) + notifier.RemoveFromSchedule(toast); + } + catch + { + // bewusst no-op + } + } + + private static IEnumerable GetScheduledDays(int mask) + { + var flags = (NotificationWeekdays)mask; + + if (flags.HasFlag(NotificationWeekdays.Monday)) yield return DayOfWeek.Monday; + if (flags.HasFlag(NotificationWeekdays.Tuesday)) yield return DayOfWeek.Tuesday; + if (flags.HasFlag(NotificationWeekdays.Wednesday)) yield return DayOfWeek.Wednesday; + if (flags.HasFlag(NotificationWeekdays.Thursday)) yield return DayOfWeek.Thursday; + if (flags.HasFlag(NotificationWeekdays.Friday)) yield return DayOfWeek.Friday; + if (flags.HasFlag(NotificationWeekdays.Saturday)) yield return DayOfWeek.Saturday; + if (flags.HasFlag(NotificationWeekdays.Sunday)) yield return DayOfWeek.Sunday; + } +} \ No newline at end of file diff --git a/Services/AppearanceService.cs b/Services/AppearanceService.cs index 6f014bd..c4e54d3 100644 --- a/Services/AppearanceService.cs +++ b/Services/AppearanceService.cs @@ -1,7 +1,5 @@ using cfs_tracker.Data; using cfs_tracker.Helpers; -using Microsoft.Maui.Controls; -using Microsoft.Maui.Graphics; namespace cfs_tracker.Services; diff --git a/Services/DatabaseLocationService.cs b/Services/DatabaseLocationService.cs index 46d8186..b3f8c1e 100644 --- a/Services/DatabaseLocationService.cs +++ b/Services/DatabaseLocationService.cs @@ -1,5 +1,3 @@ -using Microsoft.Maui.Storage; - namespace cfs_tracker.Services; public class DatabaseLocationService diff --git a/Services/ExportUiHelper.cs b/Services/ExportUiHelper.cs index fad8e40..af19bfa 100644 --- a/Services/ExportUiHelper.cs +++ b/Services/ExportUiHelper.cs @@ -1,6 +1,4 @@ -using Microsoft.Maui.ApplicationModel; - -namespace cfs_tracker.Services; +namespace cfs_tracker.Services; public static class ExportUiHelper { diff --git a/Services/INotificationScheduler.cs b/Services/INotificationScheduler.cs index ed11a46..69032b7 100644 --- a/Services/INotificationScheduler.cs +++ b/Services/INotificationScheduler.cs @@ -2,5 +2,6 @@ namespace cfs_tracker.Services; public interface INotificationScheduler { - Task SyncAsync(CancellationToken cancellationToken = default); + Task EnsurePermissionAsync(); + Task SyncAsync(); } \ No newline at end of file diff --git a/Services/NoOpNotificationScheduler.cs b/Services/NoOpNotificationScheduler.cs index 56b2187..8666cf1 100644 --- a/Services/NoOpNotificationScheduler.cs +++ b/Services/NoOpNotificationScheduler.cs @@ -2,8 +2,6 @@ namespace cfs_tracker.Services; public sealed class NoOpNotificationScheduler : INotificationScheduler { - public Task SyncAsync(CancellationToken cancellationToken = default) - { - return Task.CompletedTask; - } + public Task EnsurePermissionAsync() => Task.FromResult(true); + public Task SyncAsync() => Task.CompletedTask; } \ No newline at end of file diff --git a/Services/NotificationNavigationService.cs b/Services/NotificationNavigationService.cs new file mode 100644 index 0000000..8188241 --- /dev/null +++ b/Services/NotificationNavigationService.cs @@ -0,0 +1,41 @@ +using cfs_tracker.Views; + +namespace cfs_tracker.Services; + +public sealed class NotificationNavigationService +{ + private string? _pendingDate; + private string? _pendingStatus; + private bool _pendingCommit; + + public void QueueQuickEntry(DateTime date, string? status = null, bool commit = false) + { + _pendingDate = date.ToString("yyyy-MM-dd"); + _pendingStatus = status; + _pendingCommit = commit; + } + + public async Task FlushAsync() + { + if (Shell.Current is null || string.IsNullOrWhiteSpace(_pendingDate)) + return; + + var date = _pendingDate; + var status = _pendingStatus; + var commit = _pendingCommit; + + _pendingDate = null; + _pendingStatus = null; + _pendingCommit = false; + + var route = $"{nameof(QuickEntryPage)}?date={Uri.EscapeDataString(date)}"; + + if (!string.IsNullOrWhiteSpace(status)) + route += $"&status={Uri.EscapeDataString(status)}"; + + if (commit) + route += "&commit=true"; + + await MainThread.InvokeOnMainThreadAsync(() => Shell.Current.GoToAsync(route)); + } +} \ No newline at end of file diff --git a/Services/PdfExportService.cs b/Services/PdfExportService.cs index d1e6d5e..806aa2f 100644 --- a/Services/PdfExportService.cs +++ b/Services/PdfExportService.cs @@ -1,8 +1,6 @@ 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; @@ -47,16 +45,21 @@ public sealed class PdfExportService : IPdfExportService var entries = await _healthEntryRepository.GetEntriesForDateAsync(date); var activityNames = await GetActivityNamesAsync(); var symptomNamesByEntry = await GetSymptomNamesByEntryAsync(entries.Select(x => x.Id)); + var conflicts = DetectDayExportConflicts(entries); var sb = new StringBuilder(); sb.AppendLine($"

Tagesübersicht – {Encode(date.ToString("dd.MM.yyyy"))}

"); + + if (conflicts.Count > 0) + sb.AppendLine(BuildConflictHtml(conflicts)); + sb.AppendLine(""); - sb.AppendLine(""); + sb.AppendLine(""); sb.AppendLine(""); foreach (var entry in entries.OrderBy(x => x.Timestamp).ThenBy(x => x.Id)) { - var symptoms = symptomNamesByEntry.TryGetValue(entry.Id, out var symptomList) + var symptoms = symptomNamesByEntry.TryGetValue(entry.Id, out var symptomList) && symptomList.Count > 0 ? string.Join(", ", symptomList) : "—"; @@ -65,15 +68,16 @@ public sealed class PdfExportService : IPdfExportService : "—"; sb.AppendLine(""); - sb.AppendLine($""); + sb.AppendLine($""); sb.AppendLine(StateCell(entry.State, GetStateText(entry.State))); sb.AppendLine($""); + sb.AppendLine($""); sb.AppendLine($""); sb.AppendLine(""); } if (entries.Count == 0) - sb.AppendLine(""); + sb.AppendLine(""); sb.AppendLine("
UhrzeitStatusTätigkeitSymptome
ZeitStatusTätigkeitDauerSymptome
{Encode(entry.Timestamp.ToString("HH:mm"))}{Encode(GetDayTimeLabel(entry))}{Encode(activity)}{Encode(FormatDuration(entry.ActivityDurationMinutes))}{Encode(symptoms)}
Keine Einträge vorhanden.
Keine Einträge vorhanden.
"); @@ -310,6 +314,7 @@ public sealed class PdfExportService : IPdfExportService .Distinct() .ToList()); } + private async Task SaveHtmlAsync( string fileName, string title, @@ -319,17 +324,20 @@ public sealed class PdfExportService : IPdfExportService var folder = GetExportFolderPath(); Directory.CreateDirectory(folder); - var path = Path.Combine(folder, fileName); - var html = WrapHtml(title, bodyHtml, compactA4); + var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); + var extension = Path.GetExtension(fileName); + var path = GetUniqueFilePath(folder, fileNameWithoutExtension, extension); + var html = WrapHtml(title, bodyHtml, compactA4); await File.WriteAllTextAsync(path, html, Encoding.UTF8); return new ExportResult { FilePath = path, - FileName = fileName + FileName = Path.GetFileName(path) }; } + private string StateCell(HealthState state, string text) { var background = GetStateBackgroundCss(state); @@ -436,8 +444,6 @@ public sealed class PdfExportService : IPdfExportService } catch { - // absichtlich ignorieren, damit eine einzelne blockierte Datei - // nicht den ganzen Vorgang abbricht } } @@ -514,6 +520,18 @@ public sealed class PdfExportService : IPdfExportService .compact-symptoms { width: 32%; } + + .conflict-box { + border: 1px solid #000000; + background: #fff8e1; + padding: {{(compactA4 ? "6px" : "10px")}}; + margin-bottom: {{(compactA4 ? "8px" : "14px")}}; + } + + .conflict-box ul { + margin: 6px 0 0 18px; + padding: 0; + } @@ -521,4 +539,83 @@ public sealed class PdfExportService : IPdfExportService """; + + private static string GetUniqueFilePath(string directory, string fileNameWithoutExtension, string extension) + { + Directory.CreateDirectory(directory); + + var safeExtension = string.IsNullOrWhiteSpace(extension) + ? ".html" + : (extension.StartsWith('.') ? extension : "." + extension); + + var basePath = Path.Combine(directory, fileNameWithoutExtension + safeExtension); + if (!File.Exists(basePath)) + return basePath; + + var counter = 1; + while (true) + { + var candidate = Path.Combine(directory, $"{fileNameWithoutExtension} ({counter}){safeExtension}"); + if (!File.Exists(candidate)) + return candidate; + + counter++; + } + } + + private static string GetDayTimeLabel(HealthEntry entry) + { + if (entry.DayPart == DayPart.Morning) + return "Vormittag"; + + if (entry.DayPart == DayPart.Afternoon) + return "Nachmittag"; + + return entry.Timestamp.ToString("HH:mm"); + } + + private static string FormatDuration(int? durationMinutes) + { + if (!durationMinutes.HasValue || durationMinutes.Value <= 0) + return "—"; + + var duration = TimeSpan.FromMinutes(durationMinutes.Value); + return duration.ToString(@"hh\:mm"); + } + + private static List DetectDayExportConflicts(IEnumerable entries) + { + var result = new List(); + + var morningCount = entries.Count(x => x.DayPart == DayPart.Morning); + var afternoonCount = entries.Count(x => x.DayPart == DayPart.Afternoon); + + if (morningCount > 1) + result.Add("Mehrere Vormittag-Einträge gefunden."); + + if (afternoonCount > 1) + result.Add("Mehrere Nachmittag-Einträge gefunden."); + + return result; + } + + private static string BuildConflictHtml(IEnumerable conflicts) + { + var list = conflicts.ToList(); + if (list.Count == 0) + return string.Empty; + + var sb = new StringBuilder(); + sb.AppendLine("
"); + sb.AppendLine("Hinweis auf mögliche Konflikte:"); + sb.AppendLine("
    "); + + foreach (var item in list) + sb.AppendLine($"
  • {Encode(item)}
  • "); + + sb.AppendLine("
"); + sb.AppendLine("
"); + + return sb.ToString(); + } } \ No newline at end of file diff --git a/ViewModels/AppearanceColorItemViewModel.cs b/ViewModels/AppearanceColorItemViewModel.cs index 924dcb5..50495e9 100644 --- a/ViewModels/AppearanceColorItemViewModel.cs +++ b/ViewModels/AppearanceColorItemViewModel.cs @@ -1,6 +1,5 @@ -using CommunityToolkit.Mvvm.ComponentModel; using cfs_tracker.Helpers; -using Microsoft.Maui.Graphics; +using CommunityToolkit.Mvvm.ComponentModel; namespace cfs_tracker.ViewModels; diff --git a/ViewModels/DayEntryItemViewModel.cs b/ViewModels/DayEntryItemViewModel.cs index 88eeb16..a5a22e0 100644 --- a/ViewModels/DayEntryItemViewModel.cs +++ b/ViewModels/DayEntryItemViewModel.cs @@ -1,6 +1,5 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using Microsoft.Maui.Graphics; namespace cfs_tracker.ViewModels; @@ -11,14 +10,16 @@ public partial class DayEntryItemViewModel : ObservableObject public string SlotText { get; init; } = string.Empty; public string StateText { get; init; } = string.Empty; public string ActivityText { get; init; } = string.Empty; + public string DurationText { 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 HasDuration => !string.IsNullOrWhiteSpace(DurationText); public bool HasSymptoms => !string.IsNullOrWhiteSpace(SymptomsText); - public bool HasDetails => HasActivity || HasSymptoms; + public bool HasDetails => HasActivity || HasDuration || HasSymptoms; public string DetailsButtonText => IsExpanded ? "Details ausblenden" : "Details anzeigen"; [ObservableProperty] @@ -43,4 +44,4 @@ public partial class DayEntryItemViewModel : ObservableObject IsExpanded = !IsExpanded; } -} +} \ No newline at end of file diff --git a/ViewModels/DayViewModel.cs b/ViewModels/DayViewModel.cs index a27fb3b..f109981 100644 --- a/ViewModels/DayViewModel.cs +++ b/ViewModels/DayViewModel.cs @@ -1,13 +1,11 @@ -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 CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; using System.Collections.ObjectModel; using System.Globalization; -using Microsoft.Maui.Graphics; -using Microsoft.Maui.Storage; namespace cfs_tracker.ViewModels; @@ -189,7 +187,8 @@ public partial class DayViewModel : ObservableObject }; var activityText = string.Empty; - if (entry.ActivityId.HasValue && activityMap.TryGetValue(entry.ActivityId.Value, out var activityName) && + if (entry.ActivityId.HasValue && + activityMap.TryGetValue(entry.ActivityId.Value, out var activityName) && !string.Equals(activityName, "Keine Tätigkeit", StringComparison.OrdinalIgnoreCase)) { activityText = activityName; @@ -200,6 +199,10 @@ public partial class DayViewModel : ObservableObject ? string.Join(", ", symptoms) : string.Empty; + var durationText = entry.ActivityDurationMinutes.HasValue && entry.ActivityDurationMinutes.Value > 0 + ? TimeSpan.FromMinutes(entry.ActivityDurationMinutes.Value).ToString(@"hh\:mm") + : string.Empty; + Entries.Add(new DayEntryItemViewModel { Id = entry.Id, @@ -209,6 +212,7 @@ public partial class DayViewModel : ObservableObject entry.State.ToAppearanceTextKey(), entry.State.ToFallbackText()), ActivityText = activityText, + DurationText = durationText, SymptomsText = symptomText, IsBackfill = entry.DayPart.HasValue, StateColor = _appearanceService.GetColor(entry.State.ToAppearanceColorKey(), "#1F242B"), @@ -231,6 +235,7 @@ public partial class DayViewModel : ObservableObject await _healthEntryRepository.AddQuickEntryAsync( state: state, activityId: null, + activityDurationMinutes: null, symptomIds: null, timestamp: DateTime.Now, source: EntrySource.App); @@ -347,4 +352,4 @@ public partial class DayViewModel : ObservableObject } private static string BuildCounterText(string label, int count) => $"{label}\n{count}"; -} +} \ No newline at end of file diff --git a/ViewModels/MonthCellViewModel.cs b/ViewModels/MonthCellViewModel.cs index f84c8ce..5be2e4a 100644 --- a/ViewModels/MonthCellViewModel.cs +++ b/ViewModels/MonthCellViewModel.cs @@ -1,5 +1,4 @@ using CommunityToolkit.Mvvm.ComponentModel; -using Microsoft.Maui.Graphics; namespace cfs_tracker.ViewModels; diff --git a/ViewModels/MonthViewModel.cs b/ViewModels/MonthViewModel.cs index bdcba38..3390365 100644 --- a/ViewModels/MonthViewModel.cs +++ b/ViewModels/MonthViewModel.cs @@ -1,9 +1,9 @@ -using CommunityToolkit.Mvvm.ComponentModel; -using CommunityToolkit.Mvvm.Input; using cfs_tracker.Data; using cfs_tracker.Helpers; using cfs_tracker.Services; -using Microsoft.Maui.Storage; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Microsoft.Maui.ApplicationModel; using System.Collections.ObjectModel; namespace cfs_tracker.ViewModels; @@ -50,25 +50,31 @@ public partial class MonthViewModel : ObservableObject OpenDayCommand = new AsyncRelayCommand(OpenDayAsync); _calendarStateService.SelectedDateChanged += HandleSharedDateChanged; - SelectedDate = _calendarStateService.SelectedDate; + SelectedDate = _calendarStateService.SelectedDate.Date; + UpdateHeader(); + } + + partial void OnSelectedDateChanged(DateTime value) + { + UpdateHeader(); } public async Task RefreshAsync() { - SelectedDate = _calendarStateService.SelectedDate; - var month = new DateTime(SelectedDate.Year, SelectedDate.Month, 1); - HeaderText = DateHelper.ToGermanMonthYear(month); + SelectedDate = _calendarStateService.SelectedDate.Date; + UpdateHeader(); - var monthEnd = month.AddMonths(1); + var monthStart = new DateTime(SelectedDate.Year, SelectedDate.Month, 1); + var monthEnd = monthStart.AddMonths(1); - var entries = await _healthEntryRepository.GetEntriesBetweenAsync(month, monthEnd); + var entries = await _healthEntryRepository.GetEntriesBetweenAsync(monthStart, monthEnd); Cells.Clear(); - var daysInMonth = DateTime.DaysInMonth(month.Year, month.Month); + var daysInMonth = DateTime.DaysInMonth(monthStart.Year, monthStart.Month); for (var day = 1; day <= daysInMonth; day++) { - var date = new DateTime(month.Year, month.Month, 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); @@ -88,12 +94,20 @@ public partial class MonthViewModel : ObservableObject }); } } + + private void UpdateHeader() + { + var month = new DateTime(SelectedDate.Year, SelectedDate.Month, 1); + HeaderText = DateHelper.ToGermanMonthYear(month); + } + private async Task OpenDayAsync(MonthCellViewModel? item) { if (item is null) return; - _calendarStateService.SelectedDate = item.Date; + SelectedDate = item.Date.Date; + _calendarStateService.SelectedDate = SelectedDate; await Shell.Current.GoToAsync("//day"); } @@ -105,25 +119,32 @@ public partial class MonthViewModel : ObservableObject private async Task PreviousMonthAsync() { - _calendarStateService.SelectedDate = new DateTime(SelectedDate.Year, SelectedDate.Month, 1).AddMonths(-1); + SelectedDate = new DateTime(SelectedDate.Year, SelectedDate.Month, 1).AddMonths(-1); + _calendarStateService.SelectedDate = SelectedDate; await RefreshAsync(); } private async Task NextMonthAsync() { - _calendarStateService.SelectedDate = new DateTime(SelectedDate.Year, SelectedDate.Month, 1).AddMonths(1); + SelectedDate = new DateTime(SelectedDate.Year, SelectedDate.Month, 1).AddMonths(1); + _calendarStateService.SelectedDate = SelectedDate; await RefreshAsync(); } private async Task TodayAsync() { - _calendarStateService.ResetToToday(); - await RefreshAsync(); + var today = DateTime.Today; + SelectedDate = today; + _calendarStateService.SelectedDate = today; + await Shell.Current.GoToAsync("//day"); } - private async void HandleSharedDateChanged(DateTime date) + private void HandleSharedDateChanged(DateTime date) { - SelectedDate = date; - await RefreshAsync(); + MainThread.BeginInvokeOnMainThread(async () => + { + SelectedDate = date.Date; + await RefreshAsync(); + }); } -} +} \ No newline at end of file diff --git a/ViewModels/NotificationScheduleItemViewModel.cs b/ViewModels/NotificationScheduleItemViewModel.cs index 9c3a299..cb35128 100644 --- a/ViewModels/NotificationScheduleItemViewModel.cs +++ b/ViewModels/NotificationScheduleItemViewModel.cs @@ -1,20 +1,84 @@ +using cfs_tracker.Models; using CommunityToolkit.Mvvm.ComponentModel; -using System.Collections.ObjectModel; +using CommunityToolkit.Mvvm.Input; namespace cfs_tracker.ViewModels; public partial class NotificationScheduleItemViewModel : ObservableObject { - public int Id { get; init; } - - public ObservableCollection WeekdayOptions { get; } = new(); + public int Id { get; set; } [ObservableProperty] - private WeekdayOptionItemViewModel? selectedWeekday; + private TimeSpan selectedTime; [ObservableProperty] - private TimeSpan selectedTime = new(9, 0, 0); + private bool isEnabled; [ObservableProperty] - private bool isEnabled = true; -} + private bool monday; + + [ObservableProperty] + private bool tuesday; + + [ObservableProperty] + private bool wednesday; + + [ObservableProperty] + private bool thursday; + + [ObservableProperty] + private bool friday; + + [ObservableProperty] + private bool saturday; + + [ObservableProperty] + private bool sunday; + + public IRelayCommand ToggleMondayCommand { get; } + public IRelayCommand ToggleTuesdayCommand { get; } + public IRelayCommand ToggleWednesdayCommand { get; } + public IRelayCommand ToggleThursdayCommand { get; } + public IRelayCommand ToggleFridayCommand { get; } + public IRelayCommand ToggleSaturdayCommand { get; } + public IRelayCommand ToggleSundayCommand { get; } + + public NotificationScheduleItemViewModel() + { + ToggleMondayCommand = new RelayCommand(() => Monday = !Monday); + ToggleTuesdayCommand = new RelayCommand(() => Tuesday = !Tuesday); + ToggleWednesdayCommand = new RelayCommand(() => Wednesday = !Wednesday); + ToggleThursdayCommand = new RelayCommand(() => Thursday = !Thursday); + ToggleFridayCommand = new RelayCommand(() => Friday = !Friday); + ToggleSaturdayCommand = new RelayCommand(() => Saturday = !Saturday); + ToggleSundayCommand = new RelayCommand(() => Sunday = !Sunday); + } + + public int ToWeekdayMask() + { + var mask = NotificationWeekdays.None; + + if (Monday) mask |= NotificationWeekdays.Monday; + if (Tuesday) mask |= NotificationWeekdays.Tuesday; + if (Wednesday) mask |= NotificationWeekdays.Wednesday; + if (Thursday) mask |= NotificationWeekdays.Thursday; + if (Friday) mask |= NotificationWeekdays.Friday; + if (Saturday) mask |= NotificationWeekdays.Saturday; + if (Sunday) mask |= NotificationWeekdays.Sunday; + + return (int)mask; + } + + public void LoadFromWeekdayMask(int mask) + { + var flags = (NotificationWeekdays)mask; + + Monday = flags.HasFlag(NotificationWeekdays.Monday); + Tuesday = flags.HasFlag(NotificationWeekdays.Tuesday); + Wednesday = flags.HasFlag(NotificationWeekdays.Wednesday); + Thursday = flags.HasFlag(NotificationWeekdays.Thursday); + Friday = flags.HasFlag(NotificationWeekdays.Friday); + Saturday = flags.HasFlag(NotificationWeekdays.Saturday); + Sunday = flags.HasFlag(NotificationWeekdays.Sunday); + } +} \ No newline at end of file diff --git a/ViewModels/OptionsViewModel.cs b/ViewModels/OptionsViewModel.cs index 0e39ef0..64ad39c 100644 --- a/ViewModels/OptionsViewModel.cs +++ b/ViewModels/OptionsViewModel.cs @@ -1,10 +1,13 @@ -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 CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using System; using System.Collections.ObjectModel; +using System.Linq; +using System.Threading.Tasks; namespace cfs_tracker.ViewModels; @@ -42,12 +45,19 @@ public partial class OptionsViewModel : ObservableObject [ObservableProperty] private string currentDatabasePath = string.Empty; + [ObservableProperty] + private OptionsTab selectedTab = OptionsTab.Notifications; + public ObservableCollection AppearanceColors { get; } = new(); public ObservableCollection StatusTexts { get; } = new(); public ObservableCollection Activities { get; } = new(); public ObservableCollection Symptoms { get; } = new(); public ObservableCollection NotificationSchedules { get; } = new(); + public bool IsAppearanceTabSelected => SelectedTab == OptionsTab.Appearance; + public bool IsNotificationsTabSelected => SelectedTab == OptionsTab.Notifications; + public bool IsDataManagementTabSelected => SelectedTab == OptionsTab.DataManagement; + public IAsyncRelayCommand DeleteAllDataCommand { get; } public IAsyncRelayCommand SaveAppearanceCommand { get; } public IAsyncRelayCommand ResetAppearanceCommand { get; } @@ -64,6 +74,9 @@ public partial class OptionsViewModel : ObservableObject public IAsyncRelayCommand DeleteScheduleCommand { get; } public IAsyncRelayCommand SaveDatabaseLocationCommand { get; } public IAsyncRelayCommand ClearExportsCommand { get; } + public IRelayCommand ShowAppearanceTabCommand { get; } + public IRelayCommand ShowNotificationsTabCommand { get; } + public IRelayCommand ShowDataManagementTabCommand { get; } public OptionsViewModel( HealthEntryRepository healthEntryRepository, @@ -104,6 +117,10 @@ public partial class OptionsViewModel : ObservableObject DeleteScheduleCommand = new AsyncRelayCommand(DeleteScheduleAsync); SaveDatabaseLocationCommand = new AsyncRelayCommand(SaveDatabaseLocationAsync); ClearExportsCommand = new AsyncRelayCommand(ClearExportsAsync); + + ShowAppearanceTabCommand = new RelayCommand(() => SelectedTab = OptionsTab.Appearance); + ShowNotificationsTabCommand = new RelayCommand(() => SelectedTab = OptionsTab.Notifications); + ShowDataManagementTabCommand = new RelayCommand(() => SelectedTab = OptionsTab.DataManagement); } partial void OnDeleteConfirmationTextChanged(string value) @@ -111,6 +128,13 @@ public partial class OptionsViewModel : ObservableObject DeleteAllDataCommand.NotifyCanExecuteChanged(); } + partial void OnSelectedTabChanged(OptionsTab value) + { + OnPropertyChanged(nameof(IsAppearanceTabSelected)); + OnPropertyChanged(nameof(IsNotificationsTabSelected)); + OnPropertyChanged(nameof(IsDataManagementTabSelected)); + } + public async Task LoadAsync() { await LoadAppearanceAsync(); @@ -177,14 +201,15 @@ public partial class OptionsViewModel : ObservableObject { var fallback = AppearanceDefaults.All[key]; var value = map.TryGetValue(key, out var stored) ? stored : fallback; + var preview = ColorUtility.ParseColor(value, fallback); AppearanceColors.Add(new AppearanceColorItemViewModel { Key = key, Title = title, Fallback = fallback, - Value = value, - PreviewColor = ColorUtility.ParseColor(value, fallback) + Value = ToHex(preview), + PreviewColor = preview }); } @@ -239,23 +264,37 @@ public partial class OptionsViewModel : ObservableObject 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)); + { + var vm = new NotificationScheduleItemViewModel + { + Id = schedule.Id, + SelectedTime = new TimeSpan(schedule.Hour, schedule.Minute, 0), + IsEnabled = schedule.IsEnabled + }; + + vm.LoadFromWeekdayMask(schedule.WeekdayMask); + NotificationSchedules.Add(vm); + } } private async Task SaveAppearanceAsync() { foreach (var item in AppearanceColors) { - item.PreviewColor = ColorUtility.ParseColor(item.Value, item.Fallback); - await _appearanceService.SaveColorAsync(item.Key, item.Value); + var normalized = ToHex(ColorUtility.ParseColor(item.Value, item.Fallback)); + item.Value = normalized; + item.PreviewColor = ColorUtility.ParseColor(normalized, item.Fallback); + await _appearanceService.SaveColorAsync(item.Key, normalized); } foreach (var item in StatusTexts) await _appearanceService.SaveTextAsync(item.Key, item.Value); + await _notificationScheduler.SyncAsync(); StatusText = "Aussehen gespeichert."; } @@ -263,6 +302,7 @@ public partial class OptionsViewModel : ObservableObject { await _appearanceService.ResetAsync(); await LoadAppearanceAsync(); + await _notificationScheduler.SyncAsync(); StatusText = "Aussehen auf Standard zurückgesetzt."; } @@ -384,17 +424,40 @@ public partial class OptionsViewModel : ObservableObject private Task AddScheduleAsync() { - NotificationSchedules.Add(CreateScheduleVm(0, DayOfWeek.Monday, new TimeSpan(9, 0, 0), true)); + NotificationSchedules.Add(new NotificationScheduleItemViewModel + { + SelectedTime = new TimeSpan(14, 0, 0), + IsEnabled = true, + Monday = true, + Tuesday = true, + Wednesday = true, + Thursday = true, + Friday = true + }); + StatusText = "Benachrichtigungszeit hinzugefügt."; return Task.CompletedTask; } private async Task SaveSchedulesAsync() { + var granted = await _notificationScheduler.EnsurePermissionAsync(); + if (!granted) + { + StatusText = "Benachrichtigungsberechtigung wurde nicht erlaubt."; + return; + } + + if (NotificationSchedules.Any(x => x.ToWeekdayMask() == 0)) + { + StatusText = "Bitte pro Benachrichtigungszeit mindestens einen Wochentag auswählen."; + return; + } + var items = NotificationSchedules.Select(x => new NotificationSchedule { Id = x.Id, - DayOfWeek = x.SelectedWeekday?.Value ?? DayOfWeek.Monday, + WeekdayMask = x.ToWeekdayMask(), Hour = x.SelectedTime.Hours, Minute = x.SelectedTime.Minutes, IsEnabled = x.IsEnabled @@ -404,7 +467,7 @@ public partial class OptionsViewModel : ObservableObject await _notificationScheduler.SyncAsync(); await LoadSchedulesAsync(); - StatusText = "Benachrichtigungszeiten gespeichert. Text: 'Wie geht es dir?' mit Gelb/Rot/Grau als Schnellwahl."; + StatusText = "Benachrichtigungszeiten gespeichert."; } private Task DeleteScheduleAsync(NotificationScheduleItemViewModel? item) @@ -425,24 +488,6 @@ public partial class OptionsViewModel : ObservableObject 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( @@ -464,14 +509,20 @@ public partial class OptionsViewModel : ObservableObject "OK"); } - private static IEnumerable BuildWeekdayOptions() + private static string ToHex(Color color) { - 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" }; + var red = ClampByte(color.Red * 255d); + var green = ClampByte(color.Green * 255d); + var blue = ClampByte(color.Blue * 255d); + return $"#{red:X2}{green:X2}{blue:X2}"; } -} \ No newline at end of file + + private static int ClampByte(double value) => Math.Clamp((int)Math.Round(value), 0, 255); + + public enum OptionsTab + { + Appearance, + Notifications, + DataManagement + } +} diff --git a/ViewModels/QuickEntryViewModel.cs b/ViewModels/QuickEntryViewModel.cs index 4d3883d..9ece5ef 100644 --- a/ViewModels/QuickEntryViewModel.cs +++ b/ViewModels/QuickEntryViewModel.cs @@ -1,13 +1,11 @@ -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 CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; using System.Collections.ObjectModel; using System.Globalization; -using System.Linq; namespace cfs_tracker.ViewModels; @@ -20,6 +18,8 @@ public partial class QuickEntryViewModel : ObservableObject private readonly CalendarStateService _calendarStateService; private string _dateQuery = string.Empty; + private string _statusQuery = string.Empty; + private bool _commitFromNotification; private int? _entryId; [ObservableProperty] @@ -67,6 +67,9 @@ public partial class QuickEntryViewModel : ObservableObject [ObservableProperty] private ActivityPickerItemViewModel? selectedActivity; + [ObservableProperty] + private TimeSpan activityDuration = TimeSpan.Zero; + [ObservableProperty] private DayPartOptionItemViewModel? selectedPart; @@ -95,6 +98,7 @@ public partial class QuickEntryViewModel : ObservableObject public IAsyncRelayCommand SaveGrayCommand { get; } public IAsyncRelayCommand SaveCommand { get; } public IAsyncRelayCommand CancelCommand { get; } + public IRelayCommand ToggleSymptomCommand { get; } public QuickEntryViewModel( HealthEntryRepository healthEntryRepository, @@ -115,6 +119,7 @@ public partial class QuickEntryViewModel : ObservableObject SaveGrayCommand = new AsyncRelayCommand(() => SelectOrSaveAsync(HealthState.Gray)); SaveCommand = new AsyncRelayCommand(SaveSelectedAsync); CancelCommand = new AsyncRelayCommand(CancelAsync); + ToggleSymptomCommand = new RelayCommand(ToggleSymptom); } partial void OnIsTodayChanged(bool value) => RaiseModeChanged(); @@ -134,14 +139,22 @@ public partial class QuickEntryViewModel : ObservableObject OnPropertyChanged(nameof(SelectedStateSummaryText)); } - public void ApplyQuery(string date, string entryId) + public void ApplyQuery(string date, string? entryId, string? status, string? commit) { _dateQuery = date ?? string.Empty; - _entryId = int.TryParse(entryId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedId) + _statusQuery = status ?? string.Empty; + _commitFromNotification = string.Equals(commit, "true", StringComparison.OrdinalIgnoreCase); + + _entryId = int.TryParse(entryId, out var parsedId) ? parsedId : null; } + public void ApplyQuery(string date, string? entryId) + { + ApplyQuery(date, entryId, null, null); + } + public async Task InitializeAsync() { SelectedDate = DateTime.TryParseExact( @@ -156,15 +169,36 @@ public partial class QuickEntryViewModel : ObservableObject UpdateDateMode(); SelectedDateText = DateHelper.ToGermanDateText(SelectedDate); + IsEditing = false; + SelectedState = null; + ActivityDuration = TimeSpan.Zero; + LoadAppearance(); await LoadActivitiesAsync(); await LoadSymptomsAsync(); LoadDayParts(); + SelectedActivity = Activities.FirstOrDefault(); + SelectedPart = Parts.FirstOrDefault(x => x.Value == DayPart.Morning) ?? Parts.FirstOrDefault(); + + foreach (var symptom in Symptoms) + symptom.IsSelected = false; + if (_entryId.HasValue) + { await LoadExistingEntryAsync(); + } else - SelectedPart = Parts.FirstOrDefault(x => x.Value == DayPart.Morning); + { + if (TryParseNotificationState(_statusQuery, out var notificationState)) + SelectedState = notificationState; + + if (_commitFromNotification && IsToday && TryParseNotificationState(_statusQuery, out var quickState)) + { + await SaveAsync(quickState); + return; + } + } OnPropertyChanged(nameof(ModeText)); OnPropertyChanged(nameof(CanSave)); @@ -192,8 +226,6 @@ public partial class QuickEntryViewModel : ObservableObject Name = item.Name }); } - - SelectedActivity ??= Activities.FirstOrDefault(); } private async Task LoadSymptomsAsync() @@ -246,6 +278,7 @@ public partial class QuickEntryViewModel : ObservableObject SelectedActivity = Activities.FirstOrDefault(x => x.Id == entry.ActivityId) ?? Activities.FirstOrDefault(); + ActivityDuration = TimeSpan.FromMinutes(entry.ActivityDurationMinutes ?? 0); SelectedState = entry.State; var symptomIds = await _symptomRepository.GetSymptomIdsForEntryAsync(entry.Id); @@ -280,6 +313,7 @@ public partial class QuickEntryViewModel : ObservableObject return; var activityId = SelectedActivity?.Id; + var activityDurationMinutes = ParseActivityDurationMinutes(); var symptomIds = Symptoms.Where(x => x.IsSelected).Select(x => x.Id).ToList(); if (IsEditing && _entryId.HasValue) @@ -289,6 +323,7 @@ public partial class QuickEntryViewModel : ObservableObject date: SelectedDate, state: state, activityId: activityId, + activityDurationMinutes: activityDurationMinutes, symptomIds: symptomIds, part: IsPastDate ? SelectedPart?.Value ?? DayPart.Morning : null, source: IsPastDate ? EntrySource.Backfill : EntrySource.App); @@ -300,6 +335,7 @@ public partial class QuickEntryViewModel : ObservableObject part: SelectedPart?.Value ?? DayPart.Morning, state: state, activityId: activityId, + activityDurationMinutes: activityDurationMinutes, symptomIds: symptomIds, source: EntrySource.Backfill); } @@ -308,6 +344,7 @@ public partial class QuickEntryViewModel : ObservableObject await _healthEntryRepository.AddQuickEntryAsync( state: state, activityId: activityId, + activityDurationMinutes: activityDurationMinutes, symptomIds: symptomIds, timestamp: DateTime.Now, source: EntrySource.App); @@ -357,4 +394,51 @@ public partial class QuickEntryViewModel : ObservableObject HealthState.Gray => GrayStatusText, _ => string.Empty }; + + private static bool TryParseNotificationState(string? value, out HealthState state) + { + switch ((value ?? string.Empty).Trim().ToLowerInvariant()) + { + case "green": + case "gruen": + case "grün": + state = HealthState.Green; + return true; + + case "yellow": + case "gelb": + state = HealthState.Yellow; + return true; + + case "red": + case "rot": + state = HealthState.Red; + return true; + + case "gray": + case "grey": + case "grau": + case "schwarz": + state = HealthState.Gray; + return true; + + default: + state = default; + return false; + } + } + + private int? ParseActivityDurationMinutes() + { + var minutes = (int)Math.Round(ActivityDuration.TotalMinutes, MidpointRounding.AwayFromZero); + return minutes > 0 ? minutes : null; + } + + private void ToggleSymptom(SelectableSymptomItemViewModel? item) + { + if (item is null) + return; + + item.IsSelected = !item.IsSelected; + } } \ No newline at end of file diff --git a/ViewModels/WeekDaySummaryViewModel.cs b/ViewModels/WeekDaySummaryViewModel.cs index cdaf347..efd410b 100644 --- a/ViewModels/WeekDaySummaryViewModel.cs +++ b/ViewModels/WeekDaySummaryViewModel.cs @@ -1,6 +1,5 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using Microsoft.Maui.Graphics; namespace cfs_tracker.ViewModels; diff --git a/ViewModels/WeekViewModel.cs b/ViewModels/WeekViewModel.cs index e8daa3a..0db4e3b 100644 --- a/ViewModels/WeekViewModel.cs +++ b/ViewModels/WeekViewModel.cs @@ -1,10 +1,10 @@ -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 CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Microsoft.Maui.ApplicationModel; using System.Collections.ObjectModel; namespace cfs_tracker.ViewModels; @@ -60,14 +60,19 @@ public partial class WeekViewModel : ObservableObject OpenDayCommand = new AsyncRelayCommand(OpenDayAsync); _calendarStateService.SelectedDateChanged += HandleSharedDateChanged; - SelectedDate = _calendarStateService.SelectedDate; + SelectedDate = _calendarStateService.SelectedDate.Date; + UpdateHeader(); + } + + partial void OnSelectedDateChanged(DateTime value) + { + UpdateHeader(); } public async Task RefreshAsync() { - SelectedDate = _calendarStateService.SelectedDate; - WeekStart = DateHelper.StartOfWeekMonday(SelectedDate); - HeaderText = $"Woche {WeekStart:dd.MM.yyyy} - {WeekStart.AddDays(6):dd.MM.yyyy}"; + SelectedDate = _calendarStateService.SelectedDate.Date; + UpdateHeader(); var entries = await _healthEntryRepository.GetEntriesBetweenAsync(WeekStart, WeekStart.AddDays(7)); var activityMap = await _activityRepository.GetNameMapAsync(); @@ -97,12 +102,19 @@ public partial class WeekViewModel : ObservableObject } } + private void UpdateHeader() + { + WeekStart = DateHelper.StartOfWeekMonday(SelectedDate.Date); + HeaderText = $"Woche {WeekStart:dd.MM.yyyy} - {WeekStart.AddDays(6):dd.MM.yyyy}"; + } + private async Task OpenDayAsync(WeekDaySummaryViewModel? item) { if (item is null) return; - _calendarStateService.SelectedDate = item.Date; + SelectedDate = item.Date.Date; + _calendarStateService.SelectedDate = SelectedDate; await Shell.Current.GoToAsync("//day"); } @@ -114,25 +126,31 @@ public partial class WeekViewModel : ObservableObject private async Task PreviousWeekAsync() { - _calendarStateService.SelectedDate = DateHelper.StartOfWeekMonday(SelectedDate).AddDays(-7); + SelectedDate = DateHelper.StartOfWeekMonday(SelectedDate).AddDays(-7); + _calendarStateService.SelectedDate = SelectedDate; await RefreshAsync(); } private async Task NextWeekAsync() { - _calendarStateService.SelectedDate = DateHelper.StartOfWeekMonday(SelectedDate).AddDays(7); + SelectedDate = DateHelper.StartOfWeekMonday(SelectedDate).AddDays(7); + _calendarStateService.SelectedDate = SelectedDate; await RefreshAsync(); } - private async Task TodayAsync() { - _calendarStateService.ResetToToday(); - await RefreshAsync(); + var today = DateTime.Today; + SelectedDate = today; + _calendarStateService.SelectedDate = today; + await Shell.Current.GoToAsync("//day"); } - private async void HandleSharedDateChanged(DateTime date) + private void HandleSharedDateChanged(DateTime date) { - SelectedDate = date; - await RefreshAsync(); + MainThread.BeginInvokeOnMainThread(async () => + { + SelectedDate = date.Date; + await RefreshAsync(); + }); } -} +} \ No newline at end of file diff --git a/ViewModels/YearViewModel.cs b/ViewModels/YearViewModel.cs index 4764aba..df48b2b 100644 --- a/ViewModels/YearViewModel.cs +++ b/ViewModels/YearViewModel.cs @@ -1,9 +1,8 @@ -using CommunityToolkit.Mvvm.ComponentModel; -using CommunityToolkit.Mvvm.Input; using cfs_tracker.Data; using cfs_tracker.Helpers; using cfs_tracker.Services; -using Microsoft.Maui.Storage; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; using System.Collections.ObjectModel; namespace cfs_tracker.ViewModels; @@ -50,13 +49,19 @@ public partial class YearViewModel : ObservableObject OpenDayCommand = new AsyncRelayCommand(OpenDayAsync); _calendarStateService.SelectedDateChanged += HandleSharedDateChanged; - SelectedDate = _calendarStateService.SelectedDate; + SelectedDate = _calendarStateService.SelectedDate.Date; + UpdateHeader(); + } + + partial void OnSelectedDateChanged(DateTime value) + { + UpdateHeader(); } public async Task RefreshAsync() { - SelectedDate = _calendarStateService.SelectedDate; - HeaderText = DateHelper.ToGermanYear(SelectedDate); + SelectedDate = _calendarStateService.SelectedDate.Date; + UpdateHeader(); var yearStart = new DateTime(SelectedDate.Year, 1, 1); var yearEnd = yearStart.AddYears(1); @@ -99,12 +104,19 @@ public partial class YearViewModel : ObservableObject Months.Add(section); } } + + private void UpdateHeader() + { + HeaderText = DateHelper.ToGermanYear(SelectedDate); + } + private async Task OpenDayAsync(MonthCellViewModel? item) { if (item is null) return; - _calendarStateService.SelectedDate = item.Date; + SelectedDate = item.Date.Date; + _calendarStateService.SelectedDate = SelectedDate; await Shell.Current.GoToAsync("//day"); } @@ -116,25 +128,32 @@ public partial class YearViewModel : ObservableObject private async Task PreviousYearAsync() { - _calendarStateService.SelectedDate = new DateTime(SelectedDate.Year - 1, SelectedDate.Month, 1); + SelectedDate = new DateTime(SelectedDate.Year - 1, SelectedDate.Month, 1); + _calendarStateService.SelectedDate = SelectedDate; await RefreshAsync(); } private async Task NextYearAsync() { - _calendarStateService.SelectedDate = new DateTime(SelectedDate.Year + 1, SelectedDate.Month, 1); + SelectedDate = new DateTime(SelectedDate.Year + 1, SelectedDate.Month, 1); + _calendarStateService.SelectedDate = SelectedDate; await RefreshAsync(); } private async Task TodayAsync() { - _calendarStateService.ResetToToday(); - await RefreshAsync(); + var today = DateTime.Today; + SelectedDate = today; + _calendarStateService.SelectedDate = today; + await Shell.Current.GoToAsync("//day"); } - private async void HandleSharedDateChanged(DateTime date) + private void HandleSharedDateChanged(DateTime date) { - SelectedDate = date; - await RefreshAsync(); + MainThread.BeginInvokeOnMainThread(async () => + { + SelectedDate = date.Date; + await RefreshAsync(); + }); } -} +} \ No newline at end of file diff --git a/Views/DayPage.xaml b/Views/DayPage.xaml index 3330e34..f7c15cb 100644 --- a/Views/DayPage.xaml +++ b/Views/DayPage.xaml @@ -111,13 +111,13 @@ - - - - - - + - + + + + + + + + + + + + - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + +