15 Commits
Author SHA1 Message Date
rickyandClaude Opus 5.5 6697e835c8 Fix nav/com and navigation database template citations
- "Swapping a tray-mounted nav/com unit" cited Part 43 Appendix A
  (c)(32), which doesn't exist; the item is (c)(31). Its wording now
  names that paragraph's conditions (self-contained, panel-mounted,
  tray-mounted, manufacturer's instructions, operational check before
  use).
- "Updating the navigation database" called itself preventive
  maintenance under (c)(31). 14 CFR 43.3(k) says such an update isn't
  maintenance: it's now an Other entry citing 43.3(k), with no
  certificate type.
- Built-in templates now take their entry type from the YAML (it was
  always Maintenance).
- A migration fixes copies already in the database where an admin
  hasn't changed the text; edited ones are left alone.
- Test: every built-in template is valid and cites an existing
  Appendix A paragraph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:28:23 -05:00
rickyandClaude Opus 5.5 acb8b87ca3 Avionics logbook type
Aircraft with a separate avionics logbook can file radio, transponder and
autopilot work under it: AVIONICS joins Aircraft, Engine, Propeller and
Other everywhere a logbook is chosen or filtered (entry form, logbook
filter, squawk resolution, templates, imports).

- Logbook transcription knows it (schema enum and prompt), so scanned
  avionics pages aren't filed as Aircraft.
- The API's ?log= filter and drafts API accept it; docs updated.
- No migration: log_type is a string column. Existing entries unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:28:23 -05:00
rickyandClaude Opus 5.5 a5ca534fd1 2026.11.7: flight correction, configurable roles, invitations, read-only records viewer
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:09:41 -05:00
rickyandClaude Opus 5.5 d956cfbe83 Records package viewer: read-only, no account needed
SAM_VIEWER=true (set only by the records package's
viewer/docker-compose.yml) makes the app a read-only copy of an archive,
for whoever receives the records: `docker compose up`, then open
http://localhost:3000.

- At start (bin/docker-entrypoint → sam:viewer:prepare) the package's
  .sam.zip, mounted read-only, is imported once.
- No sign-in: everyone browses as a built-in account. Nothing can be
  changed: any request but GET/HEAD is refused, no role permission
  applies (so no edit buttons), and there's no sign-out or profile. A
  banner names the archive and when it was exported.
- It refuses to start, and every page answers 503, when the database
  has any other account, so turning it on for a real installation stops
  the app instead of exposing its records.
- The viewer listens on 127.0.0.1 only, and skips scheduled jobs
  (reminders, backups, AD searches).
- Docs: the package README (three steps now), Access & sharing, README
  settings and features, the suggested recordkeeping procedures.

Checked end to end with a built image and a real records package: the
archive imported at start, pages browsed without an account, a change
refused, and the container refusing to start once an account existed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:03:56 -05:00
rickyandClaude Opus 5.5 34e3232350 Records package viewer: setup code, release image
The viewer/docker-compose.yml in the records package (and the package's
README) said to just create an account, but first-run setup asks for a
one-time code from the log since 2026.11.5; both now say how to get it,
and the right menu for importing. The viewer runs the published image at
the release that made the package (each release is published under its
version), so whoever opens it later gets that version, not whatever
:latest is then. APP_IMAGE, for a fork, is used as it is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:40:01 -05:00
rickyandClaude Opus 5.5 3ad6b9493a Compose files and .env.example catch up
- The compose files' steps say where the first-run setup code is (it's
  asked for since 2026.11.5), that new accounts come from the admin, and
  who adds aircraft; the published image's release tags are mentioned.
- docker-compose.yml passes APP_REVISION/APP_BUILT_AT to the build when
  set, so a locally built image shows its build on Admin → About.
- .env.example lists the optional push notification keys, APP_LOCALE and
  APP_IMAGE, which the README documented but it didn't.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:35:45 -05:00
rickyandClaude Opus 5.5 9adbc3d0a8 Docs: maintenance pages follow roles, adding aircraft
The guide pages written before roles said "owners" for work Mechanics
now do too (logbook entries, corrections, asking someone to sign,
components, resolving squawks, reminders), and the Fleet page didn't say
who can add aircraft. The index lists roles, invitations and the new
setting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:30:29 -05:00
rickyandClaude Opus 5.5 c360edfce0 One way to add people on an aircraft
Since invitations from an aircraft's Access page only worked for existing
accounts, they did almost what "Add by email" does. The Access page keeps
adding people by email; new people come through the administrator (Admin
→ Users or Admin → Invitations), and outside mechanics through an Owner's
signing invitation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:18:19 -05:00
rickyandClaude Opus 5.5 9a20c91f5e Owners can invite mechanics again; who adds aircraft is an admin setting
- Admin → Settings → Who can add aircraft: administrators only (the
  default) or everyone. Adding an aircraft or importing a .sam.zip makes
  you its Owner, so this decides who can become one.
- A signing invitation from an Owner of the aircraft (or an
  administrator) lets the outside mechanic create an account for the
  invited address again, with a password or by signing in with SSO;
  checked when it's used. Others' signing invitations still need an
  existing account, and say so.
- Docs: who makes accounts, the new setting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:09:49 -05:00
rickyandClaude Opus 5.5 19bc3efa19 New accounts only from an administrator or an administrator's invitation
Anyone can add an aircraft and so manage its people, so invitations from
non-administrators could bring in new accounts without an administrator.

- An invitation makes a new account only if whoever made it is still an
  administrator when it's used; an aircraft's Access page invitations are
  for people who already have an account (its welcome page says so).
- Signing invitations no longer make accounts: the mechanic needs one
  first, and the owner is told when they don't have one.
- With SSO, "Continue with <provider>" on an administrator's invitation
  makes the account and accepts the invitation (only for its address when
  it has one), so invitations work without OIDC_AUTO_CREATE_USERS. That
  setting stays, documented as giving accounts without an invitation; the
  Authentik example now leaves it off.
- Docs: who makes accounts (guide, README, Authentik, .env.example, API).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:00:45 -05:00
rickyandClaude Opus 5.5 b4c7aaa3ff Invitation codes: a link that gives an account and roles
Ported from the original (InvitationCode), adapted to configurable roles.

- Admin → Invitations: a label, optionally one email address (only it can
  use the link, and it's emailed) and a name, how many uses (or
  unlimited), an expiry (or never), and a role on any aircraft (or none,
  for an account only).
- An aircraft's Access page: whoever manages its people invites to that
  aircraft, with only the roles they can give; they see and revoke its
  invitations.
- /join/<code>: shows what it gives; create an account (when password
  sign-in is on) or sign in, then accept. Existing accounts and SSO users
  accept too. A role someone already has on an aircraft stays.
- Roles are given as the invitation's creator (AircraftAccess), and only
  while they can still manage that aircraft's people. Codes are kept as
  digests and shown once; uses are counted under a lock; account creation
  and accepting are rate-limited; any invalid link gets the same answer.
- Docs: guide (Administration, Access & sharing), README, and why /join
  isn't on the Authentik bypass list. The README's not-yet-ported list
  now names Prometheus metrics, and no longer claims oil analysis import
  as new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 18:50:58 -05:00
rickyandClaude Opus 5.5 a645778f26 Docs catch up with today's changes
- User guide: the connection status (red top bar, the ring), a weak
  signal counting as none for flights and squawks, the offline page for
  any other page, PDFs on phones, the activity log loading as you scroll,
  What's new on About, Aircraft access on Admin → Users, and grounding
  squawks notifying everyone on the aircraft.
- README: the configurable roles table, feature rows for phones and
  offline and the REST API, and rows that said "Owners can…".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 18:32:42 -05:00
rickyandClaude Opus 5.5 3e5d896662 Locked flight readings look locked
The tach and Hobbs fields of an earlier flight were disabled but looked
like any other field. Disabled fields now look it everywhere (grey,
muted text, a not-allowed cursor), and the flight form marks its locked
readings "Locked".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 17:58:47 -05:00
rickyandClaude Opus 5.5 d8cd462194 Configurable roles: Owner, Mechanic, Pilot, Viewer and custom roles
What people can do on an aircraft now comes from their role there, and
administrators set what each role allows (Admin → Roles).

- Roles are installation-wide sets of permissions (31, grouped as flying,
  squawks and notes, maintenance records, imports and exports, the
  aircraft, notifications). Seeing an aircraft's records needs none.
- Built in: Owner (always every permission, so an aircraft can always be
  managed), Mechanic (shop maintenance: logbook, signing, components,
  inspections, ADs, squawks, reminders), Pilot (what pilots could do
  before) and Viewer (view only). Administrators can change all but
  Owner's, and add their own; a role can be deleted once nobody has it.
- Existing owners and pilots keep exactly what they could do.
- Admin → Users → a user lists their role on every aircraft, to change,
  remove or add. On the aircraft's Access page, anyone who manages people
  hands out roles, but only an Owner can give or take away Owner, nobody
  changes their own (except administrators), and an aircraft always
  keeps an Owner (AircraftAccess).
- Controllers declare the permission each action needs; a request that
  changes something with none declared is refused (and raises in
  development and tests), and a test walks every route to check.
- Weekly reminders and overdue alerts go to roles that get reminders;
  the DRS reminder also needs Manage ADs. The API follows the person's
  role; its owners_only error is now not_permitted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 17:43:38 -05:00
rickyandClaude Opus 5.5 d2cd60c6a7 Flights can be corrected after they're saved
- Edit on a flight: owners can correct any flight; a pilot, the flights
  they logged (the same rule as its engine data).
- Date, airports, route, notes, oil and fuel (its oil and fuel records
  follow) and the attached files can always be changed.
- The meter readings only on the latest flight, while its tach in is
  still the aircraft's tach: the aircraft and installed components move
  by the difference, and with both readings the duration is worked out
  from them. On earlier flights they're locked (later flights started
  from them), pointing to Update Hours; the server ignores them too.
- Each correction is in the activity log with what changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 17:12:05 -05:00
177 changed files with 2748 additions and 386 deletions

No files matched your search

+9 -1
View File
@@ -46,7 +46,7 @@ FORCE_SSL=true
# OIDC_CLIENT_ID=
# OIDC_CLIENT_SECRET=
# OIDC_PROVIDER_NAME=Authentik
# OIDC_AUTO_CREATE_USERS=false # true: create an account at first sign-in
# OIDC_AUTO_CREATE_USERS=false # true: an account at first sign-in for anyone the provider lets in, without an invitation
# OIDC_TRUST_EMAIL=false # true: link accounts by unverified email
# OIDC_ADMIN_GROUP= # members become admins (synced at sign-in)
@@ -64,6 +64,14 @@ FORCE_SSL=true
# LOGBOOK_AI_MODEL=claude-opus-5-5
# LOGBOOK_AI_EFFORT=high
# --- Push notifications --------------------------------------------------
# Optional: without them the app makes a pair once and keeps it in storage/vapid_keys.json.
# Changing the pair turns notifications off on every device until turned on again.
# VAPID_PUBLIC_KEY=
# VAPID_PRIVATE_KEY= # bin/rails runner 'k = WebPush.generate_key; puts k.public_key, k.private_key'
# --- Other ---------------------------------------------------------------
# APP_LOCALE=en # language, e.g. es for config/locales/es.yml
# APP_REPOSITORY_URL= # source link on Admin → About (for a fork)
# APP_IMAGE= # image for the records package's viewer, used as is (for a fork); default: the published one at this release
# RAILS_LOG_LEVEL=info
+25
View File
@@ -2,6 +2,31 @@
Each release has a **version** (year.month.release, e.g. 2026.11.0) and a **build** (the exact source commit, shown on Admin → About). The newest release is first.
## 2026.11.7
### Changes
- **Correct a flight.** Open it and choose **Edit**: the date, airports, route, notes, oil and fuel (its oil and fuel records follow) and its files can always be fixed. The meter readings only on the latest flight, while nothing else has changed the hours; the aircraft and its components then move by the difference. On earlier flights the readings are shown locked. Owners can correct any flight; pilots, the ones they logged.
- **Roles you can set up.** Each person has a role on each aircraft: **Owner**, **Mechanic** (maintenance records, signing, components, inspections, ADs, squawks, reminders), **Pilot** (as before) or **Viewer** (sees everything, changes nothing). Owners and pilots keep exactly what they could do. Buttons for what your role doesn't allow aren't shown.
- **Reminders and overdue alerts** go to the roles that get them: Owners and Mechanics, as roles come.
- **Records package viewer, with no account.** The package's `viewer/docker-compose.yml` now runs a read-only copy on the recipient's computer: `docker compose up`, open http://localhost:3000, and the records are there (imported by itself, nothing can be changed, reachable only from that computer). It runs the release that made the package.
### For administrators
- **Admin → Roles**: change what Mechanic, Pilot and Viewer can do (31 permissions, grouped), or add your own roles (a partner, an instructor). Owner always has everything. **Admin → Users → Edit** lists each person's role on every aircraft, to add, change or remove. Only an Owner (or an administrator) can give the Owner role, nobody changes their own, and every aircraft keeps an Owner.
- **Admin → Invitations**: a link that makes an account (or is accepted with one) and gives roles on aircraft; limited uses, an expiry, optionally one email address (and then emailed). With single sign-on, **Continue with** on the invitation makes the account.
- **New accounts come only from an administrator**, an administrator's invitation, or an Owner's signing invitation to an outside mechanic (for that address). Signing invitations from others need an existing account.
- **Who can add aircraft** (Admin → Settings) is **administrators only** by default: adding or importing an aircraft makes you its Owner, who can bring in mechanics. **After this update, other users can't add aircraft** until you choose *Everyone* there.
- `OIDC_AUTO_CREATE_USERS=true` still gives an account to anyone the identity provider lets in, without an invitation; leave it off to keep accounts to administrators and their invitations.
- The REST API follows the person's role; its `owners_only` error is now `not_permitted`.
- The update adds the roles and invitations tables, filled in automatically when the new version starts.
- The compose files and `.env.example` mention the first-run setup code and the push notification, language and image settings.
### Fixes
- Disabled fields look disabled (they looked like any other).
- The records package's viewer said to just create an account (it needs the setup code since 2026.11.5) and named the wrong menu.
## 2026.11.6
### Changes
+29 -22
View File
@@ -88,12 +88,14 @@ The app is a standard Rails app. Run `bin/rails db:prepare && bin/thrust bin/rai
| `APP_URL` | Optional public base URL, e.g. `https://aircraft.example.com` (default `https://APP_HOST`). Used for the SSO and Google Drive redirect URIs. |
| `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` | Optional. Turn on single sign-on with an OpenID Connect provider (see below). |
| `OIDC_PROVIDER_NAME` | Button label, e.g. `Authentik` (default `SSO`). |
| `OIDC_AUTO_CREATE_USERS` | `true` creates an account for anyone the provider lets in. New accounts start with no aircraft. Default off: an admin adds users first. |
| `OIDC_AUTO_CREATE_USERS` | `true` creates an account for anyone the provider lets in, without an invitation. New accounts start with no aircraft. Default off: accounts come only from an admin, an admin's invitation, or an Owner's signing invitation (signing in with SSO from the link makes the account). |
| `OIDC_TRUST_EMAIL` | `true` links existing accounts by email even if the provider doesn't mark it verified. Only use it if users can't edit their own email at the provider. |
| `OIDC_ADMIN_GROUP` | Optional. Members of this provider group become admins and others lose admin, synced at each sign-in. |
| `PWNED_PASSWORDS_CHECK` | `false` turns off the check of new passwords against Have I Been Pwned (only the first 5 characters of the password's SHA-1 are sent). Use it if the server has no outbound internet access; the check also allows the password if the service can't be reached. |
| `PASSWORD_LOGIN` | `false` hides email/password sign-in, emailed sign-in links and password resets once SSO works. It's ignored while SSO isn't configured, so you can't lock yourself out. |
| `APP_REPOSITORY_URL` | Optional. The source code link on Admin → About, for a fork. |
| `APP_IMAGE` | Optional. The image the records package's viewer runs, used as is (for a fork). Default: the published image at the release that made the package. |
| `SAM_VIEWER`, `SAM_VIEWER_ARCHIVE` | **Only for the records package's viewer** (its `viewer/docker-compose.yml` sets them). `SAM_VIEWER=true` makes the app a read-only copy with no sign-in: it imports the `.sam.zip` at `SAM_VIEWER_ARCHIVE` at start, everyone browses as a built-in account, and nothing can be changed. It refuses to start on a database with any user account, so turning it on for a real installation stops the app instead of exposing its records. |
| `APP_REVISION`, `APP_BUILT_AT` | Set as Docker build arguments (see the `Dockerfile`) so Admin → About shows the version and the records keep a software version history. |
### Single sign-on (Authentik example)
@@ -138,9 +140,9 @@ To back up or move a single aircraft with all its files, use **More → Download
| Fleet dashboard | Every aircraft you can access, with airworthiness status and its top issues. |
| Airworthiness | Grounded / limited (e.g. "VFR only" for an overdue 91.411 check) / due soon / current, from AD compliance, grounding squawks, inspections, replacement-critical and expiring parts, and expiring documents (an expired registration grounds). Warnings start 10 hours or 30 days ahead. The pilot in command still decides airworthiness (91.7). Logic: `app/services/airworthiness.rb`, `app/services/compliance.rb`. |
| Hours | Absolute tach/hobbs updates or per-flight logs. Both apply the delta to every in-service component. Downward corrections are clamped at 0. Each aircraft picks tach or Hobbs as its maintenance clock (time in service). |
| Flight import | Owners can import historical flights from `.xlsx` or `.csv` (Date, From, To, Tach, Hobbs, Oil Added, Fuel Added). Each flight's time is derived from the previous row's reading. A preview flags typos such as a tach going backwards, and rows already imported are skipped. History only: component hours aren't changed unless you choose to advance the aircraft's meters. |
| Flight import | Import historical flights from `.xlsx` or `.csv` (Date, From, To, Tach, Hobbs, Oil Added, Fuel Added). Each flight's time is derived from the previous row's reading. A preview flags typos such as a tach going backwards, and rows already imported are skipped. History only: component hours aren't changed unless you choose to advance the aircraft's meters. |
| Airworthiness enforcement | Optional per aircraft. It blocks flight logs and hours updates while the aircraft is grounded (not for limitations). |
| Components | Tree of parent and child parts, TBO and replacement limits, and service/replace reset. Owners can create new component types inline. |
| Components | Tree of parent and child parts, TBO and replacement limits, and service/replace reset. New component types can be created inline. |
| Squawks | Four priorities. "Ground Aircraft" grounds the aircraft. Inoperative items can be deferred under 91.213(d) after confirming each condition; resolving can record the fix as a logbook entry. Attachments, reopen. |
| Notes | Per-aircraft notes in Markdown, with a preview; shown on share links. |
| ADs and bulletins | Shared across aircraft and applicable to the airframe or to specific components. Hour- and month-based recurrence (due at end of month), conditional and non-mandatory types, per-aircraft "not applicable" determinations, and compliance history with method of compliance and the revision complied with. |
@@ -148,35 +150,40 @@ To back up or move a single aircraft with all its files, use **More → Download
| AD import | Import ADs from an FAA DRS export (`.xlsx` recommended: its AD numbers link to each AD's DRS page, which the import keeps; `.csv` works without links). ADs are matched by number, so nothing is duplicated. The preview suggests Track, Not applicable or Skip for each AD, and flags superseded or non-current ADs, model mismatches, appliance or STC-only ADs, and repetitive actions. |
| Inspections | Shared inspection types with hour, month, and day recurrence, plus history. Each says what overdue means (grounded, no IFR, no transponder, advisory); an annual can also count as the 100-hour, and the 100-hour's 10-hour overrun is credited (91.409(b)). One click adds the standard Part 91 set. |
| Logbook | Maintenance entries with search and a link to a scanned document page. Records the signer's certificate kind and number and an inspection's result, and flags what 43.9 / 43.11 needs that's missing. Entries transcribed by Claude stay "unverified" until someone checks them against the scan. Entry templates (built-in pilot preventive maintenance per 43.3(g) and Part 43 Appendix A(c); admins add and edit their own under Admin → Logbook templates). Engine and propeller entries link the component and record its total time and time since overhaul (SMOH/SFOH/SNEW) at the entry, worked out from the entry's airframe total time; sub-components (an oil filter on the engine…) can be included with their own times. Print entries as a PDF on Avery 5163/8163 or 5164/8164 labels or half-letter/letter pages (boxed) to sign and put in the paper logbook. |
| Documents | Collections, multi-file documents with a page viewer, per-document share visibility, bulk upload, and expiration dates (registration, insurance…). Their text is read for search: PDF text layers directly, scans by Tesseract OCR (in the image) or optionally Claude. |
| Documents | Collections, multi-file documents with a page viewer (PDFs drawn page by page with PDF.js on phones, fetching only the pages viewed), per-document share visibility, bulk upload, and expiration dates (registration, insurance…). Their text is read for search: PDF text layers directly, scans by Tesseract OCR (in the image) or optionally Claude. |
| Electronic signatures | Logbook entries can be signed electronically along the lines of AC 120-78B chapter 2: the signer reviews the entry, picks their certificate, re-enters their password (or signs in again with SSO) and confirms a "Certified by" statement. The signature records who, which certificate, the statement, the time and a SHA-256 fingerprint of the entry, sealed by the server; the signer gets an email. Signed entries are locked: a correction is a new signed entry that supersedes the original. Owners can invite an outside mechanic to sign one entry with their own account. Disabled accounts can't sign; their past signatures stay. |
| Records integrity | Every change to maintenance records is kept (who, when, field by field) in a hash chain per aircraft (Activity → Record history). Nightly: a verified SQLite backup in `storage/backups` (how many are kept: Admin → Settings), then a check of the history chains and every signature; admins are emailed on a problem (Admin → About). Software versions are recorded. A records package (Access & Sharing) bundles every entry as a PDF with signatures, a signature register, the history, the status report and the `.sam.zip` for the FAA or a buyer, with a README (and a ready-to-run `viewer/docker-compose.yml`) so the recipient can browse the data in their own local copy of the app. Scans of paper logbooks can be marked as legacy records, with an "electronic records since" date per aircraft. |
| Records integrity | Every change to maintenance records is kept (who, when, field by field) in a hash chain per aircraft (Activity → Record history). Nightly: a verified SQLite backup in `storage/backups` (how many are kept: Admin → Settings), then a check of the history chains and every signature; admins are emailed on a problem (Admin → About). Software versions are recorded. A records package (Access & Sharing) bundles every entry as a PDF with signatures, a signature register, the history, the status report and the `.sam.zip` for the FAA or a buyer, with a README and a ready-to-run `viewer/docker-compose.yml`: `docker compose up` gives the recipient a read-only copy of the app on their own computer, with the archive imported and no sign-in (`SAM_VIEWER`). Scans of paper logbooks can be marked as legacy records, with an "electronic records since" date per aircraft. |
| Off-site backup | Nightly copy of the verified database snapshot (newest 30 kept) and every new uploaded file to Google Drive, using your own Google OAuth client and the `drive.file` scope (the app sees only its own files). Restore test from the admin page; failures emailed to admins; `bin/rails offsite:restore_files` brings files back after a restore. |
| Recordkeeping procedures and audits | Admin → Recordkeeping Procedures generates the procedures document AC 120-78B asks for (who is responsible, who may sign, signing, corrections, backups, access, audits, transfer, legacy records) from the system setup plus a few details you fill in (with suggested text built from the installation's settings; a revision can't be adopted while a [bracketed] blank is left); adopt it as numbered, unchangeable revisions, included in the records package. Admin → Records Audits is a periodic QC checklist (app checks plus a restore test, a sample of entries against source documents and a user review); admins get the due date in the weekly reminder. The users' instructions are the guide's [Electronic records and signing](docs/guide/records.md) page. |
| Major repairs and alterations | Form 337, STC, and ICA tracking; an STC's ICA can become a tracked recurring inspection. |
| Weight & balance | History of empty weight and CG (linked to the alteration that changed them) and a loading calculator: takeoff and landing weight and CG against max gross and the CG envelope. The envelope can be entered as CG (inches) or as moment (lb-in/1000, as in POH moment charts and Garmin Pilot). |
| Status report | A printable maintenance status (91.417(a)(2)): total times, life-limited parts, time since overhaul, inspections, ADs with method and revision, major alterations, open discrepancies. Also on maintenance share links. |
| Calendar feed | A private iCalendar link (Profile) with everything coming due on your aircraft as all-day events; hour-based items get a date projected from the past year's flying. |
| Reminders | A Monday email to owners when something is overdue or coming due, and to anyone whose certificate (e.g. an IA) is about to expire; admins also get the records audit due date (needs SMTP; users can turn it off). |
| Reminders | A Monday email to those whose role gets reminders (Owners and Mechanics by default) when something is overdue or coming due, plus push alerts when something becomes overdue, and to anyone whose certificate (e.g. an IA) is about to expire; admins also get the records audit due date (needs SMTP; users can turn it off). |
| Oil and fuel | Records, trend charts, and averages (last 20 intervals, IQR outlier filtering, manual exclusion). |
| Activity log | Every write is recorded as an `AircraftEvent`. |
| Access | Admin, owner, and pilot roles, plus share links (Current Status or Maintenance Detail, optional expiry, at most 10 per aircraft). Admins can disable accounts; a disabled account can't sign in or sign entries, and its past signatures stay. |
| Activity log | Every write is recorded as an `AircraftEvent`; the Activity tab loads them as you scroll. |
| Access | Configurable roles per aircraft (see [Roles](#roles)), admins' invitation links (limited uses, expiry, optionally one email address) that give an account and roles, plus share links (Current Status or Maintenance Detail, optional expiry, at most 10 per aircraft). Admins can disable accounts; a disabled account can't sign in or sign entries, and its past signatures stay. |
| Sign-in security | Passwords of at least 12 characters, checked against known breaches (Have I Been Pwned, k-anonymity). 10 failed sign-ins in a row lock an account for 15 minutes from any address, and the user is emailed; admins can unlock. Optional authenticator-app (TOTP) codes with recovery codes for password and emailed-link sign-in and for signing entries; admins can reset them. Rate limits per address on every sign-in form. |
| Phones and offline | Installable (PWA). Flights and squawks logged without signal, or with one too weak to answer within 10 seconds, are kept on the device and sent later, never twice. The Fleet, Overview, W&B, Log Flight and Report Squawk pages are saved ahead of time; any other page falls back to an offline page. The top bar turns red when the server can't be reached, and a ring shows saving and sending progress. |
| REST API | Personal and integration tokens with scopes, read endpoints, squawks, draft logbook entries for signing in the app, and signed webhooks ([docs](docs/guide/api.md)). Follows the person's role. |
| Help | The [user guide](docs/guide/README.md), shown in the app under **Help**. |
### Roles
| Action | Admin | Owner | Pilot |
|---|:-:|:-:|:-:|
| View everything on the aircraft | ✓ | ✓ | ✓ |
| Update hours, log flights, add squawks/notes/oil/fuel | ✓ | ✓ | ✓ |
| Defer squawks (91.213(d)) | ✓ | ✓ | ✓ |
| Sign logbook entries with their own certificate | ✓ | ✓ | ✓ |
| Edit or delete squawks and notes, resolve squawks | ✓ | ✓ | |
| Components, logbook, ADs, inspections, documents, major records | ✓ | ✓ | |
| Edit or delete aircraft, manage people and share links | ✓ | ✓ | |
| Create aircraft (creator becomes owner) | ✓ | ✓ | ✓ |
| Users, component types, airports, templates, settings, off-site backup, procedures and audits | ✓ | | |
Each person has a role on each aircraft, and a role is a set of permissions (`app/models/permission.rb`) that administrators change under **Admin → Roles**, where they can also add their own. The built-in roles as they come:
| Action | Viewer | Pilot | Mechanic | Owner |
|---|:-:|:-:|:-:|:-:|
| View everything on the aircraft | ✓ | ✓ | ✓ | ✓ |
| Log flights, correct own flights | | ✓ | | ✓ |
| Update hours, report and defer squawks (91.213(d)), add notes/oil/fuel | | ✓ | ✓ | ✓ |
| Sign logbook entries with their own certificate | | ✓ | ✓ | ✓ |
| Logbook, components, ADs, inspections, documents, major records, W&B; edit squawks, notes, oil/fuel | | | ✓ | ✓ |
| Reminders and overdue alerts | | | ✓ | ✓ |
| Correct or delete any flight, imports, exports, restore from history | | | | ✓ |
| Edit or delete the aircraft, manage people and share links | | | | ✓ |
Owner always has every permission. Only an Owner can give the Owner role, nobody changes their own, and every aircraft keeps an Owner. Administrators can do everything on every aircraft and manage users, roles, component types, airports, templates, settings, off-site backup, procedures and audits. Whoever adds an aircraft becomes its Owner (who can add aircraft is an admin setting: administrators only by default). Controllers declare the permission each action needs (`requires_permission`); a write with none declared is refused.
Users who aren't on an aircraft get a 404 for it, identical to a missing record.
@@ -197,15 +204,15 @@ Users who aren't on an aircraft get a 404 for it, identical to a missing record.
Differences from the original:
- Integer primary keys instead of UUIDs. Share tokens are 32-character random strings.
- Logbook entries and inspection records don't keep many-to-many links to components. An inspection record or AD compliance can reference one component.
- Accounts are created by an admin, by the first-run setup, at first SSO sign-in (if `OIDC_AUTO_CREATE_USERS` is on), or by an outside mechanic accepting a signing invitation. The original's invitation codes aren't implemented yet.
- Accounts are created only by an admin, by the first-run setup, by someone opening an admin's invitation link (with a password, or SSO), by an outside mechanic from an Owner's signing invitation (for its address), or at first SSO sign-in when `OIDC_AUTO_CREATE_USERS` is on. Who can add aircraft, and so become an Owner, is an admin setting (administrators only by default).
### Not yet ported
The MCP server for AI agents, invitation codes, per-aircraft feature switches, the plugin system, and the desktop builds.
The MCP server for AI agents, Prometheus metrics, per-aircraft feature switches (only airworthiness enforcement is here, as an aircraft setting), the plugin system, and the desktop builds.
### Added in this port
AirTrail sync and export, an airport database, FAA DRS AD import, spreadsheet flight import, engine monitor data (CGR-30P/C) with interactive charts, AvLab and Blackstone oil analysis import with trends, multiple squawk attachments with a photo viewer, AI logbook transcription with Claude (images and PDFs), printable logbook entries, electronic signatures and recordkeeping along the lines of AC 120-78B (record history, nightly integrity checks, records package, procedures and audits), off-site backup to Google Drive, a user guide, and an installable app (PWA) that logs flights and squawks offline, keeps pre-flight pages for use without signal, and sends push notifications.
AirTrail sync and export, an airport database, FAA DRS AD import, spreadsheet flight import, engine monitor data (CGR-30P/C) with interactive charts, multiple squawk attachments with a photo viewer, AI logbook transcription with Claude (images and PDFs), printable logbook entries, electronic signatures and recordkeeping along the lines of AC 120-78B (record history, nightly integrity checks, records package, procedures and audits), off-site backup to Google Drive, a user guide, and an installable app (PWA) that logs flights and squawks offline, keeps pre-flight pages for use without signal, and sends push notifications.
## Translating
+1 -1
View File
@@ -1 +1 @@
2026.11.6
2026.11.7
+1 -1
View File
@@ -26,7 +26,7 @@
@utility card-body { @apply p-4; }
@utility label { @apply block text-sm font-medium text-slate-700 mb-1; }
@utility input { @apply block w-full rounded-md border-0 px-2.5 py-1.5 text-sm text-slate-900 shadow-sm ring-1 ring-slate-300 ring-inset placeholder:text-slate-400 focus:ring-2 focus:ring-sky-600 focus:outline-none bg-surface; }
@utility input { @apply block w-full rounded-md border-0 px-2.5 py-1.5 text-sm text-slate-900 shadow-sm ring-1 ring-slate-300 ring-inset placeholder:text-slate-400 focus:ring-2 focus:ring-sky-600 focus:outline-none bg-surface disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-500 disabled:shadow-none disabled:ring-slate-200; }
@utility hint { @apply mt-1 text-xs text-slate-500; }
@utility field-error { @apply mt-1 text-xs text-red-600; }
+1 -1
View File
@@ -2,7 +2,7 @@
# search terms used.
class AdAlertsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :manage_ads
before_action :set_alert, only: %i[track dismiss]
rate_limit to: 5, within: 1.minute, only: :check, with: -> { redirect_to aircraft_airworthiness_directives_path(@aircraft), alert: t("flash.ad_alerts.try_again_in_a") }
+1 -1
View File
@@ -1,6 +1,6 @@
class AdCompliancesController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :manage_ads
before_action :set_compliance, only: %i[edit update destroy]
def new
+1 -1
View File
@@ -2,7 +2,7 @@
class AdImportsController < ApplicationController
include AircraftScoped
include StoredUpload
before_action :require_owner!
requires_permission :manage_ads
def new; end
@@ -0,0 +1,32 @@
# Invitation codes for any aircraft, or none (an account only), by
# administrators (AccessInvitation).
class Admin::InvitationsController < ApplicationController
before_action :require_admin!
def index
@invitations = AccessInvitation.recent_first.includes(:created_by, grants: %i[aircraft role]).limit(200)
end
def new
@invitation = AccessInvitation.new(max_uses: 1, expires_at: AccessInvitation::VALID_FOR.from_now.change(sec: 0))
end
def create
roles = Role.all.index_by(&:id)
grants = Aircraft.where(id: params.fetch(:roles, {}).keys).filter_map do |aircraft|
role = roles[params[:roles][aircraft.id.to_s].to_i]
[ aircraft, role ] if role
end
@invitation = AccessInvitation.create_for(current_user, params.require(:access_invitation).permit(:label, :email, :name, :max_uses, :expires_at), grants)
if @invitation.persisted?
render :created
else
render :new, status: :unprocessable_entity
end
end
def destroy
AccessInvitation.find(params[:id]).update!(revoked_at: Time.current)
redirect_to admin_invitations_path, notice: t("flash.admin_invitations.revoked")
end
end
+57
View File
@@ -0,0 +1,57 @@
# The roles people can have on an aircraft and what each allows (Role,
# Permission). Owner always has every permission; the other built-in roles
# can be changed but not deleted; administrators can add their own.
class Admin::RolesController < ApplicationController
before_action :require_admin!
before_action :set_role, only: %i[edit update destroy]
def index
Role.ensure_built_in!
@roles = Role.ordered
@counts = AircraftRole.group(:role_id).count
end
def new
@role = Role.new(permissions: Permission::DEFAULTS["viewer"])
end
def create
@role = Role.new(role_params)
if @role.save
redirect_to admin_roles_path, notice: t("flash.admin_roles.created", name: @role.name)
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
attributes = @role.owner? ? role_params.except(:permissions) : role_params
if @role.update(attributes)
redirect_to admin_roles_path, notice: t("flash.admin_roles.updated", name: @role.name)
else
render :edit, status: :unprocessable_entity
end
end
def destroy
if @role.built_in?
redirect_to admin_roles_path, alert: t("flash.admin_roles.built_in")
elsif @role.aircraft_roles.exists?
redirect_to admin_roles_path, alert: t("flash.admin_roles.in_use", name: @role.name, count: @role.aircraft_roles.count)
else
@role.destroy!
redirect_to admin_roles_path, notice: t("flash.admin_roles.deleted", name: @role.name)
end
end
private
def set_role = @role = Role.find(params[:id])
# Unticking every box sends none, so an empty list is always sent too.
def role_params
params.require(:role).permit(:name, :description, permissions: []).tap { _1[:permissions] = Array(_1[:permissions]).compact_blank }
end
end
+3 -3
View File
@@ -2,18 +2,18 @@ class Admin::SettingsController < ApplicationController
before_action :require_admin!
def edit
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text].index_with { Setting.integer(_1) }
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text anyone_adds_aircraft].index_with { Setting.integer(_1) }
end
def update
submitted = params.fetch(:settings, {}).permit(:max_upload_mb, :backups_kept, :offsite_backups_kept, :documents_claude_text).to_h
submitted = params.fetch(:settings, {}).permit(:max_upload_mb, :backups_kept, :offsite_backups_kept, :documents_claude_text, :anyone_adds_aircraft).to_h
records = Setting.update_integers(submitted)
@errors = records.flat_map { _1.errors.full_messages }
if @errors.empty?
Rails.logger.info("[settings] #{current_user.email_address} changed #{submitted.inspect}")
redirect_to edit_admin_settings_path, notice: t("flash.admin_settings.settings_saved")
else
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text].index_with { Setting.integer(_1) }.merge(submitted)
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text anyone_adds_aircraft].index_with { Setting.integer(_1) }.merge(submitted)
render :edit, status: :unprocessable_entity
end
end
@@ -0,0 +1,31 @@
# Administrators give people roles on any aircraft (from Admin → Users),
# under the same rules as the aircraft's Access page (AircraftAccess).
class Admin::UserAircraftRolesController < ApplicationController
before_action :require_admin!
before_action :set_user
def create
aircraft = Aircraft.find_by(id: params[:aircraft_id])
return back(alert: t("services.aircraft_access.not_found")) unless aircraft
back_with AircraftAccess.new(aircraft, actor: current_user).add(@user, Role.find_by(id: params[:role_id])),
t("flash.admin_users.access_added", tail_number: aircraft.tail_number)
end
def update
membership = @user.aircraft_roles.find(params[:id])
back_with AircraftAccess.new(membership.aircraft, actor: current_user).change(membership, Role.find_by(id: params[:role_id])),
t("flash.admin_users.access_changed", tail_number: membership.aircraft.tail_number)
end
def destroy
membership = @user.aircraft_roles.find(params[:id])
back_with AircraftAccess.new(membership.aircraft, actor: current_user).remove(membership),
t("flash.admin_users.access_removed", tail_number: membership.aircraft.tail_number)
end
private
def set_user = @user = User.find(params[:user_id])
def back(flash) = redirect_to(edit_admin_user_path(@user, anchor: "access"), flash)
def back_with(error, notice) = back(error ? { alert: error } : { notice: notice })
end
+1 -1
View File
@@ -3,7 +3,7 @@ class Admin::UsersController < ApplicationController
before_action :set_user, only: %i[edit update destroy disable enable unlock reset_two_factor]
def index
@users = User.order(:email_address).includes(:certificates, aircraft_roles: :aircraft)
@users = User.order(:email_address).includes(:certificates, aircraft_roles: %i[aircraft role])
end
def new
@@ -1,6 +1,7 @@
# Download the aircraft's flights as an AirTrail import file.
class AirTrailExportsController < ApplicationController
include AircraftScoped
requires_permission :log_flights
def new
@export = build_export
+5 -2
View File
@@ -1,7 +1,10 @@
class AircraftController < ApplicationController
include AircraftScoped
skip_before_action :set_aircraft, only: %i[index new create]
before_action :require_owner!, only: %i[edit update destroy]
skip_before_action :set_aircraft, :authorize_permission!, only: %i[index new create]
before_action :require_aircraft_adder!, only: %i[new create]
requires_permission :edit_aircraft, only: %i[edit update]
requires_permission :delete_aircraft, only: :destroy
requires_permission :update_hours, only: :update_hours
def index
@aircraft_list = current_user.accessible_aircraft.ordered.with_attached_picture
@@ -1,7 +1,7 @@
# Download an aircraft as a .sam.zip archive (owners and admins).
class AircraftExportsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :export_data
EXPORT_DIR = Rails.root.join("tmp/exports")
@@ -2,6 +2,7 @@
# create an aircraft with all its records. The archive is checked right away;
# the import itself runs in the background (AircraftImportJob).
class AircraftImportsController < ApplicationController
before_action :require_aircraft_adder!, only: %i[new create]
before_action :set_import, only: :show
def new; end
+17 -34
View File
@@ -1,54 +1,37 @@
# Owner-only: manage who can access the aircraft, and its public share links.
# Who can access the aircraft, with which role ("manage people"), and its
# public share links ("manage sharing", see ShareTokensController). The rules
# for changing roles are in AircraftAccess.
class AircraftRolesController < ApplicationController
include AircraftScoped
before_action :require_owner!
checks_permission_itself only: :index
requires_permission :manage_people, only: %i[create update destroy]
def index
@roles = @aircraft.roles.includes(:user).order(:role, :created_at)
return permission_denied unless can?(:manage_people) || can?(:manage_sharing) || can?(:export_data)
@access = AircraftAccess.new(@aircraft, actor: current_user)
@roles = @aircraft.roles.includes(:user, :role).joins(:role).order("roles.position", :created_at)
@share_tokens = @aircraft.share_tokens.order(created_at: :desc).includes(:created_by)
end
def create
user = User.find_by(email_address: params[:email_address].to_s.strip.downcase)
unless user
return redirect_to aircraft_aircraft_roles_path(@aircraft),
alert: t("flash.aircraft_roles.no_user_with_that")
end
role = @aircraft.roles.new(user: user, role: params[:role])
if role.save
log_event("role", t("flash.aircraft_roles.added_as", display_name: user.display_name, role: role.role))
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.added", display_name: user.display_name)
else
redirect_to aircraft_aircraft_roles_path(@aircraft), alert: role.errors.full_messages.to_sentence
end
return back(alert: t("flash.aircraft_roles.no_user_with_that")) unless user
error = access.add(user, Role.find_by(id: params[:role_id]))
back(error ? { alert: error } : { notice: t("flash.aircraft_roles.added", display_name: user.display_name) })
end
def update
role = @aircraft.roles.find(params[:id])
if demoting_last_owner?(role, params[:role])
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.an_aircraft_must_keep")
end
role.update!(role: params[:role])
log_event("role", t("flash.aircraft_roles.changed_to", display_name: role.user.display_name, role: role.role))
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.role_updated")
error = access.change(@aircraft.roles.find(params[:id]), Role.find_by(id: params[:role_id]))
back(error ? { alert: error } : { notice: t("flash.aircraft_roles.role_updated") })
end
def destroy
role = @aircraft.roles.find(params[:id])
if role.user == current_user
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.you_can_t_remove")
end
if demoting_last_owner?(role, nil)
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.an_aircraft_must_keep_2")
end
role.destroy!
log_event("role", t("flash.aircraft_roles.removed", display_name: role.user.display_name))
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.access_removed")
error = access.remove(@aircraft.roles.find(params[:id]))
back(error ? { alert: error } : { notice: t("flash.aircraft_roles.access_removed") })
end
private
def demoting_last_owner?(role, new_role)
role.role == "owner" && new_role != "owner" && @aircraft.roles.owners.count <= 1
end
def access = AircraftAccess.new(@aircraft, actor: current_user)
def back(flash) = redirect_to(aircraft_aircraft_roles_path(@aircraft), flash)
end
+1 -1
View File
@@ -1,7 +1,7 @@
# Flights → Standardize airport codes (owners).
class AirportCodesController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :edit_any_flight
def show
@standardizer = AirportCodeStandardizer.new(@aircraft)
@@ -1,14 +1,14 @@
class AirworthinessDirectivesController < ApplicationController
include AircraftScoped
include Applicability
before_action :require_owner!, except: :index
requires_permission :manage_ads, except: :index
before_action :set_ad, only: %i[edit update destroy]
def index
@rows = Compliance.ad_rows(@aircraft)
@history = AdCompliance.for_aircraft(@aircraft).recent_first
.includes(:component, :logbook_entry, airworthiness_directive: :document, inspection_record: :inspection_type)
@attachable = AirworthinessDirective.where.not(id: @aircraft.applicable_ads.select(:id)).ordered if owner?
@attachable = AirworthinessDirective.where.not(id: @aircraft.applicable_ads.select(:id)).ordered if can?(:manage_ads)
@alerts = @aircraft.ad_alerts.pending
end
@@ -36,7 +36,7 @@ module Api
render json: { data: Compliance.ad_rows(aircraft).map { ApiPresenter.ad(_1) } }
end
# Logbook entries, oldest first (paged); ?log=AC|ENG|PROP|OTHER, ?signed=true|false.
# Logbook entries, oldest first (paged); ?log=AC|ENG|PROP|AVIONICS|OTHER, ?signed=true|false.
def logbook_entries
aircraft = find_aircraft(params[:id])
scope = aircraft.logbook_entries.includes(:signature)
+6 -2
View File
@@ -70,8 +70,12 @@ module Api
def find_aircraft(id = params[:aircraft_id]) = aircraft_scope.find(id)
def role_on(aircraft) = acting_user&.role_for(aircraft)
def owner_of?(aircraft) = role_on(aircraft).in?(%w[admin owner])
# What the person it's acting for can do on the aircraft, as in the app (Role).
def can?(permission, aircraft) = acting_user&.can?(permission, aircraft) || false
def not_permitted(permission)
render_error(:forbidden, "not_permitted", "This needs the \"#{Permission.label(permission)}\" permission on the aircraft.")
end
# ?limit= (1–200, default 50), ?after=<id> to continue, ?updated_since=<ISO time>.
def paginate(scope)
@@ -27,7 +27,7 @@ module Api
# POST /aircraft/:aircraft_id/draft_batches
def create
@aircraft = find_aircraft
return render_error(:forbidden, "owners_only", "Draft entries are for the aircraft's owners (act for an owner).") unless owner_of?(@aircraft)
return not_permitted(:write_logbook) unless can?(:write_logbook, @aircraft)
input = params.require(:draft_batch)
items = Array(input[:items]).map { _1.permit(:log, :text, :external_ref, resolves_squawks: []) }
@@ -54,7 +54,7 @@ module Api
# DELETE /draft_batches/:id: withdraw it while nothing in it is signed.
def destroy
batch = find_batch
return render_error(:forbidden, "owners_only", "Only the aircraft's owners can withdraw a draft.") unless owner_of?(batch.aircraft)
return not_permitted(:write_logbook) unless can?(:write_logbook, batch.aircraft)
unless batch.awaiting? && batch.entries.none?(&:signed?)
return render_error(:conflict, "signed", "Part of this draft is signed (or it's no longer awaiting signature); correct it in the app instead.")
end
+4 -3
View File
@@ -31,6 +31,7 @@ module Api
# POST /aircraft/:aircraft_id/squawks
def create
aircraft = find_aircraft
return not_permitted(:report_squawks) unless can?(:report_squawks, aircraft)
squawk = aircraft.squawks.new(create_params.merge(reported_by: acting_user, resolved: false))
squawk.component_id = nil unless aircraft.components.exists?(id: squawk.component_id)
squawk.save!
@@ -39,13 +40,13 @@ module Api
end
# PATCH /squawks/:id: external_ref by anyone who may write; the rest
# (issue, priority, component, notes) by the aircraft's owners, as in the app.
# (issue, priority, component, notes) with "manage squawks", as in the app.
def update
squawk = find_squawk
return render_error(:unprocessable_entity, "resolved", "A resolved squawk can't be changed.") if squawk.resolved?
attrs = params.require(:squawk).permit(:external_ref, :issue_reported, :priority, :component_id, :notes)
if (attrs.keys - %w[external_ref]).any? && !owner_of?(squawk.aircraft)
return render_error(:forbidden, "owners_only", "Only the aircraft's owners can change a squawk's details.")
if (attrs.keys - %w[external_ref]).any? && !can?(:manage_squawks, squawk.aircraft)
return not_permitted(:manage_squawks)
end
attrs[:component_id] = nil if attrs.key?(:component_id) && !squawk.aircraft.components.exists?(id: attrs[:component_id])
squawk.update!(attrs)
+18
View File
@@ -6,6 +6,7 @@ class ApplicationController < ActionController::Base
include RejectsNullBytes
prepend_before_action :redirect_to_setup
prepend_before_action :viewer_guard # first (see Viewer)
before_action { Current.ip_address = request.remote_ip } # for record history
helper_method :current_user
@@ -40,10 +41,27 @@ class ApplicationController < ActionController::Base
def current_user = Current.user
# First run: no users yet → create the initial admin.
# Viewer mode: never with real accounts, and nothing can be changed.
def viewer_guard
return unless Viewer.enabled?
return render(plain: Viewer::RealAccounts.new.message, status: :service_unavailable) if Viewer.real_accounts?
Viewer.user
return if request.get? || request.head?
respond_to do |format|
format.html { redirect_back fallback_location: root_path, alert: t("viewer.read_only") }
format.any { head :forbidden }
end
end
def redirect_to_setup
redirect_to new_setup_path if !User.exists? && !is_a?(SetupController)
end
# Adding or importing an aircraft (User#can_add_aircraft?).
def require_aircraft_adder!
redirect_to root_path, alert: t("flash.aircraft.ask_an_administrator") unless current_user.can_add_aircraft?
end
def require_admin!
redirect_to root_path, alert: t("flash.application.admins_only") unless current_user&.admin?
end
+1 -1
View File
@@ -1,6 +1,6 @@
class ComponentsController < ApplicationController
include AircraftScoped
before_action :require_owner!, except: %i[index show]
requires_permission :manage_components, except: %i[index show]
before_action :set_component, only: %i[show edit update destroy reset_service]
def index
+54 -15
View File
@@ -1,16 +1,38 @@
# Scopes a controller to one aircraft the current user can access and exposes
# role helpers. Unknown and inaccessible aircraft both 404 (enumeration-safe).
# Scopes a controller to one aircraft the current user can access, and checks
# what their role there allows (Role, Permission). Unknown and inaccessible
# aircraft both 404 (enumeration-safe). Administrators can do everything.
#
# Access matrix (mirrors the original):
# admin – everything
# owner – everything on their aircraft
# pilot – view all; update hours; create squawks, notes, oil/fuel, flight logs
# Each controller says which permission its actions need:
#
# requires_permission :manage_components, except: %i[index show]
# requires_permission :report_squawks, only: %i[new create]
# checks_permission_itself only: %i[edit update] # decided in the controller
#
# Looking needs no permission. A request that changes something (anything but
# GET/HEAD) with no permission declared for its action is refused, so nothing
# is left open by mistake; in development and tests it raises instead.
module AircraftScoped
extend ActiveSupport::Concern
SELF_CHECKED = "(checked by the controller)".freeze
class MissingPermission < StandardError; end
included do
class_attribute :permission_rules, instance_accessor: false, default: []
before_action :set_aircraft
helper_method :current_role, :owner?, :can_write?
before_action :authorize_permission!
helper_method :current_role, :can?, :owner?
end
class_methods do
def requires_permission(permission, only: nil, except: nil)
self.permission_rules += [ [ permission.to_s, only && Array(only).map(&:to_s), except && Array(except).map(&:to_s) ] ]
end
def checks_permission_itself(only:)
requires_permission(SELF_CHECKED, only: only)
end
end
private
@@ -21,18 +43,35 @@ module AircraftScoped
@aircraft = current_user.accessible_aircraft.find(aircraft_param)
end
# Their Role here (nil for an administrator without one).
def current_role
@current_role ||= current_user.role_for(@aircraft)
return @current_role if defined?(@current_role)
@current_role = current_user.role_for(@aircraft)
end
# Owner-level write access (admins included).
def owner? = current_role.in?(%w[admin owner])
alias_method :can_write?, :owner?
# Nothing in viewer mode (a read-only copy, see Viewer).
def can?(permission) = !Viewer.enabled? && (current_user.admin? || current_role&.can?(permission) || false)
def require_owner!
return if owner?
redirect_back fallback_location: aircraft_path(@aircraft),
alert: t("flash.common.only_owners_can_do")
# The Owner role (or an administrator): everything.
def owner? = !Viewer.enabled? && (current_user.admin? || current_role&.owner? || false)
def authorize_permission!
rules = self.class.permission_rules.select do |_, only, except|
(only.nil? || only.include?(action_name)) && (except.nil? || except.exclude?(action_name))
end
if rules.empty?
return if request.get? || request.head?
raise MissingPermission, "#{self.class.name}##{action_name} changes data without declaring a permission" if Rails.env.local?
return permission_denied
end
permission_denied unless rules.all? { |permission, *| permission == SELF_CHECKED || can?(permission) }
end
def permission_denied
respond_to do |format|
format.html { redirect_back fallback_location: aircraft_path(@aircraft), alert: t("flash.common.not_allowed") }
format.any { head :forbidden }
end
end
# Returns id only if it belongs to the given (aircraft-scoped) relation; else nil.
+6 -1
View File
@@ -21,7 +21,12 @@ module Authentication
end
def require_authentication
resume_session || request_authentication
resume_session || start_viewer_session || request_authentication
end
# Viewer mode: everyone is its built-in account, without signing in.
def start_viewer_session
start_new_session_for(Viewer.user) if Viewer.enabled? && !Viewer.real_accounts?
end
def resume_session
@@ -1,6 +1,7 @@
class ConsumableRecordsController < ApplicationController
include AircraftScoped
before_action :require_owner!, only: %i[edit update destroy]
requires_permission :record_consumables, only: %i[new create]
requires_permission :manage_consumables, only: %i[edit update destroy]
before_action :set_record, only: %i[edit update destroy]
RECORDS_PER_PAGE = 50
@@ -1,6 +1,6 @@
class DocumentCollectionsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :manage_documents
before_action :set_collection, only: %i[edit update destroy]
def new
+1 -1
View File
@@ -1,6 +1,6 @@
class DocumentsController < ApplicationController
include AircraftScoped
before_action :require_owner!, except: %i[index show]
requires_permission :manage_documents, except: %i[index show]
before_action :set_document, only: %i[show edit update destroy]
def index
@@ -3,6 +3,7 @@
# who they are again (password, or single sign-on just now), and confirms.
class EntrySignaturesController < ApplicationController
include AircraftScoped
requires_permission :sign_logbook
include EntrySigning
before_action :set_entry
+1 -1
View File
@@ -2,7 +2,7 @@
class FlightImportsController < ApplicationController
include AircraftScoped
include StoredUpload
before_action :require_owner!
requires_permission :import_flights
def new; end
+33 -5
View File
@@ -1,7 +1,11 @@
class FlightLogsController < ApplicationController
include AircraftScoped
before_action :require_owner!, only: :destroy
before_action :set_flight_log, only: %i[show engine_data_series attach_engine_data remove_engine_data]
requires_permission :log_flights, only: %i[new create]
requires_permission :delete_flights, only: :destroy
checks_permission_itself only: %i[edit update attach_engine_data remove_engine_data]
before_action :set_flight_log, only: %i[show edit update engine_data_series attach_engine_data remove_engine_data]
before_action :require_flight_editor!, only: %i[edit update]
helper_method :can_edit_flight?
before_action :require_engine_data_access!, only: %i[attach_engine_data remove_engine_data]
helper_method :manage_engine_data?
@@ -99,6 +103,22 @@ class FlightLogsController < ApplicationController
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: t("flash.flight_logs.engine_data_removed")
end
def edit
@meters_editable = @flight_log.meters_editable?
end
# A correction. The readings only change on the latest flight (see
# FlightLog#meters_editable?); on earlier ones they're left as they are.
def update
@meters_editable = @flight_log.meters_editable?
attributes = flight_log_params.except(:client_key)
attributes = attributes.except(*FlightLog::METERS) unless @meters_editable
HoursService.new(@aircraft).update_flight!(@flight_log, attributes)
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: t("flash.flight_logs.flight_corrected")
rescue ActiveRecord::RecordInvalid
render :edit, status: :unprocessable_entity
end
# Deleting a flight does not roll back hours; correct those with an hours update.
def destroy
@aircraft.flight_logs.find(params[:id]).destroy!
@@ -108,14 +128,22 @@ class FlightLogsController < ApplicationController
private
# Any flight with "correct any flight"; the ones they logged with "correct own flights".
def can_edit_flight?(flight)
can?(:edit_any_flight) || (can?(:edit_own_flights) && flight.user_id.present? && flight.user_id == current_user.id)
end
def require_flight_editor!
return if can_edit_flight?(@flight_log)
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), alert: t("flash.flight_logs.only_owners_or_the")
end
def set_flight_log
@flight_log = @aircraft.flight_logs.find(params[:id])
end
# Owners, or the pilot who logged the flight.
def manage_engine_data?
owner? || (@flight_log.user_id.present? && @flight_log.user_id == current_user.id)
end
def manage_engine_data? = can_edit_flight?(@flight_log)
def require_engine_data_access!
return if manage_engine_data?
@@ -1,6 +1,6 @@
class InspectionRecordsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :manage_inspections
before_action :set_record, only: %i[edit update destroy]
def new
@@ -1,7 +1,7 @@
class InspectionTypesController < ApplicationController
include AircraftScoped
include Applicability
before_action :require_owner!
requires_permission :manage_inspections
before_action :set_type, only: %i[edit update destroy]
def new
@@ -1,6 +1,7 @@
# The invited signer's side: sign in (or create an account for the invited
# address), add a certificate if needed, review the entry and sign it. The
# invitation gives access to that one entry only.
# The invited signer's side: sign in (or, from an Owner's invitation, create an
# account for the invited address: SigningInvitation#creates_account?), add a
# certificate if needed, review the entry and sign it. The invitation gives
# access to that one entry only.
class InvitedSigningsController < ApplicationController
include EntrySigning
allow_unauthenticated_access only: %i[show account]
@@ -12,6 +13,7 @@ class InvitedSigningsController < ApplicationController
@aircraft = @entry.aircraft
unless authenticated?
session[:return_to_after_authenticating] = request.url
session[:signing_token] = params[:token] # for an account made by signing in with SSO
return render(:welcome)
end
return render(:wrong_account) unless current_user.email_address == @invitation.email
@@ -20,10 +22,10 @@ class InvitedSigningsController < ApplicationController
render :new
end
# Creating an account for the invited email address.
# Creating an account for the invited email address (an Owner's invitation).
def account
return redirect_to(invited_signing_path(params[:token])) if authenticated?
if User.exists?(email_address: @invitation.email) || !Sso.password_login?
if User.exists?(email_address: @invitation.email) || !Sso.password_login? || !@invitation.creates_account?
return redirect_to invited_signing_path(params[:token]), alert: t("flash.invited_signings.sign_in_to_continue")
end
user = User.new(params.permit(:name, :password, :password_confirmation).merge(email_address: @invitation.email))
+68
View File
@@ -0,0 +1,68 @@
# Opening an invitation link (AccessInvitation): see what it gives, then sign
# in and accept. Only an administrator's invitation can make a new account
# (with a password here, or by signing in with SSO: SsoController); others
# need an existing one. An invitation for one email address only works for
# that address. Any invalid link (unknown, expired, used up, revoked) gets
# one answer.
class JoinsController < ApplicationController
allow_unauthenticated_access only: %i[show account]
before_action :set_invitation
rate_limit to: 10, within: 15.minutes, only: %i[account accept],
with: -> { redirect_to join_path(params[:token]), alert: t("flash.joins.try_again_later") }
def show
unless current_user
session[:return_to_after_authenticating] = request.url
session[:join_token] = params[:token] # for an account made by signing in with SSO
return render(:welcome)
end
return redirect_to(root_path, notice: t("flash.joins.already_accepted")) if @invitation.redeemed_by?(current_user)
return render(:wrong_account) unless @invitation.for?(current_user)
render :accept
end
# A new account, then the invitation accepted with it.
def account
return redirect_to(join_path(params[:token])) if current_user
unless Sso.password_login? && @invitation.creates_accounts?
return redirect_to(join_path(params[:token]), alert: t("flash.joins.sign_in_to_continue"))
end
email = @invitation.email || params[:email_address].to_s.strip.downcase
if User.exists?(email_address: email)
return redirect_to join_path(params[:token]), alert: t("flash.joins.account_exists")
end
user = User.new(params.permit(:name, :password, :password_confirmation).merge(email_address: email))
results = nil
User.transaction do
raise ActiveRecord::Rollback unless user.save
results = @invitation.redeem!(user)
end
if results
reset_session
start_new_session_for user
redirect_to root_path, notice: [ t("flash.joins.welcome"), AccessInvitation.describe(results) ].join(" ").strip
else
@account_errors = user.errors.full_messages
render :welcome, status: :unprocessable_entity
end
rescue ActiveRecord::RecordInvalid
render :invalid, layout: "public", status: :not_found
end
def accept
return redirect_to(root_path, notice: t("flash.joins.already_accepted")) if @invitation.redeemed_by?(current_user)
return render(:wrong_account) unless @invitation.for?(current_user)
redirect_to root_path, notice: [ t("flash.joins.accepted"), AccessInvitation.describe(@invitation.redeem!(current_user)) ].join(" ").strip
rescue ActiveRecord::RecordInvalid
render :invalid, layout: "public", status: :not_found
end
private
def set_invitation
@invitation = AccessInvitation.find_by_token(params[:token])
render :invalid, layout: "public", status: :not_found unless @invitation&.usable?
end
def current_user = Current.user || (resume_session && Current.user)
end
+1 -1
View File
@@ -2,7 +2,7 @@
# the loading calculator.
class LoadingSetupsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :manage_weight_balance
def edit
@setup = @aircraft.loading_setup
@@ -1,6 +1,6 @@
class LogbookEntriesController < ApplicationController
include AircraftScoped
before_action :require_owner!, except: %i[index show]
requires_permission :write_logbook, except: %i[index show]
before_action :set_entry, only: %i[show edit update destroy verify]
before_action :require_unsigned, only: %i[edit update destroy]
@@ -3,7 +3,7 @@
# entries in the background (LogbookTranscriptionJob).
class LogbookImportsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :import_records
def new
@collections = @aircraft.document_collections.ordered
+1 -1
View File
@@ -1,6 +1,6 @@
class MajorRecordsController < ApplicationController
include AircraftScoped
before_action :require_owner!, except: %i[index show]
requires_permission :manage_major_records, except: %i[index show]
before_action :set_record, only: %i[show edit update destroy]
def index
+2 -1
View File
@@ -1,6 +1,7 @@
class NotesController < ApplicationController
include AircraftScoped
before_action :require_owner!, only: %i[edit update destroy]
requires_permission :write_notes, only: %i[new create preview]
requires_permission :manage_notes, only: %i[edit update destroy]
before_action :set_note, only: %i[edit update destroy]
def index
+2 -1
View File
@@ -1,6 +1,7 @@
class OilAnalysesController < ApplicationController
include AircraftScoped
before_action :require_owner!, only: %i[edit update destroy]
requires_permission :record_oil_analyses, only: %i[new create import]
requires_permission :manage_oil_analyses, only: %i[edit update destroy]
before_action :set_analysis, only: %i[show edit update destroy]
COMPARE_SAMPLES = 6 # columns in the trend table, like the lab report's history
@@ -1,7 +1,7 @@
# Every change to the aircraft's maintenance records (AC 120-78B 3.2.2).
class RecordVersionsController < ApplicationController
include AircraftScoped
before_action :require_owner!, only: :restore
requires_permission :restore_history, only: :restore
SHARED = { "AirworthinessDirective" => AirworthinessDirective, "InspectionType" => InspectionType }.freeze
@@ -1,7 +1,7 @@
# Download every record of an aircraft in one ZIP (owners).
class RecordsPackagesController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :export_data
def show
package = RecordsPackage.new(@aircraft, source: request.host)
+1 -1
View File
@@ -1,6 +1,6 @@
class ShareTokensController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :manage_sharing
def create
token = @aircraft.share_tokens.new(params.require(:share_token).permit(:label, :privilege, :expires_at))
@@ -1,7 +1,7 @@
# An owner asks someone outside the aircraft (a mechanic) to sign an entry.
class SigningInvitationsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :write_logbook
before_action :set_entry
rate_limit to: 10, within: 1.hour, only: :create, with: -> { redirect_back fallback_location: root_path, alert: t("flash.signing_invitations.too_many_invitations_try") }
@@ -22,7 +22,9 @@ class SigningInvitationsController < ApplicationController
tail: @aircraft.tail_number, name: current_user.display_name)
end
log_event("logbook", t("flash.signing_invitations.signature_requested_from_entry", email: @invitation.email, date: l(@entry.date, format: :app)))
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: t("flash.signing_invitations.invitation_sent_to_the", email: @invitation.email, days: SigningInvitation::VALID_FOR.in_days.to_i)
notice = t("flash.signing_invitations.invitation_sent_to_the", email: @invitation.email, days: SigningInvitation::VALID_FOR.in_days.to_i)
notice = "#{notice} #{t('flash.signing_invitations.no_account_yet')}" unless invitee || @invitation.creates_account?
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: notice
else
render :new, status: :unprocessable_entity
end
+3 -1
View File
@@ -2,7 +2,9 @@ class SquawksController < ApplicationController
include AircraftScoped
# Pilots may create squawks and defer inoperative items (91.213(d) lets the
# pilot decide); editing and resolving need an owner.
before_action :require_owner!, except: %i[index new create deferral defer]
requires_permission :report_squawks, only: %i[new create]
requires_permission :defer_squawks, only: %i[deferral defer]
requires_permission :manage_squawks, except: %i[index new create deferral defer]
before_action :set_squawk, only: %i[edit update destroy resolution resolve reopen deferral defer undefer]
def index
+28 -3
View File
@@ -6,6 +6,11 @@
# email is verified (or OIDC_TRUST_EMAIL is on), since some providers let
# users edit their email. Otherwise, sign in with a password once and link
# from the profile page.
#
# Someone without an account gets one only from an invitation they opened
# first that can make one (an administrator's AccessInvitation, accepted at
# once; an Owner's SigningInvitation, for its address), or for anyone the
# provider lets in when OIDC_AUTO_CREATE_USERS is on.
class SsoController < ApplicationController
allow_unauthenticated_access only: %i[callback failure]
before_action :require_sso
@@ -29,6 +34,7 @@ class SsoController < ApplicationController
return_to = session[:return_to_after_authenticating]
reset_session # fresh session id after signing in
start_new_session_for user
return redirect_to(root_url, notice: [ t("flash.joins.welcome"), AccessInvitation.describe(@joined) ].join(" ").strip) if @joined
redirect_to return_to || root_url
end
@@ -81,15 +87,34 @@ class SsoController < ApplicationController
end
def create_user(auth)
return unless Sso.auto_create_users?
email = auth.info&.email.to_s.strip.downcase
return if email.blank? || User.exists?(email_address: email)
# The random password is never shown; a password reset can set a real one.
User.create!(email_address: email, name: auth.info&.name.presence, sso_uid: auth.uid, password: SecureRandom.base58(40))
invitation = invitation_making_account(email)
return unless invitation || signing_invitation_making_account?(email) || Sso.auto_create_users?
User.transaction do
# The random password is never shown; a password reset can set a real one.
user = User.create!(email_address: email, name: auth.info&.name.presence, sso_uid: auth.uid, password: SecureRandom.base58(40))
@joined = invitation&.redeem!(user)
user
end
rescue ActiveRecord::RecordInvalid
nil
end
# A signing invitation opened in this browser before signing in, from an
# Owner, for this email address.
def signing_invitation_making_account?(email)
invitation = SigningInvitation.find_usable(session[:signing_token])
invitation.present? && invitation.creates_account? && invitation.email == email
end
# The invitation opened in this browser before signing in, when it can
# make an account (an administrator's) for this email address.
def invitation_making_account(email)
invitation = AccessInvitation.find_by_token(session[:join_token])
invitation if invitation&.usable? && invitation.creates_accounts? && invitation.for_email?(email)
end
def email_verified?(auth)
[ true, "true" ].include?(raw_info(auth)["email_verified"])
end
@@ -1,6 +1,6 @@
class StandardInspectionsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :manage_inspections
def new; end
@@ -2,7 +2,7 @@
# keep the records and the loading setup).
class WeightBalanceRecordsController < ApplicationController
include AircraftScoped
before_action :require_owner!, except: :index
requires_permission :manage_weight_balance, except: :index
before_action :set_record, only: %i[edit update destroy]
def index
+5 -2
View File
@@ -3,11 +3,14 @@ module AircraftHelper
# What the app saves ahead of time for use without signal (see
# offline_prep_controller.js): for each of your aircraft, the Overview, W&B,
# Log Flight and Report Squawk pages, and its photo (at both page sizes).
# Log Flight and Report Squawk pages (when their role allows them), and its
# photo (at both page sizes).
def offline_pages
current_user.accessible_aircraft.ordered.limit(OFFLINE_AIRCRAFT).map do |a|
role = current_user.role_for(a)
can = ->(permission) { current_user.admin? || role&.can?(permission) }
{ tail: a.tail_number, pages: [ aircraft_path(a), aircraft_weight_balance_records_path(a) ],
flight: new_aircraft_flight_log_path(a), squawk: new_aircraft_squawk_path(a),
flight: (new_aircraft_flight_log_path(a) if can.(:log_flights)), squawk: (new_aircraft_squawk_path(a) if can.(:report_squawks)),
pictures: (%i[thumb card].map { url_for(a.picture_for(_1)) }.uniq if a.picture_shown?) }.compact
end
end
@@ -29,9 +29,9 @@ export default class extends Controller {
const forms = {}
const paths = [ "/" ]
for (const a of this.aircraftValue) {
paths.push(...a.pages, a.flight, a.squawk)
forms[a.flight] = { tail: a.tail, kind: "flight" }
forms[a.squawk] = { tail: a.tail, kind: "squawk" }
paths.push(...a.pages)
if (a.flight) { paths.push(a.flight); forms[a.flight] = { tail: a.tail, kind: "flight" } }
if (a.squawk) { paths.push(a.squawk); forms[a.squawk] = { tail: a.tail, kind: "squawk" } }
}
const pictures = this.aircraftValue.flatMap((a) => a.pictures || [])
const total = paths.length + 1
+4 -4
View File
@@ -1,17 +1,17 @@
# Daily: tells owners about items that have newly become overdue or limit
# Daily: tells those who get its reminders (Role "gets reminders") about items that have newly become overdue or limit
# the aircraft (grounded, VFR only…). Each is sent once; one that's fixed and
# becomes overdue again is sent again.
class OverdueNotificationJob < ApplicationJob
queue_as :default
def perform
Aircraft.includes(roles: :user).find_each do |aircraft|
Aircraft.includes(roles: %i[user role]).find_each do |aircraft|
issues = aircraft.airworthiness.issues.select { _1.severity.in?([ Airworthiness::RED, Airworthiness::LIMITED ]) }
keys = issues.map { |i| "#{i.category}:#{i.item.class.name}:#{i.item.id}" }
fresh = issues.reject.with_index { |_, n| aircraft.notified_issue_keys.include?(keys[n]) }
owners = aircraft.roles.select { _1.role == "owner" }.map(&:user).reject(&:disabled?)
recipients = aircraft.roles.select { _1.role.can?(:receive_reminders) }.map(&:user).reject(&:disabled?)
if fresh.any?
PushNotifier.notify(owners, :overdue, path: Rails.application.routes.url_helpers.aircraft_path(aircraft), tag: "overdue-#{aircraft.id}",
PushNotifier.notify(recipients, :overdue, path: Rails.application.routes.url_helpers.aircraft_path(aircraft), tag: "overdue-#{aircraft.id}",
tail: aircraft.tail_number, items: fresh.map(&:title).to_sentence, count: fresh.size)
end
aircraft.update_column(:notified_issue_keys, keys) if keys.sort != aircraft.notified_issue_keys.sort
+1 -1
View File
@@ -1,4 +1,4 @@
# Weekly email to aircraft owners listing what's overdue or coming due
# Weekly email to those who get an aircraft's reminders (Role "gets reminders") listing what's overdue or coming due
# (inspections, ADs, components, expiring documents), deferred items, new
# ADs, and the user's own certificates that are about to expire.
# Nothing is sent when nothing needs attention, or when email isn't set up.
+9
View File
@@ -0,0 +1,9 @@
# The link of an invitation made for one email address (AccessInvitation).
class AccessInvitationMailer < ApplicationMailer
def invite(invitation, token)
@invitation = invitation
@grants = invitation.grants.includes(:aircraft, :role).sort_by { _1.aircraft.tail_number }
@url = join_url(token)
mail subject: t(".subject", who: invitation.created_by&.display_name || t(".an_administrator")), to: invitation.email
end
end
+12 -6
View File
@@ -1,8 +1,13 @@
class ReminderMailer < ApplicationMailer
# [[aircraft, issues, new AD alerts], …] for the aircraft the user owns
# that need attention.
# Aircraft where the user's role includes the permission.
def self.aircraft_where(user, permission)
Aircraft.where(id: AircraftRole.with_permission(permission).where(user_id: user.id).select(:aircraft_id)).ordered
end
# [[aircraft, issues, new AD alerts], …] for the aircraft the user gets
# reminders for (their role's "gets reminders") that need attention.
def self.items_for(user)
Aircraft.joins(:roles).where(aircraft_roles: { user_id: user.id, role: "owner" }).ordered
aircraft_where(user, :receive_reminders)
.map { [ _1, _1.airworthiness.issues, _1.ad_alerts.pending.to_a ] }.reject { _2.empty? && _3.empty? }
end
@@ -10,10 +15,11 @@ class ReminderMailer < ApplicationMailer
def self.audit_due_for?(user) = user.admin? && AuditRun.due_soon?
# Owned aircraft whose AD baseline needs a (new) DRS import: none yet, a
# year old, or a model never covered.
# Aircraft they get reminders for and manage the ADs of, whose AD baseline
# needs a (new) DRS import: none yet, a year old, or a model never covered.
def self.drs_due_for(user)
Aircraft.joins(:roles).where(aircraft_roles: { user_id: user.id, role: "owner" }).ordered
aircraft_where(user, :receive_reminders)
.where(id: AircraftRole.with_permission(:manage_ads).where(user_id: user.id).select(:aircraft_id))
.select { DrsImport.renewal_due?(_1) || DrsImport.missing_models(_1).any? }
end
+87
View File
@@ -0,0 +1,87 @@
# An invitation code: a link someone opens to create an account (or accept
# with the one they have) and get roles on aircraft. Made by administrators
# (Admin → Invitations, any aircraft) or by whoever manages an aircraft's
# people (its Access page, that aircraft). Limited by number of uses, an
# expiry, and optionally to one email address; it can be revoked. Only a
# digest of the code is kept, so the link is shown once, when it's made.
#
# New accounts are only ever made by an administrator or from an
# administrator's invitation: anyone can add an aircraft and so manage its
# people, so other invitations are for people who already have an account.
class AccessInvitation < ApplicationRecord
VALID_FOR = 14.days
belongs_to :created_by, class_name: "User", optional: true
has_many :grants, class_name: "AccessInvitationRole", dependent: :delete_all
has_many :redemptions, class_name: "AccessInvitationRedemption", dependent: :delete_all
has_many :aircraft, through: :grants
attr_reader :token
normalizes :email, with: ->(email) { email.strip.downcase.presence }
normalizes :label, :name, with: ->(text) { text.squish.presence }
validates :label, presence: true, length: { maximum: 100 }
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }, allow_nil: true
validates :max_uses, numericality: { only_integer: true, greater_than: 0, less_than_or_equal_to: 1000 }, allow_nil: true
before_validation(on: :create) do
@token = SecureRandom.urlsafe_base64(24)
self.token_digest = self.class.digest(@token)
end
scope :recent_first, -> { order(created_at: :desc) }
scope :usable, -> {
where(revoked_at: nil).where("expires_at IS NULL OR expires_at > ?", Time.current).where("max_uses IS NULL OR uses_count < max_uses")
}
# A new invitation by creator giving roles ([[aircraft, role], …]); its
# link is emailed when it's for one address and email is set up.
def self.create_for(creator, attributes, grants)
invitation = new(attributes.merge(created_by: creator))
grants.each { |aircraft, role| invitation.grants.build(aircraft: aircraft, role: role) }
if invitation.save && invitation.email && MailSettings.configured?
AccessInvitationMailer.invite(invitation, invitation.token).deliver_later
end
invitation
end
# "N12345: Mechanic. N54321: already Owner, unchanged" (from #redeem!).
def self.describe(results)
results.map { |aircraft, role, message| "#{aircraft.tail_number}: #{[ role&.name, message ].compact.join(', ')}" }.join(" ")
end
def self.digest(token) = OpenSSL::Digest::SHA256.hexdigest(token.to_s)
def self.find_by_token(token) = token.present? ? find_by(token_digest: digest(token)) : nil
def usable? = !revoked? && !expired? && !used_up?
# Whether someone without an account can make one with it (see above),
# decided when it's used: its creator must still be an administrator.
def creates_accounts? = created_by.present? && created_by.admin? && !created_by.disabled?
def for_email?(email) = self.email.nil? || self.email == email.to_s.strip.downcase
def revoked? = revoked_at.present?
def expired? = expires_at.present? && expires_at <= Time.current
def used_up? = max_uses.present? && uses_count >= max_uses
def for?(user) = for_email?(user.email_address)
def redeemed_by?(user) = redemptions.exists?(user: user)
# Gives the person the invitation's roles, as if its creator added them
# (AircraftAccess: so it can't give more than they could, then or now).
# A role they already have on an aircraft stays as it is. Returns
# [[aircraft, role or nil, message or nil], …].
def redeem!(user)
with_lock do
raise ActiveRecord::RecordInvalid, self unless usable? && for?(user)
redemptions.create!(user: user)
increment!(:uses_count)
grants.includes(:aircraft, :role).map do |grant|
if (existing = grant.aircraft.roles.find_by(user: user))
[ grant.aircraft, nil, I18n.t("models.access_invitation.already_has", role: existing.role.name) ]
elsif created_by.nil? || created_by.disabled? || !created_by.can?(:manage_people, grant.aircraft)
[ grant.aircraft, nil, I18n.t("models.access_invitation.creator_gone") ]
else
error = AircraftAccess.new(grant.aircraft, actor: created_by).add(user, grant.role)
[ grant.aircraft, (grant.role unless error), error ]
end
end
end
end
end
@@ -0,0 +1,7 @@
# Who used an invitation, and when (once per person).
class AccessInvitationRedemption < ApplicationRecord
belongs_to :access_invitation
belongs_to :user
validates :user_id, uniqueness: { scope: :access_invitation_id }
end
+8
View File
@@ -0,0 +1,8 @@
# A role an invitation gives on one aircraft.
class AccessInvitationRole < ApplicationRecord
belongs_to :access_invitation
belongs_to :aircraft
belongs_to :role
validates :aircraft_id, uniqueness: { scope: :access_invitation_id }
end
+1
View File
@@ -9,6 +9,7 @@ class Aircraft < ApplicationRecord
end
has_many :roles, class_name: "AircraftRole", dependent: :destroy
has_many :invitation_grants, class_name: "AccessInvitationRole", dependent: :delete_all
has_many :users, through: :roles
has_many :notes, class_name: "AircraftNote", dependent: :destroy
has_many :events, class_name: "AircraftEvent", dependent: :delete_all
+14 -4
View File
@@ -1,11 +1,21 @@
# Someone's role on an aircraft (Role), which decides what they can do there.
class AircraftRole < ApplicationRecord
ROLES = LabelSet.new("aircraft_role.roles", %w[owner pilot])
belongs_to :aircraft
belongs_to :user
belongs_to :role
validates :role, inclusion: { in: ROLES.keys }
validates :user_id, uniqueness: { scope: :aircraft_id, message: "already has a role on this aircraft" }
scope :owners, -> { where(role: "owner") }
scope :owners, -> { joins(:role).where(roles: { key: "owner" }) }
# Whose role includes a permission (Owner always does).
scope :with_permission, ->(permission) {
joins(:role).where("roles.key = 'owner' OR EXISTS (SELECT 1 FROM json_each(roles.permissions) WHERE json_each.value = ?)", permission.to_s)
}
# A Role, or a built-in role's key ("owner", "pilot").
def role=(value)
super(value.is_a?(Role) || value.nil? ? value : Role.for_key(value))
end
def owner? = role&.owner?
end
+10
View File
@@ -26,6 +26,16 @@ class FlightLog < ApplicationRecord
[ departure_location, destination_location ].compact_blank.join(" → ")
end
# The meter readings that move the aircraft's and components' hours.
METERS = %w[tach_out tach_in tach_time hobbs_out hobbs_in hobbs_time].freeze
# Its readings can be corrected only while it's the last flight logged and
# nothing has changed the hours since (an hours update, an import): only
# then is the aircraft's time just this flight's on top of the one before.
def meters_editable?
aircraft.flight_logs.maximum(:id) == id && (tach_in.nil? || tach_in == aircraft.tach_time)
end
private
# Reject files the engine data parser can't read, before they're stored.
+1 -1
View File
@@ -1,6 +1,6 @@
class LogbookEntry < ApplicationRecord
include Versioned
LOG_TYPES = LabelSet.new("logbook_entry.log_types", %w[AC ENG PROP OTHER])
LOG_TYPES = LabelSet.new("logbook_entry.log_types", %w[AC ENG PROP AVIONICS OTHER])
ENTRY_TYPES = LabelSet.new("logbook_entry.entry_types", %w[MAINTENANCE INSPECTION FLIGHT HOURS_UPDATE OTHER])
# Kind of certificate of the person approving return to service (43.9(a)(4)).
+1 -1
View File
@@ -22,7 +22,7 @@ class LogbookTemplate < ApplicationRecord
existing = pluck(:name).to_set
next_position = (maximum(:position) || 0) + 1
added = defaults.reject { existing.include?(_1["name"]) }
added.each_with_index { |d, i| create!(d.slice("name", "reference", "text", "log_type", "certificate_type").merge("position" => next_position + i)) }
added.each_with_index { |d, i| create!(d.slice("name", "reference", "text", "entry_type", "log_type", "certificate_type").merge("position" => next_position + i)) }
added.size
end
+34
View File
@@ -0,0 +1,34 @@
# What a role on an aircraft can do (Role#permissions). Grouped the way the
# app is laid out; labels and descriptions are in config/locales
# (permissions.<key>.label / .description). Seeing an aircraft's records
# needs no permission: every role can view everything on its aircraft.
module Permission
GROUPS = {
flying: %w[log_flights update_hours import_flights edit_own_flights edit_any_flight delete_flights],
squawks_and_notes: %w[report_squawks defer_squawks manage_squawks write_notes manage_notes record_consumables manage_consumables],
maintenance: %w[write_logbook sign_logbook manage_components manage_inspections manage_ads manage_major_records
manage_weight_balance manage_documents record_oil_analyses manage_oil_analyses],
data: %w[import_records export_data restore_history],
aircraft: %w[edit_aircraft delete_aircraft manage_people manage_sharing],
notifications: %w[receive_reminders]
}.freeze
ALL = GROUPS.values.flatten.freeze
# The built-in roles' permissions when first created (admins can change all
# but Owner's, which always has every permission). Pilot is what pilots
# could do before roles were configurable.
DEFAULTS = {
"pilot" => %w[log_flights update_hours edit_own_flights report_squawks defer_squawks write_notes record_consumables
record_oil_analyses sign_logbook],
"mechanic" => %w[update_hours report_squawks defer_squawks manage_squawks write_notes manage_notes record_consumables
manage_consumables write_logbook sign_logbook manage_components manage_inspections manage_ads
manage_major_records manage_weight_balance manage_documents record_oil_analyses manage_oil_analyses
receive_reminders],
"viewer" => []
}.freeze
def self.label(key) = I18n.t("permissions.#{key}.label")
def self.description(key) = I18n.t("permissions.#{key}.description")
def self.group_label(group) = I18n.t("permissions.groups.#{group}")
end
+41
View File
@@ -0,0 +1,41 @@
# A role someone can have on an aircraft: a name and a set of permissions
# (Permission). Installation-wide; administrators manage them (Admin → Roles).
# Four are built in (key set): Owner, which always has every permission so an
# aircraft can always be managed, and Mechanic, Pilot and Viewer, whose
# permissions can be changed. Administrators can add their own.
class Role < ApplicationRecord
BUILT_IN = %w[owner mechanic pilot viewer].freeze
has_many :aircraft_roles, dependent: :restrict_with_error
has_many :invitation_grants, class_name: "AccessInvitationRole", dependent: :delete_all
normalizes :name, with: ->(name) { name.squish }
validates :name, presence: true, uniqueness: { case_sensitive: false }, length: { maximum: 40 }
validates :description, length: { maximum: 200 }
validates :key, inclusion: { in: BUILT_IN }, uniqueness: true, allow_nil: true
before_validation { self.permissions = Array(permissions).map(&:to_s) & Permission::ALL }
before_destroy { throw :abort if built_in? }
scope :ordered, -> { order(Arel.sql("CASE WHEN key IS NULL THEN 1 ELSE 0 END"), :position, :name) }
# The built-in roles, created when first needed (a new installation, tests).
def self.ensure_built_in!
BUILT_IN.each_with_index do |key, i|
find_or_create_by!(key: key) do |role|
role.name = I18n.t("roles.#{key}.name")
role.description = I18n.t("roles.#{key}.description")
role.permissions = Permission::DEFAULTS.fetch(key, [])
role.position = i
end
end
end
def self.for_key(key) = find_by(key: key.to_s) || (ensure_built_in! && find_by!(key: key.to_s))
def self.owner = for_key("owner")
def built_in? = key.present?
def owner? = key == "owner"
def permissions = owner? ? Permission::ALL : super
def can?(permission) = permissions.include?(permission.to_s)
end
+4
View File
@@ -10,6 +10,9 @@ class Setting < ApplicationRecord
"backups_kept" => { default: 14, in: 1..365 },
"offsite_backups_kept" => { default: 30, in: 1..365 },
"documents_claude_text" => { default: 0, in: 0..1 },
# Who can add aircraft (and so become an Owner, who invites people): 0
# administrators only, 1 everyone.
"anyone_adds_aircraft" => { default: 0, in: 0..1 },
"logbook_templates_seeded" => { default: 0, in: 0..1 } # internal flag
}.freeze
LABELS = LabelSet.new("setting.keys", INTEGERS.keys)
@@ -20,6 +23,7 @@ class Setting < ApplicationRecord
class << self
def max_upload_mb = integer("max_upload_mb")
def max_upload_bytes = max_upload_mb.megabytes
def anyone_adds_aircraft? = integer("anyone_adds_aircraft") == 1
def integer(key)
definition = INTEGERS.fetch(key)
+8
View File
@@ -22,4 +22,12 @@ class SigningInvitation < ApplicationRecord
def self.find_usable(token) = where(token_digest: digest(token), used_at: nil).where("expires_at > ?", Time.current).first
def aircraft = logbook_entry.aircraft
# Whether the mechanic can make an account for the invited address with it:
# when it's from an Owner of the aircraft or an administrator (still, when
# it's used). Who can become an Owner is up to the administrator (Admin →
# Settings, who can add aircraft); others' invitations need an account.
def creates_account?
invited_by.present? && !invited_by.disabled? && (invited_by.admin? || invited_by.role_for(aircraft)&.owner?) || false
end
end
+14 -3
View File
@@ -2,6 +2,8 @@ class User < ApplicationRecord
has_secure_password
has_many :sessions, dependent: :destroy
has_many :aircraft_roles, dependent: :destroy
has_many :access_invitations, foreign_key: :created_by_id, dependent: :nullify, inverse_of: :created_by
has_many :access_invitation_redemptions, dependent: :delete_all
has_many :push_subscriptions, dependent: :delete_all
has_many :api_tokens, dependent: :destroy
@@ -114,10 +116,19 @@ class User < ApplicationRecord
admin? ? Aircraft.all : aircraft
end
# 'admin' | 'owner' | 'pilot' | nil
# Their Role on the aircraft (nil for none; administrators may have none).
def role_for(aircraft)
return "admin" if admin?
aircraft_roles.find_by(aircraft: aircraft)&.role
aircraft_roles.includes(:role).find_by(aircraft: aircraft)&.role
end
# Adding an aircraft (or importing one) makes you its Owner: administrators,
# or everyone when Admin → Settings allows it.
def can_add_aircraft? = !Viewer.enabled? && (admin? || Setting.anyone_adds_aircraft?)
# Administrators can do everything on every aircraft.
def can?(permission, aircraft)
return false if Viewer.enabled?
admin? || role_for(aircraft)&.can?(permission) || false
end
def display_name
+63
View File
@@ -0,0 +1,63 @@
# Viewer mode (SAM_VIEWER=true): a read-only copy of an aircraft archive for
# whoever receives a records package (the FAA, a buyer), with no sign-in. It's
# what the package's viewer/docker-compose.yml runs, on that person's own
# computer.
#
# - At start (bin/rails sam:viewer:prepare, from bin/docker-entrypoint), the
# archive at SAM_VIEWER_ARCHIVE is imported, owned by a built-in account.
# - Everyone is that account (Authentication): no sign-in.
# - Nothing can be changed: requests other than GET/HEAD are refused
# (ApplicationController), and no role permission applies (AircraftScoped).
#
# So that it can never open a real installation, it refuses to run when the
# database has any account other than the built-in one: setting SAM_VIEWER on
# a real server stops it rather than exposing its records.
module Viewer
EMAIL = "viewer@sam-viewer.invalid".freeze
class RealAccounts < StandardError
def message = "SAM_VIEWER is on, but this database has user accounts: viewer mode is only for an empty " \
"copy made to look at an archive. Turn SAM_VIEWER off for a real installation."
end
def self.enabled? = ENV["SAM_VIEWER"] == "true"
def self.archive = ENV["SAM_VIEWER_ARCHIVE"].presence
# What was imported, for the banner (kept with the data).
def self.info_path = Pathname(ENV["SAM_VIEWER_INFO"].presence || Rails.root.join("storage/viewer.json"))
def self.real_accounts? = User.where.not(email_address: EMAIL).exists?
# The built-in account everyone browses as (made when first needed). It
# can't sign in by password: nobody knows it.
def self.user
User.find_or_create_by!(email_address: EMAIL) do |u|
u.name = I18n.t("viewer.account_name")
u.password = SecureRandom.base58(40)
end
end
# Checks the database, then imports the archive the first time.
def self.prepare!(output: $stdout)
raise RealAccounts if real_accounts?
owner = user
if Aircraft.exists?
output.puts "Viewer: already imported (#{Aircraft.ordered.pluck(:tail_number).join(', ')})."
elsif archive.nil? || !File.file?(archive)
output.puts "Viewer: no archive at SAM_VIEWER_ARCHIVE (#{archive.inspect}); nothing to show."
else
output.puts "Viewer: importing #{File.basename(archive)}…"
preview = AircraftArchive::Importer.check(archive)
result = AircraftArchive::Importer.new(archive, owner: owner).run
File.write(info_path, { file: File.basename(archive), tail_number: result[:aircraft].tail_number,
exported_at: preview.exported_at&.iso8601 }.to_json)
output.puts "Viewer: imported #{result[:aircraft].tail_number}: #{result[:counts].map { |k, n| "#{n} #{k.tr('_', ' ')}" }.join(', ')}"
end
output.puts "Viewer ready: open http://localhost:3000"
end
# What the banner says: the archive's file and when it was exported.
def self.info
JSON.parse(info_path.read) if info_path.file?
rescue JSON::ParserError
nil
end
end
+52
View File
@@ -0,0 +1,52 @@
# Giving, changing and taking away people's roles on an aircraft, by someone
# allowed to (the aircraft's "manage people", or an administrator). The rules,
# the same from the aircraft's Access page and Admin → Users:
# - only an Owner or an administrator can give or take away the Owner role
# (otherwise anyone who manages people could make themselves Owner);
# - only an administrator can change or remove their own role;
# - an aircraft always keeps at least one Owner.
# Each method returns nil when done, or a message saying why not.
class AircraftAccess
def initialize(aircraft, actor:)
@aircraft = aircraft
@actor = actor
end
def add(user, role)
return t("not_found") unless user && role
return t("owner_only") if role.owner? && !actor_owner?
membership = @aircraft.roles.new(user: user, role: role)
return membership.errors.full_messages.to_sentence unless membership.save
@aircraft.log_event!("role", I18n.t("flash.aircraft_roles.added_as", display_name: user.display_name, role: role.name), user: @actor)
nil
end
def change(membership, role)
return t("not_found") unless role
return if membership.role == role
return t("own_role") if membership.user == @actor && !@actor.admin?
return t("owner_only") if (role.owner? || membership.owner?) && !actor_owner?
return t("last_owner") if membership.owner? && !role.owner? && last_owner?
membership.update!(role: role)
@aircraft.log_event!("role", I18n.t("flash.aircraft_roles.changed_to", display_name: membership.user.display_name, role: role.name), user: @actor)
nil
end
def remove(membership)
return t("own_role") if membership.user == @actor && !@actor.admin?
return t("owner_only") if membership.owner? && !actor_owner?
return t("last_owner") if membership.owner? && last_owner?
membership.destroy!
@aircraft.log_event!("role", I18n.t("flash.aircraft_roles.removed", display_name: membership.user.display_name), user: @actor)
nil
end
# The roles this person can hand out here (Owner only by an Owner).
def assignable_roles = Role.ordered.select { |role| !role.owner? || actor_owner? }
private
def actor_owner? = @actor.admin? || @actor.role_for(@aircraft)&.owner?
def last_owner? = @aircraft.roles.owners.count <= 1
def t(key) = I18n.t("services.aircraft_access.#{key}")
end
+1 -1
View File
@@ -149,7 +149,7 @@ module AircraftArchive
import_notes
import_oil_analyses
import_flight_logs
@aircraft.roles.find_or_create_by!(user: @owner, role: "owner") if @owner
@aircraft.roles.find_or_create_by!(user: @owner) { _1.role = Role.owner } if @owner
@aircraft.log_event!("aircraft", "Aircraft imported from a .sam.zip archive",
notes: [ @manifest["source_instance"].presence && "Source: #{@manifest['source_instance']}", summary ].compact.join(". "),
user: @owner)
+45
View File
@@ -67,8 +67,53 @@ class HoursService
flight
end
# Correct a saved flight. Its readings change only when it's the latest
# (FlightLog#meters_editable?); the aircraft and its components then move by
# the difference. Its oil and fuel records follow. With both readings given,
# the duration is worked out from them.
def update_flight!(flight, attributes)
Aircraft.transaction do
before = flight.attributes.slice(*FlightLog::METERS, "date", "departure_location", "destination_location",
"oil_added", "fuel_added", "route", "notes")
flight.assign_attributes(attributes)
flight.tach_time = flight.tach_in - flight.tach_out if flight.tach_in && flight.tach_out
flight.hobbs_time = flight.hobbs_in - flight.hobbs_out if flight.hobbs_in && flight.hobbs_out
flight.save!
tach_delta = flight.tach_time - before["tach_time"].to_d
hobbs_delta = flight.hobbs_time.to_d - before["hobbs_time"].to_d
if tach_delta.nonzero? || hobbs_delta.nonzero?
@aircraft.tach_time += tach_delta
@aircraft.hobbs_time += hobbs_delta if @aircraft.hobbs_time
@aircraft.save!
cascade_to_components(@aircraft.hobbs? && flight.hobbs_time ? hobbs_delta : tach_delta, clamp: true)
end
sync_consumables(flight)
changed = before.keys.reject { |key| before[key] == flight[key] }
@aircraft.log_event!("flight", I18n.t("#{H}.flight_corrected", date: I18n.l(flight.date, format: :app)), user: @user,
notes: changed.map { |key| FlightLog.human_attribute_name(key) }.join(", ").presence)
end
flight
end
private
# The flight's oil and fuel records match what it says was added.
def sync_consumables(flight)
{ "oil" => [ flight.oil_added, flight.oil_level_after, flight.oil_added_type ],
"fuel" => [ flight.fuel_added, flight.fuel_level_after, flight.fuel_added_type ] }.each do |type, (qty, level, kind)|
record = flight.consumable_records.find_by(record_type: type)
if qty.to_f.positive?
record ||= @aircraft.consumable_records.new(record_type: type, flight_log: flight, flight_hours: @aircraft.tach_time,
notes: I18n.t("#{H}.auto_created_from_flight_log"))
record.update!(date: flight.date, quantity_added: qty, level_after: level, consumable_type: kind)
else
record&.destroy!
end
end
end
def cascade_to_components(delta, clamp: false)
@aircraft.components.in_use.find_each do |c|
his = c.hours_in_service + delta
+1 -1
View File
@@ -23,7 +23,7 @@ Entry types:
- OTHER: administrative entries, certifications
Fields:
- log_type: AC (airframe), ENG (engine), PROP (propeller), or OTHER
- log_type: AC (airframe), ENG (engine), PROP (propeller), AVIONICS (a separate avionics logbook: radios, transponder, autopilot, GPS…), or OTHER
- text: the entry text verbatim, or a close paraphrase where wording is unclear; write [?] for illegible words
- aircraft_hours: the tach/total time the entry records (a number), or null if none is written
- signoff_person / signoff_location: a string, or null (the person's name only; certificate details go below)
+1 -1
View File
@@ -7,7 +7,7 @@
"type": "object",
"properties": {
"date": { "type": ["string", "null"], "description": "YYYY-MM-DD, or null if unreadable" },
"log_type": { "type": "string", "enum": ["AC", "ENG", "PROP", "OTHER"] },
"log_type": { "type": "string", "enum": ["AC", "ENG", "PROP", "AVIONICS", "OTHER"] },
"entry_type": { "type": "string", "enum": ["MAINTENANCE", "INSPECTION", "FLIGHT", "HOURS_UPDATE", "OTHER"] },
"text": { "type": "string" },
"aircraft_hours": { "type": ["number", "null"] },
+1 -1
View File
@@ -44,7 +44,7 @@ class RecordsAudit
(signed + pool.where.not(id: signed.map(&:id)).order(Arel.sql("RANDOM()")).limit(@policy.audit_sample_size - signed.size).to_a).first(@policy.audit_sample_size)
end
def users = User.order(:email_address).includes(:certificates, aircraft_roles: :aircraft)
def users = User.order(:email_address).includes(:certificates, aircraft_roles: %i[aircraft role])
# Saves the audit from the auditor's answers: { key => { "passed" => "1", "note" => … } }.
def record!(user:, answers:, notes:, sample_ids:)
+23 -10
View File
@@ -64,34 +64,47 @@ class RecordsPackage
def repository = SystemInfo.new.repository_url
# The published image, as named in the project's docker-compose.image.yml
# (APP_IMAGE overrides it, e.g. for a fork's own image).
# The published image, as named in the project's docker-compose.image.yml,
# at this release (each release is also published under its version, so
# whoever opens the package years later gets the version that made it).
# APP_IMAGE, e.g. a fork's own image, is used as it is.
def viewer_image
ENV["APP_IMAGE"].presence ||
Rails.root.join("docker-compose.image.yml").then { _1.exist? ? _1.read[/^\s*image:\s*(\S+)/, 1] : nil }
return ENV["APP_IMAGE"] if ENV["APP_IMAGE"].present?
image = Rails.root.join("docker-compose.image.yml").then { _1.exist? ? _1.read[/^\s*image:\s*(\S+)/, 1] : nil } or return
version = SystemInfo.new.version
return image unless version.match?(/\A\d{4}\.\d{1,2}\.\d+\z/)
"#{image.sub(/:[^:\/]+\z/, '')}:#{version}"
end
# A ready-to-run local viewer, with its own throwaway secret key (never this
# installation's), plain HTTP on localhost.
# A ready-to-run local viewer of the archive: read-only, no account needed
# (viewer mode, see Viewer), reachable only from that computer, with its own
# throwaway secret key (never this installation's).
def viewer_compose
image = viewer_image
archive = "#{@aircraft.tail_number.downcase}.sam.zip"
<<~YAML
# Simple Aircraft Manager on your own computer, to browse #{@aircraft.tail_number.downcase}.sam.zip.
# docker compose up -d then open http://localhost:3000, create an account,
# and import #{@aircraft.tail_number.downcase}.sam.zip (Fleet -> Import). Stop: docker compose down
# Simple Aircraft Manager on your own computer, showing #{archive} read-only.
# 1. In this folder: docker compose up
# The first start imports the records; wait for "Viewer ready".
# 2. Open http://localhost:3000 (no account needed).
# Stop: Ctrl+C, then docker compose down (add -v to delete this local copy).
# Prepared with software version #{SystemInfo.new.version_label}.#{" Source: #{repository}" if repository}
services:
web:
#{image ? "image: #{image}" : "build: . # no published image known: build from the source code"}
restart: "no"
ports:
- "3000:80"
- "127.0.0.1:3000:80" # this computer only
environment:
SAM_VIEWER: "true"
SAM_VIEWER_ARCHIVE: /import/#{archive}
SECRET_KEY_BASE: #{SecureRandom.hex(64)} # for this local copy only
APP_HOST: localhost:3000
FORCE_SSL: "false"
SOLID_QUEUE_IN_PUMA: "true"
SOLID_QUEUE_SKIP_RECURRING: "true" # no reminders, backups or AD searches
volumes:
- ../#{archive}:/import/#{archive}:ro # the archive next to this folder, in the package
- viewer_storage:/rails/storage
volumes:
viewer_storage:
@@ -0,0 +1,4 @@
<p><%= t(".invites_you_html", who: (@invitation.created_by&.display_name || t(".an_administrator"))) %></p>
<% if @grants.any? %><ul><% @grants.each do |g| %><li><strong><%= g.aircraft.tail_number %></strong>: <%= g.role.name %></li><% end %></ul><% end %>
<p><%= link_to t(".accept_the_invitation"), @url %></p>
<% if @invitation.expires_at %><p style="color:#64748b;font-size:12px"><%= t(".expires_html", date: fmt_date(@invitation.expires_at.to_date)) %></p><% end %>
@@ -0,0 +1,11 @@
<%= raw t(".invites_you_text", who: (@invitation.created_by&.display_name || t(".an_administrator"))) %>
<% @grants.each do |g| %>
- <%= g.aircraft.tail_number %>: <%= g.role.name %>
<% end %>
<%= raw t(".open_the_link_text") %>
<%= @url %>
<% if @invitation.expires_at %>
<%= raw t(".expires_text", date: fmt_date(@invitation.expires_at.to_date)) %>
<% end %>
+1 -1
View File
@@ -32,7 +32,7 @@
</ul>
<% elsif key == "users" %>
<ul class="ml-6 list-disc text-xs text-slate-600">
<% @audit.users.each do |u| %><li><%= t(".last_sign_in_html", display_name: u.display_name, email_address: u.email_address, admin: (t(".admin") if u.admin?), any: (" · #{u.aircraft_roles.map { "#{AircraftRole::ROLES[_1.role]} #{_1.aircraft.tail_number}" }.join(', ')}" if u.aircraft_roles.any?), never: (u.last_signed_in_at ? t(".ago", time: time_ago_in_words(u.last_signed_in_at)) : t(".never")), disabled: (t(".disabled") if u.disabled?)) %></li><% end %>
<% @audit.users.each do |u| %><li><%= t(".last_sign_in_html", display_name: u.display_name, email_address: u.email_address, admin: (t(".admin") if u.admin?), any: (" · #{u.aircraft_roles.map { "#{_1.role.name} #{_1.aircraft.tail_number}" }.join(', ')}" if u.aircraft_roles.any?), never: (u.last_signed_in_at ? t(".ago", time: time_ago_in_words(u.last_signed_in_at)) : t(".never")), disabled: (t(".disabled") if u.disabled?)) %></li><% end %>
</ul>
<% end %>
<%= text_field_tag "answers[#{key}][note]", nil, class: "input", placeholder: t(".note_what_was_checked_or") %>
@@ -0,0 +1,2 @@
<% content_for :title, t("shared.invitation_created.title") %>
<%= render "shared/invitation_created", invitation: @invitation, back_path: admin_invitations_path %>
@@ -0,0 +1,28 @@
<% content_for :title, t(".invitations") %>
<div class="mb-2 flex items-center justify-between"><h1 class="text-2xl font-bold"><%= t(".invitations") %></h1><%= link_to t(".new_invitation"), new_admin_invitation_path, class: "btn-primary" %></div>
<p class="mb-4 text-sm text-slate-600"><%= t(".intro") %></p>
<section class="card">
<% if @invitations.any? %>
<table class="table">
<thead><tr><th><%= t(".label") %></th><th><%= t(".gives") %></th><th><%= t(".uses") %></th><th><%= t(".status") %></th><th></th></tr></thead>
<tbody>
<% @invitations.each do |inv| %>
<tr class="invitation-row">
<td><span class="font-medium"><%= inv.label %></span><div class="text-xs text-slate-500"><%= [ inv.email, inv.created_by&.display_name, fmt_date(inv.created_at) ].compact.join(" · ") %></div></td>
<td class="text-xs" data-label="<%= t(".gives") %>"><%= inv.grants.map { "#{_1.aircraft.tail_number} (#{_1.role.name})" }.join(", ").presence || t(".account_only") %></td>
<td class="tabular-nums" data-label="<%= t(".uses") %>"><%= inv.uses_count %> / <%= inv.max_uses || "∞" %></td>
<td data-label="<%= t(".status") %>">
<% if inv.revoked? %><span class="badge-gray"><%= t(".revoked") %></span>
<% elsif inv.expired? %><span class="badge-red"><%= t(".expired") %></span>
<% elsif inv.used_up? %><span class="badge-gray"><%= t(".used") %></span>
<% else %><span class="badge-green"><%= t(".active") %></span><span class="block text-xs text-slate-500"><%= inv.expires_at ? t(".until", time: l(inv.expires_at, format: :app)) : t(".never_expires") %></span><% end %>
</td>
<td class="text-right"><% if inv.usable? %><%= delete_button t(".revoke"), admin_invitation_path(inv), confirm: t(".revoke_invitation") %><% end %></td>
</tr>
<% end %>
</tbody>
</table>
<% else %>
<%= empty_state t(".no_invitations") %>
<% end %>
</section>
+29
View File
@@ -0,0 +1,29 @@
<% content_for :title, t(".new_invitation") %>
<h1 class="mb-4 text-2xl font-bold"><%= t(".new_invitation") %></h1>
<%= form_with model: @invitation, url: admin_invitations_path, method: :post, class: "card card-body max-w-3xl space-y-5" do |f| %>
<%= f.errors_summary %>
<div class="grid gap-4 sm:grid-cols-2">
<%= f.field :label, required: true, hint: t(".label_hint") %>
<%= f.field :email, as: :email, label: t(".email"), hint: t(".email_hint") %>
<%= f.field :name, label: t(".name"), hint: t(".name_hint") %>
<%= f.field :max_uses, as: :number, label: t(".max_uses"), hint: t(".max_uses_hint"), min: 1, max: 1000 %>
<%= f.field :expires_at, as: :datetime, label: t(".expires"), hint: t(".expires_hint") %>
</div>
<fieldset>
<legend class="mb-2 text-sm font-semibold"><%= t(".roles") %></legend>
<% aircraft = Aircraft.ordered.to_a %>
<% if aircraft.any? %>
<div class="grid gap-2 sm:grid-cols-2">
<% roles = Role.ordered.map { [ _1.name, _1.id ] } %>
<% aircraft.each do |a| %>
<label class="flex items-center justify-between gap-3 text-sm">
<span><span class="font-medium"><%= a.tail_number %></span> <span class="text-xs text-slate-500"><%= [ a.make, a.model ].compact_blank.join(" ") %></span></span>
<%= select_tag "roles[#{a.id}]", options_for_select([ [ t(".no_access"), "" ] ] + roles, params.dig(:roles, a.id.to_s)), class: "input w-36" %>
</label>
<% end %>
</div>
<% end %>
<p class="hint mt-2"><%= t(".roles_hint") %></p>
</fieldset>
<div class="flex flex-wrap gap-2"><%= f.submit t(".create") %><%= link_to t(".cancel"), admin_invitations_path, class: "btn-secondary" %></div>
<% end %>
@@ -2,7 +2,7 @@
Locals: policy, number, adopted_at, adopted_by, revisions, summary. %>
<% info = SystemInfo.new %>
<% aircraft = Aircraft.ordered.includes(:roles) %>
<% users = User.order(:email_address).includes(:certificates, aircraft_roles: :aircraft) %>
<% users = User.order(:email_address).includes(:certificates, aircraft_roles: %i[aircraft role]) %>
<% h2 = "mt-6 text-base font-semibold" %>
<% p_ = "mt-1 text-sm leading-relaxed" %>
<article class="text-slate-900">
@@ -50,7 +50,7 @@
<% users.each do |u| %>
<% current = u.certificates.reject(&:expired?) %>
<tr class="border-b border-slate-100 align-top"><td class="py-1"><%= u.display_name %><div class="text-xs text-slate-500"><%= u.email_address %></div></td>
<td class="text-xs"><%= [ (t(".administrator") if u.admin?), *u.aircraft_roles.map { "#{_1.role.capitalize}, #{_1.aircraft.tail_number}" } ].compact.join("; ").presence || "—" %><%= t(".disabled") if u.disabled? %></td>
<td class="text-xs"><%= [ (t(".administrator") if u.admin?), *u.aircraft_roles.map { "#{_1.role.name}, #{_1.aircraft.tail_number}" } ].compact.join("; ").presence || "—" %><%= t(".disabled") if u.disabled? %></td>
<td class="text-xs"><%= u.certificates.map { "#{_1.short_label} #{_1.number}#{" #{t('.expires_short', date: _1.expires_on)}" if _1.expires_on}" }.join("; ").presence || "—" %></td>
<td class="text-xs"><%= if u.disabled? || current.empty? then t(".no")
elsif current.any?(&:mechanic?) then t(".maintenance_and_inspection_entries")
+27
View File
@@ -0,0 +1,27 @@
<%# A role's name, description and permissions, grouped as in Permission.
Owner's permissions are shown but can't be changed: it always has all. %>
<%= form_with model: [:admin, role], class: "card card-body max-w-3xl space-y-5" do |f| %>
<%= f.errors_summary %>
<div class="grid gap-4 sm:grid-cols-2">
<%= f.field :name, required: true %>
<%= f.field :description, hint: t(".description_hint") %>
</div>
<% if role.owner? %><p class="rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200"><%= t(".owner_has_everything") %></p><% end %>
<%= hidden_field_tag "role[permissions][]", "", id: nil %>
<div class="grid gap-5 sm:grid-cols-2">
<% Permission::GROUPS.each do |group, keys| %>
<fieldset class="space-y-2" <%= "disabled" if role.owner? %>>
<legend class="mb-1 text-sm font-semibold"><%= Permission.group_label(group) %></legend>
<% keys.each do |key| %>
<label class="flex items-start gap-2 text-sm">
<%= check_box_tag "role[permissions][]", key, role.can?(key), id: "permission_#{key}", class: "mt-0.5" %>
<span><%= Permission.label(key) %><span class="block text-xs text-slate-500"><%= Permission.description(key) %></span></span>
</label>
<% end %>
</fieldset>
<% end %>
</div>
<p class="hint"><%= t(".viewing_needs_nothing") %></p>
<div class="flex flex-wrap gap-2"><%= f.submit t(".save") %><%= link_to t(".cancel"), admin_roles_path, class: "btn-secondary" %></div>
<% end %>
<% if role.persisted? && !role.built_in? %><div class="mt-4"><%= delete_button t(".delete_role"), admin_role_path(role), confirm: t(".delete_role_confirm", name: role.name) %></div><% end %>
+3
View File
@@ -0,0 +1,3 @@
<% content_for :title, t(".edit_role", name: @role.name_was) %>
<h1 class="mb-4 text-2xl font-bold"><%= t(".edit_role", name: @role.name_was) %></h1>
<%= render "form", role: @role %>
+15
View File
@@ -0,0 +1,15 @@
<% content_for :title, t(".roles") %>
<div class="mb-2 flex items-center justify-between"><h1 class="text-2xl font-bold"><%= t(".roles") %></h1><%= link_to t(".new_role"), new_admin_role_path, class: "btn-primary" %></div>
<p class="mb-4 text-sm text-slate-600"><%= t(".intro") %></p>
<section class="card"><table class="table">
<thead><tr><th><%= t(".name") %></th><th><%= t(".can") %></th><th class="text-right"><%= t(".people") %></th><th></th></tr></thead>
<tbody><% @roles.each do |role| %><tr class="role-row" id="<%= dom_id(role) %>">
<td class="align-top"><span class="font-medium"><%= role.name %></span> <% if role.built_in? %><span class="badge-gray"><%= t(".built_in") %></span><% end %>
<% if role.description.present? %><div class="text-xs text-slate-500"><%= role.description %></div><% end %></td>
<td class="align-top text-xs text-slate-600" data-label="<%= t(".can") %>">
<%= role.owner? ? t(".everything") : (role.permissions.map { Permission.label(_1) }.to_sentence.presence || t(".view_only")) %>
</td>
<td class="align-top text-right tabular-nums" data-label="<%= t(".people") %>"><%= @counts.fetch(role.id, 0) %></td>
<td class="align-top text-right"><%= link_to t(".edit"), edit_admin_role_path(role), class: "btn-secondary btn-sm" %></td>
</tr><% end %></tbody>
</table></section>
+3
View File
@@ -0,0 +1,3 @@
<% content_for :title, t(".new_role") %>
<h1 class="mb-4 text-2xl font-bold"><%= t(".new_role") %></h1>
<%= render "form", role: @role %>
+8
View File
@@ -38,6 +38,14 @@
<p class="hint"><%= t(".with_off_site_backup_to") %></p>
</div>
<h2 class="card-title pt-2"><%= t(".aircraft") %></h2>
<div>
<%= label_tag "settings[anyone_adds_aircraft]", t(".who_can_add_aircraft"), class: "label" %>
<%= select_tag "settings[anyone_adds_aircraft]", options_for_select([ [ t(".administrators_only"), 0 ], [ t(".everyone"), 1 ] ], @values["anyone_adds_aircraft"].to_i),
id: "settings_anyone_adds_aircraft", class: "input" %>
<p class="hint"><%= t(".who_can_add_aircraft_hint") %></p>
</div>
<h2 class="card-title pt-2"><%= t(".document_search") %></h2>
<div>
<%= label_tag "settings[documents_claude_text]", t(".read_scanned_documents_with"), class: "label" %>
+33
View File
@@ -1,2 +1,35 @@
<h1 class="mb-4 text-2xl font-bold"><%= t(".edit_user") %></h1>
<%= render "form", user: @user %>
<%# Their role on each aircraft (same rules as each aircraft's Access page, AircraftAccess). %>
<section class="card mt-6 max-w-3xl" id="access">
<div class="card-header"><h2 class="card-title"><%= t(".aircraft_access") %></h2></div>
<% roles = Role.ordered.to_a %>
<% memberships = @user.aircraft_roles.includes(:aircraft, :role).sort_by { _1.aircraft.tail_number } %>
<% if memberships.any? %>
<table class="table">
<tbody>
<% memberships.each do |m| %>
<tr>
<td><%= link_to m.aircraft.tail_number, aircraft_path(m.aircraft), class: "link font-medium" %> <span class="text-xs text-slate-500"><%= [ m.aircraft.make, m.aircraft.model ].compact_blank.join(" ") %></span></td>
<td><%= form_with url: admin_user_aircraft_role_path(@user, m), method: :patch do |f| %>
<%= f.select :role_id, roles.map { [ _1.name, _1.id ] }, { selected: m.role_id }, class: "input w-36", "aria-label": t(".role_on", tail_number: m.aircraft.tail_number), data: { submit_on_change: true } %>
<% end %></td>
<td class="text-right"><%= delete_button t(".remove"), admin_user_aircraft_role_path(@user, m), confirm: t(".remove_access", tail_number: m.aircraft.tail_number) %></td>
</tr>
<% end %>
</tbody>
</table>
<% else %>
<%= empty_state t(".no_aircraft") %>
<% end %>
<% others = Aircraft.where.not(id: memberships.map(&:aircraft_id)).ordered %>
<% if others.any? %>
<%= form_with url: admin_user_aircraft_roles_path(@user), class: "flex flex-wrap items-end gap-2 border-t border-slate-100 p-4" do |f| %>
<div><%= f.label :aircraft_id, t(".aircraft"), class: "label" %><%= f.select :aircraft_id, others.map { [ _1.tail_number, _1.id ] }, {}, class: "input" %></div>
<div><%= f.label :role_id, t(".role"), class: "label" %><%= f.select :role_id, roles.map { [ _1.name, _1.id ] }, { selected: Role.for_key("pilot").id }, class: "input w-36" %></div>
<%= f.submit t(".add"), class: "btn-primary" %>
<% end %>
<% end %>
<p class="hint px-4 pb-4"><%= t(".roles_hint_html", link: link_to(t(".roles"), admin_roles_path, class: "link")) %></p>
</section>
+1 -1
View File
@@ -5,7 +5,7 @@
<tbody><% @users.each do |u| %><tr>
<td><%= u.name %> <% if u.admin? %><span class="badge-blue"><%= t(".admin") %></span><% end %><% if u.sso_uid? %> <span class="badge-gray" title="Signs in with <%= Sso.label %>"><%= Sso.label %></span><% end %><% if u.otp_enabled? %> <span class="badge-green" title="<%= t(".authenticator_app_on") %>"><%= t(".n2fa") %></span><% end %><% if u.locked? %> <span class="badge-red" title="<%= t(".too_many_failed_sign_ins") %>"><%= t(".locked") %></span><% end %></td>
<td><%= u.email_address %><% if u.certificates.any? %><div class="text-xs text-slate-500"><%= u.certificates.map { "#{_1.short_label} #{_1.number}" }.join(", ") %></div><% end %></td>
<td class="text-xs"><%= u.aircraft_roles.map { "#{_1.aircraft.tail_number} (#{_1.role})" }.join(", ").presence || "—" %></td>
<td class="text-xs"><%= u.aircraft_roles.map { "#{_1.aircraft.tail_number} (#{_1.role.name})" }.join(", ").presence || "—" %></td>
<td class="text-xs text-slate-500"><%= u.last_signed_in_at ? "#{time_ago_in_words(u.last_signed_in_at)} ago" : "never" %></td>
<td class="whitespace-nowrap text-right">
<% if u.disabled? %><span class="badge-red mr-1"><%= t(".disabled") %></span><%= button_to t(".enable"), enable_admin_user_path(u), method: :patch, class: "btn-secondary btn-sm", form: { class: "inline" } %>
+7 -1
View File
@@ -1,16 +1,22 @@
<% content_for :title, t(".fleet") %>
<div class="mb-5 flex items-center justify-between">
<h1 class="text-2xl font-bold tracking-tight"><%= t(".fleet") %></h1>
<% if current_user.can_add_aircraft? %>
<div class="flex gap-2">
<%= more_menu do %><%= link_to t(".import_from_a_sam_zip"), new_aircraft_import_path, class: "menu-item" %><% end %>
<%= link_to t(".add_aircraft"), new_aircraft_path, class: "btn-primary" %>
</div>
<% end %>
</div>
<% if @aircraft_list.empty? %>
<div class="card card-body text-center">
<p class="text-slate-600"><%= t(".no_aircraft_yet") %></p>
<p class="mt-3"><%= link_to t(".add_your_first_aircraft"), new_aircraft_path, class: "btn-primary" %></p>
<% if current_user.can_add_aircraft? %>
<p class="mt-3"><%= link_to t(".add_your_first_aircraft"), new_aircraft_path, class: "btn-primary" %></p>
<% else %>
<p class="mt-2 text-sm text-slate-500"><%= t(".ask_an_administrator") %></p>
<% end %>
</div>
<% else %>
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
+6 -4
View File
@@ -4,7 +4,7 @@
<div class="grid gap-5 lg:grid-cols-3">
<div class="space-y-5 lg:col-span-2">
<% if owner? %><%= render "aircraft/setup", aircraft: @aircraft %><% end %>
<% if can?(:edit_aircraft) %><%= render "aircraft/setup", aircraft: @aircraft %><% end %>
<section class="card">
<div class="card-header">
<h2 class="card-title"><%= t(".airworthiness") %></h2>
@@ -58,6 +58,7 @@
</div>
<div class="space-y-5">
<% if can?(:update_hours) %>
<section class="card">
<div class="card-header"><h2 class="card-title"><%= t(".update_hours") %></h2></div>
<%= form_with url: hours_aircraft_path(@aircraft), method: :patch, class: "card-body space-y-3",
@@ -69,17 +70,18 @@
<div><%= f.label :hobbs_time, t(".hobbs"), class: "label" %>
<%= f.number_field :hobbs_time, value: @aircraft.hobbs_time, step: 0.1, class: "input", data: { hours_confirm_target: "hobbs" } %></div>
</div>
<p class="hint"><%= t(".enter_the_current_meter_readings_html", link: (link_to t(".log_flight"), new_aircraft_flight_log_path(@aircraft), class: "link")) %></p>
<p class="hint"><%= can?(:log_flights) ? t(".enter_the_current_meter_readings_html", link: (link_to t(".log_flight"), new_aircraft_flight_log_path(@aircraft), class: "link")) : t(".enter_the_current_meter_readings") %></p>
<%= f.submit t(".update_hours"), class: "btn-primary" %>
<% end %>
</section>
<% end %>
<%= render "aircraft/last_flight", aircraft: @aircraft, last_day: @last_day %>
<section class="card">
<div class="card-header">
<h2 class="card-title"><%= t(".details") %></h2>
<% if owner? %><%= link_to t(".edit"), edit_aircraft_path(@aircraft), class: "btn-secondary btn-sm" %><% end %>
<% if can?(:edit_aircraft) %><%= link_to t(".edit"), edit_aircraft_path(@aircraft), class: "btn-secondary btn-sm" %><% end %>
</div>
<dl class="card-body grid grid-cols-2 gap-x-3 gap-y-2 text-sm">
<dt class="text-slate-500"><%= t(".serial") %></dt><dd><%= @aircraft.serial_number.presence || "—" %></dd>
@@ -94,7 +96,7 @@
<section class="card">
<div class="card-header"><h2 class="card-title"><%= t(".notes") %></h2>
<%= link_to t(".add"), new_aircraft_note_path(@aircraft), class: "btn-secondary btn-sm" %></div>
<% if can?(:write_notes) %><%= link_to t(".add"), new_aircraft_note_path(@aircraft), class: "btn-secondary btn-sm" %><% end %></div>
<% if @notes.any? %>
<ul class="divide-y divide-slate-100">
<% @notes.each do |note| %>
+24 -6
View File
@@ -2,31 +2,46 @@
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<h2 class="mb-4 text-lg font-semibold"><%= t(".access_sharing_html") %></h2>
<div class="grid gap-5 lg:grid-cols-2">
<% if can?(:manage_people) %>
<section class="card">
<div class="card-header"><h2 class="card-title"><%= t(".people") %></h2></div>
<% roles = @access.assignable_roles %>
<table class="table">
<tbody>
<% @roles.each do |r| %>
<tr>
<td><%= r.user.display_name %><div class="text-xs text-slate-500"><%= r.user.email_address %></div></td>
<td>
<%= form_with url: aircraft_aircraft_role_path(@aircraft, r), method: :patch do |f| %>
<%= f.select :role, AircraftRole::ROLES.invert, { selected: r.role }, class: "input w-28", data: { submit_on_change: true } %>
<% if roles.include?(r.role) && (r.user != current_user || current_user.admin?) %>
<%= form_with url: aircraft_aircraft_role_path(@aircraft, r), method: :patch do |f| %>
<%= f.select :role_id, roles.map { [ _1.name, _1.id ] }, { selected: r.role_id }, class: "input w-36", "aria-label": t(".role_for", display_name: r.user.display_name), data: { submit_on_change: true } %>
<% end %>
<% else %>
<span class="badge-gray" title="<%= r.role.description %>"><%= r.role.name %></span>
<% end %>
</td>
<td class="text-right"><% unless r.user == current_user %><%= delete_button t(".remove"), aircraft_aircraft_role_path(@aircraft, r), confirm: t(".remove_s_access", display_name: r.user.display_name) %><% end %></td>
<td class="text-right"><% if r.user != current_user && roles.include?(r.role) %><%= delete_button t(".remove"), aircraft_aircraft_role_path(@aircraft, r), confirm: t(".remove_s_access", display_name: r.user.display_name) %><% end %></td>
</tr>
<% end %>
</tbody>
</table>
<%= form_with url: aircraft_aircraft_roles_path(@aircraft), class: "flex flex-wrap items-end gap-2 border-t border-slate-100 p-4" do |f| %>
<div class="flex-1"><%= f.label :email_address, t(".add_by_email"), class: "label" %><%= f.email_field :email_address, class: "input", required: true %></div>
<%= f.select :role, AircraftRole::ROLES.invert, { selected: "pilot" }, class: "input w-28" %>
<div class="w-full sm:w-auto sm:flex-1"><%= f.label :email_address, t(".add_by_email"), class: "label" %><%= f.email_field :email_address, class: "input", required: true %></div>
<%= f.select :role_id, roles.map { [ _1.name, _1.id ] }, { selected: Role.for_key("pilot").id }, class: "input w-36", "aria-label": t(".role") %>
<%= f.submit t(".add"), class: "btn-primary" %>
<% end %>
<p class="px-4 pb-4 hint"><%= t(".owners_can_edit_everything_pilots_html") %></p>
<details class="px-4 pb-4 text-sm">
<summary class="cursor-pointer text-slate-600"><%= t(".what_each_role_can_do") %></summary>
<dl class="mt-2 space-y-1">
<% Role.ordered.each do |role| %><div><dt class="inline font-semibold"><%= role.name %>:</dt> <dd class="inline text-slate-600"><%= role.description.presence || role.permissions.map { Permission.label(_1) }.to_sentence %></dd></div><% end %>
</dl>
<p class="hint mt-2"><%= t(".roles_are_set_by_an_administrator") %></p>
</details>
</section>
<% end %>
<% if can?(:manage_sharing) %>
<section class="card">
<div class="card-header"><h2 class="card-title"><%= t(".share_links") %></h2></div>
<% if @share_tokens.any? %>
@@ -59,7 +74,9 @@
<%= f.submit t(".create_share_link") %>
<% end %>
</section>
<% end %>
<% if can?(:export_data) %>
<section class="card lg:col-span-2">
<div class="card-header">
<div>
@@ -76,4 +93,5 @@
<%= link_to t(".download_records_package"), aircraft_records_package_path(@aircraft), class: "btn-secondary", data: { turbo: false } %>
</div>
</section>
<% end %>
</div>
@@ -3,7 +3,7 @@
<section class="card">
<div class="card-header">
<h2 class="card-title"><%= t(".airworthiness_directives_bulletins") %></h2>
<% if owner? %>
<% if can?(:manage_ads) %>
<div class="flex flex-wrap items-center gap-2">
<% if @attachable.any? %>
<%= form_with url: attach_aircraft_airworthiness_directives_path(@aircraft), class: "flex gap-2" do |f| %>
@@ -34,7 +34,7 @@
<td class="text-xs"><%= [row.next_due_date && l(row.next_due_date, format: :month_year), row.next_due_hours && t(".due_hours", hours: hours(row.next_due_hours), meter: Aircraft::TIME_BASES[@aircraft.time_basis].downcase, left: hours(row.next_due_hours - @aircraft.current_hours))].compact.join(" / ").presence || "—" %></td>
<td><%= compliance_badge(row.status) %></td>
<td class="whitespace-nowrap text-right">
<% if owner? %>
<% if can?(:manage_ads) %>
<%= link_to t(".comply"), new_aircraft_ad_compliance_path(@aircraft, ad_id: ad.id), class: "btn-secondary btn-sm" %>
<% if row.status.in?(%w[no_compliance overdue due_soon conditional]) %><%= link_to "N/A", new_aircraft_ad_compliance_path(@aircraft, ad_id: ad.id, not_applicable: 1), class: "btn-secondary btn-sm", title: t(".record_that_this_ad_doesn") %><% end %>
<%= link_to t(".edit"), edit_aircraft_airworthiness_directive_path(@aircraft, ad), class: "btn-secondary btn-sm" %>
@@ -58,7 +58,7 @@
<h2 class="card-title"><%= t(".ad_baseline_from_faa_drs") %></h2>
<p class="text-xs text-slate-500"><%= t(".the_full_list_comes_from") %></p>
</div>
<% if owner? %><%= link_to t(".import_from_faa_drs"), new_aircraft_ad_import_path(@aircraft), class: "btn-secondary btn-sm" %><% end %>
<% if can?(:manage_ads) %><%= link_to t(".import_from_faa_drs"), new_aircraft_ad_import_path(@aircraft), class: "btn-secondary btn-sm" %><% end %>
</div>
<div class="card-body space-y-2 text-sm">
<% if last_drs %>
@@ -77,7 +77,7 @@
<h2 class="card-title"><%= t(".newly_published_ads_that_may") %></h2>
<p class="text-xs text-slate-500"><%= t(".searched_weekly_in_the_federal_html", components: (AdWatch.new(@aircraft).terms.map(&:label).uniq.to_sentence.presence || t(".the_aircraft_and_its_installed")), ad_watch_checked_at: (t(".last_checked_ago", ad_watch_checked_at: (time_ago_in_words(@aircraft.ad_watch_checked_at))) if @aircraft.ad_watch_checked_at)) %></p>
</div>
<% if owner? %><%= button_to t(".check_now"), check_aircraft_ad_alerts_path(@aircraft), class: "btn-secondary btn-sm", data: { turbo_submits_with: t(".checking") } %><% end %>
<% if can?(:manage_ads) %><%= button_to t(".check_now"), check_aircraft_ad_alerts_path(@aircraft), class: "btn-secondary btn-sm", data: { turbo_submits_with: t(".checking") } %><% end %>
</div>
<% if @alerts.any? %>
<ul class="divide-y divide-slate-100">
@@ -89,7 +89,7 @@
<p class="mt-1 text-xs text-slate-600"><%= alert.abstract.to_s.truncate(400) %></p>
<%= link_to t(".read_it_in_the_federal"), alert.html_url, class: "link text-xs", target: "_blank", rel: "noopener" %>
</div>
<% if owner? %>
<% if can?(:manage_ads) %>
<div class="flex gap-2">
<%= button_to t(".track"), track_aircraft_ad_alert_path(@aircraft, alert), class: "btn-primary btn-sm", title: t(".add_it_to_this_aircraft") %>
<%= button_to t(".dismiss"), dismiss_aircraft_ad_alert_path(@aircraft, alert), class: "btn-secondary btn-sm", title: t(".doesn_t_apply") %>
@@ -101,7 +101,7 @@
<% else %>
<%= empty_state t(".nothing_new_to_review") %>
<% end %>
<% if owner? %>
<% if can?(:manage_ads) %>
<%= form_with url: terms_aircraft_ad_alerts_path(@aircraft), method: :patch, class: "flex flex-wrap items-end gap-2 border-t border-slate-100 px-4 py-3" do %>
<div class="min-w-0 flex-1">
<%= label_tag :ad_watch_terms, t(".additional_search_terms"), class: "label" %>
@@ -140,7 +140,7 @@
</div>
<% end %>
</td>
<td class="text-right"><% if owner? %><%= link_to t(".edit"), edit_aircraft_ad_compliance_path(@aircraft, c), class: "btn-secondary btn-sm" %><% end %></td>
<td class="text-right"><% if can?(:manage_ads) %><%= link_to t(".edit"), edit_aircraft_ad_compliance_path(@aircraft, c), class: "btn-secondary btn-sm" %><% end %></td>
</tr>
<% end %>
</tbody>
+2 -2
View File
@@ -6,7 +6,7 @@
<div class="flex items-center gap-3">
<%= link_to (@show_disposed ? t(".hide_disposed") : t(".show_disposed")),
aircraft_components_path(@aircraft, disposed: (@show_disposed ? nil : 1)), class: "link text-sm" %>
<% if owner? %><%= link_to t(".add_component"), new_aircraft_component_path(@aircraft), class: "btn-primary" %><% end %>
<% if can?(:manage_components) %><%= link_to t(".add_component"), new_aircraft_component_path(@aircraft), class: "btn-primary" %><% end %>
</div>
</div>
<% if @rows.empty? %>
@@ -39,7 +39,7 @@
</td>
<td><%= life_badge(c.life_status) %></td>
<td class="whitespace-nowrap text-right">
<% if owner? %>
<% if can?(:manage_components) %>
<%= link_to t(".edit"), edit_aircraft_component_path(@aircraft, c), class: "btn-secondary btn-sm" %>
<%= link_to t(".service"), aircraft_component_path(@aircraft, c, anchor: "service"), class: "btn-secondary btn-sm" %>
<% end %>
+4 -4
View File
@@ -4,7 +4,7 @@
<section class="card lg:col-span-2">
<div class="card-header">
<h2 class="card-title"><%= @component %> <%= life_badge(@component.life_status) %></h2>
<% if owner? %>
<% if can?(:manage_components) %>
<div class="flex gap-2">
<%= link_to t(".sub_component"), new_aircraft_component_path(@aircraft, parent_id: @component.id), class: "btn-secondary btn-sm" %>
<%= link_to t(".edit"), edit_aircraft_component_path(@aircraft, @component), class: "btn-secondary btn-sm" %>
@@ -37,7 +37,7 @@
<% if @component.notes.present? %><div class="border-t border-slate-100 px-4 py-3 text-sm"><%= simple_format @component.notes %></div><% end %>
</section>
<% if owner? %>
<% if can?(:manage_components) %>
<section class="card" id="service">
<div class="card-header"><h2 class="card-title"><%= t(".service_replace") %></h2></div>
<%= form_with url: reset_service_aircraft_component_path(@aircraft, @component), method: :post, class: "card-body space-y-3",
@@ -53,11 +53,11 @@
<% end %>
</div>
<% if @inspection_rows.any? || owner? %>
<% if @inspection_rows.any? || can?(:manage_inspections) %>
<section class="card mt-5" id="inspections">
<div class="card-header">
<h2 class="card-title"><%= t(".inspections_of_this_component") %></h2>
<% if owner? %><%= link_to t(".inspection"), new_aircraft_inspection_type_path(@aircraft, component_id: @component.id), class: "btn-secondary btn-sm" %><% end %>
<% if can?(:manage_inspections) %><%= link_to t(".inspection"), new_aircraft_inspection_type_path(@aircraft, component_id: @component.id), class: "btn-secondary btn-sm" %><% end %>
</div>
<% if @inspection_rows.any? %>
<table class="table">
@@ -20,7 +20,7 @@
<td class="truncate" data-label="Product"><%= r.consumable_type %></td>
<td class="text-right tabular-nums" data-label="Tach"><%= hours(r.flight_hours) %></td>
<td class="text-xs text-slate-500 break-words"><%= r.notes %><%= t(".excluded_from_average") if r.excluded_from_averages? %></td>
<td class="text-right"><% if owner? %><%= link_to t(".edit"), edit_aircraft_consumable_record_path(@aircraft, r), class: "btn-secondary btn-sm" %><% end %></td>
<td class="text-right"><% if can?(:manage_consumables) %><%= link_to t(".edit"), edit_aircraft_consumable_record_path(@aircraft, r), class: "btn-secondary btn-sm" %><% end %></td>
</tr>
<% end %>
</tbody>
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff. Show more