Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions docs/migrations/2026-11-21_alert_schedules.sql
Original file line number Diff line number Diff line change
@@ -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.
66 changes: 47 additions & 19 deletions docs/specs/ALERTS_SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -108,29 +122,42 @@ 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.

## 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).
Expand All @@ -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 |
Expand Down
Original file line number Diff line number Diff line change
@@ -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());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
17 changes: 17 additions & 0 deletions src/main/java/com/example/AviaryService/config/ClockConfig.java
Original file line number Diff line number Diff line change
@@ -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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -70,15 +71,36 @@ public ResponseEntity<Map<String, Object>> 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<Map<String, Object>> updateTimeZone(@RequestBody Map<String, Object> 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."));
}
}

Expand Down Expand Up @@ -163,7 +185,11 @@ private Map<String, Object> 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<String> missing = new ArrayList<>();
Expand Down Expand Up @@ -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()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ public ResponseEntity<byte[]> 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);
Expand Down Expand Up @@ -278,7 +278,7 @@ public ResponseEntity<Map<String, String>> 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(
Expand Down Expand Up @@ -934,4 +934,11 @@ public ResponseEntity<Map<String, Object>> deleteFlightLog(@PathVariable Long id
// after this fix ships.


}

// 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));
}
}
Loading
Loading