diff --git a/.gitignore b/.gitignore index 13b2f48..14f14f1 100644 --- a/.gitignore +++ b/.gitignore @@ -50,3 +50,9 @@ sendgrid.env # Local Gradle daemon JDK pin (machine-specific path) gradle.properties + +# Learning docs + +COOKIES.txt +HTTP_FUNDAMENTALS.txt +ROUTING.txt diff --git a/README.md b/README.md index b5152c7..af1d997 100644 --- a/README.md +++ b/README.md @@ -97,4 +97,4 @@ The app is a small, conventional Spring MVC project under `src/main/java/com/exa - **`config/`** — `SecurityConfig` (login/logout, BCrypt, per-route access) and `DataSeeder` (the H2 demo data). - **`resources/templates/`** + **`resources/static/`** — Thymeleaf views and the dashboard's CSS/JS. -Deeper design docs live in **[docs/](docs/)** — see `ARCHITECTURE.md`, `BACKEND.md`, `FRONTEND.md`, `DATABASE.md`, and `BUILD_AND_DEPLOY.md`. A **Share/Export** feature (print / PDF / email / text) is specced in `docs/SHARE_EXPORT_SPEC.md` but not yet built. +Deeper design docs live in **[docs/](docs/)** — see `ARCHITECTURE.md`, `BACKEND.md`, `FRONTEND.md`, `DATABASE.md`, and `BUILD_AND_DEPLOY.md`. A **Share/Export** feature (print / PDF / email / text) is specced in `docs/specs/SHARE_EXPORT_SPEC.md` but not yet built. diff --git a/build.gradle b/build.gradle index bdacbc6..20d0284 100644 --- a/build.gradle +++ b/build.gradle @@ -40,7 +40,10 @@ dependencies { implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.2' implementation 'com.h2database:h2:2.2.224' implementation 'org.apache.poi:poi:5.4.1' - // Server-side PDF rendering for Download PDF (docs/SHARE_EXPORT_SPEC.md) -- + implementation 'org.springframework.ai:spring-ai-starter-mcp-server-webmvc' + // Source: https://mvnrepository.com/artifact/software.amazon.awssdk/ses + implementation("software.amazon.awssdk:sesv2:2.56.0") + // Server-side PDF rendering for Download PDF (docs/specs/SHARE_EXPORT_SPEC.md) -- // real vector text/tables instead of the earlier html2canvas screenshot // approach, which produced huge slow-to-scroll rasterized pages. implementation 'io.github.openhtmltopdf:openhtmltopdf-pdfbox:1.1.85' @@ -52,14 +55,18 @@ dependencies { testImplementation 'org.springframework.security:spring-security-test' testImplementation 'org.mockito:mockito-core:5.11.0' - implementation 'com.sendgrid:sendgrid-java:4.10.3' - // Playwright drives a real Chromium for full-stack browser tests. // First run downloads ~150MB of browser binaries to ~/.cache/ms-playwright/. browserTestImplementation 'com.microsoft.playwright:playwright:1.47.0' } +dependencyManagement { + imports { + mavenBom "org.springframework.ai:spring-ai-bom:1.1.8" + } +} + test { useJUnitPlatform() testLogging { diff --git a/docs/ALERTS_SPEC.md b/docs/ALERTS_SPEC.md deleted file mode 100644 index ace95df..0000000 --- a/docs/ALERTS_SPEC.md +++ /dev/null @@ -1,158 +0,0 @@ -# Maintenance Alerts Spec - -Status: **Backend + email built (senders disabled until keys added); SMS = model + logging sender only; UI = functional** · Last updated: 2026-09-08 - -Alerts the aircraft owner (and anyone they add — a maintenance shop, a partner) -when a Service Timeline item is near or past its due date. Email via SendGrid, -SMS via Twilio (SMS send path stubbed until A2P 10DLC clears). - -Separate from the AeroAPI flight-sync `Subscription` — that means "poll AeroAPI -for this tail". This is a different concern with its own entities. - -## How it fires - -- **One check per user per day**, at an hour the user picks (`checkHour`, same - pattern as `Subscription.preferredCheckHour`). A `@Scheduled` job ticks - hourly; a user is evaluated only on the tick where `checkHour` matches and - `alertsEnabled` is true. -- On a tick it looks at the user's whole Service Timeline and classifies each - non-title item into a **level**: `OK` → `DUE_SOON` → `OVERDUE`. - - `OVERDUE` — `daysLeft < 0` or `hoursLeft < 0` - - `DUE_SOON` — `0 ≤ daysLeft ≤ leadTimeDays` or `0 ≤ hoursLeft ≤ leadTimeHours` - - else `OK` -- Each item stores the level it **last alerted at** (`ServiceTimeline.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 (weekly re-nudge; user-configurable). -- When an item improves (maintenance completed, due date pushed out), its - `alertLevel` is quietly reset down — no "good news" email. -- No per-edit sending. No background safety logic beyond the daily sweep. - -## Turning alerts on - -Two-step dialog (frontend), backed by `PUT /alerts/preferences {enabled:true}`: - -1. **"What's still missing"** — the client shows unfinished setup (no - maintenance rows / aircraft hours not set / schedule not saved). Skip to - step 2 if nothing's missing. Advisory only; the server does not block. -2. **Recipient list with statuses** → "Turn on alerts". - -First time `enabled` flips false→true: the server marks every current item's -`alertLevel` to its present level (so you don't get a flood) and sends **one -baseline digest** ("alerts are on, here's where everything stands"). - -## Recipients (adding people) - -`AlertRecipient` — belongs to a user. One user → many recipients. - -| field | notes | -|---|---| -| `channel` | `EMAIL` \| `SMS` | -| `destination` | email address or E.164 phone | -| `label` | optional free text ("Jane's shop") | -| `status` | `PENDING` \| `ACCEPTED` \| `DECLINED` \| `EXPIRED` | -| `confirmToken` | opaque URL-safe token, unique | -| `createdAt`, `confirmedAt`, `reminderSentAt` | timestamps | - -Flow: **add → PENDING** → confirmation sent (email: a confirm link; SMS: "reply -YES", stubbed) → recipient clicks **confirm** (`ACCEPTED`) or **decline** -(`DECLINED`). Only `ACCEPTED` recipients receive anything. - -- Confirm link (and PENDING row) **expires after 14 days**; a reminder goes out - at **day 7** (`reminderSentAt`). After expiry the row shows `EXPIRED` and the - owner presses Resend to mint a fresh token. -- **Consent basis:** user A cannot consent for user B. Email confirmation - protects sender reputation (CAN-SPAM); SMS needs double opt-in + STOP/HELP - (TCPA) — handled by a Twilio Messaging Service + inbound webhook when SMS is - finished. -- The owner's own alerts: the owner is *not* auto-added as a recipient. They add - their own email like anyone else (keeps one code path, and makes the "who gets - this" list complete and honest). - -## Rate limit - -Manual ("Send alert now") and the daily digest **share one budget**: - -- **Email:** max 1 per recipient per 24h -- **SMS:** max 1 per recipient per 72h - -On cooldown the send is skipped for that recipient (logged, not an error) and -the button greys out client-side with "Available again in Xh". - -## Digest content - -- **Subject:** `N12345 — 1 overdue, 2 due soon` -- **Body (email):** "what changed" section → full status table, worst first → - aircraft hours → generated-at timestamp → *View Dashboard* button → the - dashboard **PDF attached** (`PdfExportService.generateDashboardPdf`) → a - manage/unsubscribe link. Non-owner recipients also see tail number, make/model, - and who added them. -- **SMS:** one short line + a link. No attachment. -- Every email includes an unsubscribe link (`/alerts/unsubscribe?token=…`) and - the configured postal address (`aviary.alerts.postal-address`), for CAN-SPAM. - -## Thresholds - -One per-user default in `AlertPreference`: `leadTimeDays` (30), `leadTimeHours` -(10). Per-item overrides are a later addition. - -## Entities - -- **`AlertPreference`** — `@OneToOne` User. `alertsEnabled` (false), - `checkHour` (7), `leadTimeDays` (30), `leadTimeHours` (10), - `overdueRenudgeDays` (7), `lastCheckedOn` (LocalDate, null), - `baselineSentAt` (Instant, null). -- **`AlertRecipient`** — as table above. -- **`ServiceTimeline`** gains `alertLevel` (String, nullable) and - `alertLastFiredAt` (Instant, nullable). `ddl-auto=update` adds the columns. -- **`AlertSendLog`** — `recipientId`, `channel`, `sentAt`. Backs the rate limit - and the activity trail. Pruned after 30 days by the daily job. - -## Endpoints - -Authenticated (owner), under `/alerts`: - -| method | path | body / params | purpose | -|---|---|---|---| -| GET | `/alerts/preferences` | — | current prefs + readiness flags | -| PUT | `/alerts/preferences` | `enabled,checkHour,leadTimeDays,leadTimeHours,overdueRenudgeDays` | update; false→true triggers baseline | -| GET | `/alerts/recipients` | — | list with statuses | -| POST | `/alerts/recipients` | `channel,destination,label` | add → PENDING, sends confirmation | -| DELETE | `/alerts/recipients/{id}` | — | remove | -| POST | `/alerts/recipients/{id}/resend` | — | new token + resend confirmation | -| POST | `/alerts/send-now` | — | evaluate + send current status to ACCEPTED recipients (respects rate limit) | - -Public (no auth — `permitAll` in `SecurityConfig`), token-guarded: - -| method | path | purpose | -|---|---|---| -| GET | `/alerts/confirm?token=…` | PENDING → ACCEPTED | -| GET | `/alerts/decline?token=…` | PENDING/ACCEPTED → DECLINED | -| GET | `/alerts/unsubscribe?token=…` | ACCEPTED → DECLINED (same as decline; distinct URL for email footers) | - -## Config (env vars; app-level, not per-user) - -``` -SENDGRID_API_KEY # sendgrid.env / Heroku config var -AVIARY_SENDGRID_FROM # verified sender address -AVIARY_SENDGRID_FROM_NAME # default "Aviary Service" -AVIARY_ALERTS_BASE_URL # e.g. https://aviarist-xxxx.herokuapp.com (for links) -AVIARY_ALERTS_POSTAL_ADDRESS# CAN-SPAM footer -TWILIO_ACCOUNT_SID # SMS — later -TWILIO_AUTH_TOKEN # SMS — later -TWILIO_MESSAGING_SERVICE_SID# SMS — later -``` - -When `SENDGRID_API_KEY` / `AVIARY_SENDGRID_FROM` are blank the email sender -logs and no-ops instead of throwing. SMS sender currently always logs-and-no-ops -(`LoggingSmsSender`); `TwilioSmsSender` is a drop-in for later. - -## Not built yet - -- Real Twilio SMS send + inbound STOP webhook + A2P 10DLC. -- Per-item threshold overrides. -- HTML (vs plain-text) email body — currently plain text + PDF attachment. -- The day-7 reminder is sent by the daily job; there is no separate finer-grained - scheduler. diff --git a/docs/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md similarity index 100% rename from docs/ARCHITECTURE.md rename to docs/architecture/ARCHITECTURE.md diff --git a/docs/BACKEND.md b/docs/architecture/BACKEND.md similarity index 100% rename from docs/BACKEND.md rename to docs/architecture/BACKEND.md diff --git a/docs/BUILD_AND_DEPLOY.md b/docs/architecture/BUILD_AND_DEPLOY.md similarity index 100% rename from docs/BUILD_AND_DEPLOY.md rename to docs/architecture/BUILD_AND_DEPLOY.md diff --git a/docs/DATABASE.md b/docs/architecture/DATABASE.md similarity index 100% rename from docs/DATABASE.md rename to docs/architecture/DATABASE.md diff --git a/docs/FRONTEND.md b/docs/architecture/FRONTEND.md similarity index 100% rename from docs/FRONTEND.md rename to docs/architecture/FRONTEND.md diff --git a/project_structure.text b/docs/architecture/project_structure.text similarity index 100% rename from project_structure.text rename to docs/architecture/project_structure.text diff --git a/docs/Backend-Notes/GIT.txt b/docs/backend-notes/GIT.txt similarity index 100% rename from docs/Backend-Notes/GIT.txt rename to docs/backend-notes/GIT.txt diff --git a/docs/Backend-Notes/HTTP.txt b/docs/backend-notes/HTTP.txt similarity index 100% rename from docs/Backend-Notes/HTTP.txt rename to docs/backend-notes/HTTP.txt diff --git a/docs/Backend-Notes/SPRING-BOOT.txt b/docs/backend-notes/SPRING-BOOT.txt similarity index 100% rename from docs/Backend-Notes/SPRING-BOOT.txt rename to docs/backend-notes/SPRING-BOOT.txt diff --git a/docs/Backend-Notes/TRANSACTIONAL.md b/docs/backend-notes/TRANSACTIONAL.md similarity index 100% rename from docs/Backend-Notes/TRANSACTIONAL.md rename to docs/backend-notes/TRANSACTIONAL.md diff --git a/docs/CHANGES.md b/docs/planning/CHANGES.md similarity index 100% rename from docs/CHANGES.md rename to docs/planning/CHANGES.md diff --git a/docs/SERVICE_LAYER_PLAN.md b/docs/planning/SERVICE_LAYER_PLAN.md similarity index 100% rename from docs/SERVICE_LAYER_PLAN.md rename to docs/planning/SERVICE_LAYER_PLAN.md diff --git a/docs/STEPS.md b/docs/planning/STEPS.md similarity index 100% rename from docs/STEPS.md rename to docs/planning/STEPS.md diff --git a/docs/log_260323_094732_09FA_.csv b/docs/sample-data/log_260323_094732_09FA_.csv similarity index 100% rename from docs/log_260323_094732_09FA_.csv rename to docs/sample-data/log_260323_094732_09FA_.csv diff --git a/docs/log_260421_050819_KTMB.csv b/docs/sample-data/log_260421_050819_KTMB.csv similarity index 100% rename from docs/log_260421_050819_KTMB.csv rename to docs/sample-data/log_260421_050819_KTMB.csv diff --git a/docs/ADSB_DATA_SOURCE.md b/docs/specs/ADSB_DATA_SOURCE.md similarity index 100% rename from docs/ADSB_DATA_SOURCE.md rename to docs/specs/ADSB_DATA_SOURCE.md diff --git a/docs/ADSB_SYNC_SPEC.md b/docs/specs/ADSB_SYNC_SPEC.md similarity index 100% rename from docs/ADSB_SYNC_SPEC.md rename to docs/specs/ADSB_SYNC_SPEC.md diff --git a/docs/specs/ALERTS_SPEC.md b/docs/specs/ALERTS_SPEC.md new file mode 100644 index 0000000..f4ae117 --- /dev/null +++ b/docs/specs/ALERTS_SPEC.md @@ -0,0 +1,205 @@ +# Maintenance Alerts Spec + +Status: **Backend + email built (Amazon SES); SMS = model + logging sender only; UI = functional** · Last updated: 2026-10-18 + +Alerts the aircraft owner (and anyone they add — a maintenance shop, a partner) +when a Service Timeline item is near or past its due date. Email goes through +Amazon SES (`SesEmailService`). SMS is stubbed (`LoggingSmsSender`) until a real +provider is wired up. + +Separate from the AeroAPI flight-sync `Subscription` — that means "poll AeroAPI +for this tail". This is a different concern with its own entities. + +## How it fires + +- `AlertScheduler` ticks **every hour at :05** (FlightSyncService runs at :00). + 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. +- On a check, every non-title item on the Service Timeline gets a **level**: + `OK` → `DUE_SOON` → `OVERDUE`. + - `OVERDUE` — `daysLeft < 0` or `hoursLeft < 0` + - `DUE_SOON` — `0 ≤ daysLeft ≤ leadTimeDays` or `0 ≤ hoursLeft ≤ leadTimeHours` + - else `OK` + - An item has two limits (calendar and flight hours); the worse one wins. +- Each item stores the level it **last alerted at** (`ServiceTimeline.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). +- When an item improves (maintenance done, due date pushed out), its + `alertLevel` is quietly reset down. No "good news" email. +- No per-edit sending. + +## Turning alerts on + +The alerts section on the dashboard has an **on/off checkbox**, schedule +settings, and a readiness line. Backed by `PUT /alerts/preferences`. + +- **Readiness line:** "Before turning on: …" lists what's missing, from + `GET /alerts/preferences` → `readiness.missing`: + - "Add at least one maintenance item" + - "Set your tail number" + - "Set your owner name" + - "Enter aircraft hours" + Advisory only; the server does not block turning alerts on. +- **Every time** `enabled` flips false→true, the server snapshots each item's + current level (so the next check doesn't flood) and sends **one baseline + digest** ("Alerts are now ON. This is your starting picture…"). + +## Recipients (adding people) + +`AlertRecipient` — belongs to a user. One user → up to **10** recipients. + +| field | notes | +|---|---| +| `channel` | `EMAIL` \| `SMS` | +| `destination` | email address or E.164 phone (`+15551234567`) | +| `label` | optional free text ("Jane's shop"), max 100 chars | +| `status` | `PENDING` \| `ACCEPTED` \| `DECLINED` \| `EXPIRED` | +| `confirmToken` | random URL-safe token, unique | +| `createdAt`, `confirmedAt`, `reminderSentAt` | timestamps | + +Flow: **add → PENDING** → confirm email sent ("[owner name] added you to receive +maintenance alerts for [tail]", with Confirm and Decline links) → recipient +confirms (`ACCEPTED`) or declines (`DECLINED`). Only `ACCEPTED` recipients get +digests. + +Rules on add (`AlertRecipientService.add`), checked in this order: + +1. Address is valid (not blank, ≤ 254 chars, email or E.164 format); label ≤ 100. +2. Owner has an **owner name** and **tail number** (`requireProfile`). Also + checked on Resend. If either is cleared later, emails fall back to + "The aircraft owner" / "your aircraft" (`AlertText`). +3. Same channel + address already on the list: + - `DECLINED` / `EXPIRED` → re-invited (new token, back to `PENDING`, new email). + - `PENDING` / `ACCEPTED` → refused ("That address is already on the list"). +4. Fewer than 10 recipients. + +Errors come back as `400 {"error": "[message]"}`; the dashboard shows the +message under the form and as a toast. + +- Confirm link **expires after 14 days**; a reminder goes out at **day 7** + (`reminderSentAt`). After expiry the row shows `EXPIRED` and the owner presses + Resend for a fresh token. An expired token can't be confirmed. +- **Consent:** the owner can't consent for someone else; every recipient + confirms for themselves. SMS will need double opt-in + STOP/HELP when it's real. +- The owner is *not* auto-added. They add their own email like anyone else. + +## Rate limits + +**Digests** (daily check, baseline, and "Send alert now" share one budget, per +recipient, tracked in `AlertSendLog`): + +- **Email:** max 1 per recipient per 24h +- **SMS:** max 1 per recipient per 72h + +On cooldown the send is skipped for that recipient (logged, not an error). The +"Send alert now" result shows how many were actually sent ("Sent to 0 +recipient(s)." when everyone is on cooldown). No client-side countdown. + +**Confirm emails and owner-triggered emails** (add, resend, Email PDF): +`OutboundEmailLimiter`, max **10 per owner per hour**. Over the limit → 429 and +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 (Block Time / Time in Service). +- **Attachment:** dashboard PDF (`PdfExportService.generateDashboardPdf`), built + once per digest. +- **Footer:** "You're receiving this because [owner name] added you to maintenance + alerts for [tail]. The full dashboard is attached as a PDF." + unsubscribe link + (`/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. + +## 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). +- **`AlertRecipient`** — as table above. +- **`ServiceTimeline`** has `alertLevel` (String, nullable) and + `alertLastFiredAt` (Instant, nullable). +- **`AlertSendLog`** — `recipientId`, `channel`, `sentAt`. Backs the digest rate + limit. Rows older than 30 days are pruned. + +## Housekeeping (every scheduler tick) + +After the per-user checks, each hourly tick also: + +- sends day-7 reminders and marks 14-day-old `PENDING` rows `EXPIRED` + (`housekeepPendingRecipients`) +- prunes `AlertSendLog` rows older than 30 days (`pruneSendLog`) + +## Endpoints + +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/recipients` | — | list with statuses | +| POST | `/alerts/recipients` | form `channel,destination,label` | add → PENDING, sends confirmation | +| DELETE | `/alerts/recipients/{id}` | — | remove | +| POST | `/alerts/recipients/{id}/resend` | — | new token + resend confirmation | +| POST | `/alerts/send-now` | — | send current status to ACCEPTED recipients now → `{"sent": N}` (respects cooldown) | + +Public, no login (`AlertPublicController`, HTML; `permitAll` and CSRF-exempt in +`SecurityConfig`; the token is the proof): + +| method | path | purpose | +|---|---|---| +| GET | `/alerts/confirm?token=…` | page with a "Yes, send me alerts" button | +| POST | `/alerts/confirm` | PENDING → ACCEPTED | +| GET | `/alerts/decline?token=…` | page with a "No thanks" button | +| POST | `/alerts/decline` | → DECLINED | +| GET | `/alerts/unsubscribe?token=…` | page with an "Unsubscribe" button | +| POST | `/alerts/unsubscribe` | → DECLINED (same as decline; separate URL for email footers) | + +GET only shows a page; the POST button does the change. Email security scanners +open every link, so a GET that acted would sign people up or unsubscribe them by +accident. + +## Config (env vars; app-level, not per-user) + +``` +AWS_ACCESS_KEY_ID # IAM user with SES send permission +AWS_SECRET_ACCESS_KEY +AWS_REGION # us-east-2 (where the SES identity lives) +AVIARY_SES_FROM # sender on the verified domain, e.g. aviary-alerts@danielibarra.com +AVIARY_SES_FROM_NAME # default "Aviary" +AVIARY_ALERTS_BASE_URL # https://aviary.danielibarra.com on Heroku; http://localhost:8080 locally +AVIARY_ALERTS_POSTAL_ADDRESS # CAN-SPAM footer +``` + +Locally these come from `.env`; on Heroku from Config Vars. When the AWS keys +or `AVIARY_SES_FROM` are blank, `SesEmailService.isConfigured()` is false and +`NotificationService` logs and skips email instead of failing. SMS always logs +and skips (`LoggingSmsSender`). + +SES account is in the sandbox (verified recipients only, 200/day) until +production access is approved. + +## Not built yet + +- Real SMS send + inbound STOP webhook. +- Per-item threshold overrides. +- HTML (vs plain-text) email body. +- View-only dashboard link for recipients (they get the PDF instead). +- Day-7 reminder still uses its own wording: doesn't name the owner and falls + back to "an aircraft" instead of using `AlertText`. diff --git a/docs/SHARE_EXPORT_SPEC.md b/docs/specs/SHARE_EXPORT_SPEC.md similarity index 100% rename from docs/SHARE_EXPORT_SPEC.md rename to docs/specs/SHARE_EXPORT_SPEC.md diff --git a/src/main/java/com/example/AviaryService/config/SecurityConfig.java b/src/main/java/com/example/AviaryService/config/SecurityConfig.java index f0ddc1a..d421de9 100644 --- a/src/main/java/com/example/AviaryService/config/SecurityConfig.java +++ b/src/main/java/com/example/AviaryService/config/SecurityConfig.java @@ -15,7 +15,7 @@ import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.UserRepository; -import com.example.AviaryService.services.LoginAttemptService; +import com.example.AviaryService.services.account.LoginAttemptService; @Configuration @EnableWebSecurity diff --git a/src/main/java/com/example/AviaryService/config/SyncRunner.java b/src/main/java/com/example/AviaryService/config/SyncRunner.java index ad9d0b2..7f5f30a 100644 --- a/src/main/java/com/example/AviaryService/config/SyncRunner.java +++ b/src/main/java/com/example/AviaryService/config/SyncRunner.java @@ -9,8 +9,8 @@ import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; -import com.example.AviaryService.services.AlertScheduler; -import com.example.AviaryService.services.FlightSyncService; +import com.example.AviaryService.services.alerts.AlertScheduler; +import com.example.AviaryService.services.flights.FlightSyncService; // One-off entrypoint for Heroku Scheduler. The Eco web dyno sleeps after 30 // minutes idle, so the in-process @Scheduled sweeps in FlightSyncService and diff --git a/src/main/java/com/example/AviaryService/controllers/AlertController.java b/src/main/java/com/example/AviaryService/controllers/AlertController.java index e27cf35..84fff6d 100644 --- a/src/main/java/com/example/AviaryService/controllers/AlertController.java +++ b/src/main/java/com/example/AviaryService/controllers/AlertController.java @@ -24,13 +24,16 @@ import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.ServiceTimelineRepository; import com.example.AviaryService.repositories.UserRepository; -import com.example.AviaryService.services.AlertRecipientService; -import com.example.AviaryService.services.AlertService; - -// Owner-facing maintenance-alerts API. All routes require an authenticated user -// (SecurityConfig: anyRequest().authenticated()). The token-guarded -// confirm/decline/unsubscribe links live in AlertPublicController. See -// docs/ALERTS_SPEC.md ("Endpoints"). +import com.example.AviaryService.services.alerts.AlertRecipientService; +import com.example.AviaryService.services.alerts.AlertService; + +// The owner's control panel for maintenance alerts. The owner can change +// alert settings, add or remove the people who get alerts, resend their +// confirm emails, and send a test alert. Sends back JSON. +// +// Login needed for everything here. (SecurityConfig requires it.) The email +// links people click to confirm or unsubscribe are in AlertPublicController. +// Full endpoint list: docs/specs/ALERTS_SPEC.md ("Endpoints"). @RestController @RequestMapping("/alerts") public class AlertController { @@ -164,6 +167,7 @@ private Map prefsBody(User user, AlertPreference prefs) { .filter(t -> !t.getIsTitle()).count(); if (itemCount == 0) missing.add("Add at least one maintenance item"); if (isBlank(user.getTailNumber())) missing.add("Set your tail number"); + if (isBlank(user.getOwnerName())) missing.add("Set your owner name"); if (user.getTimeInServiceHours() == null) missing.add("Enter aircraft hours"); m.put("readiness", Map.of("missing", missing, "ready", missing.isEmpty())); return m; diff --git a/src/main/java/com/example/AviaryService/controllers/AlertPublicController.java b/src/main/java/com/example/AviaryService/controllers/AlertPublicController.java index e2c0528..a933f38 100644 --- a/src/main/java/com/example/AviaryService/controllers/AlertPublicController.java +++ b/src/main/java/com/example/AviaryService/controllers/AlertPublicController.java @@ -8,18 +8,20 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; -import com.example.AviaryService.services.AlertRecipientService; +import com.example.AviaryService.services.alerts.AlertRecipientService; -// The token-guarded links that go out in confirmation / alert emails. No login -// required (SecurityConfig permits /alerts/confirm, /alerts/decline, -// /alerts/unsubscribe) -- the opaque token in the query string is the auth. +// Handles the links inside alert emails. When an owner adds someone to get +// maintenance alerts, that person gets an email with links to confirm, +// decline, or unsubscribe. This file shows the page for each link. // -// Clicking a link (GET) only shows a page with one button; the button POSTs -// to actually confirm/decline. Corporate mail scanners open every link in an -// email, so a GET that changed state would confirm or unsubscribe people -// without them ever clicking. These POSTs are exempt from CSRF in -// SecurityConfig -- the unguessable token already proves the request came -// from the email. +// No login needed: each link has a secret token, and only the person who got +// the email has it. (SecurityConfig allows these URLs without login.) +// +// Clicking a link (GET) only shows a page with a button. Pressing the button +// (POST) does the action. Work email systems auto-click every link to scan +// it, so if the link did the action, people would get signed up or +// unsubscribed by accident. The POSTs skip the CSRF check in SecurityConfig +// because the secret token already proves the click came from the email. @RestController @RequestMapping("/alerts") public class AlertPublicController { diff --git a/src/main/java/com/example/AviaryService/controllers/GlobalExceptionHandler.java b/src/main/java/com/example/AviaryService/controllers/GlobalExceptionHandler.java index a9643bb..9121f0c 100644 --- a/src/main/java/com/example/AviaryService/controllers/GlobalExceptionHandler.java +++ b/src/main/java/com/example/AviaryService/controllers/GlobalExceptionHandler.java @@ -10,11 +10,13 @@ import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; -import com.example.AviaryService.services.RateLimitedException; +import com.example.AviaryService.services.account.RateLimitedException; -// Last-resort mapping for errors that would otherwise surface as a bare 500. -// Bodies carry both "error" and "message" because the settings page reads -// the first and the dashboard reads the second. +// Catches errors from every controller and turns them into a clean JSON +// error message, instead of a crash page (500). Has no URLs of its own. +// +// The error JSON has both "error" and "message" because the settings page +// reads "error" and the dashboard reads "message". @RestControllerAdvice public class GlobalExceptionHandler { diff --git a/src/main/java/com/example/AviaryService/controllers/UserController.java b/src/main/java/com/example/AviaryService/controllers/UserController.java index 50f89d8..946c0f2 100644 --- a/src/main/java/com/example/AviaryService/controllers/UserController.java +++ b/src/main/java/com/example/AviaryService/controllers/UserController.java @@ -18,47 +18,48 @@ import com.example.AviaryService.entity.User; import com.example.AviaryService.entity.DTO.TimelineUpdateDTO; import com.example.AviaryService.repositories.DescriptionOptionRepository; -import com.example.AviaryService.repositories.FlightLogRepository; import com.example.AviaryService.repositories.ServiceTimelineRepository; import com.example.AviaryService.repositories.UserRepository; -import com.example.AviaryService.services.AeroApiClient; -import com.example.AviaryService.services.DescriptionOptionService; -import com.example.AviaryService.services.FlightSuggestionService; -import com.example.AviaryService.services.FlightSyncService; -import com.example.AviaryService.services.HoursService; -import com.example.AviaryService.services.OutboundEmailLimiter; -import com.example.AviaryService.services.PdfExportService; -import com.example.AviaryService.services.SendGridEmailService; -import com.example.AviaryService.services.SubscriptionService; -import com.example.AviaryService.services.TimelineService; -import com.example.AviaryService.services.UserService; -import com.example.AviaryService.util.Formatting; -import com.example.AviaryService.util.Parsing; +import com.example.AviaryService.services.flights.AeroApiClient; +import com.example.AviaryService.services.dashboard.DescriptionOptionService; +import com.example.AviaryService.services.flights.FlightLogService; +import com.example.AviaryService.services.flights.FlightSuggestionService; +import com.example.AviaryService.services.flights.FlightSyncService; +import com.example.AviaryService.services.flights.GarminCsvService; +import com.example.AviaryService.services.dashboard.HoursService; +import com.example.AviaryService.services.messaging.OutboundEmailLimiter; +import com.example.AviaryService.services.dashboard.PdfExportService; +import com.example.AviaryService.services.messaging.EmailSender; +import com.example.AviaryService.services.flights.SubscriptionService; +import com.example.AviaryService.services.dashboard.TimelineService; +import com.example.AviaryService.services.account.UserService; import com.example.AviaryService.util.Validation; import org.apache.catalina.connector.Response; //import org.checkerframework.checker.units.qual.Speed; import org.slf4j.Logger; //import org.slf4j.LoggerFactory; -import jakarta.transaction.Transactional; //import java.io.FileNotFoundException; import java.io.IOException; +import java.io.InputStream; import java.net.URI; -import java.time.Duration; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Scanner; -import java.util.Set; +// The main app. Handles almost everything a logged-in owner does: +// register and login pages, the dashboard, aircraft hours, the maintenance +// timeline, flight logs (including Garmin CSV upload), suggested flights, +// flight-tracking subscriptions, and the PDF report. +// +// Uses @Controller (not @RestController) so it can return HTML pages like +// /login and /dashboard. Methods marked @ResponseBody send back JSON instead. @Controller public class UserController { private final UserRepository userRepository; private final ServiceTimelineRepository serviceTimelineRepository; private final PasswordEncoder passwordEncoder; - private final FlightLogRepository flightLogRepository; private static final Logger log = LoggerFactory.getLogger(UserController.class); private final SubscriptionService subscriptionService; @@ -72,23 +73,25 @@ public class UserController { private final AeroApiClient aeroApiClient; private final FlightSyncService flightSyncService; private final PdfExportService pdfExportService; - private final SendGridEmailService sendGridEmailService; + private final EmailSender emailSender; private final OutboundEmailLimiter emailLimiter; + private final FlightLogService flightLogService; + private final GarminCsvService garminCsvService; public UserController(UserRepository userRepository, ServiceTimelineRepository serviceTimelineRepository, PasswordEncoder passwordEncoder, DescriptionOptionRepository descriptionOptionRepository, - FlightLogRepository flightLogRepository, SubscriptionService subscriptionService, UserService userService, + SubscriptionService subscriptionService, UserService userService, TimelineService timelineService, DescriptionOptionService descriptionOptionService, HoursService hoursService, FlightSuggestionService flightSuggestionService, com.example.AviaryService.repositories.FlightSuggestionRepository flightSuggestionRepository, com.example.AviaryService.repositories.SubscriptionRepository subscriptionRepository, AeroApiClient aeroApiClient, FlightSyncService flightSyncService, PdfExportService pdfExportService, - SendGridEmailService sendGridEmailService, OutboundEmailLimiter emailLimiter) { + EmailSender emailSender, OutboundEmailLimiter emailLimiter, + FlightLogService flightLogService, GarminCsvService garminCsvService) { this.userRepository = userRepository; this.serviceTimelineRepository = serviceTimelineRepository; this.passwordEncoder = passwordEncoder; - this.flightLogRepository = flightLogRepository; this.subscriptionService = subscriptionService; this.userService = userService; @@ -101,8 +104,10 @@ public UserController(UserRepository userRepository, ServiceTimelineRepository s this.aeroApiClient = aeroApiClient; this.flightSyncService = flightSyncService; this.pdfExportService = pdfExportService; - this.sendGridEmailService = sendGridEmailService; + this.emailSender = emailSender; this.emailLimiter = emailLimiter; + this.flightLogService = flightLogService; + this.garminCsvService = garminCsvService; } @GetMapping("/register") @@ -147,7 +152,7 @@ public String showDashboard(Model model, Authentication authentication) { model.addAttribute("tailNumber", user.getTailNumber()); model.addAttribute("ownerName", user.getOwnerName()); model.addAttribute("makeModelSN", user.getMakeModelSN()); - model.addAttribute("flightlogs", sortedByFlightTime(flightLogRepository.findByUser(user))); + model.addAttribute("flightlogs", flightLogService.listFor(user)); model.addAttribute("blockTimeUpdatedAt", user.getBlockTimeUpdatedAt() != null ? user.getBlockTimeUpdatedAt().toString() : null); model.addAttribute("timeInServiceUpdatedAt", user.getTimeInServiceUpdatedAt() != null ? user.getTimeInServiceUpdatedAt().toString() : null); model.addAttribute("blockTimeUpdatedSource", user.getBlockTimeUpdatedSource()); @@ -175,7 +180,7 @@ public String showDashboard(Model model, Authentication authentication) { } // Share menu's Download PDF. Server-side rendering (openhtmltopdf) -- - // see docs/SHARE_EXPORT_SPEC.md and PdfExportService. Real vector + // see docs/specs/SHARE_EXPORT_SPEC.md and PdfExportService. Real vector // text/tables, not the earlier client-side screenshot approach. // `today` is the browser's local date, so Time Left in the PDF matches the // dashboard even when the server's UTC date differs. Only trusted within a @@ -208,8 +213,8 @@ public ResponseEntity downloadPdf(@RequestParam(required = false) String } // Share menu's "Email PDF" -- generates the same dashboard PDF as GET /pdf - // and sends it to an arbitrary recipient via SendGrid. See - // docs/SHARE_EXPORT_SPEC.md ("Channels -> Email"). Note the spec's + // and sends it to an arbitrary recipient by email. See + // docs/specs/SHARE_EXPORT_SPEC.md ("Channels -> Email"). Note the spec's // cross-cutting concerns: recipient validation plus the shared per-user // email cap (OutboundEmailLimiter) are in place. @PostMapping("/pdf/email") @@ -220,7 +225,7 @@ public ResponseEntity> emailPdf(@RequestParam String recipie if (user == null) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } - if (!sendGridEmailService.isConfigured()) { + if (!emailSender.isConfigured()) { return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) .body(Map.of("error", "Email sending is not configured on this server.")); } @@ -232,7 +237,7 @@ public ResponseEntity> emailPdf(@RequestParam String recipie byte[] pdf = pdfExportService.generateDashboardPdf(user); String filename = "Aviary_Dashboard_" + java.time.LocalDate.now() + ".pdf"; try { - sendGridEmailService.sendPdf( + emailSender.sendPdf( recipient.trim(), "Your Aviary maintenance record", "Attached is the maintenance record for " + user.getTailNumber() + ".", @@ -273,7 +278,7 @@ public ResponseEntity> getAeroApiUsage(Authentication authen // Manual, on-demand poll -- bypasses the interval/hour gate entirely. // start/end are optional ISO dates (yyyy-MM-dd) from the "Custom check // range" fields; omitted means AeroAPI's own default window. See - // docs/ADSB_SYNC_SPEC.md and docs/ADSB_DATA_SOURCE.md. + // docs/specs/ADSB_SYNC_SPEC.md and docs/specs/ADSB_DATA_SOURCE.md. @PostMapping("/subscription/check-now") @ResponseBody public ResponseEntity> checkNow( @@ -299,7 +304,7 @@ public ResponseEntity> checkNow( } } - // See docs/ADSB_SYNC_SPEC.md "Poll interval" -- how often and at what + // See docs/specs/ADSB_SYNC_SPEC.md "Poll interval" -- how often and at what // local hour the background poller checks this subscription. @PostMapping("/subscription/settings") @ResponseBody @@ -319,7 +324,7 @@ public ResponseEntity> updateSubscriptionSettings( } // Every AeroAPI suggestion ever seen, any status -- an audit trail - // independent of FlightLog's lifecycle. See docs/CHANGES.md. + // independent of FlightLog's lifecycle. See docs/planning/CHANGES.md. @GetMapping("/flightsuggestions/all") @ResponseBody public ResponseEntity>> getAllFlightSuggestions(Authentication authentication) { @@ -342,7 +347,7 @@ public ResponseEntity>> getAllFlightSuggestions(Authent } // AeroAPI-detected flight: turn a suggestion into a real FlightLog row. - // See docs/ADSB_SYNC_SPEC.md rule 1 -- this is the only thing that ever + // See docs/specs/ADSB_SYNC_SPEC.md rule 1 -- this is the only thing that ever // writes a suggestion to the log book; the poller never does. @PostMapping("/flightsuggestions/{id}/accept") @ResponseBody @@ -368,7 +373,7 @@ public ResponseEntity> acceptFlightSuggestion( } } - // Permanent for that user -- see docs/ADSB_SYNC_SPEC.md "UX flow". + // Permanent for that user -- see docs/specs/ADSB_SYNC_SPEC.md "UX flow". @PostMapping("/flightsuggestions/{id}/dismiss") @ResponseBody public ResponseEntity> dismissFlightSuggestion( @@ -439,7 +444,7 @@ public ResponseEntity addTimeline( // One subscription per user. Subscribe needs a registration; unsubscribe // and delete need only the authenticated user, so clearing the dashboard // tail number can never strand an active subscription. See - // docs/ADSB_SYNC_SPEC.md. + // docs/specs/ADSB_SYNC_SPEC.md. @PostMapping("/subscription/subscribe") @ResponseBody public ResponseEntity> subscribe(@RequestBody Map data, Authentication authentication) { @@ -517,61 +522,18 @@ public ResponseEntity> updateHours( @PostMapping("/update/{id}") @ResponseBody - @Transactional public ResponseEntity> updateTimeline( @PathVariable Long id, @RequestBody TimelineUpdateDTO updateDTO, Authentication authentication) { try { - ServiceTimeline timeline = serviceTimelineRepository.findById(id) - .orElseThrow(() -> new IllegalArgumentException("Invalid timeline ID: " + id)); - User user = userRepository.findByUsername(authentication.getName()); - if (user == null || timeline.getUser() == null || timeline.getUser().getId() != user.getId()) { - Map forbidden = new HashMap<>(); - forbidden.put("status", "error"); - forbidden.put("message", "You do not own this timeline"); - return ResponseEntity.status(HttpStatus.FORBIDDEN).body(forbidden); - } - - Validation.maxLength("Item", updateDTO.getItem()); - Validation.maxLength("Description", updateDTO.getDescription()); - Validation.maxLength("Last done", updateDTO.getLastDoneHours()); - Validation.maxLength("Due date", updateDTO.getDueDateHours()); - - System.out.println("Received updateDTO: item=" + updateDTO.getItem() + ", cycle=" + updateDTO.getCycle() + - ", description=" + updateDTO.getDescription() + ", lastDone=" + updateDTO.getLastDone() + - ", dueDate=" + updateDTO.getDueDate() + ", timeLeft=" + updateDTO.getTimeLeft()); - - if (updateDTO.getItem() != null) timeline.setItem(updateDTO.getItem()); - if (updateDTO.getDescription() != null) { - String description = updateDTO.getDescription(); - String[] defaults = {"inspect", "test", "replace", "overhaul"}; - if (java.util.Arrays.asList(defaults).contains(description.toLowerCase())) { - description = description.substring(0, 1).toUpperCase() + description.substring(1).toLowerCase(); - } - timeline.setDescription(description); - descriptionOptionService.saveCustomDescriptionOption(description, userRepository.findByUsername(authentication.getName())); - } - // Structured cycle fields. The client sends them on every save so - // null actually means "clear it" here — distinguish empty/null on - // the client if you ever want partial updates. - timeline.setCycleCalendarValue(updateDTO.getCycleCalendarValue()); - timeline.setCycleCalendarUnit(Parsing.normalizeCalendarUnit(updateDTO.getCycleCalendarUnit())); - timeline.setCycleHours(updateDTO.getCycleHours()); - timeline.setLastDoneDate(updateDTO.getLastDoneDate()); - timeline.setLastDoneHours(updateDTO.getLastDoneHours()); - timeline.setDueDateDate(updateDTO.getDueDateDate()); - timeline.setDueDateHours(updateDTO.getDueDateHours()); - timeline.setTimeLeft(updateDTO.getTimeLeft()); - - ServiceTimeline savedTimeline = serviceTimelineRepository.save(timeline); - System.out.println("Saved timeline with item: " + savedTimeline.getItem() + ", " + savedTimeline.getDescription() + ", " + savedTimeline.getLastDoneHours() + ", " + savedTimeline.getLastDoneDate() + ", "+ savedTimeline.getDueDateHours() + ", "+ savedTimeline.getDueDateDate() + ", " + savedTimeline.getTimeLeft()); - - Map response = new HashMap<>(); - response.put("status", "success"); - return ResponseEntity.ok(response); - } catch (IllegalArgumentException e) { + timelineService.updateTimeline(user, id, updateDTO); + return ResponseEntity.ok(Map.of("status", "success")); + } catch (SecurityException e) { + return ResponseEntity.status(HttpStatus.FORBIDDEN) + .body(Map.of("status", "error", "message", e.getMessage())); + } catch (IllegalArgumentException | java.util.NoSuchElementException e) { return ResponseEntity.badRequest().body(Map.of("status", "error", "message", e.getMessage())); } catch (Exception e) { log.error("Failed to update timeline {}", id, e); @@ -583,16 +545,15 @@ public ResponseEntity> updateTimeline( @DeleteMapping("/delete/{id}") @ResponseBody public ResponseEntity deleteTimeline(@PathVariable Long id, Authentication authentication) { - ServiceTimeline timeline = serviceTimelineRepository.findById(id).orElse(null); - if (timeline == null) { - return ResponseEntity.notFound().build(); - } User user = userRepository.findByUsername(authentication.getName()); - if (user == null || timeline.getUser() == null || timeline.getUser().getId() != user.getId()) { + try { + timelineService.deleteTimeline(user, id); + return ResponseEntity.ok().build(); + } catch (java.util.NoSuchElementException e) { + return ResponseEntity.notFound().build(); + } catch (SecurityException e) { return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); } - serviceTimelineRepository.delete(timeline); - return ResponseEntity.ok().build(); } @DeleteMapping("/deleteOption/{id}") @@ -617,18 +578,7 @@ public ResponseEntity deleteOption(@PathVariable Long id, Authentication @ResponseBody public void updateOrder(@RequestBody List ids, Authentication authentication) { User user = userRepository.findByUsername(authentication.getName()); - List timelines = serviceTimelineRepository.findByUserOrderByIdAsc(user); - for (int i = 0; i < ids.size(); i++) { - Long id = ids.get(i); - ServiceTimeline timeline = timelines.stream() - .filter(t -> t.getId().equals(id)) - .findFirst() - .orElse(null); - if (timeline != null) { - timeline.setTimelineOrder(i); - } - } - serviceTimelineRepository.saveAll(timelines); + timelineService.reorder(user, ids); } // NEW: GET flight logs (for AJAX if needed) @@ -636,28 +586,12 @@ public void updateOrder(@RequestBody List ids, Authentication authenticati @ResponseBody public List getFlightLogs(Authentication authentication) { User user = userRepository.findByUsername(authentication.getName()); - return sortedByFlightTime(flightLogRepository.findByUser(user)); - } - - // Chronological order for display: prefer blockTimeStart (engine start), - // fall back to timeInServiceStart (wheels-off) when only that's known. - // Rows with neither (legacy entries, or a manual entry saved without - // dates) sort last, in insertion order among themselves. - private static List sortedByFlightTime(List logs) { - return logs.stream() - .sorted(java.util.Comparator - .comparing(log -> { - java.time.Instant t = log.getBlockTimeStart() != null ? log.getBlockTimeStart() : log.getTimeInServiceStart(); - return t == null ? java.time.Instant.MAX : t; - }) - .thenComparing(FlightLog::getId)) - .collect(java.util.stream.Collectors.toList()); + return flightLogService.listFor(user); } // POST to add flight log @PostMapping(value = "/addflightlog", consumes = "application/json") @ResponseBody - @Transactional public ResponseEntity> addFlightLog( @RequestBody FlightLog newLog, @RequestParam(required = false, defaultValue = "false") boolean force, @@ -668,94 +602,21 @@ public ResponseEntity> addFlightLog( .body(errorBody("User not authenticated")); } - // Clamp readings to hundredths. Real meters never exceed 2dp (Hobbs - // 0.1, Tach 0.01), and this keeps CSV-prefilled or client-computed - // values from carrying float artifacts into storage. - newLog.setBlockTimeOut(Formatting.roundHoursOrNull(newLog.getBlockTimeOut())); - newLog.setBlockTimeIn(Formatting.roundHoursOrNull(newLog.getBlockTimeIn())); - newLog.setTimeInServiceOut(Formatting.roundHoursOrNull(newLog.getTimeInServiceOut())); - newLog.setTimeInServiceIn(Formatting.roundHoursOrNull(newLog.getTimeInServiceIn())); - - if (tooLong(newLog.getFromAirport()) || tooLong(newLog.getToAirport())) { - return ResponseEntity.badRequest().body(errorBody( - "Airport must be " + Validation.MAX_TEXT + " characters or fewer.")); - } - - // ── Validation ───────────────────────────────────────────────────────── - // Reject incomplete entries before they can corrupt displayed hours. - // Rule: must provide at least one COMPLETE pair (blockTimeOut+blockTimeIn or - // timeInServiceOut+timeInServiceIn). Partial pairs (e.g. only timeInServiceOut) are the exact case - // that used to silently wipe the user's manual hours to zero. - Double ho = newLog.getBlockTimeOut(), hi = newLog.getBlockTimeIn(); - Double to = newLog.getTimeInServiceOut(), ti = newLog.getTimeInServiceIn(); - boolean blockTimePair = (ho != null && hi != null); - boolean timeInServicePair = (to != null && ti != null); - boolean blockTimePartial = (ho == null) != (hi == null); // exactly one set - boolean timeInServicePartial = (to == null) != (ti == null); - - if (!blockTimePair && !timeInServicePair) { - return ResponseEntity.badRequest().body(errorBody( - "Enter both Block Time Out and Block Time In, or both Time in Service Out and Time in Service In.")); - } - if (blockTimePartial) { - return ResponseEntity.badRequest().body(errorBody( - "Block time entry is incomplete — enter both Block Time Out and Block Time In.")); - } - if (timeInServicePartial) { - return ResponseEntity.badRequest().body(errorBody( - "Time in Service entry is incomplete — enter both Time in Service Out and Time in Service In.")); - } - if (blockTimePair && (ho < 0 || hi < 0 || hi < ho)) { - return ResponseEntity.badRequest().body(errorBody( - "Block Time In must be ≥ Block Time Out, and values cannot be negative.")); - } - if (timeInServicePair && (to < 0 || ti < 0 || ti < to)) { - return ResponseEntity.badRequest().body(errorBody( - "Time in Service In must be ≥ Time in Service Out, and values cannot be negative.")); - } - - // A CSV-prefilled or manually-typed entry -- decides whether - // HoursService.recomputeChain treats this row's Out/In as a fixed - // anchor ("manual") or something it can rewrite to fit - // chronologically ("csv"). AeroAPI rows are never created here -- - // see FlightSuggestionService.accept(). - String source = newLog.getSource(); - if (source == null || source.isBlank()) source = "manual"; - newLog.setSource(source); - - // Only a manually-typed reading gets sanity-checked against nearby - // flights -- see HoursService.checkAccuracy. A CSV/AeroAPI reading - // has no physical meter behind it, so there's nothing to be - // "inaccurate": it just gets slotted into the chain below. - if ("manual".equals(source) && !force) { - List existingLogs = flightLogRepository.findByUser(user); - HoursService.AccuracyIssue blockIssue = blockTimePair - ? hoursService.checkAccuracy(existingLogs, newLog.getBlockTimeStart(), newLog.getBlockTimeEnd(), ho, hi, true) - : null; - HoursService.AccuracyIssue serviceIssue = timeInServicePair - ? hoursService.checkAccuracy(existingLogs, newLog.getTimeInServiceStart(), newLog.getTimeInServiceEnd(), to, ti, false) - : null; - if (blockIssue != null || serviceIssue != null) { - return ResponseEntity.status(HttpStatus.CONFLICT) - .body(inaccuracyBody(blockIssue, serviceIssue)); - } + FlightLogService.AddedFlightLog added; + try { + added = flightLogService.add(user, newLog, force); + } catch (FlightLogService.InaccurateEntryException e) { + // Not a hard error: the frontend shows this as a confirm ("Add it + // anyway?") and resubmits with force=true if the user says yes. + Map body = new HashMap<>(); + body.put("inaccurate", true); + body.put("message", e.getMessage()); + return ResponseEntity.status(HttpStatus.CONFLICT).body(body); + } catch (IllegalArgumentException e) { + return ResponseEntity.badRequest().body(errorBody(e.getMessage())); } - // Force user ownership server-side regardless of what the client sent. - newLog.setUser(user); - FlightLog savedLog = flightLogRepository.save(newLog); - - double newBlockTime = hoursService.recomputeChain(user, /*useBlockTime=*/true); - double newTimeInService = hoursService.recomputeChain(user, /*useBlockTime=*/false); - user.setBlockTimeHours(newBlockTime); - user.setTimeInServiceHours(newTimeInService); - java.time.Instant flightNow = java.time.Instant.now(); - user.setBlockTimeUpdatedAt(flightNow); - user.setBlockTimeUpdatedSource("flightlog"); - user.setTimeInServiceUpdatedAt(flightNow); - user.setTimeInServiceUpdatedSource("flightlog"); - userRepository.save(user); - + FlightLog savedLog = added.log(); Map response = new HashMap<>(); response.put("id", savedLog.getId()); response.put("fromAirport", savedLog.getFromAirport()); @@ -768,8 +629,8 @@ public ResponseEntity> addFlightLog( response.put("timeInServiceOut", savedLog.getTimeInServiceOut()); response.put("timeInServiceStart", savedLog.getTimeInServiceStart() != null ? savedLog.getTimeInServiceStart().toString() : null); response.put("timeInServiceEnd", savedLog.getTimeInServiceEnd() != null ? savedLog.getTimeInServiceEnd().toString() : null); - response.put("newBlockTime", newBlockTime); - response.put("newTimeInService", newTimeInService); + response.put("newBlockTime", added.totals().blockTime()); + response.put("newTimeInService", added.totals().timeInService()); return ResponseEntity.ok(response); } @@ -783,195 +644,15 @@ public ResponseEntity> uploadCsv(@RequestParam("csvfile") Mul log.info("Received file: name={}, size={} bytes", file.getOriginalFilename(), file.getSize()); - return parseGarminCsv(file, user); - } - - public static ResponseEntity> parseGarminCsv(MultipartFile file, User user) { - - // Block time: first → last row where oil pressure > 15 psi. - // Mirrors the physical BlockTime meter on the Cirrus, which is oil-pressure activated. - java.time.Instant blockStart = null; - java.time.Instant blockEnd = null; - - // Flight (airborne) time: GndSpd > 35 kt sustained for 3+ consecutive seconds. - // Falls back to IAS when GndSpd is empty (no GPS fix yet). - java.time.Instant airborneStart = null; - java.time.Instant airborneEnd = null; - int airborneConsec = 0; - java.time.Instant airborneCandidate = null; - - try(Scanner scanner = new Scanner(file.getInputStream())) { - int lineNumber = 0; - HashMap headerIndexMap = new HashMap<>(); - - while(scanner.hasNextLine()) { - String line = scanner.nextLine(); - lineNumber++; - - if(lineNumber == 3) { - String[] headers = line.split(","); - for(int i = 0; i < headers.length; i++) { - headerIndexMap.put(headers[i].trim(), i); - } - - Set expected = java.util.Set.of( - "Lcl Date", "Lcl Time", "UTCOfst", "AtvWpt", "Latitude", "Longitude", - "AltInd", "BaroA", "AltMSL", "OAT", "IAS", "GndSpd", "VSpd", "Pitch", - "Roll", "LatAc", "NormAc", "HDG", "TRK", "volt1", "volt2", "amp1", - "FQtyL", "FQtyR", "E1 FFlow", "E1 OilT", "E1 OilP", "E1 MAP", "E1 RPM", - "E1 %Pwr", "E1 CHT1", "E1 CHT2", "E1 CHT3", "E1 CHT4", "E1 CHT5", "E1 CHT6", - "E1 EGT1", "E1 EGT2", "E1 EGT3", "E1 EGT4", "E1 EGT5", "E1 EGT6", - "E1 TIT1", "E1 TIT2", "E1 Torq", "E1 NG", "E1 ITT", "E2 FFlow", "E2 MAP", - "E2 RPM", "E2 Torq", "E2 NG", "E2 ITT", "AltGPS", "TAS", "HSIS", "CRS", - "NAV1", "NAV2", "COM1", "COM2", "HCDI", "VCDI", "WndSpd", "WndDr", - "WptDst", "WptBrg", "MagVar", "AfcsOn", "RollM", "PitchM", "RollC", - "PichC", "VSpdG", "GPSfix", "HAL", "VAL", "HPLwas", "HPLfd", "VPLwas" - ); - if(!headerIndexMap.keySet().containsAll(expected)) { - return ResponseEntity.badRequest().body(Map.of("error", "Not a Garmin CSV file — headers do not match expected format")); - } - - continue; - } - - if(lineNumber <= 3) continue; - - String[] cols = line.split(",", -1); - for(int i = 0; i < cols.length; i++) cols[i] = cols[i].trim(); - - // Row timestamp = Lcl Date + Lcl Time + UTCOfst combined into - // a real UTC instant (was just Lcl Time before -- the date - // and offset were parsed as headers but never read, so the - // actual date a flight happened was never saved anywhere). - // Using the real clock instead of a bare time-of-day also - // fixes a flight that crosses local midnight for free. - Integer dateIdx = headerIndexMap.get("Lcl Date"); - Integer timeIdx = headerIndexMap.get("Lcl Time"); - Integer ofstIdx = headerIndexMap.get("UTCOfst"); - if (dateIdx == null || timeIdx == null || ofstIdx == null - || cols.length <= dateIdx || cols.length <= timeIdx || cols.length <= ofstIdx - || cols[dateIdx].isEmpty() || cols[timeIdx].isEmpty() || cols[ofstIdx].isEmpty()) { - continue; - } - - java.time.Instant rowTime; - try { - rowTime = java.time.OffsetDateTime.parse(cols[dateIdx] + "T" + cols[timeIdx] + cols[ofstIdx]).toInstant(); - } catch (Exception e) { continue; } - - // ── Block time via oil pressure ────────────────────────────────── - Integer oilPIdx = headerIndexMap.get("E1 OilP"); - if(oilPIdx != null && cols.length > oilPIdx && !cols[oilPIdx].isEmpty()) { - try { - if(Double.parseDouble(cols[oilPIdx]) > 15.0) { - if(blockStart == null) blockStart = rowTime; - blockEnd = rowTime; - } - } catch(NumberFormatException ignored) {} - } - - // ── Airborne time via groundspeed (IAS fallback) ───────────────── - double speed = Double.NaN; - Integer gndSpdIdx = headerIndexMap.get("GndSpd"); - if(gndSpdIdx != null && cols.length > gndSpdIdx && !cols[gndSpdIdx].isEmpty()) { - try { speed = Double.parseDouble(cols[gndSpdIdx]); } catch(NumberFormatException ignored) {} - } - if(Double.isNaN(speed)) { - Integer iasIdx = headerIndexMap.get("IAS"); - if(iasIdx != null && cols.length > iasIdx && !cols[iasIdx].isEmpty()) { - try { speed = Double.parseDouble(cols[iasIdx]); } catch(NumberFormatException ignored) {} - } - } - - if(!Double.isNaN(speed) && speed > 35.0) { - airborneConsec++; - if(airborneConsec == 1) airborneCandidate = rowTime; - if(airborneConsec >= 3 && airborneStart == null) airborneStart = airborneCandidate; - if(airborneStart != null) airborneEnd = rowTime; - } else { - airborneConsec = 0; - airborneCandidate = null; - } - } - - if(blockStart == null && airborneStart == null) { - return ResponseEntity.badRequest().body( - csvValues("Could not detect airtime or block time", blockStart, blockEnd, airborneStart, airborneEnd)); - } - - if(blockStart == null || blockEnd == null) { - return ResponseEntity.badRequest().body( - csvValues("Could not detect engine run — Oil pressure does not go up by 15psi", blockStart, blockEnd, airborneStart, airborneEnd)); - } - - - /* - if(airborneStart == null || airborneEnd == null) { - return ResponseEntity.badRequest().body( - csvValues("Could not detect air time — Speed does not go above 35kts", blockStart, blockEnd, airborneStart, airborneEnd)); - } - - */ - - //Calculate Block duration - //Create Block String H: M: S: - Duration blockDuration = Duration.between(blockStart, blockEnd); - String blockStr = "H:" + blockDuration.toHoursPart() + " M:" + blockDuration.toMinutesPart() + " S:" + blockDuration.toSecondsPart(); - - - String airStr = "N/A"; - Duration airDuration = null; - if(airborneStart != null && airborneEnd != null) { - airDuration = Duration.between(airborneStart, airborneEnd); - airStr = "H:" + airDuration.toHoursPart() + " M:" + airDuration.toMinutesPart() + " S:" + airDuration.toSecondsPart(); - } - - double blockTimeOut = user.getBlockTimeHours(); - double blockTimeIn = Math.round((blockTimeOut + blockDuration.toSeconds() / 3600.0) * 100.0) / 100.0; - double timeInServiceOut = user.getTimeInServiceHours(); - Double timeInServiceIn = airDuration != null - ? Math.round((timeInServiceOut + airDuration.toSeconds() / 3600.0) * 100.0) / 100.0 - : null; - - Map result = new HashMap<>(); - result.put("message", "CSV parse completed"); - result.put("flightDuration", blockStr); - result.put("airDuration", airStr); - result.put("blockTimeOut", blockTimeOut); - result.put("blockTimeIn", blockTimeIn); - result.put("blockTimeStart", blockStart.toString()); - result.put("blockTimeEnd", blockEnd.toString()); - result.put("timeInServiceOut", timeInServiceIn != null ? timeInServiceOut : null); - result.put("timeInServiceIn", timeInServiceIn); - result.put("timeInServiceStart", airborneStart != null ? airborneStart.toString() : null); - result.put("timeInServiceEnd", airborneEnd != null ? airborneEnd.toString() : null); - - if(airDuration == null) { - result.put("warning", "Air time not detected — Time in Service fields were not populated"); - } - - return ResponseEntity.ok(result); - + try (InputStream in = file.getInputStream()) { + GarminCsvService.CsvParseResult result = garminCsvService.parse(in, user); + return result.ok() + ? ResponseEntity.ok(result.body()) + : ResponseEntity.badRequest().body(result.body()); } catch (IOException e) { log.error("Failed to read CSV file: {}", e.getMessage()); return ResponseEntity.badRequest().body(Map.of("error", "Could not read the uploaded file")); } - - } - - private static Map csvValues(String error, java.time.Instant blockStart, java.time.Instant blockEnd, java.time.Instant airborneStart, java.time.Instant airborneEnd) { - Map map = new HashMap<>(); - map.put("error", error); - map.put("blockStart", blockStart); - map.put("blockEnd", blockEnd); - map.put("airborneStart", airborneStart); - map.put("airborneEnd", airborneEnd); - - return map; - } - - private static boolean tooLong(String value) { - return value != null && value.length() > Validation.MAX_TEXT; } private static Map errorBody(String message) { @@ -981,122 +662,37 @@ private static Map errorBody(String message) { return body; } - // A manually-typed reading that doesn't line up with the user's other - // flight logs -- see HoursService.checkAccuracy. Not a hard error: the - // frontend shows this as a confirm ("Add it anyway?") and resubmits - // with force=true if the user says yes. - private static Map inaccuracyBody(HoursService.AccuracyIssue blockIssue, HoursService.AccuracyIssue serviceIssue) { - List sentences = new ArrayList<>(); - if (blockIssue != null) sentences.add(describeAccuracyIssue("Block Time", blockIssue)); - if (serviceIssue != null) sentences.add(describeAccuracyIssue("Time in Service", serviceIssue)); - - Map body = new HashMap<>(); - body.put("inaccurate", true); - body.put("message", "This entry doesn't match your other flight logs. " - + String.join(" ", sentences) + " Add it anyway?"); - return body; - } - - private static String describeAccuracyIssue(String label, HoursService.AccuracyIssue issue) { - Double floor = issue.expectedFloor(); - Double ceiling = issue.expectedCeiling(); - if (floor != null && ceiling != null) { - return label + ": based on nearby flights, Out should be at least " + round2(floor) - + " and In should be no more than " + round2(ceiling) - + " (you entered Out: " + round2(issue.enteredOut()) + ", In: " + round2(issue.enteredIn()) + ")."; - } else if (floor != null) { - return label + ": based on nearby flights, Out should be at least " + round2(floor) - + " (you entered " + round2(issue.enteredOut()) + ")."; - } else { - return label + ": based on nearby flights, In should be no more than " + round2(ceiling) - + " (you entered " + round2(issue.enteredIn()) + ")."; - } - } - - private static double round2(double value) { - return Math.round(value * 100.0) / 100.0; - } - - // POST: complete maintenance on a row. - // Server authoritatively picks "today" and "current time-in-service hours" so the - // result is the same regardless of which tab the user clicks from. + // POST: complete maintenance on a row. See TimelineService.completeMaintenance. @PostMapping("/completeMaintenance/{id}") @ResponseBody - @Transactional public ResponseEntity> completeMaintenance( @PathVariable Long id, Authentication authentication) { User user = userRepository.findByUsername(authentication.getName()); if (user == null) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorBody("User not authenticated")); } - ServiceTimeline timeline = serviceTimelineRepository.findById(id).orElse(null); - if (timeline == null) { + TimelineService.CompletedMaintenance done; + try { + done = timelineService.completeMaintenance(user, id); + } catch (java.util.NoSuchElementException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorBody("Row not found")); - } - if (timeline.getUser() == null || timeline.getUser().getId() != user.getId()) { + } catch (SecurityException e) { return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorBody("You do not own this row")); + } catch (IllegalArgumentException e) { + return ResponseEntity.badRequest().body(errorBody(e.getMessage())); } - Integer calVal = timeline.getCycleCalendarValue(); - String calUnit = Parsing.normalizeCalendarUnit(timeline.getCycleCalendarUnit()); - Double hrsCycle = timeline.getCycleHours(); - boolean hasCalendar = (calVal != null && calVal > 0 && calUnit != null); - boolean hasHours = (hrsCycle != null && hrsCycle > 0); - if (!hasCalendar && !hasHours) { - return ResponseEntity.badRequest().body(errorBody( - "Set a calendar cycle or an hours cycle before marking maintenance complete.")); - } - - java.time.LocalDate today = java.time.LocalDate.now(); - double currentTimeInService = user.getTimeInServiceHours(); - - java.time.LocalDate dueDateLd = null; - if (hasCalendar) { - switch (calUnit) { - case "DAYS": dueDateLd = today.plusDays(calVal); break; - case "MONTHS": dueDateLd = today.plusMonths(calVal); break; - case "YEARS": dueDateLd = today.plusYears(calVal); break; - default: - return ResponseEntity.badRequest().body(errorBody("Invalid calendar unit: " + calUnit)); - } - } - Double dueHours = hasHours ? (currentTimeInService + hrsCycle) : null; - - // Only update fields that belong to the active cycle type — leave the other type's - // fields untouched so they stay visible in the UI after repaint. - if (hasCalendar) { - timeline.setLastDoneDate(today.toString()); - timeline.setDueDateDate(dueDateLd != null ? dueDateLd.toString() : null); - } - if (hasHours) { - timeline.setLastDoneHours(Formatting.formatHours(currentTimeInService)); - timeline.setDueDateHours(dueHours != null ? Formatting.formatHours(dueHours) : null); - } - // Same text the dashboard computes, from the row's saved due date/hours. - String timeLeftStr = com.example.AviaryService.util.DueDates.formatTimeLeft( - timeline.getDueDateDate(), timeline.getDueDateHours(), today, currentTimeInService); - timeline.setTimeLeft(timeLeftStr); - serviceTimelineRepository.save(timeline); - - // Build response strings from the actual saved state so repaintDateHoursCell - // receives both the date and hours parts. - String lastDoneStr = java.util.stream.Stream.of(timeline.getLastDoneDate(), timeline.getLastDoneHours()) - .filter(s -> s != null && !s.isEmpty()).collect(java.util.stream.Collectors.joining(" ")); - String dueDateStr = java.util.stream.Stream.of(timeline.getDueDateDate(), timeline.getDueDateHours()) - .filter(s -> s != null && !s.isEmpty()).collect(java.util.stream.Collectors.joining(" ")); - Map resp = new HashMap<>(); resp.put("status", "ok"); - resp.put("lastDone", lastDoneStr); - resp.put("dueDate", dueDateStr); - resp.put("timeLeft", timeLeftStr); + resp.put("lastDone", done.lastDone()); + resp.put("dueDate", done.dueDate()); + resp.put("timeLeft", done.timeLeft()); return ResponseEntity.ok(resp); } // POST to add a custom description option directly (before any row uses it) @PostMapping(value = "/addDescriptionOption", consumes = "application/json") @ResponseBody - @Transactional public ResponseEntity> addDescriptionOption( @RequestBody Map body, Authentication authentication) { User user = userRepository.findByUsername(authentication.getName()); @@ -1120,46 +716,18 @@ public ResponseEntity> addDescriptionOption( // DELETE flight log @DeleteMapping("/deleteflightlog/{id}") @ResponseBody - @Transactional public ResponseEntity> deleteFlightLog(@PathVariable Long id, Authentication authentication) { try { User user = userRepository.findByUsername(authentication.getName()); - FlightLog log = flightLogRepository.findById(id) - .orElseThrow(() -> new IllegalArgumentException("Flight log not found")); - if (!log.getUser().equals(user)) { - return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null); - } - - // This log came from an accepted AeroAPI suggestion -- deleting it - // should give the flight back, not lose it forever. Otherwise the - // suggestion stays "accepted" with nothing pointing at it, and - // its fa_flight_id permanently blocks re-suggesting that flight. - if (log.getFaFlightId() != null) { - flightSuggestionRepository.findByUserAndFaFlightId(user, log.getFaFlightId()) - .ifPresent(suggestion -> { - suggestion.setStatus("pending"); - flightSuggestionRepository.save(suggestion); - }); - } - - flightLogRepository.delete(log); - - double newBlockTime = hoursService.recomputeChain(user, /*useBlockTime=*/true); - double newTimeInService = hoursService.recomputeChain(user, /*useBlockTime=*/false); - user.setBlockTimeHours(newBlockTime); - user.setTimeInServiceHours(newTimeInService); - java.time.Instant flightNow = java.time.Instant.now(); - user.setBlockTimeUpdatedAt(flightNow); - user.setBlockTimeUpdatedSource("flightlog"); - user.setTimeInServiceUpdatedAt(flightNow); - user.setTimeInServiceUpdatedSource("flightlog"); - userRepository.save(user); + FlightLogService.HourTotals totals = flightLogService.delete(user, id); Map response = new HashMap<>(); response.put("status", "success"); - response.put("newBlockTime", newBlockTime); - response.put("newTimeInService", newTimeInService); + response.put("newBlockTime", totals.blockTime()); + response.put("newTimeInService", totals.timeInService()); return ResponseEntity.ok(response); + } catch (SecurityException e) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null); } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); } diff --git a/src/main/java/com/example/AviaryService/entity/AlertPreference.java b/src/main/java/com/example/AviaryService/entity/AlertPreference.java index b3520e0..a0a13a0 100644 --- a/src/main/java/com/example/AviaryService/entity/AlertPreference.java +++ b/src/main/java/com/example/AviaryService/entity/AlertPreference.java @@ -12,7 +12,7 @@ import jakarta.persistence.OneToOne; import jakarta.persistence.Table; -// Per-user maintenance-alert settings. See docs/ALERTS_SPEC.md. +// Per-user maintenance-alert settings. See docs/specs/ALERTS_SPEC.md. // One row per user; created lazily the first time the user opens the alerts // settings or an alert action needs it. @Entity diff --git a/src/main/java/com/example/AviaryService/entity/AlertRecipient.java b/src/main/java/com/example/AviaryService/entity/AlertRecipient.java index f1a4d00..efba71a 100644 --- a/src/main/java/com/example/AviaryService/entity/AlertRecipient.java +++ b/src/main/java/com/example/AviaryService/entity/AlertRecipient.java @@ -12,7 +12,7 @@ import jakarta.persistence.Table; // Someone a user has asked to receive maintenance alerts -- could be the owner's -// own email, a maintenance shop, a partner. See docs/ALERTS_SPEC.md. +// own email, a maintenance shop, a partner. See docs/specs/ALERTS_SPEC.md. // // A recipient only ever receives mail once status == ACCEPTED. Everything starts // PENDING and requires the recipient themselves to confirm (user A can't consent diff --git a/src/main/java/com/example/AviaryService/entity/AlertSendLog.java b/src/main/java/com/example/AviaryService/entity/AlertSendLog.java index 78ed3e7..4ae4119 100644 --- a/src/main/java/com/example/AviaryService/entity/AlertSendLog.java +++ b/src/main/java/com/example/AviaryService/entity/AlertSendLog.java @@ -11,7 +11,7 @@ import jakarta.persistence.Table; // One row per message actually handed to a sender. Backs the per-recipient rate -// limit (docs/ALERTS_SPEC.md "Rate limit") and doubles as an activity trail. +// limit (docs/specs/ALERTS_SPEC.md "Rate limit") and doubles as an activity trail. // The daily sweep prunes rows older than 30 days. @Entity @Table(name = "alert_send_log", indexes = { diff --git a/src/main/java/com/example/AviaryService/entity/FlightLog.java b/src/main/java/com/example/AviaryService/entity/FlightLog.java index 8d8afc6..5bb953b 100644 --- a/src/main/java/com/example/AviaryService/entity/FlightLog.java +++ b/src/main/java/com/example/AviaryService/entity/FlightLog.java @@ -60,7 +60,7 @@ public class FlightLog { // Set only when this row came from an accepted AeroAPI suggestion. Lets // deleting this row reset that suggestion back to pending instead of // leaving it permanently "accepted" with nothing pointing at it -- see - // docs/CHANGES.md. + // docs/planning/CHANGES.md. @Column(nullable = true) private String faFlightId; diff --git a/src/main/java/com/example/AviaryService/entity/FlightSuggestion.java b/src/main/java/com/example/AviaryService/entity/FlightSuggestion.java index a71503e..82c5d16 100644 --- a/src/main/java/com/example/AviaryService/entity/FlightSuggestion.java +++ b/src/main/java/com/example/AviaryService/entity/FlightSuggestion.java @@ -15,7 +15,7 @@ // One AeroAPI-detected flight, pending/accepted/dismissed by the user. // Unique on (user, faFlightId) -- this is the whole dedupe mechanism: a // fa_flight_id already seen for this user, in any status, is never inserted -// again. See docs/ADSB_SYNC_SPEC.md. +// again. See docs/specs/ADSB_SYNC_SPEC.md. @Entity @Table(name = "flight_suggestions", uniqueConstraints = @UniqueConstraint(columnNames = {"user_id", "fa_flight_id"})) diff --git a/src/main/java/com/example/AviaryService/entity/ServiceTimeline.java b/src/main/java/com/example/AviaryService/entity/ServiceTimeline.java index a254cd6..2db0bde 100644 --- a/src/main/java/com/example/AviaryService/entity/ServiceTimeline.java +++ b/src/main/java/com/example/AviaryService/entity/ServiceTimeline.java @@ -50,7 +50,7 @@ public class ServiceTimeline { @Column private Double cycleHours; - // Maintenance-alerts state (docs/ALERTS_SPEC.md). alertLevel is the level + // Maintenance-alerts state (docs/specs/ALERTS_SPEC.md). alertLevel is the level // this item was last alerted at -- null / "DUE_SOON" / "OVERDUE" -- so the // daily sweep only fires when an item gets worse (or an overdue item is due // for its weekly re-nudge). alertLastFiredAt backs that re-nudge timer. diff --git a/src/main/java/com/example/AviaryService/entity/Subscription.java b/src/main/java/com/example/AviaryService/entity/Subscription.java index 95206ab..6305abd 100644 --- a/src/main/java/com/example/AviaryService/entity/Subscription.java +++ b/src/main/java/com/example/AviaryService/entity/Subscription.java @@ -32,7 +32,7 @@ public class Subscription { //the last time you actually found the plane. Only updated when a position comes back. // How often the AeroAPI poller checks this subscription, and at what local - // hour. Bounds and defaults per docs/ADSB_SYNC_SPEC.md ("Poll interval"): + // hour. Bounds and defaults per docs/specs/ADSB_SYNC_SPEC.md ("Poll interval"): // 1-9 days, no settings UI to change these yet -- see "Turning it on" there. @Column(nullable = false) private int pollIntervalDays = 1; diff --git a/src/main/java/com/example/AviaryService/services/RateLimitedException.java b/src/main/java/com/example/AviaryService/services/RateLimitedException.java deleted file mode 100644 index 64f3d72..0000000 --- a/src/main/java/com/example/AviaryService/services/RateLimitedException.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.example.AviaryService.services; - -// Thrown when a user hits a rate limit; GlobalExceptionHandler turns it into -// a 429 with this message. -public class RateLimitedException extends RuntimeException { - public RateLimitedException(String message) { - super(message); - } -} diff --git a/src/main/java/com/example/AviaryService/services/SendGridEmailService.java b/src/main/java/com/example/AviaryService/services/SendGridEmailService.java deleted file mode 100644 index d5a401e..0000000 --- a/src/main/java/com/example/AviaryService/services/SendGridEmailService.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.example.AviaryService.services; - -import java.io.IOException; -import java.util.Base64; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -import com.sendgrid.Method; -import com.sendgrid.Request; -import com.sendgrid.Response; -import com.sendgrid.SendGrid; -import com.sendgrid.helpers.mail.Mail; -import com.sendgrid.helpers.mail.objects.Attachments; -import com.sendgrid.helpers.mail.objects.Content; -import com.sendgrid.helpers.mail.objects.Email; - -// Sends transactional email through SendGrid's v3 Web API. Nothing outside -// this class touches the SendGrid SDK types. See docs/SHARE_EXPORT_SPEC.md -// and docs/ALERTS_SPEC.md. The API key comes from sendgrid.env (gitignored) -// via aviary.sendgrid.api-key; from-email must be a SendGrid-verified sender -// or every send fails with HTTP 403. When key/from are blank this bean is -// present but isConfigured() is false and sends throw IllegalStateException -- -// callers are expected to check first. -@Service -public class SendGridEmailService implements EmailSender { - - private static final Logger log = LoggerFactory.getLogger(SendGridEmailService.class); - - private final SendGrid sendGrid; - private final String fromEmail; - private final String fromName; - private final boolean configured; - - public SendGridEmailService( - @Value("${aviary.sendgrid.api-key:}") String apiKey, - @Value("${aviary.sendgrid.from-email:}") String fromEmail, - @Value("${aviary.sendgrid.from-name:Aviary Service}") String fromName) { - this.sendGrid = new SendGrid(apiKey); - this.fromEmail = fromEmail; - this.fromName = fromName; - this.configured = !apiKey.isBlank() && !fromEmail.isBlank(); - if (!configured) { - log.warn("SendGrid not configured (aviary.sendgrid.api-key / from-email missing) -- email sending is disabled."); - } - } - - @Override - public boolean isConfigured() { - return configured; - } - - @Override - public void send(String toEmail, String subject, String body) { - dispatch(buildMail(toEmail, subject, body), toEmail); - } - - @Override - public void sendPdf(String toEmail, String subject, String body, byte[] pdfBytes, String filename) { - Mail mail = buildMail(toEmail, subject, body); - - Attachments attachment = new Attachments(); - attachment.setContent(Base64.getEncoder().encodeToString(pdfBytes)); - attachment.setType("application/pdf"); - attachment.setFilename(filename); - attachment.setDisposition("attachment"); - mail.addAttachments(attachment); - - dispatch(mail, toEmail); - } - - private Mail buildMail(String toEmail, String subject, String body) { - if (!configured) { - throw new IllegalStateException("SendGrid is not configured; cannot send email."); - } - return new Mail( - new Email(fromEmail, fromName), - subject, - new Email(toEmail), - new Content("text/plain", body)); - } - - // Fires the request. SendGrid returns 202 Accepted on success; anything - // outside 2xx is thrown so the caller can log/surface it. - private void dispatch(Mail mail, String toEmail) { - try { - Request request = new Request(); - request.setMethod(Method.POST); - request.setEndpoint("mail/send"); - request.setBody(mail.build()); - - Response response = sendGrid.api(request); - int status = response.getStatusCode(); - if (status < 200 || status >= 300) { - throw new RuntimeException("SendGrid rejected the message (HTTP " + status + "): " + response.getBody()); - } - log.info("SendGrid accepted message to {} (HTTP {})", toEmail, status); - } catch (IOException e) { - throw new RuntimeException("Failed to reach SendGrid: " + e.getMessage(), e); - } - } -} diff --git a/src/main/java/com/example/AviaryService/services/SmsSender.java b/src/main/java/com/example/AviaryService/services/SmsSender.java deleted file mode 100644 index 489b458..0000000 --- a/src/main/java/com/example/AviaryService/services/SmsSender.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.example.AviaryService.services; - -// Outbound SMS, provider-agnostic. Real delivery (Twilio) is blocked on A2P -// 10DLC carrier registration, which takes weeks -- until then LoggingSmsSender -// stands in and every SMS path is exercised without actually sending. -// TwilioSmsSender will be a drop-in replacement. See docs/ALERTS_SPEC.md. -public interface SmsSender { - - boolean isConfigured(); - - void send(String toPhoneE164, String body); -} diff --git a/src/main/java/com/example/AviaryService/services/TimelineService.java b/src/main/java/com/example/AviaryService/services/TimelineService.java deleted file mode 100644 index 05948de..0000000 --- a/src/main/java/com/example/AviaryService/services/TimelineService.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.example.AviaryService.services; - -import java.util.Map; - -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import com.example.AviaryService.entity.ServiceTimeline; -import com.example.AviaryService.entity.User; -import com.example.AviaryService.repositories.ServiceTimelineRepository; -import com.example.AviaryService.repositories.UserRepository; -import com.example.AviaryService.util.Parsing; - - -@Service -public class TimelineService { - - private final ServiceTimelineRepository serviceTimelineRepository; - - private final DescriptionOptionService descriptionOptionService; - - public TimelineService(UserRepository userRepository, ServiceTimelineRepository serviceTimelineRepository, DescriptionOptionService descriptionOptionService) { - this.serviceTimelineRepository = serviceTimelineRepository; - this.descriptionOptionService = descriptionOptionService; - } - - @Transactional - public ServiceTimeline addTimeline(Map data, User user) { - String item = data.get("item"); - String isTitle = data.getOrDefault("isTitle", "false"); - String description = data.get("description"); - String cycle = data.get("cycle"); - String timeLeft = data.get("timeLeft"); - String ajax = data.getOrDefault("ajax", "false"); - - ServiceTimeline timeline = new ServiceTimeline(); - timeline.setItem(item); - boolean isTitleRow = "true".equals(isTitle); - timeline.setIsTitle(isTitleRow); - - if (!isTitleRow) { - if (description != null) { - timeline.setDescription(description); - descriptionOptionService.saveCustomDescriptionOption(description, user); - } - timeline.setCycleCalendarValue(Parsing.parseIntOrNull(data.get("cycleCalendarValue"))); - timeline.setCycleCalendarUnit(Parsing.normalizeCalendarUnit(data.get("cycleCalendarUnit"))); - timeline.setCycleHours(Parsing.parseDoubleOrNull(data.get("cycleHours"))); - timeline.setLastDoneDate(blankToNull(data.get("lastDoneDate"))); - timeline.setLastDoneHours(blankToNull(data.get("lastDoneHours"))); - timeline.setDueDateDate(blankToNull(data.get("dueDateDate"))); - timeline.setDueDateHours(blankToNull(data.get("dueDateHours"))); - timeline.setTimeLeft(timeLeft); - } - timeline.setUser(user); - - Integer maxOrder = serviceTimelineRepository.findMaxTimelineOrderByUser(user); - int newOrder = (maxOrder != null) ? maxOrder + 1 : 0; - timeline.setTimelineOrder(newOrder); - - return serviceTimelineRepository.save(timeline); - - } - - // Store "" as null so an empty input matches a never-set field. - private static String blankToNull(String s) { - return (s == null || s.isBlank()) ? null : s.trim(); - } -} diff --git a/src/main/java/com/example/AviaryService/services/LoginAttemptService.java b/src/main/java/com/example/AviaryService/services/account/LoginAttemptService.java similarity index 75% rename from src/main/java/com/example/AviaryService/services/LoginAttemptService.java rename to src/main/java/com/example/AviaryService/services/account/LoginAttemptService.java index c66a606..a4a463f 100644 --- a/src/main/java/com/example/AviaryService/services/LoginAttemptService.java +++ b/src/main/java/com/example/AviaryService/services/account/LoginAttemptService.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.account; import java.time.Duration; import java.util.Locale; @@ -10,11 +10,10 @@ import com.example.AviaryService.util.SlidingWindowLimiter; -// Slows down password guessing: after MAX_FAILURES wrong passwords for a -// username within WINDOW, that username is locked until the oldest failure -// ages out. SecurityConfig's UserDetailsService marks the account locked, so -// Spring rejects the attempt before even checking the password. A successful -// login clears the count. Listens to the events Spring Security publishes. +// Stops password guessing. After MAX_FAILURES wrong passwords for a username +// within WINDOW, that username is locked until the oldest failure ages out. +// A successful login resets the count. SecurityConfig checks the lock before +// even looking at the password. @Service public class LoginAttemptService { diff --git a/src/main/java/com/example/AviaryService/services/account/RateLimitedException.java b/src/main/java/com/example/AviaryService/services/account/RateLimitedException.java new file mode 100644 index 0000000..c982afe --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/account/RateLimitedException.java @@ -0,0 +1,9 @@ +package com.example.AviaryService.services.account; + +// The error thrown when a user does something too many times. +// GlobalExceptionHandler turns it into a 429 "too many requests" response. +public class RateLimitedException extends RuntimeException { + public RateLimitedException(String message) { + super(message); + } +} diff --git a/src/main/java/com/example/AviaryService/services/UserService.java b/src/main/java/com/example/AviaryService/services/account/UserService.java similarity index 94% rename from src/main/java/com/example/AviaryService/services/UserService.java rename to src/main/java/com/example/AviaryService/services/account/UserService.java index 071fc7b..20dfc26 100644 --- a/src/main/java/com/example/AviaryService/services/UserService.java +++ b/src/main/java/com/example/AviaryService/services/account/UserService.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.account; import java.util.HashMap; import java.util.Map; @@ -14,6 +14,8 @@ import com.example.AviaryService.repositories.UserRepository; import com.example.AviaryService.util.Validation; +// User accounts. Registers new users (checking the username and password +// rules) and saves changes to a user's info, like tail number and AeroAPI key. @Service public class UserService { diff --git a/src/main/java/com/example/AviaryService/services/AlertDigest.java b/src/main/java/com/example/AviaryService/services/alerts/AlertDigest.java similarity index 71% rename from src/main/java/com/example/AviaryService/services/AlertDigest.java rename to src/main/java/com/example/AviaryService/services/alerts/AlertDigest.java index 5c89a04..a1e8462 100644 --- a/src/main/java/com/example/AviaryService/services/AlertDigest.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertDigest.java @@ -1,9 +1,8 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.alerts; -// The result of evaluating a user's Service Timeline for alerts: whether -// anything is worth sending, and the rendered subject / body if so. -// Immutable value object -- persistence of per-item state is done separately -// by AlertDigestService.markFired(). See docs/ALERTS_SPEC.md. +// 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. public class AlertDigest { private final boolean shouldSend; diff --git a/src/main/java/com/example/AviaryService/services/AlertDigestService.java b/src/main/java/com/example/AviaryService/services/alerts/AlertDigestService.java similarity index 83% rename from src/main/java/com/example/AviaryService/services/AlertDigestService.java rename to src/main/java/com/example/AviaryService/services/alerts/AlertDigestService.java index 28cd22c..7e6b9ac 100644 --- a/src/main/java/com/example/AviaryService/services/AlertDigestService.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertDigestService.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.alerts; import java.time.Instant; import java.time.LocalDate; @@ -18,12 +18,12 @@ import com.example.AviaryService.util.DueDates; import com.example.AviaryService.util.Formatting; -// Evaluates a user's Service Timeline against their alert thresholds and renders -// the digest. Two entry points: -// buildDigest(...) -- read-only; decides shouldSend and builds subject/body -// markFired(...) -- writes each item's alertLevel / alertLastFiredAt so the -// next evaluation only fires on a genuine change -// See docs/ALERTS_SPEC.md ("How it fires", "Digest content"). +// Decides what goes in a user's alert message. Checks each maintenance item +// against the user's alert settings and writes the subject and body. +// buildDigest(...) -- only reads; decides if anything should be sent +// markFired(...) -- remembers what was alerted, so an item isn't alerted +// again unless it gets worse +// See docs/specs/ALERTS_SPEC.md ("How it fires", "Digest content"). @Service public class AlertDigestService { @@ -113,7 +113,7 @@ private String buildBody(User user, List evaluated, List changed, boolean baseline, int overdue, int dueSoon) { StringBuilder sb = new StringBuilder(); - String tail = orDash(user.getTailNumber()); + String tail = AlertText.tail(user); String makeModel = orDash(user.getMakeModel()); sb.append("Maintenance status for ").append(tail); if (!"—".equals(makeModel)) { @@ -148,8 +148,8 @@ private String buildBody(User user, List evaluated, List changed, sb.append('\n'); } - sb.append("\nAircraft hours: Hobbs ").append(hours(user.getBlockTimeHours())) - .append(" · Tach ").append(hours(user.getTimeInServiceHours())).append('\n'); + sb.append("\nAircraft hours: Block Time ").append(hours(user.getBlockTimeHours())) + .append(" · Time in Service ").append(hours(user.getTimeInServiceHours())).append('\n'); return sb.toString(); } @@ -162,19 +162,26 @@ private static String label(AlertLevel level) { }; } - private static String timeLeftText(ServiceTimeline t, Double tis, LocalDate today) { - StringBuilder sb = new StringBuilder(); + static String timeLeftText(ServiceTimeline t, Double tis, LocalDate today) { + //Overdue parts first, then what's left + // "480.0 hrs overdue 106 days left" + List overdue = new ArrayList<>(); + List left = new ArrayList<>(); Long days = DueDates.daysUntil(t.getDueDateDate(), today); if (days != null) { - sb.append(days < 0 ? Math.abs(days) + " days overdue" : days + " days left"); + if(days < 0) overdue.add(Math.abs(days) + " days"); + else left.add(days + " days"); } Double hrs = DueDates.hoursUntil(t.getDueDateHours(), tis); if (hrs != null) { double rounded = Math.round(hrs * 10.0) / 10.0; - if (sb.length() > 0) sb.append(", "); - sb.append(rounded < 0 ? Math.abs(rounded) + " hrs overdue" : rounded + " hrs left"); + if (rounded < 0) overdue.add(Math.abs(rounded) + " hrs"); + else left.add(rounded + " hrs"); } - return sb.length() == 0 ? "" : sb.toString(); + List parts = new ArrayList<>(); + if(!overdue.isEmpty()) parts.add(String.join(", ", overdue) + " overdue"); + if(!left.isEmpty()) parts.add(String.join(", ", left) + " left"); + return String.join(" · ", parts); } private static String hours(Double v) { diff --git a/src/main/java/com/example/AviaryService/services/AlertLevel.java b/src/main/java/com/example/AviaryService/services/alerts/AlertLevel.java similarity index 69% rename from src/main/java/com/example/AviaryService/services/AlertLevel.java rename to src/main/java/com/example/AviaryService/services/alerts/AlertLevel.java index 8245c8f..44a8dcf 100644 --- a/src/main/java/com/example/AviaryService/services/AlertLevel.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertLevel.java @@ -1,8 +1,8 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.alerts; -// Where a Service Timeline item sits relative to its due date, for alerting. -// Ordinal order is the severity order: OK < DUE_SOON < OVERDUE. The daily sweep -// fires when an item's current level outranks the level it last alerted at. +// How close a maintenance item is to being due: OK, DUE_SOON, or OVERDUE +// (least to most serious, in that order). An alert goes out when an item +// moves up from the level it last alerted at. public enum AlertLevel { OK, DUE_SOON, diff --git a/src/main/java/com/example/AviaryService/services/AlertRecipientService.java b/src/main/java/com/example/AviaryService/services/alerts/AlertRecipientService.java similarity index 81% rename from src/main/java/com/example/AviaryService/services/AlertRecipientService.java rename to src/main/java/com/example/AviaryService/services/alerts/AlertRecipientService.java index 532ae60..5a7f0b7 100644 --- a/src/main/java/com/example/AviaryService/services/AlertRecipientService.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertRecipientService.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.alerts; import java.security.SecureRandom; import java.time.Instant; @@ -16,18 +16,21 @@ import com.example.AviaryService.entity.AlertRecipient.Status; import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.AlertRecipientRepository; - -// Add / list / remove / resend maintenance-alert recipients, and the -// token-guarded confirm / decline / unsubscribe transitions the emailed links -// hit. A recipient is PENDING until they themselves confirm -- user A cannot -// consent for user B (docs/ALERTS_SPEC.md "Recipients"). +import com.example.AviaryService.services.messaging.OutboundEmailLimiter; + +// Manages the people who get an owner's alerts: add, list, remove, and resend +// their confirm email. Also does the confirm / decline / unsubscribe when they +// click the email links (see AlertPublicController). +// +// A new recipient stays PENDING until they confirm themselves. The owner can't +// say yes for them. See docs/specs/ALERTS_SPEC.md ("Recipients"). @Service public class AlertRecipientService { private static final Logger log = LoggerFactory.getLogger(AlertRecipientService.class); private static final SecureRandom RANDOM = new SecureRandom(); - // Deliberately loose -- SendGrid/Twilio do the real validation. This just + // Deliberately loose -- the email/SMS provider does the real validation. This just // stops obvious junk from ever creating a row. private static final String EMAIL_RE = "^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$"; private static final String PHONE_RE = "^\\+[1-9]\\d{6,14}$"; @@ -50,6 +53,7 @@ public List list(User user) { @Transactional public AlertRecipient add(User user, Channel channel, String rawDestination, String label) { + requireProfile(user); String destination = rawDestination == null ? "" : rawDestination.trim(); validate(channel, destination); com.example.AviaryService.util.Validation.maxLength("Label", label == null ? null : label.trim(), 100); @@ -90,6 +94,7 @@ public void remove(User user, long id) { @Transactional public AlertRecipient resend(User user, long id) { + requireProfile(user); AlertRecipient r = ownedOrThrow(user, id); r.setStatusEnum(Status.PENDING); r.setConfirmToken(newToken()); @@ -141,12 +146,12 @@ private void sendConfirmation(AlertRecipient r) { String confirmUrl = base.isBlank() ? "(link unavailable -- alerts base URL not configured)" : base + "/alerts/confirm?token=" + r.getConfirmToken(); String declineUrl = base.isBlank() ? "" : base + "/alerts/decline?token=" + r.getConfirmToken(); - String tail = r.getUser().getTailNumber() == null || r.getUser().getTailNumber().isBlank() - ? "an aircraft" : r.getUser().getTailNumber(); + String tail = AlertText.tail(r.getUser()); + String owner = AlertText.owner(r.getUser()); if (r.getChannelEnum() == Channel.EMAIL) { String body = "" - + r.getUser().getUsername() + " added you to receive maintenance alerts for " + tail + ".\n\n" + + owner + " added you to receive maintenance alerts for " + tail + ".\n\n" + "Confirm you want these: " + confirmUrl + "\n" + (declineUrl.isEmpty() ? "" : "Not you / no thanks: " + declineUrl + "\n") + "\nThis link expires in " + AlertRecipient.CONFIRM_EXPIRY_DAYS + " days. " @@ -155,7 +160,7 @@ private void sendConfirmation(AlertRecipient r) { "Confirm maintenance alerts for " + tail, body); } else { notificationService.sendPlainSms(r.getDestination(), - r.getUser().getUsername() + " added you to maintenance alerts for " + tail + owner + " added you to maintenance alerts for " + tail + ". Reply YES to confirm, STOP to decline. " + confirmUrl); } log.info("Sent {} confirmation to recipient {}", r.getChannel(), r.getId()); @@ -170,6 +175,22 @@ private AlertRecipient ownedOrThrow(User user, long id) { return r; } + // A recipient's emails name the owner and aircraft, so both must be set + // before anyone is invited + private static void requireProfile(User user) { + + if((user.getOwnerName() == null || user.getOwnerName().isBlank()) && (user.getTailNumber() == null || user.getTailNumber().isBlank())) { + throw new IllegalArgumentException("Add your name AND tail number in Aircraft Info first."); + } + + if(user.getOwnerName() == null || user.getOwnerName().isBlank()) { + throw new IllegalArgumentException("Add your name in Aircraft Info first."); + } + if(user.getTailNumber() == null || user.getTailNumber().isBlank()) { + throw new IllegalArgumentException("Add your tail number in Aircraft Info first."); + } + } + private void validate(Channel channel, String destination) { if (destination.isEmpty()) { throw new IllegalArgumentException("Enter an address."); diff --git a/src/main/java/com/example/AviaryService/services/AlertScheduler.java b/src/main/java/com/example/AviaryService/services/alerts/AlertScheduler.java similarity index 84% rename from src/main/java/com/example/AviaryService/services/AlertScheduler.java rename to src/main/java/com/example/AviaryService/services/alerts/AlertScheduler.java index 84a3676..ec4c029 100644 --- a/src/main/java/com/example/AviaryService/services/AlertScheduler.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertScheduler.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.alerts; import java.time.LocalDate; import java.time.ZoneId; @@ -12,10 +12,10 @@ import com.example.AviaryService.entity.AlertPreference; import com.example.AviaryService.repositories.AlertPreferenceRepository; -// Hourly tick that drives maintenance alerts. Each user with alerts enabled is -// evaluated only on the tick matching their chosen check hour (AlertService -// enforces that plus a once-a-day guard). Runs at :05 to stay clear of -// FlightSyncService, which ticks at :00. See docs/ALERTS_SPEC.md. +// The clock for maintenance alerts. Runs every hour and checks each user whose +// chosen alert hour matches. 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 public class AlertScheduler { diff --git a/src/main/java/com/example/AviaryService/services/AlertService.java b/src/main/java/com/example/AviaryService/services/alerts/AlertService.java similarity index 95% rename from src/main/java/com/example/AviaryService/services/AlertService.java rename to src/main/java/com/example/AviaryService/services/alerts/AlertService.java index 5037990..6c51119 100644 --- a/src/main/java/com/example/AviaryService/services/AlertService.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertService.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.alerts; import java.time.Duration; import java.time.Instant; @@ -21,10 +21,10 @@ import com.example.AviaryService.repositories.AlertRecipientRepository; import com.example.AviaryService.repositories.AlertSendLogRepository; -// Orchestrates maintenance alerts: preferences (including the enable -> baseline -// transition), the manual "send now", the once-a-day per-user sweep, and the -// housekeeping the scheduler drives (PENDING reminder/expiry, send-log pruning). -// See docs/ALERTS_SPEC.md. +// The main alerts logic. Saves alert settings, handles "Send alert now", runs +// the daily check for each user, and does cleanup (reminds or expires +// recipients who never confirmed, deletes old send logs). +// AlertController and AlertScheduler both call into this. See docs/specs/ALERTS_SPEC.md. @Service public class AlertService { diff --git a/src/main/java/com/example/AviaryService/services/alerts/AlertText.java b/src/main/java/com/example/AviaryService/services/alerts/AlertText.java new file mode 100644 index 0000000..36997ff --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertText.java @@ -0,0 +1,21 @@ +package com.example.AviaryService.services.alerts; + +import com.example.AviaryService.entity.User; + +final class AlertText { + + // Shared wording for alert emails, so every email names the owner and + // aircraft the same way, and never shows a blank if one is missing. + private AlertText() {} + + static String owner(User user) { + String name = user.getOwnerName(); + return name == null || name.isBlank() ? "The aircraft owner" : name.trim(); + } + + static String tail(User user) { + String tail = user.getTailNumber(); + return tail == null || tail.isBlank() ? "your aircraft" : tail.trim(); + } + +} diff --git a/src/main/java/com/example/AviaryService/services/NotificationService.java b/src/main/java/com/example/AviaryService/services/alerts/NotificationService.java similarity index 87% rename from src/main/java/com/example/AviaryService/services/NotificationService.java rename to src/main/java/com/example/AviaryService/services/alerts/NotificationService.java index b35a375..32ccdb4 100644 --- a/src/main/java/com/example/AviaryService/services/NotificationService.java +++ b/src/main/java/com/example/AviaryService/services/alerts/NotificationService.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.alerts; import java.time.Duration; import java.time.Instant; @@ -14,12 +14,15 @@ import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.AlertRecipientRepository; import com.example.AviaryService.repositories.AlertSendLogRepository; - -// Fans a digest out to a user's ACCEPTED recipients, one message each, honouring -// the shared per-recipient rate limit (docs/ALERTS_SPEC.md "Rate limit"): -// email once / 24h, SMS once / 72h. Manual "send now" and the daily sweep both -// go through here, so they share the budget. A recipient on cooldown, or a -// sender that isn't configured, is skipped and logged -- never an exception. +import com.example.AviaryService.services.dashboard.PdfExportService; +import com.example.AviaryService.services.messaging.EmailSender; +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. +// "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"). @Service public class NotificationService { @@ -125,12 +128,12 @@ private void recordSend(AlertRecipient r) { private String emailFooter(User user, AlertRecipient r) { StringBuilder sb = new StringBuilder("\n\n----\n"); - sb.append("You're receiving this because you were added as a maintenance-alert\n"); - sb.append("recipient for ").append(orAircraft(user.getTailNumber())).append(".\n"); + sb.append("You're receiving this because ").append(AlertText.owner(user)) + .append(" added you to maintenance\nalerts for ").append(AlertText.tail(user)) + .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'); - sb.append("View dashboard: ").append(baseUrl).append("/dashboard\n"); } if (!postalAddress.isBlank()) { sb.append(postalAddress).append('\n'); diff --git a/src/main/java/com/example/AviaryService/services/DescriptionOptionService.java b/src/main/java/com/example/AviaryService/services/dashboard/DescriptionOptionService.java similarity index 95% rename from src/main/java/com/example/AviaryService/services/DescriptionOptionService.java rename to src/main/java/com/example/AviaryService/services/dashboard/DescriptionOptionService.java index 9565109..2c3de11 100644 --- a/src/main/java/com/example/AviaryService/services/DescriptionOptionService.java +++ b/src/main/java/com/example/AviaryService/services/dashboard/DescriptionOptionService.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.dashboard; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @@ -12,6 +12,8 @@ import org.slf4j.Logger; +// The custom choices in the maintenance item "Description" dropdown. Saves the +// ones a user types, and skips blanks, duplicates, and the built-in defaults. @Service public class DescriptionOptionService { diff --git a/src/main/java/com/example/AviaryService/services/HoursService.java b/src/main/java/com/example/AviaryService/services/dashboard/HoursService.java similarity index 97% rename from src/main/java/com/example/AviaryService/services/HoursService.java rename to src/main/java/com/example/AviaryService/services/dashboard/HoursService.java index 0536e0e..49d58f9 100644 --- a/src/main/java/com/example/AviaryService/services/HoursService.java +++ b/src/main/java/com/example/AviaryService/services/dashboard/HoursService.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.dashboard; import java.time.Instant; import java.util.ArrayList; @@ -14,6 +14,9 @@ import com.example.AviaryService.repositories.UserRepository; import com.example.AviaryService.util.Formatting; +// Keeps the aircraft's hours right (block time and time in service). Handles +// manual hour edits, catches typed readings that look like typos compared to +// existing logs, and recalculates the hours from the flight logs. @Service public class HoursService { diff --git a/src/main/java/com/example/AviaryService/services/PdfExportService.java b/src/main/java/com/example/AviaryService/services/dashboard/PdfExportService.java similarity index 94% rename from src/main/java/com/example/AviaryService/services/PdfExportService.java rename to src/main/java/com/example/AviaryService/services/dashboard/PdfExportService.java index 31c323f..bc01afa 100644 --- a/src/main/java/com/example/AviaryService/services/PdfExportService.java +++ b/src/main/java/com/example/AviaryService/services/dashboard/PdfExportService.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.dashboard; import java.io.ByteArrayOutputStream; import java.time.Instant; @@ -26,11 +26,11 @@ import com.example.AviaryService.util.Formatting; import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; -// Renders templates/pdf-export.html to real PDF bytes via openhtmltopdf -- -// see docs/SHARE_EXPORT_SPEC.md. Replaced an earlier client-side -// html2canvas+jsPDF approach that screenshotted the dashboard: that produced -// huge rasterized pages that scrolled badly in PDF viewers. This produces -// real vector text/tables instead. +// Makes the maintenance report PDF from templates/pdf-export.html, using the +// openhtmltopdf library. See docs/specs/SHARE_EXPORT_SPEC.md. +// +// It replaced an older way that took a screenshot of the dashboard. Those PDFs +// were huge and scrolled badly. This one has real text and tables. @Service public class PdfExportService { diff --git a/src/main/java/com/example/AviaryService/services/dashboard/TimelineService.java b/src/main/java/com/example/AviaryService/services/dashboard/TimelineService.java new file mode 100644 index 0000000..89c3095 --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/dashboard/TimelineService.java @@ -0,0 +1,218 @@ +package com.example.AviaryService.services.dashboard; + +import java.time.LocalDate; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.entity.DTO.TimelineUpdateDTO; +import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.util.DueDates; +import com.example.AviaryService.util.Formatting; +import com.example.AviaryService.util.Parsing; +import com.example.AviaryService.util.Validation; + + +// The maintenance timeline on the dashboard. Adds, edits, deletes, and +// reorders items, and marks maintenance done (which moves the due date and +// hours forward one cycle). +@Service +public class TimelineService { + + private final ServiceTimelineRepository serviceTimelineRepository; + + private final DescriptionOptionService descriptionOptionService; + + public TimelineService(UserRepository userRepository, ServiceTimelineRepository serviceTimelineRepository, DescriptionOptionService descriptionOptionService) { + this.serviceTimelineRepository = serviceTimelineRepository; + this.descriptionOptionService = descriptionOptionService; + } + + @Transactional + public ServiceTimeline addTimeline(Map data, User user) { + String item = data.get("item"); + String isTitle = data.getOrDefault("isTitle", "false"); + String description = data.get("description"); + String cycle = data.get("cycle"); + String timeLeft = data.get("timeLeft"); + String ajax = data.getOrDefault("ajax", "false"); + + ServiceTimeline timeline = new ServiceTimeline(); + timeline.setItem(item); + boolean isTitleRow = "true".equals(isTitle); + timeline.setIsTitle(isTitleRow); + + if (!isTitleRow) { + if (description != null) { + timeline.setDescription(description); + descriptionOptionService.saveCustomDescriptionOption(description, user); + } + timeline.setCycleCalendarValue(Parsing.parseIntOrNull(data.get("cycleCalendarValue"))); + timeline.setCycleCalendarUnit(Parsing.normalizeCalendarUnit(data.get("cycleCalendarUnit"))); + timeline.setCycleHours(Parsing.parseDoubleOrNull(data.get("cycleHours"))); + timeline.setLastDoneDate(blankToNull(data.get("lastDoneDate"))); + timeline.setLastDoneHours(blankToNull(data.get("lastDoneHours"))); + timeline.setDueDateDate(blankToNull(data.get("dueDateDate"))); + timeline.setDueDateHours(blankToNull(data.get("dueDateHours"))); + timeline.setTimeLeft(timeLeft); + } + timeline.setUser(user); + + Integer maxOrder = serviceTimelineRepository.findMaxTimelineOrderByUser(user); + int newOrder = (maxOrder != null) ? maxOrder + 1 : 0; + timeline.setTimelineOrder(newOrder); + + return serviceTimelineRepository.save(timeline); + + } + + // Saves an edited row. Throws NoSuchElementException if the row doesn't + // exist, SecurityException if it isn't this user's, and + // IllegalArgumentException for text that's too long. + @Transactional + public ServiceTimeline updateTimeline(User user, Long id, TimelineUpdateDTO updateDTO) { + ServiceTimeline timeline = getOwned(user, id); + + Validation.maxLength("Item", updateDTO.getItem()); + Validation.maxLength("Description", updateDTO.getDescription()); + Validation.maxLength("Last done", updateDTO.getLastDoneHours()); + Validation.maxLength("Due date", updateDTO.getDueDateHours()); + + if (updateDTO.getItem() != null) timeline.setItem(updateDTO.getItem()); + if (updateDTO.getDescription() != null) { + String description = updateDTO.getDescription(); + String[] defaults = {"inspect", "test", "replace", "overhaul"}; + if (java.util.Arrays.asList(defaults).contains(description.toLowerCase())) { + description = description.substring(0, 1).toUpperCase() + description.substring(1).toLowerCase(); + } + timeline.setDescription(description); + descriptionOptionService.saveCustomDescriptionOption(description, user); + } + // Structured cycle fields. The client sends them on every save so + // null actually means "clear it" here — distinguish empty/null on + // the client if you ever want partial updates. + timeline.setCycleCalendarValue(updateDTO.getCycleCalendarValue()); + timeline.setCycleCalendarUnit(Parsing.normalizeCalendarUnit(updateDTO.getCycleCalendarUnit())); + timeline.setCycleHours(updateDTO.getCycleHours()); + timeline.setLastDoneDate(updateDTO.getLastDoneDate()); + timeline.setLastDoneHours(updateDTO.getLastDoneHours()); + timeline.setDueDateDate(updateDTO.getDueDateDate()); + timeline.setDueDateHours(updateDTO.getDueDateHours()); + timeline.setTimeLeft(updateDTO.getTimeLeft()); + + return serviceTimelineRepository.save(timeline); + } + + // Throws NoSuchElementException / SecurityException like updateTimeline. + @Transactional + public void deleteTimeline(User user, Long id) { + serviceTimelineRepository.delete(getOwned(user, id)); + } + + // Applies the drag-and-drop order: ids[i] gets position i. Ids that + // aren't this user's rows are ignored. + @Transactional + public void reorder(User user, List ids) { + List timelines = serviceTimelineRepository.findByUserOrderByIdAsc(user); + for (int i = 0; i < ids.size(); i++) { + Long id = ids.get(i); + ServiceTimeline timeline = timelines.stream() + .filter(t -> t.getId().equals(id)) + .findFirst() + .orElse(null); + if (timeline != null) { + timeline.setTimelineOrder(i); + } + } + serviceTimelineRepository.saveAll(timelines); + } + + // The row's new Last Done / Due Date / Time Left text after completing + // maintenance, each "date hours" with blank parts left out. + public record CompletedMaintenance(String lastDone, String dueDate, String timeLeft) {} + + // Marks maintenance done today at the user's current Time in Service and + // rolls the due date/hours forward one cycle. The server picks "today" + // and the hours so the result is the same from any tab. Throws + // NoSuchElementException / SecurityException like updateTimeline, and + // IllegalArgumentException when the row has no cycle. + @Transactional + public CompletedMaintenance completeMaintenance(User user, Long id) { + ServiceTimeline timeline = getOwned(user, id); + + Integer calVal = timeline.getCycleCalendarValue(); + String calUnit = Parsing.normalizeCalendarUnit(timeline.getCycleCalendarUnit()); + Double hrsCycle = timeline.getCycleHours(); + boolean hasCalendar = (calVal != null && calVal > 0 && calUnit != null); + boolean hasHours = (hrsCycle != null && hrsCycle > 0); + if (!hasCalendar && !hasHours) { + throw new IllegalArgumentException( + "Set a calendar cycle or an hours cycle before marking maintenance complete."); + } + + LocalDate today = LocalDate.now(); + double currentTimeInService = user.getTimeInServiceHours(); + + LocalDate dueDateLd = null; + if (hasCalendar) { + switch (calUnit) { + case "DAYS": dueDateLd = today.plusDays(calVal); break; + case "MONTHS": dueDateLd = today.plusMonths(calVal); break; + case "YEARS": dueDateLd = today.plusYears(calVal); break; + default: + throw new IllegalArgumentException("Invalid calendar unit: " + calUnit); + } + } + Double dueHours = hasHours ? (currentTimeInService + hrsCycle) : null; + + // Only update fields that belong to the active cycle type — leave the other type's + // fields untouched so they stay visible in the UI after repaint. + if (hasCalendar) { + timeline.setLastDoneDate(today.toString()); + timeline.setDueDateDate(dueDateLd != null ? dueDateLd.toString() : null); + } + if (hasHours) { + timeline.setLastDoneHours(Formatting.formatHours(currentTimeInService)); + timeline.setDueDateHours(dueHours != null ? Formatting.formatHours(dueHours) : null); + } + // Same text the dashboard computes, from the row's saved due date/hours. + String timeLeftStr = DueDates.formatTimeLeft( + timeline.getDueDateDate(), timeline.getDueDateHours(), today, currentTimeInService); + timeline.setTimeLeft(timeLeftStr); + serviceTimelineRepository.save(timeline); + + // Build the strings from the actual saved state so the dashboard's + // repaintDateHoursCell receives both the date and hours parts. + return new CompletedMaintenance( + joinParts(timeline.getLastDoneDate(), timeline.getLastDoneHours()), + joinParts(timeline.getDueDateDate(), timeline.getDueDateHours()), + timeLeftStr); + } + + private ServiceTimeline getOwned(User user, Long id) { + ServiceTimeline timeline = serviceTimelineRepository.findById(id) + .orElseThrow(() -> new NoSuchElementException("Invalid timeline ID: " + id)); + if (user == null || timeline.getUser() == null || timeline.getUser().getId() != user.getId()) { + throw new SecurityException("You do not own this timeline"); + } + return timeline; + } + + private static String joinParts(String date, String hours) { + return Stream.of(date, hours) + .filter(s -> s != null && !s.isEmpty()).collect(Collectors.joining(" ")); + } + + // Store "" as null so an empty input matches a never-set field. + private static String blankToNull(String s) { + return (s == null || s.isBlank()) ? null : s.trim(); + } +} diff --git a/src/main/java/com/example/AviaryService/services/AeroApiClient.java b/src/main/java/com/example/AviaryService/services/flights/AeroApiClient.java similarity index 94% rename from src/main/java/com/example/AviaryService/services/AeroApiClient.java rename to src/main/java/com/example/AviaryService/services/flights/AeroApiClient.java index a028106..2c32b28 100644 --- a/src/main/java/com/example/AviaryService/services/AeroApiClient.java +++ b/src/main/java/com/example/AviaryService/services/flights/AeroApiClient.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.flights; import java.time.Instant; import java.time.LocalDate; @@ -11,16 +11,16 @@ import com.fasterxml.jackson.databind.JsonNode; -// Talks to FlightAware AeroAPI. Nothing outside this class knows the JSON -// shape or the x-apikey header -- callers get plain Java data back. -// See docs/ADSB_DATA_SOURCE.md for the endpoint reference. +// Gets flight data from FlightAware (AeroAPI). The rest of the app calls this +// and gets plain Java objects back, so only this file deals with AeroAPI's +// JSON and API key header. Endpoint details: docs/specs/ADSB_DATA_SOURCE.md. @Component public class AeroApiClient { private static final String BASE_URL = "https://aeroapi.flightaware.com/aeroapi"; // GET /flights/{ident} bounds, confirmed in aeroapi-openapi.yml (see - // docs/ADSB_DATA_SOURCE.md "Reference: GET /flights/{ident}"). Public so + // docs/specs/ADSB_DATA_SOURCE.md "Reference: GET /flights/{ident}"). Public so // the controller can validate a user-supplied range with the same // numbers, and so the frontend can be told the truth instead of a // hardcoded copy of it. diff --git a/src/main/java/com/example/AviaryService/services/flights/FlightLogService.java b/src/main/java/com/example/AviaryService/services/flights/FlightLogService.java new file mode 100644 index 0000000..b70affd --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/flights/FlightLogService.java @@ -0,0 +1,233 @@ +package com.example.AviaryService.services.flights; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.example.AviaryService.entity.FlightLog; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.FlightLogRepository; +import com.example.AviaryService.repositories.FlightSuggestionRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.util.Formatting; +import com.example.AviaryService.util.Validation; +import com.example.AviaryService.services.dashboard.HoursService; + +// The rules for flight logs. Kept here so the web controller and the future +// MCP tools both follow the same rules. +@Service +public class FlightLogService { + + private final FlightLogRepository flightLogRepository; + private final FlightSuggestionRepository flightSuggestionRepository; + private final UserRepository userRepository; + private final HoursService hoursService; + + public FlightLogService(FlightLogRepository flightLogRepository, + FlightSuggestionRepository flightSuggestionRepository, + UserRepository userRepository, HoursService hoursService) { + this.flightLogRepository = flightLogRepository; + this.flightSuggestionRepository = flightSuggestionRepository; + this.userRepository = userRepository; + this.hoursService = hoursService; + } + + // The user's Block Time and Time in Service totals after a log change. + public record HourTotals(double blockTime, double timeInService) {} + + // A saved log plus the totals it produced. + public record AddedFlightLog(FlightLog log, HourTotals totals) {} + + // A manually-typed reading that doesn't line up with the user's other + // flight logs -- see HoursService.checkAccuracy. Not a hard error: the + // caller can ask the user "Add it anyway?" and retry with force=true. + public static class InaccurateEntryException extends RuntimeException { + public InaccurateEntryException(String message) { + super(message); + } + } + + // All of this user's flight logs, in chronological order. + public List listFor(User user) { + return sortedByFlightTime(flightLogRepository.findByUser(user)); + } + + // Validates and saves a new log, then recomputes the user's hours. + // Throws IllegalArgumentException for bad input, and + // InaccurateEntryException (unless force) when a manual reading doesn't + // fit the user's other flights. + @Transactional + public AddedFlightLog add(User user, FlightLog newLog, boolean force) { + // Clamp readings to hundredths. Real meters never exceed 2dp (Hobbs + // 0.1, Tach 0.01), and this keeps CSV-prefilled or client-computed + // values from carrying float artifacts into storage. + newLog.setBlockTimeOut(Formatting.roundHoursOrNull(newLog.getBlockTimeOut())); + newLog.setBlockTimeIn(Formatting.roundHoursOrNull(newLog.getBlockTimeIn())); + newLog.setTimeInServiceOut(Formatting.roundHoursOrNull(newLog.getTimeInServiceOut())); + newLog.setTimeInServiceIn(Formatting.roundHoursOrNull(newLog.getTimeInServiceIn())); + + if (tooLong(newLog.getFromAirport()) || tooLong(newLog.getToAirport())) { + throw new IllegalArgumentException( + "Airport must be " + Validation.MAX_TEXT + " characters or fewer."); + } + + // ── Validation ───────────────────────────────────────────────────────── + // Reject incomplete entries before they can corrupt displayed hours. + // Rule: must provide at least one COMPLETE pair (blockTimeOut+blockTimeIn or + // timeInServiceOut+timeInServiceIn). Partial pairs (e.g. only timeInServiceOut) are the exact case + // that used to silently wipe the user's manual hours to zero. + Double ho = newLog.getBlockTimeOut(), hi = newLog.getBlockTimeIn(); + Double to = newLog.getTimeInServiceOut(), ti = newLog.getTimeInServiceIn(); + boolean blockTimePair = (ho != null && hi != null); + boolean timeInServicePair = (to != null && ti != null); + boolean blockTimePartial = (ho == null) != (hi == null); // exactly one set + boolean timeInServicePartial = (to == null) != (ti == null); + + if (!blockTimePair && !timeInServicePair) { + throw new IllegalArgumentException( + "Enter both Block Time Out and Block Time In, or both Time in Service Out and Time in Service In."); + } + if (blockTimePartial) { + throw new IllegalArgumentException( + "Block time entry is incomplete — enter both Block Time Out and Block Time In."); + } + if (timeInServicePartial) { + throw new IllegalArgumentException( + "Time in Service entry is incomplete — enter both Time in Service Out and Time in Service In."); + } + if (blockTimePair && (ho < 0 || hi < 0 || hi < ho)) { + throw new IllegalArgumentException( + "Block Time In must be ≥ Block Time Out, and values cannot be negative."); + } + if (timeInServicePair && (to < 0 || ti < 0 || ti < to)) { + throw new IllegalArgumentException( + "Time in Service In must be ≥ Time in Service Out, and values cannot be negative."); + } + + // A CSV-prefilled or manually-typed entry -- decides whether + // HoursService.recomputeChain treats this row's Out/In as a fixed + // anchor ("manual") or something it can rewrite to fit + // chronologically ("csv"). AeroAPI rows are never created here -- + // see FlightSuggestionService.accept(). + String source = newLog.getSource(); + if (source == null || source.isBlank()) source = "manual"; + newLog.setSource(source); + + // Only a manually-typed reading gets sanity-checked against nearby + // flights -- see HoursService.checkAccuracy. A CSV/AeroAPI reading + // has no physical meter behind it, so there's nothing to be + // "inaccurate": it just gets slotted into the chain below. + if ("manual".equals(source) && !force) { + List existingLogs = flightLogRepository.findByUser(user); + HoursService.AccuracyIssue blockIssue = blockTimePair + ? hoursService.checkAccuracy(existingLogs, newLog.getBlockTimeStart(), newLog.getBlockTimeEnd(), ho, hi, true) + : null; + HoursService.AccuracyIssue serviceIssue = timeInServicePair + ? hoursService.checkAccuracy(existingLogs, newLog.getTimeInServiceStart(), newLog.getTimeInServiceEnd(), to, ti, false) + : null; + if (blockIssue != null || serviceIssue != null) { + throw new InaccurateEntryException(inaccuracyMessage(blockIssue, serviceIssue)); + } + } + + // Force user ownership server-side regardless of what the client sent. + newLog.setUser(user); + FlightLog savedLog = flightLogRepository.save(newLog); + return new AddedFlightLog(savedLog, recomputeHours(user)); + } + + // Deletes one of the user's logs and recomputes their hours. Throws + // IllegalArgumentException if it doesn't exist, SecurityException if + // it belongs to someone else. + @Transactional + public HourTotals delete(User user, Long id) { + FlightLog log = flightLogRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("Flight log not found")); + if (!log.getUser().equals(user)) { + throw new SecurityException("You do not own this flight log"); + } + + // This log came from an accepted AeroAPI suggestion -- deleting it + // should give the flight back, not lose it forever. Otherwise the + // suggestion stays "accepted" with nothing pointing at it, and + // its fa_flight_id permanently blocks re-suggesting that flight. + if (log.getFaFlightId() != null) { + flightSuggestionRepository.findByUserAndFaFlightId(user, log.getFaFlightId()) + .ifPresent(suggestion -> { + suggestion.setStatus("pending"); + flightSuggestionRepository.save(suggestion); + }); + } + + flightLogRepository.delete(log); + return recomputeHours(user); + } + + // Re-derives both hour totals from the log chain and stamps them as + // coming from the flight log. + private HourTotals recomputeHours(User user) { + double newBlockTime = hoursService.recomputeChain(user, /*useBlockTime=*/true); + double newTimeInService = hoursService.recomputeChain(user, /*useBlockTime=*/false); + user.setBlockTimeHours(newBlockTime); + user.setTimeInServiceHours(newTimeInService); + Instant flightNow = Instant.now(); + user.setBlockTimeUpdatedAt(flightNow); + user.setBlockTimeUpdatedSource("flightlog"); + user.setTimeInServiceUpdatedAt(flightNow); + user.setTimeInServiceUpdatedSource("flightlog"); + userRepository.save(user); + return new HourTotals(newBlockTime, newTimeInService); + } + + // Chronological order for display: prefer blockTimeStart (engine start), + // fall back to timeInServiceStart (wheels-off) when only that's known. + // Rows with neither (legacy entries, or a manual entry saved without + // dates) sort last, in insertion order among themselves. + private static List sortedByFlightTime(List logs) { + return logs.stream() + .sorted(Comparator + .comparing(log -> { + Instant t = log.getBlockTimeStart() != null ? log.getBlockTimeStart() : log.getTimeInServiceStart(); + return t == null ? Instant.MAX : t; + }) + .thenComparing(FlightLog::getId)) + .collect(Collectors.toList()); + } + + private static boolean tooLong(String value) { + return value != null && value.length() > Validation.MAX_TEXT; + } + + private static String inaccuracyMessage(HoursService.AccuracyIssue blockIssue, HoursService.AccuracyIssue serviceIssue) { + List sentences = new ArrayList<>(); + if (blockIssue != null) sentences.add(describeAccuracyIssue("Block Time", blockIssue)); + if (serviceIssue != null) sentences.add(describeAccuracyIssue("Time in Service", serviceIssue)); + return "This entry doesn't match your other flight logs. " + + String.join(" ", sentences) + " Add it anyway?"; + } + + private static String describeAccuracyIssue(String label, HoursService.AccuracyIssue issue) { + Double floor = issue.expectedFloor(); + Double ceiling = issue.expectedCeiling(); + if (floor != null && ceiling != null) { + return label + ": based on nearby flights, Out should be at least " + round2(floor) + + " and In should be no more than " + round2(ceiling) + + " (you entered Out: " + round2(issue.enteredOut()) + ", In: " + round2(issue.enteredIn()) + ")."; + } else if (floor != null) { + return label + ": based on nearby flights, Out should be at least " + round2(floor) + + " (you entered " + round2(issue.enteredOut()) + ")."; + } else { + return label + ": based on nearby flights, In should be no more than " + round2(ceiling) + + " (you entered " + round2(issue.enteredIn()) + ")."; + } + } + + private static double round2(double value) { + return Math.round(value * 100.0) / 100.0; + } +} diff --git a/src/main/java/com/example/AviaryService/services/FlightSuggestionService.java b/src/main/java/com/example/AviaryService/services/flights/FlightSuggestionService.java similarity index 93% rename from src/main/java/com/example/AviaryService/services/FlightSuggestionService.java rename to src/main/java/com/example/AviaryService/services/flights/FlightSuggestionService.java index 9ee2d83..4c506a2 100644 --- a/src/main/java/com/example/AviaryService/services/FlightSuggestionService.java +++ b/src/main/java/com/example/AviaryService/services/flights/FlightSuggestionService.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.flights; import java.time.Instant; @@ -12,10 +12,11 @@ import com.example.AviaryService.repositories.FlightSuggestionRepository; import com.example.AviaryService.repositories.UserRepository; import com.example.AviaryService.util.Formatting; +import com.example.AviaryService.services.dashboard.HoursService; -// Accept/dismiss for AeroAPI-detected flights. See docs/ADSB_SYNC_SPEC.md, -// rule 1: a suggestion is never written to the log book on its own -- only -// these two user-triggered actions ever change anything. +// Accept or dismiss a flight that AeroAPI found for the user. A found flight is +// never added to the logbook on its own; only these two user actions change +// anything. See docs/specs/ADSB_SYNC_SPEC.md, rule 1. @Service public class FlightSuggestionService { diff --git a/src/main/java/com/example/AviaryService/services/FlightSyncService.java b/src/main/java/com/example/AviaryService/services/flights/FlightSyncService.java similarity index 90% rename from src/main/java/com/example/AviaryService/services/FlightSyncService.java rename to src/main/java/com/example/AviaryService/services/flights/FlightSyncService.java index e5d1ffc..5496c13 100644 --- a/src/main/java/com/example/AviaryService/services/FlightSyncService.java +++ b/src/main/java/com/example/AviaryService/services/flights/FlightSyncService.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.flights; import java.time.Instant; import java.time.LocalDate; @@ -19,13 +19,13 @@ import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.FlightSuggestionRepository; import com.example.AviaryService.repositories.SubscriptionRepository; -import com.example.AviaryService.services.AeroApiClient.AeroApiFlight; +import com.example.AviaryService.services.flights.AeroApiClient.AeroApiFlight; -// The poller from docs/ADSB_SYNC_SPEC.md ("The poller"). For each active -// subscription belonging to a user with an AeroAPI key, checks whether it's -// due, calls AeroAPI, and turns new completed flights into pending -// FlightSuggestion rows. Never touches FlightLog directly -- rule 1, -// propose never write. +// Checks FlightAware for new flights of each subscribed plane. For each active +// subscription (whose user has an AeroAPI key) that's due for a check, it asks +// AeroAPI and turns new finished flights into suggestions the user can accept +// or dismiss. It never writes to the logbook directly. +// See docs/specs/ADSB_SYNC_SPEC.md ("The poller", rule 1). @Service public class FlightSyncService { @@ -74,7 +74,7 @@ public int syncNow(Subscription subscription) { // Same, with a user-chosen range -- what "Check flights now" sends when // custom start/end dates were entered instead of leaving them blank. - // Bounds match GET /flights/{ident} exactly (docs/ADSB_DATA_SOURCE.md): + // Bounds match GET /flights/{ident} exactly (docs/specs/ADSB_DATA_SOURCE.md): // start up to MAX_START_DAYS_BACK in the past, end up to // MAX_END_DAYS_AHEAD in the future, start before end. public int syncNow(Subscription subscription, LocalDate start, LocalDate end) { diff --git a/src/main/java/com/example/AviaryService/services/flights/GarminCsvService.java b/src/main/java/com/example/AviaryService/services/flights/GarminCsvService.java new file mode 100644 index 0000000..ae66b56 --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/flights/GarminCsvService.java @@ -0,0 +1,212 @@ +package com.example.AviaryService.services.flights; + +import java.io.InputStream; +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; +import java.util.Set; + +import org.springframework.stereotype.Service; + +import com.example.AviaryService.entity.User; + +// Reads a Garmin G1000 CSV file for the logbook's "Upload CSV" button and works +// out the block time and airborne time. Only reads; nothing is saved until the +// user submits the pre-filled flight log. +@Service +public class GarminCsvService { + + // ok=true: body holds the pre-filled values. ok=false: body holds an + // "error" message (plus whatever times were detected, for debugging). + public record CsvParseResult(boolean ok, Map body) { + static CsvParseResult error(Map body) { + return new CsvParseResult(false, body); + } + } + + // Reads a Garmin engine-data CSV and works out the flight's block time + // (engine running) and airborne time, then pre-fills Out/In readings + // from the user's current hours. Returns ok=false with an "error" entry + // when the file isn't a Garmin CSV or no engine run is found. + public CsvParseResult parse(InputStream in, User user) { + + // Block time: first → last row where oil pressure > 15 psi. + // Mirrors the physical BlockTime meter on the Cirrus, which is oil-pressure activated. + java.time.Instant blockStart = null; + java.time.Instant blockEnd = null; + + // Flight (airborne) time: GndSpd > 35 kt sustained for 3+ consecutive seconds. + // Falls back to IAS when GndSpd is empty (no GPS fix yet). + java.time.Instant airborneStart = null; + java.time.Instant airborneEnd = null; + int airborneConsec = 0; + java.time.Instant airborneCandidate = null; + + try(Scanner scanner = new Scanner(in)) { + int lineNumber = 0; + HashMap headerIndexMap = new HashMap<>(); + + while(scanner.hasNextLine()) { + String line = scanner.nextLine(); + lineNumber++; + + if(lineNumber == 3) { + String[] headers = line.split(","); + for(int i = 0; i < headers.length; i++) { + headerIndexMap.put(headers[i].trim(), i); + } + + Set expected = java.util.Set.of( + "Lcl Date", "Lcl Time", "UTCOfst", "AtvWpt", "Latitude", "Longitude", + "AltInd", "BaroA", "AltMSL", "OAT", "IAS", "GndSpd", "VSpd", "Pitch", + "Roll", "LatAc", "NormAc", "HDG", "TRK", "volt1", "volt2", "amp1", + "FQtyL", "FQtyR", "E1 FFlow", "E1 OilT", "E1 OilP", "E1 MAP", "E1 RPM", + "E1 %Pwr", "E1 CHT1", "E1 CHT2", "E1 CHT3", "E1 CHT4", "E1 CHT5", "E1 CHT6", + "E1 EGT1", "E1 EGT2", "E1 EGT3", "E1 EGT4", "E1 EGT5", "E1 EGT6", + "E1 TIT1", "E1 TIT2", "E1 Torq", "E1 NG", "E1 ITT", "E2 FFlow", "E2 MAP", + "E2 RPM", "E2 Torq", "E2 NG", "E2 ITT", "AltGPS", "TAS", "HSIS", "CRS", + "NAV1", "NAV2", "COM1", "COM2", "HCDI", "VCDI", "WndSpd", "WndDr", + "WptDst", "WptBrg", "MagVar", "AfcsOn", "RollM", "PitchM", "RollC", + "PichC", "VSpdG", "GPSfix", "HAL", "VAL", "HPLwas", "HPLfd", "VPLwas" + ); + if(!headerIndexMap.keySet().containsAll(expected)) { + return CsvParseResult.error(Map.of("error", "Not a Garmin CSV file — headers do not match expected format")); + } + + continue; + } + + if(lineNumber <= 3) continue; + + String[] cols = line.split(",", -1); + for(int i = 0; i < cols.length; i++) cols[i] = cols[i].trim(); + + // Row timestamp = Lcl Date + Lcl Time + UTCOfst combined into + // a real UTC instant (was just Lcl Time before -- the date + // and offset were parsed as headers but never read, so the + // actual date a flight happened was never saved anywhere). + // Using the real clock instead of a bare time-of-day also + // fixes a flight that crosses local midnight for free. + Integer dateIdx = headerIndexMap.get("Lcl Date"); + Integer timeIdx = headerIndexMap.get("Lcl Time"); + Integer ofstIdx = headerIndexMap.get("UTCOfst"); + if (dateIdx == null || timeIdx == null || ofstIdx == null + || cols.length <= dateIdx || cols.length <= timeIdx || cols.length <= ofstIdx + || cols[dateIdx].isEmpty() || cols[timeIdx].isEmpty() || cols[ofstIdx].isEmpty()) { + continue; + } + + java.time.Instant rowTime; + try { + rowTime = java.time.OffsetDateTime.parse(cols[dateIdx] + "T" + cols[timeIdx] + cols[ofstIdx]).toInstant(); + } catch (Exception e) { continue; } + + // ── Block time via oil pressure ────────────────────────────────── + Integer oilPIdx = headerIndexMap.get("E1 OilP"); + if(oilPIdx != null && cols.length > oilPIdx && !cols[oilPIdx].isEmpty()) { + try { + if(Double.parseDouble(cols[oilPIdx]) > 15.0) { + if(blockStart == null) blockStart = rowTime; + blockEnd = rowTime; + } + } catch(NumberFormatException ignored) {} + } + + // ── Airborne time via groundspeed (IAS fallback) ───────────────── + double speed = Double.NaN; + Integer gndSpdIdx = headerIndexMap.get("GndSpd"); + if(gndSpdIdx != null && cols.length > gndSpdIdx && !cols[gndSpdIdx].isEmpty()) { + try { speed = Double.parseDouble(cols[gndSpdIdx]); } catch(NumberFormatException ignored) {} + } + if(Double.isNaN(speed)) { + Integer iasIdx = headerIndexMap.get("IAS"); + if(iasIdx != null && cols.length > iasIdx && !cols[iasIdx].isEmpty()) { + try { speed = Double.parseDouble(cols[iasIdx]); } catch(NumberFormatException ignored) {} + } + } + + if(!Double.isNaN(speed) && speed > 35.0) { + airborneConsec++; + if(airborneConsec == 1) airborneCandidate = rowTime; + if(airborneConsec >= 3 && airborneStart == null) airborneStart = airborneCandidate; + if(airborneStart != null) airborneEnd = rowTime; + } else { + airborneConsec = 0; + airborneCandidate = null; + } + } + + if(blockStart == null && airborneStart == null) { + return CsvParseResult.error( + csvValues("Could not detect airtime or block time", blockStart, blockEnd, airborneStart, airborneEnd)); + } + + if(blockStart == null || blockEnd == null) { + return CsvParseResult.error( + csvValues("Could not detect engine run — Oil pressure does not go up by 15psi", blockStart, blockEnd, airborneStart, airborneEnd)); + } + + + /* + if(airborneStart == null || airborneEnd == null) { + return CsvParseResult.error( + csvValues("Could not detect air time — Speed does not go above 35kts", blockStart, blockEnd, airborneStart, airborneEnd)); + } + + */ + + //Calculate Block duration + //Create Block String H: M: S: + Duration blockDuration = Duration.between(blockStart, blockEnd); + String blockStr = "H:" + blockDuration.toHoursPart() + " M:" + blockDuration.toMinutesPart() + " S:" + blockDuration.toSecondsPart(); + + + String airStr = "N/A"; + Duration airDuration = null; + if(airborneStart != null && airborneEnd != null) { + airDuration = Duration.between(airborneStart, airborneEnd); + airStr = "H:" + airDuration.toHoursPart() + " M:" + airDuration.toMinutesPart() + " S:" + airDuration.toSecondsPart(); + } + + double blockTimeOut = user.getBlockTimeHours(); + double blockTimeIn = Math.round((blockTimeOut + blockDuration.toSeconds() / 3600.0) * 100.0) / 100.0; + double timeInServiceOut = user.getTimeInServiceHours(); + Double timeInServiceIn = airDuration != null + ? Math.round((timeInServiceOut + airDuration.toSeconds() / 3600.0) * 100.0) / 100.0 + : null; + + Map result = new HashMap<>(); + result.put("message", "CSV parse completed"); + result.put("flightDuration", blockStr); + result.put("airDuration", airStr); + result.put("blockTimeOut", blockTimeOut); + result.put("blockTimeIn", blockTimeIn); + result.put("blockTimeStart", blockStart.toString()); + result.put("blockTimeEnd", blockEnd.toString()); + result.put("timeInServiceOut", timeInServiceIn != null ? timeInServiceOut : null); + result.put("timeInServiceIn", timeInServiceIn); + result.put("timeInServiceStart", airborneStart != null ? airborneStart.toString() : null); + result.put("timeInServiceEnd", airborneEnd != null ? airborneEnd.toString() : null); + + if(airDuration == null) { + result.put("warning", "Air time not detected — Time in Service fields were not populated"); + } + + return new CsvParseResult(true, result); + + } + + } + + private static Map csvValues(String error, java.time.Instant blockStart, java.time.Instant blockEnd, java.time.Instant airborneStart, java.time.Instant airborneEnd) { + Map map = new HashMap<>(); + map.put("error", error); + map.put("blockStart", blockStart); + map.put("blockEnd", blockEnd); + map.put("airborneStart", airborneStart); + map.put("airborneEnd", airborneEnd); + + return map; + } +} diff --git a/src/main/java/com/example/AviaryService/services/SubscriptionService.java b/src/main/java/com/example/AviaryService/services/flights/SubscriptionService.java similarity index 90% rename from src/main/java/com/example/AviaryService/services/SubscriptionService.java rename to src/main/java/com/example/AviaryService/services/flights/SubscriptionService.java index 8469b3b..e4ad952 100644 --- a/src/main/java/com/example/AviaryService/services/SubscriptionService.java +++ b/src/main/java/com/example/AviaryService/services/flights/SubscriptionService.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.flights; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -8,10 +8,10 @@ import com.example.AviaryService.repositories.SubscriptionRepository; import com.example.AviaryService.repositories.UserRepository; -// One flight-sync subscription per user. Looked up by user, never by tail -// number -- a stale/blank User.tailNumber used to make every lookup miss the -// row that was still active, so the poller kept calling AeroAPI for a plane -// the user could not unsubscribe from. +// Manages each user's flight-tracking subscription (one per user). +// Always looks it up by user, not by tail number. Looking it up by tail number +// used to miss the row when the tail number changed, so the app kept calling +// AeroAPI for a plane the user couldn't unsubscribe from. @Service public class SubscriptionService { @@ -81,7 +81,7 @@ public void delete(User user) { subscriptionRepository.delete(sub); } - // See docs/ADSB_SYNC_SPEC.md "Poll interval" for the 1-9 day / 0-23 hour bounds. + // See docs/specs/ADSB_SYNC_SPEC.md "Poll interval" for the 1-9 day / 0-23 hour bounds. @Transactional public void updateSettings(User user, int pollIntervalDays, int preferredCheckHour) { if (pollIntervalDays < 1 || pollIntervalDays > 9) { diff --git a/src/main/java/com/example/AviaryService/services/EmailSender.java b/src/main/java/com/example/AviaryService/services/messaging/EmailSender.java similarity index 62% rename from src/main/java/com/example/AviaryService/services/EmailSender.java rename to src/main/java/com/example/AviaryService/services/messaging/EmailSender.java index da7c476..c48cc08 100644 --- a/src/main/java/com/example/AviaryService/services/EmailSender.java +++ b/src/main/java/com/example/AviaryService/services/messaging/EmailSender.java @@ -1,8 +1,9 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.messaging; -// Transactional email, provider-agnostic. One implementation -// (SendGridEmailService) today; swapping providers means a new impl, not -// changes to callers. See docs/ALERTS_SPEC.md and docs/SHARE_EXPORT_SPEC.md. +// The "send an email" interface the rest of the app uses. Today the only +// version is SesEmailService. To switch email providers, write a new +// version of this; nothing else has to change. +// See docs/specs/ALERTS_SPEC.md and docs/specs/SHARE_EXPORT_SPEC.md. public interface EmailSender { // False when no API key / from-address is configured. Callers should check diff --git a/src/main/java/com/example/AviaryService/services/LoggingSmsSender.java b/src/main/java/com/example/AviaryService/services/messaging/LoggingSmsSender.java similarity index 57% rename from src/main/java/com/example/AviaryService/services/LoggingSmsSender.java rename to src/main/java/com/example/AviaryService/services/messaging/LoggingSmsSender.java index b72df34..c7073dd 100644 --- a/src/main/java/com/example/AviaryService/services/LoggingSmsSender.java +++ b/src/main/java/com/example/AviaryService/services/messaging/LoggingSmsSender.java @@ -1,13 +1,13 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.messaging; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; -// Placeholder SMS sender: logs what it would send and returns. Keeps the whole -// SMS code path (recipients, consent, digests, rate limiting) live and testable -// while real Twilio delivery waits on A2P 10DLC registration. Swap for a -// TwilioSmsSender bean when that clears -- callers depend on SmsSender, not this. +// A stand-in for sending text messages: it only logs what it would send. Real +// texting (Twilio) is waiting on carrier approval (A2P 10DLC). When that clears, +// replace this with a TwilioSmsSender. The rest of the app uses SmsSender, so +// nothing else changes. @Service public class LoggingSmsSender implements SmsSender { diff --git a/src/main/java/com/example/AviaryService/services/OutboundEmailLimiter.java b/src/main/java/com/example/AviaryService/services/messaging/OutboundEmailLimiter.java similarity index 60% rename from src/main/java/com/example/AviaryService/services/OutboundEmailLimiter.java rename to src/main/java/com/example/AviaryService/services/messaging/OutboundEmailLimiter.java index 01a6613..5baf509 100644 --- a/src/main/java/com/example/AviaryService/services/OutboundEmailLimiter.java +++ b/src/main/java/com/example/AviaryService/services/messaging/OutboundEmailLimiter.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.messaging; import java.time.Duration; @@ -6,12 +6,12 @@ import com.example.AviaryService.entity.User; import com.example.AviaryService.util.SlidingWindowLimiter; +import com.example.AviaryService.services.account.RateLimitedException; -// Caps how many user-triggered emails one account can send per hour: alert -// recipient invites/resends, "Send alert now", and the dashboard PDF email. -// These all go to addresses the user typed, so without a cap one account -// could flood any inbox through our SendGrid sender. Scheduled alert digests -// are not counted -- the app sends those, not the user. +// Limits how many emails one account can trigger per hour: alert invites and +// resends, "Send alert now", and emailing the PDF. Without it, someone could +// spam any inbox through our email account. The daily alert emails don't +// count, because the app sends those, not the user. @Service public class OutboundEmailLimiter { diff --git a/src/main/java/com/example/AviaryService/services/messaging/SesEmailService.java b/src/main/java/com/example/AviaryService/services/messaging/SesEmailService.java new file mode 100644 index 0000000..67b0e5d --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/messaging/SesEmailService.java @@ -0,0 +1,100 @@ +package com.example.AviaryService.services.messaging; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.sesv2.SesV2Client; +import software.amazon.awssdk.services.sesv2.model.Attachment; +import software.amazon.awssdk.services.sesv2.model.Body; +import software.amazon.awssdk.services.sesv2.model.Content; +import software.amazon.awssdk.services.sesv2.model.Destination; +import software.amazon.awssdk.services.sesv2.model.EmailContent; +import software.amazon.awssdk.services.sesv2.model.Message; +import software.amazon.awssdk.services.sesv2.model.SendEmailRequest; +import software.amazon.awssdk.services.sesv2.model.SesV2Exception; + +// Sends emails through Amazon SES. Only this file uses AWS's code. +// +// Setup: needs an AWS access key with SES permission, the region, and a +// from-email verified in SES (all from .env via aviary.ses.*). If any is +// blank, isConfigured() is false and sending throws, so check it first. +@Service +public class SesEmailService implements EmailSender { + + private static final Logger log = LoggerFactory.getLogger(SesEmailService.class); + + private final SesV2Client ses; + private final String from; + private final boolean configured; + + public SesEmailService( + @Value("${aviary.ses.access-key:}") String accessKey, + @Value("${aviary.ses.secret-key:}") String secretKey, + @Value("${aviary.ses.region:us-east-1}") String region, + @Value("${aviary.ses.from-email:}") String fromEmail, + @Value("${aviary.ses.from-name:Aviary Service}") String fromName) { + this.from = fromName + " <" + fromEmail + ">"; + this.configured = !accessKey.isBlank() && !secretKey.isBlank() && !fromEmail.isBlank(); + this.ses = !configured ? null : SesV2Client.builder() + .region(Region.of(region)) + .credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create(accessKey, secretKey))) + .build(); + if (!configured) { + log.warn("SES not configured (aviary.ses.* missing) -- email sending is disabled."); + } + } + + @Override + public boolean isConfigured() { + return configured; + } + + @Override + public void send(String toEmail, String subject, String body) { + dispatch(toEmail, subject, body, List.of()); + } + + @Override + public void sendPdf(String toEmail, String subject, String body, byte[] pdfBytes, String filename) { + Attachment pdf = Attachment.builder() + .rawContent(SdkBytes.fromByteArray(pdfBytes)) + .fileName(filename) + .contentType("application/pdf") + .contentDisposition("ATTACHMENT") + // A PDF is binary; base64 is the only encoding that survives email intact. + .contentTransferEncoding("BASE64") + .build(); + dispatch(toEmail, subject, body, List.of(pdf)); + } + + private void dispatch(String toEmail, String subject, String body, List attachments) { + if (!configured) { + throw new IllegalStateException("SES is not configured; cannot send email."); + } + Message.Builder message = Message.builder() + .subject(Content.builder().data(subject).build()) + .body(Body.builder().text(Content.builder().data(body).build()).build()); + if (!attachments.isEmpty()) { + message.attachments(attachments); + } + try { + ses.sendEmail(SendEmailRequest.builder() + .fromEmailAddress(from) + .destination(Destination.builder().toAddresses(toEmail).build()) + .content(EmailContent.builder().simple(message.build()).build()) + .build()); + log.info("SES accepted message to {}", toEmail); + } catch (SesV2Exception e) { + throw new RuntimeException("SES rejected the message: " + e.awsErrorDetails().errorMessage(), e); + } + } +} diff --git a/src/main/java/com/example/AviaryService/services/messaging/SmsSender.java b/src/main/java/com/example/AviaryService/services/messaging/SmsSender.java new file mode 100644 index 0000000..9359fa5 --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/messaging/SmsSender.java @@ -0,0 +1,12 @@ +package com.example.AviaryService.services.messaging; + +// The "send a text message" interface the rest of the app uses. Real texting +// (Twilio) is waiting on carrier approval (A2P 10DLC), which takes weeks. +// Until then LoggingSmsSender stands in; a TwilioSmsSender will replace it. +// See docs/specs/ALERTS_SPEC.md. +public interface SmsSender { + + boolean isConfigured(); + + void send(String toPhoneE164, String body); +} diff --git a/src/main/java/com/example/AviaryService/util/DueDates.java b/src/main/java/com/example/AviaryService/util/DueDates.java index 3048ff0..6a7e826 100644 --- a/src/main/java/com/example/AviaryService/util/DueDates.java +++ b/src/main/java/com/example/AviaryService/util/DueDates.java @@ -3,12 +3,12 @@ import java.time.LocalDate; import java.time.temporal.ChronoUnit; -import com.example.AviaryService.services.AlertLevel; +import com.example.AviaryService.services.alerts.AlertLevel; // Turns a Service Timeline row's stored due-date / due-hours strings into a // number of days / hours remaining, and classifies that against a user's alert // thresholds, and formats the Time Left text. Mirrors calculateTimeLeft in -// dashboard.js (client-side). See docs/ALERTS_SPEC.md. +// dashboard.js (client-side). See docs/specs/ALERTS_SPEC.md. public final class DueDates { private DueDates() { diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index ef692b0..075517b 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -14,12 +14,18 @@ server.tomcat.max-swallow-size=60MB aviary.remember-me.key=${AVIARY_REMEMBER_ME_KEY:dev-remember-me-key-change-me} aviary.aero-api-key.secret=${AVIARY_AERO_KEY:dev-only-fallback-not-secure} -# SendGrid email (Share/Export + Maintenance Alerts -- see docs/SHARE_EXPORT_SPEC.md -# and docs/ALERTS_SPEC.md). Key lives in the gitignored sendgrid.env. +# SendGrid email (Share/Export + Maintenance Alerts -- see docs/specs/SHARE_EXPORT_SPEC.md +# and docs/specs/ALERTS_SPEC.md). Key lives in the gitignored sendgrid.env. # from-email must be a SendGrid-verified sender. -aviary.sendgrid.api-key=${SENDGRID_API_KEY:} -aviary.sendgrid.from-email=${AVIARY_SENDGRID_FROM:} -aviary.sendgrid.from-name=${AVIARY_SENDGRID_FROM_NAME:Aviary Service} +#aviary.sendgrid.api-key=${SENDGRID_API_KEY:} +#aviary.sendgrid.from-email=${AVIARY_SENDGRID_FROM:} +#aviary.sendgrid.from-name=${AVIARY_SENDGRID_FROM_NAME:Aviary Service} + +aviary.ses.access-key=${AWS_ACCESS_KEY_ID:} +aviary.ses.secret-key=${AWS_SECRET_ACCESS_KEY:} +aviary.ses.region=${AWS_REGION:us-east-2} +aviary.ses.from-email=${AVIARY_SES_FROM:} +aviary.ses.from-name=${AVIARY_SES_FROM_NAME:Aviary} # Maintenance alerts. base-url builds the confirm / unsubscribe / dashboard # links in emails (set to the Heroku URL in prod); postal-address is the @@ -30,4 +36,9 @@ aviary.alerts.postal-address=${AVIARY_ALERTS_POSTAL_ADDRESS:} spring.web.resources.chain.strategy.content.enabled=true spring.web.resources.chain.strategy.content.paths=/** spring.web.resources.cache.cachecontrol.max-age=365d -spring.web.resources.cache.cachecontrol.cache-public=true \ No newline at end of file +spring.web.resources.cache.cachecontrol.cache-public=true + +spring.ai.mcp.server.name=aviary +spring.ai.mcp.server.version=0.0.1 +spring.ai.mcp.server.type=SYNC +spring.ai.mcp.server.protocol=STREAMABLE \ No newline at end of file diff --git a/src/main/resources/static/css/dashboardstyle.css b/src/main/resources/static/css/dashboardstyle.css index 0645172..5e61e5f 100644 --- a/src/main/resources/static/css/dashboardstyle.css +++ b/src/main/resources/static/css/dashboardstyle.css @@ -2411,7 +2411,7 @@ textarea::placeholder { display: none; } .all-suggestions-table tr.audit-message-row td::before { display: none; } } -/* ── Maintenance alert recipients (docs/ALERTS_SPEC.md) ── */ +/* ── Maintenance alert recipients (docs/specs/ALERTS_SPEC.md) ── */ .alert-recipient-list { list-style: none; padding: 0; margin: 0.5rem 0 0; } .alert-recipient-list li { display: flex; align-items: center; gap: 0.5rem; padding: 0.25rem 0; } .alert-recipient-list .alert-recipient-who { flex: 1; } diff --git a/src/main/resources/static/js/dashboard.js b/src/main/resources/static/js/dashboard.js index 6809095..f5ace69 100644 --- a/src/main/resources/static/js/dashboard.js +++ b/src/main/resources/static/js/dashboard.js @@ -1724,7 +1724,7 @@ document.addEventListener('DOMContentLoaded', () => { } }); - // AeroAPI-detected flights: Add/Dismiss. See docs/ADSB_SYNC_SPEC.md "UX flow". + // AeroAPI-detected flights: Add/Dismiss. See docs/specs/ADSB_SYNC_SPEC.md "UX flow". document.addEventListener('click', function(event) { const isAccept = event.target.classList.contains('suggestion-accept-btn'); const isDismiss = event.target.classList.contains('suggestion-dismiss-btn'); @@ -1918,7 +1918,7 @@ document.addEventListener('DOMContentLoaded', () => { // closes on an outside click, Escape, or picking an item. Print uses the // browser's print dialog; Download PDF hits the server-rendered GET /pdf. // Email/Text stay disabled (.share-coming-soon) until SendGrid/Twilio are - // actually set up -- see docs/SHARE_EXPORT_SPEC.md. + // actually set up -- see docs/specs/SHARE_EXPORT_SPEC.md. const shareToggleBtn = document.getElementById('share-toggle-btn'); const shareDropdown = document.getElementById('share-dropdown'); function setShareOpen(open) { @@ -2555,7 +2555,7 @@ document.addEventListener('DOMContentLoaded', () => { } -// ── Maintenance alerts settings (docs/ALERTS_SPEC.md) ──────────────────────── +// ── Maintenance alerts settings (docs/specs/ALERTS_SPEC.md) ──────────────────────── // Standalone DOMContentLoaded block: talks to /alerts/* and is independent of // the large closure above. document.addEventListener('DOMContentLoaded', () => { @@ -2665,12 +2665,29 @@ document.addEventListener('DOMContentLoaded', () => { try { const r = await fetch('/alerts/send-now', { method: 'POST', headers: csrf() }); const d = await r.json(); - sendNowMsg.textContent = r.ok ? `Sent to ${d.sent} recipient(s).` : (d.error || 'Failed.'); - } catch (e) { sendNowMsg.textContent = 'Failed.'; } + + if(r.ok) { + sendNowMsg.textContent = `Sent to ${d.sent} recipient(s).`; + showToast(`Sent to ${d.sent} recipient(s).`, 'success'); + } else { + sendNowMsg.textContent = d.error || 'Failed.'; + showToast(d.error || 'Failed.', 'error'); + } + + } catch (e) { sendNowMsg.textContent = 'Failed.'; + showToast('Failed.', 'error'); + } }); addBtn.addEventListener('click', async () => { + addError.textContent = ''; + if (!destInput.value.trim()) { + addError.textContent = 'Enter an address.'; + showToast('Enter an address.', 'error'); + return; + } + const params = new URLSearchParams(); params.set('channel', chanSel.value); params.set('destination', destInput.value.trim()); @@ -2678,10 +2695,19 @@ document.addEventListener('DOMContentLoaded', () => { try { const r = await fetch('/alerts/recipients', { method: 'POST', headers: csrf(), body: params }); const d = await r.json(); - if (!r.ok) { addError.textContent = d.error || 'Could not add.'; return; } - destInput.value = ''; labelInput.value = ''; + + if (!r.ok) { + addError.textContent = d.error || 'Could not add.'; + showToast(d.error || 'Could not add.', 'error'); + } else { + showToast("Recipient added.", 'success') + destInput.value = ''; labelInput.value = ''; + } loadRecipients(); - } catch (e) { addError.textContent = 'Could not add.'; } + } catch (e) { + showToast('Could not add.', 'error'); + addError.textContent = 'Could not add.'; + } }); listEl.addEventListener('click', async (ev) => { diff --git a/src/main/resources/templates/dashboard.html b/src/main/resources/templates/dashboard.html index c04f9c5..093d87b 100644 --- a/src/main/resources/templates/dashboard.html +++ b/src/main/resources/templates/dashboard.html @@ -109,7 +109,7 @@
- Check automatically every @@ -126,7 +126,7 @@ - @@ -490,7 +490,7 @@ - +

✈ flight(s) detected

@@ -505,7 +505,7 @@

✈ flight(s) detected + survives deleting the FlightLog row it became. See docs/planning/CHANGES.md. -->
View all suggested flights diff --git a/src/main/resources/templates/pdf-export.html b/src/main/resources/templates/pdf-export.html index 7b4486c..a3eaa73 100644 --- a/src/main/resources/templates/pdf-export.html +++ b/src/main/resources/templates/pdf-export.html @@ -7,7 +7,7 @@ instead of dashboard.html's flexbox layout and custom-property palette. Note: this file is parsed as strict XML, not lenient HTML5, so keep every comment and tag well-formed (no double hyphens inside a comment body). - See docs/SHARE_EXPORT_SPEC.md. + See docs/specs/SHARE_EXPORT_SPEC.md. --> diff --git a/src/test/java/com/example/AviaryService/controllers/AlertControllerTest.java b/src/test/java/com/example/AviaryService/controllers/AlertControllerTest.java index a25b367..2d99707 100644 --- a/src/test/java/com/example/AviaryService/controllers/AlertControllerTest.java +++ b/src/test/java/com/example/AviaryService/controllers/AlertControllerTest.java @@ -47,6 +47,7 @@ void setUp() { u.setUsername("alertuser"); u.setPassword("x"); u.setTailNumber("N999AV"); + u.setOwnerName("Test Owner"); u.setTimeInServiceHours(500.0); userRepository.save(u); } diff --git a/src/test/java/com/example/AviaryService/controllers/InputValidationTest.java b/src/test/java/com/example/AviaryService/controllers/InputValidationTest.java index ed17a6e..55f9af1 100644 --- a/src/test/java/com/example/AviaryService/controllers/InputValidationTest.java +++ b/src/test/java/com/example/AviaryService/controllers/InputValidationTest.java @@ -52,6 +52,8 @@ void setUp() { User u = new User(); u.setUsername(USER); u.setPassword("x"); + u.setOwnerName("Test Owner"); + u.setTailNumber("N12345"); u.setBlockTimeHours(100.0); u.setTimeInServiceHours(90.0); userRepository.save(u); diff --git a/src/test/java/com/example/AviaryService/services/alerts/AlertDigestServiceTest.java b/src/test/java/com/example/AviaryService/services/alerts/AlertDigestServiceTest.java new file mode 100644 index 0000000..ac4e2ae --- /dev/null +++ b/src/test/java/com/example/AviaryService/services/alerts/AlertDigestServiceTest.java @@ -0,0 +1,50 @@ +package com.example.AviaryService.services.alerts; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.LocalDate; + +import org.junit.jupiter.api.Test; + +import com.example.AviaryService.entity.ServiceTimeline; + +//Checks the "time left" wording in alert emails. Overdue parts come first +class AlertDigestServiceTest { + + private static final LocalDate TODAY = LocalDate.of(2026, 10, 18); + private static final Double HOURS_NOW = 2500.0; + + private static String text(String dueDate, String dueHours) { + ServiceTimeline t = new ServiceTimeline(); + t.setDueDateDate(dueDate); + t.setDueDateHours(dueHours); + return AlertDigestService.timeLeftText(t, HOURS_NOW, TODAY); + } + + @Test + void hoursOverdue_daysLeft_overdueComesFirst() { + assertEquals("480.0 hrs overdue · 106 days left", text("2027-02-01", "2020")); + } + + @Test + void bothOverdue() { + assertEquals("78 days, 630.0 hrs overdue", text("2026-08-01", "1870")); + } + + @Test + void bothLeft() { + assertEquals("12 days, 8.0 hrs left", text("2026-10-30", "2508")); + } + + @Test + void onlyDate() { + assertEquals("12 days left", text("2026-10-30", null)); + } + + @Test + void neither() { + assertEquals("", text(null, null)); + } + + +} diff --git a/src/test/java/com/example/AviaryService/services/AlertServiceIntegrationTest.java b/src/test/java/com/example/AviaryService/services/alerts/AlertServiceIntegrationTest.java similarity index 79% rename from src/test/java/com/example/AviaryService/services/AlertServiceIntegrationTest.java rename to src/test/java/com/example/AviaryService/services/alerts/AlertServiceIntegrationTest.java index 8568b35..68409cf 100644 --- a/src/test/java/com/example/AviaryService/services/AlertServiceIntegrationTest.java +++ b/src/test/java/com/example/AviaryService/services/alerts/AlertServiceIntegrationTest.java @@ -1,4 +1,4 @@ -package com.example.AviaryService.services; +package com.example.AviaryService.services.alerts; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -24,6 +24,10 @@ import com.example.AviaryService.repositories.AlertSendLogRepository; import com.example.AviaryService.repositories.ServiceTimelineRepository; import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.services.alerts.AlertDigest; +import com.example.AviaryService.services.alerts.AlertDigestService; +import com.example.AviaryService.services.alerts.AlertRecipientService; +import com.example.AviaryService.services.alerts.AlertService; // Exercises the alert services against real H2. Email/SMS senders are // unconfigured in the test profile, so NotificationService no-ops the actual @@ -54,6 +58,7 @@ void setUp() { user.setUsername("alertuser-" + System.nanoTime()); user.setPassword("x"); user.setTailNumber("N12345"); + user.setOwnerName("Test Owner"); user.setTimeInServiceHours(1200.0); userRepository.save(user); } @@ -113,6 +118,43 @@ void resend_mintsNewToken() { assertEquals(AlertRecipient.Status.PENDING, after.getStatusEnum()); } + @Test + void addReceipient_blockedWithoutOwnerName() { + user.setOwnerName(" "); + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, + () -> recipientService.add(user, AlertRecipient.Channel.EMAIL, "a@example.com", null)); + assertEquals("Add your name in Aircraft Info first.", e.getMessage()); + assertTrue(recipientService.list(user).isEmpty()); + } + + @Test + void addRecipient_blockedWithoutTailNumber() { + user.setTailNumber(null); + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, + () -> recipientService.add(user, AlertRecipient.Channel.EMAIL, "a@example.com", null)); + assertEquals("Add your tail number in Aircraft Info first.", e.getMessage()); + assertTrue(recipientService.list(user).isEmpty()); + } + + @Test + void resend_blockedWithoutOwnerName() { + AlertRecipient r = recipientService.add(user, AlertRecipient.Channel.EMAIL, "b@example.com", null); + user.setOwnerName(null); + assertThrows(IllegalArgumentException.class, () -> recipientService.resend(user, r.getId())); + } + + @Test + void digest_usesBlockTimeLabels_andTailFallback() { + user.setTailNumber(null); + AlertDigest d = digestService.buildDigest(user, alertService.getOrCreatePrefs(user), false); + assertTrue(d.body().contains("Block Time")); + assertTrue(d.body().contains("Time in Service")); + assertFalse(d.body().contains("Hobbs")); + assertTrue(d.body().contains("Maintenance status for your aircraft")); + } + + + // -- digest evaluation -- @Test diff --git a/src/test/java/com/example/AviaryService/util/DueDatesTest.java b/src/test/java/com/example/AviaryService/util/DueDatesTest.java index 8264118..13d9acd 100644 --- a/src/test/java/com/example/AviaryService/util/DueDatesTest.java +++ b/src/test/java/com/example/AviaryService/util/DueDatesTest.java @@ -7,7 +7,7 @@ import org.junit.jupiter.api.Test; -import com.example.AviaryService.services.AlertLevel; +import com.example.AviaryService.services.alerts.AlertLevel; class DueDatesTest {