diff --git a/README.md b/README.md index 8017766..790f263 100644 --- a/README.md +++ b/README.md @@ -12,13 +12,13 @@ No install, no setup, nothing to download. Register a username + password and yo A multi-user maintenance and flight-hours tracker for general-aviation aircraft owners: -- **Service timeline** — track every recurring maintenance item (annual, transponder/pitot-static tests, VOR checks, oil changes, etc.) on a **calendar cycle** (days/months/years) *or* an **engine-hours cycle**. Each row shows last-done, next-due, and live "time left," and a one-click **Complete Maintenance** button rolls the dates and hours forward automatically. -- **Hours tracking** — block time and time in service, each with a manual baseline "floor," so log-book activity can only ever raise the displayed hours, never silently lower them. -- **Log book** — record flights by hand (from/to airport, block time and time in service out and in) **or import a Garmin avionics CSV** and let the app derive block time (oil pressure > 15 psi) and airborne time (groundspeed > 35 kt) for you. +- **Status Sheet** — track every recurring maintenance item (annual, transponder/pitot-static tests, VOR checks, oil changes, etc.) on a **calendar cycle** (days/months/years) *or* an **engine-hours cycle**. Each row shows last-done, next-due, and live "time left." Enter a Last Done date or hours and the **Due Date fills in automatically** from the cycle (a Due Date you typed yourself is never overwritten), and **Mark complete** asks when the work was done (starting from the Due Date), then rolls the Due Date and hours forward one cycle from there. Hours always show a decimal (25.0). +- **Hours tracking** — Hobbs time and time in service, each with a manual baseline "floor," so log-book activity can only ever raise the displayed hours, never silently lower them. +- **Log book** — record flights by hand (from/to airport, Hobbs time and time in service out and in) **or import a Garmin avionics CSV** and let the app derive Hobbs time (oil pressure > 15 psi) and airborne time (groundspeed > 35 kt) for you. - **Aircraft info card** — make/model, tail number, owner, and serial number, editable inline. -- **Fleets** — track up to 25 aircraft in one account. Each plane has its own info card, hours, service timeline, and log book; a picker in the header switches between them and shows which ones have items overdue or due soon. +- **Fleets** — track up to 25 aircraft in one account. Each plane has its own info card, hours, Status Sheet, and log book; a picker in the header switches between them and shows which ones have items overdue or due soon. -Each account is fully isolated — its own aircraft, service timelines, flight logs, and custom maintenance descriptions. Ownership is enforced server-side on every write, and every request names the aircraft it is for, so an action always lands on the plane on screen. +Each account is fully isolated — its own aircraft, Status Sheets, flight logs, and custom maintenance descriptions. Ownership is enforced server-side on every write, and every request names the aircraft it is for, so an action always lands on the plane on screen. ## Using it @@ -26,13 +26,13 @@ Each account is fully isolated — its own aircraft, service timelines, flight l 2. **Fill in your aircraft info** — make/model, tail number, owner, serial. - **More than one plane?** Tap the aircraft button in the header → **Add aircraft**, type the tail number, **Save**. You land on the new plane, ready for its first maintenance item. Switch planes from the same button; Aviary remembers the last one you looked at. - Maintenance alerts stay account-wide: one email covers every plane, grouped by tail number. -3. **Build your service timeline** — add maintenance items with a calendar or hours cycle. Rows are drag-reorderable, and you can insert title rows to group them. -4. **Set your hours** — enter current block time and time in service manually, or let the log book keep them current. +3. **Build your Status Sheet** — add maintenance items with a calendar or hours cycle. Rows are drag-reorderable, and you can insert title rows to group them. +4. **Set your hours** — enter current Hobbs time and time in service manually, or let the log book keep them current. 5. **Log flights** — add entries by hand, or upload a Garmin CSV and Aviary computes the times and updates your meters. ## Connect an AI assistant -Aviary is also an MCP server, so an AI assistant can import your existing maintenance records — a spreadsheet, a typed list, another tracker's export — into your service timeline. +Aviary is also an MCP server, so an AI assistant can import your existing maintenance records — a spreadsheet, a typed list, another tracker's export — into your Status Sheet. The easiest way in is the **Import with AI** button on the dashboard — it shows the address with a Copy button and these same steps. @@ -48,7 +48,7 @@ You sign in on Aviary's own login page; the assistant never sees your password. 1. Give the assistant your records — paste a list or attach a spreadsheet — and ask it to import them into Aviary. If you track more than one aircraft, say which tail number they're for (the assistant can list your aircraft). 2. It shows you a **proposal** first: the items it will add, anything flagged for you to check (unclear dates, no due date, items you already have), and any rows it couldn't use and why. -3. Tell it to go ahead. The items are added to the bottom of your service timeline. Nothing is added before you confirm, and existing items are never changed or deleted. +3. Tell it to go ahead. The items are added to the bottom of your Status Sheet. Nothing is added before you confirm, and existing items are never changed or deleted. Any row with a name can be imported — including on-condition items with no dates. Values that can't be used are left blank with a note. @@ -131,10 +131,10 @@ push to main | Tool | What it does | |---|---| | `get_import_format` | Item fields, rules, and an example | -| `list_service_timeline` | The owner's current items | -| `propose_timeline_import` | Validates items into a proposal (24 h); changes nothing | +| `list_status_sheet` | The owner's current items | +| `propose_status_sheet_import` | Validates items into a proposal (24 h); changes nothing | | `continue_poor_fit` | Continues a proposal where most rows didn't fit, after the owner agrees | -| `confirm_timeline_import` | Adds exactly the proposal's items, all or nothing | +| `confirm_status_sheet_import` | Adds exactly the proposal's items, all or nothing | | `list_flights` | The owner's logged flights | **Config:** `aviary.oauth.issuer` (env `AVIARY_OAUTH_ISSUER`) is the site's public URL; the MCP address is that plus `/mcp`. It defaults to `http://localhost:8080` locally and `https://aviary.danielibarra.com` on Heroku — set it on staging to the staging URL, or sign-in there points at production. @@ -163,12 +163,12 @@ Design and contract: [specs/004-public-aviary-stats/](specs/004-public-aviary-st The app is a small, conventional Spring MVC project under `src/main/java/com/example/AviaryService/`: -- **`controllers/UserController.java`** — every route: auth pages, the dashboard, timeline CRUD + reordering, hours updates, flight-log CRUD, the Garmin CSV parser, and "Complete Maintenance." -- **`entity/`** — `User`, `ServiceTimeline`, `FlightLog`, `DescriptionOption` (+ a `DTO/` for timeline updates). +- **`controllers/UserController.java`** — every route: auth pages, the dashboard, Status Sheet CRUD + reordering, hours updates, flight-log CRUD, the Garmin CSV parser, and "Complete Maintenance." +- **`entity/`** — `User`, `StatusSheetItem`, `FlightLog`, `DescriptionOption` (+ a `DTO/` for Status Sheet updates). - **`repositories/`** — Spring Data JPA repositories, all scoped by user. - **`config/`** — `SecurityConfig` (login/logout, BCrypt, per-route access, the `/mcp` bearer-token chain) and `DataSeeder` (the H2 demo data). - **`oauth/`** — the OAuth authorization server for MCP sign-in (client metadata documents, hashed token storage, token checks). -- **`mcp/`** — MCP tools; **`services/imports/`** + **`util/TimelineImportRules`** — import proposals, confirm, and the Import with AI page's connections. +- **`mcp/`** — MCP tools; **`services/imports/`** + **`util/StatusSheetImportRules`** — import proposals, confirm, and the Import with AI page's connections. - **`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/specs/SHARE_EXPORT_SPEC.md` but not yet built. diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md index b4f9b40..045e9e9 100644 --- a/docs/architecture/ARCHITECTURE.md +++ b/docs/architecture/ARCHITECTURE.md @@ -12,10 +12,10 @@ Spring Boot 3.4.3 · Java 21 · Spring MVC + Security + Data JPA · Thymeleaf · ## Shape (monolith) - **One controller** (`UserController`) holds every route. No service layer; controllers talk to repositories directly. - **4 JPA entities** → 4 tables, all scoped to a `User`. -- **3 Thymeleaf pages**: `login`, `register`, `dashboard`. The dashboard is the whole app (two tabs: Service Timeline + Log Book). +- **3 Thymeleaf pages**: `login`, `register`, `dashboard`. The dashboard is the whole app (two tabs: Status Sheet + Log Book). ## Request flow (a typical dashboard edit) -1. Browser loads `GET /dashboard` → `UserController` fetches the user's timelines, flight logs, hours, aircraft info → Thymeleaf renders `dashboard.html`. +1. Browser loads `GET /dashboard` → `UserController` fetches the user's Status Sheet items, flight logs, hours, aircraft info → Thymeleaf renders `dashboard.html`. 2. User edits a cell → `dashboard.js` debounces and `POST`s JSON via axios (with the Spring CSRF token from ``) to an endpoint like `/update/{id}`. 3. Controller updates the entity via the repository and returns JSON. 4. "Time Left" is computed **client-side** from the due date + current time in service hours. @@ -23,8 +23,8 @@ Spring Boot 3.4.3 · Java 21 · Spring MVC + Security + Data JPA · Thymeleaf · ## Cross-cutting concerns - **Auth:** Spring Security form login, BCrypt passwords, single `USER` role. See [BACKEND](BACKEND.md#auth). - **Per-user scoping:** every entity has a `user_id`; queries filter by the authenticated user. See [DATABASE](DATABASE.md). -- **AI assistants (MCP):** `/mcp` is an MCP server secured by Aviary's own OAuth authorization server (CIMD clients, PKCE, opaque hashed tokens). Assistants preview and import service timeline items; nothing is saved until the owner confirms. See [BACKEND](BACKEND.md#mcp-server--ai-assistant-sign-in). -- **Hours model:** flight logs roll up into `User.blockTimeHours` / `timeInServiceHours`, which maintenance due-dates count against. +- **AI assistants (MCP):** `/mcp` is an MCP server secured by Aviary's own OAuth authorization server (CIMD clients, PKCE, opaque hashed tokens). Assistants preview and import Status Sheet items; nothing is saved until the owner confirms. See [BACKEND](BACKEND.md#mcp-server--ai-assistant-sign-in). +- **Hours model:** flight logs roll up into `User.hobbsTimeHours` / `timeInServiceHours`, which maintenance due-dates count against. ## Known issues (high level — details in the area maps) - Local dev uses **in-memory H2** (data is lost on restart). See [DATABASE](DATABASE.md). diff --git a/docs/architecture/BACKEND.md b/docs/architecture/BACKEND.md index 9b3ae54..3e78612 100644 --- a/docs/architecture/BACKEND.md +++ b/docs/architecture/BACKEND.md @@ -28,25 +28,31 @@ | GET | `/register` | — | `register` view | | | POST | `/register` | `username`, `password` | redirect `/login` | trims username; requires username 3-50 chars `[A-Za-z0-9._-]`, password 8-72 chars; rejects duplicates | | GET | `/login` | — | `login` view | | -| GET | `/dashboard` | — | `dashboard` view | loads timelines, flight logs, hours, aircraft info for the auth user | -| POST | `/dashboard` | JSON timeline fields | row JSON or 302 | adds a Service Timeline row; assigns next `timelineOrder` | -| POST | `/update/{id}` | `TimelineUpdateDTO` | status JSON | partial update of a timeline row. Ownership checked (403 if not owner) | -| DELETE | `/delete/{id}` | — | 200 / 403 / 404 | deletes a timeline row. Ownership checked (403 if not owner) | -| POST | `/updateOrder` | `List` ids | void | reorders timelines; user-scoped, matches ids with `.equals` | -| POST | `/updateUserInfo` | JSON aircraft fields | status JSON | updates makeModel/tailNumber/ownerName/makeModelSN for auth user | -| POST | `/updateHours` | `blockTimeToAdd`/`timeInServiceToAdd`/`newBlockTime`/`newTimeInService` | hours JSON | set-or-add block time / time in service. 400 for NaN/Infinity, a negative set value, or an add that would go below 0 (checked before anything changes) | +| GET | `/dashboard` | — | `dashboard` view | loads Status Sheet items, flight logs, hours, aircraft info for the auth user | +| POST | `/dashboard` | JSON Status Sheet fields | row JSON or 302 | adds a Status Sheet row; assigns next `statusSheetOrder`. Spec 010: also takes `dueDateAuto`/`dueHoursAuto` from the add row; a part stays auto only if it equals Last Done + cycle; `"false"` with a blank value keeps a removed Due Date blank. | +| POST | `/update/{id}` | `StatusSheetItemUpdateDTO` (+ `dueDateTouched`, `dueHoursTouched`) | saved row JSON: `lastDoneDate`, `lastDoneHours`, `dueDateDate`, `dueDateHours`, `timeLeft`, `warnings` | update of a Status Sheet row. Ownership checked (403 if not owner). Auto-fills the Due Date from Last Done + cycle (spec 007, `DueDateAutoFill`); hours must be numbers (400 "Hours must be a number, e.g. 25.0"). Both touched flags missing = older dashboard.js, saved as sent. | +| GET | `/statusSheet/{id}/cyclePreview` | — | `{dueDateDate, dueDateHours, canReset, reason}` | what "Reset to cycle" would set (Last Done + cycle). Ownership checked (403). | +| POST | `/resetDueToCycle/{id}` | — | saved row JSON (same as `/update`) | sets Due Date = Last Done + cycle, keeps Last Done, marks it auto again. 400 with the reason when there is nothing to reset. Ownership checked (403). | +| GET | `/statusSheet/{id}/completePreview?doneDate=&doneHours=` | — | `{hasCalendar, hasHours, doneDate, doneHours, nextDueDate, nextDueHours, expectedDueDate, expectedDueHours, canSave, reason}` | spec 008: what the "When was this done?" box starts with (Due Date → Last Done + cycle → today; hours: Due hours → Last Done hours + cycle → empty) and the next Due Date for edited values. Ownership checked (403). | +| POST | `/statusSheet/addRowResolve` | JSON: previous + current Last Done / cycle, shown Due Date parts, `dueDateAuto`/`dueHoursAuto`, `dueDateTouched`/`dueHoursTouched` | `{dueDateDate, dueDateAuto, dueDateHours, dueHoursAuto, lastDoneHours, warnings}` | spec 010: what the add row's Due Date should show, using the same `DueDateAutoFill` rules as saved rows. Saves nothing. Uses `@CurrentAircraft` (ownership-checked) for the Time in Service note. | +| POST | `/completeMaintenance/{id}` | `{doneDate, doneHours, expectedDueDate, expectedDueHours}` | saved row JSON | spec 008: Last Done = done date / hours, Due = + cycle (only parts with a cycle and a value). **409** "This row changed. Open it again to review." if the stored Due Date differs from `expected*` (double-click, other tab). Empty body = older page: old today-based behavior. | +| DELETE | `/delete/{id}` | — | 200 / 403 / 404 | deletes a Status Sheet row. Ownership checked (403 if not owner) | +| POST | `/updateOrder` | `List` ids | void | reorders Status Sheet items; user-scoped, matches ids with `.equals` | +| POST | `/updateUserInfo` | JSON aircraft fields | status JSON | updates makeModel/tailNumber/operatorName/makeModelSN for auth user | +| POST | `/updateHours` | `hobbsTimeToAdd`/`timeInServiceToAdd`/`newHobbsTime`/`newTimeInService` | hours JSON | set-or-add Hobbs time / time in service. 400 for NaN/Infinity, a negative set value, or an add that would go below 0 (checked before anything changes) | | GET | `/flightlogs` | — | `List` JSON | auth user's logs | | POST | `/addflightlog` | `FlightLog` JSON | log + new totals JSON | recomputes hours via `calculateMergedHours` | | DELETE | `/deleteflightlog/{id}` | — | status + new totals | **ownership checked** (403 if not owner) | | DELETE | `/deleteOption/{id}` | — | text | description option; **ownership checked** (403 if not owner) | ## Key logic -- **`calculateMergedHours(logs, useBlockTime)`** — sums flight time across all logs by **merging overlapping intervals** so overlapping flights don't double-count. Block time uses `blockTimeOut`/`blockTimeIn`; time in service uses `timeInServiceOut`/`timeInServiceIn`. Result is written back to `User.blockTimeHours`/`timeInServiceHours` on add/delete of a log. -- **`saveCustomDescriptionOption`** — persists a user's custom Service Timeline "Description" values so they reappear in the dropdown. -- **Hours "last updated" stamps:** `/updateHours` sets `blockTimeUpdatedAt`/`timeInServiceUpdatedAt` (UTC `Instant`) + `*UpdatedSource = "manual"` for whichever value changed; `/addflightlog` and `/deleteflightlog` set both with source `"flightlog"`. `GET /dashboard` passes the 4 values (timestamps as ISO strings) to the view, which renders them in the browser's local time. +- **`calculateMergedHours(logs, useHobbsTime)`** — sums flight time across all logs by **merging overlapping intervals** so overlapping flights don't double-count. Hobbs time uses `hobbsTimeOut`/`hobbsTimeIn`; time in service uses `timeInServiceOut`/`timeInServiceIn`. Result is written back to `User.hobbsTimeHours`/`timeInServiceHours` on add/delete of a log. +- **`saveCustomDescriptionOption`** — persists a user's custom Status Sheet "Description" values so they reappear in the dropdown. +- **Hours "last updated" stamps:** `/updateHours` sets `hobbsTimeUpdatedAt`/`timeInServiceUpdatedAt` (UTC `Instant`) + `*UpdatedSource = "manual"` for whichever value changed; `/addflightlog` and `/deleteflightlog` set both with source `"flightlog"`. `GET /dashboard` passes the 4 values (timestamps as ISO strings) to the view, which renders them in the browser's local time. ## Time Left + PDF -- `DueDates.formatTimeLeft(dueDate, dueHours, today, currentTimeInService)` is the one server-side Time Left formatter (smart format, see [FRONTEND](FRONTEND.md)). Used by `PdfExportService` (computed at render time — the stored `timeLeft` column goes stale) and `/completeMaintenance/{id}`. +- `DueDates.formatTimeLeft(dueDate, dueHours, today, currentTimeInService)` is the one server-side Time Left formatter (one line, parts joined by " · ", "hrs": `2 mo 12 days left · 480 hrs overdue`, spec 011; `calculateTimeLeft` in dashboard.js and the Excel formula match) (smart format, see [FRONTEND](FRONTEND.md)). Used by `PdfExportService` (computed at render time — the stored `timeLeft` column goes stale) and `/completeMaintenance/{id}`. +- `DueDateAutoFill` (spec 007) decides the Due Date to save when Last Done or the cycle changes: date = `DueDates.nextDueDate` (same as Complete Maintenance, exact day), hours = Last Done + cycle hours. Owner-typed Due Dates are kept (`dueDateAuto` / `dueHoursAuto` = FALSE). Also the one hours formatter for Last Done / Due Date (`formatHours`: 1–3 decimals, `25` → `25.0`). Unit tests: `DueDateAutoFillTest`; endpoint tests: `StatusSheetAutoFillTest`. - `GET /pdf?today=yyyy-MM-dd` — optional browser date, trusted only within ±1 day of the server date. PDF includes a Date column for flights (UTC date of block/service start) and prints hours with at least one decimal. ## Local demo data @@ -56,8 +62,8 @@ Aviary is an MCP server at `POST /mcp` (Spring AI, Streamable HTTP, SYNC) and its own OAuth authorization server, so AI assistants sign in as an owner. - **Sign-in:** authorization code + PKCE (S256 only), public clients only. Assistants identify with a **Client ID Metadata Document**: `client_id` is an https URL that `CimdFetcher` downloads (SSRF-guarded: https, no IP literals, no private/loopback/link-local DNS, no redirects, 5 KB, 5 s) and `CimdRegisteredClientRepository` turns into a client (cached 1 h). Dynamic Client Registration is off. Loopback redirect URIs may use any port (`AuthorizationServerConfig.validateRedirectUri`). Owner approves on `/oauth2/consent` (`ConsentController`). - **Tokens:** opaque, 7 days, no refresh tokens (Spring Authorization Server 1.4 gives public clients none). Stored by `JpaOAuth2AuthorizationService` in `oauth_authorizations` with token values **SHA-256 hashed**. `LocalOpaqueTokenIntrospector` checks every `/mcp` call against that table, so **Disconnect** (`/account/connections`, deletes the row) cuts an assistant off on its next request. No/dead token → 401 with `WWW-Authenticate: Bearer resource_metadata=…`; token without `aviary.read` → 403. -- **Tools** (`mcp/`): `list_flights`, `get_import_format`, `list_service_timeline`, `propose_timeline_import`, `continue_poor_fit`, `confirm_timeline_import`. Each checks its scope and gets the owner from `McpCurrentUser` (the token's user — never a parameter). -- **Import:** `TimelineImportService` + pure `util/TimelineImportRules`. Propose stores an `import_proposals` row (24 h, one open per owner) and changes nothing; confirm adds exactly the proposed rows after the existing ones in one transaction (all or nothing), never edits existing rows, skips name matches unless the owner opts in, and writes a `timeline_import_records` row. Rate limits: 30 proposals / 10 confirms per owner per hour. +- **Tools** (`mcp/`): `list_flights`, `get_import_format`, `list_status_sheet`, `propose_status_sheet_import`, `continue_poor_fit`, `confirm_status_sheet_import`. Each checks its scope and gets the owner from `McpCurrentUser` (the token's user — never a parameter). +- **Import:** `StatusSheetImportService` + pure `util/StatusSheetImportRules`. Propose stores an `import_proposals` row (24 h, one open per owner) and changes nothing; confirm adds exactly the proposed rows after the existing ones in one transaction (all or nothing), never edits existing rows, skips name matches unless the owner opts in, and writes a `timeline_import_records` row. Rate limits: 30 proposals / 10 confirms per owner per hour. ## Input limits & rate limits - **Text length:** every text column is varchar(255). `Validation.maxLength` checks item/description/aircraft fields/airports/description options up front and returns a 400 with a readable message; `GlobalExceptionHandler` catches anything missed. The AeroAPI key is capped at 100 chars (it's stored encrypted, which roughly doubles its length). @@ -66,7 +72,7 @@ Aviary is an MCP server at `POST /mcp` (Spring AI, Streamable HTTP, SYNC) and it - Unexpected exceptions in `/update/{id}` and `/updateHours` are logged and return a generic message instead of `e.getMessage()`. ## Known issues -- **(FIXED 2026-05-25) IDOR / broken access control:** `/update/{id}` and `/delete/{id}` now load the authenticated user and return 403 unless `timeline.getUser().getId()` matches — same ownership pattern as `/deleteflightlog` and `/deleteOption`. +- **(FIXED 2026-05-25) IDOR / broken access control:** `/update/{id}` and `/delete/{id}` now load the authenticated user and return 403 unless `Status Sheet.getUser().getId()` matches — same ownership pattern as `/deleteflightlog` and `/deleteOption`. - **(FIXED 2026-05-25) `updateOrder` id comparison:** now uses `t.getId().equals(id)` instead of `==` (reference compare). - **No regression test yet** for the ownership checks — worth adding (user A cannot mutate user B's rows → expect 403). - **Debug logging:** many `System.out.println` calls (incl. a per-login timing print in `SecurityConfig`). Replace with the SLF4J `log` or remove. diff --git a/docs/architecture/DATABASE.md b/docs/architecture/DATABASE.md index c8a2d7d..f066d75 100644 --- a/docs/architecture/DATABASE.md +++ b/docs/architecture/DATABASE.md @@ -12,29 +12,33 @@ All ids are `@GeneratedValue(IDENTITY)`. Every row belongs to a `User` via `user ### `users` (`User`) `id`, `username` (unique, not null), `password` (BCrypt, not null), `aeroApiKey` (encrypted, see `AeroApiKeyConverter`; one key per account), `last_viewed_aircraft_id` (FK → `aircraft`, nullable — the aircraft the dashboard opens on). -One-to-many (cascade ALL) → `aircraft`, `serviceTimeline`, `flightLogs`. +One-to-many (cascade ALL) → `aircraft`, `statusSheet`, `flightLogs`. **Legacy columns (kept, unmapped):** `block_time_hours`, `time_in_service_hours`, `make_model`, `tail_number`, `owner_name`, `make_modelsn`, both `*_updated_at`, both `*_updated_source`, both `*_manual_baseline`. These held the single aircraft before fleets. `AircraftBackfill` copies them into each account's first aircraft on boot; nothing else reads them. They stay one release so a rollback still works, then get dropped (see `docs/migrations/2026-11-09_multi_aircraft.sql`). ### `aircraft` (`Aircraft`) -`id`, `user_id` (not null), `tailNumber` (upper-cased, spaces removed), `tail_number_key` (comparison key, null when blank; unique with `user_id`), `makeModel`, `ownerName`, `makeModelSN`, `blockTimeHours` / `timeInServiceHours` (Double), `blockTimeManualBaseline` / `timeInServiceManualBaseline` (Double, manually-set floor so log activity can't silently lower the displayed total), `blockTimeUpdatedAt` / `timeInServiceUpdatedAt` (`Instant`), `blockTimeUpdatedSource` / `timeInServiceUpdatedSource` ("manual" | "flightlog"), `createdAt`. One airplane in the owner's fleet; at most 25 per user, at least 1. +`id`, `user_id` (not null), `tailNumber` (upper-cased, spaces removed), `tail_number_key` (comparison key, null when blank; unique with `user_id`), `makeModel`, `operatorName` (column `owner_name`; renamed in code Nov 2026, spec 009 — `OperatorColumnMappingTest` guards the pin), `makeModelSN`, `hobbsTimeHours` / `timeInServiceHours` (Double), `hobbsTimeManualBaseline` / `timeInServiceManualBaseline` (Double, manually-set floor so log activity can't silently lower the displayed total), `hobbsTimeUpdatedAt` / `timeInServiceUpdatedAt` (`Instant`), `hobbsTimeUpdatedSource` / `timeInServiceUpdatedSource` ("manual" | "flightlog"), `createdAt`. One airplane in the owner's fleet; at most 25 per user, at least 1. -### `service_timelines` (`ServiceTimeline`) -`id`, `item`, `isTitle` (boolean — title row vs item row), `description`, `cycle`, `lastDone`, `dueDate`, `timeLeft`, `timelineOrder` (Integer, display order **within one aircraft**), `user_id`, `aircraft_id`. +### `service_timelines` (`StatusSheetItem`) +`id`, `item`, `isTitle` (boolean — title row vs item row), `description`, `cycle`, `cycleCalendarValue` + `cycleCalendarUnit` (DAYS | MONTHS | YEARS), `cycleHours`, `lastDoneDate`, `lastDoneHours`, `dueDateDate`, `dueDateHours` (hours stored as text in the `25.0` format, 1–3 decimals; legacy non-numeric text kept as is), `dueDateAuto`, `dueHoursAuto` (Boolean, nullable — spec 007: TRUE = Due Date part auto-filled from Last Done + cycle, FALSE = typed by the owner and never overwritten, null = row from before Nov 2026, decided by comparing with the cycle math), `timeLeft`, `statusSheetOrder` (Integer, display order **within one aircraft**), `user_id`, `aircraft_id`. + +**Status Sheet keeps its old storage names.** `StatusSheetItem` is pinned to table `service_timelines` and `statusSheetOrder` to column `timeline_order`; `StatusSheetImportRecord` to `timeline_import_records`. The Nov 2026 rename changed only the Java names, so no data moved. `StatusSheetColumnMappingTest` guards this. ### `flight_logs` (`FlightLog`) -`id`, `fromAirport`, `toAirport`, `blockTimeIn`, `blockTimeOut`, `timeInServiceIn`, `timeInServiceOut` (all Double, nullable), `blockTimeStart`, `blockTimeEnd` (`Instant`, nullable — engine start/stop, UTC), `timeInServiceStart`, `timeInServiceEnd` (`Instant`, nullable — wheels-off/wheels-on, UTC), `source` (String "manual" | "csv" | "aeroapi", nullable — see `FlightLog.getEffectiveSource()` and `HoursService.recomputeChain`), `faFlightId` (String, nullable — set only when the row came from an accepted `FlightSuggestion`), `user_id`, `aircraft_id`. Hours math only ever looks at one aircraft's flights. +`id`, `fromAirport`, `toAirport`, `hobbsTimeIn`, `hobbsTimeOut`, `timeInServiceIn`, `timeInServiceOut` (all Double, nullable), `hobbsTimeStart`, `hobbsTimeEnd` (`Instant`, nullable — engine start/stop, UTC), `timeInServiceStart`, `timeInServiceEnd` (`Instant`, nullable — wheels-off/wheels-on, UTC), `source` (String "manual" | "csv" | "aeroapi", nullable — see `FlightLog.getEffectiveSource()` and `HoursService.recomputeChain`), `faFlightId` (String, nullable — set only when the row came from an accepted `FlightSuggestion`), `user_id`, `aircraft_id`. Hours math only ever looks at one aircraft's flights. + +**Hobbs columns keep their old names.** In `aircraft` and `flight_logs`, every `hobbsTime*` field is pinned with `@Column(name = "block_time_…")` (e.g. `hobbsTimeHours` → `block_time_hours`, `hobbsTimeOut` → `block_time_out`). The Nov 2026 rename changed only the Java names, so no data moved. Do not remove those pins: `ddl-auto=update` would add new, empty `hobbs_time_*` columns. `HobbsColumnMappingTest` guards this. ### `description_options` (`DescriptionOption`) -`id`, `option` (not null), `user_id`. Stores a user's custom Service Timeline description choices. +`id`, `option` (not null), `user_id`. Stores a user's custom Status Sheet description choices. ### `flight_suggestions` (`FlightSuggestion`) `id`, `tailNumber`, `faFlightId` (unique per user), `departureTime`, `arrivalTime` (`Instant`), `origin`, `destination`, `status` (String "pending" | "accepted" | "dismissed"), `createdAt`, `user_id`, `aircraft_id` (the aircraft whose subscription found it). AeroAPI-detected flights awaiting a user decision — see `docs/ADSB_SYNC_SPEC.md`. ### `import_proposals` (`ImportProposal`) -`id`, `user_id` (not null), `status` ("OPEN" | "NEEDS_FIT_CONFIRMATION" | "CONFIRMED" | "REPLACED" | "EXPIRED"), `itemsJson` / `rejectedJson` (TEXT, JSON lists), `submittedCount`, `createdAt`, `expiresAt` (+24 h), `confirmedAt`, `connectionClientId`, `aircraft_id` (target aircraft; null after that aircraft is removed). An AI assistant's previewed timeline import; at most one OPEN/NEEDS_FIT_CONFIRMATION per user per aircraft. +`id`, `user_id` (not null), `status` ("OPEN" | "NEEDS_FIT_CONFIRMATION" | "CONFIRMED" | "REPLACED" | "EXPIRED"), `itemsJson` / `rejectedJson` (TEXT, JSON lists), `submittedCount`, `createdAt`, `expiresAt` (+24 h), `confirmedAt`, `connectionClientId`, `aircraft_id` (target aircraft; null after that aircraft is removed). An AI assistant's previewed Status Sheet import; at most one OPEN/NEEDS_FIT_CONFIRMATION per user per aircraft. -### `timeline_import_records` (`TimelineImportRecord`) +### `timeline_import_records` (`StatusSheetImportRecord`) `id`, `user_id` (not null), `proposalId`, `clientId`, `clientName`, `itemCount`, `importedAt`, `aircraftLabel` (tail number at import time, text). One row per confirmed import; shown on Connected assistants. ### `subscriptions` (`Subscription`) @@ -47,7 +51,7 @@ String `id`, `registeredClientId` (assistant's CIMD URL), `principalName` (usern Composite key (`registeredClientId`, `principalName`), `authorities`. Approved scopes per assistant per owner. ## Relationships -`User` 1—* `Aircraft` (1..25). `Aircraft` 1—* `ServiceTimeline`, `FlightLog`, `FlightSuggestion`; 0..1 `Subscription`. Child rows keep `user_id` too, so ownership checks never depend on a join; services keep `row.user == row.aircraft.user`. `User` 1—* `DescriptionOption`, alert settings and recipients stay account-wide. `User` 1—* `ServiceTimeline`, `FlightLog` are cascade ALL with JSON managed/back references. +`User` 1—* `Aircraft` (1..25). `Aircraft` 1—* `StatusSheetItem`, `FlightLog`, `FlightSuggestion`; 0..1 `Subscription`. Child rows keep `user_id` too, so ownership checks never depend on a join; services keep `row.user == row.aircraft.user`. `User` 1—* `DescriptionOption`, alert settings and recipients stay account-wide. `User` 1—* `StatusSheetItem`, `FlightLog` are cascade ALL with JSON managed/back references. ## Boot-time backfill `config/AircraftBackfill` runs before the seeders on every boot: it drops the old `subscriptions(user_id)` unique constraint and, for each user without an aircraft, creates one from the legacy `users` columns and sets `aircraft_id` on that user's rows where it is null. Idempotent; logs `Aircraft backfill: N users, M rows attached`. The `aircraft_id` columns are nullable in the schema only because `ddl-auto=update` can't add NOT NULL to a populated table. @@ -56,7 +60,7 @@ Composite key (`registeredClientId`, `principalName`), `authorities`. Approved s - `UserRepository.findByUsername` - `AircraftRepository.findByIdAndUser` (the only way to load a client-supplied aircraft id) / `findByUserOrderByIdAsc` - `FlightLogRepository.findByAircraft` -- `ServiceTimelineRepository.findByAircraftOrderByTimelineOrderAsc` / `findMaxTimelineOrderByAircraft` (`@Query` for max order) / `findByUserOrderByAircraftIdAscTimelineOrderAsc` (whole fleet, for alerts and picker counts) +- `StatusSheetItemRepository.findByAircraftOrderByStatusSheetOrderAsc` / `findMaxStatusSheetOrderByAircraft` (`@Query` for max order) / `findByUserOrderByAircraftIdAscStatusSheetOrderAsc` (whole fleet, for alerts and picker counts) - `DescriptionOptionRepository.findByUser` ## Gotchas diff --git a/docs/architecture/FRONTEND.md b/docs/architecture/FRONTEND.md index 59091c8..4fc50b9 100644 --- a/docs/architecture/FRONTEND.md +++ b/docs/architecture/FRONTEND.md @@ -12,9 +12,9 @@ Each stylesheet defines the same CSS-variable palette (`--primary` green `#2C9B6 ## Dashboard structure - Fixed header (logo, **Share** menu, logout, settings gear). Share is a popover card (`.share-dropdown`, toggled via `hidden` + `aria-expanded` by `setShareOpen()` in `dashboard.js`): Print, Download PDF, then a divider and Email/Text marked with a "Soon" pill (`.share-coming-soon`). Closes on outside click, Escape, or picking an item; Arrow keys move between items. Styled with theme tokens so it works in dark mode. -- "My Hours" card: shows block time and time in service, each with a small muted "last updated" line under it (`.hours-block` / `.hours-updated`) — local date + time + relative ("2 days ago") + source ("you edited it" / "from a flight log"). Edit panel can **set** or **add** hours. -- Two tabs: **Service Timeline** and **Log Book**. -- Service Timeline table: drag-reorder (SortableJS via grip handle), title rows vs item rows, a custom Description dropdown (with add/remove custom options), and a Calendar/Clock picker for Last Done / Due Date. "Time Left" is computed client-side. +- "My Hours" card: shows Hobbs time and time in service, each with a small muted "last updated" line under it (`.hours-block` / `.hours-updated`) — local date + time + relative ("2 days ago") + source ("you edited it" / "from a flight log"). Edit panel can **set** or **add** hours. +- Two tabs: **Status Sheet** and **Log Book**. +- Status Sheet table: drag-reorder (SortableJS via grip handle), title rows vs item rows, a custom Description dropdown (with add/remove custom options), and a Calendar/Clock picker for Last Done / Due Date. "Time Left" is computed client-side. It is drawn as colored pills by `setTimeLeftText` (spec 011): one pill per limit, no icons ("45 d", "480 h"), green / amber (within the user's alert lead time, `data-lead-days` / `data-lead-hours` on `#sortable-info-table`) / red, and the word "overdue" after an overdue pill (once if both). The plain words stay on the cell (`data-plain` + print-only `.tl-plain`) for saving, the add row, print and Excel. After a row saves, `applySavedRow` shows what the server saved, so an auto-filled Due Date appears without a reload (never rewriting a box the owner is typing in). Hours boxes tidy to 1–3 decimals on blur (`formatSheetHours`, same rule as the server). `rowDueTouched` tells the server when the owner edited a Due Date part themselves. Typo warnings render in `.row-warning` under Last Done. The row's roll-forward button opens `showChoice` with **Mark complete** and **Reset to cycle (date)**; it first calls `flushRowSave` so pending edits are saved, then `GET /statusSheet/{id}/cyclePreview` to fill and enable the Reset choice. Choosing Mark complete opens `openDoneBox` ("When was this done?"): prefilled from `completePreview`, live "Next due" (250 ms debounced preview), Save disabled while saving, toast built from the saved values. The add row (not saved yet) keeps its own `addRowState` (previous inputs, auto/typed per Due Date part) and calls `POST /statusSheet/addRowResolve` (250 ms debounced) so its Due Date fills before Add; typing or Remove in its Due Date makes that part the user's; the flags go with the Add request; `resetAddRowState` after Add. No Mark complete / Reset / background saving in the add row. - Log Book table: existing rows are **readonly**; an add-row appends a flight. ## `dashboard.js` patterns (~1400 lines, one file) @@ -28,7 +28,7 @@ Each stylesheet defines the same CSS-variable palette (`--primary` green `#2C9B6 - **Last Done / Due Date menu** buttons read Add / Remove (state is the button text). Removing a field that has a value takes two taps: the first arms it as a red "Remove?" (`.confirm-remove`), the second removes it and auto-saves; reopening the menu disarms it (`disarmRemoveButton`). Empty fields remove on one tap. - **`[hidden]` always wins** (`[hidden] { display: none !important; }` at the top of `dashboardstyle.css`). Toggle visibility with `el.hidden`; rules like `.settings-table tr { display: flex }` used to override the attribute and show hidden rows. - **Mobile (≤960px) Settings**: each row stacks the label above a full-width, wrapping value area with 42px controls. -- **Mobile (≤960px) Service Timeline** renders each row as a card (`dashboardstyle.css`, "Service Timeline cards"). Saved cards and the add card share the same rules via `#sortable-info-table :is(.sortable tr:not(.title-row), .add-row)`; spacing/tap size are CSS variables on `#sortable-info-table` (`--cell-px`, `--cell-py`, `--tap`) and are fluid down to ~300px. There are deliberately no breakpoints below 960px. +- **Mobile (≤960px) Status Sheet** renders each row as a card (`dashboardstyle.css`, "Status Sheet cards"). Saved cards and the add card share the same rules via `#sortable-info-table :is(.sortable tr:not(.title-row), .add-row)`; spacing/tap size are CSS variables on `#sortable-info-table` (`--cell-px`, `--cell-py`, `--tap`) and are fluid down to ~300px. There are deliberately no breakpoints below 960px. - **Notifications:** `showToast()` / `showConfirm()` replaced native `alert()`/`confirm()`. - **Hours "last updated":** `formatUpdated(iso, source)` + `relativeTime()` render the My Hours freshness lines in the browser's local timezone (server stores UTC). `renderUpdatedFromData()` on load (reads `data-updated`/`data-source` attrs); `markUpdatedNow()` after a live change. Uses `textContent`, not `innerHTML`. - **Excel export:** `exportToExcel()` (SheetJS) is implemented but its button is commented out in `dashboard.html` (intentionally hidden). @@ -49,4 +49,4 @@ Each stylesheet defines the same CSS-variable palette (`--primary` green `#2C9B6 ## Import with AI page - `GET /account/connections` (`connections.html`): titled "Import with AI". An always-visible connect box shows this site's MCP address (`mcpUrl` = `aviary.oauth.issuer` + `/mcp`, so staging shows staging's), a Copy button (`js/connections.js`, falls back to selecting the address), three steps, the per-assistant "where to find it" list (`fragments/assistant-hints.html` — one line per assistant, update there when an app moves its menu), and what to do next. The connected-assistant list and recent imports sit below under "Connected assistants". -- Dashboard entry points: header `#connections-link` (robot icon + "Import with AI"; text hidden under 420px, `aria-label` kept) and `#import-ai-prompt` above the empty Service Timeline (server-rendered only when there are no rows; `dashboard.js` removes it via a MutationObserver when the first row is added). Both are `no-print`. +- Dashboard entry points: header `#connections-link` (robot icon + "Import with AI"; text hidden under 420px, `aria-label` kept) and `#import-ai-prompt` above the empty Status Sheet (server-rendered only when there are no rows; `dashboard.js` removes it via a MutationObserver when the first row is added). Both are `no-print`. diff --git a/docs/architecture/project_structure.text b/docs/architecture/project_structure.text index 20e94a8..103f848 100644 --- a/docs/architecture/project_structure.text +++ b/docs/architecture/project_structure.text @@ -44,12 +44,12 @@ - entity - DescriptionOption.class - DTO - - TimelineUpdateDTO.class - - ServiceTimeline.class + - StatusSheetItemUpdateDTO.class + - StatusSheetItem.class - User.class - repositories - DescriptionOptionRepository.class - - ServiceTimelineRepository.class + - StatusSheetItemRepository.class - UserRepository.class - static - css @@ -85,12 +85,12 @@ - entity - DescriptionOption.class - DTO - - TimelineUpdateDTO.class - - ServiceTimeline.class + - StatusSheetItemUpdateDTO.class + - StatusSheetItem.class - User.class - repositories - DescriptionOptionRepository.class - - ServiceTimelineRepository.class + - StatusSheetItemRepository.class - UserRepository.class - test - com @@ -189,12 +189,12 @@ - entity - DescriptionOption.java - DTO - - TimelineUpdateDTO.java - - ServiceTimeline.java + - StatusSheetItemUpdateDTO.java + - StatusSheetItem.java - User.java - repositories - DescriptionOptionRepository.java - - ServiceTimelineRepository.java + - StatusSheetItemRepository.java - UserRepository.java - resources - application-heroku.properties diff --git a/docs/backend-notes/TRANSACTIONAL.md b/docs/backend-notes/TRANSACTIONAL.md index 75a79c1..8198251 100644 --- a/docs/backend-notes/TRANSACTIONAL.md +++ b/docs/backend-notes/TRANSACTIONAL.md @@ -64,7 +64,7 @@ for shredding — including A's work. |---|---| | `services/HoursService.java` | `updateHours` | | `services/UserService.java` | `registerUser`, `updateUserInfo` | -| `services/TimelineService.java` | `addTimeline` | +| `services/StatusSheetService.java` | `addStatusSheet` | | `services/DescriptionOptionService.java` | `saveCustomDescriptionOption`, `addOption`, `deleteOption`, `cleanupAndLoadDescriptionOptions` | | `services/SubscriptionService.java` | `toggle` | @@ -72,7 +72,7 @@ for shredding — including A's work. | File | Method | |---|---| -| `controllers/UserController.java` | `updateTimeline`, `addFlightLog`, `completeMaintenance`, `addDescriptionOption`, `deleteFlightLog` | +| `controllers/UserController.java` | `updateStatusSheet`, `addFlightLog`, `completeMaintenance`, `addDescriptionOption`, `deleteFlightLog` | ### The clearest example of why it matters @@ -82,14 +82,14 @@ for shredding — including A's work. flightLogRepository.delete(log); // 1. remove the log List remainingLogs = flightLogRepository.findByUser(user); -double newBlockTime = hoursService.recomputeChain(user, true); +double newHobbsTime = hoursService.recomputeChain(user, true); double newTimeInService = hoursService.recomputeChain(user, false); -user.setBlockTimeHours(newBlockTime); +user.setHobbsTimeHours(newHobbsTime); ... userRepository.save(user); // 2. recompute the hours ``` -If step 1 commits and step 2 does not, the aircraft has a deleted flight but stale block time +If step 1 commits and step 2 does not, the aircraft has a deleted flight but stale Hobbs time and time in service hours on screen. That is the exact bug class the recent commits have been fixing. `@Transactional` is what guarantees both or neither. @@ -130,7 +130,7 @@ public ResponseEntity<...> updateHours(...) { // no @Transactional here } ``` -**Leaky — `UserController.updateTimeline` and `UserController.deleteFlightLog`.** Both +**Leaky — `UserController.updateStatusSheet` and `UserController.deleteFlightLog`.** Both carry `@Transactional` *and* wrap their whole body in `catch (Exception e)`. The exception never escapes, so the foreman files the work order regardless. In `deleteFlightLog` that means the delete can commit while the hours recomputation failed — a 500 goes to the @@ -141,7 +141,7 @@ controllers catch and format the response. ### 2. Nested transactional calls share one transaction -`UserController.updateTimeline` calls `descriptionOptionService.saveCustomDescriptionOption`, +`UserController.updateStatusSheet` calls `descriptionOptionService.saveCustomDescriptionOption`, which is itself `@Transactional`. It does not get its own transaction — it joins the controller's. @@ -156,7 +156,7 @@ Calling a `@Transactional` method from another method in the *same class* skips entirely, so no transaction is opened, silently. This codebase is currently safe — every call crosses a bean boundary (controller → service, -or `TimelineService` → `descriptionOptionService`). Worth remembering before moving a +or `StatusSheetService` → `descriptionOptionService`). Worth remembering before moving a transactional method's caller into the same class. ### 4. `@Transactional` on a controller holds the connection too long @@ -188,7 +188,7 @@ Run the app: (`-Pdev` is defined in `build.gradle` and serves templates/CSS live from `src/` so frontend edits show without a rebuild.) -Then log in and change the block time hours. Expect log lines like: +Then log in and change the Hobbs time hours. Expect log lines like: ``` Getting transaction for [com.example.AviaryService.services.HoursService.updateHours] @@ -202,8 +202,8 @@ Two experiments worth doing once: - **See a rollback.** Call the update-hours endpoint with all four parameters empty. `HoursService` throws `IllegalArgumentException`, and the log should show `Initiating transaction rollback` instead of commit. -- **See transactions nest.** Save a timeline row with a brand-new custom description. - `updateTimeline` calls `saveCustomDescriptionOption`, which is also `@Transactional`. +- **See transactions nest.** Save a Status Sheet row with a brand-new custom description. + `updateStatusSheet` calls `saveCustomDescriptionOption`, which is also `@Transactional`. The log should show `Participating in existing transaction` — trap 2, visible. To see the SQL landing between the begin and commit lines, flip diff --git a/docs/planning/SERVICE_LAYER_PLAN.md b/docs/planning/SERVICE_LAYER_PLAN.md index d372bf2..3b68ab8 100644 --- a/docs/planning/SERVICE_LAYER_PLAN.md +++ b/docs/planning/SERVICE_LAYER_PLAN.md @@ -38,7 +38,7 @@ from a scheduled job or tested without web types. Look at which repository a method touches. Everything hitting `flightLogRepository` belongs to one service; everything hitting -`serviceTimelineRepository` to another. That is usually the natural seam. +`statusSheetRepository` to another. That is usually the natural seam. ## The five services @@ -77,17 +77,17 @@ Uses `descriptionOptionRepository`. Uses `userRepository`. Holds the floor rule — displayed hours may rise, never fall. -### 4. TimelineService (~220 lines) +### 4. StatusSheetService (~220 lines) | Method | Line | Size | |---|---|---| | `completeMaintenance` | 698 | 69 | -| `updateTimeline` | 306 | 59 | -| `addTimeline` | 143 | 57 | +| `updateStatusSheet` | 306 | 59 | +| `addStatusSheet` | 143 | 57 | | `updateOrder` | 406 | 19 | -| `deleteTimeline` | 365 | 14 | +| `deleteStatusSheet` | 365 | 14 | -Uses `serviceTimelineRepository`. +Uses `statusSheetRepository`. ### 5. FlightLogService (~290 lines) @@ -155,7 +155,7 @@ Smallest first, so the pattern is second nature before the hard ones. 1. `UserService` — 2 methods, practice run 2. `DescriptionOptionService` — 4 small methods 3. `HoursService` — self-contained math -4. `TimelineService` — bigger, more entangled +4. `StatusSheetService` — bigger, more entangled 5. `FlightLogService` — biggest payoff, do it last **One service at a time, compile after each.** A 965-line rewrite in one pass with diff --git a/docs/specs/ADSB_DATA_SOURCE.md b/docs/specs/ADSB_DATA_SOURCE.md index 6ed8e8e..bf1748d 100644 --- a/docs/specs/ADSB_DATA_SOURCE.md +++ b/docs/specs/ADSB_DATA_SOURCE.md @@ -130,7 +130,7 @@ Each has three variants — `scheduled_`, `estimated_`, `actual_`. **Use `actual only**; the others are predictions. > **`actual_off` → `actual_on` is the flight.** Duration = the difference between -> them. This is *airborne* time, not block time. +> them. This is *airborne* time, not Hobbs time. #### Fields we use diff --git a/docs/specs/ADSB_SYNC_SPEC.md b/docs/specs/ADSB_SYNC_SPEC.md index bd5fd46..663d14a 100644 --- a/docs/specs/ADSB_SYNC_SPEC.md +++ b/docs/specs/ADSB_SYNC_SPEC.md @@ -12,7 +12,7 @@ License forbids mixing it with another real-time flight data provider. | Field | What it is | Source | |---|---|---| -| **Block Time** | engine-on to engine-off | manual entry only | +| **Hobbs Time** | engine-on to engine-off | manual entry only | | **Time in Service** | wheels-off to wheels-on (the real maintenance clock) | manual entry, CSV upload, or AeroAPI | AeroAPI's `actual_off`/`actual_on` map directly to Time in Service. It's just a @@ -40,7 +40,7 @@ suggestion until the user presses Add — nothing writes itself. for that as a possible future feature. 4. New flights are saved as `FlightSuggestion` rows, `pending`. 5. They show up as a banner on the Log Book tab. **Add** creates a real - `FlightLog` row (airports + departure/arrival time; Block Time is left + `FlightLog` row (airports + departure/arrival time; Hobbs Time is left blank and Time in Service is filled in from the flight's airborne duration) and flips the suggestion to `accepted`. **Dismiss** flips it to `dismissed`. Both are permanent — an diff --git a/docs/specs/ALERTS_SPEC.md b/docs/specs/ALERTS_SPEC.md index f4ae117..93eae2e 100644 --- a/docs/specs/ALERTS_SPEC.md +++ b/docs/specs/ALERTS_SPEC.md @@ -3,7 +3,7 @@ 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 +when a Status Sheet 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. @@ -18,13 +18,13 @@ for this tail". This is a different concern with its own entities. 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**: +- On a check, every non-title item on the Status Sheet 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`) +- Each item stores the level it **last alerted at** (`StatusSheetItem.alertLevel`) and when (`alertLastFiredAt`). - A digest is sent only if **either**: 1. some item moved to a worse level than it last alerted at, **or** @@ -43,7 +43,7 @@ settings, and a readiness line. Backed by `PUT /alerts/preferences`. `GET /alerts/preferences` → `readiness.missing`: - "Add at least one maintenance item" - "Set your tail number" - - "Set your owner name" + - "Set your operator 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 @@ -63,7 +63,7 @@ settings, and a readiness line. Backed by `PUT /alerts/preferences`. | `confirmToken` | random URL-safe token, unique | | `createdAt`, `confirmedAt`, `reminderSentAt` | timestamps | -Flow: **add → PENDING** → confirm email sent ("[owner name] added you to receive +Flow: **add → PENDING** → confirm email sent ("[operator 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. @@ -71,7 +71,7 @@ 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 +2. Owner has an **operator 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: @@ -111,10 +111,10 @@ nothing is saved. - **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). + 106 days left` → aircraft hours (Hobbs 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 +- **Footer:** "You're receiving this because [operator name] added you to maintenance alerts for [tail]. The full dashboard is attached as a PDF." + unsubscribe link (`/alerts/unsubscribe?token=…`) + postal address if configured (CAN-SPAM). **No dashboard link:** recipients have no login. @@ -132,7 +132,7 @@ Per-user defaults in `AlertPreference`: `leadTimeDays` (30), `leadTimeHours` `overdueRenudgeDays` (7, min 1), `lastCheckedOn` (LocalDate, null), `baselineSentAt` (Instant, null). - **`AlertRecipient`** — as table above. -- **`ServiceTimeline`** has `alertLevel` (String, nullable) and +- **`StatusSheetItem`** has `alertLevel` (String, nullable) and `alertLastFiredAt` (Instant, nullable). - **`AlertSendLog`** — `recipientId`, `channel`, `sentAt`. Backs the digest rate limit. Rows older than 30 days are pruned. diff --git a/docs/specs/SHARE_EXPORT_SPEC.md b/docs/specs/SHARE_EXPORT_SPEC.md index 0104f48..493ed57 100644 --- a/docs/specs/SHARE_EXPORT_SPEC.md +++ b/docs/specs/SHARE_EXPORT_SPEC.md @@ -88,14 +88,14 @@ intentionally bypass all of it. Scope applies to **all four actions, including Print**: -- **This tab** (default) — only the active tab (Service Timeline *or* Log Book). +- **This tab** (default) — only the active tab (Status Sheet *or* Log Book). - **Full dashboard** — both tabs' content in one document. Slightly more work on both render paths (must reveal/render both sections). ## PDF content = data only, no UI chrome -The PDF contains only the record content: **Service Timeline, Aircraft Info, -Hours (block time / time in service), and Log Book**. All interactive controls are excluded — +The PDF contains only the record content: **Status Sheet, Aircraft Info, +Hours (Hobbs time / time in service), and Log Book**. All interactive controls are excluded — the Share menu, grip handles, trash/delete icons, complete-maintenance button, chevrons, dropdowns, etc. @@ -164,7 +164,7 @@ for their attachment/link instead of building their own renderer. with alert invites/resends) → 429 past the cap. - **Tokenized PDF links** (for SMS) must be unguessable + expiring so records can't be enumerated. -- **Empty timeline** — disable Share or guard against emailing a blank PDF. +- **Empty Status Sheet** — disable Share or guard against emailing a blank PDF. - **States** — "Generating…" loading state; reuse existing `showToast` for success/failure. - **Excel export** — currently commented out; omit from the menu until real. diff --git a/src/browserTest/java/com/example/AviaryService/browser/AddRowAutoFillTest.java b/src/browserTest/java/com/example/AviaryService/browser/AddRowAutoFillTest.java new file mode 100644 index 0000000..0e8c76a --- /dev/null +++ b/src/browserTest/java/com/example/AviaryService/browser/AddRowAutoFillTest.java @@ -0,0 +1,174 @@ +package com.example.AviaryService.browser; + +import com.example.AviaryService.entity.StatusSheetItem; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.StatusSheetItemRepository; +import com.microsoft.playwright.Locator; +import com.microsoft.playwright.assertions.LocatorAssertions; +import com.microsoft.playwright.options.LoadState; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.List; + +import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Spec 010 in a real browser: the add row fills its Due Date from Last Done + + * cycle before Add (behaviors 1-8), and the saved row matches. + */ +class AddRowAutoFillTest extends BrowserTestBase { + + @Autowired + StatusSheetItemRepository statusSheetItems; + + private static final LocatorAssertions.HasValueOptions WAIT = new LocatorAssertions.HasValueOptions().setTimeout(5000); + + private Locator add; + + private List open() { + String username = seedUser("password"); + List errors = new ArrayList<>(); + page.onConsoleMessage(m -> { if ("error".equals(m.type())) errors.add(m.text()); }); + page.setViewportSize(1400, 900); + loginAs(username, "password"); + page.waitForLoadState(LoadState.NETWORKIDLE); + add = page.locator("tr.add-row"); + return errors; + } + + private Locator cell(String label) { + return add.locator("td[data-label='" + label + "']"); + } + + private void openPart(String label, String type) { + cell(label).locator(".trigger-dropdown").click(); + cell(label).locator(".add-type[data-type='" + type + "']").click(); + } + + @Test + void addRowFillsBeforeAddAndSavedRowMatches() { + List errors = open(); + add.locator("textarea[name='item']").fill("Oil change"); + + // 2: Last Done first, cycle afterwards. + openPart("Last Done", "calendar"); + cell("Last Done").locator("input[type='date']").fill("2026-10-30"); + add.locator("input[name='cycleCalendarValue']").fill("1"); + add.locator("select[name='cycleCalendarUnit']").selectOption("MONTHS"); + + // 1: Due Date fills (calendar opened by itself) before Add. + Locator dueDate = cell("Due Date").locator("input[type='date']"); + assertThat(dueDate).hasValue("2026-11-30", WAIT); + + // Hours too, and 6: 25 -> 25.0 on leaving the box. + add.locator("input[name='cycleHours']").fill("100"); + openPart("Last Done", "clock"); + Locator lastHours = cell("Last Done").locator("input.extra-input[type='text']"); + lastHours.fill("25"); + add.locator("textarea[name='item']").click(); + assertThat(lastHours).hasValue("25.0"); + assertThat(cell("Due Date").locator("input.extra-input[type='text']")).hasValue("125.0", WAIT); + + // 8: Add -> saved row matches, add row clears. + add.locator("button.add-button").click(); + page.waitForLoadState(LoadState.NETWORKIDLE); + Locator saved = page.locator("tr.auto-save-row").last(); + assertThat(saved.locator("td:nth-child(6) input[type='date']")).hasValue("2026-11-30", WAIT); + assertThat(saved.locator("td:nth-child(6) input.extra-input[type='text']")).hasValue("125.0"); + assertThat(add.locator("td[data-label='Due Date'] input.extra-input")).hasCount(0); + assertThat(add.locator("textarea[name='item']")).hasValue(""); + + StatusSheetItem row = statusSheetItems.findAll().stream() + .filter(i -> "Oil change".equals(i.getItem())).findFirst().orElseThrow(); + assertTrue(row.getDueDateAuto(), "auto-filled in the add row stays auto after Add"); + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } + + @Test + void typedAndRemovedDueDatesAreRespectedAndLastDoneClears() { + List errors = open(); + add.locator("textarea[name='item']").fill("Annual"); + add.locator("input[name='cycleCalendarValue']").fill("1"); + add.locator("select[name='cycleCalendarUnit']").selectOption("MONTHS"); + openPart("Last Done", "calendar"); + Locator lastDate = cell("Last Done").locator("input[type='date']"); + lastDate.fill("2026-10-30"); + Locator dueDate = cell("Due Date").locator("input[type='date']"); + assertThat(dueDate).hasValue("2026-11-30", WAIT); + + // 5: clearing Last Done clears the auto Due Date. + lastDate.fill(""); + assertThat(dueDate).hasCount(0, new LocatorAssertions.HasCountOptions().setTimeout(5000)); + + // 3: typed Due Date stays when Last Done changes. + lastDate.fill("2026-10-30"); + assertThat(dueDate).hasValue("2026-11-30", WAIT); + dueDate.fill("2027-06-01"); + page.waitForTimeout(600); + lastDate.fill("2026-12-05"); + page.waitForTimeout(800); + assertThat(dueDate).hasValue("2027-06-01"); + + // 4: Remove stays removed until Last Done or the cycle changes. + cell("Due Date").locator(".trigger-dropdown").click(); + Locator remove = cell("Due Date").locator(".add-type[data-type='calendar']"); + remove.click(); + remove.click(); // confirm "Remove?" + page.waitForTimeout(800); + assertThat(dueDate).hasCount(0); + add.locator("textarea[name='item']").fill("Annual inspection"); // unrelated change + page.waitForTimeout(800); + assertThat(dueDate).hasCount(0); + lastDate.fill("2026-12-10"); + assertThat(dueDate).hasValue("2027-01-10", WAIT); + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } + + @Test + void futureLastDoneShowsANoteButAddStillWorks() { + List errors = open(); + add.locator("textarea[name='item']").fill("ELT"); + add.locator("input[name='cycleCalendarValue']").fill("12"); + add.locator("select[name='cycleCalendarUnit']").selectOption("MONTHS"); + openPart("Last Done", "calendar"); + String future = java.time.LocalDate.now().plusYears(1).toString(); + cell("Last Done").locator("input[type='date']").fill(future); + assertThat(cell("Last Done").locator(".row-warning")).hasText("Last Done is in the future. Check the date."); + int before = statusSheetItems.findAll().size(); + add.locator("button.add-button").click(); + page.waitForLoadState(LoadState.NETWORKIDLE); + page.waitForTimeout(500); + assertEquals(before + 1, statusSheetItems.findAll().size(), "note does not block Add"); + assertThat(cell("Last Done").locator(".row-warning")).hasCount(0); + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } + + @Test + void titleModeFillsNothing() { + List errors = open(); + add.locator("input[name='cycleCalendarValue']").fill("1"); + add.locator("select[name='cycleCalendarUnit']").selectOption("MONTHS"); + openPart("Last Done", "calendar"); + cell("Last Done").locator("input[type='date']").fill("2026-10-30"); + assertThat(cell("Due Date").locator("input[type='date']")).hasValue("2026-11-30", WAIT); + cell("Due Date").locator(".trigger-dropdown").click(); + Locator remove = cell("Due Date").locator(".add-type[data-type='calendar']"); + remove.click(); + remove.click(); + page.waitForTimeout(600); + + page.locator(".row-type-option[data-type='title']").click(); + // Title mode hides Last Done / Due Date, so nothing can fill or show a note. + assertThat(cell("Last Done").locator("input[type='date']")).isHidden(); + page.evaluate("() => { const i = document.querySelector('.add-row td[data-label=\"Last Done\"] input[type=date]');" + + " i.value = '2026-11-15'; i.dispatchEvent(new Event('input', {bubbles: true})); }"); + page.waitForTimeout(800); + assertThat(cell("Due Date").locator("input[type='date']")).hasCount(0); + assertThat(cell("Last Done").locator(".row-warning")).hasCount(0); + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } +} diff --git a/src/browserTest/java/com/example/AviaryService/browser/BrowserTestBase.java b/src/browserTest/java/com/example/AviaryService/browser/BrowserTestBase.java index 2152501..6323811 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/BrowserTestBase.java +++ b/src/browserTest/java/com/example/AviaryService/browser/BrowserTestBase.java @@ -1,7 +1,7 @@ package com.example.AviaryService.browser; import com.example.AviaryService.entity.Aircraft; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.AircraftRepository; import com.example.AviaryService.repositories.UserRepository; @@ -105,12 +105,12 @@ protected Aircraft aircraftOf(String username) { * These take the combined "2025-10-01 100.5" form the tests were written * with (either part optional) and split it. */ - protected static void setLastDone(ServiceTimeline t, String value) { + protected static void setLastDone(StatusSheetItem t, String value) { t.setLastDoneDate(datePart(value)); t.setLastDoneHours(hoursPart(value)); } - protected static void setDueDate(ServiceTimeline t, String value) { + protected static void setDueDate(StatusSheetItem t, String value) { t.setDueDateDate(datePart(value)); t.setDueDateHours(hoursPart(value)); } diff --git a/src/browserTest/java/com/example/AviaryService/browser/ConnectionsPageTest.java b/src/browserTest/java/com/example/AviaryService/browser/ConnectionsPageTest.java index 5168221..b1a5e14 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/ConnectionsPageTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/ConnectionsPageTest.java @@ -10,9 +10,9 @@ import org.springframework.beans.factory.annotation.Autowired; import com.example.AviaryService.entity.OAuthAuthorizationEntity; -import com.example.AviaryService.entity.TimelineImportRecord; +import com.example.AviaryService.entity.StatusSheetImportRecord; import com.example.AviaryService.repositories.OAuthAuthorizationRepository; -import com.example.AviaryService.repositories.TimelineImportRecordRepository; +import com.example.AviaryService.repositories.StatusSheetImportRecordRepository; /** * Import with AI page: the connect box (address, Copy, steps, hints) is always @@ -25,7 +25,7 @@ class ConnectionsPageTest extends BrowserTestBase { OAuthAuthorizationRepository authorizationRepository; @Autowired - TimelineImportRecordRepository importRecordRepository; + StatusSheetImportRecordRepository importRecordRepository; private void seedConnection(String username) { OAuthAuthorizationEntity e = new OAuthAuthorizationEntity(); @@ -38,7 +38,7 @@ private void seedConnection(String username) { e.setAccessTokenIssuedAt(Instant.now()); authorizationRepository.save(e); - TimelineImportRecord r = new TimelineImportRecord(); + StatusSheetImportRecord r = new StatusSheetImportRecord(); r.setUser(userRepository.findByUsername(username)); r.setClientId(e.getRegisteredClientId()); r.setClientName("Test Assistant"); diff --git a/src/browserTest/java/com/example/AviaryService/browser/DashboardLayoutTest.java b/src/browserTest/java/com/example/AviaryService/browser/DashboardLayoutTest.java index 517629f..ac0d905 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/DashboardLayoutTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/DashboardLayoutTest.java @@ -1,8 +1,8 @@ package com.example.AviaryService.browser; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.repositories.UserRepository; import com.microsoft.playwright.Page; import com.microsoft.playwright.options.LoadState; @@ -31,7 +31,7 @@ class DashboardLayoutTest extends BrowserTestBase { UserRepository users; @Autowired - ServiceTimelineRepository timelines; + StatusSheetItemRepository statusSheetItems; private List attachConsoleErrorListener() { List errors = new ArrayList<>(); @@ -43,17 +43,17 @@ private List attachConsoleErrorListener() { private void seedThreeRows(User user) { for (int i = 1; i <= 3; i++) { - ServiceTimeline t = new ServiceTimeline(); + StatusSheetItem t = new StatusSheetItem(); t.setUser(user); t.setAircraft(aircraftOf(user)); t.setItem("Row " + i); t.setIsTitle(false); - t.setTimelineOrder(i); + t.setStatusSheetOrder(i); t.setDescription("Inspect"); setLastDone(t, "2025-10-01"); setDueDate(t, "2026-12-01"); t.setTimeLeft(""); - timelines.save(t); + statusSheetItems.save(t); } } @@ -103,13 +103,13 @@ void addButtonExactlyFillsItsParentForm() { void shortItemTextareaStartsAtAboutOneLineHeight() { String username = seedUser("password"); User u = users.findByUsername(username); - ServiceTimeline t = new ServiceTimeline(); + StatusSheetItem t = new StatusSheetItem(); t.setUser(u); t.setAircraft(aircraftOf(u)); t.setItem("Oil"); // single short token — should fit one line t.setIsTitle(false); - t.setTimelineOrder(1); - timelines.save(t); + t.setStatusSheetOrder(1); + statusSheetItems.save(t); var errors = attachConsoleErrorListener(); loginAs(username, "password"); @@ -186,18 +186,18 @@ void dateInputsStayInsideTheirCellsWhenWindowIsNarrow() { String username = seedUser("password"); User u = users.findByUsername(username); - ServiceTimeline t = new ServiceTimeline(); + StatusSheetItem t = new StatusSheetItem(); t.setUser(u); t.setAircraft(aircraftOf(u)); t.setItem("Magneto"); t.setIsTitle(false); - t.setTimelineOrder(1); + t.setStatusSheetOrder(1); t.setDescription("Inspect"); // Both a date and an hours value so each cell renders both inputs. setLastDone(t, "2025-10-01 100.5"); setDueDate(t, "2026-12-01 250"); t.setTimeLeft(""); - timelines.save(t); + statusSheetItems.save(t); loginAs(username, "password"); page.waitForLoadState(LoadState.NETWORKIDLE); @@ -317,17 +317,17 @@ void timeLeftColumnIsSizedToContentNotAFatFixedWidth() { // A long-overdue calendar date yields a wide value like // "9600 days overdue" — the widest realistic Time Left content. - ServiceTimeline t = new ServiceTimeline(); + StatusSheetItem t = new StatusSheetItem(); t.setUser(u); t.setAircraft(aircraftOf(u)); t.setItem("Engine"); t.setIsTitle(false); - t.setTimelineOrder(1); + t.setStatusSheetOrder(1); t.setDescription("Inspect"); setLastDone(t, "2000-01-01"); setDueDate(t, "2000-01-01"); t.setTimeLeft(""); - timelines.save(t); + statusSheetItems.save(t); loginAs(username, "password"); page.waitForLoadState(LoadState.NETWORKIDLE); @@ -376,17 +376,17 @@ void calendarAlwaysStacksAboveHoursRegardlessOfAddOrder() { // Empty Last Done / Due Date so the row starts with no inputs — just // the chevron — and we drive the +/- menu ourselves. - ServiceTimeline t = new ServiceTimeline(); + StatusSheetItem t = new StatusSheetItem(); t.setUser(u); t.setAircraft(aircraftOf(u)); t.setItem("Battery"); t.setIsTitle(false); - t.setTimelineOrder(1); + t.setStatusSheetOrder(1); t.setDescription("Inspect"); setLastDone(t, ""); setDueDate(t, ""); t.setTimeLeft(""); - timelines.save(t); + statusSheetItems.save(t); loginAs(username, "password"); page.waitForLoadState(LoadState.NETWORKIDLE); diff --git a/src/browserTest/java/com/example/AviaryService/browser/DashboardMobileCardsTest.java b/src/browserTest/java/com/example/AviaryService/browser/DashboardMobileCardsTest.java index 8d8f14e..10fb66a 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/DashboardMobileCardsTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/DashboardMobileCardsTest.java @@ -1,10 +1,10 @@ package com.example.AviaryService.browser; import com.example.AviaryService.entity.FlightLog; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.FlightLogRepository; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.repositories.UserRepository; import com.microsoft.playwright.Locator; import com.microsoft.playwright.Page; @@ -22,7 +22,7 @@ /** * Regression tests for the mobile cards. * - * At phone width (<=768px) each Service Timeline row and each Log Book row + * At phone width (<=768px) each Status Sheet row and each Log Book row * collapses into a card. The current design requires, on a 390px viewport: * - the card lays out as a CSS grid (not the old space-between flex rows), * - the Item is a bold headline (font-weight 700), @@ -44,26 +44,26 @@ class DashboardMobileCardsTest extends BrowserTestBase { UserRepository users; @Autowired - ServiceTimelineRepository timelines; + StatusSheetItemRepository statusSheetItems; @Autowired FlightLogRepository flightLogs; private void seedData(User user) { - ServiceTimeline title = new ServiceTimeline(); + StatusSheetItem title = new StatusSheetItem(); title.setUser(user); title.setAircraft(aircraftOf(user)); title.setItem("ENGINE"); title.setIsTitle(true); - title.setTimelineOrder(0); - timelines.save(title); + title.setStatusSheetOrder(0); + statusSheetItems.save(title); - ServiceTimeline item = new ServiceTimeline(); + StatusSheetItem item = new StatusSheetItem(); item.setUser(user); item.setAircraft(aircraftOf(user)); item.setItem("Annual Inspection"); item.setIsTitle(false); - item.setTimelineOrder(1); + item.setStatusSheetOrder(1); item.setDescription("Inspect"); item.setCycleCalendarValue(12); item.setCycleCalendarUnit("MONTHS"); @@ -71,15 +71,15 @@ private void seedData(User user) { setLastDone(item, "2025-06-01"); setDueDate(item, "2026-06-01 2450.0"); item.setTimeLeft("11 mo\n86.0 hrs"); - timelines.save(item); + statusSheetItems.save(item); FlightLog log = new FlightLog(); log.setUser(user); log.setAircraft(aircraftOf(user)); log.setFromAirport("KSQL"); log.setToAirport("KPAO"); - log.setBlockTimeOut(1234.5); - log.setBlockTimeIn(1236.1); + log.setHobbsTimeOut(1234.5); + log.setHobbsTimeIn(1236.1); log.setTimeInServiceOut(1100.2); log.setTimeInServiceIn(1101.5); flightLogs.save(log); @@ -108,12 +108,12 @@ private void openDashboardOnPhone() { } @Test - void serviceTimelineCardUsesFlatBorderlessFields() { + void statusSheetCardUsesFlatBorderlessFields() { openDashboardOnPhone(); Locator row = page.locator("tr.auto-save-row").first(); assertEquals("grid", cssOf(row, "display"), - "Saved service-timeline card should lay out as a CSS grid on mobile"); + "Saved Status Sheet card should lay out as a CSS grid on mobile"); // Item is a bold headline. Locator itemText = row.locator("td[data-label='Item'] textarea"); diff --git a/src/browserTest/java/com/example/AviaryService/browser/DueDateAutoFillTest.java b/src/browserTest/java/com/example/AviaryService/browser/DueDateAutoFillTest.java new file mode 100644 index 0000000..11b55b6 --- /dev/null +++ b/src/browserTest/java/com/example/AviaryService/browser/DueDateAutoFillTest.java @@ -0,0 +1,238 @@ +package com.example.AviaryService.browser; + +import com.example.AviaryService.entity.StatusSheetItem; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.StatusSheetItemRepository; +import com.microsoft.playwright.Locator; +import com.microsoft.playwright.options.LoadState; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.ArrayList; +import java.util.List; + +import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; + +/** + * Spec 007 in a real browser: after the owner enters Last Done, the + * auto-filled Due Date appears on screen without reloading the page, and + * hours tidy to the 25.0 format when the owner leaves the box. + */ +class DueDateAutoFillTest extends BrowserTestBase { + + @Autowired + StatusSheetItemRepository statusSheetItems; + + private StatusSheetItem seed(String username, Integer calValue, String calUnit, Double cycleHours, + String lastDoneDate, String lastDoneHours) { + User user = userRepository.findByUsername(username); + StatusSheetItem t = new StatusSheetItem(); + t.setUser(user); + t.setAircraft(aircraftOf(user)); + t.setItem("Oil change"); + t.setIsTitle(false); + t.setStatusSheetOrder(0); + t.setCycleCalendarValue(calValue); + t.setCycleCalendarUnit(calUnit); + t.setCycleHours(cycleHours); + t.setLastDoneDate(lastDoneDate); + t.setLastDoneHours(lastDoneHours); + return statusSheetItems.save(t); + } + + private List open(String username) { + List errors = new ArrayList<>(); + page.onConsoleMessage(m -> { if ("error".equals(m.type())) errors.add(m.text()); }); + loginAs(username, "password"); + page.waitForLoadState(LoadState.NETWORKIDLE); + return errors; + } + + @Test + void dueDateAppearsRightAfterLastDoneWithoutReload() { + String username = seedUser("password"); + StatusSheetItem item = seed(username, 1, "MONTHS", null, "2026-09-15", null); + List errors = open(username); + + Locator row = page.locator("tr.auto-save-row[data-id='" + item.getId() + "']"); + Locator lastDone = row.locator("td:nth-child(5) input[type='date']"); + lastDone.fill("2026-10-30"); + + // No reload: the Due Date shows up in place once the save returns. + Locator due = row.locator("td:nth-child(6) input[type='date']"); + assertThat(due).hasValue("2026-11-30", new com.microsoft.playwright.assertions.LocatorAssertions.HasValueOptions().setTimeout(5000)); + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } + + @Test + void hoursTidyOnBlurAndDueHoursFill() { + String username = seedUser("password"); + StatusSheetItem item = seed(username, null, null, 100.0, null, "900"); + List errors = open(username); + + Locator row = page.locator("tr.auto-save-row[data-id='" + item.getId() + "']"); + Locator lastHours = row.locator("td:nth-child(5) input.extra-input[type='text']"); + assertThat(lastHours).hasValue("900.0"); // stored "900", shown with a decimal + + lastHours.fill("950"); + row.locator("td:nth-child(2)").click(); // leave the box + assertThat(lastHours).hasValue("950.0"); + + Locator dueHours = row.locator("td:nth-child(6) input.extra-input[type='text']"); + assertThat(dueHours).hasValue("1050.0", new com.microsoft.playwright.assertions.LocatorAssertions.HasValueOptions().setTimeout(5000)); + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } + + // Reported bug: 12 mo -> 1 mo -> delete the number -> Remove the Due Date + // calendar. The old Due Date used to reappear straight away. + @Test + void removedDueDateStaysRemovedWhenCycleNumberIsDeleted() { + String username = seedUser("password"); + StatusSheetItem item = seed(username, 12, "MONTHS", null, "2020-12-01", null); + List errors = open(username); + + Locator row = page.locator("tr.auto-save-row[data-id='" + item.getId() + "']"); + Locator due = row.locator("td:nth-child(6) input[type='date']"); + Locator cycleNumber = row.locator("input[name='cycleCalendarValue']"); + + // Setting Last Done again fills 12 months later. + row.locator("td:nth-child(5) input[type='date']").fill("2020-12-01"); + cycleNumber.fill("12"); + assertThat(due).hasValue("2021-12-01", new com.microsoft.playwright.assertions.LocatorAssertions.HasValueOptions().setTimeout(5000)); + + cycleNumber.fill("1"); + assertThat(due).hasValue("2021-01-01", new com.microsoft.playwright.assertions.LocatorAssertions.HasValueOptions().setTimeout(5000)); + + cycleNumber.fill(""); + page.waitForTimeout(1200); // let that save finish + + Locator dueCell = row.locator("td:nth-child(6)"); + dueCell.locator(".trigger-dropdown").click(); + Locator remove = dueCell.locator(".add-type[data-type='calendar']"); + remove.click(); // "Remove?" (has a value) + remove.click(); // confirm + page.waitForTimeout(1500); // save + response + + assertThat(due).hasCount(0); + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } + + @Test + void rollForwardBoxOffersResetToCycleForATypedDueDate() { + String username = seedUser("password"); + StatusSheetItem item = seed(username, 1, "MONTHS", null, "2020-12-01", null); + List errors = open(username); + + Locator row = page.locator("tr.auto-save-row[data-id='" + item.getId() + "']"); + Locator due = row.locator("td:nth-child(6) input[type='date']"); + row.locator("td:nth-child(5) input[type='date']").fill("2020-12-01"); + assertThat(due).hasValue("2021-01-01", new com.microsoft.playwright.assertions.LocatorAssertions.HasValueOptions().setTimeout(5000)); + + // Owner types their own Due Date, then opens the box right away + // (before the 500ms save would have gone out on its own). + due.fill("2021-03-15"); + row.locator(".complete-btn").click(); + + Locator reset = page.locator(".choice-box button[data-choice='reset']"); + assertThat(reset).hasText("Reset to cycle (01/01/2021)"); + assertThat(reset).isEnabled(); + assertThat(page.locator(".choice-box button[data-choice='complete']")).isEnabled(); + reset.click(); + + assertThat(due).hasValue("2021-01-01", new com.microsoft.playwright.assertions.LocatorAssertions.HasValueOptions().setTimeout(5000)); + assertThat(row.locator("td:nth-child(5) input[type='date']")).hasValue("2020-12-01"); + + // Now it matches: Reset is grayed out with the reason. + row.locator(".complete-btn").click(); + assertThat(reset).isDisabled(); + assertThat(page.locator(".choice-box")).containsText("Due Date already matches the cycle"); + page.keyboard().press("Escape"); + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } + + // ── Spec 008: Mark complete asks "When was this done?" ──────────── + + private StatusSheetItem seedDue(String username, Integer calValue, String calUnit, Double cycleHours, + String lastDoneDate, String lastDoneHours, String dueDate, String dueHours) { + StatusSheetItem t = seed(username, calValue, calUnit, cycleHours, lastDoneDate, lastDoneHours); + t.setDueDateDate(dueDate); + t.setDueDateHours(dueHours); + return statusSheetItems.save(t); + } + + private void openMarkComplete(Locator row) { + row.locator(".complete-btn").click(); + page.locator(".choice-box button[data-choice='complete']").click(); + assertThat(page.locator(".done-box")).isVisible(); + } + + @Test + void markCompleteRollsFromTheDueDateWithTruthfulToast() { + String username = seedUser("password"); + StatusSheetItem item = seedDue(username, 1, "MONTHS", 100.0, "2026-11-01", "1200.0", "2026-12-01", "1300.0"); + List errors = open(username); + Locator row = page.locator("tr.auto-save-row[data-id='" + item.getId() + "']"); + + openMarkComplete(row); + Locator box = page.locator(".done-box"); + assertThat(box.locator("input[name='doneDate']")).hasValue("2026-12-01"); + assertThat(box.locator("input[name='doneHours']")).hasValue("1300.0"); + assertThat(box.locator(".done-next")).hasText("Next due: 01/01/2027 · 1400.0 hrs"); + + // Editing the date updates "Next due" live. + box.locator("input[name='doneDate']").fill("2026-11-20"); + assertThat(box.locator(".done-next")).hasText("Next due: 12/20/2026 · 1400.0 hrs"); + box.locator("input[name='doneDate']").fill("2026-12-01"); + assertThat(box.locator(".done-next")).hasText("Next due: 01/01/2027 · 1400.0 hrs"); + + // Double-click Save: rolls once. + box.locator(".confirm-btn.ok").dblclick(); + assertThat(page.locator(".toast").last()).containsText("Rolled forward. Last Done 12/01/2026 · 1300.0 hrs, Due 01/01/2027 · 1400.0 hrs."); + assertThat(row.locator("td:nth-child(5) input[type='date']")).hasValue("2026-12-01"); + assertThat(row.locator("td:nth-child(6) input[type='date']")).hasValue("2027-01-01"); + assertThat(row.locator("td:nth-child(6) input.extra-input[type='text']")).hasValue("1400.0"); + assertThat(page.locator(".done-box")).hasCount(0); + + // Second time: the box previews the next cycle. + openMarkComplete(row); + assertThat(page.locator(".done-box input[name='doneDate']")).hasValue("2027-01-01"); + assertThat(page.locator(".done-box .done-next")).hasText("Next due: 02/01/2027 · 1500.0 hrs"); + page.keyboard().press("Escape"); + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } + + @Test + void emptyBoxesGrayOutSaveAndRowWithNothingStartsWithToday() { + String username = seedUser("password"); + StatusSheetItem item = seedDue(username, 1, "MONTHS", 100.0, null, null, null, null); + List errors = open(username); + Locator row = page.locator("tr.auto-save-row[data-id='" + item.getId() + "']"); + + openMarkComplete(row); + Locator box = page.locator(".done-box"); + assertThat(box.locator("input[name='doneDate']")).hasValue(java.time.LocalDate.now().toString()); + assertThat(box.locator("input[name='doneHours']")).hasValue(""); + + box.locator("input[name='doneDate']").fill(""); + assertThat(box.locator(".done-next")).hasText("Enter when it was done."); + assertThat(box.locator(".confirm-btn.ok")).isDisabled(); + page.keyboard().press("Escape"); + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } + + // Spec 011: no hint text under Mark complete; Reset keeps its reason. + @Test + void markCompleteHasNoHintButResetKeepsItsReason() { + String username = seedUser("password"); + StatusSheetItem item = seedDue(username, 1, "MONTHS", null, "2026-11-01", null, "2026-12-01", null); + List errors = open(username); + Locator row = page.locator("tr.auto-save-row[data-id='" + item.getId() + "']"); + row.locator(".complete-btn").click(); + Locator complete = page.locator(".choice-box .choice-item:has(button[data-choice='complete'])"); + assertThat(complete.locator(".choice-hint")).hasCount(0); + Locator reset = page.locator(".choice-box .choice-item:has(button[data-choice='reset'])"); + assertThat(reset.locator(".choice-hint")).hasText("Due Date already matches the cycle"); + page.keyboard().press("Escape"); + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } +} diff --git a/src/browserTest/java/com/example/AviaryService/browser/FleetPickerTest.java b/src/browserTest/java/com/example/AviaryService/browser/FleetPickerTest.java index 022a5e1..9d10aec 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/FleetPickerTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/FleetPickerTest.java @@ -10,9 +10,9 @@ import org.springframework.beans.factory.annotation.Autowired; import com.example.AviaryService.entity.Aircraft; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.microsoft.playwright.Page; import com.microsoft.playwright.options.LoadState; @@ -23,7 +23,7 @@ */ class FleetPickerTest extends BrowserTestBase { - @Autowired ServiceTimelineRepository timelines; + @Autowired StatusSheetItemRepository statusSheetItems; private Aircraft a; private Aircraft b; @@ -46,14 +46,14 @@ private void seedFleet() { } private void row(User u, Aircraft on, String item, int order, String due) { - ServiceTimeline t = new ServiceTimeline(); + StatusSheetItem t = new StatusSheetItem(); t.setUser(u); t.setAircraft(on); t.setItem(item); t.setIsTitle(false); - t.setTimelineOrder(order); + t.setStatusSheetOrder(order); t.setDueDateDate(due); - timelines.save(t); + statusSheetItems.save(t); } private List visibleItems(Page p) { @@ -117,8 +117,8 @@ void actionInAnOlderTabLandsOnThatTabsAircraft() { + " return r.status; }"); assertEquals(200, ((Number) status).intValue()); - assertTrue(timelines.findByAircraftOrderByTimelineOrderAsc(a).stream().anyMatch(t -> t.getItem().equals("Tab one row"))); - assertTrue(timelines.findByAircraftOrderByTimelineOrderAsc(b).stream().noneMatch(t -> t.getItem().equals("Tab one row"))); + assertTrue(statusSheetItems.findByAircraftOrderByStatusSheetOrderAsc(a).stream().anyMatch(t -> t.getItem().equals("Tab one row"))); + assertTrue(statusSheetItems.findByAircraftOrderByStatusSheetOrderAsc(b).stream().noneMatch(t -> t.getItem().equals("Tab one row"))); } // The plane button must never sit under Share / Import with AI / Logout, diff --git a/src/browserTest/java/com/example/AviaryService/browser/FlightLogTableEdgeCasesTest.java b/src/browserTest/java/com/example/AviaryService/browser/FlightLogTableEdgeCasesTest.java index 827b9c4..50b89ae 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/FlightLogTableEdgeCasesTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/FlightLogTableEdgeCasesTest.java @@ -43,15 +43,15 @@ private void assertNoConsoleErrors(List errors) { } private FlightLog saveLog(User user, String from, String to, - Double blockTimeOut, Double blockTimeIn, + Double hobbsTimeOut, Double hobbsTimeIn, Double timeInServiceOut, Double timeInServiceIn) { FlightLog log = new FlightLog(); log.setUser(user); log.setAircraft(aircraftOf(user)); log.setFromAirport(from); log.setToAirport(to); - log.setBlockTimeOut(blockTimeOut); - log.setBlockTimeIn(blockTimeIn); + log.setHobbsTimeOut(hobbsTimeOut); + log.setHobbsTimeIn(hobbsTimeIn); log.setTimeInServiceOut(timeInServiceOut); log.setTimeInServiceIn(timeInServiceIn); return flightLogs.save(log); @@ -86,8 +86,8 @@ void typicalLogRendersAllCellsWithDecimalHours() { assertThat(row).hasCount(1); assertThat(row.locator("input[name='fromAirport']")).hasValue("KAAA"); assertThat(row.locator("input[name='toAirport']")).hasValue("KBBB"); - assertThat(row.locator("input[name='blockTimeOut']")).hasValue("100.0"); - assertThat(row.locator("input[name='blockTimeIn']")).hasValue("101.5"); + assertThat(row.locator("input[name='hobbsTimeOut']")).hasValue("100.0"); + assertThat(row.locator("input[name='hobbsTimeIn']")).hasValue("101.5"); assertThat(row.locator("input[name='timeInServiceOut']")).hasValue("50.0"); assertThat(row.locator("input[name='timeInServiceIn']")).hasValue("51.5"); @@ -113,8 +113,8 @@ void nullAirportsAndHoursRenderEmptyWithoutBreaking() { assertThat(row).hasCount(1); assertThat(row.locator("input[name='fromAirport']")).hasValue(""); assertThat(row.locator("input[name='toAirport']")).hasValue(""); - assertThat(row.locator("input[name='blockTimeOut']")).hasValue(""); - assertThat(row.locator("input[name='blockTimeIn']")).hasValue(""); + assertThat(row.locator("input[name='hobbsTimeOut']")).hasValue(""); + assertThat(row.locator("input[name='hobbsTimeIn']")).hasValue(""); assertThat(row.locator("input[name='timeInServiceOut']")).hasValue(""); assertThat(row.locator("input[name='timeInServiceIn']")).hasValue(""); @@ -134,8 +134,8 @@ void zeroDurationLegRendersWithZeroValues() { page.waitForLoadState(LoadState.NETWORKIDLE); var row = page.locator("tbody#logbook-body tr.log-row[data-id='" + log.getId() + "']"); - assertThat(row.locator("input[name='blockTimeOut']")).hasValue("0.0"); - assertThat(row.locator("input[name='blockTimeIn']")).hasValue("0.0"); + assertThat(row.locator("input[name='hobbsTimeOut']")).hasValue("0.0"); + assertThat(row.locator("input[name='hobbsTimeIn']")).hasValue("0.0"); assertThat(row.locator("input[name='timeInServiceOut']")).hasValue("0.0"); assertThat(row.locator("input[name='timeInServiceIn']")).hasValue("0.0"); @@ -153,7 +153,7 @@ void veryLargeHoursValueRenders() { page.waitForLoadState(LoadState.NETWORKIDLE); var row = page.locator("tbody#logbook-body tr.log-row[data-id='" + log.getId() + "']"); - assertThat(row.locator("input[name='blockTimeIn']")).hasValue("99999.9"); + assertThat(row.locator("input[name='hobbsTimeIn']")).hasValue("99999.9"); assertThat(row.locator("input[name='timeInServiceIn']")).hasValue("99999.9"); assertNoConsoleErrors(errors); diff --git a/src/browserTest/java/com/example/AviaryService/browser/HoursInfoMarksTest.java b/src/browserTest/java/com/example/AviaryService/browser/HoursInfoMarksTest.java new file mode 100644 index 0000000..51d2faa --- /dev/null +++ b/src/browserTest/java/com/example/AviaryService/browser/HoursInfoMarksTest.java @@ -0,0 +1,96 @@ +package com.example.AviaryService.browser; + +import com.microsoft.playwright.Locator; +import com.microsoft.playwright.options.LoadState; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Spec 005: info marks next to Hobbs Time and Time in Service on My Hours. + * Checks the text, that hover/focus/tap reveal it, that tapping elsewhere + * closes it, and that it fits a phone screen without horizontal scroll. + */ +class HoursInfoMarksTest extends BrowserTestBase { + + private static final String HOBBS_TIP = + "Hobbs time: engine running time, from engine start to shutdown. Includes taxi and run-up."; + private static final String TIS_TIP = + "Flight time: time in the air, from takeoff to landing. Used for maintenance and inspections."; + + private String tipDisplay(Locator mark) { + return (String) mark.evaluate("el => getComputedStyle(el, '::after').display"); + } + + private List openDashboard() { + String username = seedUser("password"); + List errors = new ArrayList<>(); + page.onConsoleMessage(m -> { if ("error".equals(m.type())) errors.add(m.text()); }); + loginAs(username, "password"); + page.waitForLoadState(LoadState.NETWORKIDLE); + return errors; + } + + @Test + void infoMarksHaveTheRightTextAndOpenOnHoverFocusAndTap() { + List errors = openDashboard(); + Locator hobbs = page.locator("#hobbs-time-info"); + Locator tis = page.locator("#time-in-service-info"); + + assertThat(hobbs).hasAttribute("aria-label", HOBBS_TIP); + assertThat(hobbs).hasAttribute("data-tip", HOBBS_TIP); + assertThat(tis).hasAttribute("aria-label", TIS_TIP); + assertThat(tis).hasAttribute("data-tip", TIS_TIP); + + assertEquals("none", tipDisplay(hobbs), "tooltip hidden by default"); + + hobbs.hover(); + page.waitForTimeout(200); + assertEquals("block", tipDisplay(hobbs), "hover shows tooltip"); + + page.mouse().move(0, 0); + tis.click(); + page.waitForTimeout(200); + assertTrue(tis.getAttribute("class").contains("open"), "tap opens tooltip"); + page.locator("h3:has-text('My Hours')").click(); + assertTrue(!tis.getAttribute("class").contains("open"), "tap elsewhere closes it"); + + page.keyboard().press("Tab"); + tis.focus(); + page.keyboard().press("Escape"); + assertTrue(!tis.getAttribute("class").contains("open")); + + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } + + @Test + void statusSheetTabHasMaintenanceInspectionsTag() { + List errors = openDashboard(); + Locator tag = page.locator("#status-sheet-info"); + assertThat(page.locator(".tab-button[data-tab='status-sheet-tab']")).hasText("Status Sheet"); + assertThat(tag).hasAttribute("data-tip", "Maintenance/inspections"); + assertThat(tag).hasAttribute("aria-label", "Status Sheet: maintenance/inspections"); + tag.hover(); + page.waitForTimeout(200); + assertEquals("block", tipDisplay(tag), "hover shows the tag text"); + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } + + @Test + void infoMarksFitAPhoneScreen() { + page.setViewportSize(360, 740); + openDashboard(); + Locator tis = page.locator("#time-in-service-info"); + tis.scrollIntoViewIfNeeded(); + tis.click(); + page.waitForTimeout(200); + Object overflow = page.evaluate( + "() => document.documentElement.scrollWidth > document.documentElement.clientWidth"); + assertEquals(false, overflow, "open tooltip must not cause horizontal scroll at 360px"); + } +} diff --git a/src/browserTest/java/com/example/AviaryService/browser/HoursTableEdgeCasesTest.java b/src/browserTest/java/com/example/AviaryService/browser/HoursTableEdgeCasesTest.java index 17a83f2..35c888d 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/HoursTableEdgeCasesTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/HoursTableEdgeCasesTest.java @@ -41,7 +41,7 @@ private void assertNoConsoleErrors(List errors) { @Test void freshUserShowsZeroHoursAndEmptyAircraftInfo() { - // User with no edits — getBlockTimeHours/getTimeInServiceHours default to 0.0, + // User with no edits — getHobbsTimeHours/getTimeInServiceHours default to 0.0, // aircraft info fields are null. String username = seedUser("password"); List errors = attachConsoleErrorListener(); @@ -49,17 +49,17 @@ void freshUserShowsZeroHoursAndEmptyAircraftInfo() { loginAs(username, "password"); page.waitForLoadState(LoadState.NETWORKIDLE); - // Hours block always renders "Block Time: 0.0" / "Time in Service: 0.0" for + // Hours block always renders "Hobbs Time: 0.0" / "Time in Service: 0.0" for // a brand-new user because the getters coalesce null → 0.0. - assertThat(page.locator("#current-block-time-display")).containsText("Block Time:"); - assertThat(page.locator("#current-block-time-display")).containsText("0"); + assertThat(page.locator("#current-hobbs-time-display")).containsText("Hobbs Time:"); + assertThat(page.locator("#current-hobbs-time-display")).containsText("0"); assertThat(page.locator("#current-time-in-service-display")).containsText("Time in Service:"); assertThat(page.locator("#current-time-in-service-display")).containsText("0"); // Aircraft info inputs are empty for a fresh user. assertThat(page.locator("input[name='makeModel']")).hasValue(""); assertThat(page.locator("input[name='tailNumber']")).hasValue(""); - assertThat(page.locator("input[name='ownerName']")).hasValue(""); + assertThat(page.locator("input[name='operatorName']")).hasValue(""); assertThat(page.locator("input[name='makeModelSN']")).hasValue(""); assertNoConsoleErrors(errors); @@ -69,7 +69,7 @@ void freshUserShowsZeroHoursAndEmptyAircraftInfo() { void decimalHoursRenderWithoutTruncation() { String username = seedUser("password"); Aircraft u = aircraftOf(username); - u.setBlockTimeHours(1234.5); + u.setHobbsTimeHours(1234.5); u.setTimeInServiceHours(987.6); aircraftRepository.save(u); @@ -79,11 +79,11 @@ void decimalHoursRenderWithoutTruncation() { // The display string is built by Thymeleaf string-concat which uses // Double.toString(); 1234.5 should appear verbatim. - assertThat(page.locator("#current-block-time-display")).containsText("1234.5"); + assertThat(page.locator("#current-hobbs-time-display")).containsText("1234.5"); assertThat(page.locator("#current-time-in-service-display")).containsText("987.6"); // The "Edit" form input mirrors the same value. - assertThat(page.locator("#current-block-time")).hasValue("1234.5"); + assertThat(page.locator("#current-hobbs-time")).hasValue("1234.5"); assertThat(page.locator("#current-time-in-service")).hasValue("987.6"); assertNoConsoleErrors(errors); @@ -93,7 +93,7 @@ void decimalHoursRenderWithoutTruncation() { void veryLargeHoursValueRenders() { String username = seedUser("password"); Aircraft u = aircraftOf(username); - u.setBlockTimeHours(99999.9); + u.setHobbsTimeHours(99999.9); u.setTimeInServiceHours(99999.9); aircraftRepository.save(u); @@ -101,7 +101,7 @@ void veryLargeHoursValueRenders() { loginAs(username, "password"); page.waitForLoadState(LoadState.NETWORKIDLE); - assertThat(page.locator("#current-block-time-display")).containsText("99999.9"); + assertThat(page.locator("#current-hobbs-time-display")).containsText("99999.9"); assertThat(page.locator("#current-time-in-service-display")).containsText("99999.9"); assertNoConsoleErrors(errors); @@ -113,7 +113,7 @@ void aircraftInfoFieldsPopulateInputs() { Aircraft u = aircraftOf(username); u.setMakeModel("Cessna 172"); u.setTailNumber("N12345"); - u.setOwnerName("Daniel I."); + u.setOperatorName("Daniel I."); u.setMakeModelSN("17280342"); aircraftRepository.save(u); @@ -123,7 +123,7 @@ void aircraftInfoFieldsPopulateInputs() { assertThat(page.locator("input[name='makeModel']")).hasValue("Cessna 172"); assertThat(page.locator("input[name='tailNumber']")).hasValue("N12345"); - assertThat(page.locator("input[name='ownerName']")).hasValue("Daniel I."); + assertThat(page.locator("input[name='operatorName']")).hasValue("Daniel I."); assertThat(page.locator("input[name='makeModelSN']")).hasValue("17280342"); assertNoConsoleErrors(errors); @@ -158,7 +158,7 @@ void zeroHoursRendersWithoutCollapsingToEmpty() { // not render as blank. String username = seedUser("password"); Aircraft u = aircraftOf(username); - u.setBlockTimeHours(0.0); + u.setHobbsTimeHours(0.0); u.setTimeInServiceHours(0.0); aircraftRepository.save(u); @@ -166,9 +166,9 @@ void zeroHoursRendersWithoutCollapsingToEmpty() { loginAs(username, "password"); page.waitForLoadState(LoadState.NETWORKIDLE); - // "Block Time: 0.0" must include the "0" — not "Block Time: ". - assertThat(page.locator("#current-block-time-display")).containsText("Block Time:"); - assertThat(page.locator("#current-block-time-display")).containsText("0"); + // "Hobbs Time: 0.0" must include the "0" — not "Hobbs Time: ". + assertThat(page.locator("#current-hobbs-time-display")).containsText("Hobbs Time:"); + assertThat(page.locator("#current-hobbs-time-display")).containsText("0"); assertNoConsoleErrors(errors); } @@ -179,18 +179,18 @@ void manualSourceStampSetsHoursUpdatedDataAttributes() { // dashboard.js reads to render the "last updated" label. String username = seedUser("password"); Aircraft u = aircraftOf(username); - u.setBlockTimeHours(50.0); - u.setBlockTimeUpdatedAt(java.time.Instant.parse("2025-10-01T12:00:00Z")); - u.setBlockTimeUpdatedSource("manual"); + u.setHobbsTimeHours(50.0); + u.setHobbsTimeUpdatedAt(java.time.Instant.parse("2025-10-01T12:00:00Z")); + u.setHobbsTimeUpdatedSource("manual"); aircraftRepository.save(u); List errors = attachConsoleErrorListener(); loginAs(username, "password"); page.waitForLoadState(LoadState.NETWORKIDLE); - assertThat(page.locator("#block-time-updated")) + assertThat(page.locator("#hobbs-time-updated")) .hasAttribute("data-source", "manual"); - assertThat(page.locator("#block-time-updated")) + assertThat(page.locator("#hobbs-time-updated")) .hasAttribute("data-updated", "2025-10-01T12:00:00Z"); assertNoConsoleErrors(errors); diff --git a/src/browserTest/java/com/example/AviaryService/browser/ImportWithAiEntryTest.java b/src/browserTest/java/com/example/AviaryService/browser/ImportWithAiEntryTest.java index 7bbfeb2..156ff5a 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/ImportWithAiEntryTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/ImportWithAiEntryTest.java @@ -5,20 +5,20 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import com.example.AviaryService.entity.ServiceTimeline; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.entity.StatusSheetItem; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.microsoft.playwright.options.LoadState; /** * Ways into the Import with AI page from the dashboard: the labeled header - * control (text on desktop, named icon on a phone). The empty-timeline + * control (text on desktop, named icon on a phone). The empty Status Sheet * "Have records in a spreadsheet?" prompt was removed; an empty aircraft * shows only "Add your first maintenance item". */ class ImportWithAiEntryTest extends BrowserTestBase { @Autowired - ServiceTimelineRepository timelineRepository; + StatusSheetItemRepository statusSheetItemRepository; private void assertNoSidewaysScroll(int width) { Object overflow = page.evaluate("document.documentElement.scrollWidth > window.innerWidth"); @@ -51,10 +51,10 @@ void headerShowsNamedIconOnPhone() { assertNoSidewaysScroll(390); } - // ---- empty timeline ---- + // ---- empty Status Sheet ---- @Test - void emptyTimelineShowsFirstItemButtonAndNoImportPrompt() { + void emptyStatusSheetShowsFirstItemButtonAndNoImportPrompt() { page.setViewportSize(1280, 800); loginAs(seedUser("password123"), "password123"); @@ -68,23 +68,23 @@ void neitherControlPrints() { loginAs(seedUser("password123"), "password123"); page.emulateMedia(new com.microsoft.playwright.Page.EmulateMediaOptions() .setMedia(com.microsoft.playwright.options.Media.PRINT)); - assertThat(page.locator("#empty-timeline")).isHidden(); + assertThat(page.locator("#empty-statusSheetItem")).isHidden(); assertThat(page.locator("#connections-link")).isHidden(); } @Test - void timelineWithItemsHasNoPrompt() { + void statusSheetWithItemsHasNoPrompt() { page.setViewportSize(1280, 800); String username = seedUser("password123"); - ServiceTimeline t = new ServiceTimeline(); + StatusSheetItem t = new StatusSheetItem(); t.setUser(userRepository.findByUsername(username)); t.setAircraft(aircraftOf(userRepository.findByUsername(username))); t.setItem("Annual"); - t.setTimelineOrder(0); - timelineRepository.save(t); + t.setStatusSheetOrder(0); + statusSheetItemRepository.save(t); loginAs(username, "password123"); - assertThat(page.locator("#empty-timeline")).hasCount(0); + assertThat(page.locator("#empty-statusSheetItem")).hasCount(0); } @Test @@ -92,12 +92,12 @@ void addingFirstRowRemovesPromptWithoutReload() { page.setViewportSize(1280, 800); loginAs(seedUser("password123"), "password123"); page.waitForLoadState(LoadState.NETWORKIDLE); - assertThat(page.locator("#empty-timeline")).isVisible(); + assertThat(page.locator("#empty-statusSheetItem")).isVisible(); page.locator(".add-row td[data-label='Item'] textarea").fill("Oil change"); page.locator("td.add-cell form button.add-button").click(); assertThat(page.locator(".sortable tr[data-id]")).hasCount(1); - assertThat(page.locator("#empty-timeline")).hasCount(0); + assertThat(page.locator("#empty-statusSheetItem")).hasCount(0); } } diff --git a/src/browserTest/java/com/example/AviaryService/browser/ServiceTimelineGridTest.java b/src/browserTest/java/com/example/AviaryService/browser/StatusSheetGridTest.java similarity index 93% rename from src/browserTest/java/com/example/AviaryService/browser/ServiceTimelineGridTest.java rename to src/browserTest/java/com/example/AviaryService/browser/StatusSheetGridTest.java index 682240b..0b85355 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/ServiceTimelineGridTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/StatusSheetGridTest.java @@ -1,8 +1,8 @@ package com.example.AviaryService.browser; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.repositories.UserRepository; import com.microsoft.playwright.Locator; import com.microsoft.playwright.Page; @@ -14,7 +14,7 @@ import java.nio.file.Paths; /** - * Regression tests for the "continuous grid" service-timeline redesign. + * Regression tests for the "continuous grid" Status Sheet redesign. * * The redesign made every cell's field fill its whole grid cell (borderless, * vertically centered) so there is no dead gap above/below short controls when @@ -28,30 +28,30 @@ * These tests guard each of those against regressions and drop before/after * screenshots (saved row + add row) at two desktop widths into the build report. */ -class ServiceTimelineGridTest extends BrowserTestBase { +class StatusSheetGridTest extends BrowserTestBase { @Autowired UserRepository users; @Autowired - ServiceTimelineRepository timelines; + StatusSheetItemRepository statusSheetItems; /** A title row + one item row whose two-line Cycle makes the row tall. */ private long seedTallCycleRow(User user) { - ServiceTimeline title = new ServiceTimeline(); + StatusSheetItem title = new StatusSheetItem(); title.setUser(user); title.setAircraft(aircraftOf(user)); title.setItem("ENGINE - LEFT"); title.setIsTitle(true); - title.setTimelineOrder(1); - timelines.save(title); + title.setStatusSheetOrder(1); + statusSheetItems.save(title); - ServiceTimeline t = new ServiceTimeline(); + StatusSheetItem t = new StatusSheetItem(); t.setUser(user); t.setAircraft(aircraftOf(user)); t.setItem("Oil & filter change"); t.setIsTitle(false); - t.setTimelineOrder(2); + t.setStatusSheetOrder(2); t.setDescription("Inspect"); t.setCycleCalendarValue(50); t.setCycleCalendarUnit("DAYS"); @@ -59,7 +59,7 @@ private long seedTallCycleRow(User user) { setLastDone(t, ""); // empty → exercises the "Add date / hrs" placeholder setDueDate(t, ""); t.setTimeLeft(""); - timelines.save(t); + statusSheetItems.save(t); return t.getId(); } @@ -234,7 +234,7 @@ void screenshotsSavedAndAddRowsAtMultipleDesktopWidths() { page.setViewportSize(w, 800); page.waitForLoadState(LoadState.NETWORKIDLE); Path shot = Paths.get("build", "reports", "browserTest-screenshots", - "timeline-grid-" + w + ".png"); + "status-sheet-grid-" + w + ".png"); shot.toFile().getParentFile().mkdirs(); page.screenshot(new Page.ScreenshotOptions().setPath(shot).setFullPage(true)); } diff --git a/src/browserTest/java/com/example/AviaryService/browser/ServiceTimelineMobileDragTest.java b/src/browserTest/java/com/example/AviaryService/browser/StatusSheetMobileDragTest.java similarity index 97% rename from src/browserTest/java/com/example/AviaryService/browser/ServiceTimelineMobileDragTest.java rename to src/browserTest/java/com/example/AviaryService/browser/StatusSheetMobileDragTest.java index 357220f..a6ec34f 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/ServiceTimelineMobileDragTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/StatusSheetMobileDragTest.java @@ -1,8 +1,8 @@ package com.example.AviaryService.browser; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.repositories.UserRepository; import com.microsoft.playwright.Locator; import com.microsoft.playwright.Page; @@ -39,7 +39,7 @@ * Screenshots of the grip and a before/after drag are dropped into the build * report at build/browsertest-screenshots/. */ -class ServiceTimelineMobileDragTest extends BrowserTestBase { +class StatusSheetMobileDragTest extends BrowserTestBase { private static final int PHONE_W = 390; private static final int PHONE_H = 844; @@ -48,35 +48,35 @@ class ServiceTimelineMobileDragTest extends BrowserTestBase { UserRepository users; @Autowired - ServiceTimelineRepository timelines; + StatusSheetItemRepository statusSheetItems; /** Two plain item rows (no title) so a drag swap is unambiguous. */ private void seedTwoItems(User user) { - ServiceTimeline alpha = new ServiceTimeline(); + StatusSheetItem alpha = new StatusSheetItem(); alpha.setUser(user); alpha.setAircraft(aircraftOf(user)); alpha.setItem("Alpha Item"); alpha.setIsTitle(false); - alpha.setTimelineOrder(0); + alpha.setStatusSheetOrder(0); alpha.setDescription("Inspect"); alpha.setCycleCalendarValue(12); alpha.setCycleCalendarUnit("MONTHS"); setLastDone(alpha, "2025-06-01"); setDueDate(alpha, "2026-06-01"); - timelines.save(alpha); + statusSheetItems.save(alpha); - ServiceTimeline bravo = new ServiceTimeline(); + StatusSheetItem bravo = new StatusSheetItem(); bravo.setUser(user); bravo.setAircraft(aircraftOf(user)); bravo.setItem("Bravo Item"); bravo.setIsTitle(false); - bravo.setTimelineOrder(1); + bravo.setStatusSheetOrder(1); bravo.setDescription("Test"); bravo.setCycleCalendarValue(6); bravo.setCycleCalendarUnit("MONTHS"); setLastDone(bravo, "2025-01-01"); setDueDate(bravo, "2025-07-01"); - timelines.save(bravo); + statusSheetItems.save(bravo); } private void openDashboardOnPhone() { @@ -269,18 +269,18 @@ void calendarPickerDoesNotOverlapChevronOnMobile() { private void seedFourItems(User user) { String[] names = { "Alpha Item", "Bravo Item", "Charlie Item", "Delta Item" }; for (int i = 0; i < names.length; i++) { - ServiceTimeline t = new ServiceTimeline(); + StatusSheetItem t = new StatusSheetItem(); t.setUser(user); t.setAircraft(aircraftOf(user)); t.setItem(names[i]); t.setIsTitle(false); - t.setTimelineOrder(i); + t.setStatusSheetOrder(i); t.setDescription("Desc " + i); t.setCycleCalendarValue(12); t.setCycleCalendarUnit("MONTHS"); setLastDone(t, "2025-06-01"); setDueDate(t, "2026-06-01"); - timelines.save(t); + statusSheetItems.save(t); } } diff --git a/src/browserTest/java/com/example/AviaryService/browser/ServiceTimelineMobileLayoutTest.java b/src/browserTest/java/com/example/AviaryService/browser/StatusSheetMobileLayoutTest.java similarity index 95% rename from src/browserTest/java/com/example/AviaryService/browser/ServiceTimelineMobileLayoutTest.java rename to src/browserTest/java/com/example/AviaryService/browser/StatusSheetMobileLayoutTest.java index 55c5eaa..7705de3 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/ServiceTimelineMobileLayoutTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/StatusSheetMobileLayoutTest.java @@ -1,8 +1,8 @@ package com.example.AviaryService.browser; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.repositories.UserRepository; import com.microsoft.playwright.Locator; import com.microsoft.playwright.Page; @@ -21,7 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; /** - * Regression tests for the mobile service-timeline layout redesign: + * Regression tests for the mobile Status Sheet layout redesign: * * - each saved item card lays out 1 / 2-2 / 1 (Item headline full width; * Description|Last Done; Cycle|Due Date; Time Left full width), so the left @@ -34,7 +34,7 @@ * Screenshots of the collapsed card and the title-mode add row are dropped into * the build report. */ -class ServiceTimelineMobileLayoutTest extends BrowserTestBase { +class StatusSheetMobileLayoutTest extends BrowserTestBase { private static final int PHONE_W = 390; private static final int PHONE_H = 844; @@ -43,23 +43,23 @@ class ServiceTimelineMobileLayoutTest extends BrowserTestBase { UserRepository users; @Autowired - ServiceTimelineRepository timelines; + StatusSheetItemRepository statusSheetItems; private void seedData(User user) { - ServiceTimeline title = new ServiceTimeline(); + StatusSheetItem title = new StatusSheetItem(); title.setUser(user); title.setAircraft(aircraftOf(user)); title.setItem("ENGINE"); title.setIsTitle(true); - title.setTimelineOrder(0); - timelines.save(title); + title.setStatusSheetOrder(0); + statusSheetItems.save(title); - ServiceTimeline item = new ServiceTimeline(); + StatusSheetItem item = new StatusSheetItem(); item.setUser(user); item.setAircraft(aircraftOf(user)); item.setItem("Annual Inspection"); item.setIsTitle(false); - item.setTimelineOrder(1); + item.setStatusSheetOrder(1); item.setDescription("Inspect"); item.setCycleCalendarValue(12); item.setCycleCalendarUnit("MONTHS"); @@ -67,7 +67,7 @@ private void seedData(User user) { setLastDone(item, "2025-06-01"); setDueDate(item, "2026-06-01 2450.0"); item.setTimeLeft("11 mo\n86.0 hrs"); - timelines.save(item); + statusSheetItems.save(item); } private double[] rectOf(Locator loc) { @@ -279,7 +279,7 @@ void timeLeftIsHorizontallyCentered() { } @Test - void serviceTimelineNeverOverflowsViewportAcrossBreakpoints() { + void statusSheetNeverOverflowsViewportAcrossBreakpoints() { String username = seedUser("password"); User u = users.findByUsername(username); seedData(u); @@ -299,7 +299,7 @@ void serviceTimelineNeverOverflowsViewportAcrossBreakpoints() { } // Visual evidence at a width that used to overflow with the desktop table. if (w == 850) { - Path shot = Paths.get("build", "browsertest-screenshots", "timeline-850-no-overflow.png"); + Path shot = Paths.get("build", "browsertest-screenshots", "status-sheet-850-no-overflow.png"); try { Files.createDirectories(shot.getParent()); } catch (Exception ignored) { } @@ -307,7 +307,7 @@ void serviceTimelineNeverOverflowsViewportAcrossBreakpoints() { } } if (over.length() > 0) { - throw new AssertionError("Service timeline overflows the viewport at:" + over); + throw new AssertionError("Status Sheet overflows the viewport at:" + over); } } diff --git a/src/browserTest/java/com/example/AviaryService/browser/ServiceTimelineTableEdgeCasesTest.java b/src/browserTest/java/com/example/AviaryService/browser/StatusSheetTableEdgeCasesTest.java similarity index 88% rename from src/browserTest/java/com/example/AviaryService/browser/ServiceTimelineTableEdgeCasesTest.java rename to src/browserTest/java/com/example/AviaryService/browser/StatusSheetTableEdgeCasesTest.java index 08cd669..bfb84b4 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/ServiceTimelineTableEdgeCasesTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/StatusSheetTableEdgeCasesTest.java @@ -1,8 +1,8 @@ package com.example.AviaryService.browser; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.repositories.UserRepository; import com.microsoft.playwright.options.LoadState; import org.junit.jupiter.api.Test; @@ -14,22 +14,22 @@ import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; /** - * Edge-case rendering tests for the Service Timeline table. + * Edge-case rendering tests for the Status Sheet table. * - * The timeline tbody contains both title rows (.title-row) and regular + * The Status Sheet item tbody contains both title rows (.title-row) and regular * item rows (.auto-save-row). Each row carries data-id; cells have * data-label="..." so we can locate by column without relying on * positional indexing that breaks when the schema shifts. * - * Add a test here every time the timeline table is fixed or extended. + * Add a test here every time the Status Sheet table is fixed or extended. */ -class ServiceTimelineTableEdgeCasesTest extends BrowserTestBase { +class StatusSheetTableEdgeCasesTest extends BrowserTestBase { @Autowired UserRepository users; @Autowired - ServiceTimelineRepository timelines; + StatusSheetItemRepository statusSheetItems; private List attachConsoleErrorListener() { List errors = new ArrayList<>(); @@ -43,24 +43,24 @@ private void assertNoConsoleErrors(List errors) { if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); } - /** Build + save a regular (non-title) timeline row. */ - private ServiceTimeline saveItem(User user, int order, String item, String description, + /** Build + save a regular (non-title) statusSheetItem row. */ + private StatusSheetItem saveItem(User user, int order, String item, String description, String lastDone, String dueDate, String timeLeft) { - ServiceTimeline t = new ServiceTimeline(); + StatusSheetItem t = new StatusSheetItem(); t.setUser(user); t.setAircraft(aircraftOf(user)); t.setItem(item); t.setIsTitle(false); - t.setTimelineOrder(order); + t.setStatusSheetOrder(order); t.setDescription(description); setLastDone(t, lastDone); setDueDate(t, dueDate); t.setTimeLeft(timeLeft); - return timelines.save(t); + return statusSheetItems.save(t); } @Test - void emptyTimelineRendersTableWithNoRows() { + void emptyStatusSheetRendersTableWithNoRows() { String username = seedUser("password"); List errors = attachConsoleErrorListener(); @@ -80,13 +80,13 @@ void titleRowRendersWithItemTextInTitleCell() { String username = seedUser("password"); User u = users.findByUsername(username); - ServiceTimeline title = new ServiceTimeline(); + StatusSheetItem title = new StatusSheetItem(); title.setUser(u); title.setAircraft(aircraftOf(u)); title.setItem("100-Hour Inspections"); title.setIsTitle(true); - title.setTimelineOrder(1); - timelines.save(title); + title.setStatusSheetOrder(1); + statusSheetItems.save(title); List errors = attachConsoleErrorListener(); loginAs(username, "password"); @@ -106,7 +106,7 @@ void titleRowRendersWithItemTextInTitleCell() { void regularRowRendersItemAndDescriptionAndDateFields() { String username = seedUser("password"); User u = users.findByUsername(username); - ServiceTimeline t = saveItem(u, 1, "Oil change", "Inspect", + StatusSheetItem t = saveItem(u, 1, "Oil change", "Inspect", "2025-10-01", "2025-12-01", "61 days"); List errors = attachConsoleErrorListener(); @@ -154,7 +154,7 @@ void regularRowRendersItemAndDescriptionAndDateFields() { void emptyDescriptionRendersWithoutFallingBackToHtmlDefault() { String username = seedUser("password"); User u = users.findByUsername(username); - ServiceTimeline t = saveItem(u, 1, "Item with no description", "", + StatusSheetItem t = saveItem(u, 1, "Item with no description", "", "2025-10-01", "2025-12-01", ""); List errors = attachConsoleErrorListener(); @@ -180,7 +180,7 @@ void veryLongItemTextRendersWithoutBreakingLayout() { // If the column is ever widened, bump this; if it shrinks, this test // will fail loudly which is the correct behaviour. String longText = "X".repeat(240); - ServiceTimeline t = saveItem(u, 1, longText, "Inspect", + StatusSheetItem t = saveItem(u, 1, longText, "Inspect", "2025-10-01", "2025-12-01", "61 days"); List errors = attachConsoleErrorListener(); @@ -199,7 +199,7 @@ void specialCharsInItemAndDescriptionAreEscapedNotInterpreted() { User u = users.findByUsername(username); // If Thymeleaf forgets to escape, this string injects markup. String injection = " & \"quote\" 'apos'"; - ServiceTimeline t = saveItem(u, 1, injection, injection, + StatusSheetItem t = saveItem(u, 1, injection, injection, "2025-10-01", "2025-12-01", "61 days"); List errors = attachConsoleErrorListener(); @@ -222,7 +222,7 @@ void specialCharsInItemAndDescriptionAreEscapedNotInterpreted() { } @Test - void multipleRowsRenderInTimelineOrder() { + void multipleRowsRenderInStatusSheetOrder() { String username = seedUser("password"); User u = users.findByUsername(username); // Insert out of order to make sure the sort actually fires. @@ -236,7 +236,7 @@ void multipleRowsRenderInTimelineOrder() { var itemTextareas = page.locator("tr.auto-save-row textarea[name='item']"); assertThat(itemTextareas).hasCount(3); - // findByUserOrderByTimelineOrderAsc → First, Second, Third. + // findByUserOrderByStatusSheetOrderAsc → First, Second, Third. assertThat(itemTextareas.nth(0)).hasValue("First"); assertThat(itemTextareas.nth(1)).hasValue("Second"); assertThat(itemTextareas.nth(2)).hasValue("Third"); diff --git a/src/browserTest/java/com/example/AviaryService/browser/TimeLeftPillsTest.java b/src/browserTest/java/com/example/AviaryService/browser/TimeLeftPillsTest.java new file mode 100644 index 0000000..c1e60f2 --- /dev/null +++ b/src/browserTest/java/com/example/AviaryService/browser/TimeLeftPillsTest.java @@ -0,0 +1,159 @@ +package com.example.AviaryService.browser; + +import com.example.AviaryService.entity.Aircraft; +import com.example.AviaryService.entity.StatusSheetItem; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.StatusSheetItemRepository; +import com.microsoft.playwright.Locator; +import com.microsoft.playwright.Page; +import com.microsoft.playwright.options.LoadState; +import com.microsoft.playwright.options.Media; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + +import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Spec 011: Time Left as colored pills, no icons; "overdue" after an overdue + * pill, once if both are; N/A when nothing is set; plain words in print. + */ +class TimeLeftPillsTest extends BrowserTestBase { + + @Autowired + StatusSheetItemRepository statusSheetItems; + + private User user; + private int order; + + private StatusSheetItem row(String name, String dueDate, String dueHours) { + StatusSheetItem t = new StatusSheetItem(); + t.setUser(user); + t.setAircraft(aircraftOf(user)); + t.setItem(name); + t.setIsTitle(false); + t.setStatusSheetOrder(order++); + t.setDueDateDate(dueDate); + t.setDueDateHours(dueHours); + return statusSheetItems.save(t); + } + + private Locator cellOf(StatusSheetItem i) { + return page.locator("tr.auto-save-row[data-id='" + i.getId() + "'] .time-left"); + } + + private List classesOfPills(Locator cell) { + List out = new ArrayList<>(); + for (Locator p : cell.locator(".tl-pill").all()) { + String c = p.getAttribute("class"); + out.add(c.contains("tl-over") ? "over" : c.contains("tl-soon") ? "soon" : "ok"); + } + return out; + } + + private List openWith(int width) { + String username = seedUser("password"); + user = userRepository.findByUsername(username); + Aircraft a = aircraftOf(user); + a.setTimeInServiceHours(1000.0); + aircraftRepository.save(a); + List errors = new ArrayList<>(); + page.onConsoleMessage(m -> { if ("error".equals(m.type())) errors.add(m.text()); }); + page.setViewportSize(width, 900); + return errors; + } + + private void login() { + loginAs(user.getUsername(), "password"); + page.waitForLoadState(LoadState.NETWORKIDLE); + } + + @Test + void everyCaseRendersAsAgreed() { + List errors = openWith(1400); + LocalDate today = LocalDate.now(); + StatusSheetItem bothFine = row("both fine", today.plusDays(45).toString(), "1035.5"); + StatusSheetItem hoursOver = row("hours over", today.plusDays(45).toString(), "520"); + StatusSheetItem dateOver = row("date over", today.minusDays(12).toString(), "1035.5"); + StatusSheetItem bothOver = row("both over", today.minusDays(12).toString(), "520"); + StatusSheetItem dateOnly = row("date only", today.plusDays(45).toString(), null); + StatusSheetItem hoursOnly = row("hours only", null, "520"); + StatusSheetItem soon = row("soon", today.plusDays(5).toString(), "1004"); + StatusSheetItem nothing = row("nothing", null, null); + login(); + + Locator c = cellOf(bothFine); + assertThat(c.locator(".tl-pill")).hasText(new String[] {"45 d", "35.5 h"}); + assertEquals(List.of("ok", "ok"), classesOfPills(c)); + assertThat(c.locator(".tl-overdue")).hasCount(0); + + c = cellOf(hoursOver); + assertThat(c.locator(".tl-pill")).hasText(new String[] {"45 d", "480 h"}); + assertEquals(List.of("ok", "over"), classesOfPills(c)); + assertThat(c.locator(".tl-overdue")).hasCount(1); + assertThat(c.locator(".tl-pills")).hasText("45 d480 hoverdue"); // word right after the hours pill + + c = cellOf(dateOver); + assertEquals(List.of("over", "ok"), classesOfPills(c)); + assertThat(c.locator(".tl-pills")).hasText("12 doverdue35.5 h"); // word right after the date pill + + c = cellOf(bothOver); + assertEquals(List.of("over", "over"), classesOfPills(c)); + assertThat(c.locator(".tl-overdue")).hasCount(1); // once, after both + assertThat(c.locator(".tl-pills")).hasText("12 d480 hoverdue"); + + c = cellOf(dateOnly); + assertThat(c.locator(".tl-pill")).hasText(new String[] {"45 d"}); + + c = cellOf(hoursOnly); + assertThat(c.locator(".tl-pill")).hasText(new String[] {"480 h"}); + assertThat(c.locator(".tl-overdue")).hasCount(1); + + assertEquals(List.of("soon", "soon"), classesOfPills(cellOf(soon))); + + assertThat(cellOf(nothing)).hasText("N/A"); + assertThat(cellOf(nothing).locator(".tl-pill")).hasCount(0); + + page.locator("#sortable-info-table").screenshot(new Locator.ScreenshotOptions() + .setPath(java.nio.file.Paths.get("build/screenshots/time-left-pills.png"))); + + // No icons anywhere in Time Left. + assertEquals(0, page.locator(".time-left i, .time-left svg").count()); + + // Print: plain words, no pills. + page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.PRINT)); + assertThat(cellOf(hoursOver).locator(".tl-pills")).isHidden(); + assertThat(cellOf(hoursOver).locator(".tl-plain")).isVisible(); + assertThat(cellOf(hoursOver).locator(".tl-plain")).hasText("45 days left · 480 hrs overdue"); + assertThat(cellOf(bothOver).locator(".tl-plain")).hasText("12 days overdue · 480 hrs overdue"); + page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.SCREEN)); + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } + + @Test + void pillsFitAPhoneAndUpdateLive() { + List errors = openWith(360); + LocalDate today = LocalDate.now(); + StatusSheetItem r = row("phone", today.plusDays(400).toString(), "520"); + login(); + + Locator c = cellOf(r); + assertThat(c.locator(".tl-pill")).hasCount(2); + Object overflow = c.evaluate("el => el.scrollWidth > el.clientWidth + 1"); + assertEquals(false, overflow, "pills must not overflow the cell at 360px"); + Object pageOverflow = page.evaluate("() => document.documentElement.scrollWidth > document.documentElement.clientWidth"); + assertEquals(false, pageOverflow, "no sideways scroll at 360px"); + + // Live: change the Due Date hours; the pill updates without reload. + Locator dueHours = page.locator("tr.auto-save-row[data-id='" + r.getId() + "'] td:nth-child(6) input.extra-input[type='text']"); + dueHours.fill("1100"); + assertThat(c.locator(".tl-pill").nth(1)).hasText("100 h"); + assertTrue(c.locator(".tl-pill").nth(1).getAttribute("class").contains("tl-ok")); + if (!errors.isEmpty()) throw new AssertionError("Console errors: " + errors); + } +} diff --git a/src/browserTest/java/com/example/AviaryService/browser/TitleDragTest.java b/src/browserTest/java/com/example/AviaryService/browser/TitleDragTest.java index 368eea1..a6c7c17 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/TitleDragTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/TitleDragTest.java @@ -9,9 +9,9 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.microsoft.playwright.Locator; import com.microsoft.playwright.Mouse; import com.microsoft.playwright.options.BoundingBox; @@ -25,7 +25,7 @@ class TitleDragTest extends BrowserTestBase { @Autowired - ServiceTimelineRepository timelines; + StatusSheetItemRepository statusSheetItems; private User seed() { String username = seedUser("password"); @@ -37,13 +37,13 @@ private User seed() { } private void save(User u, String item, boolean isTitle, int order) { - ServiceTimeline t = new ServiceTimeline(); + StatusSheetItem t = new StatusSheetItem(); t.setUser(u); t.setAircraft(aircraftOf(u)); t.setItem(item); t.setIsTitle(isTitle); - t.setTimelineOrder(order); - timelines.save(t); + t.setStatusSheetOrder(order); + statusSheetItems.save(t); } private List domOrder() { @@ -75,7 +75,7 @@ private void dragSectionBAboveSectionA() { private void assertSectionBFirstAndSaved(User u) { assertEquals("Section B", domOrder().get(0), "Section B should be first after the drag, order was " + domOrder()); - List saved = timelines.findByUserOrderByTimelineOrderAsc(u); + List saved = statusSheetItems.findByUserOrderByStatusSheetOrderAsc(u); assertEquals("Section B", saved.get(0).getItem(), "New order should be saved to the server"); } @@ -91,7 +91,7 @@ void titleCanBeDraggedOnDesktop() { } // Clicking a title shows only that section; the back bar must appear right - // above the timeline (it used to land above the aircraft-info table). + // above the Status Sheet (it used to land above the aircraft-info table). @Test void clickingTitleFiltersAndBackButtonRestoresFullList() { User u = seed(); @@ -105,7 +105,7 @@ void clickingTitleFiltersAndBackButtonRestoresFullList() { assertTrue(bar.innerText().contains("Section B"), "Bar should name the section"); assertTrue((Boolean) page.evaluate( "() => document.querySelector('.section-filter-bar').nextElementSibling.id === 'sortable-info-table'"), - "Back bar should sit directly above the Service Timeline table"); + "Back bar should sit directly above the Status Sheet table"); assertTrue(!page.locator("tr.title-row").nth(0).isVisible(), "Other sections should be hidden"); page.locator(".back-to-full-list-button").click(); diff --git a/src/browserTest/java/com/example/AviaryService/browser/TitleRowHoverTest.java b/src/browserTest/java/com/example/AviaryService/browser/TitleRowHoverTest.java new file mode 100644 index 0000000..056ddfa --- /dev/null +++ b/src/browserTest/java/com/example/AviaryService/browser/TitleRowHoverTest.java @@ -0,0 +1,73 @@ +package com.example.AviaryService.browser; + +import com.example.AviaryService.entity.StatusSheetItem; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.StatusSheetItemRepository; +import com.microsoft.playwright.Locator; +import com.microsoft.playwright.options.LoadState; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Spec 009: hovering any part of a title row darkens the whole bar (grip, + * title, empty cell and trash can) together, and only that row. + */ +class TitleRowHoverTest extends BrowserTestBase { + + @Autowired + StatusSheetItemRepository statusSheetItems; + + private StatusSheetItem save(User user, String text, boolean title, int order) { + StatusSheetItem t = new StatusSheetItem(); + t.setUser(user); + t.setAircraft(aircraftOf(user)); + t.setItem(text); + t.setIsTitle(title); + t.setStatusSheetOrder(order); + return statusSheetItems.save(t); + } + + @SuppressWarnings("unchecked") + private List cellColors(Locator row) { + return (List) row.evaluate("r => [...r.querySelectorAll('td')]" + + ".filter(td => getComputedStyle(td).display !== 'none')" + + ".map(td => getComputedStyle(td).backgroundColor)"); + } + + @Test + void wholeTitleRowDarkensTogetherAndOnlyThatRow() { + String username = seedUser("password"); + User user = userRepository.findByUsername(username); + StatusSheetItem engine = save(user, "Engine", true, 0); + save(user, "Oil change", false, 1); + StatusSheetItem airframe = save(user, "Airframe", true, 2); + + page.setViewportSize(1400, 900); + loginAs(username, "password"); + page.waitForLoadState(LoadState.NETWORKIDLE); + + Locator row = page.locator("tr.title-row[data-id='" + engine.getId() + "']"); + Locator other = page.locator("tr.title-row[data-id='" + airframe.getId() + "']"); + page.mouse().move(0, 0); + List normal = cellColors(row); + assertEquals(1, normal.stream().distinct().count(), "title bar is one color at rest: " + normal); + + for (String part : new String[] {".title-cell", ".grip-cell", ".delete-cell"}) { + row.locator(part).hover(); + page.waitForTimeout(100); + List hovered = cellColors(row); + assertEquals(1, hovered.stream().distinct().count(), "hovering " + part + ": " + hovered); + assertNotEquals(normal.get(0), hovered.get(0), "hovering " + part + " darkens the bar"); + assertEquals(normal, cellColors(other), "the other title row stays normal"); + } + + page.mouse().move(0, 0); + page.waitForTimeout(100); + assertEquals(normal, cellColors(row), "back to normal after the mouse leaves"); + } +} diff --git a/src/main/java/com/example/AviaryService/config/AircraftBackfill.java b/src/main/java/com/example/AviaryService/config/AircraftBackfill.java index 9f3de5d..cd9b1c1 100644 --- a/src/main/java/com/example/AviaryService/config/AircraftBackfill.java +++ b/src/main/java/com/example/AviaryService/config/AircraftBackfill.java @@ -32,7 +32,7 @@ // aircraft's subscription. // 2. For each user with no aircraft: creates one from the legacy users // columns (info card, both hours, both baselines, updated-at/source), -// then attaches that user's timeline rows, flights, suggestions, +// then attaches that user's Status Sheet item rows, flights, suggestions, // subscription and import proposals, and sets last_viewed_aircraft_id. // // Idempotent: users who already have an aircraft are skipped and only NULL diff --git a/src/main/java/com/example/AviaryService/config/DataSeeder.java b/src/main/java/com/example/AviaryService/config/DataSeeder.java index 6c7b21a..7e76508 100644 --- a/src/main/java/com/example/AviaryService/config/DataSeeder.java +++ b/src/main/java/com/example/AviaryService/config/DataSeeder.java @@ -5,10 +5,10 @@ import org.springframework.stereotype.Component; import com.example.AviaryService.entity.Aircraft; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.AircraftRepository; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.repositories.UserRepository; import java.util.List; @@ -17,14 +17,14 @@ public class DataSeeder implements CommandLineRunner { private final UserRepository userRepository; - private final ServiceTimelineRepository serviceTimelineRepository; + private final StatusSheetItemRepository statusSheetItemRepository; private final PasswordEncoder passwordEncoder; private final AircraftRepository aircraftRepository; - public DataSeeder(UserRepository userRepository, ServiceTimelineRepository serviceTimelineRepository, + public DataSeeder(UserRepository userRepository, StatusSheetItemRepository statusSheetItemRepository, PasswordEncoder passwordEncoder, AircraftRepository aircraftRepository) { this.userRepository = userRepository; - this.serviceTimelineRepository = serviceTimelineRepository; + this.statusSheetItemRepository = statusSheetItemRepository; this.passwordEncoder = passwordEncoder; this.aircraftRepository = aircraftRepository; } @@ -45,47 +45,47 @@ public void run(String... args) throws Exception { userRepository.save(Daniel); userRepository.save(Tomas); - // One aircraft each, which every timeline row below belongs to. + // One aircraft each, which every Status Sheet item row below belongs to. Aircraft danielPlane = firstAircraft(Daniel, 3000, 2500); Aircraft tomasPlane = firstAircraft(Tomas, 3000, 2500); // Tomas — aircraft at ~2480 total hours, ~25 hr/month // constructor: (item, isTitle, description, cycleCalendarUnit, cycleCalendarValue, cycleHours, lastDoneDate, lastDoneHours, dueDateDate, dueDateHours, timeLeft, user) - ServiceTimeline t1 = new ServiceTimeline("Annual Inspection", false, "Inspect aircraft systems per FAR 91.409", "MONTHS", 12, null, "2026-01-15", "2380", "2027-01-15", "2680", "7 months", Tomas); - ServiceTimeline t2 = new ServiceTimeline("100-Hour Inspection", false, "Inspect per FAR 91.409(b)", null, null, 100.0, "2026-04-10", "2400", "2026-08-15", "2500", "20 hours", Tomas); - ServiceTimeline t3 = new ServiceTimeline("Oil Change", false, "Replace engine oil and filter", null, null, 50.0, "2026-05-20", "2455", "2026-07-10", "2505", "25 hours", Tomas); - ServiceTimeline t4 = new ServiceTimeline("Spark Plug Inspection", false, "Clean, gap, and rotate spark plugs", null, null, 100.0, "2026-04-10", "2400", "2026-08-15", "2500", "20 hours", Tomas); - ServiceTimeline t5 = new ServiceTimeline("ELT Battery Replacement", false, "Replace ELT battery per TSO-C91a", "MONTHS", 24, null, "2024-06-10", "2100", "2026-06-10", "2490", "Overdue", Tomas); - ServiceTimeline t6 = new ServiceTimeline("Transponder Test", false, "Test per FAR 91.413", "MONTHS", 24, null, "2025-03-10", "2250", "2027-03-10", "2850", "9 months", Tomas); - ServiceTimeline t7 = new ServiceTimeline("Magneto Inspection", false, "Inspect and time magnetos", null, null, 500.0, "2025-01-15", "2000", "2027-01-01", "2500", "20 hours", Tomas); - ServiceTimeline t8 = new ServiceTimeline("Pitot-Static System Test", false, "Test per FAR 91.411", "MONTHS", 24, null, "2025-03-10", "2250", "2027-03-10", "2850", "9 months", Tomas); - - t1.setTimelineOrder(1); t2.setTimelineOrder(2); t3.setTimelineOrder(3); t4.setTimelineOrder(4); - t5.setTimelineOrder(5); t6.setTimelineOrder(6); t7.setTimelineOrder(7); t8.setTimelineOrder(8); + StatusSheetItem t1 = new StatusSheetItem("Annual Inspection", false, "Inspect aircraft systems per FAR 91.409", "MONTHS", 12, null, "2026-01-15", "2380", "2027-01-15", "2680", "7 months", Tomas); + StatusSheetItem t2 = new StatusSheetItem("100-Hour Inspection", false, "Inspect per FAR 91.409(b)", null, null, 100.0, "2026-04-10", "2400", "2026-08-15", "2500", "20 hours", Tomas); + StatusSheetItem t3 = new StatusSheetItem("Oil Change", false, "Replace engine oil and filter", null, null, 50.0, "2026-05-20", "2455", "2026-07-10", "2505", "25 hours", Tomas); + StatusSheetItem t4 = new StatusSheetItem("Spark Plug Inspection", false, "Clean, gap, and rotate spark plugs", null, null, 100.0, "2026-04-10", "2400", "2026-08-15", "2500", "20 hours", Tomas); + StatusSheetItem t5 = new StatusSheetItem("ELT Battery Replacement", false, "Replace ELT battery per TSO-C91a", "MONTHS", 24, null, "2024-06-10", "2100", "2026-06-10", "2490", "Overdue", Tomas); + StatusSheetItem t6 = new StatusSheetItem("Transponder Test", false, "Test per FAR 91.413", "MONTHS", 24, null, "2025-03-10", "2250", "2027-03-10", "2850", "9 months", Tomas); + StatusSheetItem t7 = new StatusSheetItem("Magneto Inspection", false, "Inspect and time magnetos", null, null, 500.0, "2025-01-15", "2000", "2027-01-01", "2500", "20 hours", Tomas); + StatusSheetItem t8 = new StatusSheetItem("Pitot-Static System Test", false, "Test per FAR 91.411", "MONTHS", 24, null, "2025-03-10", "2250", "2027-03-10", "2850", "9 months", Tomas); + + t1.setStatusSheetOrder(1); t2.setStatusSheetOrder(2); t3.setStatusSheetOrder(3); t4.setStatusSheetOrder(4); + t5.setStatusSheetOrder(5); t6.setStatusSheetOrder(6); t7.setStatusSheetOrder(7); t8.setStatusSheetOrder(8); // Daniel — aircraft at ~1850 total hours, ~20 hr/month - ServiceTimeline d1 = new ServiceTimeline("Annual Inspection", false, "Inspect aircraft systems per FAR 91.409", "MONTHS", 12, null, "2026-02-01", "1780", "2027-02-01", "2020", "8 months", Daniel); - ServiceTimeline d2 = new ServiceTimeline("Oil Filter Replacement", false, "Replace oil filter", null, null, 50.0, "2026-05-15", "1820", "2026-08-01", "1870", "20 hours", Daniel); - ServiceTimeline d3 = new ServiceTimeline("Landing Gear Inspection", false, "Inspect gear, doors, and actuators", "MONTHS", 12, null, "2026-02-01", "1780", "2027-02-01", "2020", "8 months", Daniel); - ServiceTimeline d4 = new ServiceTimeline("VOR Check", false, "VOR accuracy check per FAR 91.171", "DAYS", 30, null, "2026-05-25", "1838", "2026-06-24", "1854", "12 days", Daniel); - ServiceTimeline d5 = new ServiceTimeline("Brake Lining Inspection", false, "Inspect brake pads and discs", null, null, 100.0, "2026-03-10", "1770", "2026-09-15", "1870", "20 hours", Daniel); - ServiceTimeline d6 = new ServiceTimeline("Propeller Inspection", false, "Inspect blades, hub, and spinner", "MONTHS", 12, null, "2026-02-01", "1780", "2027-02-01", "2020", "8 months", Daniel); - ServiceTimeline d7 = new ServiceTimeline("Fuel System Inspection", false, "Inspect tanks, lines, and fuel caps", "MONTHS", 12, null, "2026-02-01", "1780", "2027-02-01", "2020", "8 months", Daniel); - ServiceTimeline d8 = new ServiceTimeline("Control Cable Inspection", false, "Inspect cables for wear, routing, tension","MONTHS", 12, null, "2026-02-01", "1780", "2027-02-01", "2020", "8 months", Daniel); - - d1.setTimelineOrder(1); d2.setTimelineOrder(2); d3.setTimelineOrder(3); d4.setTimelineOrder(4); - d5.setTimelineOrder(5); d6.setTimelineOrder(6); d7.setTimelineOrder(7); d8.setTimelineOrder(8); - - for (ServiceTimeline t : List.of(t1, t2, t3, t4, t5, t6, t7, t8)) t.setAircraft(tomasPlane); - for (ServiceTimeline d : List.of(d1, d2, d3, d4, d5, d6, d7, d8)) d.setAircraft(danielPlane); - - serviceTimelineRepository.saveAll(List.of(t1, t2, t3, t4, t5, t6, t7, t8, d1, d2, d3, d4, d5, d6, d7, d8)); + StatusSheetItem d1 = new StatusSheetItem("Annual Inspection", false, "Inspect aircraft systems per FAR 91.409", "MONTHS", 12, null, "2026-02-01", "1780", "2027-02-01", "2020", "8 months", Daniel); + StatusSheetItem d2 = new StatusSheetItem("Oil Filter Replacement", false, "Replace oil filter", null, null, 50.0, "2026-05-15", "1820", "2026-08-01", "1870", "20 hours", Daniel); + StatusSheetItem d3 = new StatusSheetItem("Landing Gear Inspection", false, "Inspect gear, doors, and actuators", "MONTHS", 12, null, "2026-02-01", "1780", "2027-02-01", "2020", "8 months", Daniel); + StatusSheetItem d4 = new StatusSheetItem("VOR Check", false, "VOR accuracy check per FAR 91.171", "DAYS", 30, null, "2026-05-25", "1838", "2026-06-24", "1854", "12 days", Daniel); + StatusSheetItem d5 = new StatusSheetItem("Brake Lining Inspection", false, "Inspect brake pads and discs", null, null, 100.0, "2026-03-10", "1770", "2026-09-15", "1870", "20 hours", Daniel); + StatusSheetItem d6 = new StatusSheetItem("Propeller Inspection", false, "Inspect blades, hub, and spinner", "MONTHS", 12, null, "2026-02-01", "1780", "2027-02-01", "2020", "8 months", Daniel); + StatusSheetItem d7 = new StatusSheetItem("Fuel System Inspection", false, "Inspect tanks, lines, and fuel caps", "MONTHS", 12, null, "2026-02-01", "1780", "2027-02-01", "2020", "8 months", Daniel); + StatusSheetItem d8 = new StatusSheetItem("Control Cable Inspection", false, "Inspect cables for wear, routing, tension","MONTHS", 12, null, "2026-02-01", "1780", "2027-02-01", "2020", "8 months", Daniel); + + d1.setStatusSheetOrder(1); d2.setStatusSheetOrder(2); d3.setStatusSheetOrder(3); d4.setStatusSheetOrder(4); + d5.setStatusSheetOrder(5); d6.setStatusSheetOrder(6); d7.setStatusSheetOrder(7); d8.setStatusSheetOrder(8); + + for (StatusSheetItem t : List.of(t1, t2, t3, t4, t5, t6, t7, t8)) t.setAircraft(tomasPlane); + for (StatusSheetItem d : List.of(d1, d2, d3, d4, d5, d6, d7, d8)) d.setAircraft(danielPlane); + + statusSheetItemRepository.saveAll(List.of(t1, t2, t3, t4, t5, t6, t7, t8, d1, d2, d3, d4, d5, d6, d7, d8)); } - private Aircraft firstAircraft(User user, double blockTime, double timeInService) { + private Aircraft firstAircraft(User user, double hobbsTime, double timeInService) { Aircraft a = new Aircraft(user); - a.setBlockTimeHours(blockTime); + a.setHobbsTimeHours(hobbsTime); a.setTimeInServiceHours(timeInService); a = aircraftRepository.save(a); user.setLastViewedAircraft(a); diff --git a/src/main/java/com/example/AviaryService/config/DemoDataSeeder.java b/src/main/java/com/example/AviaryService/config/DemoDataSeeder.java index acca437..db7d45d 100644 --- a/src/main/java/com/example/AviaryService/config/DemoDataSeeder.java +++ b/src/main/java/com/example/AviaryService/config/DemoDataSeeder.java @@ -15,12 +15,12 @@ import com.example.AviaryService.entity.Aircraft; import com.example.AviaryService.entity.FlightLog; import com.example.AviaryService.entity.FlightSuggestion; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.AircraftRepository; import com.example.AviaryService.repositories.FlightLogRepository; import com.example.AviaryService.repositories.FlightSuggestionRepository; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.repositories.UserRepository; // Local-only demo account for eyeballing the dashboard: log in as @@ -37,17 +37,17 @@ public class DemoDataSeeder implements CommandLineRunner { static final String PASSWORD = "Demo-pass-123"; private final UserRepository userRepository; - private final ServiceTimelineRepository timelineRepository; + private final StatusSheetItemRepository statusSheetItemRepository; private final FlightLogRepository flightLogRepository; private final FlightSuggestionRepository suggestionRepository; private final PasswordEncoder passwordEncoder; private final AircraftRepository aircraftRepository; - public DemoDataSeeder(UserRepository userRepository, ServiceTimelineRepository timelineRepository, + public DemoDataSeeder(UserRepository userRepository, StatusSheetItemRepository statusSheetItemRepository, FlightLogRepository flightLogRepository, FlightSuggestionRepository suggestionRepository, PasswordEncoder passwordEncoder, AircraftRepository aircraftRepository) { this.userRepository = userRepository; - this.timelineRepository = timelineRepository; + this.statusSheetItemRepository = statusSheetItemRepository; this.flightLogRepository = flightLogRepository; this.suggestionRepository = suggestionRepository; this.passwordEncoder = passwordEncoder; @@ -70,7 +70,7 @@ public void run(String... args) { demo.setLastViewedAircraft(sr22); userRepository.save(demo); - List rows = new ArrayList<>(); + List rows = new ArrayList<>(); rows.add(title("Engine", demo)); rows.add(item("Oil Change", "Replace", null, null, 50.0, today.minusMonths(1), "1383.9", null, "1433.9", demo)); // 15.2 hours left @@ -91,10 +91,10 @@ public void run(String... args) { rows.add(item("Pitot-Static Check", "Test", "MONTHS", 24, null, today.minusMonths(20), null, today.plusMonths(4), null, demo)); // 4 mo for (int i = 0; i < rows.size(); i++) { - rows.get(i).setTimelineOrder(i); + rows.get(i).setStatusSheetOrder(i); rows.get(i).setAircraft(sr22); } - timelineRepository.saveAll(rows); + statusSheetItemRepository.saveAll(rows); // Log book: a chain of recent flights, oldest first, each picking up // where the last left off so the meters are consistent. @@ -103,22 +103,22 @@ public void run(String... args) { {"KTMB", "KAPF", "1.8", "1.6"}, {"KAPF", "KTMB", "1.7", "1.5"}, {"KTMB", "KEYW", "2.1", "1.9"}, {"KEYW", "KTMB", "2.0", "1.8"}, }; - double block = 1532.4 - sum(legs, 2); + double hobbs = 1532.4 - sum(legs, 2); double service = 1418.7 - sum(legs, 3); Instant start = today.minusDays(20).atTime(14, 0).toInstant(ZoneOffset.UTC); for (String[] leg : legs) { - double blockLen = Double.parseDouble(leg[2]); + double hobbsLen = Double.parseDouble(leg[2]); double serviceLen = Double.parseDouble(leg[3]); - FlightLog log = new FlightLog(leg[0], leg[1], round(block + blockLen), round(block), + FlightLog log = new FlightLog(leg[0], leg[1], round(hobbs + hobbsLen), round(hobbs), round(service + serviceLen), round(service), demo); log.setSource("manual"); log.setAircraft(sr22); - log.setBlockTimeStart(start); - log.setBlockTimeEnd(start.plus(minutes(blockLen))); + log.setHobbsTimeStart(start); + log.setHobbsTimeEnd(start.plus(minutes(hobbsLen))); log.setTimeInServiceStart(start.plus(Duration.ofMinutes(6))); log.setTimeInServiceEnd(start.plus(Duration.ofMinutes(6)).plus(minutes(serviceLen))); flightLogRepository.save(log); - block += blockLen; + hobbs += hobbsLen; service += serviceLen; start = start.plus(Duration.ofDays(3)); } @@ -140,9 +140,9 @@ public void run(String... args) { seedSecondAircraft(demo, pa28, today); } - // N731KR: a smaller timeline with one overdue item, and a few flights. + // N731KR: a smaller Status Sheet item with one overdue item, and a few flights. private void seedSecondAircraft(User demo, Aircraft pa28, LocalDate today) { - List rows = new ArrayList<>(); + List rows = new ArrayList<>(); rows.add(item("Annual Inspection", "Inspect", "MONTHS", 12, null, today.minusMonths(11).minusDays(20), null, today.plusDays(10), null, demo)); // due soon rows.add(item("Oil Change", "Replace", null, null, 50.0, @@ -154,41 +154,41 @@ private void seedSecondAircraft(User demo, Aircraft pa28, LocalDate today) { rows.add(item("ELT Battery", "Replace", "MONTHS", 24, null, today.minusMonths(6), null, today.plusMonths(18), null, demo)); for (int i = 0; i < rows.size(); i++) { - rows.get(i).setTimelineOrder(i); + rows.get(i).setStatusSheetOrder(i); rows.get(i).setAircraft(pa28); } - timelineRepository.saveAll(rows); + statusSheetItemRepository.saveAll(rows); String[][] legs = { {"KFXE", "KBCT", "0.8", "0.6"}, {"KBCT", "KFXE", "0.9", "0.7"}, {"KFXE", "KVRB", "1.5", "1.3"} }; - double block = 4210.6 - sum(legs, 2); + double hobbs = 4210.6 - sum(legs, 2); double service = 4105.2 - sum(legs, 3); Instant start = today.minusDays(12).atTime(13, 0).toInstant(ZoneOffset.UTC); for (String[] leg : legs) { - double blockLen = Double.parseDouble(leg[2]); + double hobbsLen = Double.parseDouble(leg[2]); double serviceLen = Double.parseDouble(leg[3]); - FlightLog log = new FlightLog(leg[0], leg[1], round(block + blockLen), round(block), + FlightLog log = new FlightLog(leg[0], leg[1], round(hobbs + hobbsLen), round(hobbs), round(service + serviceLen), round(service), demo); log.setSource("manual"); log.setAircraft(pa28); - log.setBlockTimeStart(start); - log.setBlockTimeEnd(start.plus(minutes(blockLen))); + log.setHobbsTimeStart(start); + log.setHobbsTimeEnd(start.plus(minutes(hobbsLen))); log.setTimeInServiceStart(start.plus(Duration.ofMinutes(5))); log.setTimeInServiceEnd(start.plus(Duration.ofMinutes(5)).plus(minutes(serviceLen))); flightLogRepository.save(log); - block += blockLen; + hobbs += hobbsLen; service += serviceLen; start = start.plus(Duration.ofDays(4)); } } private Aircraft aircraft(User owner, String tail, String makeModel, String serial, - double blockTime, double timeInService) { + double hobbsTime, double timeInService) { Aircraft a = new Aircraft(owner); a.setTailNumber(tail); a.setMakeModel(makeModel); - a.setOwnerName("Demo Pilot"); + a.setOperatorName("Demo Pilot"); a.setMakeModelSN(serial); - a.setBlockTimeHours(blockTime); + a.setHobbsTimeHours(hobbsTime); a.setTimeInServiceHours(timeInService); return aircraftRepository.save(a); } @@ -198,13 +198,13 @@ private static FlightSuggestion suggestion(Aircraft aircraft, FlightSuggestion s return s; } - private static ServiceTimeline title(String name, User user) { - return new ServiceTimeline(name, true, null, null, null, null, null, null, null, null, null, user); + private static StatusSheetItem title(String name, User user) { + return new StatusSheetItem(name, true, null, null, null, null, null, null, null, null, null, user); } - private static ServiceTimeline item(String name, String description, String calUnit, Integer calValue, + private static StatusSheetItem item(String name, String description, String calUnit, Integer calValue, Double cycleHours, LocalDate lastDone, String lastDoneHours, LocalDate due, String dueHours, User user) { - return new ServiceTimeline(name, false, description, calUnit, calValue, cycleHours, + return new StatusSheetItem(name, false, description, calUnit, calValue, cycleHours, calUnit == null ? null : lastDone.toString(), lastDoneHours, due == null ? null : due.toString(), dueHours, null, user); } diff --git a/src/main/java/com/example/AviaryService/controllers/AircraftController.java b/src/main/java/com/example/AviaryService/controllers/AircraftController.java index 4ab5225..cd4fdba 100644 --- a/src/main/java/com/example/AviaryService/controllers/AircraftController.java +++ b/src/main/java/com/example/AviaryService/controllers/AircraftController.java @@ -54,7 +54,10 @@ public ResponseEntity> create(@RequestBody Map resp = new LinkedHashMap<>(); resp.put("id", created.getId()); resp.put("redirect", "/dashboard?aircraft=" + created.getId()); diff --git a/src/main/java/com/example/AviaryService/controllers/AlertController.java b/src/main/java/com/example/AviaryService/controllers/AlertController.java index 47b0e44..96ebc2b 100644 --- a/src/main/java/com/example/AviaryService/controllers/AlertController.java +++ b/src/main/java/com/example/AviaryService/controllers/AlertController.java @@ -21,10 +21,10 @@ import com.example.AviaryService.entity.Aircraft; import com.example.AviaryService.entity.AlertPreference; import com.example.AviaryService.entity.AlertRecipient; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.AircraftRepository; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.repositories.UserRepository; import com.example.AviaryService.services.alerts.AlertRecipientService; import com.example.AviaryService.services.alerts.AlertService; @@ -43,15 +43,15 @@ public class AlertController { private final AlertService alertService; private final AlertRecipientService recipientService; private final UserRepository userRepository; - private final ServiceTimelineRepository serviceTimelineRepository; + private final StatusSheetItemRepository statusSheetItemRepository; private final AircraftRepository aircraftRepository; public AlertController(AlertService alertService, AlertRecipientService recipientService, - UserRepository userRepository, ServiceTimelineRepository serviceTimelineRepository, AircraftRepository aircraftRepository) { + UserRepository userRepository, StatusSheetItemRepository statusSheetItemRepository, AircraftRepository aircraftRepository) { this.alertService = alertService; this.recipientService = recipientService; this.userRepository = userRepository; - this.serviceTimelineRepository = serviceTimelineRepository; + this.statusSheetItemRepository = statusSheetItemRepository; this.aircraftRepository = aircraftRepository; } @@ -167,12 +167,12 @@ private Map prefsBody(User user, AlertPreference prefs) { // Readiness hints for the "turn on" dialog (advisory only). List missing = new ArrayList<>(); - long itemCount = serviceTimelineRepository.findByUserOrderByTimelineOrderAsc(user).stream() + long itemCount = statusSheetItemRepository.findByUserOrderByStatusSheetOrderAsc(user).stream() .filter(t -> !t.getIsTitle()).count(); if (itemCount == 0) missing.add("Add at least one maintenance item"); List fleet = aircraftRepository.findByUserOrderByIdAsc(user); if (fleet.stream().allMatch(a -> isBlank(a.getTailNumber()))) missing.add("Set your tail number"); - if (fleet.stream().allMatch(a -> isBlank(a.getOwnerName()))) missing.add("Set your owner name"); + if (fleet.stream().allMatch(a -> isBlank(a.getOperatorName()))) missing.add("Set your operator name"); m.put("readiness", Map.of("missing", missing, "ready", missing.isEmpty())); return m; } diff --git a/src/main/java/com/example/AviaryService/controllers/ConnectionsController.java b/src/main/java/com/example/AviaryService/controllers/ConnectionsController.java index 597a85e..315c4ce 100644 --- a/src/main/java/com/example/AviaryService/controllers/ConnectionsController.java +++ b/src/main/java/com/example/AviaryService/controllers/ConnectionsController.java @@ -16,9 +16,9 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.server.ResponseStatusException; -import com.example.AviaryService.entity.TimelineImportRecord; +import com.example.AviaryService.entity.StatusSheetImportRecord; import com.example.AviaryService.entity.User; -import com.example.AviaryService.repositories.TimelineImportRecordRepository; +import com.example.AviaryService.repositories.StatusSheetImportRecordRepository; import com.example.AviaryService.repositories.UserRepository; import com.example.AviaryService.services.imports.ConnectionService; @@ -30,12 +30,12 @@ public class ConnectionsController { private final ConnectionService connectionService; private final UserRepository userRepository; - private final TimelineImportRecordRepository importRecordRepository; + private final StatusSheetImportRecordRepository importRecordRepository; // This site's MCP address -- production, staging, and local each show their own. private final String mcpUrl; public ConnectionsController(ConnectionService connectionService, UserRepository userRepository, - TimelineImportRecordRepository importRecordRepository, + StatusSheetImportRecordRepository importRecordRepository, @Value("${aviary.oauth.issuer}") String issuer) { this.connectionService = connectionService; this.userRepository = userRepository; @@ -48,8 +48,8 @@ public String connections(Principal principal, Model model) { User user = userRepository.findByUsername(principal.getName()); model.addAttribute("connections", connectionService.list(user)); // Recent imports, grouped by the assistant that made them. - Map> imports = new LinkedHashMap<>(); - for (TimelineImportRecord r : importRecordRepository.findTop20ByUserOrderByImportedAtDesc(user)) { + Map> imports = new LinkedHashMap<>(); + for (StatusSheetImportRecord r : importRecordRepository.findTop20ByUserOrderByImportedAtDesc(user)) { if (r.getClientId() != null) { imports.computeIfAbsent(r.getClientId(), k -> new ArrayList<>()).add(r); } diff --git a/src/main/java/com/example/AviaryService/controllers/ConsentController.java b/src/main/java/com/example/AviaryService/controllers/ConsentController.java index 9129933..cc49207 100644 --- a/src/main/java/com/example/AviaryService/controllers/ConsentController.java +++ b/src/main/java/com/example/AviaryService/controllers/ConsentController.java @@ -63,9 +63,9 @@ public String consent(Principal principal, Model model, private static String describe(String scope) { return switch (scope) { - case CimdRegisteredClientRepository.SCOPE_READ -> "Read your service timeline and flight log"; + case CimdRegisteredClientRepository.SCOPE_READ -> "Read your Status Sheet and flight log"; case CimdRegisteredClientRepository.SCOPE_IMPORT -> - "Propose service timeline items for you to review, and add them once you confirm"; + "Propose Status Sheet items for you to review, and add them once you confirm"; default -> scope; }; } diff --git a/src/main/java/com/example/AviaryService/controllers/UserController.java b/src/main/java/com/example/AviaryService/controllers/UserController.java index 01917da..75bff99 100644 --- a/src/main/java/com/example/AviaryService/controllers/UserController.java +++ b/src/main/java/com/example/AviaryService/controllers/UserController.java @@ -16,11 +16,11 @@ import com.example.AviaryService.entity.Aircraft; import com.example.AviaryService.entity.DescriptionOption; import com.example.AviaryService.entity.FlightLog; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; -import com.example.AviaryService.entity.DTO.TimelineUpdateDTO; +import com.example.AviaryService.entity.DTO.StatusSheetItemUpdateDTO; import com.example.AviaryService.repositories.DescriptionOptionRepository; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.repositories.UserRepository; import com.example.AviaryService.services.flights.AeroApiClient; import com.example.AviaryService.services.dashboard.DescriptionOptionService; @@ -33,11 +33,12 @@ 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.dashboard.StatusSheetService; import com.example.AviaryService.services.account.UserService; import com.example.AviaryService.services.aircraft.AircraftService; import com.example.AviaryService.services.aircraft.AircraftValidationException; import com.example.AviaryService.services.aircraft.FleetSummaryService; +import com.example.AviaryService.util.DueDateAutoFill; import com.example.AviaryService.util.Validation; import org.apache.catalina.connector.Response; @@ -55,7 +56,7 @@ // 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, +// Status Sheet item, 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 @@ -63,13 +64,13 @@ @Controller public class UserController { private final UserRepository userRepository; - private final ServiceTimelineRepository serviceTimelineRepository; + private final StatusSheetItemRepository statusSheetItemRepository; private final PasswordEncoder passwordEncoder; private static final Logger log = LoggerFactory.getLogger(UserController.class); private final SubscriptionService subscriptionService; private final UserService userService; - private final TimelineService timelineService; + private final StatusSheetService statusSheetService; private final DescriptionOptionService descriptionOptionService; private final HoursService hoursService; private final FlightSuggestionService flightSuggestionService; @@ -84,11 +85,14 @@ public class UserController { private final GarminCsvService garminCsvService; private final AircraftService aircraftService; private final FleetSummaryService fleetSummaryService; + // Spec 011: Time Left pills use the same "due soon" window as alert emails. + @org.springframework.beans.factory.annotation.Autowired + private com.example.AviaryService.repositories.AlertPreferenceRepository alertPreferenceRepository; - public UserController(UserRepository userRepository, ServiceTimelineRepository serviceTimelineRepository, + public UserController(UserRepository userRepository, StatusSheetItemRepository statusSheetItemRepository, PasswordEncoder passwordEncoder, DescriptionOptionRepository descriptionOptionRepository, SubscriptionService subscriptionService, UserService userService, - TimelineService timelineService, DescriptionOptionService descriptionOptionService, HoursService hoursService, + StatusSheetService statusSheetService, DescriptionOptionService descriptionOptionService, HoursService hoursService, FlightSuggestionService flightSuggestionService, com.example.AviaryService.repositories.FlightSuggestionRepository flightSuggestionRepository, com.example.AviaryService.repositories.SubscriptionRepository subscriptionRepository, @@ -98,12 +102,12 @@ public UserController(UserRepository userRepository, ServiceTimelineRepository s AircraftService aircraftService, FleetSummaryService fleetSummaryService) { this.userRepository = userRepository; - this.serviceTimelineRepository = serviceTimelineRepository; + this.statusSheetItemRepository = statusSheetItemRepository; this.passwordEncoder = passwordEncoder; this.subscriptionService = subscriptionService; this.userService = userService; - this.timelineService = timelineService; + this.statusSheetService = statusSheetService; this.descriptionOptionService = descriptionOptionService; this.hoursService = hoursService; this.flightSuggestionService = flightSuggestionService; @@ -179,19 +183,23 @@ public String showDashboard(@RequestParam(name = "aircraft", required = false) L .anyMatch(e -> !e.getKey().equals(currentId) && e.getValue().overdue() > 0)); model.addAttribute("aircraftRowCount", aircraftService.rowCount(aircraft)); model.addAttribute("aircraftFlightCount", aircraftService.flightCount(aircraft)); - model.addAttribute("timelines", serviceTimelineRepository.findByAircraftOrderByTimelineOrderAsc(aircraft)); + model.addAttribute("statusSheetItems", statusSheetItemRepository.findByAircraftOrderByStatusSheetOrderAsc(aircraft)); model.addAttribute("descriptionOptions", descriptionOptionService.cleanupAndLoadDescriptionOptions(user)); - model.addAttribute("blockTimeHours", aircraft.getBlockTimeHours()); + com.example.AviaryService.entity.AlertPreference pref = alertPreferenceRepository.findByUser(user) + .orElseGet(com.example.AviaryService.entity.AlertPreference::new); + model.addAttribute("leadTimeDays", pref.getLeadTimeDays()); + model.addAttribute("leadTimeHours", pref.getLeadTimeHours()); + model.addAttribute("hobbsTimeHours", aircraft.getHobbsTimeHours()); model.addAttribute("timeInServiceHours", aircraft.getTimeInServiceHours()); model.addAttribute("makeModel", aircraft.getMakeModel()); model.addAttribute("tailNumber", aircraft.getTailNumber()); - model.addAttribute("ownerName", aircraft.getOwnerName()); + model.addAttribute("operatorName", aircraft.getOperatorName()); model.addAttribute("makeModelSN", aircraft.getMakeModelSN()); model.addAttribute("flightlogs", flightLogService.listFor(aircraft)); - model.addAttribute("blockTimeUpdatedAt", aircraft.getBlockTimeUpdatedAt() != null ? aircraft.getBlockTimeUpdatedAt().toString() : null); + model.addAttribute("hobbsTimeUpdatedAt", aircraft.getHobbsTimeUpdatedAt() != null ? aircraft.getHobbsTimeUpdatedAt().toString() : null); model.addAttribute("timeInServiceUpdatedAt", aircraft.getTimeInServiceUpdatedAt() != null ? aircraft.getTimeInServiceUpdatedAt().toString() : null); - model.addAttribute("blockTimeUpdatedSource", aircraft.getBlockTimeUpdatedSource()); + model.addAttribute("hobbsTimeUpdatedSource", aircraft.getHobbsTimeUpdatedSource()); model.addAttribute("timeInServiceUpdatedSource", aircraft.getTimeInServiceUpdatedSource()); String aeroApiKey = user.getAeroApiKey(); boolean hasAeroApiKey = aeroApiKey != null && !aeroApiKey.isEmpty(); @@ -393,8 +401,10 @@ public ResponseEntity> acceptFlightSuggestion( response.put("id", flightLog.getId()); response.put("fromAirport", flightLog.getFromAirport()); response.put("toAirport", flightLog.getToAirport()); - response.put("blockTimeIn", flightLog.getBlockTimeIn()); - response.put("blockTimeOut", flightLog.getBlockTimeOut()); + response.put("hobbsTimeIn", flightLog.getHobbsTimeIn()); + response.put("blockTimeIn", flightLog.getHobbsTimeIn()); // legacy key, remove after 2026-12-31 + response.put("hobbsTimeOut", flightLog.getHobbsTimeOut()); + response.put("blockTimeOut", flightLog.getHobbsTimeOut()); // legacy key, remove after 2026-12-31 response.put("timeInServiceIn", flightLog.getTimeInServiceIn()); response.put("timeInServiceOut", flightLog.getTimeInServiceOut()); response.put("timeInServiceStart", flightLog.getTimeInServiceStart() != null ? flightLog.getTimeInServiceStart().toString() : null); @@ -435,7 +445,7 @@ public ResponseEntity> deleteFlightSuggestion( } @PostMapping("/dashboard") - public ResponseEntity addTimeline( + public ResponseEntity addStatusSheet( @RequestBody Map data, @CurrentAircraft Aircraft aircraft, Authentication authentication) { @@ -453,22 +463,22 @@ public ResponseEntity addTimeline( String ajax = data.getOrDefault("ajax", "false"); User user = userRepository.findByUsername(authentication.getName()); - ServiceTimeline timeline = timelineService.addTimeline(data, user, aircraft); + StatusSheetItem statusSheetItem = statusSheetService.addStatusSheet(data, user, aircraft); if ("true".equals(ajax)) { Map response = new HashMap<>(); - response.put("id", timeline.getId()); - response.put("item", timeline.getItem()); - response.put("description", timeline.getDescription()); - response.put("cycleCalendarValue", timeline.getCycleCalendarValue()); - response.put("cycleCalendarUnit", timeline.getCycleCalendarUnit()); - response.put("cycleHours", timeline.getCycleHours()); - response.put("lastDoneDate", timeline.getLastDoneDate()); - response.put("lastDoneHours", timeline.getLastDoneHours()); - response.put("dueDateDate", timeline.getDueDateDate()); - response.put("dueDateHours", timeline.getDueDateHours()); - response.put("timeLeft", timeline.getTimeLeft()); - response.put("isTitle", timeline.getIsTitle()); + response.put("id", statusSheetItem.getId()); + response.put("item", statusSheetItem.getItem()); + response.put("description", statusSheetItem.getDescription()); + response.put("cycleCalendarValue", statusSheetItem.getCycleCalendarValue()); + response.put("cycleCalendarUnit", statusSheetItem.getCycleCalendarUnit()); + response.put("cycleHours", statusSheetItem.getCycleHours()); + response.put("lastDoneDate", statusSheetItem.getLastDoneDate()); + response.put("lastDoneHours", statusSheetItem.getLastDoneHours()); + response.put("dueDateDate", statusSheetItem.getDueDateDate()); + response.put("dueDateHours", statusSheetItem.getDueDateHours()); + response.put("timeLeft", statusSheetItem.getTimeLeft()); + response.put("isTitle", statusSheetItem.getIsTitle()); return ResponseEntity.ok(response); } else { return ResponseEntity.status(HttpStatus.FOUND).location(URI.create("/dashboard?aircraft=" + aircraft.getId())).build(); @@ -529,10 +539,14 @@ public ResponseEntity> deleteSubscription(@CurrentAircraft A @PostMapping("/updateHours") @ResponseBody public ResponseEntity> updateHours( - @RequestParam(required = false) Double blockTimeToAdd, + @RequestParam(required = false) Double hobbsTimeToAdd, @RequestParam(required = false) Double timeInServiceToAdd, - @RequestParam(required = false) Double newBlockTime, + @RequestParam(required = false) Double newHobbsTime, @RequestParam(required = false) Double newTimeInService, + // Pre-rename names (Block Time). Accepted for one release so a tab still + // running the old dashboard.js keeps saving. Remove after 2026-12-31. + @RequestParam(name = "blockTimeToAdd", required = false) Double legacyHobbsTimeToAdd, + @RequestParam(name = "newBlockTime", required = false) Double legacyNewHobbsTime, @CurrentAircraft Aircraft aircraft, Authentication authentication) { try { @@ -540,10 +554,13 @@ public ResponseEntity> updateHours( if (user == null) { throw new IllegalArgumentException("User not found"); } - hoursService.updateHours(blockTimeToAdd, timeInServiceToAdd, newBlockTime, newTimeInService, aircraft); + if (hobbsTimeToAdd == null) hobbsTimeToAdd = legacyHobbsTimeToAdd; + if (newHobbsTime == null) newHobbsTime = legacyNewHobbsTime; + hoursService.updateHours(hobbsTimeToAdd, timeInServiceToAdd, newHobbsTime, newTimeInService, aircraft); Map response = new HashMap<>(); response.put("status", "success"); - response.put("newBlockTime", String.valueOf(aircraft.getBlockTimeHours())); + response.put("newHobbsTime", String.valueOf(aircraft.getHobbsTimeHours())); + response.put("newBlockTime", String.valueOf(aircraft.getHobbsTimeHours())); // legacy key, remove after 2026-12-31 response.put("newTimeInService", String.valueOf(aircraft.getTimeInServiceHours())); return ResponseEntity.ok(response); @@ -558,32 +575,80 @@ public ResponseEntity> updateHours( @PostMapping("/update/{id}") @ResponseBody - public ResponseEntity> updateTimeline( + public ResponseEntity> updateStatusSheet( @PathVariable Long id, - @RequestBody TimelineUpdateDTO updateDTO, + @RequestBody StatusSheetItemUpdateDTO updateDTO, Authentication authentication) { try { User user = userRepository.findByUsername(authentication.getName()); - timelineService.updateTimeline(user, id, updateDTO); - return ResponseEntity.ok(Map.of("status", "success")); + StatusSheetItem saved = statusSheetService.updateStatusSheet(user, id, updateDTO); + return ResponseEntity.ok(savedRow(saved)); } 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); + log.error("Failed to update Status Sheet item {}", id, e); return ResponseEntity.badRequest().body(Map.of("status", "error", "message", "Could not save that change.")); } } + // The saved row, so the dashboard shows an auto-filled Due Date right away + // without a reload (spec 007). Same shape for /update and /resetDueToCycle. + private Map savedRow(StatusSheetItem saved) { + Map response = new HashMap<>(); + response.put("status", "success"); + response.put("lastDoneDate", saved.getLastDoneDate()); + response.put("lastDoneHours", DueDateAutoFill.displayHours(saved.getLastDoneHours())); + response.put("dueDateDate", saved.getDueDateDate()); + response.put("dueDateHours", DueDateAutoFill.displayHours(saved.getDueDateHours())); + response.put("timeLeft", saved.getTimeLeft()); + response.put("warnings", statusSheetService.warningsFor(saved)); + return response; + } + + // What the "Reset to cycle" choice in the roll-forward box would set. + @GetMapping("/statusSheet/{id}/cyclePreview") + @ResponseBody + public ResponseEntity> cyclePreview(@PathVariable Long id, Authentication authentication) { + try { + User user = userRepository.findByUsername(authentication.getName()); + StatusSheetService.CyclePreview p = statusSheetService.cyclePreview(user, id); + Map body = new HashMap<>(); + body.put("dueDateDate", p.dueDateDate()); + body.put("dueDateHours", p.dueDateHours()); + body.put("canReset", p.canReset()); + body.put("reason", p.reason()); + return ResponseEntity.ok(body); + } catch (SecurityException e) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).body(Map.of("status", "error", "message", e.getMessage())); + } catch (java.util.NoSuchElementException e) { + return ResponseEntity.badRequest().body(Map.of("status", "error", "message", e.getMessage())); + } + } + + // "Reset to cycle": Due Date = Last Done + cycle, Last Done unchanged. + @PostMapping("/resetDueToCycle/{id}") + @ResponseBody + public ResponseEntity> resetDueToCycle(@PathVariable Long id, Authentication authentication) { + try { + User user = userRepository.findByUsername(authentication.getName()); + return ResponseEntity.ok(savedRow(statusSheetService.resetDueToCycle(user, id))); + } 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())); + } + } + @DeleteMapping("/delete/{id}") @ResponseBody - public ResponseEntity deleteTimeline(@PathVariable Long id, Authentication authentication) { + public ResponseEntity deleteStatusSheet(@PathVariable Long id, Authentication authentication) { User user = userRepository.findByUsername(authentication.getName()); try { - timelineService.deleteTimeline(user, id); + statusSheetService.deleteStatusSheet(user, id); return ResponseEntity.ok().build(); } catch (java.util.NoSuchElementException e) { return ResponseEntity.notFound().build(); @@ -614,7 +679,7 @@ public ResponseEntity deleteOption(@PathVariable Long id, Authentication @ResponseBody public ResponseEntity> updateOrder(@RequestBody List ids, @CurrentAircraft Aircraft aircraft) { try { - timelineService.reorder(aircraft, ids); + statusSheetService.reorder(aircraft, ids); return ResponseEntity.ok(Map.of("status", "success")); } catch (IllegalArgumentException e) { return ResponseEntity.badRequest().body(errorBody(e.getMessage())); @@ -661,15 +726,20 @@ public ResponseEntity> addFlightLog( response.put("id", savedLog.getId()); response.put("fromAirport", savedLog.getFromAirport()); response.put("toAirport", savedLog.getToAirport()); - response.put("blockTimeIn", savedLog.getBlockTimeIn()); - response.put("blockTimeOut", savedLog.getBlockTimeOut()); - response.put("blockTimeStart", savedLog.getBlockTimeStart() != null ? savedLog.getBlockTimeStart().toString() : null); - response.put("blockTimeEnd", savedLog.getBlockTimeEnd() != null ? savedLog.getBlockTimeEnd().toString() : null); + response.put("hobbsTimeIn", savedLog.getHobbsTimeIn()); + response.put("blockTimeIn", savedLog.getHobbsTimeIn()); // legacy key, remove after 2026-12-31 + response.put("hobbsTimeOut", savedLog.getHobbsTimeOut()); + response.put("blockTimeOut", savedLog.getHobbsTimeOut()); // legacy key, remove after 2026-12-31 + response.put("hobbsTimeStart", savedLog.getHobbsTimeStart() != null ? savedLog.getHobbsTimeStart().toString() : null); + response.put("blockTimeStart", savedLog.getHobbsTimeStart() != null ? savedLog.getHobbsTimeStart().toString() : null); // legacy key, remove after 2026-12-31 + response.put("hobbsTimeEnd", savedLog.getHobbsTimeEnd() != null ? savedLog.getHobbsTimeEnd().toString() : null); + response.put("blockTimeEnd", savedLog.getHobbsTimeEnd() != null ? savedLog.getHobbsTimeEnd().toString() : null); // legacy key, remove after 2026-12-31 response.put("timeInServiceIn", savedLog.getTimeInServiceIn()); 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", added.totals().blockTime()); + response.put("newHobbsTime", added.totals().hobbsTime()); + response.put("newBlockTime", added.totals().hobbsTime()); // legacy key, remove after 2026-12-31 response.put("newTimeInService", added.totals().timeInService()); return ResponseEntity.ok(response); } @@ -703,18 +773,98 @@ private static Map errorBody(String message) { return body; } - // POST: complete maintenance on a row. See TimelineService.completeMaintenance. + // POST: what the add row's Due Date should show (spec 010). Calculates + // only; nothing is saved. @CurrentAircraft is ownership-checked and only + // used for the "above Time in Service" note. + @PostMapping(value = "/statusSheet/addRowResolve", consumes = "application/json") + @ResponseBody + public ResponseEntity> addRowResolve( + @RequestBody Map body, + @CurrentAircraft Aircraft aircraft) { + try { + StatusSheetService.AddRowResolved r = statusSheetService.resolveAddRow(aircraft, body); + Map out = new HashMap<>(); + out.put("dueDateDate", r.dueDateDate()); + out.put("dueDateAuto", r.dueDateAuto()); + out.put("dueDateHours", r.dueDateHours()); + out.put("dueHoursAuto", r.dueHoursAuto()); + out.put("lastDoneHours", r.lastDoneHours()); + out.put("warnings", r.warnings()); + return ResponseEntity.ok(out); + } catch (IllegalArgumentException e) { + return ResponseEntity.badRequest().body(errorBody(e.getMessage())); + } + } + + // GET: what the "When was this done?" box shows (spec 008). Without params: + // what it starts with. With doneDate / doneHours: the next Due Date for them. + @GetMapping("/statusSheet/{id}/completePreview") + @ResponseBody + public ResponseEntity> completePreview( + @PathVariable Long id, + @RequestParam(required = false) String doneDate, + @RequestParam(required = false) String doneHours, + Authentication authentication) { + try { + User user = userRepository.findByUsername(authentication.getName()); + StatusSheetService.CompletePreview p = statusSheetService.completePreview(user, id, doneDate, doneHours); + Map out = new HashMap<>(); + out.put("hasCalendar", p.hasCalendar()); + out.put("hasHours", p.hasHours()); + out.put("doneDate", p.doneDate()); + out.put("doneHours", p.doneHours()); + out.put("nextDueDate", p.nextDueDate()); + out.put("nextDueHours", p.nextDueHours()); + out.put("expectedDueDate", p.expectedDueDate()); + out.put("expectedDueHours", p.expectedDueHours()); + out.put("canSave", p.canSave()); + out.put("reason", p.reason()); + return ResponseEntity.ok(out); + } catch (SecurityException e) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorBody("You do not own this row")); + } catch (java.util.NoSuchElementException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorBody("Row not found")); + } + } + + // POST: complete maintenance on a row. See StatusSheetService.completeMaintenance. @PostMapping("/completeMaintenance/{id}") @ResponseBody public ResponseEntity> completeMaintenance( - @PathVariable Long id, Authentication authentication) { + @PathVariable Long id, + @RequestBody(required = false) Map body, + Authentication authentication) { User user = userRepository.findByUsername(authentication.getName()); if (user == null) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorBody("User not authenticated")); } - TimelineService.CompletedMaintenance done; + // Spec 008: the "When was this done?" box sends the chosen values and + // the Due Date it was opened with. An empty body is an older cached + // dashboard.js: keep its today-based behavior until it reloads. + if (body != null && !body.isEmpty()) { + try { + StatusSheetItem saved = statusSheetService.completeMaintenance(user, id, + body.get("doneDate"), body.get("doneHours"), + body.get("expectedDueDate"), body.get("expectedDueHours")); + Map resp = savedRow(saved); + resp.put("lastDone", java.util.stream.Stream.of(saved.getLastDoneDate(), DueDateAutoFill.displayHours(saved.getLastDoneHours())) + .filter(s -> s != null && !s.isEmpty()).collect(java.util.stream.Collectors.joining(" "))); + resp.put("dueDate", java.util.stream.Stream.of(saved.getDueDateDate(), DueDateAutoFill.displayHours(saved.getDueDateHours())) + .filter(s -> s != null && !s.isEmpty()).collect(java.util.stream.Collectors.joining(" "))); + return ResponseEntity.ok(resp); + } catch (StatusSheetService.RowChangedException e) { + return ResponseEntity.status(HttpStatus.CONFLICT).body(errorBody(e.getMessage())); + } catch (java.util.NoSuchElementException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorBody("Row not found")); + } 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())); + } + } + StatusSheetService.CompletedMaintenance done; try { - done = timelineService.completeMaintenance(user, id); + done = statusSheetService.completeMaintenance(user, id); } catch (java.util.NoSuchElementException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorBody("Row not found")); } catch (SecurityException e) { @@ -764,7 +914,8 @@ public ResponseEntity> deleteFlightLog(@PathVariable Long id Map response = new HashMap<>(); response.put("status", "success"); - response.put("newBlockTime", totals.blockTime()); + response.put("newHobbsTime", totals.hobbsTime()); + response.put("newBlockTime", totals.hobbsTime()); // legacy key, remove after 2026-12-31 response.put("newTimeInService", totals.timeInService()); return ResponseEntity.ok(response); } catch (SecurityException e) { diff --git a/src/main/java/com/example/AviaryService/entity/Aircraft.java b/src/main/java/com/example/AviaryService/entity/Aircraft.java index 2241ba0..18bcbdd 100644 --- a/src/main/java/com/example/AviaryService/entity/Aircraft.java +++ b/src/main/java/com/example/AviaryService/entity/Aircraft.java @@ -9,7 +9,7 @@ // One airplane in an owner's fleet. Holds what used to live on User: the // info card, both hour meters, their manual baseline floors, and where each -// meter's last update came from. Service timeline rows, flights, flight +// meter's last update came from. Status Sheet rows, flights, flight // suggestions and the flight-sync subscription each point at one aircraft. // See specs/003-multi-aircraft-fleet/data-model.md. @Entity @@ -39,14 +39,14 @@ public class Aircraft { @Column private String makeModel; - @Column - private String ownerName; + @Column(name = "owner_name") // pre-rename column; keeps every saved name in place (spec 009) + private String operatorName; @Column private String makeModelSN; - @Column - private Double blockTimeHours; + @Column(name = "block_time_hours") + private Double hobbsTimeHours; @Column private Double timeInServiceHours; @@ -54,20 +54,20 @@ public class Aircraft { // Manual "floor" for each meter. Any manual edit on /updateHours writes // this too; log-book activity can only raise the displayed value above // it, never below. Nullable on purpose: "never set" differs from "0". - @Column - private Double blockTimeManualBaseline; + @Column(name = "block_time_manual_baseline") + private Double hobbsTimeManualBaseline; @Column private Double timeInServiceManualBaseline; - @Column - private Instant blockTimeUpdatedAt; + @Column(name = "block_time_updated_at") + private Instant hobbsTimeUpdatedAt; @Column private Instant timeInServiceUpdatedAt; - @Column - private String blockTimeUpdatedSource; + @Column(name = "block_time_updated_source") + private String hobbsTimeUpdatedSource; @Column private String timeInServiceUpdatedSource; @@ -79,11 +79,11 @@ public Aircraft() {} public Aircraft(User user) { this.user = user; - this.blockTimeHours = 0.0; + this.hobbsTimeHours = 0.0; this.timeInServiceHours = 0.0; this.tailNumber = ""; this.makeModel = ""; - this.ownerName = ""; + this.operatorName = ""; this.makeModelSN = ""; } @@ -116,32 +116,32 @@ public void setTailNumber(String tailNumber) { public String getMakeModel() { return makeModel; } public void setMakeModel(String makeModel) { this.makeModel = makeModel; } - public String getOwnerName() { return ownerName; } - public void setOwnerName(String ownerName) { this.ownerName = ownerName; } + public String getOperatorName() { return operatorName; } + public void setOperatorName(String operatorName) { this.operatorName = operatorName; } public String getMakeModelSN() { return makeModelSN; } public void setMakeModelSN(String makeModelSN) { this.makeModelSN = makeModelSN; } - public Double getBlockTimeHours() { return blockTimeHours != null ? blockTimeHours : 0.0; } - public void setBlockTimeHours(Double blockTimeHours) { this.blockTimeHours = blockTimeHours != null ? blockTimeHours : 0.0; } + public Double getHobbsTimeHours() { return hobbsTimeHours != null ? hobbsTimeHours : 0.0; } + public void setHobbsTimeHours(Double hobbsTimeHours) { this.hobbsTimeHours = hobbsTimeHours != null ? hobbsTimeHours : 0.0; } public Double getTimeInServiceHours() { return timeInServiceHours != null ? timeInServiceHours : 0.0; } public void setTimeInServiceHours(Double timeInServiceHours) { this.timeInServiceHours = timeInServiceHours != null ? timeInServiceHours : 0.0; } - public Double getBlockTimeManualBaseline() { return blockTimeManualBaseline; } - public void setBlockTimeManualBaseline(Double v) { this.blockTimeManualBaseline = v; } + public Double getHobbsTimeManualBaseline() { return hobbsTimeManualBaseline; } + public void setHobbsTimeManualBaseline(Double v) { this.hobbsTimeManualBaseline = v; } public Double getTimeInServiceManualBaseline() { return timeInServiceManualBaseline; } public void setTimeInServiceManualBaseline(Double v) { this.timeInServiceManualBaseline = v; } - public Instant getBlockTimeUpdatedAt() { return blockTimeUpdatedAt; } - public void setBlockTimeUpdatedAt(Instant v) { this.blockTimeUpdatedAt = v; } + public Instant getHobbsTimeUpdatedAt() { return hobbsTimeUpdatedAt; } + public void setHobbsTimeUpdatedAt(Instant v) { this.hobbsTimeUpdatedAt = v; } public Instant getTimeInServiceUpdatedAt() { return timeInServiceUpdatedAt; } public void setTimeInServiceUpdatedAt(Instant v) { this.timeInServiceUpdatedAt = v; } - public String getBlockTimeUpdatedSource() { return blockTimeUpdatedSource; } - public void setBlockTimeUpdatedSource(String v) { this.blockTimeUpdatedSource = v; } + public String getHobbsTimeUpdatedSource() { return hobbsTimeUpdatedSource; } + public void setHobbsTimeUpdatedSource(String v) { this.hobbsTimeUpdatedSource = v; } public String getTimeInServiceUpdatedSource() { return timeInServiceUpdatedSource; } public void setTimeInServiceUpdatedSource(String v) { this.timeInServiceUpdatedSource = v; } diff --git a/src/main/java/com/example/AviaryService/entity/DTO/TimelineUpdateDTO.java b/src/main/java/com/example/AviaryService/entity/DTO/StatusSheetItemUpdateDTO.java similarity index 77% rename from src/main/java/com/example/AviaryService/entity/DTO/TimelineUpdateDTO.java rename to src/main/java/com/example/AviaryService/entity/DTO/StatusSheetItemUpdateDTO.java index c1780fb..7096f25 100644 --- a/src/main/java/com/example/AviaryService/entity/DTO/TimelineUpdateDTO.java +++ b/src/main/java/com/example/AviaryService/entity/DTO/StatusSheetItemUpdateDTO.java @@ -1,6 +1,6 @@ package com.example.AviaryService.entity.DTO; -public class TimelineUpdateDTO { +public class StatusSheetItemUpdateDTO { private String item; private String description; private String cycle; @@ -16,7 +16,7 @@ public class TimelineUpdateDTO { private Double cycleHours; // Default constructor (required for Jackson deserialization) - public TimelineUpdateDTO() {} + public StatusSheetItemUpdateDTO() {} // Getters and Setters public String getItem() { return item; } @@ -73,4 +73,15 @@ public void setDueDateHours(String dueDateHours) { public Double getCycleHours() { return cycleHours; } public void setCycleHours(Double newCycHrsVal) { this.cycleHours = newCycHrsVal; } -} \ No newline at end of file + + // Spec 007: true when the owner edited that Due Date part in this save. + // Both null = an older dashboard.js that predates auto-fill; the server + // then saves the submitted Due Date as-is (old behavior). + private Boolean dueDateTouched; + private Boolean dueHoursTouched; + + public Boolean getDueDateTouched() { return dueDateTouched; } + public void setDueDateTouched(Boolean v) { this.dueDateTouched = v; } + public Boolean getDueHoursTouched() { return dueHoursTouched; } + public void setDueHoursTouched(Boolean v) { this.dueHoursTouched = v; } +} diff --git a/src/main/java/com/example/AviaryService/entity/FlightLog.java b/src/main/java/com/example/AviaryService/entity/FlightLog.java index 0c8feda..d2e3708 100644 --- a/src/main/java/com/example/AviaryService/entity/FlightLog.java +++ b/src/main/java/com/example/AviaryService/entity/FlightLog.java @@ -1,5 +1,6 @@ package com.example.AviaryService.entity; +import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonBackReference; import jakarta.persistence.*; @@ -17,11 +18,13 @@ public class FlightLog { @Column(nullable = true) private String toAirport; - @Column(nullable = true) - private Double blockTimeIn; // Use Double for decimal hours if needed + @Column(name = "block_time_in", nullable = true) + @JsonAlias("blockTimeIn") + private Double hobbsTimeIn; // Use Double for decimal hours if needed - @Column(nullable = true) - private Double blockTimeOut; + @Column(name = "block_time_out", nullable = true) + @JsonAlias("blockTimeOut") + private Double hobbsTimeOut; @Column(nullable = true) private Double timeInServiceIn; @@ -29,15 +32,17 @@ public class FlightLog { @Column(nullable = true) private Double timeInServiceOut; - // Engine-start / engine-stop, UTC -- when the blockTimeOut/blockTimeIn + // Engine-start / engine-stop, UTC -- when the hobbsTimeOut/hobbsTimeIn // readings were taken. Lets the logbook be sorted chronologically and // lets HoursService.recomputeChain place this flight correctly relative // to others instead of always appending it to the end. - @Column(nullable = true) - private java.time.Instant blockTimeStart; + @Column(name = "block_time_start", nullable = true) + @JsonAlias("blockTimeStart") + private java.time.Instant hobbsTimeStart; - @Column(nullable = true) - private java.time.Instant blockTimeEnd; + @Column(name = "block_time_end", nullable = true) + @JsonAlias("blockTimeEnd") + private java.time.Instant hobbsTimeEnd; // Wheels-up / wheels-down, UTC -- when the timeInServiceOut/timeInServiceIn // readings were taken. This is also the 14 CFR 1.1 "time in service" @@ -81,11 +86,11 @@ public class FlightLog { // Constructors public FlightLog() {} - public FlightLog(String fromAirport, String toAirport, Double blockTimeIn, Double blockTimeOut, Double timeInServiceIn, Double timeInServiceOut, User user) { + public FlightLog(String fromAirport, String toAirport, Double hobbsTimeIn, Double hobbsTimeOut, Double timeInServiceIn, Double timeInServiceOut, User user) { this.fromAirport = fromAirport; this.toAirport = toAirport; - this.blockTimeIn = blockTimeIn; - this.blockTimeOut = blockTimeOut; + this.hobbsTimeIn = hobbsTimeIn; + this.hobbsTimeOut = hobbsTimeOut; this.timeInServiceIn = timeInServiceIn; this.timeInServiceOut = timeInServiceOut; this.user = user; @@ -98,18 +103,18 @@ public FlightLog(String fromAirport, String toAirport, Double blockTimeIn, Doubl public void setFromAirport(String fromAirport) { this.fromAirport = fromAirport; } public String getToAirport() { return toAirport; } public void setToAirport(String toAirport) { this.toAirport = toAirport; } - public Double getBlockTimeIn() { return blockTimeIn; } - public void setBlockTimeIn(Double blockTimeIn) { this.blockTimeIn = blockTimeIn; } - public Double getBlockTimeOut() { return blockTimeOut; } - public void setBlockTimeOut(Double blockTimeOut) { this.blockTimeOut = blockTimeOut; } + public Double getHobbsTimeIn() { return hobbsTimeIn; } + public void setHobbsTimeIn(Double hobbsTimeIn) { this.hobbsTimeIn = hobbsTimeIn; } + public Double getHobbsTimeOut() { return hobbsTimeOut; } + public void setHobbsTimeOut(Double hobbsTimeOut) { this.hobbsTimeOut = hobbsTimeOut; } public Double getTimeInServiceIn() { return timeInServiceIn; } public void setTimeInServiceIn(Double timeInServiceIn) { this.timeInServiceIn = timeInServiceIn; } public Double getTimeInServiceOut() { return timeInServiceOut; } public void setTimeInServiceOut(Double timeInServiceOut) { this.timeInServiceOut = timeInServiceOut; } - public java.time.Instant getBlockTimeStart() { return blockTimeStart; } - public void setBlockTimeStart(java.time.Instant blockTimeStart) { this.blockTimeStart = blockTimeStart; } - public java.time.Instant getBlockTimeEnd() { return blockTimeEnd; } - public void setBlockTimeEnd(java.time.Instant blockTimeEnd) { this.blockTimeEnd = blockTimeEnd; } + public java.time.Instant getHobbsTimeStart() { return hobbsTimeStart; } + public void setHobbsTimeStart(java.time.Instant hobbsTimeStart) { this.hobbsTimeStart = hobbsTimeStart; } + public java.time.Instant getHobbsTimeEnd() { return hobbsTimeEnd; } + public void setHobbsTimeEnd(java.time.Instant hobbsTimeEnd) { this.hobbsTimeEnd = hobbsTimeEnd; } public java.time.Instant getTimeInServiceStart() { return timeInServiceStart; } public void setTimeInServiceStart(java.time.Instant timeInServiceStart) { this.timeInServiceStart = timeInServiceStart; } public java.time.Instant getTimeInServiceEnd() { return timeInServiceEnd; } diff --git a/src/main/java/com/example/AviaryService/entity/ImportProposal.java b/src/main/java/com/example/AviaryService/entity/ImportProposal.java index 59221e0..d7d9d05 100644 --- a/src/main/java/com/example/AviaryService/entity/ImportProposal.java +++ b/src/main/java/com/example/AviaryService/entity/ImportProposal.java @@ -12,8 +12,8 @@ import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; -// A previewed service timeline import from an AI assistant. Nothing reaches -// the timeline until the owner confirms it. Items and rejected rows are kept +// A previewed Status Sheet import from an AI assistant. Nothing reaches +// the Status Sheet until the owner confirms it. Items and rejected rows are kept // as JSON (they are only ever read back whole). Status: OPEN (or // NEEDS_FIT_CONFIRMATION when most rows didn't fit) -> CONFIRMED, or // REPLACED by a newer proposal, or EXPIRED after 24 hours. diff --git a/src/main/java/com/example/AviaryService/entity/TimelineImportRecord.java b/src/main/java/com/example/AviaryService/entity/StatusSheetImportRecord.java similarity index 98% rename from src/main/java/com/example/AviaryService/entity/TimelineImportRecord.java rename to src/main/java/com/example/AviaryService/entity/StatusSheetImportRecord.java index 8c080d1..34fd3a3 100644 --- a/src/main/java/com/example/AviaryService/entity/TimelineImportRecord.java +++ b/src/main/java/com/example/AviaryService/entity/StatusSheetImportRecord.java @@ -15,7 +15,7 @@ // the Connected assistants page so an owner can see what an assistant added. @Entity @Table(name = "timeline_import_records") -public class TimelineImportRecord { +public class StatusSheetImportRecord { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/src/main/java/com/example/AviaryService/entity/ServiceTimeline.java b/src/main/java/com/example/AviaryService/entity/StatusSheetItem.java similarity index 75% rename from src/main/java/com/example/AviaryService/entity/ServiceTimeline.java rename to src/main/java/com/example/AviaryService/entity/StatusSheetItem.java index 9628f38..54bb4a9 100644 --- a/src/main/java/com/example/AviaryService/entity/ServiceTimeline.java +++ b/src/main/java/com/example/AviaryService/entity/StatusSheetItem.java @@ -5,8 +5,8 @@ import jakarta.persistence.*; @Entity -@Table(name = "service_timelines") // Assuming a table name; adjust if different -public class ServiceTimeline { +@Table(name = "service_timelines") // pre-rename table name; keeps existing data in place +public class StatusSheetItem { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -35,8 +35,8 @@ public class ServiceTimeline { @Column private String timeLeft; - @Column - private Integer timelineOrder; + @Column(name = "timeline_order") // pre-rename column name; keeps existing data in place + private Integer statusSheetOrder; // Structured cycle drives the "Complete Maintenance" button. // Nullable: a row may have a calendar cycle, an hours cycle, both, or @@ -51,6 +51,27 @@ public class ServiceTimeline { @Column private Double cycleHours; + // Spec 007: whether the Due Date date / hours were auto-filled from Last + // Done + cycle (TRUE), typed by the owner (FALSE), or unknown (null, rows + // from before the feature; see DueDateAutoFill). + @Column + private Boolean dueDateAuto; + + @Column + private Boolean dueHoursAuto; + + // Display-only (spec 007): hours with 1-3 decimals ("25" shows as "25.0"). + // Stored text is not changed; legacy non-numeric text is shown as stored. + @com.fasterxml.jackson.annotation.JsonIgnore + public String getLastDoneHoursDisplay() { return com.example.AviaryService.util.DueDateAutoFill.displayHours(lastDoneHours); } + @com.fasterxml.jackson.annotation.JsonIgnore + public String getDueDateHoursDisplay() { return com.example.AviaryService.util.DueDateAutoFill.displayHours(dueDateHours); } + + public Boolean getDueDateAuto() { return dueDateAuto; } + public void setDueDateAuto(Boolean v) { this.dueDateAuto = v; } + public Boolean getDueHoursAuto() { return dueHoursAuto; } + public void setDueHoursAuto(Boolean v) { this.dueHoursAuto = v; } + // 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 @@ -75,10 +96,10 @@ public class ServiceTimeline { private Aircraft aircraft; // Constructors - public ServiceTimeline() {} + public StatusSheetItem() {} - public ServiceTimeline(String item, boolean isTitle, String description, String cycleCalendarUnit, Integer cycleCalendarValue, Double cycleHours, String lastDoneDate, String lastDoneHours, String dueDateDate, String dueDateHours, String timeLeft, User user) { + public StatusSheetItem(String item, boolean isTitle, String description, String cycleCalendarUnit, Integer cycleCalendarValue, Double cycleHours, String lastDoneDate, String lastDoneHours, String dueDateDate, String dueDateHours, String timeLeft, User user) { this.item = item; this.isTitle = isTitle; this.description = description; @@ -140,8 +161,8 @@ public void setDueDateHours(String dueDateHours) { public String getTimeLeft() { return timeLeft; } public void setTimeLeft(String timeLeft) { this.timeLeft = timeLeft; } - public Integer getTimelineOrder() { return timelineOrder; } - public void setTimelineOrder(Integer timelineOrder) { this.timelineOrder = timelineOrder; } + public Integer getStatusSheetOrder() { return statusSheetOrder; } + public void setStatusSheetOrder(Integer statusSheetOrder) { this.statusSheetOrder = statusSheetOrder; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } diff --git a/src/main/java/com/example/AviaryService/entity/User.java b/src/main/java/com/example/AviaryService/entity/User.java index f8a7e33..f72bbb7 100644 --- a/src/main/java/com/example/AviaryService/entity/User.java +++ b/src/main/java/com/example/AviaryService/entity/User.java @@ -25,7 +25,7 @@ public class User { @OneToMany(mappedBy = "user", cascade = CascadeType.ALL) @JsonManagedReference - private List serviceTimeline; + private List statusSheet; @OneToMany(mappedBy = "user", cascade = CascadeType.ALL) @JsonManagedReference @@ -89,8 +89,8 @@ public String getPassword() { return password; } - public List getServiceTimeline() { - return serviceTimeline; + public List getStatusSheetItem() { + return statusSheet; } public void setId(long id) { @@ -105,8 +105,8 @@ public void setPassword(String password) { this.password = password; } - public void setServiceTimeline(List serviceTimeline) { - this.serviceTimeline = serviceTimeline; + public void setStatusSheetItem(List statusSheet) { + this.statusSheet = statusSheet; } public List getFlightLogs() { diff --git a/src/main/java/com/example/AviaryService/mcp/AircraftTools.java b/src/main/java/com/example/AviaryService/mcp/AircraftTools.java index e593f9f..5351da8 100644 --- a/src/main/java/com/example/AviaryService/mcp/AircraftTools.java +++ b/src/main/java/com/example/AviaryService/mcp/AircraftTools.java @@ -8,7 +8,7 @@ import com.example.AviaryService.entity.User; import com.example.AviaryService.oauth.CimdRegisteredClientRepository; import com.example.AviaryService.repositories.AircraftRepository; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; // MCP tool listing the owner's aircraft, so an assistant can ask which one an // import is for and pass it as `aircraft` to the other tools. @@ -16,29 +16,29 @@ public class AircraftTools { public record AircraftSummary(Long aircraftId, String tailNumber, String makeModel, - Double timeInServiceHours, long timelineItems) {} + Double timeInServiceHours, long statusSheetItems) {} private final AircraftRepository aircraftRepository; - private final ServiceTimelineRepository timelineRepository; + private final StatusSheetItemRepository statusSheetItemRepository; private final McpCurrentUser currentUser; - public AircraftTools(AircraftRepository aircraftRepository, ServiceTimelineRepository timelineRepository, + public AircraftTools(AircraftRepository aircraftRepository, StatusSheetItemRepository statusSheetItemRepository, McpCurrentUser currentUser) { this.aircraftRepository = aircraftRepository; - this.timelineRepository = timelineRepository; + this.statusSheetItemRepository = statusSheetItemRepository; this.currentUser = currentUser; } @Tool(name = "list_aircraft", description = """ The owner's aircraft. When there is more than one, ask the owner which aircraft their records are for \ - and pass its tail number (or aircraftId) as `aircraft` to list_service_timeline, list_flights and \ - propose_timeline_import.""") + and pass its tail number (or aircraftId) as `aircraft` to list_status_sheet, list_flights and \ + propose_status_sheet_import.""") public List listAircraft() { currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_READ); User user = currentUser.require(); return aircraftRepository.findByUserOrderByIdAsc(user).stream() .map(a -> new AircraftSummary(a.getId(), a.getTailNumber(), a.getMakeModel(), - a.getTimeInServiceHours(), timelineRepository.countByAircraft(a))) + a.getTimeInServiceHours(), statusSheetItemRepository.countByAircraft(a))) .toList(); } } diff --git a/src/main/java/com/example/AviaryService/mcp/FlightTools.java b/src/main/java/com/example/AviaryService/mcp/FlightTools.java index 5b86713..6540039 100644 --- a/src/main/java/com/example/AviaryService/mcp/FlightTools.java +++ b/src/main/java/com/example/AviaryService/mcp/FlightTools.java @@ -15,7 +15,7 @@ public class FlightTools { //Only what the AI needs, never include the user (it holds the password hash) - public record FlightSummary(Long id, String from, String to, Double blockTimeOut, Double blockTimeIn) {} + public record FlightSummary(Long id, String from, String to, Double hobbsTimeOut, Double hobbsTimeIn) {} private final FlightLogService flightLogService; private final McpCurrentUser currentUser; @@ -35,7 +35,7 @@ public List listFlights( currentUser.requireScope("aviary.read"); User user = currentUser.require(); return flightLogService.listFor(aircraftResolver.resolve(user, aircraft)).stream() - .map(f -> new FlightSummary(f.getId(), f.getFromAirport(), f.getToAirport(), f.getBlockTimeOut(), f.getBlockTimeIn())) + .map(f -> new FlightSummary(f.getId(), f.getFromAirport(), f.getToAirport(), f.getHobbsTimeOut(), f.getHobbsTimeIn())) .toList(); } diff --git a/src/main/java/com/example/AviaryService/mcp/McpConfig.java b/src/main/java/com/example/AviaryService/mcp/McpConfig.java index 30593cf..3d14078 100644 --- a/src/main/java/com/example/AviaryService/mcp/McpConfig.java +++ b/src/main/java/com/example/AviaryService/mcp/McpConfig.java @@ -9,10 +9,10 @@ public class McpConfig { @Bean - ToolCallbackProvider aviaryTools(FlightTools flightTools, TimelineImportTools timelineImportTools, + ToolCallbackProvider aviaryTools(FlightTools flightTools, StatusSheetImportTools statusSheetImportTools, AircraftTools aircraftTools) { return MethodToolCallbackProvider.builder() - .toolObjects(flightTools, timelineImportTools, aircraftTools).build(); + .toolObjects(flightTools, statusSheetImportTools, aircraftTools).build(); } } diff --git a/src/main/java/com/example/AviaryService/mcp/TimelineImportTools.java b/src/main/java/com/example/AviaryService/mcp/StatusSheetImportTools.java similarity index 71% rename from src/main/java/com/example/AviaryService/mcp/TimelineImportTools.java rename to src/main/java/com/example/AviaryService/mcp/StatusSheetImportTools.java index 0aa9891..5e1607b 100644 --- a/src/main/java/com/example/AviaryService/mcp/TimelineImportTools.java +++ b/src/main/java/com/example/AviaryService/mcp/StatusSheetImportTools.java @@ -13,43 +13,43 @@ import com.example.AviaryService.entity.Aircraft; import com.example.AviaryService.entity.User; import com.example.AviaryService.oauth.CimdRegisteredClientRepository; -import com.example.AviaryService.repositories.ServiceTimelineRepository; -import com.example.AviaryService.services.imports.TimelineImportService; -import com.example.AviaryService.services.imports.TimelineImportService.ImportResult; +import com.example.AviaryService.repositories.StatusSheetItemRepository; +import com.example.AviaryService.services.imports.StatusSheetImportService; +import com.example.AviaryService.services.imports.StatusSheetImportService.ImportResult; import com.example.AviaryService.util.DueDates; import com.example.AviaryService.util.Formatting; -import com.example.AviaryService.util.TimelineImportRules; -import com.example.AviaryService.util.TimelineImportRules.InputItem; -import com.example.AviaryService.util.TimelineImportRules.RejectedRow; +import com.example.AviaryService.util.StatusSheetImportRules; +import com.example.AviaryService.util.StatusSheetImportRules.InputItem; +import com.example.AviaryService.util.StatusSheetImportRules.RejectedRow; -// MCP tools for importing a service timeline. Thin door in front of -// TimelineImportService: check scope, resolve the token's owner, delegate. +// MCP tools for importing a Status Sheet. Thin door in front of +// StatusSheetImportService: check scope, resolve the token's owner, delegate. // Outputs are records that never include the User (it holds the password hash). @Component -public class TimelineImportTools { +public class StatusSheetImportTools { public record ImportFormat(Map itemFields, List rules, int maxItems, String example) {} - public record TimelineRow(Long id, String item, String description, boolean isTitle, + public record StatusSheetRow(Long id, String item, String description, boolean isTitle, String lastDone, String due, String cycle, String timeLeft) {} - private final TimelineImportService importService; - private final ServiceTimelineRepository timelineRepository; + private final StatusSheetImportService importService; + private final StatusSheetItemRepository statusSheetItemRepository; private final McpCurrentUser currentUser; private final McpAircraftResolver aircraftResolver; - public TimelineImportTools(TimelineImportService importService, ServiceTimelineRepository timelineRepository, + public StatusSheetImportTools(StatusSheetImportService importService, StatusSheetItemRepository statusSheetItemRepository, McpCurrentUser currentUser, McpAircraftResolver aircraftResolver) { this.importService = importService; - this.timelineRepository = timelineRepository; + this.statusSheetItemRepository = statusSheetItemRepository; this.currentUser = currentUser; this.aircraftResolver = aircraftResolver; } @Tool(name = "get_import_format", description = """ - How Aviary service timeline items must look, with the rules and an example. Call this first, then \ + How Aviary Status Sheet items must look, with the rules and an example. Call this first, then \ convert the owner's maintenance records (any format) into these items before proposing. Each aircraft \ - has its own timeline: if list_aircraft shows more than one, ask the owner which aircraft the records \ + has its own statusSheetItem: if list_aircraft shows more than one, ask the owner which aircraft the records \ are for and pass it as `aircraft`.""") public ImportFormat getImportFormat() { currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_READ); @@ -67,19 +67,19 @@ public ImportFormat getImportFormat() { fields.put("dateAmbiguous", "true if you weren't sure which date was meant"); fields.put("onCondition", "true for an item with no fixed interval (inspected/replaced on condition); it needs no dates"); fields.put("sourceRow", "the original line from the owner's records"); - return new ImportFormat(fields, TimelineImportRules.RULES, TimelineImportRules.MAX_ITEMS, - TimelineImportRules.FORMAT_EXAMPLE); + return new ImportFormat(fields, StatusSheetImportRules.RULES, StatusSheetImportRules.MAX_ITEMS, + StatusSheetImportRules.FORMAT_EXAMPLE); } - @Tool(name = "list_service_timeline", description = "One aircraft's current service timeline items, in order.") - public List listServiceTimeline( + @Tool(name = "list_status_sheet", description = "One aircraft's current Status Sheet items, in order.") + public List listStatusSheetItem( @ToolParam(description = AIRCRAFT_PARAM, required = false) String aircraft) { currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_READ); User user = currentUser.require(); Aircraft target = aircraftResolver.resolve(user, aircraft); LocalDate today = LocalDate.now(); - return timelineRepository.findByAircraftOrderByTimelineOrderAsc(target).stream() - .map(t -> new TimelineRow(t.getId(), t.getItem(), t.getDescription(), t.getIsTitle(), + return statusSheetItemRepository.findByAircraftOrderByStatusSheetOrderAsc(target).stream() + .map(t -> new StatusSheetRow(t.getId(), t.getItem(), t.getDescription(), t.getIsTitle(), join(t.getLastDoneDate(), t.getLastDoneHours()), join(t.getDueDateDate(), t.getDueDateHours()), Formatting.formatCycle(t.getCycleCalendarValue(), t.getCycleCalendarUnit(), t.getCycleHours()), @@ -88,13 +88,13 @@ public List listServiceTimeline( .toList(); } - @Tool(name = "propose_timeline_import", description = """ - Preview importing service timeline items. Send every maintenance item in the owner's records -- an item \ + @Tool(name = "propose_status_sheet_import", description = """ + Preview importing Status Sheet items. Send every maintenance item in the owner's records -- an item \ only needs a name. Changes nothing: returns a proposal with the items as Aviary would store them, flags \ and notes for the owner to check, and rows that can't be imported with reasons. Show the owner the \ proposal before confirming. Calling this again for the same aircraft replaces the previous proposal \ (use it to revise).""") - public ImportResult proposeTimelineImport( + public ImportResult proposeStatusSheetImport( @ToolParam(description = "Items converted from the owner's records; see get_import_format") List items, @ToolParam(description = "Rows that are not maintenance items at all, each with a reason. Never put a real item here just because it has no dates.", required = false) List rejectedBySource, @@ -113,17 +113,17 @@ public ImportResult proposeTimelineImport( @Tool(name = "continue_poor_fit", description = """ For a POOR_FIT proposal: the owner agreed to continue with only the rows that fit. Returns the proposal, \ which can then be confirmed.""") - public ImportResult continuePoorFit(@ToolParam(description = "proposalId from propose_timeline_import") Long proposalId) { + public ImportResult continuePoorFit(@ToolParam(description = "proposalId from propose_status_sheet_import") Long proposalId) { currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_IMPORT); return importService.continuePoorFit(currentUser.require(), proposalId); } - @Tool(name = "confirm_timeline_import", description = """ - Add a proposal's items to the owner's service timeline. Only call this after the owner has seen the \ - proposal and said to go ahead. Items matching ones already on the timeline are skipped unless listed in \ + @Tool(name = "confirm_status_sheet_import", description = """ + Add a proposal's items to the owner's Status Sheet. Only call this after the owner has seen the \ + proposal and said to go ahead. Items matching ones already on the statusSheetItem are skipped unless listed in \ addDuplicatesAnyway. Existing items are never changed.""") - public ImportResult confirmTimelineImport( - @ToolParam(description = "proposalId from propose_timeline_import") Long proposalId, + public ImportResult confirmStatusSheetImport( + @ToolParam(description = "proposalId from propose_status_sheet_import") Long proposalId, @ToolParam(description = "Indexes of DUPLICATE_EXISTING items the owner wants added anyway", required = false) List addDuplicatesAnyway) { currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_IMPORT); diff --git a/src/main/java/com/example/AviaryService/repositories/ServiceTimelineRepository.java b/src/main/java/com/example/AviaryService/repositories/ServiceTimelineRepository.java deleted file mode 100644 index ece7eac..0000000 --- a/src/main/java/com/example/AviaryService/repositories/ServiceTimelineRepository.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.example.AviaryService.repositories; - -import com.example.AviaryService.entity.Aircraft; -import com.example.AviaryService.entity.ServiceTimeline; -import com.example.AviaryService.entity.User; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import java.util.List; - -public interface ServiceTimelineRepository extends JpaRepository { - // One aircraft's timeline. timelineOrder is ordered within an aircraft. - List findByAircraftOrderByTimelineOrderAsc(Aircraft aircraft); - List findByAircraftOrderByIdAsc(Aircraft aircraft); - long countByAircraft(Aircraft aircraft); - - @Query("SELECT MAX(st.timelineOrder) FROM ServiceTimeline st WHERE st.aircraft = :aircraft") - Integer findMaxTimelineOrderByAircraft(@Param("aircraft") Aircraft aircraft); - - // The whole fleet, grouped by aircraft (alert digest, picker counts). - List findByUserOrderByAircraftIdAscTimelineOrderAsc(User user); - - // Every row the account owns, across aircraft (tests, counts). - List findByUserOrderByTimelineOrderAsc(User user); - - void deleteByAircraft(Aircraft aircraft); -} diff --git a/src/main/java/com/example/AviaryService/repositories/StatusSheetImportRecordRepository.java b/src/main/java/com/example/AviaryService/repositories/StatusSheetImportRecordRepository.java new file mode 100644 index 0000000..3d5e269 --- /dev/null +++ b/src/main/java/com/example/AviaryService/repositories/StatusSheetImportRecordRepository.java @@ -0,0 +1,12 @@ +package com.example.AviaryService.repositories; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.example.AviaryService.entity.StatusSheetImportRecord; +import com.example.AviaryService.entity.User; + +public interface StatusSheetImportRecordRepository extends JpaRepository { + List findTop20ByUserOrderByImportedAtDesc(User user); +} diff --git a/src/main/java/com/example/AviaryService/repositories/StatusSheetItemRepository.java b/src/main/java/com/example/AviaryService/repositories/StatusSheetItemRepository.java new file mode 100644 index 0000000..3245fbd --- /dev/null +++ b/src/main/java/com/example/AviaryService/repositories/StatusSheetItemRepository.java @@ -0,0 +1,27 @@ +package com.example.AviaryService.repositories; + +import com.example.AviaryService.entity.Aircraft; +import com.example.AviaryService.entity.StatusSheetItem; +import com.example.AviaryService.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import java.util.List; + +public interface StatusSheetItemRepository extends JpaRepository { + // One aircraft's Status Sheet. statusSheetOrder is ordered within an aircraft. + List findByAircraftOrderByStatusSheetOrderAsc(Aircraft aircraft); + List findByAircraftOrderByIdAsc(Aircraft aircraft); + long countByAircraft(Aircraft aircraft); + + @Query("SELECT MAX(st.statusSheetOrder) FROM StatusSheetItem st WHERE st.aircraft = :aircraft") + Integer findMaxStatusSheetOrderByAircraft(@Param("aircraft") Aircraft aircraft); + + // The whole fleet, grouped by aircraft (alert digest, picker counts). + List findByUserOrderByAircraftIdAscStatusSheetOrderAsc(User user); + + // Every row the account owns, across aircraft (tests, counts). + List findByUserOrderByStatusSheetOrderAsc(User user); + + void deleteByAircraft(Aircraft aircraft); +} diff --git a/src/main/java/com/example/AviaryService/repositories/TimelineImportRecordRepository.java b/src/main/java/com/example/AviaryService/repositories/TimelineImportRecordRepository.java deleted file mode 100644 index 71fc91f..0000000 --- a/src/main/java/com/example/AviaryService/repositories/TimelineImportRecordRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.example.AviaryService.repositories; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.example.AviaryService.entity.TimelineImportRecord; -import com.example.AviaryService.entity.User; - -public interface TimelineImportRecordRepository extends JpaRepository { - List findTop20ByUserOrderByImportedAtDesc(User user); -} diff --git a/src/main/java/com/example/AviaryService/services/account/UserService.java b/src/main/java/com/example/AviaryService/services/account/UserService.java index c2c3b25..dd39dda 100644 --- a/src/main/java/com/example/AviaryService/services/account/UserService.java +++ b/src/main/java/com/example/AviaryService/services/account/UserService.java @@ -68,9 +68,15 @@ public void updateUserInfo(Map data, User user, Aircraft aircraf if (user == null) { throw new IllegalArgumentException("User not found"); } + // Pre-rename key ("ownerName") from a tab still running the old page. + // The new key wins. Remove after 2026-12-31 (spec 009). + if (!data.containsKey("operatorName") && data.containsKey("ownerName")) { + data = new java.util.HashMap<>(data); + data.put("operatorName", data.get("ownerName")); + } Validation.maxLength("Make/model", data.get("makeModel")); - Validation.maxLength("Owner name", data.get("ownerName")); + Validation.maxLength("Operator name", data.get("operatorName")); Validation.maxLength("Serial number", data.get("makeModelSN")); // Stored encrypted (AeroApiKeyConverter), which roughly doubles the // length, so the plain key has a tighter limit than the column. @@ -93,7 +99,7 @@ public void updateUserInfo(Map data, User user, Aircraft aircraf aircraft.setTailNumber(tailNumber); } if (data.containsKey("makeModel")) aircraft.setMakeModel(data.get("makeModel")); - if (data.containsKey("ownerName")) aircraft.setOwnerName(data.get("ownerName")); + if (data.containsKey("operatorName")) aircraft.setOperatorName(data.get("operatorName")); if (data.containsKey("makeModelSN")) aircraft.setMakeModelSN(data.get("makeModelSN")); if (data.containsKey("aeroApiKey")) user.setAeroApiKey(data.get("aeroApiKey")); diff --git a/src/main/java/com/example/AviaryService/services/aircraft/AircraftService.java b/src/main/java/com/example/AviaryService/services/aircraft/AircraftService.java index fddb29e..3c760b3 100644 --- a/src/main/java/com/example/AviaryService/services/aircraft/AircraftService.java +++ b/src/main/java/com/example/AviaryService/services/aircraft/AircraftService.java @@ -12,7 +12,7 @@ import com.example.AviaryService.repositories.FlightLogRepository; import com.example.AviaryService.repositories.FlightSuggestionRepository; import com.example.AviaryService.repositories.ImportProposalRepository; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.repositories.SubscriptionRepository; import com.example.AviaryService.repositories.UserRepository; import com.example.AviaryService.util.Validation; @@ -25,19 +25,19 @@ public class AircraftService { private final AircraftRepository aircraftRepository; private final UserRepository userRepository; - private final ServiceTimelineRepository timelineRepository; + private final StatusSheetItemRepository statusSheetItemRepository; private final FlightLogRepository flightLogRepository; private final FlightSuggestionRepository suggestionRepository; private final SubscriptionRepository subscriptionRepository; private final ImportProposalRepository proposalRepository; public AircraftService(AircraftRepository aircraftRepository, UserRepository userRepository, - ServiceTimelineRepository timelineRepository, FlightLogRepository flightLogRepository, + StatusSheetItemRepository statusSheetItemRepository, FlightLogRepository flightLogRepository, FlightSuggestionRepository suggestionRepository, SubscriptionRepository subscriptionRepository, ImportProposalRepository proposalRepository) { this.aircraftRepository = aircraftRepository; this.userRepository = userRepository; - this.timelineRepository = timelineRepository; + this.statusSheetItemRepository = statusSheetItemRepository; this.flightLogRepository = flightLogRepository; this.suggestionRepository = suggestionRepository; this.subscriptionRepository = subscriptionRepository; @@ -52,14 +52,14 @@ public List listFor(User user) { // required here (the info card can add the rest later). Becomes the // aircraft the dashboard opens on. @Transactional - public Aircraft create(User user, String tailNumber, String makeModel, String ownerName, String makeModelSN) { + public Aircraft create(User user, String tailNumber, String makeModel, String operatorName, String makeModelSN) { try { Validation.requireValidTailNumber(tailNumber, true); } catch (IllegalArgumentException e) { throw new AircraftValidationException("tailNumber", e.getMessage()); } checkLength("makeModel", "Make/model", makeModel); - checkLength("ownerName", "Owner name", ownerName); + checkLength("operatorName", "Operator name", operatorName); checkLength("makeModelSN", "Serial number", makeModelSN); if (aircraftRepository.countByUser(user) >= Aircraft.MAX_PER_USER) { @@ -73,7 +73,7 @@ public Aircraft create(User user, String tailNumber, String makeModel, String ow Aircraft aircraft = new Aircraft(user); aircraft.setTailNumber(tailNumber); aircraft.setMakeModel(trimToEmpty(makeModel)); - aircraft.setOwnerName(trimToEmpty(ownerName)); + aircraft.setOperatorName(trimToEmpty(operatorName)); aircraft.setMakeModelSN(trimToEmpty(makeModelSN)); aircraft = aircraftRepository.save(aircraft); @@ -136,7 +136,7 @@ public Aircraft remove(User user, Long aircraftId, String confirm) { suggestionRepository.deleteByAircraft(aircraft); subscriptionRepository.deleteByAircraft(aircraft); flightLogRepository.deleteByAircraft(aircraft); - timelineRepository.deleteByAircraft(aircraft); + statusSheetItemRepository.deleteByAircraft(aircraft); Aircraft next = aircraftRepository.findByUserOrderByIdAsc(user).stream() .filter(a -> !a.getId().equals(aircraft.getId())) @@ -153,7 +153,7 @@ public Aircraft remove(User user, Long aircraftId, String confirm) { // How much a remove would delete, for the confirm dialog. public long rowCount(Aircraft aircraft) { - return timelineRepository.countByAircraft(aircraft); + return statusSheetItemRepository.countByAircraft(aircraft); } public long flightCount(Aircraft aircraft) { diff --git a/src/main/java/com/example/AviaryService/services/aircraft/FleetSummaryService.java b/src/main/java/com/example/AviaryService/services/aircraft/FleetSummaryService.java index b4faf58..9936e7f 100644 --- a/src/main/java/com/example/AviaryService/services/aircraft/FleetSummaryService.java +++ b/src/main/java/com/example/AviaryService/services/aircraft/FleetSummaryService.java @@ -8,10 +8,10 @@ import org.springframework.stereotype.Service; import com.example.AviaryService.entity.AlertPreference; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.AlertPreferenceRepository; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.services.alerts.AlertLevel; import com.example.AviaryService.util.DueDates; @@ -29,12 +29,12 @@ public record Counts(int overdue, int dueSoon) { public static final Counts NONE = new Counts(0, 0); } - private final ServiceTimelineRepository timelineRepository; + private final StatusSheetItemRepository statusSheetItemRepository; private final AlertPreferenceRepository preferenceRepository; - public FleetSummaryService(ServiceTimelineRepository timelineRepository, + public FleetSummaryService(StatusSheetItemRepository statusSheetItemRepository, AlertPreferenceRepository preferenceRepository) { - this.timelineRepository = timelineRepository; + this.statusSheetItemRepository = statusSheetItemRepository; this.preferenceRepository = preferenceRepository; } @@ -44,9 +44,9 @@ public Map summarize(User user, LocalDate today) { int leadDays = prefs == null ? DEFAULT_LEAD_DAYS : prefs.getLeadTimeDays(); int leadHours = prefs == null ? DEFAULT_LEAD_HOURS : prefs.getLeadTimeHours(); - List rows = timelineRepository.findByUserOrderByAircraftIdAscTimelineOrderAsc(user); + List rows = statusSheetItemRepository.findByUserOrderByAircraftIdAscStatusSheetOrderAsc(user); Map tally = new HashMap<>(); - for (ServiceTimeline t : rows) { + for (StatusSheetItem t : rows) { if (t.getIsTitle() || t.getAircraft() == null) continue; // Each row against its own aircraft's time in service. AlertLevel level = DueDates.classify(t.getDueDateDate(), t.getDueDateHours(), diff --git a/src/main/java/com/example/AviaryService/services/alerts/AlertDigestService.java b/src/main/java/com/example/AviaryService/services/alerts/AlertDigestService.java index 1d76577..7f5dd8d 100644 --- a/src/main/java/com/example/AviaryService/services/alerts/AlertDigestService.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertDigestService.java @@ -13,10 +13,10 @@ import com.example.AviaryService.entity.Aircraft; import com.example.AviaryService.entity.AlertPreference; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.AircraftRepository; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.util.DueDates; import com.example.AviaryService.util.Formatting; @@ -33,12 +33,12 @@ public class AlertDigestService { private static final DateTimeFormatter STAMP = DateTimeFormatter.ofPattern("MMM d, yyyy h:mm a 'UTC'").withZone(ZoneOffset.UTC); - private final ServiceTimelineRepository serviceTimelineRepository; + private final StatusSheetItemRepository statusSheetItemRepository; private final AircraftRepository aircraftRepository; - public AlertDigestService(ServiceTimelineRepository serviceTimelineRepository, + public AlertDigestService(StatusSheetItemRepository statusSheetItemRepository, AircraftRepository aircraftRepository) { - this.serviceTimelineRepository = serviceTimelineRepository; + this.statusSheetItemRepository = statusSheetItemRepository; this.aircraftRepository = aircraftRepository; } @@ -49,10 +49,10 @@ public AlertDigest buildDigest(User user, AlertPreference prefs, boolean baselin // Every row across the fleet, grouped by aircraft. Each hours-cycle // row is judged against ITS OWN aircraft's time in service, never // another plane's (Constitution II). - List rows = serviceTimelineRepository.findByUserOrderByAircraftIdAscTimelineOrderAsc(user); + List rows = statusSheetItemRepository.findByUserOrderByAircraftIdAscStatusSheetOrderAsc(user); List evaluated = new ArrayList<>(); - for (ServiceTimeline t : rows) { + for (StatusSheetItem t : rows) { if (t.getIsTitle()) { continue; } @@ -88,8 +88,8 @@ public void markFired(User user, AlertPreference prefs) { LocalDate today = LocalDate.now(ZoneOffset.UTC); Instant now = Instant.now(); - List rows = serviceTimelineRepository.findByUserOrderByAircraftIdAscTimelineOrderAsc(user); - for (ServiceTimeline t : rows) { + List rows = statusSheetItemRepository.findByUserOrderByAircraftIdAscStatusSheetOrderAsc(user); + for (StatusSheetItem t : rows) { if (t.getIsTitle()) { continue; } @@ -101,10 +101,10 @@ public void markFired(User user, AlertPreference prefs) { t.setAlertLastFiredAt(now); } } - serviceTimelineRepository.saveAll(rows); + statusSheetItemRepository.saveAll(rows); } - private static Double timeInServiceOf(ServiceTimeline t) { + private static Double timeInServiceOf(StatusSheetItem t) { return t.getAircraft() == null ? null : t.getAircraft().getTimeInServiceHours(); } @@ -191,7 +191,7 @@ private static void appendRows(StringBuilder sb, List rows) { } private static void appendHours(StringBuilder sb, String label, Aircraft a) { - sb.append("\n").append(label).append(": Block Time ").append(hours(a.getBlockTimeHours())) + sb.append("\n").append(label).append(": Hobbs Time ").append(hours(a.getHobbsTimeHours())) .append(" · Time in Service ").append(hours(a.getTimeInServiceHours())).append('\n'); } @@ -203,7 +203,7 @@ private static String label(AlertLevel level) { }; } - static String timeLeftText(ServiceTimeline t, Double tis, LocalDate today) { + static String timeLeftText(StatusSheetItem t, Double tis, LocalDate today) { //Overdue parts first, then what's left // "480.0 hrs overdue 106 days left" List overdue = new ArrayList<>(); @@ -235,12 +235,12 @@ private static String orDash(String s) { // Plain holder (fields accessed directly below, not record-style). private static final class Row { - final ServiceTimeline row; + final StatusSheetItem row; final AlertLevel current; final AlertLevel previous; final String timeLeft; - Row(ServiceTimeline row, AlertLevel current, AlertLevel previous, String timeLeft) { + Row(StatusSheetItem row, AlertLevel current, AlertLevel previous, String timeLeft) { this.row = row; this.current = current; this.previous = previous; diff --git a/src/main/java/com/example/AviaryService/services/alerts/AlertLevel.java b/src/main/java/com/example/AviaryService/services/alerts/AlertLevel.java index 44a8dcf..eb17b92 100644 --- a/src/main/java/com/example/AviaryService/services/alerts/AlertLevel.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertLevel.java @@ -23,7 +23,7 @@ public static AlertLevel parse(String stored) { } } - // Stored on ServiceTimeline.alertLevel: null for OK (keeps existing rows + // Stored on StatusSheetItem.alertLevel: null for OK (keeps existing rows // untouched), the enum name otherwise. public String stored() { return this == OK ? null : name(); diff --git a/src/main/java/com/example/AviaryService/services/alerts/AlertRecipientService.java b/src/main/java/com/example/AviaryService/services/alerts/AlertRecipientService.java index c13cac1..2c01023 100644 --- a/src/main/java/com/example/AviaryService/services/alerts/AlertRecipientService.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertRecipientService.java @@ -152,11 +152,11 @@ private void sendConfirmation(AlertRecipient r) { String declineUrl = base.isBlank() ? "" : base + "/alerts/decline?token=" + r.getConfirmToken(); List fleet = aircraftRepository.findByUserOrderByIdAsc(r.getUser()); String tail = AlertText.tail(fleet); - String owner = AlertText.owner(fleet); + String operator = AlertText.operator(fleet); if (r.getChannelEnum() == Channel.EMAIL) { String body = "" - + owner + " added you to receive maintenance alerts for " + tail + ".\n\n" + + operator + " 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. " @@ -165,7 +165,7 @@ private void sendConfirmation(AlertRecipient r) { "Confirm maintenance alerts for " + tail, body); } else { notificationService.sendPlainSms(r.getDestination(), - owner + " added you to maintenance alerts for " + tail + operator + " 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()); @@ -180,16 +180,16 @@ private AlertRecipient ownedOrThrow(User user, long id) { return r; } - // A recipient's emails name the owner and aircraft, so both must be set + // A recipient's emails name the operator and aircraft, so both must be set // before anyone is invited private void requireProfile(User user) { List fleet = aircraftRepository.findByUserOrderByIdAsc(user); - boolean hasOwner = AlertText.anyOwnerName(fleet); + boolean hasOperator = AlertText.anyOperatorName(fleet); boolean hasTail = AlertText.anyTailNumber(fleet); - if (!hasOwner && !hasTail) { + if (!hasOperator && !hasTail) { throw new IllegalArgumentException("Add your name AND tail number in Aircraft Info first."); } - if (!hasOwner) { + if (!hasOperator) { throw new IllegalArgumentException("Add your name in Aircraft Info first."); } if (!hasTail) { diff --git a/src/main/java/com/example/AviaryService/services/alerts/AlertText.java b/src/main/java/com/example/AviaryService/services/alerts/AlertText.java index 2565777..42a7ffa 100644 --- a/src/main/java/com/example/AviaryService/services/alerts/AlertText.java +++ b/src/main/java/com/example/AviaryService/services/alerts/AlertText.java @@ -11,13 +11,13 @@ final class AlertText { // Alerts are account-wide, so these take the whole fleet (ordered by id). private AlertText() {} - // The first owner name set on any aircraft, first aircraft first. - static String owner(List fleet) { + // The first operator name set on any aircraft, first aircraft first. + static String operator(List fleet) { for (Aircraft a : fleet) { - String name = a.getOwnerName(); + String name = a.getOperatorName(); if (name != null && !name.isBlank()) return name.trim(); } - return "The aircraft owner"; + return "The aircraft operator"; } // One aircraft: its tail number. Several: "your fleet (3 aircraft)". @@ -31,8 +31,8 @@ static String tailOf(Aircraft aircraft, String fallback) { return tail == null || tail.isBlank() ? fallback : tail.trim(); } - static boolean anyOwnerName(List fleet) { - return fleet.stream().anyMatch(a -> a.getOwnerName() != null && !a.getOwnerName().isBlank()); + static boolean anyOperatorName(List fleet) { + return fleet.stream().anyMatch(a -> a.getOperatorName() != null && !a.getOperatorName().isBlank()); } static boolean anyTailNumber(List fleet) { diff --git a/src/main/java/com/example/AviaryService/services/alerts/NotificationService.java b/src/main/java/com/example/AviaryService/services/alerts/NotificationService.java index b9c6cc8..e74ef42 100644 --- a/src/main/java/com/example/AviaryService/services/alerts/NotificationService.java +++ b/src/main/java/com/example/AviaryService/services/alerts/NotificationService.java @@ -133,7 +133,7 @@ private void recordSend(AlertRecipient r) { private String emailFooter(List fleet, AlertRecipient r) { StringBuilder sb = new StringBuilder("\n\n----\n"); - sb.append("You're receiving this because ").append(AlertText.owner(fleet)) + sb.append("You're receiving this because ").append(AlertText.operator(fleet)) .append(" added you to maintenance\nalerts for ").append(AlertText.tail(fleet)) .append(". The full dashboard is attached as a PDF.\n"); if (!baseUrl.isBlank()) { diff --git a/src/main/java/com/example/AviaryService/services/dashboard/HoursService.java b/src/main/java/com/example/AviaryService/services/dashboard/HoursService.java index be51452..15e535b 100644 --- a/src/main/java/com/example/AviaryService/services/dashboard/HoursService.java +++ b/src/main/java/com/example/AviaryService/services/dashboard/HoursService.java @@ -14,7 +14,7 @@ import com.example.AviaryService.repositories.AircraftRepository; import com.example.AviaryService.util.Formatting; -// Keeps one aircraft's hours right (block time and time in service). Handles +// Keeps one aircraft's hours right (Hobbs 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 @@ -29,26 +29,26 @@ public HoursService(AircraftRepository aircraftRepository, FlightLogRepository f } @Transactional - public void updateHours(Double blockTimeToAdd, - Double timeInServiceToAdd, Double newBlockTime, + public void updateHours(Double hobbsTimeToAdd, + Double timeInServiceToAdd, Double newHobbsTime, Double newTimeInService, Aircraft aircraft) { // NaN/Infinity would poison every Time Left calculation, and a meter // reading can't be negative. - for (Double v : new Double[] { newBlockTime, newTimeInService }) { + for (Double v : new Double[] { newHobbsTime, newTimeInService }) { if (v != null && (!Double.isFinite(v) || v < 0)) { throw new IllegalArgumentException("Hours must be a number of 0 or more."); } } - for (Double v : new Double[] { blockTimeToAdd, timeInServiceToAdd }) { + for (Double v : new Double[] { hobbsTimeToAdd, timeInServiceToAdd }) { if (v != null && !Double.isFinite(v)) { throw new IllegalArgumentException("Hours must be a number."); } } // Checked up front so a rejected add never leaves the aircraft half-updated. - double currentBlock = aircraft.getBlockTimeHours() == null ? 0 : aircraft.getBlockTimeHours(); + double currentHobbs = aircraft.getHobbsTimeHours() == null ? 0 : aircraft.getHobbsTimeHours(); double currentService = aircraft.getTimeInServiceHours() == null ? 0 : aircraft.getTimeInServiceHours(); - if ((newBlockTime == null && blockTimeToAdd != null && currentBlock + blockTimeToAdd < 0) + if ((newHobbsTime == null && hobbsTimeToAdd != null && currentHobbs + hobbsTimeToAdd < 0) || (newTimeInService == null && timeInServiceToAdd != null && currentService + timeInServiceToAdd < 0)) { throw new IllegalArgumentException("That would make your hours negative."); } @@ -57,23 +57,23 @@ public void updateHours(Double blockTimeToAdd, System.out.println("=========="); - if (newBlockTime != null) { //If newBlockTime has a value - aircraft.setBlockTimeHours(newBlockTime); + if (newHobbsTime != null) { //If newHobbsTime has a value + aircraft.setHobbsTimeHours(newHobbsTime); // Manual edit also sets the floor — logs can raise this, never lower it. - aircraft.setBlockTimeManualBaseline(newBlockTime); - System.out.println("Setting BlockTime time to: " + newBlockTime); + aircraft.setHobbsTimeManualBaseline(newHobbsTime); + System.out.println("Setting HobbsTime time to: " + newHobbsTime); updated = true; - } else if (blockTimeToAdd != null) { //else if blockTimeToAdd has a value - double currentBlockTime = aircraft.getBlockTimeHours(); - double computedBlockTime = Formatting.roundHours(currentBlockTime + blockTimeToAdd); - aircraft.setBlockTimeHours(computedBlockTime); - aircraft.setBlockTimeManualBaseline(computedBlockTime); - System.out.println("Adding " + blockTimeToAdd + " to current BlockTime: " + currentBlockTime); + } else if (hobbsTimeToAdd != null) { //else if hobbsTimeToAdd has a value + double currentHobbsTime = aircraft.getHobbsTimeHours(); + double computedHobbsTime = Formatting.roundHours(currentHobbsTime + hobbsTimeToAdd); + aircraft.setHobbsTimeHours(computedHobbsTime); + aircraft.setHobbsTimeManualBaseline(computedHobbsTime); + System.out.println("Adding " + hobbsTimeToAdd + " to current HobbsTime: " + currentHobbsTime); updated = true; } - double finalBlockTime = aircraft.getBlockTimeHours(); - System.out.println("Current blockTime: " + finalBlockTime); + double finalHobbsTime = aircraft.getHobbsTimeHours(); + System.out.println("Current hobbsTime: " + finalHobbsTime); if (newTimeInService != null) { //If newTimeInService has a value aircraft.setTimeInServiceHours(newTimeInService); @@ -97,9 +97,9 @@ public void updateHours(Double blockTimeToAdd, } java.time.Instant now = java.time.Instant.now(); - if (newBlockTime != null || blockTimeToAdd != null) { - aircraft.setBlockTimeUpdatedAt(now); - aircraft.setBlockTimeUpdatedSource("manual"); + if (newHobbsTime != null || hobbsTimeToAdd != null) { + aircraft.setHobbsTimeUpdatedAt(now); + aircraft.setHobbsTimeUpdatedSource("manual"); } if (newTimeInService != null || timeInServiceToAdd != null) { aircraft.setTimeInServiceUpdatedAt(now); @@ -122,7 +122,7 @@ public record AccuracyIssue(Double expectedFloor, Double expectedCeiling, Double // this pair -- without those there's nothing to compare chronologically, // so it's waved through (same as before this feature existed). public AccuracyIssue checkAccuracy(List existingLogs, Instant candidateStart, Instant candidateEnd, - Double enteredOut, Double enteredIn, boolean useBlockTime) { + Double enteredOut, Double enteredIn, boolean useHobbsTime) { if (candidateStart == null || candidateEnd == null || enteredOut == null || enteredIn == null) { return null; } @@ -131,10 +131,10 @@ public AccuracyIssue checkAccuracy(List existingLogs, Instant candida Double ceiling = null; // lowest known reading at/after candidateEnd for (FlightLog log : existingLogs) { - Instant logStart = useBlockTime ? log.getBlockTimeStart() : log.getTimeInServiceStart(); - Instant logEnd = useBlockTime ? log.getBlockTimeEnd() : log.getTimeInServiceEnd(); - Double logOut = useBlockTime ? log.getBlockTimeOut() : log.getTimeInServiceOut(); - Double logIn = useBlockTime ? log.getBlockTimeIn() : log.getTimeInServiceIn(); + Instant logStart = useHobbsTime ? log.getHobbsTimeStart() : log.getTimeInServiceStart(); + Instant logEnd = useHobbsTime ? log.getHobbsTimeEnd() : log.getTimeInServiceEnd(); + Double logOut = useHobbsTime ? log.getHobbsTimeOut() : log.getTimeInServiceOut(); + Double logIn = useHobbsTime ? log.getHobbsTimeIn() : log.getTimeInServiceIn(); if (logStart == null || logEnd == null || logOut == null || logIn == null) continue; if (!logEnd.isAfter(candidateStart) && (floor == null || logIn > floor)) { @@ -155,7 +155,7 @@ public AccuracyIssue checkAccuracy(List existingLogs, Instant candida /** * Walks one aircraft's flight logs in real chronological order (by - * blockTimeStart or timeInServiceStart, whichever pair useBlockTime + * hobbsTimeStart or timeInServiceStart, whichever pair useHobbsTime * selects) and recomputes Out/In for every non-manual row so the chain * stays accurate no matter what order flights were entered in. * @@ -169,24 +169,24 @@ public AccuracyIssue checkAccuracy(List existingLogs, Instant candida * absolute numbers to wherever this flight actually falls in time. * * Returns the final running total, which becomes the aircraft's displayed - * blockTimeHours/timeInServiceHours. Saves every row it changes; does + * hobbsTimeHours/timeInServiceHours. Saves every row it changes; does * not save the aircraft -- the caller sets the displayed hours field itself. */ @Transactional - public double recomputeChain(Aircraft aircraft, boolean useBlockTime) { - Double baselineBoxed = useBlockTime ? aircraft.getBlockTimeManualBaseline() : aircraft.getTimeInServiceManualBaseline(); + public double recomputeChain(Aircraft aircraft, boolean useHobbsTime) { + Double baselineBoxed = useHobbsTime ? aircraft.getHobbsTimeManualBaseline() : aircraft.getTimeInServiceManualBaseline(); if (baselineBoxed == null) { - baselineBoxed = useBlockTime ? aircraft.getBlockTimeHours() : aircraft.getTimeInServiceHours(); - if (useBlockTime) aircraft.setBlockTimeManualBaseline(baselineBoxed); + baselineBoxed = useHobbsTime ? aircraft.getHobbsTimeHours() : aircraft.getTimeInServiceHours(); + if (useHobbsTime) aircraft.setHobbsTimeManualBaseline(baselineBoxed); else aircraft.setTimeInServiceManualBaseline(baselineBoxed); } List chain = flightLogRepository.findByAircraft(aircraft).stream() - .filter(log -> (useBlockTime ? log.getBlockTimeOut() : log.getTimeInServiceOut()) != null - && (useBlockTime ? log.getBlockTimeIn() : log.getTimeInServiceIn()) != null) + .filter(log -> (useHobbsTime ? log.getHobbsTimeOut() : log.getTimeInServiceOut()) != null + && (useHobbsTime ? log.getHobbsTimeIn() : log.getTimeInServiceIn()) != null) .sorted(Comparator .comparing(log -> { - Instant start = useBlockTime ? log.getBlockTimeStart() : log.getTimeInServiceStart(); + Instant start = useHobbsTime ? log.getHobbsTimeStart() : log.getTimeInServiceStart(); return start == null ? Instant.MAX : start; }) .thenComparing(FlightLog::getId)) @@ -195,22 +195,22 @@ public double recomputeChain(Aircraft aircraft, boolean useBlockTime) { double running = Formatting.roundHours(baselineBoxed); List toSave = new ArrayList<>(); for (FlightLog log : chain) { - Instant start = useBlockTime ? log.getBlockTimeStart() : log.getTimeInServiceStart(); + Instant start = useHobbsTime ? log.getHobbsTimeStart() : log.getTimeInServiceStart(); boolean isAnchor = start == null || "manual".equals(log.getEffectiveSource()); if (isAnchor) { - double in = useBlockTime ? log.getBlockTimeIn() : log.getTimeInServiceIn(); + double in = useHobbsTime ? log.getHobbsTimeIn() : log.getTimeInServiceIn(); running = Formatting.roundHours(Math.max(running, in)); } else { - double out = useBlockTime ? log.getBlockTimeOut() : log.getTimeInServiceOut(); - double in = useBlockTime ? log.getBlockTimeIn() : log.getTimeInServiceIn(); + double out = useHobbsTime ? log.getHobbsTimeOut() : log.getTimeInServiceOut(); + double in = useHobbsTime ? log.getHobbsTimeIn() : log.getTimeInServiceIn(); // Round every step so error can't accumulate down the chain. double duration = Formatting.roundHours(in - out); double newOut = Formatting.roundHours(running); double newIn = Formatting.roundHours(running + duration); - if (useBlockTime) { - log.setBlockTimeOut(newOut); - log.setBlockTimeIn(newIn); + if (useHobbsTime) { + log.setHobbsTimeOut(newOut); + log.setHobbsTimeIn(newIn); } else { log.setTimeInServiceOut(newOut); log.setTimeInServiceIn(newIn); diff --git a/src/main/java/com/example/AviaryService/services/dashboard/PdfExportService.java b/src/main/java/com/example/AviaryService/services/dashboard/PdfExportService.java index facded2..d1b97c6 100644 --- a/src/main/java/com/example/AviaryService/services/dashboard/PdfExportService.java +++ b/src/main/java/com/example/AviaryService/services/dashboard/PdfExportService.java @@ -18,10 +18,10 @@ import org.thymeleaf.context.Context; import com.example.AviaryService.entity.FlightLog; -import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.StatusSheetItem; import com.example.AviaryService.entity.Aircraft; import com.example.AviaryService.repositories.FlightLogRepository; -import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; import com.example.AviaryService.util.DueDates; import com.example.AviaryService.util.Formatting; import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; @@ -35,14 +35,14 @@ public class PdfExportService { private final ITemplateEngine templateEngine; - private final ServiceTimelineRepository serviceTimelineRepository; + private final StatusSheetItemRepository statusSheetItemRepository; private final FlightLogRepository flightLogRepository; public PdfExportService(ITemplateEngine templateEngine, - ServiceTimelineRepository serviceTimelineRepository, + StatusSheetItemRepository statusSheetItemRepository, FlightLogRepository flightLogRepository) { this.templateEngine = templateEngine; - this.serviceTimelineRepository = serviceTimelineRepository; + this.statusSheetItemRepository = statusSheetItemRepository; this.flightLogRepository = flightLogRepository; } @@ -56,13 +56,13 @@ public byte[] generateDashboardPdf(Aircraft aircraft, LocalDate today) { Context context = new Context(); context.setVariable("makeModel", aircraft.getMakeModel()); context.setVariable("tailNumber", aircraft.getTailNumber()); - context.setVariable("ownerName", aircraft.getOwnerName()); + context.setVariable("operatorName", aircraft.getOperatorName()); context.setVariable("makeModelSN", aircraft.getMakeModelSN()); - context.setVariable("blockTimeHours", formatHoursOrBlank(aircraft.getBlockTimeHours())); + context.setVariable("hobbsTimeHours", formatHoursOrBlank(aircraft.getHobbsTimeHours())); context.setVariable("timeInServiceHours", formatHoursOrBlank(aircraft.getTimeInServiceHours())); context.setVariable("generatedAt", DateTimeFormatter.ofPattern("MMM d, yyyy h:mm a") .withZone(ZoneOffset.UTC).format(Instant.now()) + " UTC"); - context.setVariable("timelineRows", buildTimelineRows(aircraft, today)); + context.setVariable("statusSheetRows", buildStatusSheetRows(aircraft, today)); context.setVariable("logRows", buildLogRows(aircraft)); String html = templateEngine.process("pdf-export", context); @@ -104,20 +104,20 @@ private byte[] renderPdf(String html) { } } - private List> buildTimelineRows(Aircraft aircraft, LocalDate today) { - return serviceTimelineRepository.findByAircraftOrderByTimelineOrderAsc(aircraft).stream() - .map(t -> timelineRowData(t, today, aircraft.getTimeInServiceHours())) + private List> buildStatusSheetRows(Aircraft aircraft, LocalDate today) { + return statusSheetItemRepository.findByAircraftOrderByStatusSheetOrderAsc(aircraft).stream() + .map(t -> statusSheetRowData(t, today, aircraft.getTimeInServiceHours())) .collect(Collectors.toList()); } - private Map timelineRowData(ServiceTimeline t, LocalDate today, Double currentTimeInService) { + private Map statusSheetRowData(StatusSheetItem t, LocalDate today, Double currentTimeInService) { Map row = new HashMap<>(); row.put("isTitle", t.getIsTitle()); row.put("item", t.getItem()); row.put("description", t.getDescription()); row.put("cycle", Formatting.formatCycle(t.getCycleCalendarValue(), t.getCycleCalendarUnit(), t.getCycleHours())); - row.put("lastDone", joinNonBlank(t.getLastDoneDate(), withHrs(t.getLastDoneHours()))); - row.put("dueDate", joinNonBlank(t.getDueDateDate(), withHrs(t.getDueDateHours()))); + row.put("lastDone", joinNonBlank(t.getLastDoneDate(), withHrs(t.getLastDoneHoursDisplay()))); + row.put("dueDate", joinNonBlank(t.getDueDateDate(), withHrs(t.getDueDateHoursDisplay()))); // Computed now, not the stored timeLeft column -- that's only as fresh // as the last edit to the row. String timeLeft = DueDates.formatTimeLeft(t.getDueDateDate(), t.getDueDateHours(), today, currentTimeInService); @@ -130,7 +130,7 @@ private List> buildLogRows(Aircraft aircraft) { List logs = flightLogRepository.findByAircraft(aircraft).stream() .sorted(Comparator .comparing(log -> { - Instant start = log.getBlockTimeStart() != null ? log.getBlockTimeStart() : log.getTimeInServiceStart(); + Instant start = log.getHobbsTimeStart() != null ? log.getHobbsTimeStart() : log.getTimeInServiceStart(); return start == null ? Instant.MAX : start; }) .thenComparing(FlightLog::getId)) @@ -139,12 +139,12 @@ private List> buildLogRows(Aircraft aircraft) { List> rows = new ArrayList<>(); for (FlightLog log : logs) { Map row = new HashMap<>(); - Instant start = log.getBlockTimeStart() != null ? log.getBlockTimeStart() : log.getTimeInServiceStart(); + Instant start = log.getHobbsTimeStart() != null ? log.getHobbsTimeStart() : log.getTimeInServiceStart(); row.put("date", start == null ? "" : FLIGHT_DATE.format(start)); row.put("fromAirport", log.getFromAirport()); row.put("toAirport", log.getToAirport()); - row.put("blockTimeOut", formatHoursOrBlank(log.getBlockTimeOut())); - row.put("blockTimeIn", formatHoursOrBlank(log.getBlockTimeIn())); + row.put("hobbsTimeOut", formatHoursOrBlank(log.getHobbsTimeOut())); + row.put("hobbsTimeIn", formatHoursOrBlank(log.getHobbsTimeIn())); row.put("timeInServiceOut", formatHoursOrBlank(log.getTimeInServiceOut())); row.put("timeInServiceIn", formatHoursOrBlank(log.getTimeInServiceIn())); rows.add(row); diff --git a/src/main/java/com/example/AviaryService/services/dashboard/StatusSheetService.java b/src/main/java/com/example/AviaryService/services/dashboard/StatusSheetService.java new file mode 100644 index 0000000..364637b --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/dashboard/StatusSheetService.java @@ -0,0 +1,522 @@ +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.Aircraft; +import com.example.AviaryService.entity.StatusSheetItem; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.entity.DTO.StatusSheetItemUpdateDTO; +import com.example.AviaryService.repositories.StatusSheetItemRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.util.DueDateAutoFill; +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 Status Sheet 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 StatusSheetService { + + private final StatusSheetItemRepository statusSheetItemRepository; + + private final DescriptionOptionService descriptionOptionService; + + public StatusSheetService(UserRepository userRepository, StatusSheetItemRepository statusSheetItemRepository, DescriptionOptionService descriptionOptionService) { + this.statusSheetItemRepository = statusSheetItemRepository; + this.descriptionOptionService = descriptionOptionService; + } + + @Transactional + public StatusSheetItem addStatusSheet(Map data, User user, Aircraft aircraft) { + 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"); + + StatusSheetItem statusSheetItem = new StatusSheetItem(); + statusSheetItem.setItem(item); + boolean isTitleRow = "true".equals(isTitle); + statusSheetItem.setIsTitle(isTitleRow); + + if (!isTitleRow) { + if (description != null) { + statusSheetItem.setDescription(description); + descriptionOptionService.saveCustomDescriptionOption(description, user); + } + statusSheetItem.setCycleCalendarValue(Parsing.parseIntOrNull(data.get("cycleCalendarValue"))); + statusSheetItem.setCycleCalendarUnit(Parsing.normalizeCalendarUnit(data.get("cycleCalendarUnit"))); + statusSheetItem.setCycleHours(Parsing.parseDoubleOrNull(data.get("cycleHours"))); + statusSheetItem.setLastDoneDate(blankToNull(data.get("lastDoneDate"))); + statusSheetItem.setLastDoneHours(DueDateAutoFill.normalizeHours(data.get("lastDoneHours"))); + // New row: a Due Date the owner typed is theirs; a blank one fills + // from Last Done + cycle (spec 007). + DueDateAutoFill.Cycle cycleNow = cycleOf(statusSheetItem); + String typedDueDate = blankToNull(data.get("dueDateDate")); + String typedDueHours = DueDateAutoFill.normalizeHours(data.get("dueDateHours")); + DueDateAutoFill.Resolved date = DueDateAutoFill.resolveDate(null, null, null, null, + statusSheetItem.getLastDoneDate(), cycleNow, typedDueDate, typedDueDate != null); + DueDateAutoFill.Resolved hours = DueDateAutoFill.resolveHours(null, null, null, null, + statusSheetItem.getLastDoneHours(), cycleNow, typedDueHours, typedDueHours != null); + // Spec 010: the add row says which parts the user removed + // ("false" with a blank value). Those stay blank instead of being + // filled on save. A typed value is the user's unless it equals + // Last Done + cycle (same rule as saved rows). + if ("false".equals(data.get("dueDateAuto")) && typedDueDate == null) { + date = new DueDateAutoFill.Resolved(null, false); + } + if ("false".equals(data.get("dueHoursAuto")) && typedDueHours == null) { + hours = new DueDateAutoFill.Resolved(null, false); + } + statusSheetItem.setDueDateDate(date.value()); + statusSheetItem.setDueDateAuto(date.auto()); + statusSheetItem.setDueDateHours(hours.value()); + statusSheetItem.setDueHoursAuto(hours.auto()); + statusSheetItem.setTimeLeft(aircraft == null ? timeLeft : DueDates.formatTimeLeft( + statusSheetItem.getDueDateDate(), statusSheetItem.getDueDateHours(), LocalDate.now(), + aircraft.getTimeInServiceHours())); + } + statusSheetItem.setUser(user); + statusSheetItem.setAircraft(aircraft); + + Integer maxOrder = statusSheetItemRepository.findMaxStatusSheetOrderByAircraft(aircraft); + int newOrder = (maxOrder != null) ? maxOrder + 1 : 0; + statusSheetItem.setStatusSheetOrder(newOrder); + + return statusSheetItemRepository.save(statusSheetItem); + + } + + // 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 StatusSheetItem updateStatusSheet(User user, Long id, StatusSheetItemUpdateDTO updateDTO) { + StatusSheetItem statusSheetItem = 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) statusSheetItem.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(); + } + statusSheetItem.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. + // Snapshot before applying the edit: auto-fill compares old and new. + DueDateAutoFill.Cycle storedCycle = cycleOf(statusSheetItem); + String storedLastDoneDate = statusSheetItem.getLastDoneDate(); + String storedLastDoneHours = statusSheetItem.getLastDoneHours(); + String storedDueDate = statusSheetItem.getDueDateDate(); + String storedDueHours = statusSheetItem.getDueDateHours(); + + statusSheetItem.setCycleCalendarValue(updateDTO.getCycleCalendarValue()); + statusSheetItem.setCycleCalendarUnit(Parsing.normalizeCalendarUnit(updateDTO.getCycleCalendarUnit())); + statusSheetItem.setCycleHours(updateDTO.getCycleHours()); + DueDateAutoFill.Cycle newCycle = cycleOf(statusSheetItem); + + String newLastDoneDate = blankToNull(updateDTO.getLastDoneDate()); + String newLastDoneHours = hoursIfChanged(storedLastDoneHours, updateDTO.getLastDoneHours()); + statusSheetItem.setLastDoneDate(newLastDoneDate); + statusSheetItem.setLastDoneHours(newLastDoneHours); + + boolean legacyClient = updateDTO.getDueDateTouched() == null && updateDTO.getDueHoursTouched() == null; + if (legacyClient) { + // Older dashboard.js (no touched flags): save what it sent, as before. + statusSheetItem.setDueDateDate(blankToNull(updateDTO.getDueDateDate())); + statusSheetItem.setDueDateHours(hoursIfChanged(storedDueHours, updateDTO.getDueDateHours())); + } else { + boolean dateTouched = Boolean.TRUE.equals(updateDTO.getDueDateTouched()); + boolean hoursTouched = Boolean.TRUE.equals(updateDTO.getDueHoursTouched()); + DueDateAutoFill.Resolved date = DueDateAutoFill.resolveDate( + storedLastDoneDate, storedCycle, storedDueDate, statusSheetItem.getDueDateAuto(), + newLastDoneDate, newCycle, updateDTO.getDueDateDate(), dateTouched); + DueDateAutoFill.Resolved hours = DueDateAutoFill.resolveHours( + storedLastDoneHours, storedCycle, storedDueHours, statusSheetItem.getDueHoursAuto(), + newLastDoneHours, newCycle, + hoursTouched ? hoursIfChanged(storedDueHours, updateDTO.getDueDateHours()) : null, hoursTouched); + statusSheetItem.setDueDateDate(date.value()); + statusSheetItem.setDueDateAuto(date.auto()); + statusSheetItem.setDueDateHours(hours.value()); + statusSheetItem.setDueHoursAuto(hours.auto()); + } + statusSheetItem.setTimeLeft(DueDates.formatTimeLeft(statusSheetItem.getDueDateDate(), + statusSheetItem.getDueDateHours(), LocalDate.now(), currentTimeInService(statusSheetItem))); + + return statusSheetItemRepository.save(statusSheetItem); + } + + // Throws NoSuchElementException / SecurityException like updateStatusSheet. + @Transactional + public void deleteStatusSheet(User user, Long id) { + statusSheetItemRepository.delete(getOwned(user, id)); + } + + // Applies the drag-and-drop order: ids[i] gets position i, within one + // aircraft. Rejects the whole list (nothing saved) if any id isn't a row + // of that aircraft, so a drag can never reorder another plane's rows. + @Transactional + public void reorder(Aircraft aircraft, List ids) { + List statusSheetItems = statusSheetItemRepository.findByAircraftOrderByIdAsc(aircraft); + java.util.Set own = statusSheetItems.stream().map(StatusSheetItem::getId).collect(Collectors.toSet()); + for (Long id : ids) { + if (!own.contains(id)) { + throw new IllegalArgumentException("Those rows aren't all on this aircraft."); + } + } + for (int i = 0; i < ids.size(); i++) { + Long id = ids.get(i); + StatusSheetItem statusSheetItem = statusSheetItems.stream() + .filter(t -> t.getId().equals(id)) + .findFirst() + .orElse(null); + if (statusSheetItem != null) { + statusSheetItem.setStatusSheetOrder(i); + } + } + statusSheetItemRepository.saveAll(statusSheetItems); + } + + // 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 row's aircraft's 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 updateStatusSheet, and + // IllegalArgumentException when the row has no cycle. + @Transactional + public CompletedMaintenance completeMaintenance(User user, Long id) { + StatusSheetItem statusSheetItem = getOwned(user, id); + + Integer calVal = statusSheetItem.getCycleCalendarValue(); + String calUnit = Parsing.normalizeCalendarUnit(statusSheetItem.getCycleCalendarUnit()); + Double hrsCycle = statusSheetItem.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(); + // The row's own aircraft, never another plane in the fleet. + double currentTimeInService = statusSheetItem.getAircraft().getTimeInServiceHours(); + + LocalDate dueDateLd = hasCalendar ? DueDates.nextDueDate(today, calVal, calUnit) : null; + Double dueHours = hasHours ? DueDates.nextDueHours(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) { + statusSheetItem.setLastDoneDate(today.toString()); + statusSheetItem.setDueDateDate(dueDateLd != null ? dueDateLd.toString() : null); + statusSheetItem.setDueDateAuto(true); + } + if (hasHours) { + statusSheetItem.setLastDoneHours(DueDateAutoFill.formatHours(currentTimeInService)); + statusSheetItem.setDueDateHours(DueDateAutoFill.formatHours(dueHours)); + statusSheetItem.setDueHoursAuto(true); + } + // Same text the dashboard computes, from the row's saved due date/hours. + String timeLeftStr = DueDates.formatTimeLeft( + statusSheetItem.getDueDateDate(), statusSheetItem.getDueDateHours(), today, currentTimeInService); + statusSheetItem.setTimeLeft(timeLeftStr); + statusSheetItemRepository.save(statusSheetItem); + + // Build the strings from the actual saved state so the dashboard's + // repaintDateHoursCell receives both the date and hours parts. + return new CompletedMaintenance( + joinParts(statusSheetItem.getLastDoneDate(), statusSheetItem.getLastDoneHours()), + joinParts(statusSheetItem.getDueDateDate(), statusSheetItem.getDueDateHours()), + timeLeftStr); + } + + // ── Add row, spec 010: same Due Date rules before Add ────────────── + + // What the add row should show. Nothing is saved; the add row keeps its + // own state (previous inputs, auto/typed per part) and passes it in. + public record AddRowResolved(String dueDateDate, boolean dueDateAuto, + String dueDateHours, boolean dueHoursAuto, + String lastDoneHours, List warnings) {} + + public AddRowResolved resolveAddRow(Aircraft aircraft, Map in) { + DueDateAutoFill.Cycle prevCycle = new DueDateAutoFill.Cycle( + intOrNull(in.get("prevCycleCalendarValue")), + Parsing.normalizeCalendarUnit(str(in.get("prevCycleCalendarUnit"))), + doubleOrNull(in.get("prevCycleHours"))); + DueDateAutoFill.Cycle cycle = new DueDateAutoFill.Cycle( + intOrNull(in.get("cycleCalendarValue")), + Parsing.normalizeCalendarUnit(str(in.get("cycleCalendarUnit"))), + doubleOrNull(in.get("cycleHours"))); + String lastDate = blankToNull(str(in.get("lastDoneDate"))); + String lastHours = DueDateAutoFill.normalizeHours(str(in.get("lastDoneHours"))); + String prevLastHours = DueDateAutoFill.parseHours(str(in.get("prevLastDoneHours"))) == null + ? blankToNull(str(in.get("prevLastDoneHours"))) + : DueDateAutoFill.normalizeHours(str(in.get("prevLastDoneHours"))); + boolean dateTouched = Boolean.TRUE.equals(in.get("dueDateTouched")); + boolean hoursTouched = Boolean.TRUE.equals(in.get("dueHoursTouched")); + String dueHours = str(in.get("dueDateHours")); + if (hoursTouched) { + dueHours = DueDateAutoFill.normalizeHours(dueHours); + } + + DueDateAutoFill.Resolved date = DueDateAutoFill.resolveDate( + blankToNull(str(in.get("prevLastDoneDate"))), prevCycle, blankToNull(str(in.get("dueDateDate"))), + boolOrNull(in.get("dueDateAuto")), lastDate, cycle, str(in.get("dueDateDate")), dateTouched); + DueDateAutoFill.Resolved hours = DueDateAutoFill.resolveHours( + prevLastHours, prevCycle, blankToNull(dueHours), + boolOrNull(in.get("dueHoursAuto")), lastHours, cycle, dueHours, hoursTouched); + + // Same typo notes as saved rows (warningsFor), on an unsaved item. + StatusSheetItem probe = new StatusSheetItem(); + probe.setLastDoneDate(lastDate); + probe.setLastDoneHours(lastHours); + probe.setAircraft(aircraft); + return new AddRowResolved(date.value(), date.auto(), hours.value(), hours.auto(), + lastHours, warningsFor(probe)); + } + + private static String str(Object o) { + return o == null ? null : o.toString(); + } + + private static Integer intOrNull(Object o) { + if (o instanceof Number n) return n.intValue(); + return Parsing.parseIntOrNull(str(o)); + } + + private static Double doubleOrNull(Object o) { + if (o instanceof Number n) return n.doubleValue(); + return Parsing.parseDoubleOrNull(str(o)); + } + + private static Boolean boolOrNull(Object o) { + if (o instanceof Boolean b) return b; + String s = str(o); + return s == null || s.isBlank() ? null : Boolean.valueOf(s); + } + + // ── Mark complete, spec 008: "When was this done?" ───────────────── + + // Thrown when the row's Due Date changed after the box opened (a + // double-click, another tab). Mapped to 409; nothing is saved. + public static class RowChangedException extends RuntimeException { + public RowChangedException() { + super("This row changed. Open it again to review."); + } + } + + // What the box shows: which parts it offers, what they start with (or the + // owner's edited values), the next Due Date for them, and the row's current + // Due Date (echoed back on save for the at-most-once check). + public record CompletePreview(boolean hasCalendar, boolean hasHours, + String doneDate, String doneHours, + String nextDueDate, String nextDueHours, + String expectedDueDate, String expectedDueHours, + boolean canSave, String reason) {} + + // doneDate / doneHours null = "what does the box start with". Blank = the + // owner emptied that box. + public CompletePreview completePreview(User user, Long id, String doneDate, String doneHours) { + StatusSheetItem i = getOwned(user, id); + DueDateAutoFill.Cycle cycle = cycleOf(i); + boolean hasCalendar = cycle.hasCalendar(); + boolean hasHours = cycle.hasHours(); + if (!hasCalendar && !hasHours) { + return new CompletePreview(false, false, null, null, null, null, + i.getDueDateDate(), i.getDueDateHours(), false, + "Set a calendar cycle or an hours cycle before marking maintenance complete."); + } + String date = doneDate != null ? doneDate + : DueDateAutoFill.prefillDoneDate(i.getLastDoneDate(), i.getDueDateDate(), cycle, LocalDate.now()); + String hours = doneHours != null ? doneHours + : DueDateAutoFill.prefillDoneHours(i.getLastDoneHours(), i.getDueDateHours(), cycle); + + String nextDate = null, nextHours = null, reason = null; + boolean dateGiven = hasCalendar && date != null && !date.isBlank(); + boolean hoursGiven = hasHours && hours != null && !hours.isBlank(); + try { + if (dateGiven) { + LocalDate d = DueDateAutoFill.validDoneDate(date); + nextDate = DueDates.nextDueDate(d, cycle.calendarValue(), cycle.calendarUnit()).toString(); + } + if (hoursGiven) { + String h = DueDateAutoFill.normalizeHours(hours); + nextHours = DueDateAutoFill.expectedDueHours(h, cycle); + hours = h; + } + if (!dateGiven && !hoursGiven) { + reason = "Enter when it was done."; + } + } catch (IllegalArgumentException e) { + reason = e.getMessage(); + } + return new CompletePreview(hasCalendar, hasHours, + hasCalendar ? date : null, hasHours ? hours : null, + reason == null ? nextDate : null, reason == null ? nextHours : null, + i.getDueDateDate(), i.getDueDateHours(), reason == null, reason); + } + + // Saves Mark complete: Last Done = the done date / hours, Due Date = that + + // cycle, for each part that has a cycle and a value. Refuses (409) if the + // row's Due Date is no longer what the box was opened with. + @Transactional + public StatusSheetItem completeMaintenance(User user, Long id, String doneDate, String doneHours, + String expectedDueDate, String expectedDueHours) { + StatusSheetItem i = getOwned(user, id); + if (!sameOrBothBlankDate(i.getDueDateDate(), expectedDueDate) + || !sameOrBothBlankHours(i.getDueDateHours(), expectedDueHours)) { + throw new RowChangedException(); + } + CompletePreview p = completePreview(user, id, + doneDate == null ? "" : doneDate, doneHours == null ? "" : doneHours); + if (!p.canSave()) { + throw new IllegalArgumentException(p.reason()); + } + if (p.nextDueDate() != null) { + i.setLastDoneDate(p.doneDate().trim()); + i.setDueDateDate(p.nextDueDate()); + i.setDueDateAuto(true); + } + if (p.nextDueHours() != null) { + i.setLastDoneHours(p.doneHours()); + i.setDueDateHours(p.nextDueHours()); + i.setDueHoursAuto(true); + } + i.setTimeLeft(DueDates.formatTimeLeft(i.getDueDateDate(), i.getDueDateHours(), LocalDate.now(), + currentTimeInService(i))); + return statusSheetItemRepository.save(i); + } + + private static boolean sameOrBothBlankDate(String a, String b) { + boolean blankA = a == null || a.isBlank(), blankB = b == null || b.isBlank(); + return (blankA && blankB) || DueDateAutoFill.sameDate(a, b) || (!blankA && !blankB && a.trim().equals(b.trim())); + } + + private static boolean sameOrBothBlankHours(String a, String b) { + boolean blankA = a == null || a.isBlank(), blankB = b == null || b.isBlank(); + return (blankA && blankB) || DueDateAutoFill.sameHours(a, b) || (!blankA && !blankB && a.trim().equals(b.trim())); + } + + // What "Reset to cycle" would set (spec 007): Due Date = stored Last Done + + // cycle, for each part that can be computed. canReset is false when there + // is nothing to count from or the Due Date already matches. + public record CyclePreview(String dueDateDate, String dueDateHours, boolean canReset, String reason) {} + + public CyclePreview cyclePreview(User user, Long id) { + return previewOf(getOwned(user, id)); + } + + private static CyclePreview previewOf(StatusSheetItem i) { + DueDateAutoFill.Cycle cycle = cycleOf(i); + String date = DueDateAutoFill.expectedDueDate(i.getLastDoneDate(), cycle); + String hours = DueDateAutoFill.expectedDueHours(i.getLastDoneHours(), cycle); + if (date == null && hours == null) { + return new CyclePreview(null, null, false, "Enter Last Done first"); + } + boolean dateDiffers = date != null && !DueDateAutoFill.sameDate(i.getDueDateDate(), date); + boolean hoursDiffers = hours != null && !DueDateAutoFill.sameHours(i.getDueDateHours(), hours); + if (!dateDiffers && !hoursDiffers) { + return new CyclePreview(date, hours, false, "Due Date already matches the cycle"); + } + return new CyclePreview(date, hours, true, null); + } + + // "Reset to cycle": keeps Last Done, sets each computable Due Date part to + // Last Done + cycle and hands it back to auto-fill. + @Transactional + public StatusSheetItem resetDueToCycle(User user, Long id) { + StatusSheetItem i = getOwned(user, id); + CyclePreview p = previewOf(i); + if (!p.canReset()) { + throw new IllegalArgumentException(p.reason()); + } + if (p.dueDateDate() != null) { + i.setDueDateDate(p.dueDateDate()); + i.setDueDateAuto(true); + } + if (p.dueDateHours() != null) { + i.setDueDateHours(p.dueDateHours()); + i.setDueHoursAuto(true); + } + i.setTimeLeft(DueDates.formatTimeLeft(i.getDueDateDate(), i.getDueDateHours(), LocalDate.now(), + currentTimeInService(i))); + return statusSheetItemRepository.save(i); + } + + private StatusSheetItem getOwned(User user, Long id) { + StatusSheetItem statusSheetItem = statusSheetItemRepository.findById(id) + .orElseThrow(() -> new NoSuchElementException("Invalid Status Sheet item ID: " + id)); + if (user == null || statusSheetItem.getUser() == null || statusSheetItem.getUser().getId() != user.getId()) { + throw new SecurityException("You do not own this Status Sheet item"); + } + return statusSheetItem; + } + + private static String joinParts(String date, String hours) { + return Stream.of(date, hours) + .filter(s -> s != null && !s.isEmpty()).collect(Collectors.joining(" ")); + } + + private static DueDateAutoFill.Cycle cycleOf(StatusSheetItem i) { + return new DueDateAutoFill.Cycle(i.getCycleCalendarValue(), i.getCycleCalendarUnit(), i.getCycleHours()); + } + + // Hours text the owner did not change (including legacy text like + // "1200 TT") is kept exactly as stored. A changed value must be a number + // and is saved in the 25.0 format (spec 007). + private static String hoursIfChanged(String stored, String submitted) { + if (DueDateAutoFill.sameText(stored, submitted)) { + return stored; + } + return DueDateAutoFill.normalizeHours(submitted); + } + + private static Double currentTimeInService(StatusSheetItem i) { + return i.getAircraft() != null ? i.getAircraft().getTimeInServiceHours() : null; + } + + // Typo checks shown on the row; the Due Date still fills (spec 007). + public List warningsFor(StatusSheetItem i) { + List warnings = new java.util.ArrayList<>(); + LocalDate last = DueDateAutoFill.validDate(i.getLastDoneDate()); + if (last != null && last.isAfter(LocalDate.now())) { + warnings.add("Last Done is in the future. Check the date."); + } + java.math.BigDecimal lastHours = DueDateAutoFill.parseHours(i.getLastDoneHours()); + Double tis = currentTimeInService(i); + if (lastHours != null && tis != null && lastHours.doubleValue() > tis) { + warnings.add("Last Done hours are above current Time in Service. Check the hours."); + } + return warnings; + } + + // 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/dashboard/TimelineService.java b/src/main/java/com/example/AviaryService/services/dashboard/TimelineService.java deleted file mode 100644 index 12aaeab..0000000 --- a/src/main/java/com/example/AviaryService/services/dashboard/TimelineService.java +++ /dev/null @@ -1,219 +0,0 @@ -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.Aircraft; -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, Aircraft aircraft) { - 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); - timeline.setAircraft(aircraft); - - Integer maxOrder = serviceTimelineRepository.findMaxTimelineOrderByAircraft(aircraft); - 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, within one - // aircraft. Rejects the whole list (nothing saved) if any id isn't a row - // of that aircraft, so a drag can never reorder another plane's rows. - @Transactional - public void reorder(Aircraft aircraft, List ids) { - List timelines = serviceTimelineRepository.findByAircraftOrderByIdAsc(aircraft); - java.util.Set own = timelines.stream().map(ServiceTimeline::getId).collect(Collectors.toSet()); - for (Long id : ids) { - if (!own.contains(id)) { - throw new IllegalArgumentException("Those rows aren't all on this aircraft."); - } - } - 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 row's aircraft's 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(); - // The row's own aircraft, never another plane in the fleet. - double currentTimeInService = timeline.getAircraft().getTimeInServiceHours(); - - LocalDate dueDateLd = hasCalendar ? DueDates.nextDueDate(today, calVal, calUnit) : null; - Double dueHours = hasHours ? DueDates.nextDueHours(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/flights/FlightLogService.java b/src/main/java/com/example/AviaryService/services/flights/FlightLogService.java index e4d3450..63a1932 100644 --- a/src/main/java/com/example/AviaryService/services/flights/FlightLogService.java +++ b/src/main/java/com/example/AviaryService/services/flights/FlightLogService.java @@ -38,8 +38,8 @@ public FlightLogService(FlightLogRepository flightLogRepository, this.hoursService = hoursService; } - // The user's Block Time and Time in Service totals after a log change. - public record HourTotals(double blockTime, double timeInService) {} + // The user's Hobbs Time and Time in Service totals after a log change. + public record HourTotals(double hobbsTime, double timeInService) {} // A saved log plus the totals it produced. public record AddedFlightLog(FlightLog log, HourTotals totals) {} @@ -68,8 +68,8 @@ public AddedFlightLog add(User user, Aircraft aircraft, FlightLog newLog, boolea // Clamp readings to hundredths. Real meters never exceed 2dp (block // time 0.1, time in service 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.setHobbsTimeOut(Formatting.roundHoursOrNull(newLog.getHobbsTimeOut())); + newLog.setHobbsTimeIn(Formatting.roundHoursOrNull(newLog.getHobbsTimeIn())); newLog.setTimeInServiceOut(Formatting.roundHoursOrNull(newLog.getTimeInServiceOut())); newLog.setTimeInServiceIn(Formatting.roundHoursOrNull(newLog.getTimeInServiceIn())); @@ -80,31 +80,31 @@ public AddedFlightLog add(User user, Aircraft aircraft, FlightLog newLog, boolea // ── Validation ───────────────────────────────────────────────────────── // Reject incomplete entries before they can corrupt displayed hours. - // Rule: must provide at least one COMPLETE pair (blockTimeOut+blockTimeIn or + // Rule: must provide at least one COMPLETE pair (hobbsTimeOut+hobbsTimeIn 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 ho = newLog.getHobbsTimeOut(), hi = newLog.getHobbsTimeIn(); Double to = newLog.getTimeInServiceOut(), ti = newLog.getTimeInServiceIn(); - boolean blockTimePair = (ho != null && hi != null); + boolean hobbsTimePair = (ho != null && hi != null); boolean timeInServicePair = (to != null && ti != null); - boolean blockTimePartial = (ho == null) != (hi == null); // exactly one set + boolean hobbsTimePartial = (ho == null) != (hi == null); // exactly one set boolean timeInServicePartial = (to == null) != (ti == null); - if (!blockTimePair && !timeInServicePair) { + if (!hobbsTimePair && !timeInServicePair) { throw new IllegalArgumentException( - "Enter both Block Time Out and Block Time In, or both Time in Service Out and Time in Service In."); + "Enter both Hobbs Time Out and Hobbs Time In, or both Time in Service Out and Time in Service In."); } - if (blockTimePartial) { + if (hobbsTimePartial) { throw new IllegalArgumentException( - "Block time entry is incomplete — enter both Block Time Out and Block Time In."); + "Hobbs time entry is incomplete — enter both Hobbs Time Out and Hobbs 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)) { + if (hobbsTimePair && (ho < 0 || hi < 0 || hi < ho)) { throw new IllegalArgumentException( - "Block Time In must be ≥ Block Time Out, and values cannot be negative."); + "Hobbs Time In must be ≥ Hobbs Time Out, and values cannot be negative."); } if (timeInServicePair && (to < 0 || ti < 0 || ti < to)) { throw new IllegalArgumentException( @@ -126,14 +126,14 @@ public AddedFlightLog add(User user, Aircraft aircraft, FlightLog newLog, boolea // "inaccurate": it just gets slotted into the chain below. if ("manual".equals(source) && !force) { List existingLogs = flightLogRepository.findByAircraft(aircraft); - HoursService.AccuracyIssue blockIssue = blockTimePair - ? hoursService.checkAccuracy(existingLogs, newLog.getBlockTimeStart(), newLog.getBlockTimeEnd(), ho, hi, true) + HoursService.AccuracyIssue hobbsIssue = hobbsTimePair + ? hoursService.checkAccuracy(existingLogs, newLog.getHobbsTimeStart(), newLog.getHobbsTimeEnd(), 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)); + if (hobbsIssue != null || serviceIssue != null) { + throw new InaccurateEntryException(inaccuracyMessage(hobbsIssue, serviceIssue)); } } @@ -175,20 +175,20 @@ public HourTotals delete(User user, Long id) { // Re-derives both hour totals from the log chain and stamps them as // coming from the flight log. private HourTotals recomputeHours(Aircraft aircraft) { - double newBlockTime = hoursService.recomputeChain(aircraft, /*useBlockTime=*/true); - double newTimeInService = hoursService.recomputeChain(aircraft, /*useBlockTime=*/false); - aircraft.setBlockTimeHours(newBlockTime); + double newHobbsTime = hoursService.recomputeChain(aircraft, /*useHobbsTime=*/true); + double newTimeInService = hoursService.recomputeChain(aircraft, /*useHobbsTime=*/false); + aircraft.setHobbsTimeHours(newHobbsTime); aircraft.setTimeInServiceHours(newTimeInService); Instant flightNow = Instant.now(); - aircraft.setBlockTimeUpdatedAt(flightNow); - aircraft.setBlockTimeUpdatedSource("flightlog"); + aircraft.setHobbsTimeUpdatedAt(flightNow); + aircraft.setHobbsTimeUpdatedSource("flightlog"); aircraft.setTimeInServiceUpdatedAt(flightNow); aircraft.setTimeInServiceUpdatedSource("flightlog"); aircraftRepository.save(aircraft); - return new HourTotals(newBlockTime, newTimeInService); + return new HourTotals(newHobbsTime, newTimeInService); } - // Chronological order for display: prefer blockTimeStart (engine start), + // Chronological order for display: prefer hobbsTimeStart (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. @@ -196,7 +196,7 @@ private static List sortedByFlightTime(List logs) { return logs.stream() .sorted(Comparator .comparing(log -> { - Instant t = log.getBlockTimeStart() != null ? log.getBlockTimeStart() : log.getTimeInServiceStart(); + Instant t = log.getHobbsTimeStart() != null ? log.getHobbsTimeStart() : log.getTimeInServiceStart(); return t == null ? Instant.MAX : t; }) .thenComparing(FlightLog::getId)) @@ -207,9 +207,9 @@ private static boolean tooLong(String value) { return value != null && value.length() > Validation.MAX_TEXT; } - private static String inaccuracyMessage(HoursService.AccuracyIssue blockIssue, HoursService.AccuracyIssue serviceIssue) { + private static String inaccuracyMessage(HoursService.AccuracyIssue hobbsIssue, HoursService.AccuracyIssue serviceIssue) { List sentences = new ArrayList<>(); - if (blockIssue != null) sentences.add(describeAccuracyIssue("Block Time", blockIssue)); + if (hobbsIssue != null) sentences.add(describeAccuracyIssue("Hobbs Time", hobbsIssue)); 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?"; diff --git a/src/main/java/com/example/AviaryService/services/flights/FlightSuggestionService.java b/src/main/java/com/example/AviaryService/services/flights/FlightSuggestionService.java index 6846816..14ca7e1 100644 --- a/src/main/java/com/example/AviaryService/services/flights/FlightSuggestionService.java +++ b/src/main/java/com/example/AviaryService/services/flights/FlightSuggestionService.java @@ -47,7 +47,7 @@ public FlightLog accept(long suggestionId, User user) { throw new IllegalArgumentException("This flight is already in your log book."); } - // Block Time can't come from AeroAPI (no engine data) -- stays blank + // Hobbs Time can't come from AeroAPI (no engine data) -- stays blank // for the user to fill in. Time in Service IS the flight's airborne // duration (ADSB_SYNC_SPEC.md, "the real maintenance clock"). Out/In // are just seeded with the right duration here -- this suggestion @@ -66,7 +66,7 @@ public FlightLog accept(long suggestionId, User user) { flightLog.setAircraft(aircraft); flightLogRepository.save(flightLog); - double newTimeInService = hoursService.recomputeChain(aircraft, /*useBlockTime=*/false); + double newTimeInService = hoursService.recomputeChain(aircraft, /*useHobbsTime=*/false); aircraft.setTimeInServiceHours(newTimeInService); Instant now = Instant.now(); aircraft.setTimeInServiceUpdatedAt(now); diff --git a/src/main/java/com/example/AviaryService/services/flights/GarminCsvService.java b/src/main/java/com/example/AviaryService/services/flights/GarminCsvService.java index 999b039..e8ce6d4 100644 --- a/src/main/java/com/example/AviaryService/services/flights/GarminCsvService.java +++ b/src/main/java/com/example/AviaryService/services/flights/GarminCsvService.java @@ -12,7 +12,7 @@ import com.example.AviaryService.entity.Aircraft; // 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 +// out the Hobbs time and airborne time. Only reads; nothing is saved until the // user submits the pre-filled flight log. @Service public class GarminCsvService { @@ -25,16 +25,16 @@ static CsvParseResult error(Map body) { } } - // Reads a Garmin engine-data CSV and works out the flight's block time + // Reads a Garmin engine-data CSV and works out the flight's Hobbs 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, Aircraft aircraft) { - // 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; + // Hobbs time: first → last row where oil pressure > 15 psi. + // Mirrors the physical HobbsTime meter on the Cirrus, which is oil-pressure activated. + java.time.Instant hobbsStart = null; + java.time.Instant hobbsEnd = null; // Flight (airborne) time: GndSpd > 35 kt sustained for 3+ consecutive seconds. // Falls back to IAS when GndSpd is empty (no GPS fix yet). @@ -102,13 +102,13 @@ public CsvParseResult parse(InputStream in, Aircraft aircraft) { rowTime = java.time.OffsetDateTime.parse(cols[dateIdx] + "T" + cols[timeIdx] + cols[ofstIdx]).toInstant(); } catch (Exception e) { continue; } - // ── Block time via oil pressure ────────────────────────────────── + // ── Hobbs 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; + if(hobbsStart == null) hobbsStart = rowTime; + hobbsEnd = rowTime; } } catch(NumberFormatException ignored) {} } @@ -137,29 +137,29 @@ public CsvParseResult parse(InputStream in, Aircraft aircraft) { } } - if(blockStart == null && airborneStart == null) { + if(hobbsStart == null && airborneStart == null) { return CsvParseResult.error( - csvValues("Could not detect airtime or block time", blockStart, blockEnd, airborneStart, airborneEnd)); + csvValues("Could not detect airtime or Hobbs time", hobbsStart, hobbsEnd, airborneStart, airborneEnd)); } - if(blockStart == null || blockEnd == null) { + if(hobbsStart == null || hobbsEnd == null) { return CsvParseResult.error( - csvValues("Could not detect engine run — Oil pressure does not go up by 15psi", blockStart, blockEnd, airborneStart, airborneEnd)); + csvValues("Could not detect engine run — Oil pressure does not go up by 15psi", hobbsStart, hobbsEnd, 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)); + csvValues("Could not detect air time — Speed does not go above 35kts", hobbsStart, hobbsEnd, 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(); + Duration hobbsDuration = Duration.between(hobbsStart, hobbsEnd); + String hobbsStr = "H:" + hobbsDuration.toHoursPart() + " M:" + hobbsDuration.toMinutesPart() + " S:" + hobbsDuration.toSecondsPart(); String airStr = "N/A"; @@ -169,8 +169,8 @@ public CsvParseResult parse(InputStream in, Aircraft aircraft) { airStr = "H:" + airDuration.toHoursPart() + " M:" + airDuration.toMinutesPart() + " S:" + airDuration.toSecondsPart(); } - double blockTimeOut = aircraft.getBlockTimeHours(); - double blockTimeIn = Math.round((blockTimeOut + blockDuration.toSeconds() / 3600.0) * 100.0) / 100.0; + double hobbsTimeOut = aircraft.getHobbsTimeHours(); + double hobbsTimeIn = Math.round((hobbsTimeOut + hobbsDuration.toSeconds() / 3600.0) * 100.0) / 100.0; double timeInServiceOut = aircraft.getTimeInServiceHours(); Double timeInServiceIn = airDuration != null ? Math.round((timeInServiceOut + airDuration.toSeconds() / 3600.0) * 100.0) / 100.0 @@ -178,12 +178,16 @@ public CsvParseResult parse(InputStream in, Aircraft aircraft) { Map result = new HashMap<>(); result.put("message", "CSV parse completed"); - result.put("flightDuration", blockStr); + result.put("flightDuration", hobbsStr); result.put("airDuration", airStr); - result.put("blockTimeOut", blockTimeOut); - result.put("blockTimeIn", blockTimeIn); - result.put("blockTimeStart", blockStart.toString()); - result.put("blockTimeEnd", blockEnd.toString()); + result.put("hobbsTimeOut", hobbsTimeOut); + result.put("blockTimeOut", hobbsTimeOut); // legacy key, remove after 2026-12-31 + result.put("hobbsTimeIn", hobbsTimeIn); + result.put("blockTimeIn", hobbsTimeIn); // legacy key, remove after 2026-12-31 + result.put("hobbsTimeStart", hobbsStart.toString()); + result.put("blockTimeStart", hobbsStart.toString()); // legacy key, remove after 2026-12-31 + result.put("hobbsTimeEnd", hobbsEnd.toString()); + result.put("blockTimeEnd", hobbsEnd.toString()); // legacy key, remove after 2026-12-31 result.put("timeInServiceOut", timeInServiceIn != null ? timeInServiceOut : null); result.put("timeInServiceIn", timeInServiceIn); result.put("timeInServiceStart", airborneStart != null ? airborneStart.toString() : null); @@ -199,11 +203,13 @@ public CsvParseResult parse(InputStream in, Aircraft aircraft) { } - private static Map csvValues(String error, java.time.Instant blockStart, java.time.Instant blockEnd, java.time.Instant airborneStart, java.time.Instant airborneEnd) { + private static Map csvValues(String error, java.time.Instant hobbsStart, java.time.Instant hobbsEnd, 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("hobbsStart", hobbsStart); + map.put("blockStart", hobbsStart); // legacy key, remove after 2026-12-31 + map.put("hobbsEnd", hobbsEnd); + map.put("blockEnd", hobbsEnd); // legacy key, remove after 2026-12-31 map.put("airborneStart", airborneStart); map.put("airborneEnd", airborneEnd); diff --git a/src/main/java/com/example/AviaryService/services/imports/TimelineImportService.java b/src/main/java/com/example/AviaryService/services/imports/StatusSheetImportService.java similarity index 84% rename from src/main/java/com/example/AviaryService/services/imports/TimelineImportService.java rename to src/main/java/com/example/AviaryService/services/imports/StatusSheetImportService.java index 18d62f8..1142662 100644 --- a/src/main/java/com/example/AviaryService/services/imports/TimelineImportService.java +++ b/src/main/java/com/example/AviaryService/services/imports/StatusSheetImportService.java @@ -20,36 +20,36 @@ import com.example.AviaryService.entity.Aircraft; import com.example.AviaryService.entity.ImportProposal; import com.example.AviaryService.entity.OAuthAuthorizationEntity; -import com.example.AviaryService.entity.ServiceTimeline; -import com.example.AviaryService.entity.TimelineImportRecord; +import com.example.AviaryService.entity.StatusSheetItem; +import com.example.AviaryService.entity.StatusSheetImportRecord; import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.ImportProposalRepository; import com.example.AviaryService.repositories.OAuthAuthorizationRepository; -import com.example.AviaryService.repositories.ServiceTimelineRepository; -import com.example.AviaryService.repositories.TimelineImportRecordRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; +import com.example.AviaryService.repositories.StatusSheetImportRecordRepository; import com.example.AviaryService.util.DueDates; import com.example.AviaryService.util.Formatting; import com.example.AviaryService.util.SlidingWindowLimiter; -import com.example.AviaryService.util.TimelineImportRules; -import com.example.AviaryService.util.TimelineImportRules.ImportFlag; -import com.example.AviaryService.util.TimelineImportRules.InputItem; -import com.example.AviaryService.util.TimelineImportRules.ItemResult; -import com.example.AviaryService.util.TimelineImportRules.ProposedItem; -import com.example.AviaryService.util.TimelineImportRules.RejectedRow; -import com.example.AviaryService.util.TimelineImportRules.SubmissionOutcome; +import com.example.AviaryService.util.StatusSheetImportRules; +import com.example.AviaryService.util.StatusSheetImportRules.ImportFlag; +import com.example.AviaryService.util.StatusSheetImportRules.InputItem; +import com.example.AviaryService.util.StatusSheetImportRules.ItemResult; +import com.example.AviaryService.util.StatusSheetImportRules.ProposedItem; +import com.example.AviaryService.util.StatusSheetImportRules.RejectedRow; +import com.example.AviaryService.util.StatusSheetImportRules.SubmissionOutcome; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -// Service timeline import through an AI assistant: propose (preview only), +// Status Sheet import through an AI assistant: propose (preview only), // continue a poor fit, confirm (saves exactly the proposal, all or nothing). // Imports only ever add rows -- existing items are never changed or deleted. // Every lookup is by owner, so one owner can't see or confirm another's // proposal. @Service -public class TimelineImportService { +public class StatusSheetImportService { - private static final Logger log = LoggerFactory.getLogger(TimelineImportService.class); + private static final Logger log = LoggerFactory.getLogger(StatusSheetImportService.class); static final Duration PROPOSAL_TTL = Duration.ofHours(24); static final int PROPOSALS_PER_HOUR = 30; @@ -77,8 +77,8 @@ public static ImportResult choose(String message) { } private final ImportProposalRepository proposalRepository; - private final ServiceTimelineRepository timelineRepository; - private final TimelineImportRecordRepository recordRepository; + private final StatusSheetItemRepository statusSheetItemRepository; + private final StatusSheetImportRecordRepository recordRepository; private final OAuthAuthorizationRepository authorizationRepository; private final TransactionTemplate transaction; private final ObjectMapper objectMapper = new ObjectMapper(); @@ -87,23 +87,23 @@ public static ImportResult choose(String message) { private final SlidingWindowLimiter confirmLimiter; @Autowired - public TimelineImportService(ImportProposalRepository proposalRepository, - ServiceTimelineRepository timelineRepository, - TimelineImportRecordRepository recordRepository, + public StatusSheetImportService(ImportProposalRepository proposalRepository, + StatusSheetItemRepository statusSheetItemRepository, + StatusSheetImportRecordRepository recordRepository, OAuthAuthorizationRepository authorizationRepository, PlatformTransactionManager transactionManager) { - this(proposalRepository, timelineRepository, recordRepository, authorizationRepository, + this(proposalRepository, statusSheetItemRepository, recordRepository, authorizationRepository, transactionManager, Clock.systemUTC()); } - TimelineImportService(ImportProposalRepository proposalRepository, - ServiceTimelineRepository timelineRepository, - TimelineImportRecordRepository recordRepository, + StatusSheetImportService(ImportProposalRepository proposalRepository, + StatusSheetItemRepository statusSheetItemRepository, + StatusSheetImportRecordRepository recordRepository, OAuthAuthorizationRepository authorizationRepository, PlatformTransactionManager transactionManager, Clock clock) { this.proposalRepository = proposalRepository; - this.timelineRepository = timelineRepository; + this.statusSheetItemRepository = statusSheetItemRepository; this.recordRepository = recordRepository; this.authorizationRepository = authorizationRepository; this.transaction = new TransactionTemplate(transactionManager); @@ -115,15 +115,15 @@ public TimelineImportService(ImportProposalRepository proposalRepository, // ---- propose ---- // Builds and stores a proposal for one aircraft. Changes nothing on the - // timeline. Any earlier open proposal of this owner FOR THE SAME AIRCRAFT + // Status Sheet item. Any earlier open proposal of this owner FOR THE SAME AIRCRAFT // is replaced; a pending proposal for another aircraft is left alone. public ImportResult propose(User user, Aircraft aircraft, List items, List rejectedBySource, String clientId) { List input = items == null ? List.of() : items; List fromSource = cleanSourceRejects(rejectedBySource); - if (input.size() > TimelineImportRules.MAX_ITEMS) { + if (input.size() > StatusSheetImportRules.MAX_ITEMS) { return ImportResult.status("TOO_LARGE", "That's " + input.size() + " items; the most one proposal can hold is " - + TimelineImportRules.MAX_ITEMS + ". Split the records and propose each part separately."); + + StatusSheetImportRules.MAX_ITEMS + ". Split the records and propose each part separately."); } if (!proposeLimiter.tryAcquire(user.getUsername())) { return rateLimited("Too many proposals in the last hour. Try again later."); @@ -131,17 +131,17 @@ public ImportResult propose(User user, Aircraft aircraft, List items, return transaction.execute(tx -> { LocalDate today = LocalDate.now(clock.withZone(ZoneOffset.UTC)); - ItemResult result = TimelineImportRules.evaluate(input, existingNames(aircraft), today); + ItemResult result = StatusSheetImportRules.evaluate(input, existingNames(aircraft), today); List rejected = new ArrayList<>(result.rejected()); rejected.addAll(fromSource); int submitted = input.size() + fromSource.size(); - SubmissionOutcome outcome = TimelineImportRules.classify(input.size(), submitted, rejected.size(), result); + SubmissionOutcome outcome = StatusSheetImportRules.classify(input.size(), submitted, rejected.size(), result); if (outcome == SubmissionOutcome.REJECTED) { return new ImportResult("REJECTED", null, null, null, rejected, null, "No maintenance items were found, so nothing was proposed. Every row was either missing an item " + "name or set aside as not being a maintenance item (reasons below). See the example for the format.", - TimelineImportRules.FORMAT_EXAMPLE, null, null, null, null); + StatusSheetImportRules.FORMAT_EXAMPLE, null, null, null, null); } for (ImportProposal old : proposalRepository.findByUserAndAircraftAndStatusIn(user, aircraft, LIVE)) { @@ -221,12 +221,12 @@ public ImportResult confirm(User user, Long proposalId, Set addDuplicat LocalDate today = LocalDate.now(clock.withZone(ZoneOffset.UTC)); Double currentTis = aircraft.getTimeInServiceHours(); - Integer max = timelineRepository.findMaxTimelineOrderByAircraft(aircraft); + Integer max = statusSheetItemRepository.findMaxStatusSheetOrderByAircraft(aircraft); int order = max == null ? 0 : max + 1; int added = 0; for (ProposedItem item : items) { - boolean matches = existing.contains(TimelineImportRules.normalizeName(item.item())); + boolean matches = existing.contains(StatusSheetImportRules.normalizeName(item.item())); if (matches && !optIn.contains(item.index())) { if (item.flags().contains(ImportFlag.DUPLICATE_EXISTING)) { skipped.add(item.item()); @@ -235,7 +235,7 @@ public ImportResult confirm(User user, Long proposalId, Set addDuplicat } continue; } - timelineRepository.save(toRow(user, aircraft, item, order++, today, currentTis)); + statusSheetItemRepository.save(toRow(user, aircraft, item, order++, today, currentTis)); added++; } @@ -244,7 +244,7 @@ public ImportResult confirm(User user, Long proposalId, Set addDuplicat proposal.setConfirmedAt(now); proposalRepository.save(proposal); - TimelineImportRecord record = new TimelineImportRecord(); + StatusSheetImportRecord record = new StatusSheetImportRecord(); record.setUser(user); record.setProposalId(proposal.getId()); record.setClientId(proposal.getConnectionClientId()); @@ -255,17 +255,17 @@ public ImportResult confirm(User user, Long proposalId, Set addDuplicat recordRepository.save(record); String message = "Added " + added + (added == 1 ? " item" : " items") + " to " - + aircraft.getDisplayName() + "'s service timeline."; + + aircraft.getDisplayName() + "'s Status Sheet."; if (!skipped.isEmpty() || !newDuplicates.isEmpty()) { message += " Skipped " + (skipped.size() + newDuplicates.size()) - + " that match items already on the timeline."; + + " that match items already on the Status Sheet."; } return new ImportResult("IMPORTED", proposal.getId(), null, null, null, null, message, null, added, skipped, newDuplicates, null); }); } catch (RuntimeException e) { // The transaction rolled back, so nothing from this proposal was saved. - log.warn("Timeline import {} failed for {}", proposalId, user.getUsername(), e); + log.warn("Status Sheet item import {} failed for {}", proposalId, user.getUsername(), e); return ImportResult.status("FAILED", "The import failed and nothing was added. The proposal is still open; try confirming again."); } @@ -305,13 +305,13 @@ private void expireIfDue(ImportProposal proposal) { } } - private ServiceTimeline toRow(User user, Aircraft aircraft, ProposedItem item, int order, LocalDate today, Double currentTis) { - ServiceTimeline row = new ServiceTimeline(); + private StatusSheetItem toRow(User user, Aircraft aircraft, ProposedItem item, int order, LocalDate today, Double currentTis) { + StatusSheetItem row = new StatusSheetItem(); row.setUser(user); row.setAircraft(aircraft); row.setItem(item.item()); row.setIsTitle(item.isTitle()); - row.setTimelineOrder(order); + row.setStatusSheetOrder(order); if (item.isTitle()) { return row; } @@ -328,7 +328,7 @@ private ServiceTimeline toRow(User user, Aircraft aircraft, ProposedItem item, i return row; } - // The timeline has no on-condition column, so the description says it -- + // The Status Sheet item has no on-condition column, so the description says it -- // otherwise the row shows up with every date blank and no explanation. static String onConditionDescription(String description) { if (description == null || description.isBlank()) return "On condition"; @@ -341,8 +341,8 @@ static String onConditionDescription(String description) { // on another plane is not a duplicate. private Set existingNames(Aircraft aircraft) { Set names = new HashSet<>(); - for (ServiceTimeline row : timelineRepository.findByAircraftOrderByTimelineOrderAsc(aircraft)) { - names.add(TimelineImportRules.normalizeName(row.getItem())); + for (StatusSheetItem row : statusSheetItemRepository.findByAircraftOrderByStatusSheetOrderAsc(aircraft)) { + names.add(StatusSheetImportRules.normalizeName(row.getItem())); } return names; } @@ -370,7 +370,7 @@ private static String summarize(List items, List reje if (titles > 0) sb.append(" and ").append(titles).append(titles == 1 ? " title row" : " title rows"); sb.append(" to add"); if (flagged > 0) sb.append(", ").append(flagged).append(" flagged for the owner to check"); - if (duplicates > 0) sb.append(" (").append(duplicates).append(" already on the timeline and skipped unless the owner opts in)"); + if (duplicates > 0) sb.append(" (").append(duplicates).append(" already on the Status Sheet and skipped unless the owner opts in)"); if (onCondition > 0) sb.append("; ").append(onCondition).append(" on condition"); if (noSchedule > 0) sb.append("; ").append(noSchedule).append(" with no due date or interval (Time Left shows N/A)"); if (dropped > 0) sb.append("; ").append(dropped).append(" with a value left blank (see notes)"); @@ -390,7 +390,7 @@ private static List cleanSourceRejects(List rows) { private static String truncate(String s) { if (s == null) return ""; - return s.length() > TimelineImportRules.MAX_SOURCE_ROW ? s.substring(0, TimelineImportRules.MAX_SOURCE_ROW) : s; + return s.length() > StatusSheetImportRules.MAX_SOURCE_ROW ? s.substring(0, StatusSheetImportRules.MAX_SOURCE_ROW) : s; } private static ImportResult rateLimited(String message) { diff --git a/src/main/java/com/example/AviaryService/services/stats/PublicStatsService.java b/src/main/java/com/example/AviaryService/services/stats/PublicStatsService.java index 2fd617d..fdac5a1 100644 --- a/src/main/java/com/example/AviaryService/services/stats/PublicStatsService.java +++ b/src/main/java/com/example/AviaryService/services/stats/PublicStatsService.java @@ -107,7 +107,7 @@ private boolean isStale(PublicStatsSnapshot snap) { private PublicStatsSnapshot compute() { Instant now = clock.instant(); - // Hours flown = time in service. Block time is empty on production + // Hours flown = time in service. Hobbs time is empty on production // flights, so it would always show 0 (research R6). Double hours = flightLogRepository.sumHoursFlown(); double hoursFlown = hours == null ? 0.0 : Math.round(hours * 10.0) / 10.0; diff --git a/src/main/java/com/example/AviaryService/util/DueDateAutoFill.java b/src/main/java/com/example/AviaryService/util/DueDateAutoFill.java new file mode 100644 index 0000000..c5c8352 --- /dev/null +++ b/src/main/java/com/example/AviaryService/util/DueDateAutoFill.java @@ -0,0 +1,254 @@ +package com.example.AviaryService.util; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.time.format.DateTimeParseException; +import java.util.Objects; +import java.util.Set; + +// Spec 007: fills a Status Sheet row's Due Date from Last Done + cycle. +// +// Pure functions only (no Spring, no repositories) so every rule is unit +// tested in DueDateAutoFillTest. The date math is DueDates.nextDueDate, the +// same one Complete Maintenance uses, so the two can never disagree. +// +// Who owns a Due Date part (date or hours) is tracked by an "auto" marker: +// TRUE -> the app filled it; it follows Last Done + cycle. +// FALSE -> the owner typed it; it is never overwritten. +// null -> row from before this feature; decided by comparison: blank, or +// equal to what the cycle gives for the stored Last Done, = auto. +public final class DueDateAutoFill { + + private DueDateAutoFill() { + } + + private static final Set UNITS = Set.of("DAYS", "MONTHS", "YEARS"); + + // Dates outside this range are treated as half-typed (e.g. year "0002"). + private static final int MIN_YEAR = 1900; + private static final int MAX_YEAR = 2200; + + public record Cycle(Integer calendarValue, String calendarUnit, Double hours) { + public boolean hasCalendar() { + return calendarValue != null && calendarValue > 0 && calendarUnit != null && UNITS.contains(calendarUnit); + } + + public boolean hasHours() { + return hours != null && Double.isFinite(hours) && hours > 0; + } + } + + // The value to save for one Due Date part, and whether it is auto-filled. + public record Resolved(String value, boolean auto) { + } + + // ── Hours format: at least 1 and at most 3 decimals ───────────────── + + // 25 -> "25.0", 25.25 -> "25.25", 25.12345 -> "25.123". null for null/NaN. + public static String formatHours(Double hours) { + if (hours == null || !Double.isFinite(hours)) { + return null; + } + return formatHours(BigDecimal.valueOf(hours)); + } + + private static String formatHours(BigDecimal v) { + BigDecimal r = v.setScale(3, RoundingMode.HALF_UP).stripTrailingZeros(); + if (r.scale() < 1) { + r = r.setScale(1, RoundingMode.UNNECESSARY); + } + return r.toPlainString(); + } + + // A plain non-negative number ("25", "25.5", ".5", " 25 "), else null. + public static BigDecimal parseHours(String raw) { + if (raw == null) { + return null; + } + String s = raw.trim(); + if (!s.matches("\\d+(\\.\\d*)?|\\.\\d+")) { + return null; + } + return new BigDecimal(s); + } + + // Normalizes typed hours to the display format. Blank -> null. Throws + // IllegalArgumentException with the owner-facing message if it is not + // a number. + public static String normalizeHours(String raw) { + if (raw == null || raw.isBlank()) { + return null; + } + BigDecimal v = parseHours(raw); + if (v == null) { + throw new IllegalArgumentException("Hours must be a number, e.g. 25.0"); + } + return formatHours(v); + } + + // Display-only: numeric text gets the decimal format; anything else + // (legacy "1200 TT") is shown as stored. + public static String displayHours(String stored) { + BigDecimal v = parseHours(stored); + return v == null ? stored : formatHours(v); + } + + // ── Expected due values ──────────────────────────────────────────── + + // A complete, sensible ISO date ("2026-10-30"), or null. Legacy cells + // that append hours ("2026-10-30 12.5") are read by their first token. + public static LocalDate validDate(String raw) { + if (raw == null || raw.isBlank()) { + return null; + } + String token = raw.trim().split("\\s+")[0]; + try { + LocalDate d = LocalDate.parse(token); + return (d.getYear() < MIN_YEAR || d.getYear() > MAX_YEAR) ? null : d; + } catch (DateTimeParseException e) { + return null; + } + } + + public static String expectedDueDate(String lastDoneDate, Cycle cycle) { + LocalDate last = validDate(lastDoneDate); + if (last == null || cycle == null || !cycle.hasCalendar()) { + return null; + } + return DueDates.nextDueDate(last, cycle.calendarValue(), cycle.calendarUnit()).toString(); + } + + public static String expectedDueHours(String lastDoneHours, Cycle cycle) { + BigDecimal last = parseHours(lastDoneHours); + if (last == null || cycle == null || !cycle.hasHours()) { + return null; + } + return formatHours(last.add(BigDecimal.valueOf(cycle.hours()))); + } + + // ── Mark complete (spec 008): what the "When was this done?" box starts with ── + + // Due Date, else Last Done + cycle, else today. null if the row has no + // calendar cycle (the date part is not offered). + public static String prefillDoneDate(String lastDoneDate, String dueDate, Cycle cycle, LocalDate today) { + if (cycle == null || !cycle.hasCalendar()) { + return null; + } + LocalDate due = validDate(dueDate); + if (due != null) { + return due.toString(); + } + String fromLast = expectedDueDate(lastDoneDate, cycle); + return fromLast != null ? fromLast : today.toString(); + } + + // Due Date hours, else Last Done hours + cycle, else null (empty box). + // Never guessed from current Time in Service (owner's rule). + public static String prefillDoneHours(String lastDoneHours, String dueHours, Cycle cycle) { + if (cycle == null || !cycle.hasHours()) { + return null; + } + BigDecimal due = parseHours(dueHours); + if (due != null) { + return formatHours(due); + } + return expectedDueHours(lastDoneHours, cycle); + } + + // A done date the owner entered: complete ISO date, year 1900-2200. + public static LocalDate validDoneDate(String raw) { + LocalDate d = validDate(raw); + if (d == null || !raw.trim().matches("\\d{4}-\\d{2}-\\d{2}")) { + throw new IllegalArgumentException("Enter the date it was done"); + } + return d; + } + + // ── Deciding what to save ────────────────────────────────────────── + + // storedX = values on the row before this save; newX = values after. + // touched = the owner edited this Due Date part in this save. + public static Resolved resolveDate(String storedLastDone, Cycle storedCycle, String storedDue, Boolean storedAuto, + String newLastDone, Cycle newCycle, String submittedDue, boolean touched) { + String newExpected = expectedDueDate(newLastDone, newCycle); + if (touched) { + // Owner typed or removed it. Removed (blank) stays theirs too, so a + // later unrelated save does not bring it back. + String v = blankToNull(submittedDue); + return new Resolved(v, v != null && sameDate(v, newExpected)); + } + boolean auto = storedAuto != null + ? storedAuto + : isBlank(storedDue) || sameDate(storedDue, expectedDueDate(storedLastDone, storedCycle)); + if (!auto) { + // An owner-removed (blank) Due Date fills again only when Last Done + // or the cycle actually changes. + if (isBlank(storedDue) && newExpected != null + && inputsChanged(storedLastDone, storedCycle, newLastDone, newCycle)) { + return new Resolved(newExpected, true); + } + return new Resolved(storedDue, false); + } + if (newExpected != null) { + return new Resolved(newExpected, true); + } + if (isBlank(newLastDone)) { + return new Resolved(null, true); // Last Done cleared: clear the auto Due Date + } + return new Resolved(storedDue, true); // half-typed date or no cycle: keep as is + } + + public static Resolved resolveHours(String storedLastDone, Cycle storedCycle, String storedDue, Boolean storedAuto, + String newLastDone, Cycle newCycle, String submittedDue, boolean touched) { + String newExpected = expectedDueHours(newLastDone, newCycle); + if (touched) { + String v = blankToNull(submittedDue); + return new Resolved(v, v != null && sameHours(v, newExpected)); + } + boolean auto = storedAuto != null + ? storedAuto + : isBlank(storedDue) || sameHours(storedDue, expectedDueHours(storedLastDone, storedCycle)); + if (!auto) { + if (isBlank(storedDue) && newExpected != null + && inputsChanged(storedLastDone, storedCycle, newLastDone, newCycle)) { + return new Resolved(newExpected, true); + } + return new Resolved(storedDue, false); + } + if (newExpected != null) { + return new Resolved(newExpected, true); + } + if (isBlank(newLastDone)) { + return new Resolved(null, true); + } + return new Resolved(storedDue, true); + } + + private static boolean inputsChanged(String storedLastDone, Cycle storedCycle, String newLastDone, Cycle newCycle) { + return !sameText(storedLastDone, newLastDone) || !Objects.equals(storedCycle, newCycle); + } + + public static boolean sameDate(String a, String b) { + LocalDate da = validDate(a), db = validDate(b); + return da != null && da.equals(db); + } + + public static boolean sameHours(String a, String b) { + BigDecimal ha = parseHours(a), hb = parseHours(b); + return ha != null && hb != null && ha.setScale(3, RoundingMode.HALF_UP).compareTo(hb.setScale(3, RoundingMode.HALF_UP)) == 0; + } + + private static boolean isBlank(String s) { + return s == null || s.isBlank(); + } + + private static String blankToNull(String s) { + return isBlank(s) ? null : s.trim(); + } + + // Convenience for callers comparing typed text with what is stored. + public static boolean sameText(String a, String b) { + return Objects.equals(blankToNull(a), blankToNull(b)); + } +} diff --git a/src/main/java/com/example/AviaryService/util/DueDates.java b/src/main/java/com/example/AviaryService/util/DueDates.java index c6f26a8..8394573 100644 --- a/src/main/java/com/example/AviaryService/util/DueDates.java +++ b/src/main/java/com/example/AviaryService/util/DueDates.java @@ -5,7 +5,7 @@ import com.example.AviaryService.services.alerts.AlertLevel; -// Turns a Service Timeline row's stored due-date / due-hours strings into a +// Turns a Status Sheet 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/specs/ALERTS_SPEC.md. @@ -84,7 +84,7 @@ public static AlertLevel classify(String dueDateDate, String dueDateHours, // The Time Left text shown on the dashboard, print view and PDF, computed // fresh from the due date / due hours (never the stored timeLeft column, - // which goes stale). Calendar line first, hours line second, "N/A" if + // which goes stale). Calendar part first, hours part second, one line joined by " · " (spec 011), "N/A" if // neither. MUST stay in sync with calculateTimeLeft in dashboard.js. public static String formatTimeLeft(String dueDateDate, String dueDateHours, LocalDate today, Double currentTimeInService) { @@ -96,8 +96,8 @@ public static String formatTimeLeft(String dueDateDate, String dueDateHours, Double hours = hoursUntil(dueDateHours, currentTimeInService); if (hours != null) { double rounded = Math.round(hours * 10.0) / 10.0; - if (sb.length() > 0) sb.append('\n'); - sb.append(plainNumber(Math.abs(rounded))).append(rounded < 0 ? " hours overdue" : " hours left"); + if (sb.length() > 0) sb.append(" · "); + sb.append(plainNumber(Math.abs(rounded))).append(rounded < 0 ? " hrs overdue" : " hrs left"); } return sb.length() == 0 ? "N/A" : sb.toString(); } diff --git a/src/main/java/com/example/AviaryService/util/Formatting.java b/src/main/java/com/example/AviaryService/util/Formatting.java index 50188aa..c5b896d 100644 --- a/src/main/java/com/example/AviaryService/util/Formatting.java +++ b/src/main/java/com/example/AviaryService/util/Formatting.java @@ -4,7 +4,7 @@ public class Formatting { private Formatting() {} - // Real-world hour readings never exceed hundredths (block time reads to + // Real-world hour readings never exceed hundredths (Hobbs time reads to // 0.1, time in service to 0.01, AeroAPI is minute precision). Repeated double addition in // HoursService.recomputeChain otherwise leaves artifacts like // "2.0433333333333334". One home for the 2dp rule. diff --git a/src/main/java/com/example/AviaryService/util/TimelineImportRules.java b/src/main/java/com/example/AviaryService/util/StatusSheetImportRules.java similarity index 98% rename from src/main/java/com/example/AviaryService/util/TimelineImportRules.java rename to src/main/java/com/example/AviaryService/util/StatusSheetImportRules.java index 9d3be17..0c33471 100644 --- a/src/main/java/com/example/AviaryService/util/TimelineImportRules.java +++ b/src/main/java/com/example/AviaryService/util/StatusSheetImportRules.java @@ -13,7 +13,7 @@ import java.util.Objects; import java.util.Set; -// Turns the service timeline items an AI assistant pulled out of an owner's +// Turns the Status Sheet items an AI assistant pulled out of an owner's // records into Aviary items -- or into rejected rows with a plain reason. // Pure (no Spring, no database) so every rule is unit-tested. // @@ -24,7 +24,7 @@ // the owner to see in the proposal. Only rows with no name are rejected. Due // date / due hours come from last done + cycle with the same math as // Complete Maintenance. -public final class TimelineImportRules { +public final class StatusSheetImportRules { public static final int MAX_ITEMS = 200; public static final int MAX_SOURCE_ROW = 500; @@ -35,7 +35,7 @@ public enum ImportFlag { FUTURE_DATE, // last done is after today -- probably a typo UNSUPPORTED_CYCLE, // e.g. "every 50 landings"; kept in the description, not tracked CYCLE_INFERRED, // no cycle given; worked out from last done -> due - DUPLICATE_EXISTING, // same name as an item already on the timeline; skipped unless the owner opts in + DUPLICATE_EXISTING, // same name as an item already on the Status Sheet; skipped unless the owner opts in DUPLICATE_IN_INPUT, // same name appears more than once in this import ON_CONDITION, // marked on condition: inspected/replaced when its condition calls for it NO_SCHEDULE, // no due date or interval at all; shows N/A until the owner adds one @@ -87,7 +87,7 @@ public record ItemResult(List items, List rejected) { "Only rows that are not maintenance items at all (or have no name you can find) go in rejectedBySource, with a reason.", "At most " + MAX_ITEMS + " items per proposal."); - private TimelineImportRules() {} + private StatusSheetImportRules() {} public enum SubmissionOutcome { PROPOSED, // a normal proposal @@ -99,7 +99,7 @@ public enum SubmissionOutcome { // The verdict on a whole submission. submitted counts every row the // assistant sent (items + rows it couldn't read itself); rejected counts // every row that didn't make it into the proposal. Title rows alone don't - // count as usable -- a list of headings isn't a timeline. + // count as usable -- a list of headings isn't a Status Sheet item. public static SubmissionOutcome classify(int itemCount, int submitted, int rejected, ItemResult result) { if (itemCount > MAX_ITEMS) return SubmissionOutcome.TOO_LARGE; boolean anyRealItem = result.items().stream().anyMatch(i -> !i.isTitle()); diff --git a/src/main/resources/static/css/dashboardstyle.css b/src/main/resources/static/css/dashboardstyle.css index 6e0be60..001dfa5 100644 --- a/src/main/resources/static/css/dashboardstyle.css +++ b/src/main/resources/static/css/dashboardstyle.css @@ -152,7 +152,7 @@ input[type="checkbox"]:focus-visible { .fixed-header #subscribe, .edit-hours-btn, .back-to-full-list-button, -#add-block-time-btn, +#add-hobbs-time-btn, #add-time-in-service-btn, .add-button, .add-log-button, @@ -307,7 +307,7 @@ input[type="checkbox"]:focus-visible { .edit-hours-btn:hover, .back-to-full-list-button:hover { background: var(--primary-light); border-color: var(--primary); } -/* Shown above the Service Timeline while one section (title) is filtered. */ +/* Shown above the Status Sheet while one section (title) is filtered. */ .section-filter-bar { display: flex; align-items: center; @@ -327,16 +327,16 @@ input[type="checkbox"]:focus-visible { .section-filter-label strong { color: var(--text); } -#add-block-time-btn, +#add-hobbs-time-btn, #add-time-in-service-btn { background: var(--primary); color: #fff; padding: 5px 10px; } -#add-block-time-btn:hover, #add-time-in-service-btn:hover { background: var(--primary-dark); } +#add-hobbs-time-btn:hover, #add-time-in-service-btn:hover { background: var(--primary-dark); } /* Utility actions — quiet outline style so they don't compete with the - page's real work (the timeline and log book). */ + page's real work (the statusSheetItem and log book). */ #print-dashboard, #export-excel { background: var(--surface); @@ -385,7 +385,7 @@ input[type="checkbox"]:focus-visible { flex-wrap: wrap; } -.current-block-time-display, +.current-hobbs-time-display, .current-time-in-service-display { font-size: 15px; font-weight: 600; @@ -399,6 +399,12 @@ input[type="checkbox"]:focus-visible { gap: 2px; } +.hours-label-row { + display: inline-flex; + align-items: center; + flex-wrap: nowrap; +} + .hours-updated { font-size: 11px; font-weight: 500; @@ -574,7 +580,7 @@ input[type="checkbox"]:focus-visible { width: auto; } -/* ── Service timeline table ── */ +/* ── Status Sheet table ── */ #sortable-info-table { table-layout: auto; border-collapse: collapse; @@ -706,7 +712,9 @@ td.add-cell { .title-row .title-cell { cursor: pointer; } /* click a title to show just that section */ /* Hover highlight only with a real mouse -- on touch it stuck after a tap. */ @media (hover: hover) { - .title-row .title-cell:hover { background: var(--primary-dark); } + /* Whole bar darkens together: grip, title, empty cell and trash can (spec 009). + Not while the row is being dragged, so no dark color sticks after a drop. */ + .title-row:not(.sortable-chosen):not(.sortable-ghost):hover td { background: var(--primary-dark); } } /* No grid hairlines inside the solid green title bar */ .title-row td { border-color: transparent; } @@ -1346,11 +1354,11 @@ textarea::placeholder { display: none; } .add-row.title-mode td:nth-child(n+3):nth-child(-n+7) * { visibility: hidden; } /* ── Mobile / narrow (≤960px) ── - The service-timeline table has a hard min-content width of ~903px (the Last + The status-sheet table has a hard min-content width of ~903px (the Last Done / Due Date columns floor at 150px so the date inputs never clip). Below that the table would grow past the viewport and the whole page would scroll sideways. So we switch to the stacked card layout at ≤960px (comfortably - above 903) — the cards always fit, so the timeline never overflows. ── */ + above 903) — the cards always fit, so the statusSheetItem never overflows. ── */ @media screen and (max-width: 960px) { .header { padding: 16px clamp(8px, 3vw, 24px) 0; } .main { padding: 12px clamp(8px, 3vw, 24px); } @@ -1582,7 +1590,7 @@ textarea::placeholder { display: none; } padding: 0; } - /* ════ Service Timeline cards ════ + /* ════ Status Sheet cards ════ Saved item cards and the add card share every rule below through `#sortable-info-table :is(.sortable tr:not(.title-row), .add-row)`, so the add card always matches the saved ones. The #id prefix also lets these @@ -2046,7 +2054,7 @@ textarea::placeholder { display: none; } .logbook-table thead { display: none; } .logbook-table tbody#logbook-body { display: flex; flex-direction: column; gap: 8px; margin: 0; } - /* Option C: each log = 2-col grid (From|To, Block Time Out|In, Time in Service Out|In) */ + /* Option C: each log = 2-col grid (From|To, Hobbs Time Out|In, Time in Service Out|In) */ .logbook-table tr.log-row, .logbook-table tr.add-log-row { display: grid; @@ -2148,7 +2156,7 @@ textarea::placeholder { display: none; } margin: 0; padding: 8px 24px 0; } - #service-tab { padding: 0; } + #status-sheet-tab { padding: 0; } /* One line per Time Left entry ("12 days left" / "181.3 hours left"), wrapping only between the calendar and hours lines. */ @@ -2654,7 +2662,7 @@ textarea::placeholder { display: none; } #add-aircraft-save.saving::after { content: "…"; } /* Empty aircraft: first step is visible right away. */ -#empty-timeline { display: flex; flex-direction: column; gap: 10px; margin-bottom: 12px; } +#empty-statusSheetItem { display: flex; flex-direction: column; gap: 10px; margin-bottom: 12px; } .add-first-item-btn { align-self: flex-start; min-height: 44px; @@ -2738,5 +2746,135 @@ textarea::placeholder { display: none; } #aircraft-picker-btn .aircraft-picker-caret { display: none; } } @media print { - .aircraft-picker, #empty-timeline { display: none !important; } + .aircraft-picker, #empty-statusSheetItem { display: none !important; } +} + +/* Info marks next to Hobbs Time / Time in Service (My Hours). The tooltip + text comes from data-tip; it shows on hover, keyboard focus, or tap + (.open, toggled in dashboard.js). */ +.info-mark { + position: relative; + display: inline-flex; + align-items: center; + margin-left: 4px; + padding: 0; + border: 0; + background: none; + color: var(--text-muted); + font-size: 0.9em; + cursor: help; + vertical-align: middle; +} +.info-mark:focus-visible { outline: 2px solid var(--text-muted); outline-offset: 2px; border-radius: 50%; } +.info-mark::after { + content: attr(data-tip); + position: absolute; + left: 50%; + top: calc(100% + 6px); + transform: translateX(calc(-50% + var(--tip-shift, 0px))); + width: max-content; + max-width: min(260px, calc(100vw - 32px)); + padding: 6px 10px; + border: 1px solid var(--border); + border-radius: 6px; + background: var(--surface); + color: var(--text); + font-size: 12px; + font-weight: normal; + line-height: 1.35; + text-align: left; + white-space: normal; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12); + z-index: 50; + display: none; + pointer-events: none; +} +.info-mark:hover::after, +.info-mark:focus-visible::after, +.info-mark.open::after { display: block; } +/* Phones: the info marks add ~17px per hours block. Tighter column spacing + keeps both blocks on one line, so My Hours doesn't grow taller. */ +@media (max-width: 480px) { + .hours-display-and-editbutton-container { column-gap: 12px; } +} +/* Status Sheet tab info mark sits between the two tab buttons. */ +.tabs .info-mark { align-self: center; margin-left: 0; margin-right: 4px; } +/* Spec 007: typo check under Last Done (e.g. a future date). */ +.row-warning { + margin-top: 4px; + font-size: 11px; + line-height: 1.3; + color: #9A5B00; +} +:root[data-theme="dark"] .row-warning { color: #F0B65A; } +/* Spec 007: roll-forward box with two choices (Mark complete / Reset to cycle). */ +.choice-box { max-width: 400px; } +.choice-list { display: flex; flex-direction: column; gap: 14px; margin-bottom: 16px; text-align: left; } +.choice-item .confirm-btn { width: 100%; min-height: 44px; } +.confirm-btn.choice-secondary { background: var(--surface); color: var(--text); border: 1px solid var(--border); } +.confirm-btn.choice-secondary:hover:not(:disabled) { background: var(--primary-light); } +.choice-item .confirm-btn:disabled { opacity: 0.5; cursor: not-allowed; } +.choice-hint { margin-top: 4px; font-size: 12px; line-height: 1.35; color: var(--text-muted); } +/* Spec 008: "When was this done?" box. */ +.done-box { max-width: 380px; text-align: left; } +.done-box .confirm-message { text-align: center; } +.done-fields { display: flex; flex-direction: column; gap: 12px; margin-bottom: 12px; } +.done-field { display: flex; flex-direction: column; gap: 4px; font-size: 13px; font-weight: 600; color: var(--text); } +.done-field input { + font: inherit; font-size: 16px; font-weight: normal; padding: 8px 10px; min-height: 44px; + border: 1px solid var(--border); border-radius: 6px; background: var(--surface); color: var(--text); +} +.done-next { min-height: 20px; margin-bottom: 16px; font-size: 14px; color: var(--text); } +.done-next.done-next-error { color: #B3261E; } +:root[data-theme="dark"] .done-next.done-next-error { color: #F2B8B5; } +.done-box .confirm-actions { justify-content: flex-end; } +.done-box .confirm-btn.ok:disabled { opacity: 0.5; cursor: not-allowed; } + +/* ── Spec 011: Time Left pills ([2 mo 12 d] [480 h] overdue) ── */ +:root { + --tl-ok-bg: #E3F4EC; --tl-ok-fg: #1E7A54; + --tl-soon-bg: #FFF1D6; --tl-soon-fg: #8A5A00; + --tl-over-bg: #FDE4E9; --tl-over-fg: #B3203F; +} +:root[data-theme="dark"] { + --tl-ok-bg: #173D2C; --tl-ok-fg: #8FDDB7; + --tl-soon-bg: #3D2F12; --tl-soon-fg: #F3C46B; + --tl-over-bg: #47202A; --tl-over-fg: #FF9AAE; +} +.time-left .tl-pills { + display: inline-flex; + flex-wrap: wrap; /* wraps when the table is tight; one line on wide screens (below) */ + align-items: center; + justify-content: center; + gap: 4px 6px; + max-width: 100%; +} +.time-left .tl-pill { + display: inline-block; + padding: 2px 8px; + border-radius: 999px; + font-size: 12px; + font-weight: 600; + line-height: 1.4; + white-space: nowrap; +} +.time-left .tl-pill.tl-ok { background: var(--tl-ok-bg); color: var(--tl-ok-fg) !important; } +.time-left .tl-pill.tl-soon { background: var(--tl-soon-bg); color: var(--tl-soon-fg) !important; } +.time-left .tl-pill.tl-over { background: var(--tl-over-bg); color: var(--tl-over-fg) !important; } +.time-left .tl-overdue { + font-size: 12px; + font-weight: 700; + color: var(--tl-over-fg) !important; + white-space: nowrap; +} +/* Screen shows pills; print shows the plain words. */ +.time-left .tl-plain { display: none; } +@media print { + .time-left .tl-pills { display: none !important; } + .time-left .tl-plain { display: inline !important; white-space: normal; } +} +/* Wide screens: one line, [45 d] [480 h] overdue. Narrower (incl. phone cards): + pills wrap so the table never scrolls sideways. */ +@media (min-width: 1200px) { + .time-left .tl-pills { flex-wrap: nowrap; } } diff --git a/src/main/resources/static/js/dashboard.js b/src/main/resources/static/js/dashboard.js index 1346300..fc7dea8 100644 --- a/src/main/resources/static/js/dashboard.js +++ b/src/main/resources/static/js/dashboard.js @@ -3,8 +3,225 @@ console.log('dashboard.js loaded'); // One debounce timer per row / per aircraft-info field. A single shared timer // meant editing a second row (or field) within 500ms cancelled the first save. const rowSaveTimers = new Map(); +// Spec 007: per row, whether the owner edited the Due Date date / hours since +// the last save went out (kept across the 500ms debounce). +const rowDueTouched = new Map(); +// The pending (debounced) save per row, and the save currently in flight. +const rowPendingSends = new Map(); +const rowInFlight = new Map(); + +// Hours with 1-3 decimals: "25" -> "25.0", "25.12345" -> "25.123" (half up). +// Same rule as DueDateAutoFill.formatHours on the server. null if not a number. +function formatSheetHours(raw) { + const s = String(raw ?? '').trim(); + if (!/^(\d+(\.\d*)?|\.\d+)$/.test(s)) return null; + let [i, f = ''] = s.split('.'); + i = i.replace(/^0+(?=\d)/, '') || '0'; + if (f.length > 3) { + const n = BigInt(i + f.slice(0, 3)) + (f[3] >= '5' ? 1n : 0n); + const str = n.toString().padStart(4, '0'); + i = str.slice(0, -3); + f = str.slice(-3); + } + f = f.replace(/0+$/, '') || '0'; + return `${i}.${f}`; +} + +// Shows what the server saved for a row (spec 007): an auto-filled Due Date +// appears right after Last Done is entered, no reload. Never rewrites a box +// the owner is typing in. +function applySavedRow(row, saved) { + if (!row || !saved || saved.status !== 'success') return; + const lastCell = row.querySelector('td:nth-child(5) .input-with-dropdown'); + const dueCell = row.querySelector('td:nth-child(6) .input-with-dropdown'); + const focused = document.activeElement; + + if (dueCell && !dueCell.contains(focused)) { + const shownDate = dueCell.querySelector('input[type="date"]')?.value || ''; + const shownHours = dueCell.querySelector('input[type="text"].extra-input')?.value || ''; + const newDate = saved.dueDateDate || ''; + const newHours = saved.dueDateHours || ''; + if (shownDate !== newDate || shownHours !== newHours) { + repaintDateHoursCell(row, 'dueDate', [newDate, newHours].filter(Boolean).join(' ')); + } + } + const lastHoursInput = lastCell?.querySelector('input[type="text"].extra-input'); + if (lastHoursInput && lastHoursInput !== focused && saved.lastDoneHours != null + && lastHoursInput.value !== saved.lastDoneHours) { + lastHoursInput.value = saved.lastDoneHours; + } + + row.setAttribute('data-lastDoneDate', saved.lastDoneDate || ''); + row.setAttribute('data-lastDoneHours', saved.lastDoneHours || ''); + row.setAttribute('data-dueDateDate', saved.dueDateDate || ''); + row.setAttribute('data-dueDateHours', saved.dueDateHours || ''); + + const tl = row.querySelector('td:nth-child(7) .time-left'); + if (tl && saved.timeLeft) setTimeLeftText(tl, saved.timeLeft); + + const lastTd = row.querySelector('td:nth-child(5)'); + let note = lastTd?.querySelector('.row-warning'); + const warnings = Array.isArray(saved.warnings) ? saved.warnings : []; + if (warnings.length && lastTd) { + if (!note) { + note = document.createElement('div'); + note.className = 'row-warning no-print'; + note.setAttribute('role', 'status'); + lastTd.appendChild(note); + } + note.textContent = warnings.join(' '); + } else if (note) { + note.remove(); + } +} + +// Tidy Status Sheet hours when the owner leaves the box (never mid-typing). +document.addEventListener('focusout', (e) => { + const el = e.target; + if (!(el instanceof HTMLInputElement) || !el.matches('.input-with-dropdown input.extra-input[type="text"]')) return; + const formatted = formatSheetHours(el.value); + if (formatted !== null && formatted !== el.value) { + el.value = formatted; + if (el.closest('.auto-save-row')) autoSave(el); + else if (el.closest('.add-row')) scheduleAddRowResolve(); + } +}); + +// ── Add row, spec 010: fill the Due Date before Add ────────────────── +// The add row isn't saved, so it keeps its own state and asks the server to +// apply the same rule saved rows use (POST /statusSheet/addRowResolve). +const addRowState = { prev: null, dateAuto: null, hoursAuto: null, + touched: { date: false, hours: false }, + present: { date: false, hours: false }, timer: null, seq: 0 }; + +function resetAddRowState() { + clearTimeout(addRowState.timer); + addRowState.prev = null; + addRowState.dateAuto = null; + addRowState.hoursAuto = null; + addRowState.touched = { date: false, hours: false }; + addRowState.present = { date: false, hours: false }; + addRowState.seq++; + document.querySelector('.add-row .row-warning')?.remove(); +} + +function addRowCell(label) { + return document.querySelector(`.add-row td[data-label="${label}"] .input-with-dropdown`); +} + +function readAddRow() { + const last = addRowCell('Last Done'), due = addRowCell('Due Date'); + const v = (el) => (el ? el.value.trim() : ''); + return { + lastDoneDate: v(last?.querySelector('input[type="date"]')), + lastDoneHours: v(last?.querySelector('input[type="text"].extra-input')), + cycleCalendarValue: v(document.querySelector('.add-row input[name="cycleCalendarValue"]')), + cycleCalendarUnit: v(document.querySelector('.add-row select[name="cycleCalendarUnit"]')), + cycleHours: v(document.querySelector('.add-row input[name="cycleHours"]')), + dueDateDate: v(due?.querySelector('input[type="date"]')), + dueDateHours: v(due?.querySelector('input[type="text"].extra-input')), + hasDueDateInput: !!due?.querySelector('input[type="date"]'), + hasDueHoursInput: !!due?.querySelector('input[type="text"].extra-input') + }; +} + +function addRowIsTitle() { + return document.getElementById('isTitleHidden')?.value === 'true'; +} + +function scheduleAddRowResolve() { + clearTimeout(addRowState.timer); + if (addRowIsTitle()) { document.querySelector('.add-row .row-warning')?.remove(); return; } + addRowState.timer = setTimeout(resolveAddRow, 250); +} + +async function resolveAddRow() { + const now = readAddRow(); + // A Due Date calendar/clock that was there and is now gone = the user removed it. + if (addRowState.present.date && !now.hasDueDateInput) addRowState.touched.date = true; + if (addRowState.present.hours && !now.hasDueHoursInput) addRowState.touched.hours = true; + const prev = addRowState.prev || {}; + const body = { + prevLastDoneDate: prev.lastDoneDate ?? null, prevLastDoneHours: prev.lastDoneHours ?? null, + prevCycleCalendarValue: prev.cycleCalendarValue ?? null, prevCycleCalendarUnit: prev.cycleCalendarUnit ?? null, + prevCycleHours: prev.cycleHours ?? null, + lastDoneDate: now.lastDoneDate, lastDoneHours: now.lastDoneHours, + cycleCalendarValue: now.cycleCalendarValue, cycleCalendarUnit: now.cycleCalendarUnit, cycleHours: now.cycleHours, + dueDateDate: now.dueDateDate, dueDateHours: now.dueDateHours, + dueDateAuto: addRowState.dateAuto, dueHoursAuto: addRowState.hoursAuto, + dueDateTouched: addRowState.touched.date, dueHoursTouched: addRowState.touched.hours + }; + const mine = ++addRowState.seq; + addRowState.touched = { date: false, hours: false }; + try { + const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content'); + const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content'); + const r = (await axios.post('/statusSheet/addRowResolve', body, { + headers: { [csrfHeader]: csrfToken, 'Content-Type': 'application/json' } + })).data; + if (mine !== addRowState.seq) return; // a newer check is on its way + addRowState.prev = now; + addRowState.dateAuto = r.dueDateAuto; + addRowState.hoursAuto = r.dueHoursAuto; + const row = document.querySelector('.add-row'); + const dueCell = addRowCell('Due Date'); + if (dueCell && !dueCell.contains(document.activeElement) + && ((r.dueDateDate || '') !== now.dueDateDate || (r.dueDateHours || '') !== now.dueDateHours)) { + repaintDateHoursCell(row, 'dueDate', [r.dueDateDate, r.dueDateHours].filter(Boolean).join(' ')); + } + const after = readAddRow(); + addRowState.present = { date: after.hasDueDateInput, hours: after.hasDueHoursInput }; + showAddRowNote(r.warnings || []); + updateAddRowTimeLeft(); + } catch (e) { + if (mine !== addRowState.seq) return; + showAddRowNote(e?.response?.data?.message ? [e.response.data.message] : []); + } +} + +function showAddRowNote(messages) { + const td = document.querySelector('.add-row td[data-label="Last Done"]'); + if (!td) return; + let note = td.querySelector('.row-warning'); + if (!messages.length) { note?.remove(); return; } + if (!note) { + note = document.createElement('div'); + note.className = 'row-warning no-print'; + note.setAttribute('role', 'status'); + td.appendChild(note); + } + note.textContent = messages.join(' '); +} + +// Typing in the add row's Last Done or cycle re-checks; typing in its Due Date +// makes that part the user's. +document.addEventListener('input', (e) => { + const t = e.target; + if (!(t instanceof HTMLElement) || !t.closest('.add-row')) return; + const dueTd = t.closest('td[data-label="Due Date"]'); + if (dueTd && t.matches('input.extra-input')) { + if (t.type === 'date') addRowState.touched.date = true; + else addRowState.touched.hours = true; + } + if (dueTd || t.closest('td[data-label="Last Done"]') || t.matches('[name^="cycle"]')) { + scheduleAddRowResolve(); + } +}); +document.addEventListener('change', (e) => { + const t = e.target; + if (t instanceof HTMLElement && t.closest('.add-row') && t.matches('select[name="cycleCalendarUnit"]')) { + scheduleAddRowResolve(); + } +}); +// Add / Remove on the add row's calendar or clock changes what is there. +document.addEventListener('click', (e) => { + const b = e.target; + if (b instanceof HTMLElement && b.closest('.add-row') && b.matches('.add-type')) { + setTimeout(scheduleAddRowResolve, 0); // after the input is added/removed + } +}); const userInfoSaveTimers = new Map(); -let previousBlockTimeHours = document.getElementById('current-block-time')?.value || 0; +let previousHobbsTimeHours = document.getElementById('current-hobbs-time')?.value || 0; let previousTimeInServiceHours = document.getElementById('current-time-in-service')?.value || 0; // True from a successful CSV parse until the next Add (or a fresh upload) -- // tells the server this Out/In pair was computed from CSV data, not typed by @@ -108,6 +325,93 @@ function showConfirm(message, confirmLabel = 'Confirm') { } +// A confirm box with several actions (spec 007: roll-forward box). choices = +// [{ key, label, hint, disabled, primary }]. Resolves with the chosen key, or +// null for Cancel / Esc / click outside. Disabled choices stay visible with +// their hint so the owner sees why. +function showChoice(message, choices) { + return new Promise(resolve => { + const overlay = document.createElement('div'); + overlay.className = 'confirm-overlay'; + const box = document.createElement('div'); + box.className = 'confirm-box choice-box'; + box.setAttribute('role', 'dialog'); + box.setAttribute('aria-modal', 'true'); + const msg = document.createElement('div'); + msg.className = 'confirm-message'; + msg.textContent = message; + box.appendChild(msg); + + const list = document.createElement('div'); + list.className = 'choice-list'; + choices.forEach(c => { + const item = document.createElement('div'); + item.className = 'choice-item'; + const btn = document.createElement('button'); + btn.type = 'button'; + btn.className = 'confirm-btn ' + (c.primary ? 'ok' : 'choice-secondary'); + btn.dataset.choice = c.key; + btn.textContent = c.label; + if (c.disabled) btn.disabled = true; + item.appendChild(btn); + if (c.hint) { + const hint = document.createElement('div'); + hint.className = 'choice-hint'; + hint.textContent = c.hint; + item.appendChild(hint); + } + btn.addEventListener('click', () => close(c.key)); + list.appendChild(item); + }); + box.appendChild(list); + + const actions = document.createElement('div'); + actions.className = 'confirm-actions'; + const cancel = document.createElement('button'); + cancel.type = 'button'; + cancel.className = 'confirm-btn cancel'; + cancel.textContent = 'Cancel'; + cancel.addEventListener('click', () => close(null)); + actions.appendChild(cancel); + box.appendChild(actions); + + overlay.appendChild(box); + document.body.appendChild(overlay); + requestAnimationFrame(() => overlay.classList.add('show')); + + function onKey(e) { if (e.key === 'Escape') close(null); } + function close(result) { + overlay.classList.remove('show'); + setTimeout(() => overlay.remove(), 150); + document.removeEventListener('keydown', onKey); + resolve(result); + } + overlay.addEventListener('click', (e) => { if (e.target === overlay) close(null); }); + document.addEventListener('keydown', onKey); + }); +} + +// "2021-01-01" -> "01/01/2021" by hand, so a time zone can never shift the day. +function formatPlainDate(iso) { + const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso || ''); + return m ? `${m[2]}/${m[3]}/${m[1]}` : (iso || ''); +} + +// "Reset to cycle" from the roll-forward box: Due Date = Last Done + cycle. +async function resetDueToCycle(row, id) { + try { + const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content'); + const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content'); + const response = await axios.post(`/resetDueToCycle/${id}`, {}, { + headers: { [csrfHeader]: csrfToken, 'Content-Type': 'application/json' } + }); + applySavedRow(row, response.data); + showToast('Due Date reset to the cycle.', 'success'); + } catch (error) { + showToast(error?.response?.data?.message || 'Could not reset the Due Date.', 'error'); + } +} + // ── "Last updated" formatting for the My Hours card ── function relativeTime(date) { const sec = Math.round((Date.now() - date.getTime()) / 1000); @@ -141,7 +445,7 @@ function renderUpdatedFromData(elId) { if (el) el.textContent = formatUpdated(el.getAttribute('data-updated'), el.getAttribute('data-source')); } -// When a Block Time / Time in Service reading was actually taken -- distinct +// When a Hobbs Time / Time in Service reading was actually taken -- distinct // from formatUpdated above, which is "when this field was last edited." function formatLogTimestamp(iso) { if (!iso) return ''; @@ -197,8 +501,8 @@ function buildLogRowHtml(log) { return ` ${escapeHtml(log.fromAirport)} ${escapeHtml(log.toAirport)} - ${log.blockTimeOut ?? ''}${formatLogTimestamp(log.blockTimeStart)} - ${log.blockTimeIn ?? ''}${formatLogTimestamp(log.blockTimeEnd)} + ${log.hobbsTimeOut ?? ''}${formatLogTimestamp(log.hobbsTimeStart)} + ${log.hobbsTimeIn ?? ''}${formatLogTimestamp(log.hobbsTimeEnd)} ${log.timeInServiceOut ?? ''}${formatLogTimestamp(log.timeInServiceStart)} ${log.timeInServiceIn ?? ''}${formatLogTimestamp(log.timeInServiceEnd)} @@ -270,33 +574,65 @@ function autoSave(input) { const dueDateCal = data.dueDateDate || ''; const dueDateHrs = data.dueDateHours || ''; setTimeLeftText(timeLeftSpan, calculateTimeLeft(dueDateCal, dueDateHrs, currentTimeInServiceHours)); - data.timeLeft = timeLeftSpan.textContent; + data.timeLeft = timeLeftSpan.dataset.plain ?? timeLeftSpan.textContent; + } + + // Spec 007: remember (until the save goes out) whether the owner edited the + // Due Date date or hours themselves, so the server never overwrites it. + const dueCell = row.querySelector('td:nth-child(6)'); + const touched = rowDueTouched.get(id) || { date: false, hours: false }; + if (dueCell && dueCell.contains(input)) { + // Typing in a Due Date box, or tapping Remove on its calendar/clock + // (autoSave is then called with the Remove button), both count as + // the owner editing that part. + const removedType = input.classList?.contains('add-type') ? input.getAttribute('data-type') : null; + if (input.type === 'date' || removedType === 'calendar') touched.date = true; + else if ((input.type === 'text' && !removedType) || removedType === 'clock') touched.hours = true; } + rowDueTouched.set(id, touched); clearTimeout(rowSaveTimers.get(id)); //status.textContent = '...'; //status.className = 'save-status saving'; - rowSaveTimers.set(id, setTimeout(() => { + const send = () => { rowSaveTimers.delete(id); + rowPendingSends.delete(id); const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content'); const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content'); - console.log(data); - axios.post(`/update/${id}`, data, { + const sentTouched = rowDueTouched.get(id) || { date: false, hours: false }; + rowDueTouched.delete(id); + data.dueDateTouched = sentTouched.date; + data.dueHoursTouched = sentTouched.hours; + + const p = axios.post(`/update/${id}`, data, { headers: { [csrfHeader]: csrfToken } }) .then(response => { - - console.log ('Row id: ' + id + ' saved ✓'); + applySavedRow(row, response.data); }) .catch(error => { - //status.textContent = '✖'; - //status.className = 'save-status error'; console.error('Error saving:', error.response ? error.response.data : error); showToast(error.response?.data?.message || 'Could not save that change. Check your connection and try again.', 'error'); - }); - }, 500)); + }) + .finally(() => { if (rowInFlight.get(id) === p) rowInFlight.delete(id); }); + rowInFlight.set(id, p); + return p; + }; + rowPendingSends.set(id, send); + rowSaveTimers.set(id, setTimeout(send, 500)); +} + +// Finish this row's pending save now (skip the 500ms wait) and wait for any +// save already on its way, so a following action sees what is on screen. +function flushRowSave(id) { + const pending = rowPendingSends.get(id); + if (pending) { + clearTimeout(rowSaveTimers.get(id)); + return pending(); + } + return rowInFlight.get(id) || Promise.resolve(); } async function loadAeroApiUsage() { @@ -450,32 +786,150 @@ async function completeMaintenance(button) { showToast('Could not identify row.', 'error'); return; } - const confirmed = await showConfirm( - 'Mark this maintenance as just completed? This will reset Last Done to today / current hours and roll Due Date forward by the cycle.', - 'Mark complete'); - if (!confirmed) return; + // Make sure the server has what is on screen before previewing (spec 007). + await flushRowSave(id); + let preview = null; try { - const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content'); - const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content'); - const response = await axios.post(`/completeMaintenance/${id}`, {}, { - headers: { [csrfHeader]: csrfToken, 'Content-Type': 'application/json' } - }); - const { lastDone, dueDate, timeLeft } = response.data; - repaintDateHoursCell(row, 'lastDone', lastDone); - repaintDateHoursCell(row, 'dueDate', dueDate); - const parseSplit = (s) => { const [d, ...h] = (s || '').split(' '); return { date: d || '', hours: h.join(' ') }; }; - const ld = parseSplit(lastDone), dd = parseSplit(dueDate); - row.setAttribute('data-lastDoneDate', ld.date); - row.setAttribute('data-lastDoneHours', ld.hours); - row.setAttribute('data-dueDateDate', dd.date); - row.setAttribute('data-dueDateHours', dd.hours); - const tl = row.querySelector('td:nth-child(7) .time-left'); - if (tl) setTimeLeftText(tl, timeLeft || 'N/A'); - showToast('Maintenance completed. Due Date rolled forward.', 'success'); - } catch (error) { - const msg = error?.response?.data?.message || 'Failed to update maintenance.'; - showToast(msg, 'error'); + preview = (await axios.get(`/statusSheet/${id}/cyclePreview`)).data; + } catch (e) { + preview = { canReset: false, reason: 'Could not load the cycle date.' }; + } + const resetValue = [preview.dueDateDate ? formatPlainDate(preview.dueDateDate) : null, + preview.dueDateHours ? `${preview.dueDateHours} hrs` : null].filter(Boolean).join(' · '); + const choice = await showChoice('Mark this maintenance complete, or reset the Due Date?', [ + { key: 'complete', label: 'Mark complete', primary: true }, + { key: 'reset', label: resetValue ? `Reset to cycle (${resetValue})` : 'Reset to cycle', + disabled: !preview.canReset, + hint: preview.canReset ? 'Keeps Last Done. Due Date goes back to Last Done + cycle.' : preview.reason } + ]); + if (choice === 'reset') { await resetDueToCycle(row, id); return; } + if (choice !== 'complete') return; + await openDoneBox(row, id); +} + +// Spec 008: "When was this done?" box. Starts with the row's Due Date (the +// server decides the prefill), shows the next Due Date as the owner edits, +// and saves Last Done = that date / hours, Due = + cycle. The Due Date the box +// was opened with is sent back so a double-click or a second tab can never +// roll the row twice (the server answers 409). +async function openDoneBox(row, id) { + let start; + try { + start = (await axios.get(`/statusSheet/${id}/completePreview`)).data; + } catch (e) { + showToast(e?.response?.data?.message || 'Could not open Mark complete. Try again.', 'error'); + return; + } + if (!start.hasCalendar && !start.hasHours) { + showToast(start.reason || 'Set a cycle first.', 'error'); + return; } + + const overlay = document.createElement('div'); + overlay.className = 'confirm-overlay'; + overlay.innerHTML = + ''; + const dateField = overlay.querySelector('[data-part="date"]'); + const hoursField = overlay.querySelector('[data-part="hours"]'); + const dateInput = dateField.querySelector('input'); + const hoursInput = hoursField.querySelector('input'); + const next = overlay.querySelector('.done-next'); + const save = overlay.querySelector('.confirm-btn.ok'); + if (start.hasCalendar) dateInput.value = start.doneDate || ''; else dateField.remove(); + if (start.hasHours) hoursInput.value = start.doneHours || ''; else hoursField.remove(); + document.body.appendChild(overlay); + requestAnimationFrame(() => overlay.classList.add('show')); + (start.hasCalendar ? dateInput : hoursInput).focus(); + + const showResult = (p) => { + const parts = [p.nextDueDate ? formatPlainDate(p.nextDueDate) : null, + p.nextDueHours ? `${p.nextDueHours} hrs` : null].filter(Boolean); + next.textContent = p.canSave ? `Next due: ${parts.join(' · ')}` : (p.reason || ''); + next.classList.toggle('done-next-error', !p.canSave); + save.disabled = !p.canSave; + }; + showResult(start); + + let timer = null, seq = 0; + const refresh = () => { + clearTimeout(timer); + save.disabled = true; + timer = setTimeout(async () => { + const mine = ++seq; + const params = new URLSearchParams({ + doneDate: start.hasCalendar ? dateInput.value : '', + doneHours: start.hasHours ? hoursInput.value : '' + }); + try { + const p = (await axios.get(`/statusSheet/${id}/completePreview?${params}`)).data; + if (mine === seq) showResult(p); + } catch (e) { + if (mine === seq) { next.textContent = 'Could not check that date. Try again.'; save.disabled = true; } + } + }, 250); + }; + dateInput.addEventListener('input', refresh); + hoursInput.addEventListener('input', refresh); + hoursInput.addEventListener('blur', () => { + const f = formatSheetHours(hoursInput.value); + if (f !== null && f !== hoursInput.value) { hoursInput.value = f; refresh(); } + }); + + let closed = false; + const close = () => { + if (closed) return; + closed = true; + clearTimeout(timer); + overlay.classList.remove('show'); + setTimeout(() => overlay.remove(), 150); + document.removeEventListener('keydown', onKey); + }; + function onKey(e) { if (e.key === 'Escape') close(); } + document.addEventListener('keydown', onKey); + overlay.querySelector('.confirm-btn.cancel').addEventListener('click', close); + overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); }); + + save.addEventListener('click', async () => { + if (save.disabled) return; + save.disabled = true; // one save per box, even on a double-click + try { + const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content'); + const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content'); + const response = await axios.post(`/completeMaintenance/${id}`, { + doneDate: start.hasCalendar ? dateInput.value : '', + doneHours: start.hasHours ? hoursInput.value : '', + expectedDueDate: start.expectedDueDate || '', + expectedDueHours: start.expectedDueHours || '' + }, { headers: { [csrfHeader]: csrfToken, 'Content-Type': 'application/json' } }); + const saved = response.data; + repaintDateHoursCell(row, 'lastDone', [saved.lastDoneDate, saved.lastDoneHours].filter(Boolean).join(' ')); + repaintDateHoursCell(row, 'dueDate', [saved.dueDateDate, saved.dueDateHours].filter(Boolean).join(' ')); + applySavedRow(row, saved); + close(); + const last = [saved.lastDoneDate ? formatPlainDate(saved.lastDoneDate) : null, + saved.lastDoneHours ? `${saved.lastDoneHours} hrs` : null].filter(Boolean).join(' · '); + const due = [saved.dueDateDate ? formatPlainDate(saved.dueDateDate) : null, + saved.dueDateHours ? `${saved.dueDateHours} hrs` : null].filter(Boolean).join(' · '); + showToast(`Rolled forward. Last Done ${last}, Due ${due}.`, 'success'); + } catch (error) { + const msg = error?.response?.data?.message || 'Could not save. Nothing was changed.'; + next.textContent = msg; + next.classList.add('done-next-error'); + showToast(msg, 'error'); + if (error?.response?.status !== 409) save.disabled = false; // 409: reopen to review + } + }); } // Rebuilds the dual-input cell (date input and/or hours input) from a @@ -767,21 +1221,110 @@ function calculateTimeLeft(dueDateCal, dueDateHrs, currentTimeInServiceHours) { const dueDateHours = parseFloat(dueDateTimeValue); if (!isNaN(dueDateHours) && !isNaN(currentTimeInServiceHours)) { const hoursLeft = Math.round((dueDateHours - currentTimeInServiceHours) * 10) / 10; - const hoursText = hoursLeft < 0 ? `${Math.abs(hoursLeft)} hours overdue` : `${hoursLeft} hours left`; - output += output ? `\n${hoursText}` : hoursText; + const hoursText = hoursLeft < 0 ? `${Math.abs(hoursLeft)} hrs overdue` : `${hoursLeft} hrs left`; + output += output ? ` · ${hoursText}` : hoursText; // same as DueDates.formatTimeLeft (spec 011) } } - console.log("calculateTimeLeft OUTPUT--->" + output); - return output || 'N/A'; } +// Spec 011: each limit's amount, short label, plain words and status. +// Same amounts and rounding as calculateTimeLeft / DueDates.formatTimeLeft. +function timeLeftParts(dueDateCal, dueDateHrs, currentTimeInServiceHours) { + const table = document.getElementById('sortable-info-table'); + const leadDays = parseInt(table?.dataset.leadDays, 10); + const leadHours = parseFloat(table?.dataset.leadHours); + const soonDays = isNaN(leadDays) ? 30 : leadDays; + const soonHours = isNaN(leadHours) ? 10 : leadHours; + const parts = []; + const due = parseIsoDate(dueDateCal); + if (due) { + const now = new Date(); + const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); + const days = Math.round((due - today) / 86400000); + const plain = formatCalendarTimeLeft(dueDateCal, now); + parts.push({ + kind: 'date', plain, + label: plain.replace(/ (left|overdue)$/, '').replace(/\bdays?\b/g, 'd'), + status: days < 0 ? 'over' : (days <= soonDays ? 'soon' : 'ok') + }); + } + const dueHours = parseFloat(dueDateHrs); + if (dueDateHrs !== '' && dueDateHrs != null && !isNaN(dueHours) && !isNaN(currentTimeInServiceHours)) { + const left = Math.round((dueHours - currentTimeInServiceHours) * 10) / 10; + const abs = Math.abs(left); + parts.push({ + kind: 'hours', + plain: left < 0 ? `${abs} hrs overdue` : `${abs} hrs left`, + label: `${abs} h`, + status: left < 0 ? 'over' : (left <= soonHours ? 'soon' : 'ok') + }); + } + return parts; +} + +// Due Date parts for the row a Time Left cell belongs to: its inputs, else +// the row's data attributes (rows not built yet). +function dueValuesForCell(cell) { + const row = cell.closest('tr'); + const container = row?.querySelector('td:nth-child(6) .input-with-dropdown'); + if (!row || !container) return null; + const dateInput = container.querySelector('input[type="date"]'); + const textInput = container.querySelector('input[type="text"].extra-input'); + const hasInputs = dateInput || textInput || !row.hasAttribute('data-dueDateDate'); + return { + date: hasInputs ? (dateInput ? dateInput.value : '') : (row.getAttribute('data-dueDateDate') || ''), + hours: hasInputs ? (textInput ? textInput.value : '') : (row.getAttribute('data-dueDateHours') || '') + }; +} + +// Draws Time Left as colored pills (spec 011): [2 mo 12 d] [480 h] overdue. +// No icons; the unit tells date from hours. "overdue" follows an overdue +// pill, once after both if both are. The plain words stay on the cell +// (data-plain + a print-only span) for print, saving and export. function setTimeLeftText(cell, text) { - cell.textContent = text; - // Color comes from CSS (.time-left / .time-left.overdue) so it follows - // the light/dark theme; an inline color here would override both. - cell.classList.toggle('overdue', text.includes('overdue')); + const due = dueValuesForCell(cell); + const tisInput = document.getElementById('current-time-in-service'); + const tis = tisInput ? parseFloat(tisInput.value) || 0 : 0; + const parts = due ? timeLeftParts(due.date, due.hours, tis) : []; + + cell.textContent = ''; + if (!parts.length) { + const plainText = (text && text.trim()) ? text.trim() : (text === '' ? '' : 'N/A'); + cell.textContent = plainText; + cell.dataset.plain = plainText; + cell.classList.toggle('overdue', plainText.includes('overdue')); + return; + } + const screen = document.createElement('span'); + screen.className = 'tl-pills no-print'; + const bothOver = parts.length === 2 && parts.every(p => p.status === 'over'); + parts.forEach((p, i) => { + const pill = document.createElement('span'); + pill.className = `tl-pill tl-${p.status}`; + pill.textContent = p.label; + const what = p.kind === 'date' ? 'Date' : 'Hours'; + const state = p.status === 'over' ? '' : (p.status === 'soon' ? ', due soon' : ''); + pill.setAttribute('aria-label', `${what}: ${p.plain}${state}`); + screen.appendChild(pill); + if (p.status === 'over' && (!bothOver || i === parts.length - 1)) { + const word = document.createElement('span'); + word.className = 'tl-overdue'; + word.textContent = 'overdue'; + word.setAttribute('aria-hidden', 'true'); // already in the pill's label + screen.appendChild(word); + } + }); + const plain = parts.map(p => p.plain).join(' · '); + const printSpan = document.createElement('span'); + printSpan.className = 'print-only tl-plain'; + printSpan.textContent = plain; + cell.appendChild(screen); + cell.appendChild(printSpan); + cell.dataset.plain = plain; + // Color comes from CSS so it follows the light/dark theme. + cell.classList.toggle('overdue', parts.some(p => p.status === 'over')); } // Function to update all Time Left cells in real-time @@ -873,10 +1416,10 @@ document.addEventListener('DOMContentLoaded', () => { scheduleMidnightUpdate(); // My Hours "last updated" lines (initial render from server data) - renderUpdatedFromData('block-time-updated'); + renderUpdatedFromData('hobbs-time-updated'); renderUpdatedFromData('time-in-service-updated'); - // Flight log rows: when each Block Time/Time in Service reading was taken + // Flight log rows: when each Hobbs Time/Time in Service reading was taken renderLogTimestamps(); // Cycle hours come from the server as a Double ("500.0"); show whole @@ -1059,7 +1602,7 @@ document.addEventListener('DOMContentLoaded', () => { button.closest('.type-dropdown').style.display = 'none'; } else if (event.target.classList.contains('edit-hours-btn')) { document.getElementById('add-time-in-service').value = ''; - document.getElementById('add-block-time').value = ''; + document.getElementById('add-hobbs-time').value = ''; const editSection = document.querySelector('.edit-hours-section'); editSection.style.display = editSection.style.display === 'flex' ? 'none' : 'flex'; } @@ -1167,7 +1710,7 @@ document.addEventListener('DOMContentLoaded', () => { }); // Mobile/narrow: tap a flight log card to collapse it down to just From/To; - // tap again to expand. Same 960px gate as the timeline cards above. The + // tap again to expand. Same 960px gate as the Status Sheet cards above. The // delete button keeps its own click. document.getElementById('logbook-body').addEventListener('click', function(e) { if (!window.matchMedia('(max-width: 960px)').matches) return; @@ -1206,7 +1749,7 @@ document.addEventListener('DOMContentLoaded', () => { currentSectionId = null; } - // A bar directly above the Service Timeline table (it used to be inserted + // A bar directly above the Status Sheet table (it used to be inserted // above the page's FIRST table -- the aircraft info -- so it was off screen). function addBackButton(sectionName) { document.querySelector('.section-filter-bar')?.remove(); @@ -1242,19 +1785,19 @@ document.addEventListener('DOMContentLoaded', () => { options.forEach(option => option.onclick = () => selectOption(option)); }); - let previousBlockTimeHours = 0; + let previousHobbsTimeHours = 0; let previousTimeInServiceHours = 0; // One timer per field. A single shared timer meant that typing in TimeInService - // within 500ms of typing in BlockTime cancelled the pending BlockTime save. - let blockTimeout; + // within 500ms of typing in HobbsTime cancelled the pending HobbsTime save. + let hobbsTimeout; let timeInServiceTimeout; // The typed value still waiting out the 500ms debounce, or null if none. - let pendingBlockTimeSet = null; + let pendingHobbsTimeSet = null; let pendingTimeInServiceSet = null; - const currentBlockTimeHoursInput = document.getElementById('current-block-time'); + const currentHobbsTimeHoursInput = document.getElementById('current-hobbs-time'); const currentTimeInServiceHoursInput = document.getElementById('current-time-in-service'); function csrfHeaders() { @@ -1266,23 +1809,23 @@ document.addEventListener('DOMContentLoaded', () => { // Sends "set hours to exactly this". Returns a promise so callers can wait // for it to land before doing anything else. async function sendSetHours(kind, value) { - const isBlockTime = kind === 'blockTime'; - const input = isBlockTime ? currentBlockTimeHoursInput : currentTimeInServiceHoursInput; - const displayId = isBlockTime ? 'current-block-time-display' : 'current-time-in-service-display'; - const label = isBlockTime ? 'Block Time' : 'Time in Service'; - const previous = isBlockTime ? previousBlockTimeHours : previousTimeInServiceHours; + const isHobbsTime = kind === 'hobbsTime'; + const input = isHobbsTime ? currentHobbsTimeHoursInput : currentTimeInServiceHoursInput; + const displayId = isHobbsTime ? 'current-hobbs-time-display' : 'current-time-in-service-display'; + const label = isHobbsTime ? 'Hobbs Time' : 'Time in Service'; + const previous = isHobbsTime ? previousHobbsTimeHours : previousTimeInServiceHours; const params = new URLSearchParams(); - params.append(isBlockTime ? 'newBlockTime' : 'newTimeInService', parseFloat(value)); + params.append(isHobbsTime ? 'newHobbsTime' : 'newTimeInService', parseFloat(value)); try { const response = await axios.post('/updateHours', params, { headers: csrfHeaders() }); if (response.data.status === 'success') { - if (isBlockTime) previousBlockTimeHours = value; else previousTimeInServiceHours = value; + if (isHobbsTime) previousHobbsTimeHours = value; else previousTimeInServiceHours = value; document.getElementById(displayId).textContent = `${label}: ${value}`; - markUpdatedNow(isBlockTime ? 'block-time-updated' : 'time-in-service-updated', 'manual'); + markUpdatedNow(isHobbsTime ? 'hobbs-time-updated' : 'time-in-service-updated', 'manual'); console.log(`${label} hours updated successfully:`, - isBlockTime ? response.data.newBlockTime : response.data.newTimeInService); + isHobbsTime ? response.data.newHobbsTime : response.data.newTimeInService); return true; } console.error(`Failed to update ${label} hours:`, response.data.message); @@ -1299,31 +1842,31 @@ document.addEventListener('DOMContentLoaded', () => { // Called before "add hours" so a delayed set can never land afterwards and // overwrite the addition. async function flushPendingHours() { - clearTimeout(blockTimeout); + clearTimeout(hobbsTimeout); clearTimeout(timeInServiceTimeout); - const blockTime = pendingBlockTimeSet; + const hobbsTime = pendingHobbsTimeSet; const timeInService = pendingTimeInServiceSet; - pendingBlockTimeSet = null; + pendingHobbsTimeSet = null; pendingTimeInServiceSet = null; - if (blockTime !== null) await sendSetHours('blockTime', blockTime); + if (hobbsTime !== null) await sendSetHours('hobbsTime', hobbsTime); if (timeInService !== null) await sendSetHours('timeInService', timeInService); } - if (currentBlockTimeHoursInput) { - previousBlockTimeHours = currentBlockTimeHoursInput.value || 0; - currentBlockTimeHoursInput.addEventListener('input', function() { + if (currentHobbsTimeHoursInput) { + previousHobbsTimeHours = currentHobbsTimeHoursInput.value || 0; + currentHobbsTimeHoursInput.addEventListener('input', function() { updateAllTimeLeft(); updateAddRowTimeLeft(); - clearTimeout(blockTimeout); - const newBlockTimeHours = this.value.trim(); - if (newBlockTimeHours === '' || isNaN(parseFloat(newBlockTimeHours))) { - pendingBlockTimeSet = null; + clearTimeout(hobbsTimeout); + const newHobbsTimeHours = this.value.trim(); + if (newHobbsTimeHours === '' || isNaN(parseFloat(newHobbsTimeHours))) { + pendingHobbsTimeSet = null; return; } - pendingBlockTimeSet = newBlockTimeHours; - blockTimeout = setTimeout(() => { - pendingBlockTimeSet = null; - sendSetHours('blockTime', newBlockTimeHours); + pendingHobbsTimeSet = newHobbsTimeHours; + hobbsTimeout = setTimeout(() => { + pendingHobbsTimeSet = null; + sendSetHours('hobbsTime', newHobbsTimeHours); }, 500); }); } @@ -1410,7 +1953,8 @@ document.addEventListener('DOMContentLoaded', () => { } const description = document.querySelector('.add-row .custom-dropdown input[name="description"]').value; - const timeLeft = document.querySelector('.add-row .time-left').textContent; + const addTimeLeftEl = document.querySelector('.add-row .time-left'); + const timeLeft = addTimeLeftEl.dataset.plain ?? addTimeLeftEl.textContent; const addCalVal = document.querySelector('.add-row input[name="cycleCalendarValue"]')?.value || ''; const addCalUnit = document.querySelector('.add-row select[name="cycleCalendarUnit"]')?.value || ''; const addHrs = document.querySelector('.add-row input[name="cycleHours"]')?.value || ''; @@ -1438,8 +1982,11 @@ document.addEventListener('DOMContentLoaded', () => { data[`${field}Date`] = dateInput ? dateInput.value.trim() : ''; data[`${field}Hours`] = textInput ? textInput.value.trim() : ''; }); + // Spec 010: which Due Date parts were auto-filled / removed in the add row. + data.dueDateAuto = addRowState.dateAuto === null ? '' : String(addRowState.dateAuto); + data.dueHoursAuto = addRowState.hoursAuto === null ? '' : String(addRowState.hoursAuto); - console.log("NEW Service timeline row, POST request -->: ", data); + console.log("NEW Status Sheet row, POST request -->: ", data); axios.post('/dashboard', data, { headers: { @@ -1622,6 +2169,8 @@ document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.add-row .input-with-dropdown input.extra-input').forEach(input => input.remove()); document.querySelectorAll('.add-row .add-type').forEach(btn => btn.textContent = 'Add'); document.querySelector('.add-row .time-left').textContent = ''; + delete document.querySelector('.add-row .time-left').dataset.plain; + resetAddRowState(); selectRowType('item', document.querySelector('.row-type-option[data-type="item"]')); @@ -1632,7 +2181,7 @@ document.addEventListener('DOMContentLoaded', () => { }) .catch(error => { console.error('Error adding row:', error.response ? error.response.data : error); - showToast('Error adding row: ' + (error.response?.data || error.message), 'error'); + showToast(error.response?.data?.message || ('Error adding row: ' + (error.response?.data || error.message)), 'error'); }); }); } @@ -1641,9 +2190,9 @@ document.addEventListener('DOMContentLoaded', () => { document.addEventListener('click', function(event) { - if (event.target.id === 'add-block-time-btn') { - const blockTimeToAdd = document.getElementById('add-block-time').value.trim(); - addBlockTimeHours(blockTimeToAdd); + if (event.target.id === 'add-hobbs-time-btn') { + const hobbsTimeToAdd = document.getElementById('add-hobbs-time').value.trim(); + addHobbsTimeHours(hobbsTimeToAdd); } else if (event.target.id === 'add-time-in-service-btn') { const timeInServiceToAdd = document.getElementById('add-time-in-service').value.trim(); @@ -1808,10 +2357,10 @@ document.addEventListener('DOMContentLoaded', () => { }); }); - async function addBlockTimeHours(blockTimeToAdd) { - if (blockTimeToAdd && !isNaN(blockTimeToAdd)) { + async function addHobbsTimeHours(hobbsTimeToAdd) { + if (hobbsTimeToAdd && !isNaN(hobbsTimeToAdd)) { await flushPendingHours(); - await updateHours({ blockTimeToAdd: parseFloat(blockTimeToAdd) }); + await updateHours({ hobbsTimeToAdd: parseFloat(hobbsTimeToAdd) }); } } @@ -1840,13 +2389,13 @@ document.addEventListener('DOMContentLoaded', () => { }); if (response.data.status === 'success') { - const { newBlockTime, newTimeInService } = response.data; + const { newHobbsTime, newTimeInService } = response.data; - if (newBlockTime !== undefined) { - document.getElementById('current-block-time').value = newBlockTime; - document.getElementById('current-block-time-display').textContent = `Block Time: ${newBlockTime}`; - previousBlockTimeHours = newBlockTime; - console.log('Block time updated successfully:', newBlockTime); + if (newHobbsTime !== undefined) { + document.getElementById('current-hobbs-time').value = newHobbsTime; + document.getElementById('current-hobbs-time-display').textContent = `Hobbs Time: ${newHobbsTime}`; + previousHobbsTimeHours = newHobbsTime; + console.log('Hobbs time updated successfully:', newHobbsTime); } if (newTimeInService !== undefined) { @@ -1856,7 +2405,7 @@ document.addEventListener('DOMContentLoaded', () => { console.log('Time in Service updated successfully:', newTimeInService); } - if ('blockTimeToAdd' in updateParams) markUpdatedNow('block-time-updated', 'manual'); + if ('hobbsTimeToAdd' in updateParams) markUpdatedNow('hobbs-time-updated', 'manual'); if ('timeInServiceToAdd' in updateParams) markUpdatedNow('time-in-service-updated', 'manual'); // Update time left displays if needed (from your existing functions) @@ -1880,7 +2429,7 @@ document.addEventListener('DOMContentLoaded', () => { // Helper to generate Excel formula for Time Left (mimics calculateTimeLeft) function getTimeLeftFormula(row) { // row is 1-based Excel row - return `=IF(E${row}="","N/A",IF(ISERROR(DATEVALUE(LEFT(E${row},10))),LET(hourVal,VALUE(E${row}),IF(hourVal>B$1,(hourVal-B$1)&" hours left",ABS(hourVal-B$1)&" hours overdue")),LET(dateVal,DATEVALUE(LEFT(E${row},10)),spacePos,FIND(" ",E${row}&" "),hourStr,IF(spacePos=11,"",MID(E${row},spacePos+1,99)),hourVal,IF(hourStr="",NA(),VALUE(hourStr)),daysTxt,IF(dateVal>TODAY(),(dateVal-TODAY())&" days left",IF(dateValB$1,(hourVal-B$1)&" hours left",ABS(hourVal-B$1)&" hours overdue")),IF(hoursTxt="",daysTxt,daysTxt&CHAR(10)&hoursTxt))))`; + return `=IF(E${row}="","N/A",IF(ISERROR(DATEVALUE(LEFT(E${row},10))),LET(hourVal,VALUE(E${row}),IF(hourVal>B$1,(hourVal-B$1)&" hrs left",ABS(hourVal-B$1)&" hrs overdue")),LET(dateVal,DATEVALUE(LEFT(E${row},10)),spacePos,FIND(" ",E${row}&" "),hourStr,IF(spacePos=11,"",MID(E${row},spacePos+1,99)),hourVal,IF(hourStr="",NA(),VALUE(hourStr)),daysTxt,IF(dateVal>TODAY(),(dateVal-TODAY())&" days left",IF(dateValB$1,(hourVal-B$1)&" hrs left",ABS(hourVal-B$1)&" hrs overdue")),IF(hoursTxt="",daysTxt,daysTxt&" · "&hoursTxt))))`; } // Main export function @@ -1954,8 +2503,8 @@ document.addEventListener('DOMContentLoaded', () => { ws['!cols'] = colWidths; // Add sheet and download - XLSX.utils.book_append_sheet(wb, ws, "Service Timeline"); - XLSX.writeFile(wb, `Aircraft_Service_Timeline_${new Date().toISOString().split('T')[0]}.xlsx`); + XLSX.utils.book_append_sheet(wb, ws, "Status Sheet"); + XLSX.writeFile(wb, `Aircraft_Status_Sheet_${new Date().toISOString().split('T')[0]}.xlsx`); } // Share menu: a popover card under the Share button. Opens on click, @@ -2356,18 +2905,18 @@ document.addEventListener('DOMContentLoaded', () => { headers: { [csrfHeader]: csrfToken } }); allSuggestionsStale = true; // deleting can reset a suggestion back to pending - const { newBlockTime, newTimeInService } = deleteResponse.data; - if (newBlockTime !== undefined) { - document.getElementById('current-block-time').value = newBlockTime; - document.getElementById('current-block-time-display').textContent = `Block Time: ${newBlockTime}`; - previousBlockTimeHours = newBlockTime; + const { newHobbsTime, newTimeInService } = deleteResponse.data; + if (newHobbsTime !== undefined) { + document.getElementById('current-hobbs-time').value = newHobbsTime; + document.getElementById('current-hobbs-time-display').textContent = `Hobbs Time: ${newHobbsTime}`; + previousHobbsTimeHours = newHobbsTime; } if (newTimeInService !== undefined) { document.getElementById('current-time-in-service').value = newTimeInService; document.getElementById('current-time-in-service-display').textContent = `Time in Service: ${newTimeInService}`; previousTimeInServiceHours = newTimeInService; } - markUpdatedNow('block-time-updated', 'flightlog'); + markUpdatedNow('hobbs-time-updated', 'flightlog'); markUpdatedNow('time-in-service-updated', 'flightlog'); // A delete can shift other rows' Out/In too (see @@ -2385,8 +2934,8 @@ document.addEventListener('DOMContentLoaded', () => { async function submitAddFlightLog(force) { // Read raw strings first so an empty input stays null (not 0), letting // the server enforce the "complete pair" rule cleanly. - const rawBlockTimeIn = parseFloat(parseFloat(document.getElementById('blockTimeIn').value.trim()).toFixed(2)); - const rawBlockTimeOut = parseFloat(parseFloat(document.getElementById('blockTimeOut').value.trim()).toFixed(2)); + const rawHobbsTimeIn = parseFloat(parseFloat(document.getElementById('hobbsTimeIn').value.trim()).toFixed(2)); + const rawHobbsTimeOut = parseFloat(parseFloat(document.getElementById('hobbsTimeOut').value.trim()).toFixed(2)); const rawTimeInServiceIn = parseFloat(parseFloat(document.getElementById('timeInServiceIn').value.trim()).toFixed(2)); const rawTimeInServiceOut = parseFloat(parseFloat(document.getElementById('timeInServiceOut').value.trim()).toFixed(2)); const numOrNull = (s) => (s === '' || isNaN(parseFloat(s))) ? null : parseFloat(s); @@ -2394,12 +2943,12 @@ document.addEventListener('DOMContentLoaded', () => { const data = { fromAirport: document.getElementById('fromAirport').value, toAirport: document.getElementById('toAirport').value, - blockTimeOut: numOrNull(rawBlockTimeOut), - blockTimeIn: numOrNull(rawBlockTimeIn), + hobbsTimeOut: numOrNull(rawHobbsTimeOut), + hobbsTimeIn: numOrNull(rawHobbsTimeIn), timeInServiceOut: numOrNull(rawTimeInServiceOut), timeInServiceIn: numOrNull(rawTimeInServiceIn), - blockTimeStart: datetimeLocalToIso(document.getElementById('blockTimeStart').value), - blockTimeEnd: datetimeLocalToIso(document.getElementById('blockTimeEnd').value), + hobbsTimeStart: datetimeLocalToIso(document.getElementById('hobbsTimeStart').value), + hobbsTimeEnd: datetimeLocalToIso(document.getElementById('hobbsTimeEnd').value), timeInServiceStart: datetimeLocalToIso(document.getElementById('timeInServiceStart').value), timeInServiceEnd: datetimeLocalToIso(document.getElementById('timeInServiceEnd').value), source: csvPrefilled ? 'csv' : 'manual', @@ -2428,28 +2977,28 @@ document.addEventListener('DOMContentLoaded', () => { await refreshLogbookRows(); // Update hours display from backend-calculated totals - if (log.newBlockTime !== undefined && log.newBlockTime !== null) { - document.getElementById('current-block-time').value = log.newBlockTime; - document.getElementById('current-block-time-display').textContent = `Block Time: ${log.newBlockTime}`; - previousBlockTimeHours = log.newBlockTime; + if (log.newHobbsTime !== undefined && log.newHobbsTime !== null) { + document.getElementById('current-hobbs-time').value = log.newHobbsTime; + document.getElementById('current-hobbs-time-display').textContent = `Hobbs Time: ${log.newHobbsTime}`; + previousHobbsTimeHours = log.newHobbsTime; } if (log.newTimeInService !== undefined && log.newTimeInService !== null) { document.getElementById('current-time-in-service').value = log.newTimeInService; document.getElementById('current-time-in-service-display').textContent = `Time in Service: ${log.newTimeInService}`; previousTimeInServiceHours = log.newTimeInService; } - markUpdatedNow('block-time-updated', 'flightlog'); + markUpdatedNow('hobbs-time-updated', 'flightlog'); markUpdatedNow('time-in-service-updated', 'flightlog'); // Clear inputs document.getElementById('fromAirport').value = ''; document.getElementById('toAirport').value = ''; - document.getElementById('blockTimeIn').value = ''; - document.getElementById('blockTimeOut').value = ''; + document.getElementById('hobbsTimeIn').value = ''; + document.getElementById('hobbsTimeOut').value = ''; document.getElementById('timeInServiceIn').value = ''; document.getElementById('timeInServiceOut').value = ''; - document.getElementById('blockTimeStart').value = ''; - document.getElementById('blockTimeEnd').value = ''; + document.getElementById('hobbsTimeStart').value = ''; + document.getElementById('hobbsTimeEnd').value = ''; document.getElementById('timeInServiceStart').value = ''; document.getElementById('timeInServiceEnd').value = ''; csvPrefilled = false; @@ -2501,18 +3050,18 @@ document.addEventListener('DOMContentLoaded', () => { }); allSuggestionsStale = true; // deleting can reset a suggestion back to pending console.log(`Log ${id} deleted`); - const { newBlockTime, newTimeInService } = deleteResponse.data; - if (newBlockTime !== undefined) { - document.getElementById('current-block-time').value = newBlockTime; - document.getElementById('current-block-time-display').textContent = `Block Time: ${newBlockTime}`; - previousBlockTimeHours = newBlockTime; + const { newHobbsTime, newTimeInService } = deleteResponse.data; + if (newHobbsTime !== undefined) { + document.getElementById('current-hobbs-time').value = newHobbsTime; + document.getElementById('current-hobbs-time-display').textContent = `Hobbs Time: ${newHobbsTime}`; + previousHobbsTimeHours = newHobbsTime; } if (newTimeInService !== undefined) { document.getElementById('current-time-in-service').value = newTimeInService; document.getElementById('current-time-in-service-display').textContent = `Time in Service: ${newTimeInService}`; previousTimeInServiceHours = newTimeInService; } - markUpdatedNow('block-time-updated', 'flightlog'); + markUpdatedNow('hobbs-time-updated', 'flightlog'); markUpdatedNow('time-in-service-updated', 'flightlog'); updateAllTimeLeft(); updateAddRowTimeLeft(); @@ -2567,12 +3116,12 @@ document.addEventListener('DOMContentLoaded', () => { const data = response.data; showToast("CSV parsed successfully", 'info'); - document.getElementById("blockTimeOut").value = data.blockTimeOut ?? ''; - document.getElementById("blockTimeIn").value = data.blockTimeIn ?? ''; + document.getElementById("hobbsTimeOut").value = data.hobbsTimeOut ?? ''; + document.getElementById("hobbsTimeIn").value = data.hobbsTimeIn ?? ''; document.getElementById("timeInServiceOut").value = data.timeInServiceOut ?? ''; document.getElementById("timeInServiceIn").value = data.timeInServiceIn ?? ''; - document.getElementById("blockTimeStart").value = isoToDatetimeLocal(data.blockTimeStart); - document.getElementById("blockTimeEnd").value = isoToDatetimeLocal(data.blockTimeEnd); + document.getElementById("hobbsTimeStart").value = isoToDatetimeLocal(data.hobbsTimeStart); + document.getElementById("hobbsTimeEnd").value = isoToDatetimeLocal(data.hobbsTimeEnd); document.getElementById("timeInServiceStart").value = isoToDatetimeLocal(data.timeInServiceStart); document.getElementById("timeInServiceEnd").value = isoToDatetimeLocal(data.timeInServiceEnd); csvPrefilled = true; @@ -2588,9 +3137,9 @@ document.addEventListener('DOMContentLoaded', () => { const errorMessage = error.response?.data?.error || 'Upload failed'; showToast(errorMessage, 'error'); - console.log(errorData?.error); // "Could not detect airtime or block time" - console.log(errorData?.blockStart); // ISO instant string - console.log(errorData?.blockEnd); + console.log(errorData?.error); // "Could not detect airtime or Hobbs time" + console.log(errorData?.hobbsStart); // ISO instant string + console.log(errorData?.hobbsEnd); console.log(errorData?.airborneStart); console.log(errorData?.airborneEnd); @@ -2783,10 +3332,10 @@ document.addEventListener('DOMContentLoaded', () => { loadRecipients(); }); -// Empty-timeline "Import with AI" prompt: remove it as soon as the timeline +// empty Status Sheet "Import with AI" prompt: remove it as soon as the Status Sheet // gets its first row, so it never sits above real items. document.addEventListener('DOMContentLoaded', function () { - const prompt = document.getElementById('empty-timeline'); + const prompt = document.getElementById('empty-statusSheetItem'); const tbody = document.querySelector('.sortable'); if (!prompt || !tbody) return; const observer = new MutationObserver(function () { @@ -2895,7 +3444,7 @@ document.addEventListener('DOMContentLoaded', function () { const r = await axios.post('/aircraft', { tailNumber: tailInput.value, makeModel: document.getElementById('new-make-model').value, - ownerName: document.getElementById('new-owner-name').value, + operatorName: document.getElementById('new-operator-name').value, makeModelSN: document.getElementById('new-serial').value, }, { headers: csrfHeaderOnly() }); window.location.href = r.data.redirect; @@ -2969,3 +3518,37 @@ document.addEventListener('DOMContentLoaded', function () { } }); }); + +// Info marks (My Hours). Hover and keyboard focus are handled in CSS; this +// adds tap-to-toggle for touch screens, closes on tap outside or Esc, and +// nudges the tooltip sideways so it never runs off a narrow screen. +function placeInfoTip(mark) { + const r = mark.getBoundingClientRect(); + const vw = document.documentElement.clientWidth; + const half = Math.min(260, vw - 32) / 2; + const center = r.left + r.width / 2; + let shift = 0; + if (center - half < 16) shift = 16 - (center - half); + else if (center + half > vw - 16) shift = (vw - 16) - (center + half); + mark.style.setProperty('--tip-shift', shift + 'px'); +} +document.addEventListener('mouseover', (e) => { + const mark = e.target.closest('.info-mark'); + if (mark) placeInfoTip(mark); +}); +document.addEventListener('focusin', (e) => { + const mark = e.target.closest('.info-mark'); + if (mark) placeInfoTip(mark); +}); +document.addEventListener('click', (e) => { + const mark = e.target.closest('.info-mark'); + document.querySelectorAll('.info-mark.open').forEach((m) => { + if (m !== mark) m.classList.remove('open'); + }); + if (mark) { placeInfoTip(mark); mark.classList.toggle('open'); } +}); +document.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + document.querySelectorAll('.info-mark.open').forEach((m) => m.classList.remove('open')); + } +}); diff --git a/src/main/resources/templates/consent.html b/src/main/resources/templates/consent.html index 5cceb44..fcc4538 100644 --- a/src/main/resources/templates/consent.html +++ b/src/main/resources/templates/consent.html @@ -28,10 +28,10 @@

Connect an assistant

It will be able to:

diff --git a/src/main/resources/templates/dashboard.html b/src/main/resources/templates/dashboard.html index 8bde624..1b1898b 100644 --- a/src/main/resources/templates/dashboard.html +++ b/src/main/resources/templates/dashboard.html @@ -102,8 +102,8 @@

Add aircraft

More details (optional) - - + + @@ -277,33 +277,33 @@

Add aircraft

- +

My Hours

- - + +
- +