From 305c2a6439489355217a992c66f16798589fd3e6 Mon Sep 17 00:00:00 2001 From: dannysusername Date: Sat, 21 Nov 2026 19:54:57 -0500 Subject: [PATCH] Alert emails: show only what's due, color the PDF, per-type schedules Email content and look (spec 013) - The alert email lists only overdue and due-soon items (owner's lead times), most urgent first, with "[new]" marks, then "The other N items are on track." No more 39 lines of "ok". - Sent as text + HTML (inline-styled template, dashboard pill colors, per-recipient stop link). Fleets: one section per aircraft with something due. - PDF Time Left is labeled OVERDUE (red) / DUE SOON (amber) using the owner's lead times, for alert, download and share PDFs. When alerts send (spec 014) - Three alert emails, each Off / Once / every N days: Due soon (default every 7 days), Overdue (every 3 days, was "re-nudge"; existing values carry over), Status report (Off). Rules live in AlertSchedule (pure). - The daily check runs at the owner's hour in their own time zone (from the browser), not the server's. - Fix: the email limit is one per calendar day in the owner's zone. The old rolling 24 hours dropped every other daily email. - Alerts read time from an injected Clock; simulation tests run the real scheduler over 10-60 simulated days. Tests: 366 unit, 103 browser, all passing. Co-Authored-By: Claude Opus 5.5 --- .../migrations/2026-11-21_alert_schedules.sql | 20 ++ docs/specs/ALERTS_SPEC.md | 66 +++-- .../browser/AlertSettingsTest.java | 71 +++++ .../browser/BrowserTestBase.java | 2 +- .../AviaryService/config/ClockConfig.java | 17 ++ .../controllers/AlertController.java | 37 ++- .../controllers/UserController.java | 13 +- .../AviaryService/entity/AlertPreference.java | 99 ++++++- .../services/alerts/AlertDigest.java | 84 ++++-- .../services/alerts/AlertDigestService.java | 191 ++++++------ .../services/alerts/AlertEmailRenderer.java | 205 +++++++++++++ .../alerts/AlertRecipientService.java | 12 +- .../services/alerts/AlertSchedule.java | 88 ++++++ .../services/alerts/AlertScheduler.java | 12 +- .../services/alerts/AlertService.java | 96 +++++- .../services/alerts/EmailFooter.java | 15 + .../services/alerts/LeadTimes.java | 16 + .../services/alerts/NotificationService.java | 49 ++-- .../services/dashboard/PdfExportService.java | 33 ++- .../services/messaging/EmailSender.java | 10 +- .../services/messaging/SesEmailService.java | 17 +- .../resources/static/css/dashboardstyle.css | 9 + src/main/resources/static/js/dashboard.js | 72 ++++- src/main/resources/templates/dashboard.html | 41 ++- .../templates/email/alert-digest.html | 79 +++++ src/main/resources/templates/pdf-export.html | 11 +- .../controllers/AlertPreferencesApiTest.java | 119 ++++++++ .../controllers/UserControllerTest.java | 4 + .../services/alerts/AlertDigestFleetTest.java | 37 ++- .../alerts/AlertEmailRendererTest.java | 204 +++++++++++++ .../services/alerts/AlertScheduleTest.java | 179 ++++++++++++ .../alerts/AlertServiceIntegrationTest.java | 6 +- .../services/alerts/AlertSimulationTest.java | 275 ++++++++++++++++++ .../services/alerts/AlertTimeZoneTest.java | 89 ++++++ .../alerts/NotificationServiceEmailTest.java | 97 ++++++ .../dashboard/PdfExportColorsTest.java | 90 ++++++ .../AviaryService/support/MutableClock.java | 53 ++++ 37 files changed, 2268 insertions(+), 250 deletions(-) create mode 100644 docs/migrations/2026-11-21_alert_schedules.sql create mode 100644 src/browserTest/java/com/example/AviaryService/browser/AlertSettingsTest.java create mode 100644 src/main/java/com/example/AviaryService/config/ClockConfig.java create mode 100644 src/main/java/com/example/AviaryService/services/alerts/AlertEmailRenderer.java create mode 100644 src/main/java/com/example/AviaryService/services/alerts/AlertSchedule.java create mode 100644 src/main/java/com/example/AviaryService/services/alerts/EmailFooter.java create mode 100644 src/main/java/com/example/AviaryService/services/alerts/LeadTimes.java create mode 100644 src/main/resources/templates/email/alert-digest.html create mode 100644 src/test/java/com/example/AviaryService/controllers/AlertPreferencesApiTest.java create mode 100644 src/test/java/com/example/AviaryService/services/alerts/AlertEmailRendererTest.java create mode 100644 src/test/java/com/example/AviaryService/services/alerts/AlertScheduleTest.java create mode 100644 src/test/java/com/example/AviaryService/services/alerts/AlertSimulationTest.java create mode 100644 src/test/java/com/example/AviaryService/services/alerts/AlertTimeZoneTest.java create mode 100644 src/test/java/com/example/AviaryService/services/alerts/NotificationServiceEmailTest.java create mode 100644 src/test/java/com/example/AviaryService/services/dashboard/PdfExportColorsTest.java create mode 100644 src/test/java/com/example/AviaryService/support/MutableClock.java diff --git a/docs/migrations/2026-11-21_alert_schedules.sql b/docs/migrations/2026-11-21_alert_schedules.sql new file mode 100644 index 0000000..bb13758 --- /dev/null +++ b/docs/migrations/2026-11-21_alert_schedules.sql @@ -0,0 +1,20 @@ +-- Alert email schedules (specs/014-alert-reminder-frequency). +-- +-- Additive only. Hibernate ddl-auto=update adds these columns on boot; the +-- integer columns carry a DEFAULT so existing rows are filled. This file is +-- the explicit record for any DB where ddl-auto is off. PostgreSQL syntax. +-- +-- overdue_renudge_days keeps its values and meaning (every N days) and is now +-- the "Overdue" frequency. It can also hold 0 = Off and -1 = Once. New rows +-- get 3 from the entity; existing rows keep what owners set (FR-006). + +ALTER TABLE alert_preferences ADD COLUMN IF NOT EXISTS due_soon_every_days INTEGER NOT NULL DEFAULT 7; -- 0 Off, -1 Once, 1-90 +ALTER TABLE alert_preferences ADD COLUMN IF NOT EXISTS status_every_days INTEGER NOT NULL DEFAULT 0; -- 0 Off, 1-90 +ALTER TABLE alert_preferences ADD COLUMN IF NOT EXISTS time_zone VARCHAR(255); -- IANA id, null = America/New_York +ALTER TABLE alert_preferences ADD COLUMN IF NOT EXISTS last_due_soon_sent_at TIMESTAMP(6) WITH TIME ZONE; +ALTER TABLE alert_preferences ADD COLUMN IF NOT EXISTS last_overdue_sent_at TIMESTAMP(6) WITH TIME ZONE; +ALTER TABLE alert_preferences ADD COLUMN IF NOT EXISTS last_status_sent_at TIMESTAMP(6) WITH TIME ZONE; + +-- last_checked_on now holds the owner's local date (in time_zone) instead of +-- the server's. No backfill needed: at worst one owner is checked a second +-- time on deploy day, and the schedule rules send nothing new in that case. diff --git a/docs/specs/ALERTS_SPEC.md b/docs/specs/ALERTS_SPEC.md index 93eae2e..db83d99 100644 --- a/docs/specs/ALERTS_SPEC.md +++ b/docs/specs/ALERTS_SPEC.md @@ -16,8 +16,9 @@ for this tail". This is a different concern with its own entities. A user is evaluated only when alerts are on, the current hour matches their `checkHour`, and they haven't been checked today (`lastCheckedOn`). So: at most one check per user per day. -- `checkHour` is in the **server's time zone** (`ZoneId.systemDefault()`). On - Heroku that is UTC. +- `checkHour` is in the **owner's time zone** (`AlertPreference.timeZone`, sent by + the dashboard from the browser; `America/New_York` until known). `lastCheckedOn` + is the owner's local date (spec 014). - On a check, every non-title item on the Status Sheet gets a **level**: `OK` → `DUE_SOON` → `OVERDUE`. - `OVERDUE` — `daysLeft < 0` or `hoursLeft < 0` @@ -26,10 +27,21 @@ for this tail". This is a different concern with its own entities. - An item has two limits (calendar and flight hours); the worse one wins. - Each item stores the level it **last alerted at** (`StatusSheetItem.alertLevel`) and when (`alertLastFiredAt`). -- A digest is sent only if **either**: - 1. some item moved to a worse level than it last alerted at, **or** - 2. some item is still `OVERDUE` and `alertLastFiredAt` is ≥ `overdueRenudgeDays` - ago (re-nudge; default 7, user-configurable). +- **Three kinds of alert email, each with its own frequency** (spec 014), set in + Settings → Alert schedule. Each is Off, Once (not the status report), or every + N days (1–90). Defaults: **Due soon every 7 days, Overdue every 3 days, Status + report Off.** `AlertSchedule.decide` (pure, unit-tested) says to send when: + 1. an item became `DUE_SOON` since the last email (Due soon not Off), or + 2. an item became `OVERDUE` since the last email (Overdue not Off), or + 3. something is due soon and N days passed since the last email that listed + due-soon items (`lastDueSoonSentAt`), or + 4. something is overdue and N days passed since `lastOverdueSentAt`, or + 5. the status report is on and N days passed since `lastStatusSentAt`. + Several reasons on one day → one email. "N days" compares the owner's local + dates. A status report with nothing due has the subject + `N12345 — weekly status: all on track`. +- The old "re-nudge overdue every N days" (`overdueRenudgeDays`) is now the + Overdue frequency; existing values carry over. - When an item improves (maintenance done, due date pushed out), its `alertLevel` is quietly reset down. No "good news" email. - No per-edit sending. @@ -94,7 +106,9 @@ message under the form and as a toast. **Digests** (daily check, baseline, and "Send alert now" share one budget, per recipient, tracked in `AlertSendLog`): -- **Email:** max 1 per recipient per 24h +- **Email:** max 1 per recipient per **calendar day in the owner's time zone** + (was a rolling 24 h, which dropped the next day's email whenever the hourly + check ran a few seconds earlier; spec 014 R4) - **SMS:** max 1 per recipient per 72h On cooldown the send is skipped for that recipient (logged, not an error). The @@ -108,14 +122,22 @@ nothing is saved. ## Digest content - **Subject:** `N12345 — 1 overdue, 2 due soon` (or `N12345 — maintenance status`). -- **Body (plain text):** "Maintenance status for [tail] ([make/model])" + timestamp - → baseline note or "What changed" → full status, worst first. Each line puts - the overdue part first, e.g. `OVERDUE Annual Inspection — 480.0 hrs overdue · - 106 days left` → aircraft hours (Hobbs Time / Time in Service). -- **Attachment:** dashboard PDF (`PdfExportService.generateDashboardPdf`), built - once per digest. +- **Body (spec 013):** sent as **text + HTML** (same content; `AlertEmailRenderer`, + template `templates/email/alert-digest.html`, inline styles only). Heading + `[tail] ([make/model]) — [counts]` + "as of" time → baseline line (first email + only) → **only items that are overdue or due soon** (owner's lead times), grouped + `OVERDUE` then `DUE SOON`, most urgent first (days/leadDays vs hours/leadHours, + the smaller wins), `[new]` / "New" on items that got worse since the last email → + "The other N items are on track." (or "All N items are on track.") → hours + (Hobbs Time / Time in Service). Items that are fine are not listed; they're in the PDF. + Fleet: one section per aircraft with something due, then "N2BB and N3CC: all items + on track." +- **Attachment:** Status Sheet PDF for the fleet (`PdfExportService.generateFleetPdf`), + built once per digest. Time Left is labeled `OVERDUE` (red `#B3203F`) or + `DUE SOON` (amber `#8A5A00`) using the owner's lead times, the same rule as the + dashboard pills. The PDF downloaded or shared from the dashboard uses the same rule. - **Footer:** "You're receiving this because [operator name] added you to maintenance - alerts for [tail]. The full dashboard is attached as a PDF." + unsubscribe link + alerts for [tail]." + unsubscribe link (per recipient) (`/alerts/unsubscribe?token=…`) + postal address if configured (CAN-SPAM). **No dashboard link:** recipients have no login. - **SMS:** one short line. No attachment. @@ -123,14 +145,19 @@ nothing is saved. ## Thresholds Per-user defaults in `AlertPreference`: `leadTimeDays` (30), `leadTimeHours` -(10). Per-item overrides are a later addition. +(10). They decide what "due soon" means; how often each email goes out is the +three frequencies above. Per-item overrides are a later addition. ## Entities - **`AlertPreference`** — `@OneToOne` User. `alertsEnabled` (false), `checkHour` (7, clamped 0–23), `leadTimeDays` (30), `leadTimeHours` (10), - `overdueRenudgeDays` (7, min 1), `lastCheckedOn` (LocalDate, null), - `baselineSentAt` (Instant, null). + `overdueRenudgeDays` = Overdue frequency (3 for new rows; 0 Off, -1 Once, + 1–90), `dueSoonEveryDays` (7), `statusEveryDays` (0 = Off), `timeZone` (IANA, + null → America/New_York), `lastDueSoonSentAt` / `lastOverdueSentAt` / + `lastStatusSentAt` (Instant, null), `lastCheckedOn` (owner-local LocalDate, + null), `baselineSentAt` (Instant, null). Migration note: + `docs/migrations/2026-11-21_alert_schedules.sql`. - **`AlertRecipient`** — as table above. - **`StatusSheetItem`** has `alertLevel` (String, nullable) and `alertLastFiredAt` (Instant, nullable). @@ -151,8 +178,9 @@ Login required (owner), under `/alerts` (`AlertController`, JSON): | method | path | body / params | purpose | |---|---|---|---| -| GET | `/alerts/preferences` | — | current prefs + readiness | -| PUT | `/alerts/preferences` | JSON `enabled,checkHour,leadTimeDays,leadTimeHours,overdueRenudgeDays` | update; false→true sends baseline | +| GET | `/alerts/preferences` | — | current prefs (+ `dueSoonEvery`, `overdueEvery`, `statusEvery` as `"off"`/`"once"`/N, `timeZone`) + readiness | +| PUT | `/alerts/preferences` | JSON `enabled,checkHour,leadTimeDays,leadTimeHours,dueSoonEvery,overdueEvery,statusEvery` (old `overdueRenudgeDays` still accepted) | update; false→true sends baseline; bad frequency → 400 | +| POST | `/alerts/time-zone` | JSON `timeZone` (IANA id) | sets the owner's zone; invalid → 400 | | GET | `/alerts/recipients` | — | list with statuses | | POST | `/alerts/recipients` | form `channel,destination,label` | add → PENDING, sends confirmation | | DELETE | `/alerts/recipients/{id}` | — | remove | diff --git a/src/browserTest/java/com/example/AviaryService/browser/AlertSettingsTest.java b/src/browserTest/java/com/example/AviaryService/browser/AlertSettingsTest.java new file mode 100644 index 0000000..cbfb981 --- /dev/null +++ b/src/browserTest/java/com/example/AviaryService/browser/AlertSettingsTest.java @@ -0,0 +1,71 @@ +package com.example.AviaryService.browser; + +import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import com.example.AviaryService.repositories.AlertPreferenceRepository; +import com.microsoft.playwright.Browser; + +// Spec 014 matrix E: the alert schedule settings -- three emails with clear +// defaults and one-line explanations, saving, and the owner's time zone. +class AlertSettingsTest extends BrowserTestBase { + + @Autowired AlertPreferenceRepository preferenceRepository; + + private String openSettings() { + String username = seedUser("password"); + loginAs(username, "password"); + page.navigate(baseUrl() + "/dashboard"); + page.locator("#settings").click(); + assertThat(page.locator("#alerts-due-soon-every")).isVisible(); + return username; + } + + @Test + void e1_defaultsAndExplanations() { + openSettings(); + assertThat(page.locator("#alerts-due-soon-every")).hasValue("7"); + assertThat(page.locator("#alerts-overdue-every")).hasValue("3"); + assertThat(page.locator("#alerts-status-every")).hasValue("off"); + assertThat(page.locator("#alerts-due-soon-hint")).hasText("Email me every 7 days while anything is due soon."); + assertThat(page.locator("#alerts-overdue-hint")).hasText("Email me every 3 days while anything is overdue."); + assertThat(page.locator("#alerts-status-hint")).hasText("No scheduled status email."); + // Status report has no "Once". + assertEquals(0, page.locator("#alerts-status-every option[value='once']").count()); + } + + @Test + void e2_changesAreSaved() { + openSettings(); + page.locator("#alerts-due-soon-every").selectOption("off"); + page.locator("#alerts-overdue-every").selectOption("2"); + page.locator("#alerts-status-every").selectOption("custom"); + page.locator("#alerts-status-every-days").fill("10"); + assertThat(page.locator("#alerts-status-hint")).hasText("Email the full status every 10 days, even when nothing is due."); + page.waitForResponse(r -> r.url().endsWith("/alerts/preferences") && "PUT".equals(r.request().method()), + () -> page.locator("#alerts-save-schedule").click()); + + page.reload(); + page.locator("#settings").click(); + assertThat(page.locator("#alerts-due-soon-every")).hasValue("off"); + assertThat(page.locator("#alerts-due-soon-hint")).hasText("Never email just because something is due soon."); + assertThat(page.locator("#alerts-overdue-every")).hasValue("2"); + assertThat(page.locator("#alerts-status-every")).hasValue("custom"); + assertThat(page.locator("#alerts-status-every-days")).hasValue("10"); + } + + @Test + void e3_timeZoneComesFromTheBrowser() { + context.close(); + context = browser.newContext(new Browser.NewContextOptions().setTimezoneId("America/Chicago")); + page = context.newPage(); + String username = openSettings(); + assertThat(page.locator("#alerts-time-zone")).hasText("America/Chicago"); + page.waitForTimeout(500); // the POST that saves it + assertEquals("America/Chicago", preferenceRepository.findByUser(userRepository.findByUsername(username)) + .orElseThrow().getTimeZone()); + } +} diff --git a/src/browserTest/java/com/example/AviaryService/browser/BrowserTestBase.java b/src/browserTest/java/com/example/AviaryService/browser/BrowserTestBase.java index 6323811..b7fc7f4 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/BrowserTestBase.java +++ b/src/browserTest/java/com/example/AviaryService/browser/BrowserTestBase.java @@ -30,7 +30,7 @@ public abstract class BrowserTestBase { // expensive step in a Playwright run, so we keep one Browser per JVM // and isolate state with fresh BrowserContexts per test. private static Playwright playwright; - private static Browser browser; + protected static Browser browser; protected BrowserContext context; protected Page page; diff --git a/src/main/java/com/example/AviaryService/config/ClockConfig.java b/src/main/java/com/example/AviaryService/config/ClockConfig.java new file mode 100644 index 0000000..1406122 --- /dev/null +++ b/src/main/java/com/example/AviaryService/config/ClockConfig.java @@ -0,0 +1,17 @@ +package com.example.AviaryService.config; + +import java.time.Clock; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +// The app's "now". Alerts read time from this so tests can move it forward +// day by day (spec 014). UTC; each owner's own zone is applied on top. +@Configuration +public class ClockConfig { + + @Bean + public Clock clock() { + return Clock.systemUTC(); + } +} diff --git a/src/main/java/com/example/AviaryService/controllers/AlertController.java b/src/main/java/com/example/AviaryService/controllers/AlertController.java index 96ebc2b..8bc3afa 100644 --- a/src/main/java/com/example/AviaryService/controllers/AlertController.java +++ b/src/main/java/com/example/AviaryService/controllers/AlertController.java @@ -27,6 +27,7 @@ import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.repositories.UserRepository; import com.example.AviaryService.services.alerts.AlertRecipientService; +import com.example.AviaryService.services.alerts.AlertSchedule; import com.example.AviaryService.services.alerts.AlertService; // The owner's control panel for maintenance alerts. The owner can change @@ -70,15 +71,36 @@ public ResponseEntity> updatePreferences( if (user == null) return unauthorized(); AlertPreference current = alertService.getOrCreatePrefs(user); try { + // "overdueRenudgeDays": pre-014 key from an old open tab. + Object overdue = body.containsKey("overdueEvery") ? body.get("overdueEvery") : body.get("overdueRenudgeDays"); AlertPreference prefs = alertService.updatePrefs(user, asBool(body.get("enabled"), current.isAlertsEnabled()), asInt(body.get("checkHour"), current.getCheckHour()), asInt(body.get("leadTimeDays"), current.getLeadTimeDays()), asInt(body.get("leadTimeHours"), current.getLeadTimeHours()), - asInt(body.get("overdueRenudgeDays"), current.getOverdueRenudgeDays())); + frequency(overdue, current.getOverdueEveryDays(), true), + frequency(body.get("dueSoonEvery"), current.getDueSoonEveryDays(), true), + frequency(body.get("statusEvery"), current.getStatusEveryDays(), false)); return ResponseEntity.ok(prefsBody(user, prefs)); } catch (IllegalArgumentException e) { - return ResponseEntity.badRequest().body(Map.of("error", e.getMessage())); + return ResponseEntity.badRequest().body(Map.of("status", "error", "error", e.getMessage(), "message", e.getMessage())); + } + } + + // The owner's time zone, sent by the dashboard from the browser (spec 014). + @PostMapping("/time-zone") + public ResponseEntity> updateTimeZone(@RequestBody Map body, Authentication auth) { + User user = currentUser(auth); + if (user == null) return unauthorized(); + Object zone = body.get("timeZone"); + if (!(zone instanceof String z) || z.isBlank()) { + return ResponseEntity.badRequest().body(Map.of("status", "error", "message", "Missing time zone.")); + } + try { + AlertPreference prefs = alertService.updateTimeZone(user, z); + return ResponseEntity.ok(Map.of("timeZone", prefs.zone().getId())); + } catch (java.time.DateTimeException e) { + return ResponseEntity.badRequest().body(Map.of("status", "error", "message", "Unknown time zone.")); } } @@ -163,7 +185,11 @@ private Map prefsBody(User user, AlertPreference prefs) { m.put("checkHour", prefs.getCheckHour()); m.put("leadTimeDays", prefs.getLeadTimeDays()); m.put("leadTimeHours", prefs.getLeadTimeHours()); - m.put("overdueRenudgeDays", prefs.getOverdueRenudgeDays()); + m.put("overdueRenudgeDays", prefs.getOverdueRenudgeDays()); // pre-014 key, same value as overdueEvery + m.put("dueSoonEvery", AlertSchedule.Frequency.toJson(prefs.getDueSoonEveryDays())); + m.put("overdueEvery", AlertSchedule.Frequency.toJson(prefs.getOverdueEveryDays())); + m.put("statusEvery", AlertSchedule.Frequency.toJson(prefs.getStatusEveryDays())); + m.put("timeZone", prefs.zone().getId()); // Readiness hints for the "turn on" dialog (advisory only). List missing = new ArrayList<>(); @@ -198,6 +224,11 @@ private static boolean asBool(Object v, boolean dflt) { return dflt; } + // Missing -> keep current; otherwise "off", "once" or 1-90 days. + private static int frequency(Object v, int current, boolean allowOnce) { + return v == null ? current : AlertSchedule.Frequency.parse(v, allowOnce); + } + private static int asInt(Object v, int dflt) { if (v instanceof Number n) return n.intValue(); if (v instanceof String s && !s.isBlank()) { diff --git a/src/main/java/com/example/AviaryService/controllers/UserController.java b/src/main/java/com/example/AviaryService/controllers/UserController.java index 75bff99..47999c0 100644 --- a/src/main/java/com/example/AviaryService/controllers/UserController.java +++ b/src/main/java/com/example/AviaryService/controllers/UserController.java @@ -246,7 +246,7 @@ public ResponseEntity downloadPdf(@RequestParam(required = false) String } catch (java.time.format.DateTimeParseException ignored) { // bad value -> server date } - byte[] pdf = pdfExportService.generateDashboardPdf(aircraft, asOf); + byte[] pdf = pdfExportService.generateDashboardPdf(aircraft, asOf, leadTimesFor(user)); org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders(); headers.setContentType(org.springframework.http.MediaType.APPLICATION_PDF); @@ -278,7 +278,7 @@ public ResponseEntity> emailPdf(@RequestParam String recipie } emailLimiter.acquire(user); - byte[] pdf = pdfExportService.generateDashboardPdf(aircraft); + byte[] pdf = pdfExportService.generateDashboardPdf(aircraft, java.time.LocalDate.now(), leadTimesFor(user)); String filename = "Aviary_Dashboard_" + java.time.LocalDate.now() + ".pdf"; try { emailSender.sendPdf( @@ -934,4 +934,11 @@ public ResponseEntity> deleteFlightLog(@PathVariable Long id // after this fix ships. -} \ No newline at end of file + + // The owner's alert lead times: which items are DUE SOON in the PDF, the + // same values the dashboard's amber pills use (spec 013). + private com.example.AviaryService.services.alerts.LeadTimes leadTimesFor(User user) { + return com.example.AviaryService.services.alerts.LeadTimes.of( + alertPreferenceRepository.findByUser(user).orElse(null)); + } +} diff --git a/src/main/java/com/example/AviaryService/entity/AlertPreference.java b/src/main/java/com/example/AviaryService/entity/AlertPreference.java index a0a13a0..900120d 100644 --- a/src/main/java/com/example/AviaryService/entity/AlertPreference.java +++ b/src/main/java/com/example/AviaryService/entity/AlertPreference.java @@ -43,11 +43,36 @@ public class AlertPreference { @Column(nullable = false) private int leadTimeHours = 10; - // While an item stays overdue, re-nudge every this-many days. + // Overdue frequency (spec 014; was "re-nudge overdue every N days", same + // column): 0 = Off, -1 = Once, 1-90 = every N days. New owners: 3. @Column(nullable = false) - private int overdueRenudgeDays = 7; + private int overdueRenudgeDays = 3; - // The date the sweep last evaluated this user -- guards against a double + // Due soon frequency: 0 = Off, -1 = Once, 1-90 = every N days. + @Column(nullable = false, columnDefinition = "integer default 7") + private int dueSoonEveryDays = 7; + + // Status report frequency: 0 = Off, 1-90 = every N days (no Once). + @Column(nullable = false, columnDefinition = "integer default 0") + private int statusEveryDays = 0; + + // Owner's IANA time zone, e.g. America/New_York. Null until the browser + // reports one; zone() falls back to America/New_York. + @Column + private String timeZone; + + // When the last email listing due-soon / overdue items, and the last + // status report, went out. Each frequency counts from its own. + @Column + private Instant lastDueSoonSentAt; + + @Column + private Instant lastOverdueSentAt; + + @Column + private Instant lastStatusSentAt; + + // The owner's local date (in zone()) the sweep last evaluated this user -- guards against a double // run in the same day if the process restarts on the check hour. @Column private LocalDate lastCheckedOn; @@ -135,4 +160,72 @@ public Instant getBaselineSentAt() { public void setBaselineSentAt(Instant baselineSentAt) { this.baselineSentAt = baselineSentAt; } + + public int getOverdueEveryDays() { + return overdueRenudgeDays; + } + + public void setOverdueEveryDays(int v) { + this.overdueRenudgeDays = v; + } + + public int getDueSoonEveryDays() { + return dueSoonEveryDays; + } + + public void setDueSoonEveryDays(int dueSoonEveryDays) { + this.dueSoonEveryDays = dueSoonEveryDays; + } + + public int getStatusEveryDays() { + return statusEveryDays; + } + + public void setStatusEveryDays(int statusEveryDays) { + this.statusEveryDays = statusEveryDays; + } + + public String getTimeZone() { + return timeZone; + } + + public void setTimeZone(String timeZone) { + this.timeZone = timeZone; + } + + public static final java.time.ZoneId DEFAULT_ZONE = java.time.ZoneId.of("America/New_York"); + + // The owner's zone, or America/New_York when unknown or invalid. + public java.time.ZoneId zone() { + if (timeZone == null || timeZone.isBlank()) return DEFAULT_ZONE; + try { + return java.time.ZoneId.of(timeZone); + } catch (java.time.DateTimeException e) { + return DEFAULT_ZONE; + } + } + + public Instant getLastDueSoonSentAt() { + return lastDueSoonSentAt; + } + + public void setLastDueSoonSentAt(Instant lastDueSoonSentAt) { + this.lastDueSoonSentAt = lastDueSoonSentAt; + } + + public Instant getLastOverdueSentAt() { + return lastOverdueSentAt; + } + + public void setLastOverdueSentAt(Instant lastOverdueSentAt) { + this.lastOverdueSentAt = lastOverdueSentAt; + } + + public Instant getLastStatusSentAt() { + return lastStatusSentAt; + } + + public void setLastStatusSentAt(Instant lastStatusSentAt) { + this.lastStatusSentAt = lastStatusSentAt; + } } diff --git a/src/main/java/com/example/AviaryService/services/alerts/AlertDigest.java b/src/main/java/com/example/AviaryService/services/alerts/AlertDigest.java index a1e8462..72c2212 100644 --- a/src/main/java/com/example/AviaryService/services/alerts/AlertDigest.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertDigest.java @@ -1,41 +1,85 @@ package com.example.AviaryService.services.alerts; -// One alert message's content: whether there's anything to send, plus the -// subject and body. Only holds data; AlertDigestService builds it. -// See docs/specs/ALERTS_SPEC.md. +import java.time.Instant; +import java.util.List; + +// One alert message's content: whether there's anything to send, the subject, +// and what's due per aircraft. Only holds data: AlertDigestService builds it, +// AlertEmailRenderer turns it into the text and HTML emails. +// See docs/specs/ALERTS_SPEC.md and specs/013-alert-email-design/data-model.md. public class AlertDigest { + // One aircraft's part of the email. `due` is overdue items first, then + // due soon, each group sorted by sortKey (most urgent first). + public record AircraftSection(String tail, String makeModel, String hobbsTime, String timeInService, + List due, int onTrackCount, int itemCount) { + public boolean hasDue() { + return !due.isEmpty(); + } + } + + // An item that needs attention. timeText is e.g. "10 days left" or + // "480.0 hrs overdue · 106 days left". isNew: worse than at the last email. + public record DueItem(String name, AlertLevel level, String timeText, boolean isNew, double sortKey) { + public boolean overdue() { + return level == AlertLevel.OVERDUE; + } + } + private final boolean shouldSend; - private final String subject; - private final String body; + private String subject; private final int overdueCount; private final int dueSoonCount; + private final Instant asOf; + private final boolean baseline; + private final List sections; + private final LeadTimes leadTimes; + private String body = ""; + // Spec 014: what the schedule needs. newX = an item got worse into that + // state since the last email. + private boolean newDueSoon; + private boolean newOverdue; + private java.time.ZoneId zone = com.example.AviaryService.entity.AlertPreference.DEFAULT_ZONE; - public AlertDigest(boolean shouldSend, String subject, String body, int overdueCount, int dueSoonCount) { + public AlertDigest(boolean shouldSend, String subject, int overdueCount, int dueSoonCount, + Instant asOf, boolean baseline, List sections, LeadTimes leadTimes) { this.shouldSend = shouldSend; this.subject = subject; - this.body = body; this.overdueCount = overdueCount; this.dueSoonCount = dueSoonCount; + this.asOf = asOf; + this.baseline = baseline; + this.sections = List.copyOf(sections); + this.leadTimes = leadTimes; } - public boolean shouldSend() { - return shouldSend; - } + public boolean shouldSend() { return shouldSend; } + public String subject() { return subject; } + public int overdueCount() { return overdueCount; } + public int dueSoonCount() { return dueSoonCount; } + public Instant asOf() { return asOf; } + public boolean baseline() { return baseline; } + public List sections() { return sections; } + public LeadTimes leadTimes() { return leadTimes; } - public String subject() { - return subject; - } + // The plain-text email without the per-recipient footer. + public String body() { return body; } - public String body() { - return body; - } + void setBody(String body) { this.body = body; } - public int overdueCount() { - return overdueCount; + public boolean newDueSoon() { return newDueSoon; } + public boolean newOverdue() { return newOverdue; } + public java.time.ZoneId zone() { return zone; } + + void setFacts(boolean newDueSoon, boolean newOverdue, java.time.ZoneId zone) { + this.newDueSoon = newDueSoon; + this.newOverdue = newOverdue; + if (zone != null) this.zone = zone; } - public int dueSoonCount() { - return dueSoonCount; + void setSubject(String subject) { this.subject = subject; } + + public boolean isFleet() { + return sections.size() > 1; } } diff --git a/src/main/java/com/example/AviaryService/services/alerts/AlertDigestService.java b/src/main/java/com/example/AviaryService/services/alerts/AlertDigestService.java index 7f5dd8d..cbee04c 100644 --- a/src/main/java/com/example/AviaryService/services/alerts/AlertDigestService.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertDigestService.java @@ -3,8 +3,6 @@ import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -30,20 +28,21 @@ @Service public class AlertDigestService { - private static final DateTimeFormatter STAMP = - DateTimeFormatter.ofPattern("MMM d, yyyy h:mm a 'UTC'").withZone(ZoneOffset.UTC); - private final StatusSheetItemRepository statusSheetItemRepository; private final AircraftRepository aircraftRepository; + private final AlertEmailRenderer renderer; + private final java.time.Clock clock; public AlertDigestService(StatusSheetItemRepository statusSheetItemRepository, - AircraftRepository aircraftRepository) { + AircraftRepository aircraftRepository, AlertEmailRenderer renderer, java.time.Clock clock) { this.statusSheetItemRepository = statusSheetItemRepository; this.aircraftRepository = aircraftRepository; + this.renderer = renderer; + this.clock = clock; } public AlertDigest buildDigest(User user, AlertPreference prefs, boolean baseline) { - LocalDate today = LocalDate.now(ZoneOffset.UTC); + LocalDate today = LocalDate.now(clock.withZone(ZoneOffset.UTC)); List fleet = aircraftRepository.findByUserOrderByIdAsc(user); // Every row across the fleet, grouped by aircraft. Each hours-cycle @@ -61,7 +60,8 @@ public AlertDigest buildDigest(User user, AlertPreference prefs, boolean baselin t.getDueDateDate(), t.getDueDateHours(), tis, today, prefs.getLeadTimeDays(), prefs.getLeadTimeHours()); AlertLevel previous = AlertLevel.parse(t.getAlertLevel()); - evaluated.add(new Row(t, current, previous, timeLeftText(t, tis, today))); + evaluated.add(new Row(t, current, previous, timeLeftText(t, tis, today), + sortKey(t, tis, today, prefs.getLeadTimeDays(), prefs.getLeadTimeHours()))); } int overdue = (int) evaluated.stream().filter(r -> r.current == AlertLevel.OVERDUE).count(); @@ -69,24 +69,26 @@ public AlertDigest buildDigest(User user, AlertPreference prefs, boolean baselin List changed = evaluated.stream().filter(r -> r.current.worseThan(r.previous)).toList(); - boolean renudgeDue = evaluated.stream().anyMatch(r -> - r.current == AlertLevel.OVERDUE - && r.row.getAlertLastFiredAt() != null - && ChronoUnit.DAYS.between(r.row.getAlertLastFiredAt(), Instant.now()) >= prefs.getOverdueRenudgeDays()); - - boolean shouldSend = baseline || !changed.isEmpty() || renudgeDue; + // Whether to send is now AlertSchedule's call (spec 014); this only + // reports what changed. shouldSend stays for "something got worse". + boolean shouldSend = baseline || !changed.isEmpty(); + boolean newDueSoon = changed.stream().anyMatch(r -> r.current == AlertLevel.DUE_SOON); + boolean newOverdue = changed.stream().anyMatch(r -> r.current == AlertLevel.OVERDUE); String subject = buildSubject(fleet, overdue, dueSoon); - String body = buildBody(fleet, evaluated, changed, baseline, overdue, dueSoon); - - return new AlertDigest(shouldSend, subject, body, overdue, dueSoon); + LeadTimes lead = LeadTimes.of(prefs); + AlertDigest digest = new AlertDigest(shouldSend, subject, overdue, dueSoon, Instant.now(clock), baseline, + buildSections(fleet, evaluated, lead), lead); + digest.setFacts(newDueSoon, newOverdue, prefs.zone()); + digest.setBody(renderer.text(digest, null)); + return digest; } // Persist current levels so the next run only fires on a change. Called after // a successful send and for the baseline. public void markFired(User user, AlertPreference prefs) { - LocalDate today = LocalDate.now(ZoneOffset.UTC); - Instant now = Instant.now(); + LocalDate today = LocalDate.now(clock.withZone(ZoneOffset.UTC)); + Instant now = Instant.now(clock); List rows = statusSheetItemRepository.findByUserOrderByAircraftIdAscStatusSheetOrderAsc(user); for (StatusSheetItem t : rows) { @@ -108,99 +110,81 @@ private static Double timeInServiceOf(StatusSheetItem t) { return t.getAircraft() == null ? null : t.getAircraft().getTimeInServiceHours(); } - // -- rendering -- + // -- the email's content (AlertEmailRenderer writes it) -- - private String buildSubject(List fleet, int overdue, int dueSoon) { - String tail = fleet.size() > 1 - ? "Your fleet" - : (fleet.isEmpty() ? "Your aircraft" : AlertText.tailOf(fleet.get(0), "Your aircraft")); - if (overdue == 0 && dueSoon == 0) { - return tail + " — maintenance status"; - } - List parts = new ArrayList<>(); - if (overdue > 0) parts.add(overdue + " overdue"); - if (dueSoon > 0) parts.add(dueSoon + " due soon"); - return tail + " — " + String.join(", ", parts); - } - - private String buildBody(List fleet, List evaluated, List changed, - boolean baseline, int overdue, int dueSoon) { - StringBuilder sb = new StringBuilder(); - boolean multi = fleet.size() > 1; - - sb.append("Maintenance status for ").append(AlertText.tail(fleet)); - if (!multi && !fleet.isEmpty()) { - String makeModel = orDash(fleet.get(0).getMakeModel()); - if (!"—".equals(makeModel)) { - sb.append(" (").append(makeModel).append(')'); - } - } - sb.append("\nas of ").append(STAMP.format(Instant.now())).append("\n"); - - if (baseline) { - sb.append("\nAlerts are now ON. This is your starting picture — from here you'll only\n"); - sb.append("get an email when something changes or an overdue item needs another nudge.\n"); - } else if (!changed.isEmpty()) { - sb.append("\nWhat changed:\n"); - for (Row r : changed) { - sb.append(" • ").append(label(r.current)).append(" "); - if (multi) sb.append(AlertText.tailOf(r.row.getAircraft(), "Unnamed aircraft")).append(": "); - sb.append(r.row.getItem()).append(" — ").append(r.timeLeft).append('\n'); - } - } - - sb.append("\nFull status (").append(overdue).append(" overdue, ") - .append(dueSoon).append(" due soon):\n"); - if (evaluated.isEmpty()) { - sb.append(" (no maintenance items)\n"); - } - - if (!multi) { - appendRows(sb, evaluated); - if (!fleet.isEmpty()) appendHours(sb, "Aircraft hours", fleet.get(0)); - return sb.toString(); - } - - // One section per aircraft that has items, in fleet order. + // One section per aircraft, in fleet order: what's overdue or due soon + // (overdue first, then due soon, most urgent first; ties keep Status + // Sheet order) and how many items are on track. + private static List buildSections(List fleet, List evaluated, + LeadTimes lead) { + List sections = new ArrayList<>(); for (Aircraft a : fleet) { List mine = evaluated.stream() .filter(r -> r.row.getAircraft() != null && a.getId().equals(r.row.getAircraft().getId())) .toList(); - if (mine.isEmpty()) continue; - sb.append("\n").append(AlertText.tailOf(a, "Unnamed aircraft")); - String makeModel = orDash(a.getMakeModel()); - if (!"—".equals(makeModel)) sb.append(" · ").append(makeModel); - sb.append('\n'); - appendRows(sb, mine); - appendHours(sb, " Hours", a); + List due = mine.stream() + .filter(r -> r.current != AlertLevel.OK) + .sorted(Comparator.comparingInt((Row r) -> r.current == AlertLevel.OVERDUE ? 0 : 1) + .thenComparingDouble(r -> r.sortKey)) + .map(r -> new AlertDigest.DueItem(r.row.getItem(), r.current, + r.timeLeft == null ? "" : r.timeLeft.replace('\n', ' '), + r.current.worseThan(r.previous), r.sortKey)) + .toList(); + sections.add(new AlertDigest.AircraftSection( + AlertText.tailOf(a, fleet.size() > 1 ? "Unnamed aircraft" : "Your aircraft"), + a.getMakeModel() == null ? "" : a.getMakeModel().trim(), + hours(a.getHobbsTimeHours()), hours(a.getTimeInServiceHours()), + due, mine.size() - due.size(), mine.size())); } - return sb.toString(); + return sections; } - private static void appendRows(StringBuilder sb, List rows) { - List sorted = new ArrayList<>(rows); - sorted.sort(Comparator.comparingInt((Row r) -> -r.current.ordinal())); - for (Row r : sorted) { - sb.append(" ").append(String.format("%-9s", label(r.current))).append(' ') - .append(r.row.getItem()); - if (r.timeLeft != null && !r.timeLeft.isBlank() && !"N/A".equals(r.timeLeft)) { - sb.append(" — ").append(r.timeLeft.replace('\n', ' ')); - } - sb.append('\n'); - } + // How far through the owner's warning window an item is, so days and + // hours compare: days/leadDays and hours/leadHours, the smaller wins. + // Negative = overdue (more negative = more overdue). Research R3. + static double sortKey(StatusSheetItem t, Double tis, LocalDate today, int leadDays, int leadHours) { + double key = Double.MAX_VALUE; + Long days = DueDates.daysUntil(t.getDueDateDate(), today); + if (days != null) key = Math.min(key, days / (double) Math.max(leadDays, 1)); + Double hrs = DueDates.hoursUntil(t.getDueDateHours(), tis); + if (hrs != null) key = Math.min(key, hrs / Math.max(leadHours, 1)); + return key; } - private static void appendHours(StringBuilder sb, String label, Aircraft a) { - sb.append("\n").append(label).append(": Hobbs Time ").append(hours(a.getHobbsTimeHours())) - .append(" · Time in Service ").append(hours(a.getTimeInServiceHours())).append('\n'); + // Newest time an overdue item was alerted under the old per-item rule; seeds + // lastOverdueSentAt once after spec 014 deploys (research R6/R7). + public Instant latestOverdueAlertAt(User user) { + return statusSheetItemRepository.findByUserOrderByAircraftIdAscStatusSheetOrderAsc(user).stream() + .filter(t -> AlertLevel.parse(t.getAlertLevel()) == AlertLevel.OVERDUE && t.getAlertLastFiredAt() != null) + .map(StatusSheetItem::getAlertLastFiredAt) + .max(Instant::compareTo) + .orElse(null); } - private static String label(AlertLevel level) { - return switch (level) { - case OVERDUE -> "OVERDUE"; - case DUE_SOON -> "DUE SOON"; - case OK -> "ok"; - }; + // A scheduled status report with nothing due gets its own subject: + // "N12SAS — weekly status: all on track" (spec 014 FR-010). + public void markAsStatusReport(AlertDigest digest, List fleet, int everyDays) { + if (digest.overdueCount() > 0 || digest.dueSoonCount() > 0) return; + String tail = fleet.size() > 1 + ? "Your fleet" + : (fleet.isEmpty() ? "Your aircraft" : AlertText.tailOf(fleet.get(0), "Your aircraft")); + String when = everyDays == 7 ? "weekly status" : "status every " + everyDays + " days"; + digest.setSubject(tail + " — " + when + ": all on track"); + } + + // -- subject -- + + private String buildSubject(List fleet, int overdue, int dueSoon) { + String tail = fleet.size() > 1 + ? "Your fleet" + : (fleet.isEmpty() ? "Your aircraft" : AlertText.tailOf(fleet.get(0), "Your aircraft")); + if (overdue == 0 && dueSoon == 0) { + return tail + " — maintenance status"; + } + List parts = new ArrayList<>(); + if (overdue > 0) parts.add(overdue + " overdue"); + if (dueSoon > 0) parts.add(dueSoon + " due soon"); + return tail + " — " + String.join(", ", parts); } static String timeLeftText(StatusSheetItem t, Double tis, LocalDate today) { @@ -229,9 +213,6 @@ private static String hours(Double v) { return v == null ? "—" : Formatting.formatHours(v); } - private static String orDash(String s) { - return s == null || s.isBlank() ? "—" : s; - } // Plain holder (fields accessed directly below, not record-style). private static final class Row { @@ -239,12 +220,14 @@ private static final class Row { final AlertLevel current; final AlertLevel previous; final String timeLeft; + final double sortKey; - Row(StatusSheetItem row, AlertLevel current, AlertLevel previous, String timeLeft) { + Row(StatusSheetItem row, AlertLevel current, AlertLevel previous, String timeLeft, double sortKey) { this.row = row; this.current = current; this.previous = previous; this.timeLeft = timeLeft; + this.sortKey = sortKey; } } } diff --git a/src/main/java/com/example/AviaryService/services/alerts/AlertEmailRenderer.java b/src/main/java/com/example/AviaryService/services/alerts/AlertEmailRenderer.java new file mode 100644 index 0000000..02f5c21 --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertEmailRenderer.java @@ -0,0 +1,205 @@ +package com.example.AviaryService.services.alerts; + +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.stereotype.Component; +import org.thymeleaf.ITemplateEngine; +import org.thymeleaf.context.Context; + +import com.example.AviaryService.services.alerts.AlertDigest.AircraftSection; +import com.example.AviaryService.services.alerts.AlertDigest.DueItem; + +// Writes an alert digest as a plain-text email and an HTML email with the +// same content: only what's overdue or due soon, a line for everything on +// track, the hours, and the recipient's footer. +// Layout: specs/013-alert-email-design/contracts/alert-email.md. +@Component +public class AlertEmailRenderer { + + static final DateTimeFormatter STAMP = + DateTimeFormatter.ofPattern("MMM d, yyyy h:mm a 'UTC'").withZone(ZoneOffset.UTC); + + // Dashboard Time Left pill colors (light theme), dashboardstyle.css. + static final String SOON_BG = "#FFF1D6", SOON_FG = "#8A5A00"; + static final String OVER_BG = "#FDE4E9", OVER_FG = "#B3203F"; + + private final ITemplateEngine templateEngine; + + public AlertEmailRenderer(ITemplateEngine templateEngine) { + this.templateEngine = templateEngine; + } + + // ---- plain text ---- + + // footer may be null (AlertDigest.body(): no recipient yet). + public String text(AlertDigest d, EmailFooter footer) { + StringBuilder sb = new StringBuilder(); + sb.append(title(d)).append(" — ").append(counts(d)).append('\n'); + sb.append("as of ").append(STAMP.format(d.asOf())).append('\n'); + if (d.baseline()) { + sb.append('\n').append(baselineLine()).append('\n'); + } + + if (!d.isFleet()) { + AircraftSection s = d.sections().isEmpty() ? null : d.sections().get(0); + if (s != null) appendGroups(sb, s); + String summary = singleSummary(s); + sb.append('\n').append(summary.isEmpty() ? "" : summary + " ").append(attachmentLine(d)).append('\n'); + if (s != null) sb.append('\n').append(hoursLine(s)).append('\n'); + } else { + for (AircraftSection s : d.sections()) { + if (!s.hasDue()) continue; + sb.append('\n').append(sectionTitle(s)).append('\n'); + appendGroups(sb, s); + sb.append(hoursLine(s)).append('\n'); + } + String onTrack = fleetOnTrackLine(d); + if (onTrack != null) sb.append('\n').append(onTrack).append('\n'); + sb.append('\n').append(attachmentLine(d)).append('\n'); + } + + if (footer != null) { + sb.append("\n----\n").append(footerSentence(footer)).append('\n'); + if (footer.hasUnsubscribe()) sb.append("Stop these emails: ").append(footer.unsubscribeUrl()).append('\n'); + if (footer.hasPostalAddress()) sb.append(footer.postalAddress()).append('\n'); + } + return sb.toString(); + } + + private static void appendGroups(StringBuilder sb, AircraftSection s) { + List over = s.due().stream().filter(DueItem::overdue).toList(); + List soon = s.due().stream().filter(i -> !i.overdue()).toList(); + if (!over.isEmpty()) appendGroup(sb, "OVERDUE", over); + if (!soon.isEmpty()) appendGroup(sb, "DUE SOON", soon); + } + + private static void appendGroup(StringBuilder sb, String label, List items) { + sb.append('\n').append(label).append('\n'); + for (DueItem i : items) { + sb.append(" • ").append(i.name()); + if (i.timeText() != null && !i.timeText().isBlank()) sb.append(" — ").append(i.timeText()); + if (i.isNew()) sb.append(" [new]"); + sb.append('\n'); + } + } + + // ---- HTML ---- + + public String html(AlertDigest d, EmailFooter footer) { + Context ctx = new Context(); + ctx.setVariable("title", title(d)); + ctx.setVariable("counts", counts(d)); + ctx.setVariable("asOf", STAMP.format(d.asOf())); + ctx.setVariable("baselineLine", d.baseline() ? baselineLine() : null); + ctx.setVariable("fleet", d.isFleet()); + + List> sections = new ArrayList<>(); + for (AircraftSection s : d.sections()) { + if (d.isFleet() && !s.hasDue()) continue; + Map m = new LinkedHashMap<>(); + m.put("title", d.isFleet() ? sectionTitle(s) : null); + m.put("groups", groups(s)); + m.put("hours", hoursLine(s)); + sections.add(m); + } + ctx.setVariable("sections", sections); + + AircraftSection single = !d.isFleet() && !d.sections().isEmpty() ? d.sections().get(0) : null; + ctx.setVariable("summary", d.isFleet() ? fleetOnTrackLine(d) : singleSummary(single)); + ctx.setVariable("attachment", attachmentLine(d)); + ctx.setVariable("footerSentence", footer == null ? null : footerSentence(footer)); + ctx.setVariable("unsubscribeUrl", footer != null && footer.hasUnsubscribe() ? footer.unsubscribeUrl() : null); + ctx.setVariable("postalAddress", footer != null && footer.hasPostalAddress() ? footer.postalAddress() : null); + return templateEngine.process("email/alert-digest", ctx); + } + + private static List> groups(AircraftSection s) { + List> out = new ArrayList<>(); + List over = s.due().stream().filter(DueItem::overdue).toList(); + List soon = s.due().stream().filter(i -> !i.overdue()).toList(); + if (!over.isEmpty()) out.add(group("Overdue", OVER_FG, OVER_BG, over)); + if (!soon.isEmpty()) out.add(group("Due soon", SOON_FG, SOON_BG, soon)); + return out; + } + + private static Map group(String label, String fg, String bg, List items) { + Map g = new LinkedHashMap<>(); + g.put("label", label); + g.put("fg", fg); + g.put("bg", bg); + List> rows = new ArrayList<>(); + for (DueItem i : items) { + Map r = new LinkedHashMap<>(); + r.put("name", i.name()); + r.put("time", i.timeText() == null || i.timeText().isBlank() ? label : i.timeText()); + r.put("isNew", i.isNew()); + rows.add(r); + } + g.put("items", rows); + return g; + } + + // ---- shared wording ---- + + static String title(AlertDigest d) { + if (d.isFleet()) return "Your fleet"; + if (d.sections().isEmpty()) return "Your aircraft"; + return sectionTitle(d.sections().get(0)); + } + + static String sectionTitle(AircraftSection s) { + return s.makeModel() == null || s.makeModel().isBlank() ? s.tail() : s.tail() + " (" + s.makeModel() + ")"; + } + + static String counts(AlertDigest d) { + List parts = new ArrayList<>(); + if (d.overdueCount() > 0) parts.add(d.overdueCount() + " overdue"); + if (d.dueSoonCount() > 0) parts.add(d.dueSoonCount() + " due soon"); + return parts.isEmpty() ? "all on track" : String.join(", ", parts); + } + + static String baselineLine() { + return "Alerts are on. From now on you'll get an email when something comes due or changes."; + } + + static String singleSummary(AircraftSection s) { + if (s == null) return "There are no aircraft on this account yet."; + if (s.itemCount() == 0) return s.tail() + " has no maintenance items yet."; + if (!s.hasDue()) { + return s.itemCount() == 1 ? "Its 1 item is on track." : "All " + s.itemCount() + " items are on track."; + } + if (s.onTrackCount() == 0) return ""; + return s.onTrackCount() == 1 ? "The other item is on track." + : "The other " + s.onTrackCount() + " items are on track."; + } + + // "N2BB and N3CC: all items on track." -- null when every aircraft has something due. + static String fleetOnTrackLine(AlertDigest d) { + List tails = d.sections().stream().filter(s -> !s.hasDue()).map(AircraftSection::tail).toList(); + if (tails.isEmpty()) return null; + return joinAnd(tails) + ": all items on track."; + } + + static String attachmentLine(AlertDigest d) { + return d.isFleet() ? "The full Status Sheets are attached (PDF)." : "The full Status Sheet is attached (PDF)."; + } + + static String hoursLine(AircraftSection s) { + return "Hours: Hobbs Time " + s.hobbsTime() + " · Time in Service " + s.timeInService(); + } + + static String footerSentence(EmailFooter f) { + return "You're receiving this because " + f.operator() + " added you to maintenance alerts for " + + f.tails() + "."; + } + + static String joinAnd(List items) { + if (items.size() == 1) return items.get(0); + return String.join(", ", items.subList(0, items.size() - 1)) + " and " + items.get(items.size() - 1); + } +} diff --git a/src/main/java/com/example/AviaryService/services/alerts/AlertRecipientService.java b/src/main/java/com/example/AviaryService/services/alerts/AlertRecipientService.java index 2c01023..7523b21 100644 --- a/src/main/java/com/example/AviaryService/services/alerts/AlertRecipientService.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertRecipientService.java @@ -43,8 +43,12 @@ public class AlertRecipientService { private final OutboundEmailLimiter emailLimiter; private final AircraftRepository aircraftRepository; + private final java.time.Clock clock; + public AlertRecipientService(AlertRecipientRepository recipientRepository, - NotificationService notificationService, OutboundEmailLimiter emailLimiter, AircraftRepository aircraftRepository) { + NotificationService notificationService, OutboundEmailLimiter emailLimiter, AircraftRepository aircraftRepository, + java.time.Clock clock) { + this.clock = clock; this.recipientRepository = recipientRepository; this.notificationService = notificationService; this.emailLimiter = emailLimiter; @@ -70,7 +74,7 @@ public AlertRecipient add(User user, Channel channel, String rawDestination, Str // Re-inviting someone who previously declined/expired: fresh token, back to PENDING. r.setStatusEnum(Status.PENDING); r.setConfirmToken(newToken()); - r.setCreatedAt(Instant.now()); + r.setCreatedAt(Instant.now(clock)); r.setConfirmedAt(null); r.setReminderSentAt(null); recipientRepository.save(r); @@ -102,7 +106,7 @@ public AlertRecipient resend(User user, long id) { AlertRecipient r = ownedOrThrow(user, id); r.setStatusEnum(Status.PENDING); r.setConfirmToken(newToken()); - r.setCreatedAt(Instant.now()); + r.setCreatedAt(Instant.now(clock)); r.setConfirmedAt(null); r.setReminderSentAt(null); recipientRepository.save(r); @@ -123,7 +127,7 @@ public boolean confirm(String token) { return false; } r.setStatusEnum(Status.ACCEPTED); - r.setConfirmedAt(Instant.now()); + r.setConfirmedAt(Instant.now(clock)); recipientRepository.save(r); return true; } diff --git a/src/main/java/com/example/AviaryService/services/alerts/AlertSchedule.java b/src/main/java/com/example/AviaryService/services/alerts/AlertSchedule.java new file mode 100644 index 0000000..0bc1f44 --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertSchedule.java @@ -0,0 +1,88 @@ +package com.example.AviaryService.services.alerts; + +import java.time.LocalDate; +import java.util.EnumSet; +import java.util.Set; + +// When an alert email goes out (spec 014). Pure: the caller gathers what's +// due and when each kind of email was last sent; this says why to send today, +// or returns an empty set for "send nothing". +// Rules: specs/014-alert-reminder-frequency/contracts/schedule-rules.md. +public final class AlertSchedule { + + private AlertSchedule() {} + + public enum Reason { NEW_DUE_SOON, NEW_OVERDUE, DUE_SOON_REMINDER, OVERDUE_REMINDER, STATUS_REPORT } + + // Frequencies use Frequency's encoding. Dates are the owner's local dates; + // a last-sent date is null when that email has never gone out. + public record Input(int dueSoonEvery, int overdueEvery, int statusEvery, + boolean anyDueSoon, boolean anyOverdue, boolean newDueSoon, boolean newOverdue, + LocalDate today, LocalDate lastDueSoonSent, LocalDate lastOverdueSent, + LocalDate lastStatusSent) {} + + public static Set decide(Input in) { + Set reasons = EnumSet.noneOf(Reason.class); + // 1, 2: something got worse since the last email (Once counts here too). + if (in.newDueSoon() && in.dueSoonEvery() != Frequency.OFF) reasons.add(Reason.NEW_DUE_SOON); + if (in.newOverdue() && in.overdueEvery() != Frequency.OFF) reasons.add(Reason.NEW_OVERDUE); + // 3, 4: still due soon / overdue, and that reminder's interval has passed. + if (in.anyDueSoon() && intervalPassed(in.dueSoonEvery(), in.lastDueSoonSent(), in.today()) + && !reasons.contains(Reason.NEW_DUE_SOON)) { + reasons.add(Reason.DUE_SOON_REMINDER); + } + if (in.anyOverdue() && intervalPassed(in.overdueEvery(), in.lastOverdueSent(), in.today()) + && !reasons.contains(Reason.NEW_OVERDUE)) { + reasons.add(Reason.OVERDUE_REMINDER); + } + // 5: scheduled status report, whatever is due. + if (intervalPassed(in.statusEvery(), in.lastStatusSent(), in.today())) reasons.add(Reason.STATUS_REPORT); + return reasons; + } + + // "Every N days": N local days after the last one (Mon -> next Mon for 7). + // Never sent counts as passed. Off and Once never repeat. + static boolean intervalPassed(int every, LocalDate last, LocalDate today) { + if (every <= 0) return false; + return last == null || !today.isBefore(last.plusDays(every)); + } + + // How often an email goes out, stored as one int: + // 0 = Off, -1 = Once, 1..90 = every N days. + // The API speaks "off", "once" or a number, so the sentinels stay here. + public static final class Frequency { + public static final int OFF = 0; + public static final int ONCE = -1; + public static final int MAX_DAYS = 90; + + private Frequency() {} + + public static int parse(Object v, boolean allowOnce) { + if (v instanceof Number n) return clamp(n.intValue()); + if (v instanceof String s) { + String t = s.trim().toLowerCase(); + if (t.equals("off")) return OFF; + if (t.equals("once")) { + if (!allowOnce) throw new IllegalArgumentException("The status report can be Off or every N days."); + return ONCE; + } + try { + return clamp(Integer.parseInt(t)); + } catch (NumberFormatException e) { + // fall through + } + } + throw new IllegalArgumentException("Choose Off, Once, or a number of days from 1 to " + MAX_DAYS + "."); + } + + public static Object toJson(int v) { + if (v == OFF) return "off"; + if (v == ONCE) return "once"; + return v; + } + + private static int clamp(int days) { + return Math.max(1, Math.min(MAX_DAYS, days)); + } + } +} diff --git a/src/main/java/com/example/AviaryService/services/alerts/AlertScheduler.java b/src/main/java/com/example/AviaryService/services/alerts/AlertScheduler.java index ec4c029..64a70ca 100644 --- a/src/main/java/com/example/AviaryService/services/alerts/AlertScheduler.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertScheduler.java @@ -1,7 +1,6 @@ package com.example.AviaryService.services.alerts; -import java.time.LocalDate; -import java.time.ZoneId; +import java.time.ZonedDateTime; import java.util.List; import org.slf4j.Logger; @@ -13,7 +12,7 @@ import com.example.AviaryService.repositories.AlertPreferenceRepository; // The clock for maintenance alerts. Runs every hour and checks each user whose -// chosen alert hour matches. AlertService makes sure nobody is checked more +// chosen alert hour matches, in that user's own time zone. AlertService makes sure nobody is checked more // than once a day. Runs at :05 so it doesn't overlap FlightSyncService, which // runs at :00. See docs/specs/ALERTS_SPEC.md. @Component @@ -31,13 +30,12 @@ public AlertScheduler(AlertPreferenceRepository preferenceRepository, AlertServi @Scheduled(cron = "0 5 * * * *") public void tick() { - int hour = alertService.currentLocalHour(); - LocalDate today = LocalDate.now(ZoneId.systemDefault()); - List enabled = preferenceRepository.findByAlertsEnabledTrue(); for (AlertPreference prefs : enabled) { try { - alertService.runSweepForUser(prefs.getUser(), prefs, today, hour); + // Each owner's own hour and date (spec 014): 7:00 is their 7:00. + ZonedDateTime local = alertService.nowFor(prefs); + alertService.runSweepForUser(prefs.getUser(), prefs, local.toLocalDate(), local.getHour()); } catch (Exception e) { // One user's bad data must never stall the whole sweep. log.warn("Alert sweep failed for user {}: {}", diff --git a/src/main/java/com/example/AviaryService/services/alerts/AlertService.java b/src/main/java/com/example/AviaryService/services/alerts/AlertService.java index e9d9649..0e30052 100644 --- a/src/main/java/com/example/AviaryService/services/alerts/AlertService.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertService.java @@ -1,12 +1,13 @@ package com.example.AviaryService.services.alerts; +import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.List; +import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,18 +40,20 @@ public class AlertService { private final AlertDigestService digestService; private final NotificationService notificationService; private final AircraftRepository aircraftRepository; + private final Clock clock; public AlertService(AlertPreferenceRepository preferenceRepository, AlertRecipientRepository recipientRepository, AlertSendLogRepository sendLogRepository, AlertDigestService digestService, - NotificationService notificationService, AircraftRepository aircraftRepository) { + NotificationService notificationService, AircraftRepository aircraftRepository, Clock clock) { this.preferenceRepository = preferenceRepository; this.recipientRepository = recipientRepository; this.sendLogRepository = sendLogRepository; this.digestService = digestService; this.notificationService = notificationService; this.aircraftRepository = aircraftRepository; + this.clock = clock; } @Transactional @@ -64,14 +67,26 @@ public AlertPreference getOrCreatePrefs(User user) { // isn't flooded on the next sweep. @Transactional public AlertPreference updatePrefs(User user, boolean enabled, int checkHour, - int leadTimeDays, int leadTimeHours, int overdueRenudgeDays) { + int leadTimeDays, int leadTimeHours, int overdueEvery) { + AlertPreference current = getOrCreatePrefs(user); + return updatePrefs(user, enabled, checkHour, leadTimeDays, leadTimeHours, overdueEvery, + current.getDueSoonEveryDays(), current.getStatusEveryDays()); + } + + // Frequencies use AlertSchedule.Frequency's encoding (0 Off, -1 Once, + // 1-90 days); the controller has already parsed and validated them. + @Transactional + public AlertPreference updatePrefs(User user, boolean enabled, int checkHour, + int leadTimeDays, int leadTimeHours, int overdueEvery, int dueSoonEvery, int statusEvery) { AlertPreference prefs = getOrCreatePrefs(user); boolean wasEnabled = prefs.isAlertsEnabled(); prefs.setCheckHour(clamp(checkHour, 0, 23)); prefs.setLeadTimeDays(Math.max(0, leadTimeDays)); prefs.setLeadTimeHours(Math.max(0, leadTimeHours)); - prefs.setOverdueRenudgeDays(Math.max(1, overdueRenudgeDays)); + prefs.setOverdueEveryDays(frequency(overdueEvery, true)); + prefs.setDueSoonEveryDays(frequency(dueSoonEvery, true)); + prefs.setStatusEveryDays(frequency(statusEvery, false)); prefs.setAlertsEnabled(enabled); preferenceRepository.save(prefs); @@ -81,12 +96,23 @@ public AlertPreference updatePrefs(User user, boolean enabled, int checkHour, return prefs; } + // The owner's time zone, from their browser. Invalid ids are refused. + @Transactional + public AlertPreference updateTimeZone(User user, String zoneId) { + ZoneId zone = ZoneId.of(zoneId.trim()); // DateTimeException if invalid + AlertPreference prefs = getOrCreatePrefs(user); + prefs.setTimeZone(zone.getId()); + return preferenceRepository.save(prefs); + } + private void sendBaseline(User user, AlertPreference prefs) { AlertDigest digest = digestService.buildDigest(user, prefs, true); int sent = notificationService.sendDigest(user, digest); digestService.markFired(user, prefs); - prefs.setBaselineSentAt(Instant.now()); - prefs.setLastCheckedOn(LocalDate.now(ZoneOffset.UTC)); + // The baseline is a full status, so every timer starts from it. + recordSent(prefs, digest, true); + prefs.setBaselineSentAt(Instant.now(clock)); + prefs.setLastCheckedOn(LocalDate.now(clock.withZone(prefs.zone()))); preferenceRepository.save(prefs); log.info("Baseline alert digest for {} sent to {} recipient(s).", user.getUsername(), sent); } @@ -99,11 +125,15 @@ public int sendNow(User user) { AlertDigest digest = digestService.buildDigest(user, prefs, false); int sent = notificationService.sendDigest(user, digest); digestService.markFired(user, prefs); + recordSent(prefs, digest, false); + preferenceRepository.save(prefs); return sent; } // One user's daily evaluation. No-op unless alerts are on, it's their chosen - // hour, and today's sweep hasn't already run. + // hour, and today's sweep hasn't already run. `today` and `currentHour` + // are in the owner's zone (AlertScheduler). Whether to email is + // AlertSchedule's call (spec 014). @Transactional public boolean runSweepForUser(User user, AlertPreference prefs, LocalDate today, int currentHour) { if (!prefs.isAlertsEnabled()) { @@ -117,22 +147,60 @@ public boolean runSweepForUser(User user, AlertPreference prefs, LocalDate today } AlertDigest digest = digestService.buildDigest(user, prefs, false); + ZoneId zone = prefs.zone(); + if (prefs.getLastOverdueSentAt() == null && digest.overdueCount() > 0) { + // First run after spec 014: continue the old per-item re-nudge clock. + prefs.setLastOverdueSentAt(digestService.latestOverdueAlertAt(user)); + } + Set reasons = AlertSchedule.decide(new AlertSchedule.Input( + prefs.getDueSoonEveryDays(), prefs.getOverdueEveryDays(), prefs.getStatusEveryDays(), + digest.dueSoonCount() > 0, digest.overdueCount() > 0, digest.newDueSoon(), digest.newOverdue(), + today, localDate(prefs.getLastDueSoonSentAt(), zone), localDate(prefs.getLastOverdueSentAt(), zone), + localDate(prefs.getLastStatusSentAt(), zone))); + boolean sentSomething = false; - if (digest.shouldSend()) { + if (!reasons.isEmpty()) { + if (reasons.equals(Set.of(AlertSchedule.Reason.STATUS_REPORT))) { + digestService.markAsStatusReport(digest, aircraftRepository.findByUserOrderByIdAsc(user), + prefs.getStatusEveryDays()); + } int sent = notificationService.sendDigest(user, digest); digestService.markFired(user, prefs); + recordSent(prefs, digest, reasons.contains(AlertSchedule.Reason.STATUS_REPORT)); sentSomething = sent > 0; - log.info("Daily alert sweep for {}: digest sent to {} recipient(s).", user.getUsername(), sent); + log.info("Daily alert sweep for {} ({}): digest sent to {} recipient(s).", user.getUsername(), reasons, sent); } prefs.setLastCheckedOn(today); preferenceRepository.save(prefs); return sentSomething; } + // After an email goes out: each kind of reminder counts from the last + // email that listed its items (research R7). + private void recordSent(AlertPreference prefs, AlertDigest digest, boolean statusReport) { + Instant now = Instant.now(clock); + if (digest.dueSoonCount() > 0) prefs.setLastDueSoonSentAt(now); + if (digest.overdueCount() > 0) prefs.setLastOverdueSentAt(now); + if (statusReport) prefs.setLastStatusSentAt(now); + } + + private static LocalDate localDate(Instant at, ZoneId zone) { + return at == null ? null : at.atZone(zone).toLocalDate(); + } + + private static int frequency(int v, boolean allowOnce) { + if (v == AlertSchedule.Frequency.OFF) return v; + if (v == AlertSchedule.Frequency.ONCE) { + if (!allowOnce) throw new IllegalArgumentException("The status report can be Off or every N days."); + return v; + } + return clamp(v, 1, AlertSchedule.Frequency.MAX_DAYS); + } + // Called once per scheduler tick, after the per-user sweeps. @Transactional public void housekeepPendingRecipients() { - Instant now = Instant.now(); + Instant now = Instant.now(clock); List pending = recipientRepository.findByStatus(Status.PENDING.name()); for (AlertRecipient r : pending) { long ageDays = Duration.between(r.getCreatedAt(), now).toDays(); @@ -150,7 +218,7 @@ public void housekeepPendingRecipients() { @Transactional public void pruneSendLog() { - sendLogRepository.deleteBySentAtBefore(Instant.now().minus(Duration.ofDays(SEND_LOG_RETENTION_DAYS))); + sendLogRepository.deleteBySentAtBefore(Instant.now(clock).minus(Duration.ofDays(SEND_LOG_RETENTION_DAYS))); } private void sendReminder(AlertRecipient r) { @@ -172,9 +240,9 @@ private void sendReminder(AlertRecipient r) { } } - // Used by the scheduler to know "what hour is it" consistently. - public int currentLocalHour() { - return ZonedDateTime.now(ZoneId.systemDefault()).getHour(); + // "Now" in the owner's zone; the scheduler compares its hour and date. + public ZonedDateTime nowFor(AlertPreference prefs) { + return ZonedDateTime.now(clock).withZoneSameInstant(prefs.zone()); } private static int clamp(int v, int lo, int hi) { diff --git a/src/main/java/com/example/AviaryService/services/alerts/EmailFooter.java b/src/main/java/com/example/AviaryService/services/alerts/EmailFooter.java new file mode 100644 index 0000000..d149119 --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/alerts/EmailFooter.java @@ -0,0 +1,15 @@ +package com.example.AviaryService.services.alerts; + +// The bottom of an alert email, per recipient: who added them, for which +// aircraft, their own stop link, and the postal address (CAN-SPAM). The +// link and address may be blank, then they're left out. +public record EmailFooter(String operator, String tails, String unsubscribeUrl, String postalAddress) { + + public boolean hasUnsubscribe() { + return unsubscribeUrl != null && !unsubscribeUrl.isBlank(); + } + + public boolean hasPostalAddress() { + return postalAddress != null && !postalAddress.isBlank(); + } +} diff --git a/src/main/java/com/example/AviaryService/services/alerts/LeadTimes.java b/src/main/java/com/example/AviaryService/services/alerts/LeadTimes.java new file mode 100644 index 0000000..389de91 --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/alerts/LeadTimes.java @@ -0,0 +1,16 @@ +package com.example.AviaryService.services.alerts; + +import com.example.AviaryService.entity.AlertPreference; + +// How far ahead an item counts as "due soon": the owner's alert lead times. +// The alert email, the PDF and the dashboard's amber pills all use these, so +// they always agree (spec 013). +public record LeadTimes(int days, int hours) { + + // Same defaults as AlertPreference: 30 days, 10 hours. + public static final LeadTimes DEFAULT = new LeadTimes(30, 10); + + public static LeadTimes of(AlertPreference prefs) { + return prefs == null ? DEFAULT : new LeadTimes(prefs.getLeadTimeDays(), prefs.getLeadTimeHours()); + } +} diff --git a/src/main/java/com/example/AviaryService/services/alerts/NotificationService.java b/src/main/java/com/example/AviaryService/services/alerts/NotificationService.java index e74ef42..057f202 100644 --- a/src/main/java/com/example/AviaryService/services/alerts/NotificationService.java +++ b/src/main/java/com/example/AviaryService/services/alerts/NotificationService.java @@ -21,7 +21,7 @@ import com.example.AviaryService.services.messaging.SmsSender; // Sends an alert to each of a user's confirmed recipients, one message each. -// Limit per recipient: one email per 24 hours, one text per 72 hours. +// Limit per recipient: one email per calendar day (owner's zone), one text per 72 hours. // "Send alert now" and the daily check share that limit. A recipient on // cooldown, or a sender that isn't set up, is skipped and logged instead of // causing an error. See docs/specs/ALERTS_SPEC.md ("Rate limit"). @@ -30,7 +30,6 @@ public class NotificationService { private static final Logger log = LoggerFactory.getLogger(NotificationService.class); - private static final Duration EMAIL_COOLDOWN = Duration.ofHours(24); private static final Duration SMS_COOLDOWN = Duration.ofHours(72); private final EmailSender emailSender; @@ -39,6 +38,8 @@ public class NotificationService { private final AlertSendLogRepository sendLogRepository; private final PdfExportService pdfExportService; private final AircraftRepository aircraftRepository; + private final AlertEmailRenderer renderer; + private final java.time.Clock clock; private final String baseUrl; private final String postalAddress; @@ -46,6 +47,7 @@ public class NotificationService { public NotificationService(EmailSender emailSender, SmsSender smsSender, AlertRecipientRepository recipientRepository, AlertSendLogRepository sendLogRepository, PdfExportService pdfExportService, AircraftRepository aircraftRepository, + AlertEmailRenderer renderer, java.time.Clock clock, @Value("${aviary.alerts.base-url:}") String baseUrl, @Value("${aviary.alerts.postal-address:}") String postalAddress) { this.emailSender = emailSender; @@ -54,6 +56,8 @@ public NotificationService(EmailSender emailSender, SmsSender smsSender, this.sendLogRepository = sendLogRepository; this.pdfExportService = pdfExportService; this.aircraftRepository = aircraftRepository; + this.renderer = renderer; + this.clock = clock; this.baseUrl = baseUrl == null ? "" : baseUrl.replaceAll("/+$", ""); this.postalAddress = postalAddress == null ? "" : postalAddress; } @@ -73,7 +77,7 @@ public int sendDigest(User user, AlertDigest digest) { int sent = 0; for (AlertRecipient r : accepted) { - if (onCooldown(r)) { + if (onCooldown(r, digest.zone())) { log.info("Recipient {} on cooldown -- skipping this digest.", r.getId()); continue; } @@ -84,11 +88,12 @@ public int sendDigest(User user, AlertDigest digest) { continue; } if (pdf == null) { - pdf = pdfExportService.generateFleetPdf(fleet, java.time.LocalDate.now()); + pdf = pdfExportService.generateFleetPdf(fleet, java.time.LocalDate.now(clock.withZone(digest.zone())), digest.leadTimes()); } + EmailFooter footer = footerFor(fleet, r); emailSender.sendPdf(r.getDestination(), digest.subject(), - digest.body() + emailFooter(fleet, r), - pdf, "Aviary_Maintenance_" + java.time.LocalDate.now() + ".pdf"); + renderer.text(digest, footer), renderer.html(digest, footer), + pdf, "Aviary_Maintenance_" + java.time.LocalDate.now(clock.withZone(digest.zone())) + ".pdf"); } else { smsSender.send(r.getDestination(), smsBody(fleet, digest)); } @@ -122,28 +127,26 @@ public String baseUrl() { // -- internals -- - private boolean onCooldown(AlertRecipient r) { - Duration cd = r.getChannelEnum() == AlertRecipient.Channel.SMS ? SMS_COOLDOWN : EMAIL_COOLDOWN; - return sendLogRepository.existsByRecipientIdAndSentAtAfter(r.getId(), Instant.now().minus(cd)); + // Email: at most one per calendar day in the owner's zone (spec 014 R4). + // A rolling 24 hours dropped tomorrow's email whenever the hourly check + // ran a few seconds earlier than today's. Text: one per 72 hours. + private boolean onCooldown(AlertRecipient r, java.time.ZoneId zone) { + Instant since = r.getChannelEnum() == AlertRecipient.Channel.SMS + ? Instant.now(clock).minus(SMS_COOLDOWN) + : java.time.LocalDate.now(clock.withZone(zone)).atStartOfDay(zone).toInstant().minusNanos(1); + return sendLogRepository.existsByRecipientIdAndSentAtAfter(r.getId(), since); } private void recordSend(AlertRecipient r) { - sendLogRepository.save(new AlertSendLog(r.getId(), r.getChannelEnum())); + AlertSendLog entry = new AlertSendLog(r.getId(), r.getChannelEnum()); + entry.setSentAt(Instant.now(clock)); + sendLogRepository.save(entry); } - private String emailFooter(List fleet, AlertRecipient r) { - StringBuilder sb = new StringBuilder("\n\n----\n"); - sb.append("You're receiving this because ").append(AlertText.operator(fleet)) - .append(" added you to maintenance\nalerts for ").append(AlertText.tail(fleet)) - .append(". The full dashboard is attached as a PDF.\n"); - if (!baseUrl.isBlank()) { - sb.append("Stop these emails: ").append(baseUrl) - .append("/alerts/unsubscribe?token=").append(r.getConfirmToken()).append('\n'); - } - if (!postalAddress.isBlank()) { - sb.append(postalAddress).append('\n'); - } - return sb.toString(); + // Per recipient: their own stop link (spec 013 research R2). + private EmailFooter footerFor(List fleet, AlertRecipient r) { + String stop = baseUrl.isBlank() ? null : baseUrl + "/alerts/unsubscribe?token=" + r.getConfirmToken(); + return new EmailFooter(AlertText.operator(fleet), AlertText.tail(fleet), stop, postalAddress); } private String smsBody(List fleet, AlertDigest digest) { diff --git a/src/main/java/com/example/AviaryService/services/dashboard/PdfExportService.java b/src/main/java/com/example/AviaryService/services/dashboard/PdfExportService.java index d1b97c6..8a496fb 100644 --- a/src/main/java/com/example/AviaryService/services/dashboard/PdfExportService.java +++ b/src/main/java/com/example/AviaryService/services/dashboard/PdfExportService.java @@ -22,6 +22,8 @@ import com.example.AviaryService.entity.Aircraft; import com.example.AviaryService.repositories.FlightLogRepository; import com.example.AviaryService.repositories.StatusSheetItemRepository; +import com.example.AviaryService.services.alerts.AlertLevel; +import com.example.AviaryService.services.alerts.LeadTimes; import com.example.AviaryService.util.DueDates; import com.example.AviaryService.util.Formatting; import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; @@ -46,13 +48,11 @@ public PdfExportService(ITemplateEngine templateEngine, this.flightLogRepository = flightLogRepository; } - public byte[] generateDashboardPdf(Aircraft aircraft) { - return generateDashboardPdf(aircraft, LocalDate.now()); - } - // `today` drives Time Left, so the PDF matches what the user's own browser - // shows (the server may be a day ahead/behind in UTC). - public byte[] generateDashboardPdf(Aircraft aircraft, LocalDate today) { + // shows (the server may be a day ahead/behind in UTC). `lead` is the + // owner's alert lead times: they decide which items are DUE SOON, the + // same as the dashboard's amber pills (spec 013). + public byte[] generateDashboardPdf(Aircraft aircraft, LocalDate today, LeadTimes lead) { Context context = new Context(); context.setVariable("makeModel", aircraft.getMakeModel()); context.setVariable("tailNumber", aircraft.getTailNumber()); @@ -62,7 +62,7 @@ public byte[] generateDashboardPdf(Aircraft aircraft, LocalDate today) { context.setVariable("timeInServiceHours", formatHoursOrBlank(aircraft.getTimeInServiceHours())); context.setVariable("generatedAt", DateTimeFormatter.ofPattern("MMM d, yyyy h:mm a") .withZone(ZoneOffset.UTC).format(Instant.now()) + " UTC"); - context.setVariable("statusSheetRows", buildStatusSheetRows(aircraft, today)); + context.setVariable("statusSheetRows", buildStatusSheetRows(aircraft, today, lead)); context.setVariable("logRows", buildLogRows(aircraft)); String html = templateEngine.process("pdf-export", context); @@ -71,14 +71,14 @@ public byte[] generateDashboardPdf(Aircraft aircraft, LocalDate today) { // Alert emails cover the whole fleet but carry one attachment: each // aircraft's report, one after another, merged into a single PDF. - public byte[] generateFleetPdf(List fleet, LocalDate today) { + public byte[] generateFleetPdf(List fleet, LocalDate today, LeadTimes lead) { if (fleet.size() == 1) { - return generateDashboardPdf(fleet.get(0), today); + return generateDashboardPdf(fleet.get(0), today, lead); } try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { org.apache.pdfbox.multipdf.PDFMergerUtility merger = new org.apache.pdfbox.multipdf.PDFMergerUtility(); for (Aircraft aircraft : fleet) { - merger.addSource(new org.apache.pdfbox.io.RandomAccessReadBuffer(generateDashboardPdf(aircraft, today))); + merger.addSource(new org.apache.pdfbox.io.RandomAccessReadBuffer(generateDashboardPdf(aircraft, today, lead))); } merger.setDestinationStream(out); merger.mergeDocuments(org.apache.pdfbox.io.IOUtils.createMemoryOnlyStreamCache()); @@ -104,13 +104,14 @@ private byte[] renderPdf(String html) { } } - private List> buildStatusSheetRows(Aircraft aircraft, LocalDate today) { + private List> buildStatusSheetRows(Aircraft aircraft, LocalDate today, LeadTimes lead) { return statusSheetItemRepository.findByAircraftOrderByStatusSheetOrderAsc(aircraft).stream() - .map(t -> statusSheetRowData(t, today, aircraft.getTimeInServiceHours())) + .map(t -> statusSheetRowData(t, today, aircraft.getTimeInServiceHours(), lead)) .collect(Collectors.toList()); } - private Map statusSheetRowData(StatusSheetItem t, LocalDate today, Double currentTimeInService) { + private Map statusSheetRowData(StatusSheetItem t, LocalDate today, Double currentTimeInService, + LeadTimes lead) { Map row = new HashMap<>(); row.put("isTitle", t.getIsTitle()); row.put("item", t.getItem()); @@ -122,7 +123,11 @@ private Map statusSheetRowData(StatusSheetItem t, LocalDate toda // as the last edit to the row. String timeLeft = DueDates.formatTimeLeft(t.getDueDateDate(), t.getDueDateHours(), today, currentTimeInService); row.put("timeLeft", timeLeft); - row.put("overdue", timeLeft.contains("overdue")); + // Same rule as alerts and the dashboard pills: the closest limit decides. + AlertLevel level = DueDates.classify(t.getDueDateDate(), t.getDueDateHours(), currentTimeInService, today, + lead.days(), lead.hours()); + row.put("status", switch (level) { case OVERDUE -> "over"; case DUE_SOON -> "soon"; case OK -> "ok"; }); + row.put("statusLabel", switch (level) { case OVERDUE -> "OVERDUE"; case DUE_SOON -> "DUE SOON"; case OK -> null; }); return row; } diff --git a/src/main/java/com/example/AviaryService/services/messaging/EmailSender.java b/src/main/java/com/example/AviaryService/services/messaging/EmailSender.java index c48cc08..dd3468f 100644 --- a/src/main/java/com/example/AviaryService/services/messaging/EmailSender.java +++ b/src/main/java/com/example/AviaryService/services/messaging/EmailSender.java @@ -13,6 +13,12 @@ public interface EmailSender { // Plain-text email, no attachment (confirmation links, reminders). void send(String toEmail, String subject, String body); - // Plain-text email with a single PDF attachment (dashboard export, digests). - void sendPdf(String toEmail, String subject, String body, byte[] pdfBytes, String filename); + // Plain-text email with a single PDF attachment (dashboard export). + default void sendPdf(String toEmail, String subject, String body, byte[] pdfBytes, String filename) { + sendPdf(toEmail, subject, body, null, pdfBytes, filename); + } + + // Text + HTML versions of the same email with a single PDF attachment + // (alert digests, spec 013). htmlBody may be null: then text only. + void sendPdf(String toEmail, String subject, String textBody, String htmlBody, byte[] pdfBytes, String filename); } diff --git a/src/main/java/com/example/AviaryService/services/messaging/SesEmailService.java b/src/main/java/com/example/AviaryService/services/messaging/SesEmailService.java index 67b0e5d..34fe81d 100644 --- a/src/main/java/com/example/AviaryService/services/messaging/SesEmailService.java +++ b/src/main/java/com/example/AviaryService/services/messaging/SesEmailService.java @@ -60,11 +60,11 @@ public boolean isConfigured() { @Override public void send(String toEmail, String subject, String body) { - dispatch(toEmail, subject, body, List.of()); + dispatch(toEmail, subject, body, null, List.of()); } @Override - public void sendPdf(String toEmail, String subject, String body, byte[] pdfBytes, String filename) { + public void sendPdf(String toEmail, String subject, String body, String htmlBody, byte[] pdfBytes, String filename) { Attachment pdf = Attachment.builder() .rawContent(SdkBytes.fromByteArray(pdfBytes)) .fileName(filename) @@ -73,16 +73,21 @@ public void sendPdf(String toEmail, String subject, String body, byte[] pdfBytes // A PDF is binary; base64 is the only encoding that survives email intact. .contentTransferEncoding("BASE64") .build(); - dispatch(toEmail, subject, body, List.of(pdf)); + dispatch(toEmail, subject, body, htmlBody, List.of(pdf)); } - private void dispatch(String toEmail, String subject, String body, List attachments) { + private void dispatch(String toEmail, String subject, String body, String htmlBody, List attachments) { if (!configured) { throw new IllegalStateException("SES is not configured; cannot send email."); } + // SES sends text + HTML as multipart/alternative; mail apps pick one. + Body.Builder content = Body.builder().text(Content.builder().data(body).charset("UTF-8").build()); + if (htmlBody != null) { + content.html(Content.builder().data(htmlBody).charset("UTF-8").build()); + } Message.Builder message = Message.builder() - .subject(Content.builder().data(subject).build()) - .body(Body.builder().text(Content.builder().data(body).build()).build()); + .subject(Content.builder().data(subject).charset("UTF-8").build()) + .body(content.build()); if (!attachments.isEmpty()) { message.attachments(attachments); } diff --git a/src/main/resources/static/css/dashboardstyle.css b/src/main/resources/static/css/dashboardstyle.css index 001dfa5..ddd08f0 100644 --- a/src/main/resources/static/css/dashboardstyle.css +++ b/src/main/resources/static/css/dashboardstyle.css @@ -2878,3 +2878,12 @@ textarea::placeholder { display: none; } @media (min-width: 1200px) { .time-left .tl-pills { flex-wrap: nowrap; } } + +/* Alert schedule (spec 014): one line per alert email. */ +.alerts-schedule-line { margin-bottom: 6px; } +.alerts-frequency { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 8px; margin: 6px 0; } +.alerts-frequency > label { min-width: 7.5rem; font-weight: 600; } +.alerts-frequency .alerts-every-hint { flex-basis: 100%; margin-left: 7.5rem; } +@media (max-width: 600px) { + .alerts-frequency .alerts-every-hint { margin-left: 0; } +} diff --git a/src/main/resources/static/js/dashboard.js b/src/main/resources/static/js/dashboard.js index d3084d4..fc8d15f 100644 --- a/src/main/resources/static/js/dashboard.js +++ b/src/main/resources/static/js/dashboard.js @@ -3161,8 +3161,54 @@ document.addEventListener('DOMContentLoaded', () => { const checkHour = $('alerts-check-hour'); const leadDays = $('alerts-lead-days'); const leadHours = $('alerts-lead-hours'); - const renudgeDays = $('alerts-renudge-days'); const saveSchedule = $('alerts-save-schedule'); + const zoneLabel = $('alerts-time-zone'); + + // Spec 014: Due soon / Overdue / Status report, each Off, Once, or every N days. + const KINDS = ['due-soon', 'overdue', 'status']; + const PRESETS = ['1', '2', '3', '7', '14', '30']; + const everySel = (k) => $(`alerts-${k}-every`); + const everyDays = (k) => $(`alerts-${k}-every-days`); + + function setEvery(kind, value) { + const sel = everySel(kind), days = everyDays(kind); + const v = String(value); + if (v === 'off' || v === 'once' || PRESETS.includes(v)) { + sel.value = v; + } else { + sel.value = 'custom'; + days.value = v; + } + refreshEvery(kind); + } + + function getEvery(kind) { + const v = everySel(kind).value; + if (v === 'custom') return Number(everyDays(kind).value) || 1; + return (v === 'off' || v === 'once') ? v : Number(v); + } + + function everyHint(kind, v) { + const what = kind === 'due-soon' ? 'due soon' : 'overdue'; + if (kind === 'status') { + return v === 'off' ? 'No scheduled status email.' + : `Email the full status every ${v === 1 ? 'day' : v + ' days'}, even when nothing is due.`; + } + if (v === 'off') return `Never email just because something is ${what}.`; + if (v === 'once') return `Email me once when something becomes ${what}.`; + return `Email me every ${v === 1 ? 'day' : v + ' days'} while anything is ${what}.`; + } + + function refreshEvery(kind) { + const custom = everySel(kind).value === 'custom'; + everyDays(kind).closest('.alerts-every-custom').hidden = !custom; + $(`alerts-${kind}-hint`).textContent = everyHint(kind, getEvery(kind)); + } + + KINDS.forEach(k => { + everySel(k).addEventListener('change', () => refreshEvery(k)); + everyDays(k).addEventListener('input', () => refreshEvery(k)); + }); const sendNowBtn = $('alerts-send-now'); const sendNowMsg = $('alerts-send-now-result'); const chanSel = $('alert-recipient-channel'); @@ -3191,7 +3237,11 @@ document.addEventListener('DOMContentLoaded', () => { checkHour.value = p.checkHour; leadDays.value = p.leadTimeDays; leadHours.value = p.leadTimeHours; - renudgeDays.value = p.overdueRenudgeDays; + setEvery('due-soon', p.dueSoonEvery); + setEvery('overdue', p.overdueEvery); + setEvery('status', p.statusEvery); + zoneLabel.textContent = p.timeZone; + syncTimeZone(p.timeZone); const missing = (p.readiness && p.readiness.missing) || []; readiness.textContent = missing.length ? 'Before turning on: ' + missing.join('; ') @@ -3199,6 +3249,20 @@ document.addEventListener('DOMContentLoaded', () => { } catch (e) { /* leave defaults */ } } + // "7:00" means the owner's 7:00: tell the server the browser's zone when + // it differs from the saved one (spec 014). + async function syncTimeZone(saved) { + let zone; + try { zone = Intl.DateTimeFormat().resolvedOptions().timeZone; } catch (e) { return; } + if (!zone || zone === saved) return; + try { + const r = await fetch('/alerts/time-zone', { + method: 'POST', headers: jsonHeaders(), body: JSON.stringify({ timeZone: zone }), + }); + if (r.ok) zoneLabel.textContent = (await r.json()).timeZone; + } catch (e) { /* keep the saved zone */ } + } + function statusBadge(s) { const map = { PENDING: 'Pending', ACCEPTED: 'Accepted', DECLINED: 'Declined', EXPIRED: 'Expired' }; return map[s] || s; @@ -3234,7 +3298,9 @@ document.addEventListener('DOMContentLoaded', () => { checkHour: Number(checkHour.value), leadTimeDays: Number(leadDays.value), leadTimeHours: Number(leadHours.value), - overdueRenudgeDays: Number(renudgeDays.value), + dueSoonEvery: getEvery('due-soon'), + overdueEvery: getEvery('overdue'), + statusEvery: getEvery('status'), ...extra, }; const r = await fetch('/alerts/preferences', { diff --git a/src/main/resources/templates/dashboard.html b/src/main/resources/templates/dashboard.html index c0c49af..f850fb0 100644 --- a/src/main/resources/templates/dashboard.html +++ b/src/main/resources/templates/dashboard.html @@ -235,15 +235,38 @@

Add aircraft

Alert schedule - Check daily at - - (local time). Warn - days / - hours before due. - Re-nudge overdue every - days. + +
+ Check daily at + + (your time). +
+
+ Due soon means + days or + hours before due. +
+
+ + + + +
diff --git a/src/main/resources/templates/email/alert-digest.html b/src/main/resources/templates/email/alert-digest.html new file mode 100644 index 0000000..0ff9486 --- /dev/null +++ b/src/main/resources/templates/email/alert-digest.html @@ -0,0 +1,79 @@ + + + + + + + Alert + + + + + + +
+ + + + + + + + + + + + + + + + +
+
N12SAS
+
1 due soon
+
as of
+
Alerts are on.
+
+
N1AA (Cessna 172)
+ + + + + + + + +
Due soon
+ ELT Battery + New + + 10 days left +
+
Hours
+
+
The other 38 items are on track.
+
The full Status Sheet is attached (PDF).
+
+
You're receiving this because…
+ +
Address
+
+
+ + diff --git a/src/main/resources/templates/pdf-export.html b/src/main/resources/templates/pdf-export.html index 2d4e4c0..1c41c79 100644 --- a/src/main/resources/templates/pdf-export.html +++ b/src/main/resources/templates/pdf-export.html @@ -63,8 +63,13 @@ white-space: pre-line; font-weight: bold; } - td.time-left.overdue { - color: #E64E6D; + /* Spec 013: same states and colors as the dashboard's Time Left pills, + plus a word so they still read in black and white. */ + td.time-left.over { + color: #B3203F; + } + td.time-left.soon { + color: #8A5A00; } tr.title-row td { background-color: #2C9B6F; @@ -123,7 +128,7 @@

Status Sheet

- + diff --git a/src/test/java/com/example/AviaryService/controllers/AlertPreferencesApiTest.java b/src/test/java/com/example/AviaryService/controllers/AlertPreferencesApiTest.java new file mode 100644 index 0000000..14653de --- /dev/null +++ b/src/test/java/com/example/AviaryService/controllers/AlertPreferencesApiTest.java @@ -0,0 +1,119 @@ +package com.example.AviaryService.controllers; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; + +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.support.TestFleet; +import com.example.AviaryService.repositories.AircraftRepository; + +// Spec 014 matrix D (+ C4): the alert settings API -- defaults, Off/Once/N, +// validation, the old key, time zone, and one owner never touching another. +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +class AlertPreferencesApiTest { + + @Autowired MockMvc mvc; + @Autowired UserRepository userRepository; + @Autowired AircraftRepository aircraftRepository; + + private String owner; + + private String newOwner(String prefix) { + User u = new User(); + u.setUsername(prefix + System.nanoTime()); + u.setPassword("x"); + userRepository.save(u); + TestFleet.addAircraft(aircraftRepository, userRepository, u, "N1", "Pat", 0, 0); + return u.getUsername(); + } + + @BeforeEach + void setUp() { + owner = newOwner("prefs-"); + } + + private org.springframework.test.web.servlet.ResultActions putPrefs(String who, String json) throws Exception { + return mvc.perform(put("/alerts/preferences").with(user(who)).with(csrf()) + .contentType(MediaType.APPLICATION_JSON).content(json)); + } + + @Test + void d1_newOwnerGetsTheDefaults() throws Exception { + mvc.perform(get("/alerts/preferences").with(user(owner))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.statusEvery").value("off")) + .andExpect(jsonPath("$.dueSoonEvery").value(7)) + .andExpect(jsonPath("$.overdueEvery").value(3)) + .andExpect(jsonPath("$.timeZone").value("America/New_York")); + } + + @Test + void d2_offOnceAndDaysRoundTrip() throws Exception { + putPrefs(owner, "{\"dueSoonEvery\":\"once\",\"overdueEvery\":\"off\",\"statusEvery\":14}") + .andExpect(status().isOk()) + .andExpect(jsonPath("$.dueSoonEvery").value("once")) + .andExpect(jsonPath("$.overdueEvery").value("off")) + .andExpect(jsonPath("$.statusEvery").value(14)); + mvc.perform(get("/alerts/preferences").with(user(owner))) + .andExpect(jsonPath("$.dueSoonEvery").value("once")) + .andExpect(jsonPath("$.overdueEvery").value("off")) + .andExpect(jsonPath("$.statusEvery").value(14)); + } + + @Test + void d3_statusReportCannotBeOnce() throws Exception { + putPrefs(owner, "{\"statusEvery\":\"once\"}").andExpect(status().isBadRequest()); + putPrefs(owner, "{\"dueSoonEvery\":\"weekly\"}").andExpect(status().isBadRequest()); + mvc.perform(get("/alerts/preferences").with(user(owner))) + .andExpect(jsonPath("$.statusEvery").value("off")) + .andExpect(jsonPath("$.dueSoonEvery").value(7)); + } + + @Test + void d4_oneOwnerNeverChangesAnother() throws Exception { + String other = newOwner("prefs-other-"); + putPrefs(other, "{\"dueSoonEvery\":2,\"overdueEvery\":1,\"statusEvery\":7}").andExpect(status().isOk()); + mvc.perform(get("/alerts/preferences").with(user(owner))) + .andExpect(jsonPath("$.dueSoonEvery").value(7)) + .andExpect(jsonPath("$.overdueEvery").value(3)) + .andExpect(jsonPath("$.statusEvery").value("off")); + } + + @Test + void oldRenudgeKeyStillSetsOverdue() throws Exception { + putPrefs(owner, "{\"overdueRenudgeDays\":5}") + .andExpect(status().isOk()) + .andExpect(jsonPath("$.overdueEvery").value(5)); + } + + @Test + void c4_timeZoneIsValidated() throws Exception { + mvc.perform(post("/alerts/time-zone").with(user(owner)).with(csrf()) + .contentType(MediaType.APPLICATION_JSON).content("{\"timeZone\":\"Not/AZone\"}")) + .andExpect(status().isBadRequest()); + mvc.perform(get("/alerts/preferences").with(user(owner))) + .andExpect(jsonPath("$.timeZone").value("America/New_York")); + mvc.perform(post("/alerts/time-zone").with(user(owner)).with(csrf()) + .contentType(MediaType.APPLICATION_JSON).content("{\"timeZone\":\"America/Chicago\"}")) + .andExpect(status().isOk()); + mvc.perform(get("/alerts/preferences").with(user(owner))) + .andExpect(jsonPath("$.timeZone").value("America/Chicago")); + } +} diff --git a/src/test/java/com/example/AviaryService/controllers/UserControllerTest.java b/src/test/java/com/example/AviaryService/controllers/UserControllerTest.java index 3ede98e..0762820 100644 --- a/src/test/java/com/example/AviaryService/controllers/UserControllerTest.java +++ b/src/test/java/com/example/AviaryService/controllers/UserControllerTest.java @@ -80,6 +80,10 @@ void setUp() { jdbc.update("DELETE FROM flight_suggestions"); jdbc.update("DELETE FROM subscriptions"); jdbc.update("DELETE FROM import_proposals"); + // Alert rows left by non-transactional alert tests (spec 014 simulations). + jdbc.update("DELETE FROM alert_send_log"); + jdbc.update("DELETE FROM alert_recipients"); + jdbc.update("DELETE FROM alert_preferences"); jdbc.update("DELETE FROM timeline_import_records"); aircraftRepository.deleteAll(); userRepository.deleteAll(); diff --git a/src/test/java/com/example/AviaryService/services/alerts/AlertDigestFleetTest.java b/src/test/java/com/example/AviaryService/services/alerts/AlertDigestFleetTest.java index e53eeea..22bfd94 100644 --- a/src/test/java/com/example/AviaryService/services/alerts/AlertDigestFleetTest.java +++ b/src/test/java/com/example/AviaryService/services/alerts/AlertDigestFleetTest.java @@ -57,13 +57,32 @@ private void item(Aircraft a, String name, String dueDate, String dueHours) { statusSheetItemRepository.save(t); } + // Spec 013 research R3: most urgent first, days and hours compared by how + // far into the owner's lead time they are (defaults 30 days / 10 hrs). + @Test + void dueItemsAreSortedMostUrgentFirst() { + java.time.LocalDate today = java.time.LocalDate.now(java.time.ZoneOffset.UTC); + item(sr22, "Date 25 days", today.plusDays(25).toString(), null); // 25/30 = 0.83 + item(sr22, "Hours 8 left", null, "1408"); // 8/10 = 0.8 (TIS 1400) + item(sr22, "Date 5 days", today.plusDays(5).toString(), null); // 0.17 + item(sr22, "Overdue 3 days", today.minusDays(3).toString(), null); + item(sr22, "Overdue 12 days", today.minusDays(12).toString(), null); + item(sr22, "Fine", today.plusDays(300).toString(), null); + + AlertDigest d = digestService.buildDigest(owner, alertService.getOrCreatePrefs(owner), false); + + java.util.List order = d.sections().get(0).due().stream().map(AlertDigest.DueItem::name).toList(); + assertEquals(java.util.List.of("Overdue 12 days", "Overdue 3 days", "Date 5 days", "Hours 8 left", "Date 25 days"), order); + assertEquals(1, d.sections().get(0).onTrackCount()); + } + @Test void oneAircraftReadsLikeBefore() { item(sr22, "ELT Battery", "2020-01-01", null); AlertDigest d = digestService.buildDigest(owner, alertService.getOrCreatePrefs(owner), false); assertEquals("N482DM — 1 overdue", d.subject()); - assertTrue(d.body().startsWith("Maintenance status for N482DM (Cirrus SR22)"), d.body()); - assertTrue(d.body().contains("Aircraft hours: Hobbs Time")); + assertTrue(d.body().startsWith("N482DM (Cirrus SR22) — 1 overdue"), d.body()); + assertTrue(d.body().contains("Hours: Hobbs Time")); } @Test @@ -80,16 +99,16 @@ void twoAircraftShareOneDigestGroupedByTail() { assertEquals(2, d.overdueCount()); assertEquals("Your fleet — 2 overdue", d.subject()); String body = d.body(); - assertTrue(body.startsWith("Maintenance status for your fleet (3 aircraft)"), body); + assertTrue(body.startsWith("Your fleet — 2 overdue"), body); int sr22At = body.indexOf("\nN482DM"); int pa28At = body.indexOf("\nN731KR"); assertTrue(sr22At > 0 && pa28At > sr22At, body); - assertTrue(body.substring(pa28At).contains("OVERDUE Oil Change"), body); - assertTrue(body.substring(sr22At, pa28At).contains("ok Magneto"), body); - // An aircraft with nothing to report gets no section. - assertFalse(body.contains("N999XX"), body); - // What changed names the tail. - assertTrue(body.contains("N731KR: Oil Change"), body); + assertTrue(body.substring(pa28At).contains(" • Oil Change —"), body); + // Spec 013: an item that's fine isn't listed, it's only counted. + assertFalse(body.contains("Magneto"), body); + // An aircraft with nothing due gets no section, just the on-track line. + assertFalse(body.contains("\nN999XX ("), body); + assertTrue(body.contains("N999XX: all items on track."), body); assertTrue(idle.getId() > 0); } } diff --git a/src/test/java/com/example/AviaryService/services/alerts/AlertEmailRendererTest.java b/src/test/java/com/example/AviaryService/services/alerts/AlertEmailRendererTest.java new file mode 100644 index 0000000..d68fe8a --- /dev/null +++ b/src/test/java/com/example/AviaryService/services/alerts/AlertEmailRendererTest.java @@ -0,0 +1,204 @@ +package com.example.AviaryService.services.alerts; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +import org.junit.jupiter.api.Test; +import org.thymeleaf.spring6.SpringTemplateEngine; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; + +import com.example.AviaryService.services.alerts.AlertDigest.AircraftSection; +import com.example.AviaryService.services.alerts.AlertDigest.DueItem; + +// Spec 013: the alert email lists only what needs attention, in text and HTML. +// See specs/013-alert-email-design/contracts/alert-email.md. Also writes +// sample emails to build/alert-preview/ to look at in a browser. +class AlertEmailRendererTest { + + private static final Instant AS_OF = Instant.parse("2026-11-21T12:00:00Z"); + private static final EmailFooter FOOTER = new EmailFooter("Jane Doe", "N12SAS", + "https://aviary.example/alerts/unsubscribe?token=abc", "123 Main St, Miami FL"); + + private final AlertEmailRenderer renderer = new AlertEmailRenderer(engine()); + + private static SpringTemplateEngine engine() { + ClassLoaderTemplateResolver r = new ClassLoaderTemplateResolver(); + r.setPrefix("templates/"); + r.setSuffix(".html"); + r.setTemplateMode(TemplateMode.HTML); + r.setCharacterEncoding("UTF-8"); + SpringTemplateEngine e = new SpringTemplateEngine(); + e.setTemplateResolver(r); + return e; + } + + private static DueItem soon(String name, String time, boolean isNew) { + return new DueItem(name, AlertLevel.DUE_SOON, time, isNew, 0.3); + } + + private static DueItem over(String name, String time) { + return new DueItem(name, AlertLevel.OVERDUE, time, false, -0.4); + } + + private static AircraftSection section(String tail, String makeModel, List due, int itemCount) { + return new AircraftSection(tail, makeModel, "865.4", "679.8", due, itemCount - due.size(), itemCount); + } + + private static AlertDigest digest(boolean baseline, AircraftSection... sections) { + int o = 0, s = 0; + for (AircraftSection sec : sections) { + for (DueItem i : sec.due()) { + if (i.overdue()) o++; else s++; + } + } + return new AlertDigest(true, "subject", o, s, AS_OF, baseline, List.of(sections), LeadTimes.DEFAULT); + } + + private static AlertDigest reported() { + return digest(false, section("N12SAS", "Cirrus SR22T", List.of(soon("ELT Battery", "10 days left", true)), 39)); + } + + private static long bulletLines(String text) { + return text.lines().filter(l -> l.startsWith(" • ")).count(); + } + + // ---- text (US1) ---- + + @Test + void reportedExampleListsOnlyTheDueItem() { + String t = renderer.text(reported(), FOOTER); + + assertTrue(t.startsWith("N12SAS (Cirrus SR22T) — 1 due soon\nas of Nov 21, 2026 12:00 PM UTC\n"), t); + assertEquals(1, bulletLines(t), t); + assertTrue(t.contains("DUE SOON\n • ELT Battery — 10 days left [new]\n"), t); + assertTrue(t.contains("The other 38 items are on track. The full Status Sheet is attached (PDF)."), t); + assertTrue(t.contains("Hours: Hobbs Time 865.4 · Time in Service 679.8"), t); + assertFalse(Pattern.compile("\\bok\\b").matcher(t).find(), t); + assertFalse(t.contains("Full status"), t); + } + + @Test + void overdueComesBeforeDueSoon() { + String t = renderer.text(digest(false, section("N12SAS", "", + List.of(over("Annual", "12 days overdue"), soon("Oil", "4.5 hrs left", false)), 5)), null); + assertTrue(t.indexOf("OVERDUE\n • Annual") < t.indexOf("DUE SOON\n • Oil"), t); + assertTrue(t.startsWith("N12SAS — 1 overdue, 1 due soon\n"), t); + } + + @Test + void nothingDueSaysAllOnTrack() { + String t = renderer.text(digest(false, section("N12SAS", "", List.of(), 39)), FOOTER); + assertTrue(t.contains("All 39 items are on track. The full Status Sheet is attached (PDF)."), t); + assertTrue(t.startsWith("N12SAS — all on track\n"), t); + assertFalse(t.contains("OVERDUE") || t.contains("DUE SOON"), t); + assertEquals(0, bulletLines(t)); + } + + @Test + void onlyNewItemsAreMarked() { + String t = renderer.text(digest(false, section("N12SAS", "", + List.of(soon("A", "3 days left", true), soon("B", "5 days left", false)), 2)), null); + assertTrue(t.contains(" • A — 3 days left [new]\n"), t); + assertTrue(t.contains(" • B — 5 days left\n"), t); + } + + @Test + void baselineSaysAlertsAreOn() { + String t = renderer.text(digest(true, section("N12SAS", "", List.of(), 3)), null); + assertTrue(t.contains("Alerts are on. From now on you'll get an email when something comes due or changes."), t); + } + + @Test + void footerComesLast() { + String t = renderer.text(reported(), FOOTER); + int footerAt = t.indexOf("\n----\n"); + assertTrue(footerAt > t.indexOf("Hours:"), t); + assertTrue(t.substring(footerAt).contains( + "You're receiving this because Jane Doe added you to maintenance alerts for N12SAS."), t); + assertTrue(t.contains("Stop these emails: https://aviary.example/alerts/unsubscribe?token=abc"), t); + assertTrue(t.contains("123 Main St, Miami FL"), t); + assertFalse(renderer.text(reported(), null).contains("----")); + } + + @Test + void oneOtherItemIsSingular() { + String t = renderer.text(digest(false, section("N12SAS", "", List.of(soon("A", "3 days left", false)), 2)), null); + assertTrue(t.contains("The other item is on track."), t); + } + + // ---- HTML (US2) ---- + + @Test + void htmlUsesDashboardColorsAndEscapesNames() { + AlertDigest d = digest(false, section("N12SAS", "Cirrus SR22T", + List.of(over("x", "3 days overdue"), soon("ELT Battery", "10 days left", true)), 39)); + String h = renderer.html(d, FOOTER); + + assertTrue(h.contains("background:#FFF1D6; color:#8A5A00;"), h); + assertTrue(h.contains("background:#FDE4E9; color:#B3203F;"), h); + assertTrue(h.contains("<b>x</b>"), h); + assertFalse(h.contains("x"), h); + assertTrue(h.contains("href=\"https://aviary.example/alerts/unsubscribe?token=abc\""), h); + assertEquals(1, h.split(">New<", -1).length - 1, "one New tag"); + assertTrue(h.contains("The other 37 items are on track."), h); + assertFalse(h.contains(" many = new ArrayList<>(List.of( + over("Annual", "12 days overdue"), + soon("ELT Battery", "10 days left", true), + soon("Alternator # 1 Brushes", "8.2 hrs left", false))); + AlertDigest single = digest(false, section("N12SAS", "Cirrus SR22T", many, 39)); + Files.writeString(dir.resolve("single.html"), renderer.html(single, FOOTER)); + Files.writeString(dir.resolve("single.txt"), renderer.text(single, FOOTER)); + Files.writeString(dir.resolve("fleet.html"), renderer.html(fleet(), FOOTER)); + Files.writeString(dir.resolve("fleet.txt"), renderer.text(fleet(), FOOTER)); + assertTrue(Files.size(dir.resolve("single.html")) > 0); + } +} diff --git a/src/test/java/com/example/AviaryService/services/alerts/AlertScheduleTest.java b/src/test/java/com/example/AviaryService/services/alerts/AlertScheduleTest.java new file mode 100644 index 0000000..3f607b9 --- /dev/null +++ b/src/test/java/com/example/AviaryService/services/alerts/AlertScheduleTest.java @@ -0,0 +1,179 @@ +package com.example.AviaryService.services.alerts; + +import static com.example.AviaryService.services.alerts.AlertSchedule.Reason.DUE_SOON_REMINDER; +import static com.example.AviaryService.services.alerts.AlertSchedule.Reason.NEW_DUE_SOON; +import static com.example.AviaryService.services.alerts.AlertSchedule.Reason.NEW_OVERDUE; +import static com.example.AviaryService.services.alerts.AlertSchedule.Reason.OVERDUE_REMINDER; +import static com.example.AviaryService.services.alerts.AlertSchedule.Reason.STATUS_REPORT; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.time.LocalDate; +import java.util.EnumSet; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +import com.example.AviaryService.services.alerts.AlertSchedule.Frequency; +import com.example.AviaryService.services.alerts.AlertSchedule.Input; +import com.example.AviaryService.services.alerts.AlertSchedule.Reason; + +// Spec 014: every rule in contracts/schedule-rules.md, case by case (matrix A). +// Pure: no Spring, no clock, no database. +class AlertScheduleTest { + + private static final LocalDate TODAY = LocalDate.of(2026, 3, 10); + + // Builder with the defaults: Due soon every 7, Overdue every 3, Status Off. + private static final class In { + int dueSoonEvery = 7, overdueEvery = 3, statusEvery = Frequency.OFF; + boolean anyDueSoon, anyOverdue, newDueSoon, newOverdue; + LocalDate lastDueSoon, lastOverdue, lastStatus; + + Set decide() { + return AlertSchedule.decide(new Input(dueSoonEvery, overdueEvery, statusEvery, + anyDueSoon, anyOverdue, newDueSoon, newOverdue, TODAY, lastDueSoon, lastOverdue, lastStatus)); + } + } + + private static Set none() { + return EnumSet.noneOf(Reason.class); + } + + @Test + void a1_nothingDueSendsNothing() { + assertEquals(none(), new In().decide()); + } + + @Test + void a2_newDueSoonSends() { + In in = new In(); + in.anyDueSoon = true; + in.newDueSoon = true; + assertEquals(EnumSet.of(NEW_DUE_SOON), in.decide()); + } + + @Test + void a3_dueSoonSixDaysAfterLastEmailWaits() { + In in = new In(); + in.anyDueSoon = true; + in.lastDueSoon = TODAY.minusDays(6); + assertEquals(none(), in.decide()); + } + + @Test + void a4_dueSoonReminderAfterSevenDays() { + In in = new In(); + in.anyDueSoon = true; + in.lastDueSoon = TODAY.minusDays(7); + assertEquals(EnumSet.of(DUE_SOON_REMINDER), in.decide()); + } + + @Test + void a5_dueSoonOnceNeverRepeats() { + In in = new In(); + in.dueSoonEvery = Frequency.ONCE; + in.anyDueSoon = true; + in.lastDueSoon = TODAY.minusDays(30); + assertEquals(none(), in.decide()); + } + + @Test + void a6_dueSoonOffIgnoresNewItems() { + In in = new In(); + in.dueSoonEvery = Frequency.OFF; + in.anyDueSoon = true; + in.newDueSoon = true; + assertEquals(none(), in.decide()); + } + + @Test + void a7_overdueReminderAfterThreeDays() { + In in = new In(); + in.anyOverdue = true; + in.lastOverdue = TODAY.minusDays(3); + assertEquals(EnumSet.of(OVERDUE_REMINDER), in.decide()); + } + + @Test + void a8_overdueOffStillLetsDueSoonThrough() { + In in = new In(); + in.overdueEvery = Frequency.OFF; + in.anyOverdue = true; + in.lastOverdue = TODAY.minusDays(30); + in.anyDueSoon = true; + in.newDueSoon = true; + assertEquals(EnumSet.of(NEW_DUE_SOON), in.decide()); + } + + @Test + void a9_statusReportAfterSevenDays() { + In in = new In(); + in.statusEvery = 7; + in.lastStatus = TODAY.minusDays(7); + assertEquals(EnumSet.of(STATUS_REPORT), in.decide()); + in.lastStatus = TODAY.minusDays(6); + assertEquals(none(), in.decide()); + } + + @Test + void a10_statusReportNeverSentGoesOutNow() { + In in = new In(); + in.statusEvery = 7; + assertEquals(EnumSet.of(STATUS_REPORT), in.decide()); + } + + @Test + void a11_statusAndDueSoonSameDayAreBothReasons() { + In in = new In(); + in.statusEvery = 7; + in.lastStatus = TODAY.minusDays(7); + in.anyDueSoon = true; + in.lastDueSoon = TODAY.minusDays(7); + assertEquals(EnumSet.of(STATUS_REPORT, DUE_SOON_REMINDER), in.decide()); + } + + @Test + void a12_straightToOverdue() { + In in = new In(); + in.anyOverdue = true; + in.newOverdue = true; + assertEquals(EnumSet.of(NEW_OVERDUE), in.decide()); + } + + @Test + void overdueOnceSendsWhenNewButNeverReminds() { + In in = new In(); + in.overdueEvery = Frequency.ONCE; + in.anyOverdue = true; + in.newOverdue = true; + assertEquals(EnumSet.of(NEW_OVERDUE), in.decide()); + in.newOverdue = false; + in.lastOverdue = TODAY.minusDays(40); + assertEquals(none(), in.decide()); + } + + @Test + void reminderWithNoPreviousEmailGoesOut() { + In in = new In(); + in.anyOverdue = true; // overdue, never emailed about it + assertEquals(EnumSet.of(OVERDUE_REMINDER), in.decide()); + } + + @Test + void a13_frequencyParseAndLabel() { + assertEquals(Frequency.OFF, Frequency.parse("off", true)); + assertEquals(Frequency.OFF, Frequency.parse("Off", false)); + assertEquals(Frequency.ONCE, Frequency.parse("once", true)); + assertEquals(7, Frequency.parse("7", true)); + assertEquals(14, Frequency.parse(14, true)); + assertEquals(90, Frequency.parse(500, true)); // clamped + assertEquals(1, Frequency.parse(-5, true)); // clamped (only -1 via "once") + assertThrows(IllegalArgumentException.class, () -> Frequency.parse("once", false)); + assertThrows(IllegalArgumentException.class, () -> Frequency.parse("weekly", true)); + assertThrows(IllegalArgumentException.class, () -> Frequency.parse(null, true)); + assertEquals("off", Frequency.toJson(Frequency.OFF)); + assertEquals("once", Frequency.toJson(Frequency.ONCE)); + assertEquals(3, Frequency.toJson(3)); + } +} diff --git a/src/test/java/com/example/AviaryService/services/alerts/AlertServiceIntegrationTest.java b/src/test/java/com/example/AviaryService/services/alerts/AlertServiceIntegrationTest.java index dae51fc..0b4e04d 100644 --- a/src/test/java/com/example/AviaryService/services/alerts/AlertServiceIntegrationTest.java +++ b/src/test/java/com/example/AviaryService/services/alerts/AlertServiceIntegrationTest.java @@ -155,7 +155,7 @@ void digest_usesHobbsTimeLabels_andTailFallback() { assertTrue(d.body().contains("Hobbs Time")); assertTrue(d.body().contains("Time in Service")); assertFalse(d.body().contains("Block Time")); - assertTrue(d.body().contains("Maintenance status for your aircraft")); + assertTrue(d.body().startsWith("Your aircraft"), d.body()); } @@ -174,7 +174,7 @@ void digest_countsOverdueAndDueSoon() { assertEquals(1, d.overdueCount()); assertEquals(1, d.dueSoonCount()); assertTrue(d.subject().contains("N12345")); - assertTrue(d.body().contains("Annual")); + assertTrue(d.body().contains(" • Annual —"), d.body()); } @Test @@ -199,7 +199,7 @@ void baselineDigest_alwaysSends_evenWithNothingDue() { AlertPreference prefs = alertService.getOrCreatePrefs(user); AlertDigest d = digestService.buildDigest(user, prefs, true); assertTrue(d.shouldSend()); - assertTrue(d.body().contains("Alerts are now ON")); + assertTrue(d.body().contains("Alerts are on."), d.body()); } // -- enable transition + sweep -- diff --git a/src/test/java/com/example/AviaryService/services/alerts/AlertSimulationTest.java b/src/test/java/com/example/AviaryService/services/alerts/AlertSimulationTest.java new file mode 100644 index 0000000..6438936 --- /dev/null +++ b/src/test/java/com/example/AviaryService/services/alerts/AlertSimulationTest.java @@ -0,0 +1,275 @@ +package com.example.AviaryService.services.alerts; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.when; + +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Primary; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.bean.override.mockito.MockitoBean; + +import com.example.AviaryService.entity.Aircraft; +import com.example.AviaryService.entity.AlertPreference; +import com.example.AviaryService.entity.AlertRecipient; +import com.example.AviaryService.entity.StatusSheetItem; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.AlertPreferenceRepository; +import com.example.AviaryService.repositories.AlertRecipientRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.repositories.AircraftRepository; +import com.example.AviaryService.services.dashboard.PdfExportService; +import com.example.AviaryService.services.messaging.EmailSender; +import com.example.AviaryService.services.messaging.SmsSender; +import com.example.AviaryService.support.MutableClock; +import com.example.AviaryService.support.TestFleet; + +// Spec 014 matrix B: run the REAL scheduler once a day for N simulated days +// (a test clock moves forward) and record which days each owner got an email. +// Every case prints " emails on days: [...]" so a failure shows the day. +// See specs/014-alert-reminder-frequency/contracts/schedule-rules.md. +@SpringBootTest +@ActiveProfiles("test") +@Import(AlertSimulationTest.TestClock.class) +class AlertSimulationTest { + + @TestConfiguration + static class TestClock { + @Bean + @Primary + MutableClock mutableClock() { + return new MutableClock(Instant.parse("2026-01-05T00:00:00Z")); + } + } + + static final ZoneId NY = ZoneId.of("America/New_York"); + static final LocalDate DAY0 = LocalDate.of(2026, 1, 5); // a Monday, no DST change for 60+ days + + @Autowired MutableClock clock; + @Autowired AlertScheduler scheduler; + @Autowired UserRepository userRepository; + @Autowired AircraftRepository aircraftRepository; + @Autowired StatusSheetItemRepository itemRepository; + @Autowired AlertPreferenceRepository preferenceRepository; + @Autowired AlertRecipientRepository recipientRepository; + + @MockitoBean EmailSender emailSender; + @MockitoBean SmsSender smsSender; + @MockitoBean PdfExportService pdfExportService; + + // destination -> (day, subject) of every email handed to the sender + private final List sends = new ArrayList<>(); + + @BeforeEach + void setUp() { + sends.clear(); + when(emailSender.isConfigured()).thenReturn(true); + when(pdfExportService.generateFleetPdf(any(), any(), any())).thenReturn(new byte[] {1}); + doAnswer(inv -> { + long day = ChronoUnit.DAYS.between(DAY0, LocalDate.ofInstant(clock.instant(), NY)); + sends.add(new String[] {inv.getArgument(0), String.valueOf(day), inv.getArgument(1)}); + return null; + }).when(emailSender).sendPdf(anyString(), anyString(), anyString(), any(), any(), anyString()); + } + + // ---- fixtures ---- + + private final class Owner { + final User user; + final Aircraft plane; + final AlertPreference prefs; + final String inbox; + + Owner(String name) { + User u = new User(); + u.setUsername("sim-" + name + "-" + System.nanoTime()); + u.setPassword("x"); + user = userRepository.save(u); + plane = TestFleet.addAircraft(aircraftRepository, userRepository, user, "N" + name.toUpperCase(), "Pat", 100, 100); + AlertPreference p = new AlertPreference(user); + p.setAlertsEnabled(true); // set directly: no baseline email, so day 0 is the first sweep + p.setTimeZone(NY.getId()); + prefs = preferenceRepository.save(p); + inbox = user.getUsername() + "@example.com"; + AlertRecipient r = new AlertRecipient(user, AlertRecipient.Channel.EMAIL, inbox, null, "tok-" + name); + r.setStatusEnum(AlertRecipient.Status.ACCEPTED); + recipientRepository.save(r); + } + + StatusSheetItem item(String name, int dueOnDay) { + StatusSheetItem t = new StatusSheetItem(); + t.setUser(user); + t.setAircraft(plane); + t.setItem(name); + t.setIsTitle(false); + t.setStatusSheetOrder(0); + t.setDueDateDate(DAY0.plusDays(dueOnDay).toString()); + return itemRepository.save(t); + } + + Owner every(int dueSoon, int overdue, int status) { + AlertPreference p = preferenceRepository.findById(prefs.getId()).orElseThrow(); + p.setDueSoonEveryDays(dueSoon); + p.setOverdueEveryDays(overdue); + p.setStatusEveryDays(status); + preferenceRepository.save(p); + return this; + } + + List days() { + return sends.stream().filter(s -> s[0].equals(inbox)).map(s -> Integer.parseInt(s[1])).toList(); + } + + List subjects() { + return sends.stream().filter(s -> s[0].equals(inbox)).map(s -> s[2]).toList(); + } + } + + // One scheduler tick per day at the owner's 7:05 (the scheduler runs at :05). + // `onDay` runs before that day's tick (e.g. to fix an item). + private void run(int days, java.util.function.IntConsumer onDay, Duration driftPerDay) { + for (int d = 0; d < days; d++) { + if (onDay != null) onDay.accept(d); + ZonedDateTime at = ZonedDateTime.of(DAY0.plusDays(d), LocalTime.of(7, 5), NY).minus(driftPerDay.multipliedBy(d)); + clock.set(at.toInstant()); + scheduler.tick(); + } + } + + private void run(int days) { + run(days, null, Duration.ZERO); + } + + private static void print(String name, Owner o) { + System.out.println(name + " emails on days: " + o.days()); + } + + // ---- matrix B ---- + + @Test + void b1_defaultsDueSoonThenOverdue() { + Owner o = new Owner("b1"); + o.item("ELT Battery", 25); // lead 30 -> due soon from day 0; overdue from day 26 + run(40); + print("B1", o); + assertEquals(List.of(0, 7, 14, 21, 26, 29, 32, 35, 38), o.days()); + } + + @Test + void b2_fixedItemStopsReminders() { + Owner o = new Owner("b2"); + StatusSheetItem t = o.item("ELT Battery", 25); + run(20, d -> { + if (d == 10) { + t.setDueDateDate(DAY0.plusDays(400).toString()); + itemRepository.save(t); + } + }, Duration.ZERO); + print("B2", o); + assertEquals(List.of(0, 7), o.days()); + } + + @Test + void b3_nothingDueSendsNothing() { + Owner o = new Owner("b3"); + o.item("Annual", 300); + run(60); + print("B3", o); + assertEquals(List.of(), o.days()); + } + + @Test + void b4_neverMoreThanOneEmailADay() { + Owner o = new Owner("b4").every(1, 1, 1); + o.item("Overdue thing", -5); + o.item("Due soon thing", 20); + run(10); + print("B4", o); + assertEquals(List.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), o.days()); + } + + @Test + void b5_weeklyStatusReport() { + Owner o = new Owner("b5").every(7, 3, 7); + o.item("Annual", 300); + run(21); + print("B5", o); + assertEquals(List.of(0, 7, 14), o.days()); + assertTrue(o.subjects().stream().allMatch(s -> s.equals("NB5 — weekly status: all on track")), o.subjects().toString()); + } + + @Test + void b6_dueSoonOffWaitsForOverdue() { + Owner o = new Owner("b6").every(AlertSchedule.Frequency.OFF, 3, AlertSchedule.Frequency.OFF); + o.item("Annual", 5); // due soon days 0-5, overdue from day 6 + run(13); + print("B6", o); + assertEquals(List.of(6, 9, 12), o.days()); + } + + @Test + void b7_overdueOnce() { + Owner o = new Owner("b7").every(7, AlertSchedule.Frequency.ONCE, AlertSchedule.Frequency.OFF); + o.item("Annual", -1); + run(10); + print("B7", o); + assertEquals(List.of(0), o.days()); + } + + @Test + void b8_alertsOffSendsNothing() { + Owner o = new Owner("b8"); + AlertPreference p = preferenceRepository.findById(o.prefs.getId()).orElseThrow(); + p.setAlertsEnabled(false); + preferenceRepository.save(p); + o.item("Annual", -1); + run(10); + print("B8", o); + assertEquals(List.of(), o.days()); + } + + // FR-006: an existing owner's "re-nudge every 5 days" carries over. + @Test + void b9_existingRenudgeCarriesOver() { + Owner o = new Owner("b9"); + AlertPreference p = preferenceRepository.findById(o.prefs.getId()).orElseThrow(); + p.setOverdueRenudgeDays(5); + preferenceRepository.save(p); + assertEquals(5, preferenceRepository.findById(o.prefs.getId()).orElseThrow().getOverdueEveryDays()); + o.item("Annual", -1); + run(16); + print("B9", o); + assertEquals(List.of(0, 5, 10, 15), o.days()); + } + + // R4: the old rolling 24 hours dropped an email whenever today's check ran + // a little earlier than yesterday's. One per calendar day can't drift. + @Test + void b10_dailyEmailsSurviveAnEarlierCheckTime() { + Owner o = new Owner("b10").every(1, 1, 1); + o.item("Annual", 300); + run(10, null, Duration.ofSeconds(30)); + print("B10", o); + assertEquals(List.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), o.days()); + } +} diff --git a/src/test/java/com/example/AviaryService/services/alerts/AlertTimeZoneTest.java b/src/test/java/com/example/AviaryService/services/alerts/AlertTimeZoneTest.java new file mode 100644 index 0000000..3eb537c --- /dev/null +++ b/src/test/java/com/example/AviaryService/services/alerts/AlertTimeZoneTest.java @@ -0,0 +1,89 @@ +package com.example.AviaryService.services.alerts; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.time.Instant; +import java.time.LocalDate; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.ActiveProfiles; + +import com.example.AviaryService.entity.AlertPreference; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.AircraftRepository; +import com.example.AviaryService.repositories.AlertPreferenceRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.support.MutableClock; +import com.example.AviaryService.support.TestFleet; + +// Spec 014 matrix C: "Check daily at 7:00" is the owner's 7:00, not the +// server's. We tick the real scheduler at chosen UTC moments and look at +// whether (and for which local date) the owner was checked. +@SpringBootTest +@ActiveProfiles("test") +@Import(AlertSimulationTest.TestClock.class) +class AlertTimeZoneTest { + + @Autowired MutableClock clock; + @Autowired AlertScheduler scheduler; + @Autowired UserRepository userRepository; + @Autowired AircraftRepository aircraftRepository; + @Autowired AlertPreferenceRepository preferenceRepository; + + private AlertPreference owner(String zone) { + User u = new User(); + u.setUsername("tz-" + System.nanoTime()); + u.setPassword("x"); + userRepository.save(u); + TestFleet.addAircraft(aircraftRepository, userRepository, u, "N1", "Pat", 0, 0); + AlertPreference p = new AlertPreference(u); + p.setAlertsEnabled(true); + p.setCheckHour(7); + p.setTimeZone(zone); + return preferenceRepository.save(p); + } + + private LocalDate checkedOn(AlertPreference p) { + return preferenceRepository.findById(p.getId()).orElseThrow().getLastCheckedOn(); + } + + private void tickAt(String utc) { + clock.set(Instant.parse(utc)); + scheduler.tick(); + } + + @Test + void c1_newYorkSevenIsNoonUtcInWinterAndElevenInSummer() { + AlertPreference winter = owner("America/New_York"); + tickAt("2026-01-15T07:05:00Z"); // 2:05 in New York + assertNull(checkedOn(winter)); + tickAt("2026-01-15T12:05:00Z"); // 7:05 EST + assertEquals(LocalDate.of(2026, 1, 15), checkedOn(winter)); + + AlertPreference summer = owner("America/New_York"); + tickAt("2026-07-15T12:05:00Z"); // 8:05 EDT: not their hour + assertNull(checkedOn(summer)); + tickAt("2026-07-16T11:05:00Z"); // 7:05 EDT + assertEquals(LocalDate.of(2026, 7, 16), checkedOn(summer)); + } + + @Test + void c2_tokyoSevenIsTheDayBeforeInUtc() { + AlertPreference tokyo = owner("Asia/Tokyo"); + tickAt("2026-01-14T22:05:00Z"); // 7:05 on Jan 15 in Tokyo + assertEquals(LocalDate.of(2026, 1, 15), checkedOn(tokyo)); + } + + @Test + void c3_unknownZoneUsesNewYork() { + AlertPreference none = owner(null); + tickAt("2026-02-02T07:05:00Z"); + assertNull(checkedOn(none)); + tickAt("2026-02-02T12:05:00Z"); + assertEquals(LocalDate.of(2026, 2, 2), checkedOn(none)); + } +} diff --git a/src/test/java/com/example/AviaryService/services/alerts/NotificationServiceEmailTest.java b/src/test/java/com/example/AviaryService/services/alerts/NotificationServiceEmailTest.java new file mode 100644 index 0000000..0fc59c3 --- /dev/null +++ b/src/test/java/com/example/AviaryService/services/alerts/NotificationServiceEmailTest.java @@ -0,0 +1,97 @@ +package com.example.AviaryService.services.alerts; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.thymeleaf.spring6.SpringTemplateEngine; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; + +import com.example.AviaryService.entity.Aircraft; +import com.example.AviaryService.entity.AlertRecipient; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.AircraftRepository; +import com.example.AviaryService.repositories.AlertRecipientRepository; +import com.example.AviaryService.repositories.AlertSendLogRepository; +import com.example.AviaryService.services.dashboard.PdfExportService; +import com.example.AviaryService.services.messaging.EmailSender; +import com.example.AviaryService.services.messaging.SmsSender; + +// Spec 013 US2: every alert email carries a text and an HTML version, each +// with that recipient's own stop link, and the PDF uses the owner's lead times. +class NotificationServiceEmailTest { + + @Test + void sendsTextAndHtmlWithEachRecipientsOwnStopLink() { + EmailSender email = mock(EmailSender.class); + when(email.isConfigured()).thenReturn(true); + AlertRecipientRepository recipients = mock(AlertRecipientRepository.class); + AlertSendLogRepository sendLog = mock(AlertSendLogRepository.class); + when(sendLog.existsByRecipientIdAndSentAtAfter(anyLong(), any())).thenReturn(false); + PdfExportService pdf = mock(PdfExportService.class); + when(pdf.generateFleetPdf(any(), any(), any())).thenReturn(new byte[] {1}); + AircraftRepository aircraft = mock(AircraftRepository.class); + + User owner = new User(); + Aircraft a = new Aircraft(owner); + a.setTailNumber("N12SAS"); + a.setOperatorName("Jane Doe"); + when(aircraft.findByUserOrderByIdAsc(owner)).thenReturn(List.of(a)); + when(recipients.findByUserAndStatus(owner, AlertRecipient.Status.ACCEPTED.name())) + .thenReturn(List.of(recipient(1, "a@example.com", "tokA"), recipient(2, "b@example.com", "tokB"))); + + ClassLoaderTemplateResolver r = new ClassLoaderTemplateResolver(); + r.setPrefix("templates/"); + r.setSuffix(".html"); + r.setTemplateMode(TemplateMode.HTML); + SpringTemplateEngine engine = new SpringTemplateEngine(); + engine.setTemplateResolver(r); + + NotificationService service = new NotificationService(email, mock(SmsSender.class), recipients, sendLog, + pdf, aircraft, new AlertEmailRenderer(engine), java.time.Clock.systemUTC(), "https://aviary.example", "123 Main St"); + + LeadTimes lead = new LeadTimes(7, 5); + AlertDigest digest = new AlertDigest(true, "N12SAS — 1 due soon", 0, 1, Instant.now(), false, + List.of(new AlertDigest.AircraftSection("N12SAS", "", "1.0", "2.0", + List.of(new AlertDigest.DueItem("ELT Battery", AlertLevel.DUE_SOON, "5 days left", false, 0.7)), 3, 4)), + lead); + + assertEquals(2, service.sendDigest(owner, digest)); + + ArgumentCaptor text = ArgumentCaptor.forClass(String.class); + ArgumentCaptor html = ArgumentCaptor.forClass(String.class); + verify(email, times(2)).sendPdf(anyString(), eq("N12SAS — 1 due soon"), text.capture(), html.capture(), + any(), anyString()); + assertTrue(text.getAllValues().get(0).contains("token=tokA")); + assertTrue(text.getAllValues().get(1).contains("token=tokB")); + assertNotNull(html.getAllValues().get(0)); + assertTrue(html.getAllValues().get(0).contains("N12SAS") && html.getAllValues().get(0).contains("token=tokA")); + assertTrue(html.getAllValues().get(1).contains("token=tokB")); + // One PDF for all recipients, built with the owner's lead times. + verify(pdf, times(1)).generateFleetPdf(any(), any(), eq(lead)); + } + + private static AlertRecipient recipient(long id, String dest, String token) { + AlertRecipient r = new AlertRecipient(); + r.setId(id); + r.setChannelEnum(AlertRecipient.Channel.EMAIL); + r.setStatusEnum(AlertRecipient.Status.ACCEPTED); + r.setDestination(dest); + r.setConfirmToken(token); + return r; + } +} diff --git a/src/test/java/com/example/AviaryService/services/dashboard/PdfExportColorsTest.java b/src/test/java/com/example/AviaryService/services/dashboard/PdfExportColorsTest.java new file mode 100644 index 0000000..c67ec09 --- /dev/null +++ b/src/test/java/com/example/AviaryService/services/dashboard/PdfExportColorsTest.java @@ -0,0 +1,90 @@ +package com.example.AviaryService.services.dashboard; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.LocalDate; + +import org.apache.pdfbox.Loader; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.text.PDFTextStripper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.transaction.annotation.Transactional; + +import com.example.AviaryService.entity.Aircraft; +import com.example.AviaryService.entity.StatusSheetItem; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.AircraftRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.services.alerts.LeadTimes; +import com.example.AviaryService.support.TestFleet; + +// Spec 013 US3: the PDF marks due-soon items (not only overdue ones), using +// the owner's lead times. See contracts/pdf-time-left.md. +@SpringBootTest +@ActiveProfiles("test") +@Transactional +class PdfExportColorsTest { + + @Autowired PdfExportService pdfExportService; + @Autowired UserRepository userRepository; + @Autowired AircraftRepository aircraftRepository; + @Autowired StatusSheetItemRepository statusSheetItemRepository; + + private static final LocalDate TODAY = LocalDate.of(2026, 11, 21); + private Aircraft plane; + + @BeforeEach + void setUp() { + User u = new User(); + u.setUsername("pdf-colors-" + System.nanoTime()); + u.setPassword("x"); + userRepository.save(u); + plane = TestFleet.addAircraft(aircraftRepository, userRepository, u, "N12SAS", "", 900, 680); + item(u, "Annual", TODAY.minusDays(3).toString(), null, 0); // overdue + item(u, "ELT Battery", TODAY.plusDays(10).toString(), null, 1); // due soon (30-day lead) + item(u, "Fire Extinguisher", TODAY.plusDays(286).toString(), null, 2); // fine + item(u, "Alternator Brushes", null, "688", 3); // 8 hrs left: due soon (10-hr lead) + } + + private void item(User u, String name, String dueDate, String dueHours, int order) { + StatusSheetItem t = new StatusSheetItem(); + t.setUser(u); + t.setAircraft(plane); + t.setItem(name); + t.setIsTitle(false); + t.setStatusSheetOrder(order); + t.setDueDateDate(dueDate); + t.setDueDateHours(dueHours); + statusSheetItemRepository.save(t); + } + + private String text(LeadTimes lead) throws Exception { + byte[] pdf = pdfExportService.generateDashboardPdf(plane, TODAY, lead); + try (PDDocument doc = Loader.loadPDF(pdf)) { + return new PDFTextStripper().getText(doc); + } + } + + private static int count(String haystack, String needle) { + return haystack.split(java.util.regex.Pattern.quote(needle), -1).length - 1; + } + + @Test + void defaultLeadTimesMarkOverdueAndDueSoon() throws Exception { + String t = text(LeadTimes.DEFAULT); + assertEquals(1, count(t, "OVERDUE"), t); + assertEquals(2, count(t, "DUE SOON"), t); + } + + @Test + void shorterDayLeadTimeLeavesOnlyTheHoursItemDueSoon() throws Exception { + String t = text(new LeadTimes(7, 10)); + assertEquals(1, count(t, "OVERDUE"), t); + assertEquals(1, count(t, "DUE SOON"), t); + } +} diff --git a/src/test/java/com/example/AviaryService/support/MutableClock.java b/src/test/java/com/example/AviaryService/support/MutableClock.java new file mode 100644 index 0000000..bdd6032 --- /dev/null +++ b/src/test/java/com/example/AviaryService/support/MutableClock.java @@ -0,0 +1,53 @@ +package com.example.AviaryService.support; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; + +// A clock tests can move: set(...) jumps to a moment, advance(...) moves +// forward. Lets alert tests run the real scheduler over simulated days. +public class MutableClock extends Clock { + + private volatile Instant now; + private final ZoneId zone; + + public MutableClock(Instant start) { + this(start, ZoneOffset.UTC); + } + + private MutableClock(Instant start, ZoneId zone) { + this.now = start; + this.zone = zone; + } + + public void set(Instant instant) { + this.now = instant; + } + + public void advance(Duration d) { + this.now = now.plus(d); + } + + @Override + public Instant instant() { + return now; + } + + @Override + public ZoneId getZone() { + return zone; + } + + // Shares this clock's time; only the zone differs. + @Override + public Clock withZone(ZoneId z) { + MutableClock parent = this; + return new Clock() { + @Override public Instant instant() { return parent.instant(); } + @Override public ZoneId getZone() { return z; } + @Override public Clock withZone(ZoneId other) { return parent.withZone(other); } + }; + } +}