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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.

Expand Down
34 changes: 23 additions & 11 deletions docs/architecture/DATABASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
93 changes: 93 additions & 0 deletions docs/migrations/2026-11-09_multi_aircraft.sql
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading