diff --git a/README.md b/README.md index 57ae5b2..9f9779e 100644 --- a/README.md +++ b/README.md @@ -16,13 +16,16 @@ A multi-user maintenance and flight-hours tracker for general-aviation aircraft - **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. - **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. -Each account is fully isolated — its own aircraft, service timeline, flight logs, and custom maintenance descriptions. Ownership is enforced server-side on every write. +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. ## Using it 1. **Register** at the link above (or **log in**). 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. 5. **Log flights** — add entries by hand, or upload a Garmin CSV and Aviary computes the times and updates your meters. @@ -43,7 +46,7 @@ You sign in on Aviary's own login page; the assistant never sees your password. **Import:** -1. Give the assistant your records — paste a list or attach a spreadsheet — and ask it to import them into Aviary. +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. diff --git a/docs/architecture/DATABASE.md b/docs/architecture/DATABASE.md index afc0224..c8a2d7d 100644 --- a/docs/architecture/DATABASE.md +++ b/docs/architecture/DATABASE.md @@ -8,29 +8,37 @@ - There is a tracked file named `dbdata` at the repo root (purpose unconfirmed — verify whether it holds local DB state or config). ## Tables (entity → table) -All ids are `@GeneratedValue(IDENTITY)`. Every row belongs to a `User` via `user_id` (FK, not null). +All ids are `@GeneratedValue(IDENTITY)`. Every row belongs to a `User` via `user_id` (FK, not null). Per-plane rows also belong to one `Aircraft` via `aircraft_id` (see below). ### `users` (`User`) -`id`, `username` (unique, not null), `password` (BCrypt, not null), `blockTimeHours` (Double), `timeInServiceHours` (Double), `makeModel`, `tailNumber`, `ownerName`, `makeModelSN`, `blockTimeUpdatedAt` / `timeInServiceUpdatedAt` (`Instant`, UTC timestamp, nullable), `blockTimeUpdatedSource` / `timeInServiceUpdatedSource` (String "manual" | "flightlog", nullable), `blockTimeManualBaseline` / `timeInServiceManualBaseline` (Double, manually-set floor so log activity can't silently lower the displayed total), `aeroApiKey` (encrypted, see `AeroApiKeyConverter`). -One-to-many (cascade ALL) → `serviceTimeline`, `flightLogs`. +`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`. + +**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. ### `service_timelines` (`ServiceTimeline`) -`id`, `item`, `isTitle` (boolean — title row vs item row), `description`, `cycle`, `lastDone`, `dueDate`, `timeLeft`, `timelineOrder` (Integer, display order), `user_id`. +`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`. ### `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`. +`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. ### `description_options` (`DescriptionOption`) `id`, `option` (not null), `user_id`. Stores a user's custom Service Timeline description choices. ### `flight_suggestions` (`FlightSuggestion`) -`id`, `tailNumber`, `faFlightId` (unique per user), `departureTime`, `arrivalTime` (`Instant`), `origin`, `destination`, `status` (String "pending" | "accepted" | "dismissed"), `createdAt`, `user_id`. AeroAPI-detected flights awaiting a user decision — see `docs/ADSB_SYNC_SPEC.md`. +`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`. An AI assistant's previewed timeline import; at most one OPEN/NEEDS_FIT_CONFIRMATION per user. +`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. ### `timeline_import_records` (`TimelineImportRecord`) -`id`, `user_id` (not null), `proposalId`, `clientId`, `clientName`, `itemCount`, `importedAt`. One row per confirmed import; shown on Connected assistants. +`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`) +`id`, `user_id` (not null, **no longer unique**), `aircraft_id` (unique — one flight-sync subscription per aircraft), `tailNumber`, `active`, `status`, `lastCheckedAt`, `lastSeenAt`, `pollIntervalDays`, `preferredCheckHour`. The old one-per-user unique constraint is dropped by `AircraftBackfill`. ### `oauth_authorizations` (`OAuthAuthorizationEntity`) — no `user_id` String `id`, `registeredClientId` (assistant's CIMD URL), `principalName` (username), scopes, attributes (TEXT), and the authorization code / access token / refresh token **SHA-256 hashes** with issued/expires/metadata, plus `clientName`, `lastUsedAt`. One row = one connected assistant; deleting it disconnects. Keyed by username rather than FK because Spring Authorization Server works in principal names. @@ -39,12 +47,16 @@ String `id`, `registeredClientId` (assistant's CIMD URL), `principalName` (usern Composite key (`registeredClientId`, `principalName`), `authorities`. Approved scopes per assistant per owner. ## Relationships -`User` 1—* `ServiceTimeline`, `FlightLog` (both cascade ALL, JSON managed/back references to avoid serialization loops). `User` 1—* `DescriptionOption`, `FlightSuggestion` (FK only, no mapped collection on `User` — accessed via repository query). +`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. + +## 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. ## Repositories (Spring Data JPA) - `UserRepository.findByUsername` -- `FlightLogRepository.findByUser` -- `ServiceTimelineRepository.findByUserOrderByTimelineOrderAsc` / `findByUserOrderByIdAsc` / `findMaxTimelineOrderByUser` (`@Query` for max order) +- `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) - `DescriptionOptionRepository.findByUser` ## Gotchas diff --git a/docs/migrations/2026-11-09_multi_aircraft.sql b/docs/migrations/2026-11-09_multi_aircraft.sql new file mode 100644 index 0000000..a84616b --- /dev/null +++ b/docs/migrations/2026-11-09_multi_aircraft.sql @@ -0,0 +1,93 @@ +-- Multiple aircraft per account (specs/003-multi-aircraft-fleet). +-- +-- Hibernate ddl-auto=update creates the new `aircraft` table and adds the +-- nullable aircraft_id / last_viewed_aircraft_id columns on boot. It never +-- DROPS anything, so the old one-subscription-per-user unique constraint +-- would stay and block a second aircraft's subscription. AircraftBackfill +-- (config/AircraftBackfill.java) drops it and attaches existing data on every +-- boot, idempotently. This file is the explicit record and covers any DB +-- where ddl-auto is off. PostgreSQL syntax. + +-- 1. New table (what Hibernate generates from entity/Aircraft.java). +CREATE TABLE IF NOT EXISTS aircraft ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL REFERENCES users(id), + tail_number VARCHAR(255), + tail_number_key VARCHAR(255), + make_model VARCHAR(255), + owner_name VARCHAR(255), + make_modelsn VARCHAR(255), + block_time_hours DOUBLE PRECISION, + time_in_service_hours DOUBLE PRECISION, + block_time_manual_baseline DOUBLE PRECISION, + time_in_service_manual_baseline DOUBLE PRECISION, + block_time_updated_at TIMESTAMP WITH TIME ZONE, + time_in_service_updated_at TIMESTAMP WITH TIME ZONE, + block_time_updated_source VARCHAR(255), + time_in_service_updated_source VARCHAR(255), + created_at TIMESTAMP WITH TIME ZONE, + CONSTRAINT uq_aircraft_user_tail UNIQUE (user_id, tail_number_key) +); + +-- 2. New columns. +ALTER TABLE service_timelines ADD COLUMN IF NOT EXISTS aircraft_id BIGINT REFERENCES aircraft(id); +ALTER TABLE flight_logs ADD COLUMN IF NOT EXISTS aircraft_id BIGINT REFERENCES aircraft(id); +ALTER TABLE flight_suggestions ADD COLUMN IF NOT EXISTS aircraft_id BIGINT REFERENCES aircraft(id); +ALTER TABLE subscriptions ADD COLUMN IF NOT EXISTS aircraft_id BIGINT REFERENCES aircraft(id); +ALTER TABLE import_proposals ADD COLUMN IF NOT EXISTS aircraft_id BIGINT REFERENCES aircraft(id); +ALTER TABLE users ADD COLUMN IF NOT EXISTS last_viewed_aircraft_id BIGINT REFERENCES aircraft(id); + +-- 3. One subscription per AIRCRAFT, no longer per user (non-additive). +ALTER TABLE subscriptions DROP CONSTRAINT IF EXISTS uq_subscriptions_user; +-- Hibernate's own name for the old @JoinColumn(unique = true) varies; find it with: +-- SELECT conname FROM pg_constraint WHERE conrelid = 'subscriptions'::regclass AND contype = 'u'; +-- and drop any that cover only user_id. +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'uq_subscriptions_aircraft') THEN + ALTER TABLE subscriptions ADD CONSTRAINT uq_subscriptions_aircraft UNIQUE (aircraft_id); + END IF; +END $$; + +-- 4. Backfill: each existing user's data becomes its first aircraft. +-- The legacy users columns are kept (unmapped) for one release so a code +-- rollback still finds them. +INSERT INTO aircraft (user_id, tail_number, tail_number_key, make_model, owner_name, make_modelsn, + block_time_hours, time_in_service_hours, + block_time_manual_baseline, time_in_service_manual_baseline, + block_time_updated_at, time_in_service_updated_at, + block_time_updated_source, time_in_service_updated_source, created_at) +SELECT u.id, UPPER(TRIM(u.tail_number)), + NULLIF(UPPER(REGEXP_REPLACE(COALESCE(u.tail_number, ''), '\s', '', 'g')), ''), + u.make_model, u.owner_name, u.make_modelsn, + COALESCE(u.block_time_hours, 0), COALESCE(u.time_in_service_hours, 0), + u.block_time_manual_baseline, u.time_in_service_manual_baseline, + u.block_time_updated_at, u.time_in_service_updated_at, + u.block_time_updated_source, u.time_in_service_updated_source, NOW() +FROM users u +WHERE NOT EXISTS (SELECT 1 FROM aircraft a WHERE a.user_id = u.id); + +UPDATE service_timelines t SET aircraft_id = (SELECT MIN(a.id) FROM aircraft a WHERE a.user_id = t.user_id) WHERE t.aircraft_id IS NULL; +UPDATE flight_logs f SET aircraft_id = (SELECT MIN(a.id) FROM aircraft a WHERE a.user_id = f.user_id) WHERE f.aircraft_id IS NULL; +UPDATE flight_suggestions s SET aircraft_id = (SELECT MIN(a.id) FROM aircraft a WHERE a.user_id = s.user_id) WHERE s.aircraft_id IS NULL; +UPDATE subscriptions s SET aircraft_id = (SELECT MIN(a.id) FROM aircraft a WHERE a.user_id = s.user_id) WHERE s.aircraft_id IS NULL; +UPDATE import_proposals p SET aircraft_id = (SELECT MIN(a.id) FROM aircraft a WHERE a.user_id = p.user_id) WHERE p.aircraft_id IS NULL; +UPDATE users u SET last_viewed_aircraft_id = (SELECT MIN(a.id) FROM aircraft a WHERE a.user_id = u.id) + WHERE u.last_viewed_aircraft_id IS NULL; + +-- 5. FOLLOW-UP (next release, NOT run now). Only after production's boot log +-- shows the backfill attached everything and SELECT COUNT(*) ... WHERE +-- aircraft_id IS NULL is 0 for each table: +-- +-- ALTER TABLE service_timelines ALTER COLUMN aircraft_id SET NOT NULL; +-- ALTER TABLE flight_logs ALTER COLUMN aircraft_id SET NOT NULL; +-- ALTER TABLE flight_suggestions ALTER COLUMN aircraft_id SET NOT NULL; +-- ALTER TABLE subscriptions ALTER COLUMN aircraft_id SET NOT NULL; +-- ALTER TABLE users DROP COLUMN block_time_hours, DROP COLUMN time_in_service_hours, +-- DROP COLUMN make_model, DROP COLUMN tail_number, DROP COLUMN owner_name, DROP COLUMN make_modelsn, +-- DROP COLUMN block_time_updated_at, DROP COLUMN time_in_service_updated_at, +-- DROP COLUMN block_time_updated_source, DROP COLUMN time_in_service_updated_source, +-- DROP COLUMN block_time_manual_baseline, DROP COLUMN time_in_service_manual_baseline; +-- +-- (import_proposals.aircraft_id stays nullable: proposals outlive removed aircraft.) +-- After dropping the users columns, AircraftBackfill can be deleted. diff --git a/src/browserTest/java/com/example/AviaryService/browser/BrowserTestBase.java b/src/browserTest/java/com/example/AviaryService/browser/BrowserTestBase.java index f202a57..2152501 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/BrowserTestBase.java +++ b/src/browserTest/java/com/example/AviaryService/browser/BrowserTestBase.java @@ -1,7 +1,9 @@ package com.example.AviaryService.browser; +import com.example.AviaryService.entity.Aircraft; import com.example.AviaryService.entity.ServiceTimeline; import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.AircraftRepository; import com.example.AviaryService.repositories.UserRepository; import com.microsoft.playwright.Browser; import com.microsoft.playwright.BrowserContext; @@ -42,6 +44,9 @@ public abstract class BrowserTestBase { @Autowired protected PasswordEncoder passwordEncoder; + @Autowired + protected AircraftRepository aircraftRepository; + private static final AtomicInteger USER_COUNTER = new AtomicInteger(); @BeforeAll @@ -79,9 +84,22 @@ protected String seedUser(String rawPassword) { user.setUsername(username); user.setPassword(passwordEncoder.encode(rawPassword)); userRepository.save(user); + // Every account has an aircraft; seeded rows attach to it via aircraftOf(). + Aircraft aircraft = aircraftRepository.save(new Aircraft(user)); + user.setLastViewedAircraft(aircraft); + userRepository.save(user); return username; } + /** The user's first (in these tests, only) aircraft. */ + protected Aircraft aircraftOf(User user) { + return aircraftRepository.findFirstByUserOrderByIdAsc(user).orElseThrow(); + } + + protected Aircraft aircraftOf(String username) { + return aircraftOf(userRepository.findByUsername(username)); + } + /** * Last Done / Due Date are stored as separate date and hours columns. * These take the combined "2025-10-01 100.5" form the tests were written diff --git a/src/browserTest/java/com/example/AviaryService/browser/DashboardLayoutTest.java b/src/browserTest/java/com/example/AviaryService/browser/DashboardLayoutTest.java index 04c464f..517629f 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/DashboardLayoutTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/DashboardLayoutTest.java @@ -45,6 +45,7 @@ private void seedThreeRows(User user) { for (int i = 1; i <= 3; i++) { ServiceTimeline t = new ServiceTimeline(); t.setUser(user); + t.setAircraft(aircraftOf(user)); t.setItem("Row " + i); t.setIsTitle(false); t.setTimelineOrder(i); @@ -104,6 +105,7 @@ void shortItemTextareaStartsAtAboutOneLineHeight() { User u = users.findByUsername(username); ServiceTimeline t = new ServiceTimeline(); t.setUser(u); + t.setAircraft(aircraftOf(u)); t.setItem("Oil"); // single short token — should fit one line t.setIsTitle(false); t.setTimelineOrder(1); @@ -186,6 +188,7 @@ void dateInputsStayInsideTheirCellsWhenWindowIsNarrow() { ServiceTimeline t = new ServiceTimeline(); t.setUser(u); + t.setAircraft(aircraftOf(u)); t.setItem("Magneto"); t.setIsTitle(false); t.setTimelineOrder(1); @@ -316,6 +319,7 @@ void timeLeftColumnIsSizedToContentNotAFatFixedWidth() { // "9600 days overdue" — the widest realistic Time Left content. ServiceTimeline t = new ServiceTimeline(); t.setUser(u); + t.setAircraft(aircraftOf(u)); t.setItem("Engine"); t.setIsTitle(false); t.setTimelineOrder(1); @@ -374,6 +378,7 @@ void calendarAlwaysStacksAboveHoursRegardlessOfAddOrder() { // the chevron — and we drive the +/- menu ourselves. ServiceTimeline t = new ServiceTimeline(); t.setUser(u); + t.setAircraft(aircraftOf(u)); t.setItem("Battery"); t.setIsTitle(false); t.setTimelineOrder(1); diff --git a/src/browserTest/java/com/example/AviaryService/browser/DashboardMobileCardsTest.java b/src/browserTest/java/com/example/AviaryService/browser/DashboardMobileCardsTest.java index a9424a8..8d8f14e 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/DashboardMobileCardsTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/DashboardMobileCardsTest.java @@ -52,6 +52,7 @@ class DashboardMobileCardsTest extends BrowserTestBase { private void seedData(User user) { ServiceTimeline title = new ServiceTimeline(); title.setUser(user); + title.setAircraft(aircraftOf(user)); title.setItem("ENGINE"); title.setIsTitle(true); title.setTimelineOrder(0); @@ -59,6 +60,7 @@ private void seedData(User user) { ServiceTimeline item = new ServiceTimeline(); item.setUser(user); + item.setAircraft(aircraftOf(user)); item.setItem("Annual Inspection"); item.setIsTitle(false); item.setTimelineOrder(1); @@ -73,6 +75,7 @@ private void seedData(User user) { FlightLog log = new FlightLog(); log.setUser(user); + log.setAircraft(aircraftOf(user)); log.setFromAirport("KSQL"); log.setToAirport("KPAO"); log.setBlockTimeOut(1234.5); diff --git a/src/browserTest/java/com/example/AviaryService/browser/FleetPickerTest.java b/src/browserTest/java/com/example/AviaryService/browser/FleetPickerTest.java new file mode 100644 index 0000000..022a5e1 --- /dev/null +++ b/src/browserTest/java/com/example/AviaryService/browser/FleetPickerTest.java @@ -0,0 +1,179 @@ +package com.example.AviaryService.browser; + +import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import com.example.AviaryService.entity.Aircraft; +import com.example.AviaryService.entity.ServiceTimeline; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.ServiceTimelineRepository; +import com.microsoft.playwright.Page; +import com.microsoft.playwright.options.LoadState; + +/** + * US3 / US4: switching aircraft, the remembered choice, per-aircraft tables, + * due counts in the picker, and the two-tab rule (an action lands on the + * aircraft on screen, not whichever was picked last). + */ +class FleetPickerTest extends BrowserTestBase { + + @Autowired ServiceTimelineRepository timelines; + + private Aircraft a; + private Aircraft b; + private String username; + + private void seedFleet() { + username = seedUser("password"); + User u = userRepository.findByUsername(username); + a = aircraftOf(u); + a.setTailNumber("N1AA"); + a.setMakeModel("Cessna 172"); + a = aircraftRepository.save(a); + b = new Aircraft(u); + b.setTailNumber("N2BB"); + b.setMakeModel("Piper PA-28"); + b = aircraftRepository.save(b); + row(u, a, "Alpha Annual", 0, "2099-01-01"); + row(u, a, "Alpha Oil", 1, "2099-01-01"); + row(u, b, "Bravo ELT", 0, "2020-01-01"); // overdue + } + + private void row(User u, Aircraft on, String item, int order, String due) { + ServiceTimeline t = new ServiceTimeline(); + t.setUser(u); + t.setAircraft(on); + t.setItem(item); + t.setIsTitle(false); + t.setTimelineOrder(order); + t.setDueDateDate(due); + timelines.save(t); + } + + private List visibleItems(Page p) { + @SuppressWarnings("unchecked") + List values = (List) p.locator("tr.auto-save-row td[data-label='Item'] textarea") + .evaluateAll("els => els.map(e => e.value)"); + return values; + } + + @Test + void switchShowsThatAircraftAndIsRemembered() { + seedFleet(); + loginAs(username, "password"); + page.waitForLoadState(LoadState.NETWORKIDLE); + assertThat(page.locator(".aircraft-picker-name")).hasText("N1AA"); + assertEquals(List.of("Alpha Annual", "Alpha Oil"), visibleItems(page)); + + page.locator("#aircraft-picker-btn").click(); + assertThat(page.locator(".aircraft-option")).hasCount(2); + assertThat(page.locator(".aircraft-option[aria-current='true'] .aircraft-option-name")).hasText("N1AA"); + assertThat(page.locator(".aircraft-option").nth(1)).containsText("Piper PA-28"); + + page.locator(".aircraft-option").nth(1).click(); + page.waitForURL(baseUrl() + "/dashboard?aircraft=" + b.getId()); + assertThat(page.locator(".aircraft-picker-name")).hasText("N2BB"); + assertEquals(List.of("Bravo ELT"), visibleItems(page)); + + page.reload(); + assertThat(page.locator(".aircraft-picker-name")).hasText("N2BB"); + + // A fresh login lands on the last aircraft viewed. + context.clearCookies(); + loginAs(username, "password"); + assertThat(page.locator(".aircraft-picker-name")).hasText("N2BB"); + } + + @Test + void pickerShowsDueCountsAndFlagsOtherAircraft() { + seedFleet(); + loginAs(username, "password"); + // Viewing A while B has an overdue item: the button shows a dot. + assertThat(page.locator("#aircraft-picker-btn .aircraft-overdue-dot")).isVisible(); + page.locator("#aircraft-picker-btn").click(); + // Nothing due: no chip at all. + assertThat(page.locator(".aircraft-option").nth(0).locator(".chip")).hasCount(0); + assertThat(page.locator(".aircraft-option").nth(1).locator(".chip-overdue")).hasText("1 overdue"); + } + + @Test + void actionInAnOlderTabLandsOnThatTabsAircraft() { + seedFleet(); + loginAs(username, "password"); // tab 1 shows A + Page tab2 = context.newPage(); + tab2.navigate(baseUrl() + "/dashboard?aircraft=" + b.getId()); // now B is "last viewed" + tab2.waitForLoadState(LoadState.NETWORKIDLE); + + Object status = page.evaluate("async () => {" + + " const t = document.querySelector('meta[name=\"_csrf\"]').content;" + + " const h = document.querySelector('meta[name=\"_csrf_header\"]').content;" + + " const r = await axios.post('/dashboard', { item: 'Tab one row', ajax: 'true' }, { headers: { [h]: t } });" + + " 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"))); + } + + // The plane button must never sit under Share / Import with AI / Logout, + // and the info card fields stay in one column. + @Test + void headerButtonsNeverOverlapThePlaneButton() { + seedFleet(); + a.setTailNumber("N1234567AB"); + aircraftRepository.save(a); + loginAs(username, "password"); + for (int width : new int[] {375, 480, 640, 760, 900, 1280}) { + page.setViewportSize(width, 800); + page.waitForTimeout(100); + var plane = page.locator("#aircraft-picker-btn").boundingBox(); + var right = page.locator(".fixed-header .header-right").boundingBox(); + assertTrue(plane.x + plane.width <= right.x + 0.5, + "plane button overlaps the header buttons at " + width + "px"); + assertTrue(plane.width >= 44, "plane button squeezed below 44px at " + width + "px"); + Object scroll = page.evaluate("() => document.documentElement.scrollWidth > window.innerWidth"); + assertEquals(Boolean.FALSE, scroll, "sideways scroll at " + width + "px"); + } + page.setViewportSize(1280, 800); + @SuppressWarnings("unchecked") + List lefts = (List) page.locator(".aircraft-info-table input.user-info-input") + .evaluateAll("els => els.map(e => Math.round(e.getBoundingClientRect().left))"); + assertEquals(1, lefts.stream().distinct().count(), "info card fields not aligned: " + lefts); + } + + @Test + void singleAircraftDashboardIsUnchangedApartFromAdd() { + username = seedUser("password"); + loginAs(username, "password"); + page.waitForLoadState(LoadState.NETWORKIDLE); + assertThat(page.locator(".aircraft-picker-name")).hasText("Unnamed aircraft"); + assertThat(page.locator("#remove-aircraft-btn")).hasCount(0); // no "Remove aircraft" + page.locator("#aircraft-picker-btn").click(); + assertThat(page.locator(".aircraft-option")).hasCount(1); + assertThat(page.locator("#add-aircraft-btn")).isEnabled(); + } + + @Test + void removeAircraftNeedsTheTailNumber() { + seedFleet(); + loginAs(username, "password"); + page.navigate(baseUrl() + "/dashboard?aircraft=" + b.getId()); + page.locator("#aircraft-picker-btn").click(); + assertThat(page.locator("#remove-aircraft-btn")).hasText("Remove N2BB…"); + page.locator("#remove-aircraft-btn").click(); + assertThat(page.locator("#remove-aircraft-dialog")).isVisible(); + assertThat(page.locator("#remove-aircraft-ok")).isDisabled(); + page.locator("#remove-aircraft-confirm").fill("n2 bb"); + assertThat(page.locator("#remove-aircraft-ok")).isEnabled(); + page.locator("#remove-aircraft-ok").click(); + page.waitForURL(baseUrl() + "/dashboard?aircraft=" + a.getId()); + assertTrue(aircraftRepository.findById(b.getId()).isEmpty()); + assertEquals(List.of("Alpha Annual", "Alpha Oil"), visibleItems(page)); + } +} diff --git a/src/browserTest/java/com/example/AviaryService/browser/FlightLogTableEdgeCasesTest.java b/src/browserTest/java/com/example/AviaryService/browser/FlightLogTableEdgeCasesTest.java index b1256d1..827b9c4 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/FlightLogTableEdgeCasesTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/FlightLogTableEdgeCasesTest.java @@ -47,6 +47,7 @@ private FlightLog saveLog(User user, String from, String to, Double timeInServiceOut, Double timeInServiceIn) { FlightLog log = new FlightLog(); log.setUser(user); + log.setAircraft(aircraftOf(user)); log.setFromAirport(from); log.setToAirport(to); log.setBlockTimeOut(blockTimeOut); diff --git a/src/browserTest/java/com/example/AviaryService/browser/HoursTableEdgeCasesTest.java b/src/browserTest/java/com/example/AviaryService/browser/HoursTableEdgeCasesTest.java index 35484f2..17a83f2 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/HoursTableEdgeCasesTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/HoursTableEdgeCasesTest.java @@ -1,5 +1,6 @@ package com.example.AviaryService.browser; +import com.example.AviaryService.entity.Aircraft; import com.example.AviaryService.entity.User; import com.example.AviaryService.repositories.UserRepository; import com.microsoft.playwright.options.LoadState; @@ -67,10 +68,10 @@ void freshUserShowsZeroHoursAndEmptyAircraftInfo() { @Test void decimalHoursRenderWithoutTruncation() { String username = seedUser("password"); - User u = users.findByUsername(username); + Aircraft u = aircraftOf(username); u.setBlockTimeHours(1234.5); u.setTimeInServiceHours(987.6); - users.save(u); + aircraftRepository.save(u); List errors = attachConsoleErrorListener(); loginAs(username, "password"); @@ -91,10 +92,10 @@ void decimalHoursRenderWithoutTruncation() { @Test void veryLargeHoursValueRenders() { String username = seedUser("password"); - User u = users.findByUsername(username); + Aircraft u = aircraftOf(username); u.setBlockTimeHours(99999.9); u.setTimeInServiceHours(99999.9); - users.save(u); + aircraftRepository.save(u); List errors = attachConsoleErrorListener(); loginAs(username, "password"); @@ -109,12 +110,12 @@ void veryLargeHoursValueRenders() { @Test void aircraftInfoFieldsPopulateInputs() { String username = seedUser("password"); - User u = users.findByUsername(username); + Aircraft u = aircraftOf(username); u.setMakeModel("Cessna 172"); u.setTailNumber("N12345"); u.setOwnerName("Daniel I."); u.setMakeModelSN("17280342"); - users.save(u); + aircraftRepository.save(u); List errors = attachConsoleErrorListener(); loginAs(username, "password"); @@ -134,10 +135,10 @@ void specialCharsInAircraftInfoDoNotBreakRendering() { // If the template forgot th:value escaping somewhere, "