From f3700f3692abad01074e5e53621076295d3f8a75 Mon Sep 17 00:00:00 2001 From: "MWG Bender[bot]" <331880973+mwg-bender[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:34:53 +0000 Subject: [PATCH 1/2] feat(web): make an Event repeat from the create dialog and mark repeating Events in the list The create Event dialog gets a Repeat section (off with every opening, never shown in Edit): Weekly, Every other week, Monthly on the nth weekday (First to Fourth or Last, and the weekday), Monthly on the same date, Yearly on the same date and Yearly on a holiday (the HolidayPreset list by readable name), plus an optional end date. The week, weekday and holiday default from the picked date until the admin picks one. An end that is not after the start shows the API's own "End must be after the start." and disables Create. Create with Repeat on sends one POST api/series (new SeriesService, same Idempotency-Key handling as the Event create, the key kept across ambiguous failures) and no Event: Name, Schedule { First exactly as BuildEventDate makes it with the browser's offset kept, Rule, End at the start's time and offset }, the dialog's slot count, Unique games only and the Filters. The roll shown is not saved; a hint under the switch says so. Success closes the dialog and reloads the list; a refusal shows the API's message in the dialog's alert. The Events list marks every Occurrence (SeriesId set) with a "Repeats" icon beside its name, inside the Name column, so the grid template is unchanged. The pure model is RepeatChoice; the section is RepeatSection. Every Web reader of Selections was checked with an empty Occurrence; all already coped, and new tests pin it. Refs #100, #204 --- .../EmptyOccurrenceTests.cs | 141 +++++++ MW-GC.EventManager.Web.Tests/PageHarness.cs | 1 + .../RepeatChoiceTests.cs | 164 ++++++++ .../RepeatSectionDialogTests.cs | 364 ++++++++++++++++++ .../ServiceRouteContractTests.cs | 20 +- .../StubApiHandler.cs | 7 + .../Services/AppServices.cs | 1 + .../Services/SeriesService.cs | 21 + .../Shared/Events/EventEditDialog.razor | 50 ++- .../Shared/Events/EventList.razor | 13 +- .../Shared/Events/RepeatChoice.cs | 141 +++++++ .../Shared/Events/RepeatSection.razor | 82 ++++ 12 files changed, 997 insertions(+), 8 deletions(-) create mode 100644 MW-GC.EventManager.Web.Tests/EmptyOccurrenceTests.cs create mode 100644 MW-GC.EventManager.Web.Tests/RepeatChoiceTests.cs create mode 100644 MW-GC.EventManager.Web.Tests/RepeatSectionDialogTests.cs create mode 100644 MW-GC.EventManager.Web/Services/SeriesService.cs create mode 100644 MW-GC.EventManager.Web/Shared/Events/RepeatChoice.cs create mode 100644 MW-GC.EventManager.Web/Shared/Events/RepeatSection.razor diff --git a/MW-GC.EventManager.Web.Tests/EmptyOccurrenceTests.cs b/MW-GC.EventManager.Web.Tests/EmptyOccurrenceTests.cs new file mode 100644 index 0000000..00fc532 --- /dev/null +++ b/MW-GC.EventManager.Web.Tests/EmptyOccurrenceTests.cs @@ -0,0 +1,141 @@ +using Bunit; +using MW_GC.EventManager.Shared.Entities; +using MW_GC.EventManager.Shared.Models; +using MW_GC.EventManager.Web.Pages; +using MW_GC.EventManager.Web.Services; +using static MW_GC.EventManager.Web.Tests.PageActions; + +namespace MW_GC.EventManager.Web.Tests; + +// #100, #204: the repeat marker in the Events list, and every Web reader of an Event's Selections with an Occurrence +// that has none yet (ADR 0002). "Weekly night" is an Occurrence (SeriesId set, no Selections); "Game night" is a +// standalone Event with one Selection, its Winner. +[TestClass] +public sealed class EmptyOccurrenceTests : IDisposable +{ + private readonly StubApiHandler api = new(); + private readonly PageHarness harness; + private readonly GameEntity kart = new() { Name = "Kart" }; + private readonly ActivityEntity grandPrix; + private readonly EventEntity night; + private readonly EventEntity weekly; + + public EmptyOccurrenceTests() + { + grandPrix = new ActivityEntity { Name = "Grand Prix", GameId = kart.Id }; + night = new EventEntity { Name = "Game night", Date = new DateTimeOffset(2026, 10, 9, 19, 0, 0, TimeSpan.Zero), Selections = [Pick(kart, grandPrix)], WinnerActivityId = grandPrix.Id }; + weekly = new EventEntity { Name = "Weekly night", Date = new DateTimeOffset(2026, 10, 2, 19, 0, 0, TimeSpan.Zero), SeriesId = Guid.NewGuid(), OccurrenceKey = new DateTimeOffset(2026, 10, 2, 19, 0, 0, TimeSpan.Zero) }; + api.Json(HttpMethod.Get, "/api/events", new[] { night, weekly }) + .Json(HttpMethod.Get, "/api/games", new[] { kart }) + .Json(HttpMethod.Get, "/api/activities", new[] { grandPrix }) + .Json(HttpMethod.Get, "/api/themes", Array.Empty()) + .Json(HttpMethod.Get, "/api/holidays", Array.Empty()) + .Json(HttpMethod.Get, $"/api/events/{weekly.Id}/metrics", new { id = weekly.Id }) + .Json(HttpMethod.Get, $"/api/events/{weekly.Id}/likes", new { count = 0 }); + harness = new PageHarness(api); + } + + public void Dispose() => harness.Dispose(); + + // The marker has an accessible name on the Occurrence's row and is missing from the standalone Event's row; the + // empty Occurrence shows 0 Selections and no Winner, and the grid keeps its five columns. + [TestMethod] + public void TheList_MarksTheOccurrenceOnly_AndShowsZeroSelectionsAndNoWinner() + { + var page = Loaded(); + + var occurrence = Row(page, "Weekly night"); + var marker = Assert.ContainsSingle(occurrence.QuerySelectorAll(".repeat-marker")); + Assert.AreEqual("Repeats", marker.GetAttribute("aria-label")); + Assert.AreEqual("img", marker.GetAttribute("role")); + Assert.IsEmpty(Row(page, "Game night").QuerySelectorAll(".repeat-marker")); + + var cells = occurrence.QuerySelectorAll("td").Select(c => Normalize(c.TextContent)).ToList(); + Assert.HasCount(5, cells); + Assert.AreEqual("Weekly night", cells[0]); + Assert.AreEqual("0", cells[2]); + Assert.AreEqual("None", cells[3]); + Assert.AreEqual("minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) 120px", + page.Find("table").GetAttribute("style")!.Split("grid-template-columns:")[1].Split(';')[0].Trim()); + } + + // Details of an empty Occurrence opens with no error and no Selection card, so no Select Winner either. + [TestMethod] + public async Task Details_OfAnEmptyOccurrence_OpensWithoutError_AndOffersNoWinner() + { + var page = Loaded(); + + await RowButton(page, "Weekly night", "Details").ClickAsync(new()); + + Assert.IsTrue(page.HasFormDialog()); + Assert.AreEqual("Weekly night", page.FormDialog().GetAttribute("aria-label")); + Assert.IsEmpty(page.FormDialog().Alerts()); + Assert.IsFalse(page.FormDialog().QuerySelectorAll("fluent-button").Any(b => b.TextContent.Trim() == "Select Winner")); + Assert.IsFalse(harness.UnhandledException.IsCompleted); + } + + // Edit of an empty Occurrence opens with no slot and no error and no Repeat section; rolling it is the next card. + [TestMethod] + public async Task Edit_OfAnEmptyOccurrence_OpensWithoutError() + { + var page = Loaded(); + + await RowButton(page, "Weekly night", "Edit").ClickAsync(new()); + + Assert.AreEqual("Edit Event", page.DialogTitle()); + Assert.IsEmpty(page.FormDialog().Alerts()); + Assert.IsEmpty(page.FormDialog().QuerySelectorAll("fluent-button[aria-label^='Re-roll slot']")); + Assert.IsNull(page.FormDialog().QuerySelector(".repeat-section")); + Assert.IsFalse(harness.UnhandledException.IsCompleted); + } + + // Stats, the Activity performance panel and Play stats all run PlayStats.Compute: an empty past Occurrence offered + // nothing, so it adds no Offered, no win and no Likes to any row, and no rate is a division by zero. + [TestMethod] + public void PlayStats_CountsNothingForAnEmptyOccurrence() + { + var metrics = new[] { new EventMetricsWithLikes(weekly.Id, 9, null, null, null, 4) }; + var stats = new PlayStats(new FixedClock(new DateTimeOffset(2026, 11, 1, 0, 0, 0, TimeSpan.Zero))); + + var withIt = stats.Compute([night, weekly], [kart], [grandPrix], metrics); + var onlyIt = stats.Compute([weekly], [kart], [grandPrix], metrics); + + var row = Assert.ContainsSingle(withIt.Activities); + Assert.AreEqual((1, 1, night.Date), (row.Offered, row.Wins, row.LastOffered)); + Assert.AreEqual(new ActivityPerformance(1m, 0m, null), row.Performance); + var unused = Assert.ContainsSingle(onlyIt.Activities); + Assert.AreEqual((0, 0, (DateTimeOffset?)null), (unused.Offered, unused.Wins, unused.LastOffered)); + Assert.AreEqual(new ActivityPerformance(null, null, null), unused.Performance); + Assert.AreEqual(0, Assert.ContainsSingle(onlyIt.Games).Offered); + } + + // The Stats page renders with an empty Occurrence in the list: no "NaN", the Activity's numbers from the one Event. + [TestMethod] + public void TheStatsPage_RendersWithAnEmptyOccurrence() + { + api.Json(HttpMethod.Get, "/api/event-metrics", Array.Empty()); + var page = harness.Render(); + + page.WaitForAssertion(() => Assert.HasCount(2, page.FindAll("tbody tr.fluent-data-grid-row"))); + Assert.DoesNotContain("NaN", page.Markup); + Assert.AreEqual("1", page.Find("table.stats-activities .stats-offered").TextContent.Trim()); + Assert.IsEmpty(page.PageAlerts()); + } + + // ---- helpers ------------------------------------------------------------------------------- + + private IRenderedComponent Loaded() + { + var page = harness.Render(); + page.WaitForRows(2); + return page; + } + + private static AngleSharp.Dom.IElement Row(IRenderedComponent page, string name) => + page.FindAll("tbody tr.fluent-data-grid-row").Single(r => r.TextContent.Contains(name)); + + private sealed class FixedClock(DateTimeOffset now) : TimeProvider + { + public override DateTimeOffset GetUtcNow() => now; + } +} diff --git a/MW-GC.EventManager.Web.Tests/PageHarness.cs b/MW-GC.EventManager.Web.Tests/PageHarness.cs index eb76217..ebad2c2 100644 --- a/MW-GC.EventManager.Web.Tests/PageHarness.cs +++ b/MW-GC.EventManager.Web.Tests/PageHarness.cs @@ -23,6 +23,7 @@ public PageHarness(StubApiHandler api) _context.Services.AddLibraryClients(); _context.Services.AddSingleton(new ActivityService(http)); _context.Services.AddSingleton(new EventService(http)); + _context.Services.AddSingleton(new SeriesService(http)); _context.Services.AddSingleton(new EventMetricsClient(http)); _context.Services.AddSingleton(new CommentClient(http)); _context.Services.AddScoped(); diff --git a/MW-GC.EventManager.Web.Tests/RepeatChoiceTests.cs b/MW-GC.EventManager.Web.Tests/RepeatChoiceTests.cs new file mode 100644 index 0000000..cdd7447 --- /dev/null +++ b/MW-GC.EventManager.Web.Tests/RepeatChoiceTests.cs @@ -0,0 +1,164 @@ +using MW_GC.EventManager.Shared.Series; +using MW_GC.EventManager.Web.Shared.Events; + +namespace MW_GC.EventManager.Web.Tests; + +// #100, #204: the Repeat section's pure model. Every expected value is written out by hand: 10 December 2026 is a +// Thursday in the second week of its month, 31 December 2026 a Thursday in its last, and Thanksgiving 2026 is 26 +// November (the fourth Thursday). +[TestClass] +public sealed class RepeatChoiceTests +{ + private static readonly TimeSpan Chicago = TimeSpan.FromHours(-6); + private static readonly DateTimeOffset SecondThursday = new(2026, 12, 10, 19, 0, 0, Chicago); + + [TestMethod] + public void ANewChoice_IsOff_AndWeekly_WithNoEnd() + { + var choice = new RepeatChoice(); + + Assert.IsFalse(choice.IsOn); + Assert.AreEqual(RecurrenceKind.Weekly, choice.Kind); + Assert.IsNull(choice.EndDate); + Assert.IsNull(choice.EndFor(SecondThursday)); + Assert.IsNull(choice.ScheduleFor(SecondThursday).End); + } + + [TestMethod] + public void TheRulesAreOffered_InTheseWords_WeeklyFirst() + { + CollectionAssert.AreEqual( + new[] { "Weekly", "Every other week", "Monthly on the nth weekday", "Monthly on the same date", "Yearly on the same date", "Yearly on a holiday" }, + RepeatChoice.Rules.Select(r => r.Name).ToArray()); + CollectionAssert.AreEqual(new[] { "First", "Second", "Third", "Fourth", "Last" }, RepeatChoice.Weeks.Select(w => w.Name).ToArray()); + } + + [TestMethod] + [DataRow(RecurrenceKind.Weekly)] + [DataRow(RecurrenceKind.BiWeekly)] + [DataRow(RecurrenceKind.MonthlyNthWeekday)] + [DataRow(RecurrenceKind.MonthlySameDate)] + [DataRow(RecurrenceKind.AnnualSameDate)] + [DataRow(RecurrenceKind.AnnualHoliday)] + public void EachRule_MakesItsExactRecurrenceRule(RecurrenceKind kind) + { + var choice = new RepeatChoice { IsOn = true, Kind = kind }; + + var expected = kind switch + { + RecurrenceKind.Weekly => new RecurrenceRule(RecurrenceKind.Weekly), + RecurrenceKind.BiWeekly => new RecurrenceRule(RecurrenceKind.BiWeekly), + RecurrenceKind.MonthlyNthWeekday => new RecurrenceRule(RecurrenceKind.MonthlyNthWeekday, WeekOfMonth.Second, DayOfWeek.Thursday), + RecurrenceKind.MonthlySameDate => new RecurrenceRule(RecurrenceKind.MonthlySameDate), + RecurrenceKind.AnnualSameDate => new RecurrenceRule(RecurrenceKind.AnnualSameDate), + _ => new RecurrenceRule(RecurrenceKind.AnnualHoliday, Preset: HolidayPreset.NewYearsDay), + }; + Assert.AreEqual(expected, choice.ScheduleFor(SecondThursday).Rule); + } + + // A Thursday in the second week gives Second and Thursday. + [TestMethod] + public void TheNthWeekday_DefaultsToThePickedDatesWeekAndWeekday() + { + var choice = new RepeatChoice { IsOn = true, Kind = RecurrenceKind.MonthlyNthWeekday }; + + Assert.AreEqual(RecurrenceRule.MonthlyNthWeekday(WeekOfMonth.Second, DayOfWeek.Thursday), choice.ScheduleFor(SecondThursday).Rule); + } + + [TestMethod] + [DataRow(1, WeekOfMonth.First)] + [DataRow(7, WeekOfMonth.First)] + [DataRow(8, WeekOfMonth.Second)] + [DataRow(14, WeekOfMonth.Second)] + [DataRow(15, WeekOfMonth.Third)] + [DataRow(21, WeekOfMonth.Third)] + [DataRow(22, WeekOfMonth.Fourth)] + [DataRow(28, WeekOfMonth.Fourth)] + [DataRow(29, WeekOfMonth.Last)] + [DataRow(31, WeekOfMonth.Last)] + public void TheDefaultWeek_FollowsTheDay(int day, WeekOfMonth week) => + Assert.AreEqual(week, RepeatChoice.DefaultWeek(new DateOnly(2026, 12, day))); + + // A date in the last week (a fifth Thursday) is Last, never a Fourth one week too early. + [TestMethod] + public void ADateInTheLastWeek_GivesLast() + { + var choice = new RepeatChoice { IsOn = true, Kind = RecurrenceKind.MonthlyNthWeekday }; + + Assert.AreEqual(RecurrenceRule.MonthlyNthWeekday(WeekOfMonth.Last, DayOfWeek.Thursday), + choice.ScheduleFor(new DateTimeOffset(2026, 12, 31, 19, 0, 0, Chicago)).Rule); + } + + [TestMethod] + public void AChosenWeekAndWeekday_WinOverTheDate() + { + var choice = new RepeatChoice { IsOn = true, Kind = RecurrenceKind.MonthlyNthWeekday, ChosenWeek = WeekOfMonth.Last, ChosenWeekday = DayOfWeek.Friday }; + + Assert.AreEqual(RecurrenceRule.MonthlyNthWeekday(WeekOfMonth.Last, DayOfWeek.Friday), choice.ScheduleFor(SecondThursday).Rule); + } + + // 23:30 on Thursday at UTC-06:00 is already Friday in UTC: the weekday is read at the start's own offset. + [TestMethod] + public void TheWeekday_IsReadAtTheStartsOwnOffset() + { + var choice = new RepeatChoice { IsOn = true, Kind = RecurrenceKind.MonthlyNthWeekday }; + var late = new DateTimeOffset(2026, 12, 10, 23, 30, 0, Chicago); + + Assert.AreEqual(RecurrenceRule.MonthlyNthWeekday(WeekOfMonth.Second, DayOfWeek.Thursday), choice.ScheduleFor(late).Rule); + } + + [TestMethod] + public void TheHoliday_DefaultsToTheOneOnThePickedDate_AndAChosenOneWins() + { + var thanksgiving = new DateTimeOffset(2026, 11, 26, 18, 0, 0, Chicago); + var choice = new RepeatChoice { IsOn = true, Kind = RecurrenceKind.AnnualHoliday }; + + Assert.AreEqual(RecurrenceRule.AnnualHoliday(HolidayPreset.Thanksgiving), choice.ScheduleFor(thanksgiving).Rule); + choice.ChosenHoliday = HolidayPreset.EasterSunday; + Assert.AreEqual(RecurrenceRule.AnnualHoliday(HolidayPreset.EasterSunday), choice.ScheduleFor(thanksgiving).Rule); + } + + // One table of names: every preset has exactly one readable name, and the names are distinct. + [TestMethod] + public void EveryHolidayPreset_HasOneReadableName() + { + foreach (var preset in Enum.GetValues()) + { + var name = Assert.ContainsSingle(RepeatChoice.Holidays.Where(h => h.Value == preset)).Name; + Assert.IsFalse(string.IsNullOrWhiteSpace(name), preset.ToString()); + } + Assert.HasCount(Enum.GetValues().Length, RepeatChoice.Holidays); + Assert.HasCount(RepeatChoice.Holidays.Count, RepeatChoice.Holidays.Select(h => h.Name).Distinct()); + Assert.AreEqual("Thanksgiving", RepeatChoice.HolidayName(HolidayPreset.Thanksgiving)); + Assert.AreEqual("Martin Luther King Jr. Day", RepeatChoice.HolidayName(HolidayPreset.MartinLutherKingJrDay)); + Assert.AreEqual("St. Patrick's Day", RepeatChoice.HolidayName(HolidayPreset.StPatricksDay)); + } + + // The start is sent exactly as given, its offset kept, and the end is the end date at the start's time and offset. + [TestMethod] + public void TheSchedule_KeepsTheStartsOffset_AndPutsTheEndAtItsTimeAndOffset() + { + var choice = new RepeatChoice { IsOn = true, EndDate = new DateOnly(2027, 3, 4) }; + + var schedule = choice.ScheduleFor(SecondThursday); + + Assert.AreEqual(SecondThursday, schedule.First); + Assert.AreEqual(Chicago, schedule.First.Offset); + Assert.AreEqual(new DateTimeOffset(2027, 3, 4, 19, 0, 0, Chicago), schedule.End); + Assert.AreEqual(Chicago, schedule.End!.Value.Offset); + } + + [TestMethod] + [DataRow(2026, 12, 9, true)] + [DataRow(2026, 12, 10, true)] + [DataRow(2026, 12, 11, false)] + public void AnEndNotAfterTheStart_GivesTheApisWording(int year, int month, int day, bool refused) + { + var choice = new RepeatChoice { IsOn = true, EndDate = new DateOnly(year, month, day) }; + + Assert.AreEqual(refused ? "End must be after the start." : null, choice.EndProblem(SecondThursday)); + } + + [TestMethod] + public void NoEnd_IsNoProblem() => Assert.IsNull(new RepeatChoice { IsOn = true }.EndProblem(SecondThursday)); +} diff --git a/MW-GC.EventManager.Web.Tests/RepeatSectionDialogTests.cs b/MW-GC.EventManager.Web.Tests/RepeatSectionDialogTests.cs new file mode 100644 index 0000000..aab2ed0 --- /dev/null +++ b/MW-GC.EventManager.Web.Tests/RepeatSectionDialogTests.cs @@ -0,0 +1,364 @@ +using System.Globalization; +using System.Net; +using System.Text.Json; +using AngleSharp.Dom; +using Bunit; +using Microsoft.AspNetCore.Components; +using Microsoft.FluentUI.AspNetCore.Components; +using MW_GC.EventManager.Shared.Entities; +using MW_GC.EventManager.Shared.Series; +using MW_GC.EventManager.Web.Pages; +using MW_GC.EventManager.Web.Shared.Events; +using static MW_GC.EventManager.Web.Tests.PageActions; + +namespace MW_GC.EventManager.Web.Tests; + +// #100, #204: the Repeat section of the create Event dialog on the real Events page, over a stub API. The browser's +// zone is pinned to Kathmandu (UTC+05:45, never UTC, no daylight saving) so a start sent in UTC instead of the local +// offset fails even on a UTC machine. The Event is typed for 10 December 2026, a Thursday in the second week, at the +// dialog's 19:00, so the start the dialog sends is written out as "2026-12-10T19:00:00+05:45". +[TestClass] +public sealed class RepeatSectionDialogTests : IDisposable +{ + private const string Start = "2026-12-10T19:00:00+05:45"; + private const string EndMessage = "End must be after the start."; + private static readonly TimeSpan Kathmandu = new(5, 45, 0); + private readonly StubApiHandler api = new(); + private readonly PageHarness harness; + private readonly GameEntity kart = new() { Name = "Kart" }, brawl = new() { Name = "Brawl" }, puzzle = new() { Name = "Puzzle" }; + private readonly ThemeEntity spooky = new() { Name = "Spooky" }; + private readonly HolidayEntity halloween = new() { Name = "Halloween" }; + private readonly EventEntity night; + private readonly string? zone = Environment.GetEnvironmentVariable("TZ"); + private readonly CultureInfo culture = CultureInfo.CurrentCulture; + + public RepeatSectionDialogTests() + { + Environment.SetEnvironmentVariable("TZ", "Asia/Kathmandu"); + TimeZoneInfo.ClearCachedData(); + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; + var grandPrix = new ActivityEntity { Name = "Grand Prix", GameId = kart.Id }; + var stock = new ActivityEntity { Name = "Stock", GameId = brawl.Id }; + var tiles = new ActivityEntity { Name = "Tiles", GameId = puzzle.Id }; + night = new EventEntity { Name = "Game night", Date = new DateTimeOffset(2026, 10, 9, 19, 0, 0, TimeSpan.Zero), Selections = [Pick(kart, grandPrix)] }; + api.Json(HttpMethod.Get, "/api/games", new[] { kart, brawl, puzzle }) + .Json(HttpMethod.Get, "/api/activities", new[] { grandPrix, stock, tiles }) + .Json(HttpMethod.Get, "/api/themes", new[] { spooky }) + .Json(HttpMethod.Get, "/api/holidays", new[] { halloween }) + .Json(HttpMethod.Get, "/api/events", new[] { night }) + .Status(HttpMethod.Post, "/api/series", HttpStatusCode.Created, "{}") + .Status(HttpMethod.Post, "/api/events", HttpStatusCode.Created, "{}"); + harness = new PageHarness(api); + } + + public void Dispose() + { + harness.Dispose(); + Environment.SetEnvironmentVariable("TZ", zone); + TimeZoneInfo.ClearCachedData(); + CultureInfo.CurrentCulture = culture; + } + + [TestMethod] + public async Task Repeat_IsOffWhenTheDialogOpens_AndOffAgainAfterReopening() + { + var page = await OpenCreate(); + AssertOff(page); + + await SwitchRepeat(page, true); + Assert.IsTrue(IsOn(page)); + Assert.AreEqual("Weekly", Select(page, "Repeats").QuerySelectorAll("fluent-option").First().TextContent.Trim()); + Assert.AreEqual(nameof(RecurrenceKind.Weekly), Select(page, "Repeats").GetAttribute("current-value")); + // The hint under the switch says the roll shown is not saved. + Assert.AreEqual("Each repeat starts with no picks yet: the activities rolled below are not saved.", + Section(page).QuerySelector(".repeat-hint")!.TextContent.Trim()); + await page.FormDialog().Button("Cancel").ClickAsync(new()); + + await page.Button("Create Event").ClickAsync(new()); + AssertOff(page); + } + + [TestMethod] + [DataRow(RecurrenceKind.Weekly, new string[0])] + [DataRow(RecurrenceKind.BiWeekly, new string[0])] + [DataRow(RecurrenceKind.MonthlyNthWeekday, new[] { "Week of the month", "Weekday" })] + [DataRow(RecurrenceKind.MonthlySameDate, new string[0])] + [DataRow(RecurrenceKind.AnnualSameDate, new string[0])] + [DataRow(RecurrenceKind.AnnualHoliday, new[] { "Holiday" })] + public async Task EachRule_ShowsExactlyItsExtraSelects(RecurrenceKind kind, string[] extra) + { + var page = await OpenCreate(); + await SwitchRepeat(page, true); + + await Choose(page, "Repeats", kind.ToString()); + + CollectionAssert.AreEqual(new[] { "Repeats" }.Concat(extra).ToArray(), + Section(page).QuerySelectorAll("fluent-select").Select(s => s.GetAttribute("aria-label")).ToArray()); + } + + [TestMethod] + [DataRow(RecurrenceKind.Weekly, null, null, null)] + [DataRow(RecurrenceKind.BiWeekly, null, null, null)] + [DataRow(RecurrenceKind.MonthlyNthWeekday, WeekOfMonth.Second, DayOfWeek.Thursday, null)] + [DataRow(RecurrenceKind.MonthlySameDate, null, null, null)] + [DataRow(RecurrenceKind.AnnualSameDate, null, null, null)] + [DataRow(RecurrenceKind.AnnualHoliday, null, null, HolidayPreset.NewYearsDay)] + public async Task CreateWithRepeatOn_SendsOneSeries_WithTheRuleAndTheStartsOffset_AndNoEvent( + RecurrenceKind kind, WeekOfMonth? week, DayOfWeek? weekday, HolidayPreset? preset) + { + var page = await OpenCreate(); + await SwitchRepeat(page, true); + await Choose(page, "Repeats", kind.ToString()); + + var (series, body) = await CreateSeries(page); + + Assert.AreEqual(new RecurrenceRule(kind, week, weekday, preset), series.Schedule.Rule); + AssertStart(series, body); + Assert.IsNull(series.Schedule.End); + Assert.AreEqual("Every Thursday", series.Name); + } + + // The extra selects send what the admin picks, not the date's defaults (Second Thursday, no holiday on the date). + [TestMethod] + public async Task TheChosenWeekWeekdayAndHoliday_AreSent() + { + var page = await OpenCreate(); + await SwitchRepeat(page, true); + await Choose(page, "Repeats", nameof(RecurrenceKind.MonthlyNthWeekday)); + Assert.AreEqual("Second", Select(page, "Week of the month").GetAttribute("current-value")); + Assert.AreEqual("Thursday", Select(page, "Weekday").GetAttribute("current-value")); + await Choose(page, "Week of the month", "Last"); + await Choose(page, "Weekday", "Friday"); + + var (series, _) = await CreateSeries(page); + Assert.AreEqual(RecurrenceRule.MonthlyNthWeekday(WeekOfMonth.Last, DayOfWeek.Friday), series.Schedule.Rule); + + await OpenCreate(page); + await SwitchRepeat(page, true); + await Choose(page, "Repeats", nameof(RecurrenceKind.AnnualHoliday)); + Assert.AreEqual("Thanksgiving", Select(page, "Holiday").QuerySelectorAll("fluent-option") + .Single(o => o.GetAttribute("value") == nameof(HolidayPreset.Thanksgiving)).TextContent.Trim()); + await Choose(page, "Holiday", nameof(HolidayPreset.Thanksgiving)); + (series, _) = await CreateSeries(page); + Assert.AreEqual(RecurrenceRule.AnnualHoliday(HolidayPreset.Thanksgiving), series.Schedule.Rule); + } + + // The slot count is the dialog's (two after removing one of three), Unique games only and every Filter are sent. + [TestMethod] + public async Task TheSeries_CarriesTheDialogsSlotCount_UniqueGamesOnly_AndFilters() + { + var page = await OpenCreate(); + await SwitchRepeat(page, true); + await page.FormDialog().QuerySelector("fluent-button[aria-label='Remove slot 1']")!.ClickAsync(new()); + await Check(page, "Filter by games", "Brawl"); + await Check(page, "Filter by themes", "Spooky"); + await Check(page, "Filter by holidays", "Halloween"); + await SwitchNamed(page, "Themed Activities Only").TriggerEventAsync("onswitchcheckedchange", new CheckboxChangeEventArgs { Checked = true }); + await SwitchNamed(page, "Unique games only").TriggerEventAsync("onswitchcheckedchange", new CheckboxChangeEventArgs { Checked = false }); + + var (series, _) = await CreateSeries(page); + + Assert.AreEqual(2, series.SlotCount); + Assert.IsFalse(series.UniqueGamesOnly); + Assert.IsTrue(series.Filters.ThemedOnly); + CollectionAssert.AreEqual(new[] { brawl.Id }, series.Filters.GameIds); + CollectionAssert.AreEqual(new[] { spooky.Id }, series.Filters.ThemeIds); + CollectionAssert.AreEqual(new[] { halloween.Id }, series.Filters.HolidayIds); + } + + [TestMethod] + public async Task AnEndDate_IsSentAtTheStartsTimeAndOffset_AndOneNotAfterTheStartDisablesCreate() + { + var page = await OpenCreate(); + await SwitchRepeat(page, true); + + await TypeEnd(page, "12/10/2026"); + Assert.AreEqual(EndMessage, Assert.ContainsSingle(Section(page).Alerts())); + Assert.IsTrue(page.FormDialog().Button("Create Event").HasAttribute("disabled")); + + await TypeEnd(page, "03/04/2027"); + Assert.IsEmpty(Section(page).Alerts()); + Assert.IsFalse(page.FormDialog().Button("Create Event").HasAttribute("disabled")); + var (series, body) = await CreateSeries(page); + + Assert.AreEqual(new DateTimeOffset(2027, 3, 4, 19, 0, 0, Kathmandu), series.Schedule.End); + StringAssert.Contains(body, "\"end\":\"2027-03-04T19:00:00+05:45\""); + } + + [TestMethod] + public async Task CreateWithRepeatOff_SendsTheEventAsBefore_AndNoSeries() + { + var page = await OpenCreate(); + + await page.FormDialog().Button("Create Event").ClickAsync(new()); + + page.WaitForAssertion(() => Assert.IsFalse(page.HasFormDialog())); + Assert.AreEqual(0, api.Count(HttpMethod.Post, "/api/series")); + var sent = JsonSerializer.Deserialize(Assert.ContainsSingle(api.Bodies(HttpMethod.Post, "/api/events"))!, JsonSerializerOptions.Web)!; + Assert.AreEqual("Every Thursday", sent.Name); + Assert.HasCount(3, sent.Selections); + Assert.IsNull(sent.SeriesId); + } + + // A create whose answer was lost keeps its key, so the retry sends the same one; a new opening gets a new one. + [TestMethod] + public async Task ARetryAfterALostAnswer_SendsTheSameIdempotencyKey() + { + api.Offline(HttpMethod.Post, "/api/series"); + var page = await OpenCreate(); + await SwitchRepeat(page, true); + await page.FormDialog().Button("Create Event").ClickAsync(new()); + page.WaitForAssertion(() => Assert.IsNotEmpty(page.FormDialog().Alerts())); + + api.Status(HttpMethod.Post, "/api/series", HttpStatusCode.Created, "{}"); + await page.FormDialog().Button("Create Event").ClickAsync(new()); + page.WaitForAssertion(() => Assert.IsFalse(page.HasFormDialog())); + + var keys = api.IdempotencyKeys(HttpMethod.Post, "/api/series"); + Assert.HasCount(2, keys); + Assert.IsTrue(Guid.TryParseExact(keys[0], "D", out var key) && key != Guid.Empty, keys[0]); + Assert.AreEqual(keys[0], keys[1]); + await OpenCreate(page); + await SwitchRepeat(page, true); + await page.FormDialog().Button("Create Event").ClickAsync(new()); + page.WaitForAssertion(() => Assert.HasCount(3, api.IdempotencyKeys(HttpMethod.Post, "/api/series"))); + Assert.AreNotEqual(keys[0], api.IdempotencyKeys(HttpMethod.Post, "/api/series")[2]); + } + + [TestMethod] + public async Task AnApiRefusal_ShowsItsMessageInTheAlert_AndKeepsTheDialogOpen() + { + api.Status(HttpMethod.Post, "/api/series", HttpStatusCode.BadRequest, "\"End must be after the start.\""); + var page = await OpenCreate(); + await SwitchRepeat(page, true); + + await page.FormDialog().Button("Create Event").ClickAsync(new()); + + page.WaitForAssertion(() => Assert.AreEqual("The event was not saved. End must be after the start.", Assert.ContainsSingle(page.FormDialog().Alerts()))); + Assert.IsTrue(page.HasFormDialog()); + Assert.AreEqual(1, api.Count(HttpMethod.Post, "/api/series")); + Assert.AreEqual(0, api.Count(HttpMethod.Post, "/api/events")); + } + + // A saved Series closes the dialog and reloads the list, so its Occurrences show. + [TestMethod] + public async Task ASavedSeries_ClosesTheDialog_AndReloadsTheList() + { + var page = await OpenCreate(); + await SwitchRepeat(page, true); + var reads = api.Count(HttpMethod.Get, "/api/events"); + + await page.FormDialog().Button("Create Event").ClickAsync(new()); + + page.WaitForAssertion(() => Assert.AreEqual(reads + 1, api.Count(HttpMethod.Get, "/api/events"))); + Assert.IsFalse(page.HasFormDialog()); + Assert.IsEmpty(page.PageAlerts()); + } + + [TestMethod] + public async Task TheEditDialog_NeverShowsTheRepeatSection() + { + var page = await OpenPage(); + await page.Button("Create Event").ClickAsync(new()); + await SwitchRepeat(page, true); + await page.FormDialog().Button("Cancel").ClickAsync(new()); + + await RowButton(page, "Game night", "Edit").ClickAsync(new()); + + Assert.AreEqual("Edit Event", page.DialogTitle()); + Assert.IsNull(page.FormDialog().QuerySelector(".repeat-section")); + Assert.IsFalse(page.FormDialog().QuerySelectorAll("fluent-switch").Any(s => s.GetAttribute("aria-label") == "Repeat")); + } + + // Every new control has its accessible name, and a switch and a select a keyboard reaches (no tabindex=-1). + [TestMethod] + public async Task EveryRepeatControl_HasItsAccessibleName_AndIsInTheTabOrder() + { + var page = await OpenCreate(); + await SwitchRepeat(page, true); + await Choose(page, "Repeats", nameof(RecurrenceKind.MonthlyNthWeekday)); + + var controls = new List { RepeatSwitch(page) }; + controls.AddRange(Section(page).QuerySelectorAll("fluent-select")); + controls.Add(EndBox(page)); + CollectionAssert.AreEqual(new[] { "Repeat", "Repeats", "Week of the month", "Weekday", "Ends on (optional)" }, + controls.Select(c => c.GetAttribute("aria-label")).ToArray()); + Assert.IsFalse(controls.Any(c => c.GetAttribute("tabindex") == "-1" || c.HasAttribute("disabled"))); + } + + // ---- helpers ------------------------------------------------------------------------------- + + private async Task> OpenPage() + { + if (TimeZoneInfo.Local.BaseUtcOffset != Kathmandu) Assert.Inconclusive("This platform does not take the local zone from TZ."); + var page = harness.Render(); + page.WaitForRows(1); + return await Task.FromResult(page); + } + + private async Task> OpenCreate() + { + var page = await OpenPage(); + await OpenCreate(page); + return page; + } + + // A create dialog named Every Thursday, for 10 December 2026 at the dialog's 19:00. + private static async Task OpenCreate(IRenderedComponent page) + { + await page.Button("Create Event").ClickAsync(new()); + await page.FormDialog().QuerySelector("fluent-text-field[placeholder='Enter event name...']")!.ChangeAsync(new ChangeEventArgs { Value = "Every Thursday" }); + await page.FormDialog().QuerySelector("fluent-text-field.fluent-datepicker")!.ChangeAsync(new ChangeEventArgs { Value = "12/10/2026" }); + } + + private async Task<(SeriesEntity Series, string Body)> CreateSeries(IRenderedComponent page) + { + var before = api.Count(HttpMethod.Post, "/api/series"); + await page.FormDialog().Button("Create Event").ClickAsync(new()); + page.WaitForAssertion(() => Assert.IsFalse(page.HasFormDialog(), string.Join(" | ", page.HasFormDialog() ? page.FormDialog().Alerts() : []))); + var bodies = api.Bodies(HttpMethod.Post, "/api/series"); + Assert.AreEqual(before + 1, bodies.Count, "one Series per create"); + Assert.AreEqual(0, api.Count(HttpMethod.Post, "/api/events"), "a repeating create sends no Event"); + return (JsonSerializer.Deserialize(bodies[^1]!, JsonSerializerOptions.Web)!, bodies[^1]!); + } + + private static void AssertStart(SeriesEntity series, string body) + { + Assert.AreEqual(new DateTimeOffset(2026, 12, 10, 19, 0, 0, Kathmandu), series.Schedule.First); + Assert.AreEqual(Kathmandu, series.Schedule.First.Offset); + StringAssert.Contains(body, $"\"first\":\"{Start}\""); + } + + private static void AssertOff(IRenderedComponent page) + { + Assert.IsFalse(IsOn(page)); + Assert.IsEmpty(Section(page).QuerySelectorAll("fluent-select")); + Assert.IsNull(Section(page).QuerySelector(".repeat-hint")); + } + + private static IElement Section(IRenderedComponent page) => page.FormDialog().QuerySelector(".repeat-section")!; + + private static IElement SwitchNamed(IRenderedComponent page, string label) => + page.FormDialog().QuerySelectorAll("fluent-switch").Single(s => s.GetAttribute("aria-label") == label); + + private static IElement RepeatSwitch(IRenderedComponent page) => SwitchNamed(page, "Repeat"); + + private static bool IsOn(IRenderedComponent page) => RepeatSwitch(page).HasAttribute("current-checked"); + + private static Task SwitchRepeat(IRenderedComponent page, bool on) => + RepeatSwitch(page).TriggerEventAsync("onswitchcheckedchange", new CheckboxChangeEventArgs { Checked = on }); + + private static IElement Select(IRenderedComponent page, string label) => + Section(page).QuerySelectorAll("fluent-select").Single(s => s.GetAttribute("aria-label") == label); + + private static Task Choose(IRenderedComponent page, string label, string value) => + Select(page, label).QuerySelectorAll("fluent-option").Single(o => o.GetAttribute("value") == value).ClickAsync(new()); + + private static Task Check(IRenderedComponent page, string group, string label) => + page.FormDialog().QuerySelector($"[role=group][aria-label='{group}']")!.QuerySelectorAll("fluent-checkbox") + .Single(c => c.TextContent.Trim() == label).TriggerEventAsync("oncheckedchange", new CheckboxChangeEventArgs { Checked = true }); + + private static IElement EndBox(IRenderedComponent page) => Section(page).QuerySelector("fluent-text-field.fluent-datepicker")!; + + private static Task TypeEnd(IRenderedComponent page, string date) => EndBox(page).ChangeAsync(new ChangeEventArgs { Value = date }); +} diff --git a/MW-GC.EventManager.Web.Tests/ServiceRouteContractTests.cs b/MW-GC.EventManager.Web.Tests/ServiceRouteContractTests.cs index 99125b2..f9069a5 100644 --- a/MW-GC.EventManager.Web.Tests/ServiceRouteContractTests.cs +++ b/MW-GC.EventManager.Web.Tests/ServiceRouteContractTests.cs @@ -47,6 +47,9 @@ private static string Display(Type service) => service.IsGenericType new(typeof(EventService), nameof(EventService.GetFeedbackLinkAsync), "GET", "api/events/{id}/feedback-link", h => new EventService(h).GetFeedbackLinkAsync(Id)), new(typeof(EventService), nameof(EventService.GetLikesAsync), "GET", "api/events/{id}/likes", h => new EventService(h).GetLikesAsync(Id)), + // A Series and its Occurrences (#204): only the create so far. + new(typeof(SeriesService), nameof(SeriesService.CreateAsync), "POST", "api/series", h => new SeriesService(h).CreateAsync(new SeriesEntity { Id = Id }, Guid.NewGuid())), + new(typeof(EventMetricsClient), nameof(EventMetricsClient.LoadAllAsync), "GET", "api/event-metrics", h => new EventMetricsClient(h).LoadAllAsync()), new(typeof(EventMetricsClient), nameof(EventMetricsClient.GetAsync), "GET", "api/events/{id}/metrics", h => new EventMetricsClient(h).GetAsync(Id)), new(typeof(EventMetricsClient), nameof(EventMetricsClient.SaveAsync), "PUT", "api/events/{id}/metrics", h => new EventMetricsClient(h).SaveAsync(Id, new EventMetricsEntity(), null)), @@ -78,7 +81,7 @@ .. LibraryRows("api/activities", "api/activities/{id}"), private static readonly Type[] Services = [ - typeof(ActivityService), typeof(EventService), typeof(EventMetricsClient), typeof(CommentClient), + typeof(ActivityService), typeof(EventService), typeof(SeriesService), typeof(EventMetricsClient), typeof(CommentClient), typeof(LibraryClient), typeof(LibraryClient), typeof(LibraryClient), typeof(LibraryClient) ]; @@ -134,6 +137,21 @@ public async Task EventSaveSendsTheIdempotencyKeyHeader() Assert.AreEqual(key.ToString("D"), Assert.ContainsSingle(request.IdempotencyKey)); } + // #204: a Series create sends its key exactly as an Event create does. + [TestMethod] + public async Task SeriesCreateSendsTheIdempotencyKeyHeader() + { + var key = Guid.NewGuid(); + var (client, recorder) = Client(Table.Single(r => r.Service == typeof(SeriesService))); + + await new SeriesService(client).CreateAsync(new SeriesEntity { Id = Id }, key); + + var request = Assert.ContainsSingle(recorder.Sent); + Assert.AreEqual(HttpMethod.Post, request.Method); + Assert.AreEqual("api/series", request.Path); + Assert.AreEqual(key.ToString("D"), Assert.ContainsSingle(request.IdempotencyKey)); + } + [TestMethod] public void EveryRowMatchesARouteTheApiDeclares() { diff --git a/MW-GC.EventManager.Web.Tests/StubApiHandler.cs b/MW-GC.EventManager.Web.Tests/StubApiHandler.cs index 0aad3a2..e34d858 100644 --- a/MW-GC.EventManager.Web.Tests/StubApiHandler.cs +++ b/MW-GC.EventManager.Web.Tests/StubApiHandler.cs @@ -50,12 +50,19 @@ public TaskCompletionSource Hold(HttpMethod method, string path, Func IfMatches(HttpMethod method, string path) => _ifMatches.Where(r => r.Method == method && r.Path == path).Select(r => r.IfMatch).ToList(); + // The Idempotency-Key headers sent to one route, oldest first (null for a request without one). + public List IdempotencyKeys(HttpMethod method, string path) => + _keys.Where(r => r.Method == method && r.Path == path).Select(r => r.Key).ToList(); + + private readonly List<(HttpMethod Method, string Path, string? Key)> _keys = []; + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var path = request.RequestUri!.AbsolutePath; var body = request.Content is null ? null : await request.Content.ReadAsStringAsync(cancellationToken); Requests.Add((request.Method, path, body)); _ifMatches.Add((request.Method, path, request.Headers.TryGetValues("If-Match", out var tags) ? string.Join(", ", tags) : null)); + _keys.Add((request.Method, path, request.Headers.TryGetValues("Idempotency-Key", out var keys) ? string.Join(", ", keys) : null)); foreach (var route in _routes) if (route.Method == request.Method && route.Path == path) return await route.Respond(); diff --git a/MW-GC.EventManager.Web/Services/AppServices.cs b/MW-GC.EventManager.Web/Services/AppServices.cs index 754cd5b..a32a682 100644 --- a/MW-GC.EventManager.Web/Services/AppServices.cs +++ b/MW-GC.EventManager.Web/Services/AppServices.cs @@ -27,6 +27,7 @@ public static IServiceCollection AddAppServices(this IServiceCollection services services.AddLibraryClients(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/MW-GC.EventManager.Web/Services/SeriesService.cs b/MW-GC.EventManager.Web/Services/SeriesService.cs new file mode 100644 index 0000000..1fecd9f --- /dev/null +++ b/MW-GC.EventManager.Web/Services/SeriesService.cs @@ -0,0 +1,21 @@ +using System.Net.Http.Json; +using MW_GC.EventManager.Shared.Entities; + +namespace MW_GC.EventManager.Web.Services; + +/// +/// The Series routes (#204, ADR 0002). Only the create for now: the Series stores itself under its +/// Idempotency-Key and makes its Occurrences at once, so a retry with the same key never makes a second one. +/// +public sealed class SeriesService(HttpClient http) +{ + public async Task CreateAsync(SeriesEntity series, Guid idempotencyKey) + { + using var request = new HttpRequestMessage(HttpMethod.Post, "api/series") + { + Content = JsonContent.Create(series) + }; + request.Headers.Add("Idempotency-Key", idempotencyKey.ToString("D")); + return await http.SendAsync(request); + } +} diff --git a/MW-GC.EventManager.Web/Shared/Events/EventEditDialog.razor b/MW-GC.EventManager.Web/Shared/Events/EventEditDialog.razor index 6d45aff..17d809f 100644 --- a/MW-GC.EventManager.Web/Shared/Events/EventEditDialog.razor +++ b/MW-GC.EventManager.Web/Shared/Events/EventEditDialog.razor @@ -3,6 +3,7 @@ the save's busy guard. The page opens it (OpenCreate, OpenEdit) and hears back when an Event was saved, so it can reload its list, and when a message belongs on the page instead of here. *@ @inject EventService EventSvc +@inject SeriesService SeriesSvc @inject FocusReturn Focus @if (_showCustomize) @@ -29,6 +30,13 @@ + @* #100, #204: a new Event can repeat; an edited one never shows this. *@ + @if (_editingEvent is null) + { + @* Changed re-renders this dialog, so Create follows the end date's check. *@ + + } + @@ -40,7 +48,7 @@ Cancel + Disabled="@(string.IsNullOrWhiteSpace(_custName) || Repeating && _repeat.EndProblem(BuildEventDate()) is not null)"> @(_editingEvent is not null ? "Update Event" : "Create Event") @@ -95,6 +103,10 @@ private AvoidRecentFilter _avoidRecent = new(); // The slots and every rule that fills them; the dialog keeps only what its inputs bind. private readonly SlotPlanner _planner = new(Random.Shared); + // The Repeat section (#100, #204): off with every opening, shown in a create only. + private RepeatChoice _repeat = new(); + // A create with Repeat on saves a Series instead of the Event. + private bool Repeating => _editingEvent is null && _repeat.IsOn; // The planner always rolls from the library and the Events the page holds now. protected override void OnParametersSet() @@ -142,6 +154,7 @@ _custUniqueGames = true; _playersDuration = new(); _avoidRecent = new(); + _repeat = new(); SyncFilter(); _planner.SetSlots([]); _planner.AddSlotError = null; @@ -191,6 +204,7 @@ // As the other Filters count; the typed text, so text that is not valid counts too. PlayersDuration = _playersDuration.Texts, AvoidRecent = _avoidRecent.Text, + Repeat = _repeat.Snapshot(), Slots = _planner.Slots.Select(s => new { s.GameId, s.ActivityId }) }; @@ -259,6 +273,13 @@ _customizeError = "Select 1–5 activities before saving. Adjust the filters or add an activity slot."; return; } + // Repeat on: one Series, no Event. Its Occurrences start with no Selections, so the roll is not saved. + if (Repeating) + { + var series = BuildSeries(); + await SendAsync(() => SeriesSvc.CreateAsync(series, _createKey)); + return; + } // Unchanged slots save their stored snapshot; a changed slot must be a library choice. var built = slots.Select(BuildSelection).ToList(); if (slots.Any(s => s.GameId == Guid.Empty || s.ActivityId == Guid.Empty) || built.Any(s => s is null)) @@ -281,17 +302,34 @@ _customizeError = "Activities must be distinct, and games must be distinct when Unique games only is enabled."; return; } + entity.NormalizeWinner(); + await SendAsync(() => _editingEvent is not null ? EventSvc.UpdateAsync(entity) : EventSvc.SaveAsync(entity, _createKey)); + } + + // The Series a create with Repeat on sends (#204): the start exactly as the Event's, its offset kept (the Series' + // calendar arithmetic runs at it), the slot count and the Filters the dialog holds. Avoid recent, players tonight + // and longest duration are not in a Series' Filters and are not sent. + private SeriesEntity BuildSeries() => new() + { + Id = _createKey, + Name = _custName, + Schedule = _repeat.ScheduleFor(BuildEventDate()), + SlotCount = _planner.Slots.Count, + UniqueGamesOnly = _custUniqueGames, + Filters = new SeriesFilters { ThemedOnly = _custThemedOnly, GameIds = _custGameIds.ToList(), ThemeIds = _custThemeIds.ToList(), HolidayIds = _custHolidayIds.ToList() } + }; + + // Runs one save: its busy guard, the page's message cleared first, the API's message in this dialog (or the page's + // error bar once it closed), and the close and list reload on success. _createKey is kept on any failure. + private async Task SendAsync(Func> send) + { _generating = true; // The dialog this save belongs to; a dismissed or replaced dialog is left alone. var token = _customize.Current; try { await PageError.InvokeAsync(null); - entity.NormalizeWinner(); - - using var response = _editingEvent is not null - ? await EventSvc.UpdateAsync(entity) - : await EventSvc.SaveAsync(entity, _createKey); + using var response = await send(); if (await ApiResult.ErrorAsync(response) is { } error) { if (_customize.IsCurrent(token)) _customizeError = $"The event was not saved. {error}"; diff --git a/MW-GC.EventManager.Web/Shared/Events/EventList.razor b/MW-GC.EventManager.Web/Shared/Events/EventList.razor index 9b9bdf6..eca82e1 100644 --- a/MW-GC.EventManager.Web/Shared/Events/EventList.razor +++ b/MW-GC.EventManager.Web/Shared/Events/EventList.razor @@ -16,7 +16,16 @@ - + @* #100, #204: an Occurrence of a Series carries the repeat marker beside its name; a standalone Event none. *@ + + @if (context.SeriesId is not null) + { + + + } + @context.Name + @context.Date.ToLocalTime().ToString("g") @@ -78,6 +87,8 @@ // Sorts the grid by the underlying instant while the column renders local time. private static readonly GridSort _dateSort = GridSort.ByAscending(e => e.Date); + // The Name column sorts by the name alone, as it did as a property column. + private static readonly GridSort _nameSort = GridSort.ByAscending(e => e.Name); private IQueryable Filtered => string.IsNullOrWhiteSpace(_search) ? Events.AsQueryable() diff --git a/MW-GC.EventManager.Web/Shared/Events/RepeatChoice.cs b/MW-GC.EventManager.Web/Shared/Events/RepeatChoice.cs new file mode 100644 index 0000000..59acee5 --- /dev/null +++ b/MW-GC.EventManager.Web/Shared/Events/RepeatChoice.cs @@ -0,0 +1,141 @@ +using MW_GC.EventManager.Shared.Series; + +namespace MW_GC.EventManager.Web.Shared.Events; + +/// One choice in a Repeat select: the value it stands for and the words the admin reads. +public sealed record RepeatOption(T Value, string Name); + +/// +/// The Repeat section of the create Event dialog (#100, #204): whether the new Event repeats, on which rule, and +/// the optional end, turned into the Series' schedule. Pure: no clock, no JS, no services. The dialog keeps one for +/// each opening, so Repeat is off with every opening. Monthly on the nth weekday and Yearly on a holiday take their +/// defaults from the picked date (its weekday, which week of the month it is in, the holiday that falls on it) until +/// the admin picks a value, so moving the date moves an untouched default with it. +/// +public sealed class RepeatChoice +{ + /// The API's own wording for an end that is not after the start (SeriesValidator.EndMessage). + public const string EndMessage = "End must be after the start."; + + /// The rules offered, Weekly first, in the words the admin reads. Not daily, not custom. + public static IReadOnlyList> Rules { get; } = + [ + new(RecurrenceKind.Weekly, "Weekly"), + new(RecurrenceKind.BiWeekly, "Every other week"), + new(RecurrenceKind.MonthlyNthWeekday, "Monthly on the nth weekday"), + new(RecurrenceKind.MonthlySameDate, "Monthly on the same date"), + new(RecurrenceKind.AnnualSameDate, "Yearly on the same date"), + new(RecurrenceKind.AnnualHoliday, "Yearly on a holiday"), + ]; + + /// The weeks of a month a monthly nth-weekday rule can pick; there is no fifth. + public static IReadOnlyList> Weeks { get; } = + [ + new(WeekOfMonth.First, "First"), + new(WeekOfMonth.Second, "Second"), + new(WeekOfMonth.Third, "Third"), + new(WeekOfMonth.Fourth, "Fourth"), + new(WeekOfMonth.Last, "Last"), + ]; + + /// The weekdays, Sunday first. + public static IReadOnlyList> Weekdays { get; } = + Enum.GetValues().Select(d => new RepeatOption(d, d.ToString())).ToList(); + + /// The one table of readable names for the holiday presets, in calendar order. + public static IReadOnlyList> Holidays { get; } = + [ + new(HolidayPreset.NewYearsDay, "New Year's Day"), + new(HolidayPreset.MartinLutherKingJrDay, "Martin Luther King Jr. Day"), + new(HolidayPreset.ValentinesDay, "Valentine's Day"), + new(HolidayPreset.PresidentsDay, "Presidents' Day"), + new(HolidayPreset.StPatricksDay, "St. Patrick's Day"), + new(HolidayPreset.EarthDay, "Earth Day"), + new(HolidayPreset.EasterSunday, "Easter Sunday"), + new(HolidayPreset.MothersDay, "Mother's Day"), + new(HolidayPreset.MemorialDay, "Memorial Day"), + new(HolidayPreset.FathersDay, "Father's Day"), + new(HolidayPreset.IndependenceDay, "Independence Day"), + new(HolidayPreset.LaborDay, "Labor Day"), + new(HolidayPreset.ColumbusDay, "Columbus Day / Indigenous Peoples' Day"), + new(HolidayPreset.Halloween, "Halloween"), + new(HolidayPreset.Thanksgiving, "Thanksgiving"), + new(HolidayPreset.ChristmasEve, "Christmas Eve"), + new(HolidayPreset.Christmas, "Christmas Day"), + new(HolidayPreset.NewYearsEve, "New Year's Eve"), + ]; + + /// Whether the new Event repeats. Off until the admin turns it on. + public bool IsOn { get; set; } + + public RecurrenceKind Kind { get; set; } = RecurrenceKind.Weekly; + + /// The week and weekday the admin picked for a monthly nth-weekday rule; null follows the date. + public WeekOfMonth? ChosenWeek { get; set; } + public DayOfWeek? ChosenWeekday { get; set; } + + /// The holiday the admin picked; null follows the date. + public HolidayPreset? ChosenHoliday { get; set; } + + /// The last day an Occurrence may fall on, or null for no end. + public DateOnly? EndDate { get; set; } + + public WeekOfMonth WeekFor(DateOnly start) => ChosenWeek ?? DefaultWeek(start); + public DayOfWeek WeekdayFor(DateOnly start) => ChosenWeekday ?? start.DayOfWeek; + public HolidayPreset HolidayFor(DateOnly start) => ChosenHoliday ?? DefaultHoliday(start); + + /// + /// Which week of its month is in: First to Fourth by its day (the 1st to 7th is First, and + /// so on), and Last for a fifth one (the 29th to the 31st), since there is no fifth. A date that is both the fourth + /// and the last of its weekday (the 22nd to the 28th in the month's last seven days) stays Fourth; Last is always + /// offered in . + /// + public static WeekOfMonth DefaultWeek(DateOnly date) => ((date.Day - 1) / 7) switch + { + 0 => WeekOfMonth.First, + 1 => WeekOfMonth.Second, + 2 => WeekOfMonth.Third, + 3 => WeekOfMonth.Fourth, + _ => WeekOfMonth.Last, + }; + + /// The holiday that falls on , or the first in the table when none does. + public static HolidayPreset DefaultHoliday(DateOnly date) => + Holidays.Select(h => h.Value).FirstOrDefault(h => HolidayPresets.DateIn(h, date.Year) == date, Holidays[0].Value); + + /// The readable name of . + public static string HolidayName(HolidayPreset preset) => Holidays.Single(h => h.Value == preset).Name; + + /// The rule the choices make for a Series that starts on . + public RecurrenceRule RuleFor(DateOnly start) => Kind switch + { + RecurrenceKind.Weekly => RecurrenceRule.Weekly(), + RecurrenceKind.BiWeekly => RecurrenceRule.BiWeekly(), + RecurrenceKind.MonthlyNthWeekday => RecurrenceRule.MonthlyNthWeekday(WeekFor(start), WeekdayFor(start)), + RecurrenceKind.MonthlySameDate => RecurrenceRule.MonthlySameDate(), + RecurrenceKind.AnnualSameDate => RecurrenceRule.AnnualSameDate(), + RecurrenceKind.AnnualHoliday => RecurrenceRule.AnnualHoliday(HolidayFor(start)), + _ => throw new ArgumentOutOfRangeException(nameof(Kind), Kind, "Repeat must be a known rule."), + }; + + /// + /// The end instant: at 's time of day and UTC offset, the offset the + /// Series' calendar arithmetic runs at, so an Occurrence on the end date is made and none after it. Null for none. + /// + public DateTimeOffset? EndFor(DateTimeOffset first) => EndDate is { } end + ? new DateTimeOffset(end.ToDateTime(TimeOnly.FromTimeSpan(first.TimeOfDay)), first.Offset) + : null; + + /// The API's message when the end is not after ; null when it is, or there is none. + public string? EndProblem(DateTimeOffset first) => EndFor(first) is { } end && end <= first ? EndMessage : null; + + /// + /// The Series' schedule: exactly as given (its offset kept), the rule and the end. The + /// weekday, week and date the rule reads are 's own, at its offset. + /// + public RecurrenceSeries ScheduleFor(DateTimeOffset first) => + new(first, RuleFor(DateOnly.FromDateTime(first.DateTime)), EndFor(first)); + + /// What the admin chose, for the dialog's unsaved-changes check; defaults that follow the date are not choices. + public object Snapshot() => new { IsOn, Kind, ChosenWeek, ChosenWeekday, ChosenHoliday, EndDate }; +} diff --git a/MW-GC.EventManager.Web/Shared/Events/RepeatSection.razor b/MW-GC.EventManager.Web/Shared/Events/RepeatSection.razor new file mode 100644 index 0000000..4b2e936 --- /dev/null +++ b/MW-GC.EventManager.Web/Shared/Events/RepeatSection.razor @@ -0,0 +1,82 @@ +@* The Repeat section of the create Event dialog (#100, #204): the Repeat switch, the rule, the extra selects only the + rule that needs them shows (the week and weekday for Monthly on the nth weekday, the holiday for Yearly on a + holiday) and the optional end date. The choices live in Choice (RepeatChoice), which the dialog owns and resets + with every opening; every change is handed back through Changed, so the dialog can enable or disable Create. *@ +@using MW_GC.EventManager.Shared.Series + +
+ + + @if (Choice.IsOn) + { +
@Hint
+ + + + + @if (Choice.Kind == RecurrenceKind.MonthlyNthWeekday) + { + + + + + + + } + @if (Choice.Kind == RecurrenceKind.AnnualHoliday) + { + + + + } + + + @if (Choice.EndProblem(Start) is { } problem) + { +
@problem
+ } +
+
+ } +
+
+ +@code { + /// The one hint under the switch: what a repeating Event saves, and that the roll shown is not saved. + public const string Hint = "Each repeat starts with no picks yet: the activities rolled below are not saved."; + + // The dialog's choices for this opening. + [Parameter, EditorRequired] public RepeatChoice Choice { get; set; } = null!; + // The start as the dialog saves it: the defaults (weekday, week, holiday) follow its date, and the end must be after it. + [Parameter] public DateTimeOffset Start { get; set; } + // A choice changed and Choice already holds it. + [Parameter] public EventCallback Changed { get; set; } + + private DateOnly StartDate => DateOnly.FromDateTime(Start.DateTime); + + // The end date box: a day, or empty for no end. + private DateTime? EndValue + { + get => Choice.EndDate?.ToDateTime(TimeOnly.MinValue); + set => Choice.EndDate = value is { } day ? DateOnly.FromDateTime(day) : null; + } + + private Task Change(Action apply) + { + apply(); + return Changed.InvokeAsync(); + } +} From a559789034ac28c19bfe1eb9f175b163d2a61c4d Mon Sep 17 00:00:00 2001 From: "MWG Bender[bot]" <331880973+mwg-bender[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:47:48 +0000 Subject: [PATCH 2/2] fix(web): disambiguate holiday presets and protect edits PR #231 review fix-up. A holiday preset is a date rule, not the Holiday tag on Activities (GLOSSARY.md, ADR 0002), so the repeat model no longer calls presets plain "Holiday": RepeatChoice.Holidays becomes HolidayPresetOptions (HolidayPresets is already the Shared rules table), and ChosenHoliday, HolidayFor, DefaultHoliday and HolidayName become ChosenHolidayPreset, HolidayPresetFor, DefaultHolidayPreset and HolidayPresetName. The select's label and accessible name are now "Holiday preset". The rule wording "Yearly on a holiday" and the readable preset names are unchanged. New tests pin what the review found unguarded, each shown able to fail by a throwaway mutation: - an Edit saved after a cancelled repeating create is a PUT of the Event and sends no Series (Repeating guard on _editingEvent); - the Holiday preset select's accessible name and selected preset; - turning Repeat on counts as an unsaved change (Repeat snapshot); - the Events Name header still sorts by name (TemplateColumn SortBy); - the repeat marker's title, and the exact lost-answer alert text. Refs #100, #204 --- .../EmptyOccurrenceTests.cs | 1 + .../ListsAtScaleTests.cs | 11 ++ .../RepeatChoiceTests.cs | 14 +- .../RepeatSectionDialogTests.cs | 9 +- .../RepeatSectionGuardTests.cs | 138 ++++++++++++++++++ .../Shared/Events/RepeatChoice.cs | 25 ++-- .../Shared/Events/RepeatSection.razor | 14 +- 7 files changed, 183 insertions(+), 29 deletions(-) create mode 100644 MW-GC.EventManager.Web.Tests/RepeatSectionGuardTests.cs diff --git a/MW-GC.EventManager.Web.Tests/EmptyOccurrenceTests.cs b/MW-GC.EventManager.Web.Tests/EmptyOccurrenceTests.cs index 00fc532..3ef9d11 100644 --- a/MW-GC.EventManager.Web.Tests/EmptyOccurrenceTests.cs +++ b/MW-GC.EventManager.Web.Tests/EmptyOccurrenceTests.cs @@ -48,6 +48,7 @@ public void TheList_MarksTheOccurrenceOnly_AndShowsZeroSelectionsAndNoWinner() var marker = Assert.ContainsSingle(occurrence.QuerySelectorAll(".repeat-marker")); Assert.AreEqual("Repeats", marker.GetAttribute("aria-label")); Assert.AreEqual("img", marker.GetAttribute("role")); + Assert.AreEqual("Repeats", marker.GetAttribute("title"), "the marker's hover text"); Assert.IsEmpty(Row(page, "Game night").QuerySelectorAll(".repeat-marker")); var cells = occurrence.QuerySelectorAll("td").Select(c => Normalize(c.TextContent)).ToList(); diff --git a/MW-GC.EventManager.Web.Tests/ListsAtScaleTests.cs b/MW-GC.EventManager.Web.Tests/ListsAtScaleTests.cs index a0f87c5..401091c 100644 --- a/MW-GC.EventManager.Web.Tests/ListsAtScaleTests.cs +++ b/MW-GC.EventManager.Web.Tests/ListsAtScaleTests.cs @@ -81,6 +81,17 @@ public async Task Events_DateHeaderClick_StillReSorts() Order(page, events.Select(e => e.Name)))); } + // #100, #204: the Name column became a template column (for the repeat marker); its header still sorts by the name, + // not the date (by date, March night would come before July night). + [TestMethod] + public async Task Events_NameHeaderClick_SortsByName() + { + var page = Open("events"); + await SortHeader(page, "Name").ClickAsync(new MouseEventArgs()); + page.WaitForAssertion(() => Assert.AreEqual("December night, January night, July night, March night, October night", + Order(page, events.Select(e => e.Name)))); + } + [TestMethod] public async Task Events_NewEventAppearsAtTheTop() { diff --git a/MW-GC.EventManager.Web.Tests/RepeatChoiceTests.cs b/MW-GC.EventManager.Web.Tests/RepeatChoiceTests.cs index cdd7447..73ee079 100644 --- a/MW-GC.EventManager.Web.Tests/RepeatChoiceTests.cs +++ b/MW-GC.EventManager.Web.Tests/RepeatChoiceTests.cs @@ -114,7 +114,7 @@ public void TheHoliday_DefaultsToTheOneOnThePickedDate_AndAChosenOneWins() var choice = new RepeatChoice { IsOn = true, Kind = RecurrenceKind.AnnualHoliday }; Assert.AreEqual(RecurrenceRule.AnnualHoliday(HolidayPreset.Thanksgiving), choice.ScheduleFor(thanksgiving).Rule); - choice.ChosenHoliday = HolidayPreset.EasterSunday; + choice.ChosenHolidayPreset = HolidayPreset.EasterSunday; Assert.AreEqual(RecurrenceRule.AnnualHoliday(HolidayPreset.EasterSunday), choice.ScheduleFor(thanksgiving).Rule); } @@ -124,14 +124,14 @@ public void EveryHolidayPreset_HasOneReadableName() { foreach (var preset in Enum.GetValues()) { - var name = Assert.ContainsSingle(RepeatChoice.Holidays.Where(h => h.Value == preset)).Name; + var name = Assert.ContainsSingle(RepeatChoice.HolidayPresetOptions.Where(h => h.Value == preset)).Name; Assert.IsFalse(string.IsNullOrWhiteSpace(name), preset.ToString()); } - Assert.HasCount(Enum.GetValues().Length, RepeatChoice.Holidays); - Assert.HasCount(RepeatChoice.Holidays.Count, RepeatChoice.Holidays.Select(h => h.Name).Distinct()); - Assert.AreEqual("Thanksgiving", RepeatChoice.HolidayName(HolidayPreset.Thanksgiving)); - Assert.AreEqual("Martin Luther King Jr. Day", RepeatChoice.HolidayName(HolidayPreset.MartinLutherKingJrDay)); - Assert.AreEqual("St. Patrick's Day", RepeatChoice.HolidayName(HolidayPreset.StPatricksDay)); + Assert.HasCount(Enum.GetValues().Length, RepeatChoice.HolidayPresetOptions); + Assert.HasCount(RepeatChoice.HolidayPresetOptions.Count, RepeatChoice.HolidayPresetOptions.Select(h => h.Name).Distinct()); + Assert.AreEqual("Thanksgiving", RepeatChoice.HolidayPresetName(HolidayPreset.Thanksgiving)); + Assert.AreEqual("Martin Luther King Jr. Day", RepeatChoice.HolidayPresetName(HolidayPreset.MartinLutherKingJrDay)); + Assert.AreEqual("St. Patrick's Day", RepeatChoice.HolidayPresetName(HolidayPreset.StPatricksDay)); } // The start is sent exactly as given, its offset kept, and the end is the end date at the start's time and offset. diff --git a/MW-GC.EventManager.Web.Tests/RepeatSectionDialogTests.cs b/MW-GC.EventManager.Web.Tests/RepeatSectionDialogTests.cs index aab2ed0..f326640 100644 --- a/MW-GC.EventManager.Web.Tests/RepeatSectionDialogTests.cs +++ b/MW-GC.EventManager.Web.Tests/RepeatSectionDialogTests.cs @@ -22,6 +22,7 @@ public sealed class RepeatSectionDialogTests : IDisposable { private const string Start = "2026-12-10T19:00:00+05:45"; private const string EndMessage = "End must be after the start."; + private const string LostAnswer = "The save could not be confirmed. Retry in this dialog to avoid creating a duplicate. If you changed the details, reload the event list and check for the saved event first."; private static readonly TimeSpan Kathmandu = new(5, 45, 0); private readonly StubApiHandler api = new(); private readonly PageHarness harness; @@ -84,7 +85,7 @@ public async Task Repeat_IsOffWhenTheDialogOpens_AndOffAgainAfterReopening() [DataRow(RecurrenceKind.MonthlyNthWeekday, new[] { "Week of the month", "Weekday" })] [DataRow(RecurrenceKind.MonthlySameDate, new string[0])] [DataRow(RecurrenceKind.AnnualSameDate, new string[0])] - [DataRow(RecurrenceKind.AnnualHoliday, new[] { "Holiday" })] + [DataRow(RecurrenceKind.AnnualHoliday, new[] { "Holiday preset" })] public async Task EachRule_ShowsExactlyItsExtraSelects(RecurrenceKind kind, string[] extra) { var page = await OpenCreate(); @@ -136,9 +137,9 @@ public async Task TheChosenWeekWeekdayAndHoliday_AreSent() await OpenCreate(page); await SwitchRepeat(page, true); await Choose(page, "Repeats", nameof(RecurrenceKind.AnnualHoliday)); - Assert.AreEqual("Thanksgiving", Select(page, "Holiday").QuerySelectorAll("fluent-option") + Assert.AreEqual("Thanksgiving", Select(page, "Holiday preset").QuerySelectorAll("fluent-option") .Single(o => o.GetAttribute("value") == nameof(HolidayPreset.Thanksgiving)).TextContent.Trim()); - await Choose(page, "Holiday", nameof(HolidayPreset.Thanksgiving)); + await Choose(page, "Holiday preset", nameof(HolidayPreset.Thanksgiving)); (series, _) = await CreateSeries(page); Assert.AreEqual(RecurrenceRule.AnnualHoliday(HolidayPreset.Thanksgiving), series.Schedule.Rule); } @@ -208,7 +209,7 @@ public async Task ARetryAfterALostAnswer_SendsTheSameIdempotencyKey() var page = await OpenCreate(); await SwitchRepeat(page, true); await page.FormDialog().Button("Create Event").ClickAsync(new()); - page.WaitForAssertion(() => Assert.IsNotEmpty(page.FormDialog().Alerts())); + page.WaitForAssertion(() => Assert.AreEqual(LostAnswer, Assert.ContainsSingle(page.FormDialog().Alerts()))); api.Status(HttpMethod.Post, "/api/series", HttpStatusCode.Created, "{}"); await page.FormDialog().Button("Create Event").ClickAsync(new()); diff --git a/MW-GC.EventManager.Web.Tests/RepeatSectionGuardTests.cs b/MW-GC.EventManager.Web.Tests/RepeatSectionGuardTests.cs new file mode 100644 index 0000000..cab0ed2 --- /dev/null +++ b/MW-GC.EventManager.Web.Tests/RepeatSectionGuardTests.cs @@ -0,0 +1,138 @@ +using System.Globalization; +using System.Net; +using System.Text.Json; +using AngleSharp.Dom; +using Bunit; +using Microsoft.AspNetCore.Components; +using Microsoft.FluentUI.AspNetCore.Components; +using MW_GC.EventManager.Shared.Entities; +using MW_GC.EventManager.Web.Pages; +using static MW_GC.EventManager.Web.Tests.PageActions; + +namespace MW_GC.EventManager.Web.Tests; + +// #100, #204: what keeps the Repeat section of the create Event dialog inside a create, on the real Events page over a +// stub API: an Edit saved after a cancelled repeating create is still an Event update, never a Series. +[TestClass] +public sealed class RepeatSectionGuardTests : IDisposable +{ + private readonly StubApiHandler api = new(); + private readonly PageHarness harness; + private readonly GameEntity kart = new() { Name = "Kart" }, brawl = new() { Name = "Brawl" }; + private readonly EventEntity night; + private readonly CultureInfo culture = CultureInfo.CurrentCulture; + + public RepeatSectionGuardTests() + { + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; + var grandPrix = new ActivityEntity { Name = "Grand Prix", GameId = kart.Id }; + var stock = new ActivityEntity { Name = "Stock", GameId = brawl.Id }; + night = new EventEntity { Name = "Game night", Date = new DateTimeOffset(2026, 10, 9, 19, 0, 0, TimeSpan.Zero), Selections = [Pick(kart, grandPrix)] }; + api.Json(HttpMethod.Get, "/api/games", new[] { kart, brawl }) + .Json(HttpMethod.Get, "/api/activities", new[] { grandPrix, stock }) + .Json(HttpMethod.Get, "/api/themes", Array.Empty()) + .Json(HttpMethod.Get, "/api/holidays", Array.Empty()) + .Json(HttpMethod.Get, "/api/events", new[] { night }) + .Status(HttpMethod.Post, "/api/series", HttpStatusCode.Created, "{}") + .Status(HttpMethod.Post, "/api/events", HttpStatusCode.Created, "{}") + .Status(HttpMethod.Put, $"/api/events/{night.Id}", HttpStatusCode.OK, "{}"); + harness = new PageHarness(api); + } + + public void Dispose() + { + harness.Dispose(); + CultureInfo.CurrentCulture = culture; + } + + // Repeat turned on in a create that was cancelled must not leak into the next Edit: the Edit never shows Repeat, + // and its save is the Event's own PUT, with no Series sent. + [TestMethod] + public async Task AnEditSaved_AfterARepeatingCreateWasCancelled_UpdatesTheEvent_AndSendsNoSeries() + { + var page = OpenPage(); + await page.Button("Create Event").ClickAsync(new()); + await SwitchRepeat(page, true); + Assert.IsTrue(RepeatSwitch(page).HasAttribute("current-checked"), "Repeat did not turn on in the create"); + await page.FormDialog().Button("Cancel").ClickAsync(new()); + + await RowButton(page, "Game night", "Edit").ClickAsync(new()); + Assert.AreEqual("Edit Event", page.DialogTitle()); + Assert.IsNull(page.FormDialog().QuerySelector(".repeat-section")); + await page.FormDialog().Button("Update Event").ClickAsync(new()); + + page.WaitForAssertion(() => Assert.IsFalse(page.HasFormDialog(), string.Join(" | ", page.HasFormDialog() ? page.FormDialog().Alerts() : []))); + Assert.AreEqual(0, api.Count(HttpMethod.Post, "/api/series"), "an Edit sent a Series"); + Assert.AreEqual(0, api.Count(HttpMethod.Post, "/api/events"), "an Edit created an Event"); + var sent = JsonSerializer.Deserialize(Assert.ContainsSingle(api.Bodies(HttpMethod.Put, $"/api/events/{night.Id}"))!, JsonSerializerOptions.Web)!; + Assert.AreEqual(night.Id, sent.Id); + Assert.AreEqual("Game night", sent.Name); + } + + // Turning Repeat on is an unsaved change like any other input: Escape asks "Discard changes?". Turning it off again + // makes the dialog clean, so Escape closes it at once. Nothing is sent either way. + [TestMethod] + public async Task TurningRepeatOn_AsksToDiscard_AndTurningItOffAgainClosesAtOnce() + { + var page = OpenPage(); + await page.Button("Create Event").ClickAsync(new()); + await SwitchRepeat(page, true); + + await Dismiss(page); + Assert.IsTrue(page.HasFormDialog(), "Escape closed the dialog and lost Repeat"); + Assert.IsTrue(page.HasConfirmation(), "turning Repeat on did not count as a change"); + Assert.AreEqual("Discard changes?", page.Confirmation().QuerySelector("h4")!.TextContent.Trim()); + await page.Confirmation().Button("Keep editing").ClickAsync(new()); + Assert.IsTrue(RepeatSwitch(page).HasAttribute("current-checked"), "Keep editing lost Repeat"); + + await SwitchRepeat(page, false); + await Dismiss(page); + Assert.IsFalse(page.HasConfirmation(), "Repeat turned off again still asked to discard"); + Assert.IsFalse(page.HasFormDialog()); + Assert.IsEmpty(api.Requests.Where(r => r.Method != HttpMethod.Get).ToList()); + } + + // A holiday preset is a date rule, not an Activity's Holiday tag (GLOSSARY.md, ADR 0002), so its select is named + // "Holiday preset". On Thanksgiving 2026 it starts on Thanksgiving, and the preset the admin picks is the selected one. + [TestMethod] + public async Task TheHolidayPresetSelect_IsNamedHolidayPreset_AndShowsTheSelectedPreset() + { + var page = OpenPage(); + await page.Button("Create Event").ClickAsync(new()); + await page.FormDialog().QuerySelector("fluent-text-field.fluent-datepicker")!.ChangeAsync(new ChangeEventArgs { Value = "11/26/2026" }); + await SwitchRepeat(page, true); + await Choose(page, "Repeats", "AnnualHoliday"); + + var preset = Select(page, "Holiday preset"); + Assert.AreEqual("Holiday preset", preset.GetAttribute("aria-label")); + Assert.AreEqual("Thanksgiving", preset.GetAttribute("current-value")); + Assert.AreEqual("Thanksgiving", preset.QuerySelector("fluent-option[selected]")!.TextContent.Trim()); + Assert.IsFalse(page.FormDialog().QuerySelectorAll("fluent-select").Any(s => s.GetAttribute("aria-label") == "Holiday"), + "a select is still named Holiday, the Activity tag's name"); + + await Choose(page, "Holiday preset", "Christmas"); + Assert.AreEqual("Christmas", Select(page, "Holiday preset").GetAttribute("current-value")); + Assert.AreEqual("Christmas Day", Select(page, "Holiday preset").QuerySelector("fluent-option[selected]")!.TextContent.Trim()); + } + + // ---- helpers ------------------------------------------------------------------------------- + + private IRenderedComponent OpenPage() + { + var page = harness.Render(); + page.WaitForRows(1); + return page; + } + + private static IElement RepeatSwitch(IRenderedComponent page) => + page.FormDialog().QuerySelectorAll("fluent-switch").Single(s => s.GetAttribute("aria-label") == "Repeat"); + + private static Task SwitchRepeat(IRenderedComponent page, bool on) => + RepeatSwitch(page).TriggerEventAsync("onswitchcheckedchange", new CheckboxChangeEventArgs { Checked = on }); + + private static IElement Select(IRenderedComponent page, string label) => + page.FormDialog().QuerySelector(".repeat-section")!.QuerySelectorAll("fluent-select").Single(s => s.GetAttribute("aria-label") == label); + + private static Task Choose(IRenderedComponent page, string label, string value) => + Select(page, label).QuerySelectorAll("fluent-option").Single(o => o.GetAttribute("value") == value).ClickAsync(new()); +} diff --git a/MW-GC.EventManager.Web/Shared/Events/RepeatChoice.cs b/MW-GC.EventManager.Web/Shared/Events/RepeatChoice.cs index 59acee5..d4d0abc 100644 --- a/MW-GC.EventManager.Web/Shared/Events/RepeatChoice.cs +++ b/MW-GC.EventManager.Web/Shared/Events/RepeatChoice.cs @@ -42,8 +42,11 @@ public sealed class RepeatChoice public static IReadOnlyList> Weekdays { get; } = Enum.GetValues().Select(d => new RepeatOption(d, d.ToString())).ToList(); - /// The one table of readable names for the holiday presets, in calendar order. - public static IReadOnlyList> Holidays { get; } = + /// + /// The one table of readable names for the holiday presets (date rules, not the Holiday tag on Activities), in + /// calendar order. Not named HolidayPresets: that is the Shared rules table the dates come from. + /// + public static IReadOnlyList> HolidayPresetOptions { get; } = [ new(HolidayPreset.NewYearsDay, "New Year's Day"), new(HolidayPreset.MartinLutherKingJrDay, "Martin Luther King Jr. Day"), @@ -74,15 +77,15 @@ public sealed class RepeatChoice public WeekOfMonth? ChosenWeek { get; set; } public DayOfWeek? ChosenWeekday { get; set; } - /// The holiday the admin picked; null follows the date. - public HolidayPreset? ChosenHoliday { get; set; } + /// The holiday preset the admin picked; null follows the date. + public HolidayPreset? ChosenHolidayPreset { get; set; } /// The last day an Occurrence may fall on, or null for no end. public DateOnly? EndDate { get; set; } public WeekOfMonth WeekFor(DateOnly start) => ChosenWeek ?? DefaultWeek(start); public DayOfWeek WeekdayFor(DateOnly start) => ChosenWeekday ?? start.DayOfWeek; - public HolidayPreset HolidayFor(DateOnly start) => ChosenHoliday ?? DefaultHoliday(start); + public HolidayPreset HolidayPresetFor(DateOnly start) => ChosenHolidayPreset ?? DefaultHolidayPreset(start); /// /// Which week of its month is in: First to Fourth by its day (the 1st to 7th is First, and @@ -99,12 +102,12 @@ public sealed class RepeatChoice _ => WeekOfMonth.Last, }; - /// The holiday that falls on , or the first in the table when none does. - public static HolidayPreset DefaultHoliday(DateOnly date) => - Holidays.Select(h => h.Value).FirstOrDefault(h => HolidayPresets.DateIn(h, date.Year) == date, Holidays[0].Value); + /// The holiday preset that falls on , or the first in the table when none does. + public static HolidayPreset DefaultHolidayPreset(DateOnly date) => + HolidayPresetOptions.Select(h => h.Value).FirstOrDefault(h => HolidayPresets.DateIn(h, date.Year) == date, HolidayPresetOptions[0].Value); /// The readable name of . - public static string HolidayName(HolidayPreset preset) => Holidays.Single(h => h.Value == preset).Name; + public static string HolidayPresetName(HolidayPreset preset) => HolidayPresetOptions.Single(h => h.Value == preset).Name; /// The rule the choices make for a Series that starts on . public RecurrenceRule RuleFor(DateOnly start) => Kind switch @@ -114,7 +117,7 @@ public static HolidayPreset DefaultHoliday(DateOnly date) => RecurrenceKind.MonthlyNthWeekday => RecurrenceRule.MonthlyNthWeekday(WeekFor(start), WeekdayFor(start)), RecurrenceKind.MonthlySameDate => RecurrenceRule.MonthlySameDate(), RecurrenceKind.AnnualSameDate => RecurrenceRule.AnnualSameDate(), - RecurrenceKind.AnnualHoliday => RecurrenceRule.AnnualHoliday(HolidayFor(start)), + RecurrenceKind.AnnualHoliday => RecurrenceRule.AnnualHoliday(HolidayPresetFor(start)), _ => throw new ArgumentOutOfRangeException(nameof(Kind), Kind, "Repeat must be a known rule."), }; @@ -137,5 +140,5 @@ public RecurrenceSeries ScheduleFor(DateTimeOffset first) => new(first, RuleFor(DateOnly.FromDateTime(first.DateTime)), EndFor(first)); /// What the admin chose, for the dialog's unsaved-changes check; defaults that follow the date are not choices. - public object Snapshot() => new { IsOn, Kind, ChosenWeek, ChosenWeekday, ChosenHoliday, EndDate }; + public object Snapshot() => new { IsOn, Kind, ChosenWeek, ChosenWeekday, ChosenHolidayPreset, EndDate }; } diff --git a/MW-GC.EventManager.Web/Shared/Events/RepeatSection.razor b/MW-GC.EventManager.Web/Shared/Events/RepeatSection.razor index 4b2e936..eade4b6 100644 --- a/MW-GC.EventManager.Web/Shared/Events/RepeatSection.razor +++ b/MW-GC.EventManager.Web/Shared/Events/RepeatSection.razor @@ -1,6 +1,6 @@ @* The Repeat section of the create Event dialog (#100, #204): the Repeat switch, the rule, the extra selects only the - rule that needs them shows (the week and weekday for Monthly on the nth weekday, the holiday for Yearly on a - holiday) and the optional end date. The choices live in Choice (RepeatChoice), which the dialog owns and resets + rule that needs them shows (the week and weekday for Monthly on the nth weekday, the holiday preset for Yearly + on a holiday) and the optional end date. The choices live in Choice (RepeatChoice), which the dialog owns and resets with every opening; every change is handed back through Changed, so the dialog can enable or disable Create. *@ @using MW_GC.EventManager.Shared.Series @@ -35,10 +35,10 @@ @if (Choice.Kind == RecurrenceKind.AnnualHoliday) { - + } @@ -60,7 +60,7 @@ // The dialog's choices for this opening. [Parameter, EditorRequired] public RepeatChoice Choice { get; set; } = null!; - // The start as the dialog saves it: the defaults (weekday, week, holiday) follow its date, and the end must be after it. + // The start as the dialog saves it: the defaults (weekday, week, holiday preset) follow its date, and the end must be after it. [Parameter] public DateTimeOffset Start { get; set; } // A choice changed and Choice already holds it. [Parameter] public EventCallback Changed { get; set; }