43 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
rickyandClaude Opus 5.5 34879e7310 2026.11.6: PDFs on phones, connection status, weak signal, activity paging, REST API
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:40:10 -05:00
rickyandClaude Opus 5.5 e8b0cd030e What's new stays short as releases pile up
- Admin → About shows the running version's release notes, with a link
  to all releases.
- The What's new page keeps the running version (and any newer) open and
  folds each older release to one line, grouped by month: its version
  and a count of its changes, fixes and notes for administrators.
- CHANGELOG.md itself is unchanged and reads the same on GitHub; the
  app splits it into releases when shown (Changelog).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:38:45 -05:00
rickyandClaude Opus 5.5 e4bc3a5b7b Weak signal counts as no signal
With a signal so weak requests hang, the phone still says it's online, so
nothing fell back: Log Flight waited minutes with no feedback, and pages
never reached the offline page.

- Log Flight and Report Squawk say "Sending…" and, after 10 seconds
  without an answer (60 with photos), keep the entry on the device as
  with no signal. When the top bar is already red they keep it right
  away. If it got through after all, the copy sent later is dropped
  (same client_key).
- What's kept on the device isn't sent while the top bar is red, gives
  up after 15 seconds, and goes again as soon as the server answers.
- Every page of the app falls back to its kept copy or the offline page:
  after 10 seconds, then 3 while requests keep failing, and at once right
  after a failure. Downloads made while you wait (.sam.zip, records
  package, PDFs) have no time limit.

Checked on an Android 14 emulator with a connection that accepts
requests and never answers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:34:13 -05:00
rickyandClaude Opus 5.5 d9de1be562 Connection status in the top bar, as SilverBullet does
- The top bar (and the phone's status bar) turns red when the server
  can't be reached: the device is offline, or a request failed (signal
  but no internet, or the proxy answering for the app). While red it
  checks /up every 15 seconds and turns back on its own.
- A ring fills while pages are saved for offline use or flights and
  squawks logged offline are sent, with the percentage in its middle,
  and hides when done. While some wait to send, it's amber with how many.

Checked on an Android 14 emulator: airplane mode on and off, saving for
offline, and a flight logged offline then sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:15:50 -05:00
rickyandClaude Opus 5.5 66fa5f4423 PDFs show on phones, drawn with PDF.js
Android shows nothing for a PDF in a frame and iPhones only its first
page. On touch screens the document viewer now draws every page with
PDF.js 6.5.438 (vendored in public/pdfjs/<version>/, loaded only there);
desktop browsers keep their own viewer in the frame.

- Pages are drawn as they come near the screen and let go once far from
  it, so a long manual doesn't use up a phone's memory.
- Only the parts of the file those pages need are downloaded: uploaded
  files now send Accept-Ranges, and PDF.js's background fetch of the
  whole file is off.
- JBIG2/JPEG 2000 scans decode (wasm, with JS fallbacks).

Checked on an Android 14 emulator with Chromium 160 (which reports
pdfViewerEnabled but can't show a PDF in a frame).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:15:45 -05:00
rickyandClaude Opus 5.5 2e8d789975 Activity log loads as you scroll
The activity log stopped at 200 events. It now loads 50 at a time, the
next page coming in a lazy frame as it scrolls into view (as Oil & Fuel
does), keeping the category filter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:15:33 -05:00
rickyandClaude Opus 5.5 e4c27c6ff7 API: draft logbook entries for signing
- POST /aircraft/:id/draft_batches turns a visit's work items into one
  unsigned entry per logbook, signed in the app (by a user with a
  certificate, or a mechanic through a returned or emailed invitation link).
- The squawks they resolve and inspections they complete (with their result)
  are held until every entry is signed, then applied, attributed to the last
  signer; draft_batch.completed webhook. A draft never clears a squawk alone.
- Drafts are for owners (integrations act for one, drafts:write scope);
  unsigned drafts can be withdrawn; lookup by external_ref.
- The signing and entry pages show where a draft came from and what signing
  will do.
- The suggested recordkeeping procedures describe the API once it's in use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 19:11:38 -05:00
rickyandClaude Opus 5.5 bffdea937c REST API v1: tokens, read endpoints, squawks, webhooks
- Personal tokens (Profile → API tokens) act as their owner; integration
  tokens (Admin → Integrations) reach chosen aircraft and scopes, and their
  writes name the person they're for (SAM-On-Behalf-Of). Tokens are stored
  hashed, shown once, revocable, with last use recorded.
- GET aircraft, components, due list, inspections, ADs, logbook entries and
  squawks; POST/PATCH squawks with external_ref links to the other system.
- Idempotency-Key for safe retries, paging, JSON errors, rate limits.
- Record history keeps the token with each change (in the hashed payload).
- Webhooks (squawk created/updated/resolved, entry signed), HMAC-signed,
  retried, never sent to the server itself; deliveries listed for admins.
- The outbound address check is shared by AirTrail and webhooks; reporting a
  squawk is announced the same way from the form and the API.
- docs/guide/api.md: the API reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 19:05:10 -05:00
rickyandClaude Opus 5.5 ec0f43019f Favicon matches the app icon
The white plane in a blue ring on the dark rounded square, tuned to read
at 16 px, instead of the plane emoji (which looked different everywhere).
Adds favicon.ico (16/32/48) for browsers and tools that ask for it, busts
the cached SVG with ?v=2, and keeps it with the offline page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 14:37:30 -05:00
rickyandClaude Opus 5.5 291990412e 2026.11.5: faster photos, phone-friendly cards, profile layout, push diagnostics, hardening
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:33:22 -05:00
rickyandClaude Opus 5.5 a2672b99a3 Restore thumbnails for photos recorded without dimensions
Photos uploaded before image processing was installed are marked analyzed
with no width, so the "unreadable image" check showed them as file links.
Every resizable image gets a thumbnail again; one that can't be read still
falls back to the original when resizing fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:26:28 -05:00
rickyandClaude Opus 5.5 908c943e21 Fix crashes found by fuzzing malformed input
- Components can't be made into a parent loop, and the parts tree walks
  stop safely if one exists (logbook entry and squawk resolution pages
  crashed).
- A rejected aircraft photo no longer breaks the edit page; empty photos
  are refused; images that can't be read aren't resized, and a failed
  resize sends the original instead of an error.
- Unsupported formats (/report.pdf…) answer 406; tampered upload
  references, out-of-range numbers and constraint violations get a form
  message instead of a 500; requests with null bytes are refused (400).
- Blank values in required columns with defaults take the default;
  optional links to records that don't exist are validation errors.
- Imports (oil report, logbook scans, .sam.zip) accept only uploaded files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:17:43 -05:00
rickyandClaude Opus 5.5 5876c07a1a Harden installs reachable from the internet without a proxy
- Refuse to start with a placeholder or short SECRET_KEY_BASE (under 32
  characters); warn and fail sam:doctor under 64. .env.example no longer
  ships a placeholder.
- First-run setup needs a one-time code printed only in the server log, so
  only whoever runs the server can create the admin account.
- AirTrail: the server resolves the address and connects to exactly that;
  never the server itself or link-local addresses (cloud metadata);
  private-network addresses only for admins or hosts in
  AIRTRAIL_ALLOWED_HOSTS.
- Host authorization when APP_HOST is set: APP_HOST, the APP_URL host,
  ALLOWED_HOSTS, localhost and IP addresses; /up exempt. A blocked name
  gets a short explanation instead of a blank 403.
- docker-compose.direct.yml: HTTPS without a proxy via Thruster's built-in
  Let's Encrypt (TLS_DOMAIN).
- Notes' Markdown no longer allows the unused class attribute.
- README, .env.example and the user guide updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:42:53 -05:00
rickyandClaude Opus 5.5 faae719b12 Profile: two columns on wide screens
The account and its security (sign-on, two-factor, sessions) on the left,
calendar, certificates, this device and integrations on the right; one
column on phones. The account form gets a title like the other cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:10:32 -05:00
ricky e199e6feeb Add LICENSE file with public domain declaration 2026-11-14 12:07:29 -05:00
rickyandClaude Opus 5.5 d4b71d17a1 Smaller aircraft photos, one-row-per-item detail cards, push diagnostics
- Aircraft photos get 192px and 960x432 copies made on upload; the header,
  share page and Fleet cards use them (and the offline copies), instead of
  the full original.
- Flight, engine data, component and major record details show one label
  and value per row on phones (wide items no longer add grid columns).
- Profile re-records this device's push subscription on every visit, and
  says why if it can't; Send test delivers now and lists each device's
  result; Google's other push hosts are accepted; turning notifications on
  shows the browser's actual error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 11:55:11 -05:00
rickyandClaude Opus 5.5 3f314a13bb 2026.11.4: time zones, Update Hours confirmation, squawk thumbnails, workflow polish
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:51:22 -05:00
rickyandClaude Opus 5.5 9662c7ae16 Time zones: each person's own, and TZ for the installation
- Requests run in the viewer's zone: Profile -> Time zone, else their
  device's (a tz cookie set from the browser), else the installation's;
  times show in it and "today" is the local date (a new flight's date)
- Docker's TZ sets the installation zone (default UTC): scheduled jobs run
  on its clock (recurring.yml), and it's used before a device's zone is known
- The weekly reminder email is worked out in the recipient's zone
- Signatures, record history and exports keep exact UTC timestamps
- users.time_zone; README, .env.example and guide updated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:49:22 -05:00
rickyandClaude Opus 5.5 03b9ad65cb Workflow polish: setup checklist, next leg, grouped component limits
- Setup checklist on a new aircraft's Overview (owners): components,
  standard inspections, DRS AD import, registration/airworthiness
  certificate, weight and balance; hideable per device
- Log Flight: "Save and log next leg" reopens the form on the same date,
  starting where the leg ended
- Component form: limits in two collapsible groups (replacement and expiry;
  overhaul and TBO), open when in use
- Squawk form warns what "Ground Aircraft" does
- Logbook entry form: inspection result only for inspection entries
  (show-when controller); document names default from the file
- Dates in pickers, the activity log, airworthiness lines, search, audits
  and transcription notes use the app format
- No duplicate Report Squawk button on Squawks; "Record service" label

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:43:03 -05:00
rickyandClaude Opus 5.5 3452a35896 Aircraft description stays inside the Details card
simple_format makes paragraphs, so the padded box around them is a div:
inside a <p> the browser closed it early and the text spilled out unstyled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:22:30 -05:00
rickyandClaude Opus 5.5 79a64cc208 Squawk photos as thumbnails
- Photos show as 64px thumbnails (160px resized copies, made once with
  libvips and kept; lazy-loaded) that open the in-app viewer, which has
  Download; other files keep their name chip and download link
- image_processing gem and the vips variant processor (libvips was already
  in the image)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:16:46 -05:00
rickyandClaude Opus 5.5 9d3643df33 Sticky solid top bar so iPadOS doesn't blur it in the home-screen app
iOS/iPadOS 26 draws a blur over the top of home-screen web apps; with a
solid, full-width bar stuck to the top edge WebKit extends its color
instead. The status banners now sit just below the bar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:01:12 -05:00
rickyandClaude Opus 5.5 cce1ce51b5 Confirm Update Hours and say what changed
- Updating the meters without a flight asks first, showing each reading's
  change, that every in-service component moves and no flight is logged,
  and a warning when a reading goes down; unchanged readings aren't sent
- The flash lists each changed reading (old -> new, difference) and how far
  the components moved; a lowered reading is labelled a correction

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 06:51:22 -05:00
rickyandClaude Opus 5.5 f534541467 2026.11.3: installed app works offline, notifications, More menus, translatable text
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:40:49 -05:00
rickyandClaude Opus 5.5 8d5f57da81 Installed app: offline squawks and pre-flight pages, push notifications, shortcuts
Offline
- Flights and squawks saved offline are tagged with their user and only sent
  while that user is signed in; storage is made persistent; Background Sync
  sends them with the app closed (Chromium); unsent count on the app badge
- Report Squawk works offline (photos included, one-time key like flights)
- The Fleet page and, for each of your aircraft, the Overview, W&B, Log
  Flight and Report Squawk pages and photo are saved ahead of time, so the
  app opens and works without signal; copies say when they were saved
- Sign-out clears saved forms, pages and photos (asks first if items wait)
- Offline page rendered by Rails (localized, follows the theme, no inline
  script); service worker version follows the build

Install and notify
- Web Push (web-push gem, VAPID keys from env or storage/vapid_keys.json):
  grounding squawks, newly overdue items (daily, once each), signing
  requests; per-device on/off and test in Profile -> This device; only
  browser push service endpoints accepted
- Manifest shortcuts (Log Flight, Report Squawk via /go/...), lang and
  localized description; install help on Profile; reload notice after a
  release

Also
- Dockerfile: libssl-dev in the build stage (openssl gem); lockfile checksums
- Leftover English and %{_} interpolation names from the localization pass
- Guide and README updated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:39:42 -05:00
rickyandClaude Opus 5.5 89ed0a76f9 Move all user-facing text into config/locales/en.yml for localization
- Views use lazy t(".key") lookups; sentences with values or links stay
  whole (interpolation, _html keys); counts use one/other plurals
- Stored-value labels (statuses, types, priorities...) are LabelSets read
  from labels: in the current locale; field names and validation messages
  under activerecord:; flash and activity text under flash:
- Services, models, helpers, mailer subjects, the logbook PDF, procedures
  templates, records package README and transcription warnings localized;
  the PDF reuses LogbookEntry#certification_statement instead of a copy
- Scripts read js: strings from a JSON tag via app/javascript/i18n.js
- Dates through I18n.l (app, weekday, month_year, long formats); html lang
  follows the locale
- APP_LOCALE picks the language (falls back to English); missing
  translations raise in development and tests
- README: Translating section and APP_LOCALE

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:08:20 -05:00
rickyandClaude Opus 5.5 3f45b557c2 Secondary actions behind More menus; tidier aircraft header and tabs
- more_menu helper (menu / menu-item styles): each section keeps its main
  action as a button; imports, exports, printing and tools move under More
  (flights, logbook, logbook entry, documents, inspections, fleet)
- Aircraft header: More with status report and, for owners, access &
  sharing, edit, .sam.zip and records package; Access & Sharing and Oil
  Analysis tabs removed (oil analysis is under Oil & Fuel with a switch)
- Logbook: Print selected appears once an entry is ticked; filters apply on
  change; dates use fmt_date (also AirTrail, notes, audits, About)
- Header shows the role on the aircraft and hides the usual Available badge;
  no second Grounded badge on the Overview; AD DRS import listed once
- Flights: stat cards 2x2 on phones; By year opens visibly, only with more
  than one year; duplicate + Log Flight removed
- Remove unused hello_controller.js; guide and README updated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 21:21:57 -05:00
rickyandClaude Opus 5.5 bff6a05173 Remove orphaned code and unused Solid Cable; simplify compliance status
- Delete methods nothing calls: BackupRun.last_good, EntrySignature#short_id,
  Sso#issuer_origin, InspectionType#effect_label and #latest_record_for,
  ApplicationHelper#airworthiness_dot, Airworthiness::Status#can_fly? and
  FlightStats#shortest_flight (tests now check red? / longest_flight)
- Routes: sessions and passwords limited to the actions that exist
- Theme toggle: drop the unused button target
- Action Cable was never used (no broadcasts or streams): async adapter in
  production, solid_cable gem, cable database and app/channels removed
- Empty system test setup removed with capybara and selenium-webdriver
- Compliance: one due_result helper for overdue / due soon; inspections use
  next_due for the date, as ADs do
- applicable_to moved into SharedRecordHistory (was identical in ADs and
  inspection types)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 21:04:41 -05:00
553 changed files with 15663 additions and 3521 deletions

No files matched your search

+35 -6
View File
@@ -2,16 +2,32 @@
# block is required. Every setting is explained in the README. # block is required. Every setting is explained in the README.
# --- Required ---------------------------------------------------------- # --- Required ----------------------------------------------------------
# Generate with: bin/rails secret (or: openssl rand -hex 64) # Generate with: bin/rails secret (or: openssl rand -hex 64). Anyone who knows
# Keep a copy somewhere safe off the server: signatures and stored secrets # it can sign in as anyone, so the app won't start with a placeholder or a
# depend on it, and a restore needs the same one. # short one. Keep a copy somewhere safe off the server: signatures and stored
SECRET_KEY_BASE=change-me # secrets depend on it, and a restore needs the same one.
SECRET_KEY_BASE=
# The host name people use to reach the app (used in email links). # The host name people use to reach the app (used in email links).
APP_HOST=aircraft.example.com APP_HOST=aircraft.example.com
# The installation's time zone (scheduled jobs run on its clock; people see
# their own zone, from Profile or their device). Default UTC.
# TZ=America/New_York
# true: the app redirects to HTTPS and sets secure cookies (use behind a TLS # true: the app redirects to HTTPS and sets secure cookies (use behind a TLS
# proxy such as Traefik, Caddy or Cloudflare Tunnel). false: plain HTTP on a LAN. # proxy such as Traefik, Caddy or Cloudflare Tunnel, or with TLS_DOMAIN).
# false: plain HTTP, only on a private network: passwords travel unencrypted.
FORCE_SSL=true FORCE_SSL=true
# --- HTTPS without a proxy (docker-compose.direct.yml) -------------------
# The app gets a Let's Encrypt certificate for this name itself (ports 80
# and 443 must reach it).
# TLS_DOMAIN=aircraft.example.com
# --- Allowed addresses ---------------------------------------------------
# Requests are answered only for APP_HOST (and the APP_URL host), localhost
# and IP addresses. Other names that should work, comma-separated:
# ALLOWED_HOSTS=sam.lan,aircraft.home.arpa
# --- Address ----------------------------------------------------------- # --- Address -----------------------------------------------------------
# Full public URL, if it isn't https://APP_HOST (used for the single sign-on # Full public URL, if it isn't https://APP_HOST (used for the single sign-on
# and Google Drive redirect URIs). # and Google Drive redirect URIs).
@@ -30,9 +46,14 @@ FORCE_SSL=true
# OIDC_CLIENT_ID= # OIDC_CLIENT_ID=
# OIDC_CLIENT_SECRET= # OIDC_CLIENT_SECRET=
# OIDC_PROVIDER_NAME=Authentik # 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_TRUST_EMAIL=false # true: link accounts by unverified email
# OIDC_ADMIN_GROUP= # members become admins (synced at sign-in) # OIDC_ADMIN_GROUP= # members become admins (synced at sign-in)
# --- AirTrail ------------------------------------------------------------
# AirTrail servers on your private network that everyone may connect to
# (admins can always use private addresses), comma-separated host names:
# AIRTRAIL_ALLOWED_HOSTS=airtrail.lan
# PASSWORD_LOGIN=true # false: SSO only (invited mechanics then can't sign in) # PASSWORD_LOGIN=true # false: SSO only (invited mechanics then can't sign in)
# --- Sign-in security ---------------------------------------------------- # --- Sign-in security ----------------------------------------------------
@@ -43,6 +64,14 @@ FORCE_SSL=true
# LOGBOOK_AI_MODEL=claude-opus-5-5 # LOGBOOK_AI_MODEL=claude-opus-5-5
# LOGBOOK_AI_EFFORT=high # 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 --------------------------------------------------------------- # --- 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_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 # RAILS_LOG_LEVEL=info
+110
View File
@@ -2,6 +2,116 @@
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. 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
- **PDFs show on phones.** Android showed nothing for a PDF document and iPhones only its first page. On phones and tablets every page is now drawn in the app, as it scrolls into view, downloading only the parts of the file those pages need (a long manual opens quickly and doesn't use up mobile data). Computers keep the browser's own PDF viewer.
- **Connection status in the top bar.** It turns red when the server can't be reached, and back on its own when it can. A ring fills while pages are saved for offline use or what was logged offline is sent; it's amber with a count while flights or squawks wait to send.
- **A weak signal counts as no signal.** Log Flight and Report Squawk say "Sending…" and, if the server doesn't answer within 10 seconds (a minute with photos), keep the entry on the phone and send it when the connection's back. If it got through after all, it isn't logged twice. Every page falls back to its offline copy or the offline page instead of loading forever.
- **The activity log loads as you scroll** (it stopped at 200 events).
- **What's new** shows the running version's notes on Admin → About; older releases fold to one line each.
- **REST API** for other programs, such as a script that pulls what's coming due or a work-order system: read aircraft, parts, due items, inspections, ADs, squawks and logbook entries; report and update squawks; send draft logbook entries to be signed in the app. Webhooks announce squawks reported, updated and resolved, entries signed, and drafts completed. Personal tokens are made in Profile. The API never signs an entry; see Help → REST API.
### For administrators
- **Admin → Integrations** makes tokens for other systems, acting for the person each request names, limited to the aircraft chosen, plus webhook endpoints.
- The update adds the API's tables; they're created automatically when the new version starts.
## 2026.11.5
### Changes
- **Faster photos.** Aircraft photos load as small copies on the Fleet page and the aircraft header (they were the full original, slow on mobile). The offline copies use the small versions too.
- **Detail cards read one item per row on a phone**: flights, engine data, components and major repairs and alterations. Wider screens show two columns.
- **Profile uses the width of a desktop screen**: your account and its security on the left; calendar, certificates, this device and integrations on the right.
- **Notifications:** opening Profile on a device records its notification subscription again, so a device whose subscription was never saved starts receiving them. **Send test** lists each device and whether its push service accepted the notification, with the reason if not. If turning notifications on fails, the browser's error is shown.
### For administrators
- **The app won't start with a placeholder or short `SECRET_KEY_BASE`** (under 32 characters), since anyone who knows it can sign in as anyone. `sam:doctor` flags one under 64 characters. Use the output of `bin/rails secret`.
- **First-run setup asks for a one-time code** printed in the server log (`docker compose logs web | grep "Setup code"`), so only whoever runs the server can create the admin account.
- **HTTPS without a proxy:** `docker-compose.direct.yml` with `TLS_DOMAIN` gets and renews a Let's Encrypt certificate by itself.
- **The app answers only for its own names** when `APP_HOST` is set: `APP_HOST`, the `APP_URL` host, `localhost`, IP addresses, and any names listed in the new `ALLOWED_HOSTS`. Other names get a short explanation. If you reach the app by another name (such as a LAN name), add it to `ALLOWED_HOSTS`.
- **AirTrail servers on a private network** can be connected only by an administrator, or by anyone when listed in `AIRTRAIL_ALLOWED_HOSTS`. The server itself and link-local addresses are always refused.
- The project is released into the public domain (LICENSE, The Unlicense).
### Fixes
- A file that isn't a photo, or an empty one, chosen as the aircraft photo now shows "must be an image" instead of an error page. An image that can't be read is shown as the original file.
- A component can't be set as a part of its own parts; that made the logbook entry and squawk resolution pages fail.
- Many malformed requests that caused error pages now get a proper answer: pages requested in another format, blank required values, links to records that don't exist, numbers too large to store, and text sent where a file belongs.
## 2026.11.4
### Changes
- **Time zones.** Times show in your own zone and "today" is your local date (a new flight no longer defaults to tomorrow in the evening). It follows your device automatically, or choose one in Profile. The administrator sets the installation's zone with `TZ` (e.g. `America/New_York`), which also sets when the nightly and weekly jobs run. Signatures and the record history still show UTC.
- **Update Hours asks first**, showing each reading's change and that every in-service component moves without logging a flight; the message afterwards says exactly what changed. A lowered reading is marked as a correction.
- **Squawk photos show as thumbnails** that open the photo viewer.
- **Save and log next leg** on Log Flight: saves the flight and opens the form for the next one, starting where it ended.
- **Setup checklist** on a new aircraft's Overview: components, standard inspections, ADs from DRS, registration and airworthiness certificate, weight and balance.
- The component form groups its limits into **Replacement and expiry** and **Overhaul and TBO**, opened only when used.
- Choosing **Ground Aircraft** on a squawk says what it does before you submit.
- The logbook entry form shows **Inspection result** only for inspection entries.
- A new document is named from its file when you leave the name blank.
- Dates read the same way everywhere, including the logbook-entry pickers, the activity log and the airworthiness list.
### Fixes
- On iPad and iPhone home-screen apps, the top bar stays sharp (it's now fixed to the top of the screen).
- An aircraft's description stays inside the Details card.
## 2026.11.3
### Installed app
- **Works without signal.** While you're online the app saves, for each of your aircraft, the Overview, weight and balance, Log Flight and Report Squawk pages and its photo, plus the Fleet page. At the plane with no signal, open the app and use it as usual; a saved copy says when it was saved.
- **Report Squawk offline**, photos included, like Log Flight. Saved items are sent when the connection is back (on Android even with the app closed), only ever under the account that saved them, and the number waiting shows on the app icon.
- **Notifications** (Profile → This device): a grounding squawk on your aircraft, items newly overdue on aircraft you own (checked each morning), and requests to sign a logbook entry. On iPhone and iPad they work in the installed app.
- **Shortcuts**: a long press on the app icon offers Log Flight and Report Squawk.
- **Install help** on Profile, and a **Reload** notice when a new version is installed.
- Signing out clears what the device saved for offline use.
### Changes
- Each section shows its main action as a button; imports, exports, printing and tools are under **More**. The aircraft's **More** menu has the status report and, for owners, Access & sharing, editing the aircraft and its downloads.
- Oil Analysis is under **Oil & Fuel**; the tabs fit on one line.
- The header shows your role on the aircraft, and no longer shows "Available" (the usual status).
- **Print selected** in the logbook appears once an entry is ticked; the logbook filter applies as you change it.
- Dates read the same everywhere (the logbook list, notes, audits, About).
- All the app's text is in one translation file; see Translating in the README.
### Fixes
- The flight statistics' cards fit two to a row on phones, and **By year** shows that it opens.
- Various unused code removed.
## 2026.11.2 ## 2026.11.2
### Changes ### Changes
+1 -1
View File
@@ -30,7 +30,7 @@ FROM base AS build
# Install packages needed to build gems # Install packages needed to build gems
RUN apt-get update -qq && \ RUN apt-get update -qq && \
apt-get install --no-install-recommends -y build-essential git libyaml-dev pkg-config && \ apt-get install --no-install-recommends -y build-essential git libssl-dev libyaml-dev pkg-config && \
rm -rf /var/lib/apt/lists /var/cache/apt/archives rm -rf /var/lib/apt/lists /var/cache/apt/archives
# Install application gems # Install application gems
+5 -9
View File
@@ -23,10 +23,9 @@ gem "bcrypt", "~> 3.1.7"
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem "tzinfo-data", platforms: %i[ windows jruby ] gem "tzinfo-data", platforms: %i[ windows jruby ]
# Use the database-backed adapters for Rails.cache, Active Job, and Action Cable # Use the database-backed adapters for Rails.cache and Active Job
gem "solid_cache" gem "solid_cache"
gem "solid_queue" gem "solid_queue"
gem "solid_cable"
# Reduces boot times through caching; required in config/boot.rb # Reduces boot times through caching; required in config/boot.rb
gem "bootsnap", require: false gem "bootsnap", require: false
@@ -38,7 +37,7 @@ gem "kamal", require: false
gem "thruster", require: false gem "thruster", require: false
# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] # Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images]
# gem "image_processing", "~> 1.2" gem "image_processing", "~> 1.2"
group :development, :test do group :development, :test do
# See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
@@ -56,12 +55,6 @@ group :development do
gem "web-console" gem "web-console"
end end
group :test do
# Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
gem "capybara"
gem "selenium-webdriver"
end
gem "chartkick", "~> 5.2" gem "chartkick", "~> 5.2"
gem "json", "~> 3.1" gem "json", "~> 3.1"
@@ -85,4 +78,7 @@ gem "omniauth-rails_csrf_protection", "~> 2.0"
gem "prawn", "~> 2.5" # printable logbook entries gem "prawn", "~> 2.5" # printable logbook entries
gem "rotp", "~> 6.3" # authenticator app (TOTP) codes gem "rotp", "~> 6.3" # authenticator app (TOTP) codes
# Push notifications to installed apps and browsers (Web Push, VAPID)
gem "web-push", "~> 3.1"
gem "rqrcode", "~> 3.1" # QR code for setting up the authenticator gem "rqrcode", "~> 3.1" # QR code for setting up the authenticator
+38 -30
View File
@@ -100,15 +100,6 @@ GEM
brakeman (8.1.0) brakeman (8.1.0)
racc racc
builder (3.3.0) builder (3.3.0)
capybara (3.40.0)
addressable
matrix
mini_mime (>= 0.1.3)
nokogiri (~> 1.11)
rack (>= 1.6.0)
rack-test (>= 0.6.3)
regexp_parser (>= 1.5, < 3.0)
xpath (~> 3.2)
caxlsx (4.5.0) caxlsx (4.5.0)
htmlentities (~> 4.3, >= 4.3.4) htmlentities (~> 4.3, >= 4.3.4)
marcel (~> 1.0) marcel (~> 1.0)
@@ -150,6 +141,14 @@ GEM
faraday (>= 1, < 3) faraday (>= 1, < 3)
faraday-net_http (3.5.0) faraday-net_http (3.5.0)
net-http (~> 0.5) net-http (~> 0.5)
ffi (1.17.4-aarch64-linux-gnu)
ffi (1.17.4-aarch64-linux-musl)
ffi (1.17.4-arm-linux-gnu)
ffi (1.17.4-arm-linux-musl)
ffi (1.17.4-arm64-darwin)
ffi (1.17.4-x86_64-darwin)
ffi (1.17.4-x86_64-linux-gnu)
ffi (1.17.4-x86_64-linux-musl)
fugit (1.14.0) fugit (1.14.0)
et-orbi (~> 1.4) et-orbi (~> 1.4)
raabro (~> 1.4) raabro (~> 1.4)
@@ -162,6 +161,9 @@ GEM
htmlentities (4.4.2) htmlentities (4.4.2)
i18n (1.15.2) i18n (1.15.2)
concurrent-ruby (~> 1.0) concurrent-ruby (~> 1.0)
image_processing (1.14.0)
mini_magick (>= 4.9.5, < 6)
ruby-vips (>= 2.0.17, < 3)
importmap-rails (2.2.3) importmap-rails (2.2.3)
actionpack (>= 6.0.0) actionpack (>= 6.0.0)
activesupport (>= 6.0.0) activesupport (>= 6.0.0)
@@ -180,6 +182,8 @@ GEM
bindata bindata
faraday (~> 2.0) faraday (~> 2.0)
faraday-follow_redirects faraday-follow_redirects
jwt (3.3.0)
base64
kamal (2.12.0) kamal (2.12.0)
activesupport (>= 7.0) activesupport (>= 7.0)
base64 (~> 0.2) base64 (~> 0.2)
@@ -205,6 +209,8 @@ GEM
net-smtp net-smtp
marcel (1.2.1) marcel (1.2.1)
matrix (0.4.3) matrix (0.4.3)
mini_magick (5.4.0)
logger
mini_mime (1.1.5) mini_mime (1.1.5)
minitest (6.1.0) minitest (6.1.0)
drb (~> 2.0) drb (~> 2.0)
@@ -268,6 +274,7 @@ GEM
tzinfo tzinfo
validate_url validate_url
webfinger (~> 2.0) webfinger (~> 2.0)
openssl (4.0.2)
opentelemetry-api (1.11.1) opentelemetry-api (1.11.1)
logger logger
ostruct (0.6.3) ostruct (0.6.3)
@@ -402,18 +409,11 @@ GEM
rubocop-performance (>= 1.24) rubocop-performance (>= 1.24)
rubocop-rails (>= 2.30) rubocop-rails (>= 2.30)
ruby-progressbar (1.13.0) ruby-progressbar (1.13.0)
ruby-vips (2.3.0)
ffi (~> 1.12)
logger
rubyzip (3.7.0) rubyzip (3.7.0)
securerandom (0.4.1) securerandom (0.4.1)
selenium-webdriver (4.52.0)
base64 (~> 0.2)
logger (~> 1.4)
rubyzip (>= 1.2.2, < 4.0)
websocket (~> 1.0)
solid_cable (4.1.0)
actioncable (>= 7.2)
activejob (>= 7.2)
activerecord (>= 7.2)
railties (>= 7.2)
solid_cache (1.0.10) solid_cache (1.0.10)
activejob (>= 7.2) activejob (>= 7.2)
activerecord (>= 7.2) activerecord (>= 7.2)
@@ -485,6 +485,9 @@ GEM
actionview (>= 8.0.0) actionview (>= 8.0.0)
bindex (>= 0.4.0) bindex (>= 0.4.0)
railties (>= 8.0.0) railties (>= 8.0.0)
web-push (3.1.0)
jwt (~> 3.0)
openssl (>= 3.0)
webfinger (2.1.3) webfinger (2.1.3)
activesupport activesupport
faraday (~> 2.0) faraday (~> 2.0)
@@ -493,13 +496,10 @@ GEM
addressable (>= 2.8.0) addressable (>= 2.8.0)
crack (>= 0.3.2) crack (>= 0.3.2)
hashdiff (>= 0.4.0, < 2.0.0) hashdiff (>= 0.4.0, < 2.0.0)
websocket (1.2.11)
websocket-driver (0.8.2) websocket-driver (0.8.2)
base64 base64
websocket-extensions (>= 0.1.0) websocket-extensions (>= 0.1.0)
websocket-extensions (0.1.5) websocket-extensions (0.1.5)
xpath (3.2.0)
nokogiri (~> 1.8)
zeitwerk (2.8.3) zeitwerk (2.8.3)
PLATFORMS PLATFORMS
@@ -518,12 +518,12 @@ DEPENDENCIES
bcrypt (~> 3.1.7) bcrypt (~> 3.1.7)
bootsnap bootsnap
brakeman brakeman
capybara
caxlsx (~> 4.5) caxlsx (~> 4.5)
chartkick (~> 5.2) chartkick (~> 5.2)
commonmarker (~> 2.10) commonmarker (~> 2.10)
csv (~> 3.3) csv (~> 3.3)
debug debug
image_processing (~> 1.2)
importmap-rails importmap-rails
json (~> 3.1) json (~> 3.1)
kamal kamal
@@ -540,8 +540,6 @@ DEPENDENCIES
rqrcode (~> 3.1) rqrcode (~> 3.1)
rubocop-rails-omakase rubocop-rails-omakase
rubyzip (~> 3.7) rubyzip (~> 3.7)
selenium-webdriver
solid_cable
solid_cache solid_cache
solid_queue solid_queue
sqlite3 (>= 2.1) sqlite3 (>= 2.1)
@@ -551,6 +549,7 @@ DEPENDENCIES
turbo-rails turbo-rails
tzinfo-data tzinfo-data
web-console web-console
web-push (~> 3.1)
webmock (~> 3.34) webmock (~> 3.34)
CHECKSUMS CHECKSUMS
@@ -584,7 +583,6 @@ CHECKSUMS
bootsnap (1.26.1) sha256=5b5bd90f8f13ea338627c1d56ffbe2ea25e743ac48c2afec1a9bea3a06a264e2 bootsnap (1.26.1) sha256=5b5bd90f8f13ea338627c1d56ffbe2ea25e743ac48c2afec1a9bea3a06a264e2
brakeman (8.1.0) sha256=cfa9e5214e4925842f4bc849a64f8a7e6c5d0425fe98eac8d7b7bc60fdc17e07 brakeman (8.1.0) sha256=cfa9e5214e4925842f4bc849a64f8a7e6c5d0425fe98eac8d7b7bc60fdc17e07
builder (3.3.0) sha256=497918d2f9dca528fdca4b88d84e4ef4387256d984b8154e9d5d3fe5a9c8835f builder (3.3.0) sha256=497918d2f9dca528fdca4b88d84e4ef4387256d984b8154e9d5d3fe5a9c8835f
capybara (3.40.0) sha256=42dba720578ea1ca65fd7a41d163dd368502c191804558f6e0f71b391054aeef
caxlsx (4.5.0) sha256=e3d98d859f148df05d5462086b5079b523f29c1766b569535f1d68629ce743ff caxlsx (4.5.0) sha256=e3d98d859f148df05d5462086b5079b523f29c1766b569535f1d68629ce743ff
chartkick (5.3.0) sha256=19a2bba39decf54c4939d3f31460535f8814c85045672ba2ed616c6897325b00 chartkick (5.3.0) sha256=19a2bba39decf54c4939d3f31460535f8814c85045672ba2ed616c6897325b00
chunky_png (1.4.0) sha256=89d5b31b55c0cf4da3cf89a2b4ebc3178d8abe8cbaf116a1dba95668502fdcfe chunky_png (1.4.0) sha256=89d5b31b55c0cf4da3cf89a2b4ebc3178d8abe8cbaf116a1dba95668502fdcfe
@@ -612,6 +610,14 @@ CHECKSUMS
faraday (2.15.1) sha256=8708154deda739c5e86cc42b74960e23e8491fce0eba9e11639a6a34b1ac288f faraday (2.15.1) sha256=8708154deda739c5e86cc42b74960e23e8491fce0eba9e11639a6a34b1ac288f
faraday-follow_redirects (0.5.0) sha256=5cde93c894b30943a5d2b93c2fe9284216a6b756f7af406a1e55f211d97d10ad faraday-follow_redirects (0.5.0) sha256=5cde93c894b30943a5d2b93c2fe9284216a6b756f7af406a1e55f211d97d10ad
faraday-net_http (3.5.0) sha256=2e7094c34e38754ee048cc3df47376f8657005d9375f8473bce1c3b526a22e36 faraday-net_http (3.5.0) sha256=2e7094c34e38754ee048cc3df47376f8657005d9375f8473bce1c3b526a22e36
ffi (1.17.4-aarch64-linux-gnu) sha256=b208f06f91ffd8f5e1193da3cae3d2ccfc27fc36fba577baf698d26d91c080df
ffi (1.17.4-aarch64-linux-musl) sha256=9286b7a615f2676245283aef0a0a3b475ae3aae2bb5448baace630bb77b91f39
ffi (1.17.4-arm-linux-gnu) sha256=d6dbddf7cb77bf955411af5f187a65b8cd378cb003c15c05697f5feee1cb1564
ffi (1.17.4-arm-linux-musl) sha256=9d4838ded0465bef6e2426935f6bcc93134b6616785a84ffd2a3d82bc3cf6f95
ffi (1.17.4-arm64-darwin) sha256=19071aaf1419251b0a46852abf960e77330a3b334d13a4ab51d58b31a937001b
ffi (1.17.4-x86_64-darwin) sha256=aa70390523cf3235096cf64962b709b4cfbd5c082a2cb2ae714eb0fe2ccda496
ffi (1.17.4-x86_64-linux-gnu) sha256=9d3db14c2eae074b382fa9c083fe95aec6e0a1451da249eab096c34002bc752d
ffi (1.17.4-x86_64-linux-musl) sha256=3fdf9888483de005f8ef8d1cf2d3b20d86626af206cbf780f6a6a12439a9c49e
fugit (1.14.0) sha256=e311a9cc85a54bb67649df45060e721282a1e2c8ebad40e41874a3a7d576f37e fugit (1.14.0) sha256=e311a9cc85a54bb67649df45060e721282a1e2c8ebad40e41874a3a7d576f37e
globalid (1.4.0) sha256=037f12fbf1d9d7a014d501c2d5c77356fd4ddd96d7a7991d6700bba96706f427 globalid (1.4.0) sha256=037f12fbf1d9d7a014d501c2d5c77356fd4ddd96d7a7991d6700bba96706f427
hashdiff (1.2.1) sha256=9c079dbc513dfc8833ab59c0c2d8f230fa28499cc5efb4b8dd276cf931457cd1 hashdiff (1.2.1) sha256=9c079dbc513dfc8833ab59c0c2d8f230fa28499cc5efb4b8dd276cf931457cd1
@@ -619,11 +625,13 @@ CHECKSUMS
hashie (5.2.0) sha256=357a22635195c2e3911fbbc3de9a7d528843d1f42ab0aae02171048f16332d72 hashie (5.2.0) sha256=357a22635195c2e3911fbbc3de9a7d528843d1f42ab0aae02171048f16332d72
htmlentities (4.4.2) sha256=bbafbdf69f2eca9262be4efef7e43e6a1de54c95eb600f26984f71d2fe96c5c3 htmlentities (4.4.2) sha256=bbafbdf69f2eca9262be4efef7e43e6a1de54c95eb600f26984f71d2fe96c5c3
i18n (1.15.2) sha256=00f9eb62412fe593b2a65a97daa75300d37abb8f7202ec748e94b6d46a9dd1b5 i18n (1.15.2) sha256=00f9eb62412fe593b2a65a97daa75300d37abb8f7202ec748e94b6d46a9dd1b5
image_processing (1.14.0) sha256=754cc169c9c262980889bec6bfd325ed1dafad34f85242b5a07b60af004742fb
importmap-rails (2.2.3) sha256=7101be2a4dc97cf1558fb8f573a718404c5f6bcfe94f304bf1f39e444feeb16a importmap-rails (2.2.3) sha256=7101be2a4dc97cf1558fb8f573a718404c5f6bcfe94f304bf1f39e444feeb16a
io-console (0.9.5) sha256=83dd9bbf4c4680416629245b39cd4212eb5f4d9a4ea91804870c1f6b846414d5 io-console (0.9.5) sha256=83dd9bbf4c4680416629245b39cd4212eb5f4d9a4ea91804870c1f6b846414d5
irb (1.18.0) sha256=de9454a0703a54704b9811a5ef31a60c86949fbf4013fcf244fabc7c775248e3 irb (1.18.0) sha256=de9454a0703a54704b9811a5ef31a60c86949fbf4013fcf244fabc7c775248e3
json (3.1.0) sha256=3ce7ccf8fde58960177a3a756c31f292a4c1e1dedee884547096a5b0604e3bd8 json (3.1.0) sha256=3ce7ccf8fde58960177a3a756c31f292a4c1e1dedee884547096a5b0604e3bd8
json-jwt (1.17.2) sha256=97e37c1c3e22e9e1d74a1c0d77319c5cdc8a636226e5dbb1664b0b34eddcf1c9 json-jwt (1.17.2) sha256=97e37c1c3e22e9e1d74a1c0d77319c5cdc8a636226e5dbb1664b0b34eddcf1c9
jwt (3.3.0) sha256=44cc34fbc341c148233cf66641522b4bce0dfb1ce55e8073f05c56f44f4ee546
kamal (2.12.0) sha256=c51d1ab085e515470f98d0c0f043637122b5ebf76e8b610cb1fbbed0b7f9b8fa kamal (2.12.0) sha256=c51d1ab085e515470f98d0c0f043637122b5ebf76e8b610cb1fbbed0b7f9b8fa
language_server-protocol (3.17.0.6) sha256=5ef2c0c138f8267e1bc631d3328347d354f96724b0af22f2c79516120443b7f0 language_server-protocol (3.17.0.6) sha256=5ef2c0c138f8267e1bc631d3328347d354f96724b0af22f2c79516120443b7f0
lint_roller (1.1.0) sha256=2c0c845b632a7d172cb849cc90c1bce937a28c5c8ccccb50dfd46a485003cc87 lint_roller (1.1.0) sha256=2c0c845b632a7d172cb849cc90c1bce937a28c5c8ccccb50dfd46a485003cc87
@@ -632,6 +640,7 @@ CHECKSUMS
mail (2.9.1) sha256=06574eca475253d6c18145dd70af80d0eb970182d55053497c5f4d797ea160e8 mail (2.9.1) sha256=06574eca475253d6c18145dd70af80d0eb970182d55053497c5f4d797ea160e8
marcel (1.2.1) sha256=1678e9360e32f9eafa917c80029e2f6d10b2715c66a4b87b6d0da9b9cd1f859f marcel (1.2.1) sha256=1678e9360e32f9eafa917c80029e2f6d10b2715c66a4b87b6d0da9b9cd1f859f
matrix (0.4.3) sha256=a0d5ab7ddcc1973ff690ab361b67f359acbb16958d1dc072b8b956a286564c5b matrix (0.4.3) sha256=a0d5ab7ddcc1973ff690ab361b67f359acbb16958d1dc072b8b956a286564c5b
mini_magick (5.4.0) sha256=f120af581d9ed4ec52c57f35a67a605d112bb1d8f582d1415b147fda42d11d78
mini_mime (1.1.5) sha256=8681b7e2e4215f2a159f9400b5816d85e9d8c6c6b491e96a12797e798f8bccef mini_mime (1.1.5) sha256=8681b7e2e4215f2a159f9400b5816d85e9d8c6c6b491e96a12797e798f8bccef
minitest (6.1.0) sha256=ff373595aa8888631e8a5463986a76b3845346ae6d7fa46e139c1633d418076e minitest (6.1.0) sha256=ff373595aa8888631e8a5463986a76b3845346ae6d7fa46e139c1633d418076e
msgpack (1.8.7) sha256=dfefec761b5f9047e6e8d95d2c7f8af4b3725d984a01942adc533aa819a2df33 msgpack (1.8.7) sha256=dfefec761b5f9047e6e8d95d2c7f8af4b3725d984a01942adc533aa819a2df33
@@ -656,6 +665,7 @@ CHECKSUMS
omniauth-rails_csrf_protection (2.0.1) sha256=c6e3204d7e3925bb537cb52d50fdfc9f05293f1a9d87c5d4ab4ca3a39ba8c32d omniauth-rails_csrf_protection (2.0.1) sha256=c6e3204d7e3925bb537cb52d50fdfc9f05293f1a9d87c5d4ab4ca3a39ba8c32d
omniauth_openid_connect (0.8.0) sha256=1f2f3890386e2a742221cee0d2e903b78d874e6fab9ea3bfa31c1462f4793d25 omniauth_openid_connect (0.8.0) sha256=1f2f3890386e2a742221cee0d2e903b78d874e6fab9ea3bfa31c1462f4793d25
openid_connect (2.5.0) sha256=659aff8edce0907798e3f6837e5f27ae2937ae8735216f3e900ab8daa29e39c4 openid_connect (2.5.0) sha256=659aff8edce0907798e3f6837e5f27ae2937ae8735216f3e900ab8daa29e39c4
openssl (4.0.2) sha256=1037ad2868ae58df9ad917891c0c0f9815a1172f6846d4bcdd508e4c2ee747c2
opentelemetry-api (1.11.1) sha256=d07f9987ea6240b3fd5ed5dd7450f93c58e403e0553e804069c23ae18ba61ff7 opentelemetry-api (1.11.1) sha256=d07f9987ea6240b3fd5ed5dd7450f93c58e403e0553e804069c23ae18ba61ff7
ostruct (0.6.3) sha256=95a2ed4a4bd1d190784e666b47b2d3f078e4a9efda2fccf18f84ddc6538ed912 ostruct (0.6.3) sha256=95a2ed4a4bd1d190784e666b47b2d3f078e4a9efda2fccf18f84ddc6538ed912
parallel (2.3.0) sha256=f75a3e904101ce6a1ccb6b8dc800cbafd42166d83330192438dcf29395167a6f parallel (2.3.0) sha256=f75a3e904101ce6a1ccb6b8dc800cbafd42166d83330192438dcf29395167a6f
@@ -698,10 +708,9 @@ CHECKSUMS
rubocop-rails (2.38.0) sha256=6e2b7c532efa95e3050371bec20b8f5b025662acead8bc70ee31f0e3e6fa2f06 rubocop-rails (2.38.0) sha256=6e2b7c532efa95e3050371bec20b8f5b025662acead8bc70ee31f0e3e6fa2f06
rubocop-rails-omakase (1.1.0) sha256=2af73ac8ee5852de2919abbd2618af9c15c19b512c4cfc1f9a5d3b6ef009109d rubocop-rails-omakase (1.1.0) sha256=2af73ac8ee5852de2919abbd2618af9c15c19b512c4cfc1f9a5d3b6ef009109d
ruby-progressbar (1.13.0) sha256=80fc9c47a9b640d6834e0dc7b3c94c9df37f08cb072b7761e4a71e22cff29b33 ruby-progressbar (1.13.0) sha256=80fc9c47a9b640d6834e0dc7b3c94c9df37f08cb072b7761e4a71e22cff29b33
ruby-vips (2.3.0) sha256=e685ec02c13969912debbd98019e50492e12989282da5f37d05f5471442f5374
rubyzip (3.7.0) sha256=65c19294da75297a939006f3516deacc33185fbd721ff1954f7a231db6d3e121 rubyzip (3.7.0) sha256=65c19294da75297a939006f3516deacc33185fbd721ff1954f7a231db6d3e121
securerandom (0.4.1) sha256=cc5193d414a4341b6e225f0cb4446aceca8e50d5e1888743fac16987638ea0b1 securerandom (0.4.1) sha256=cc5193d414a4341b6e225f0cb4446aceca8e50d5e1888743fac16987638ea0b1
selenium-webdriver (4.52.0) sha256=5d45ba100ea8b57f5a8c25979a636d48b4c60c39973478930d78e884bdeecd2d
solid_cable (4.1.0) sha256=828e3d509207b82b4f05f4e9c85f696994710679b52d511aa7f97ebd212d3226
solid_cache (1.0.10) sha256=bc05a2fb3ac78a6f43cbb5946679cf9db67dd30d22939ededc385cb93e120d41 solid_cache (1.0.10) sha256=bc05a2fb3ac78a6f43cbb5946679cf9db67dd30d22939ededc385cb93e120d41
solid_queue (1.7.2) sha256=a22685e1d2ee14ce7b4e5d4592c9d8e837951884c51555609dee58679ed03325 solid_queue (1.7.2) sha256=a22685e1d2ee14ce7b4e5d4592c9d8e837951884c51555609dee58679ed03325
sqlite3 (2.10.2-aarch64-linux-gnu) sha256=e9aea2c2b3476fc875dd8a89313a9a2862818519c0186bfb5b56d6f57bb08d98 sqlite3 (2.10.2-aarch64-linux-gnu) sha256=e9aea2c2b3476fc875dd8a89313a9a2862818519c0186bfb5b56d6f57bb08d98
@@ -741,12 +750,11 @@ CHECKSUMS
useragent (0.16.11) sha256=700e6413ad4bb954bb63547fa098dddf7b0ebe75b40cc6f93b8d54255b173844 useragent (0.16.11) sha256=700e6413ad4bb954bb63547fa098dddf7b0ebe75b40cc6f93b8d54255b173844
validate_url (1.0.15) sha256=72fe164c0713d63a9970bd6700bea948babbfbdcec392f2342b6704042f57451 validate_url (1.0.15) sha256=72fe164c0713d63a9970bd6700bea948babbfbdcec392f2342b6704042f57451
web-console (4.3.0) sha256=e13b71301cdfc2093f155b5aa3a622db80b4672d1f2f713119cc7ec7ac6a6da4 web-console (4.3.0) sha256=e13b71301cdfc2093f155b5aa3a622db80b4672d1f2f713119cc7ec7ac6a6da4
web-push (3.1.0) sha256=501ab00340c58fb70dabda59f28a86b3cccb0930c6f1f30721b2a5b24de7187d
webfinger (2.1.3) sha256=567a52bde77fb38ca6b67e55db755f988766ec4651c1d24916a65aa70540695c webfinger (2.1.3) sha256=567a52bde77fb38ca6b67e55db755f988766ec4651c1d24916a65aa70540695c
webmock (3.34.0) sha256=72eed29dc8c00148d592acaedaaa6b869e2e397de57dfc8602b84aa834f46b33 webmock (3.34.0) sha256=72eed29dc8c00148d592acaedaaa6b869e2e397de57dfc8602b84aa834f46b33
websocket (1.2.11) sha256=b7e7a74e2410b5e85c25858b26b3322f29161e300935f70a0e0d3c35e0462737
websocket-driver (0.8.2) sha256=97c556b019bf3410b4961002ac501621e9322d3f8a7bc02161a09301cc4c4146 websocket-driver (0.8.2) sha256=97c556b019bf3410b4961002ac501621e9322d3f8a7bc02161a09301cc4c4146
websocket-extensions (0.1.5) sha256=1c6ba63092cda343eb53fc657110c71c754c56484aad42578495227d717a8241 websocket-extensions (0.1.5) sha256=1c6ba63092cda343eb53fc657110c71c754c56484aad42578495227d717a8241
xpath (3.2.0) sha256=6dfda79d91bb3b949b947ecc5919f042ef2f399b904013eb3ef6d20dd3a4082e
zeitwerk (2.8.3) sha256=2c85125a8467ce069e20123d1e709a08955c9d29c118c25b46b7b7fafdbb92e5 zeitwerk (2.8.3) sha256=2c85125a8467ce069e20123d1e709a08955c9d29c118c25b46b7b7fafdbb92e5
BUNDLED WITH BUNDLED WITH
+24
View File
@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
+58 -30
View File
@@ -8,9 +8,9 @@ The port aims to be **easy to host**. It runs as one process with one SQLite dat
## Stack ## Stack
- Ruby 4.0, Rails 8.1, SQLite. Solid Queue, Solid Cache, and Solid Cable all use SQLite, so there are no extra services. Background jobs (nightly backup and records check, weekly reminders and AD search) run in the web process. - Ruby 4.0, Rails 8.1, SQLite. Solid Queue and Solid Cache both use SQLite, so there are no extra services. Background jobs (nightly backup and records check, weekly reminders and AD search) run in the web process.
- Hotwire (Turbo and Stimulus) with importmap, so there is no Node build step. Tailwind CSS 4 runs through `tailwindcss-rails`. - Hotwire (Turbo and Stimulus) with importmap, so there is no Node build step. Tailwind CSS 4 runs through `tailwindcss-rails`.
- Active Storage on local disk handles pictures, document pages, squawk attachments, and track logs. Identical files are stored once (hard links). - Active Storage on local disk handles pictures, document pages, squawk attachments, and track logs; libvips makes the photo thumbnails. Identical files are stored once (hard links).
- Chartkick and Chart.js draw the oil and fuel charts. - Chartkick and Chart.js draw the oil and fuel charts.
- Authentication uses the Rails 8 built-in generator (sessions plus password reset), emailed sign-in links, and optional OpenID Connect single sign-on (OmniAuth). - Authentication uses the Rails 8 built-in generator (sessions plus password reset), emailed sign-in links, and optional OpenID Connect single sign-on (OmniAuth).
- Prawn renders the printable logbook entries; Commonmarker renders Markdown notes and the user guide. - Prawn renders the printable logbook entries; Commonmarker renders Markdown notes and the user guide.
@@ -33,7 +33,7 @@ bin/dev # http://localhost:3000
``` ```
With demo data, sign in as `admin@example.com` / `demo-password-123` (admin, owner of N12345) or `pilot@example.com` / `demo-password-123` (pilot). With demo data, sign in as `admin@example.com` / `demo-password-123` (admin, owner of N12345) or `pilot@example.com` / `demo-password-123` (pilot).
Without demo data, the first visit asks you to create the admin account. Without demo data, the first visit asks you to create the admin account. It needs the one-time setup code printed in the server's log (the line starting `Setup code`), so only whoever runs the server can claim it.
Run the tests: `bin/rails test` Run the tests: `bin/rails test`
@@ -48,11 +48,14 @@ cp .env.example .env # set SECRET_KEY_BASE (bin/rails secret), APP_HOST
docker compose up -d --build # http://<host>:3000 docker compose up -d --build # http://<host>:3000
``` ```
Data lives in the `sam_storage` volume. Set `FORCE_SSL=false` if you serve plain HTTP on a LAN. Set it to `true` when a TLS reverse proxy such as Caddy, Traefik, or Cloudflare Tunnel sits in front. Data lives in the `sam_storage` volume. Set `FORCE_SSL=false` only if you serve plain HTTP on a private network: passwords and sign-in cookies then travel unencrypted. Set it to `true` when a TLS reverse proxy such as Caddy, Traefik, or Cloudflare Tunnel sits in front, or use the built-in HTTPS below.
The first visit asks for the setup code from the log: `docker compose logs web | grep "Setup code"`.
Other examples in the repository: Other examples in the repository:
- [`docker-compose.image.yml`](docker-compose.image.yml): runs the published image (`barrettefab/simple-aircraft-manager-rails` on Docker Hub) without cloning the source, with a health check and update steps. - [`docker-compose.image.yml`](docker-compose.image.yml): runs the published image (`barrettefab/simple-aircraft-manager-rails` on Docker Hub) without cloning the source, with a health check and update steps.
- [`docker-compose.direct.yml`](docker-compose.direct.yml): directly on the internet with HTTPS and no proxy. The image's web server gets and renews a Let's Encrypt certificate for `TLS_DOMAIN` by itself (ports 80 and 443 must reach the server).
- [`docker-compose.traefik.yml`](docker-compose.traefik.yml): behind Traefik with HTTPS, with optional Authentik forward auth (see [Running behind Authentik](docs/authentik.md)). - [`docker-compose.traefik.yml`](docker-compose.traefik.yml): behind Traefik with HTTPS, with optional Authentik forward auth (see [Running behind Authentik](docs/authentik.md)).
[`.env.example`](.env.example) lists every setting, grouped and commented. After starting or updating, `docker compose exec web bin/rails sam:doctor` checks the installation. [`.env.example`](.env.example) lists every setting, grouped and commented. After starting or updating, `docker compose exec web bin/rails sam:doctor` checks the installation.
@@ -69,22 +72,30 @@ The app is a standard Rails app. Run `bin/rails db:prepare && bin/thrust bin/rai
| Variable | Purpose | | Variable | Purpose |
|---|---| |---|---|
| `SECRET_KEY_BASE` | Required in production (`bin/rails secret`). Alternatively provide `RAILS_MASTER_KEY`. | | `SECRET_KEY_BASE` | Required in production (`bin/rails secret`). Anyone who knows it can sign in as anyone, so the app won't start with a placeholder or one under 32 characters, and `sam:doctor` flags one under 64. Alternatively provide `RAILS_MASTER_KEY`. |
| `FORCE_SSL` | `true` (default) redirects to HTTPS and sets secure cookies. Use `false` for plain HTTP. | | `FORCE_SSL` | `true` (default) redirects to HTTPS and sets secure cookies. Use `false` for plain HTTP, only on a private network. |
| `APP_HOST` | Host name the app is reached at, used in email links (password resets, sign-in links, signing invitations, reminders). | | `TLS_DOMAIN` | Optional. HTTPS without a proxy: the app gets a Let's Encrypt certificate for this name (see `docker-compose.direct.yml`). |
| `APP_HOST` | Host name the app is reached at, used in email links (password resets, sign-in links, signing invitations, reminders). When set, the app answers only for this name, the `APP_URL` host, `ALLOWED_HOSTS`, `localhost` and IP addresses. |
| `ALLOWED_HOSTS` | Optional. Other names the app may be reached by, comma-separated (e.g. a LAN name). |
| `AIRTRAIL_ALLOWED_HOSTS` | Optional. AirTrail servers on your private network that anyone may connect to, comma-separated. Admins can always connect to private addresses; nobody can use the server itself or link-local addresses. |
| `SMTP_ADDRESS`, `SMTP_PORT`, `SMTP_USERNAME`, `SMTP_PASSWORD`, `MAIL_FROM` | Optional. They enable email: password resets and **Email me a sign-in link**. Without them an admin resets passwords from **Users**. Check the setup with **Admin → About → Send test email**. | | `SMTP_ADDRESS`, `SMTP_PORT`, `SMTP_USERNAME`, `SMTP_PASSWORD`, `MAIL_FROM` | Optional. They enable email: password resets and **Email me a sign-in link**. Without them an admin resets passwords from **Users**. Check the setup with **Admin → About → Send test email**. |
| `SMTP_TLS` | `true` for servers that use TLS from the start. That's the default on port 465; other ports upgrade with STARTTLS. | | `SMTP_TLS` | `true` for servers that use TLS from the start. That's the default on port 465; other ports upgrade with STARTTLS. |
| `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` | Optional. The key pair that signs push notifications (generate with `bin/rails runner 'k = WebPush.generate_key; puts k.public_key, k.private_key'`). Without them the app generates a pair once and keeps it in `storage/vapid_keys.json`. Changing it turns notifications off on every device until they're turned on again. |
| `TZ` | Optional. The installation's time zone, Docker's standard setting, e.g. `America/New_York`: scheduled jobs (nightly backup, the 7am overdue check, Monday reminders) run on its clock, and it's used for anyone whose device zone isn't known yet. Each person sees times in their own zone (Profile, or their device). Default `UTC`. |
| `APP_LOCALE` | Optional. The app's language, e.g. `es` for `config/locales/es.yml` (see [Translating](#translating)). Default `en`. |
| `ANTHROPIC_API_KEY` | Optional. Lets Claude transcribe scanned logbook pages into entries (**Logbook → Import scans**). Without it, scans are only uploaded. | | `ANTHROPIC_API_KEY` | Optional. Lets Claude transcribe scanned logbook pages into entries (**Logbook → Import scans**). Without it, scans are only uploaded. |
| `LOGBOOK_AI_MODEL`, `LOGBOOK_AI_EFFORT` | Optional. The Claude model and effort used for transcription (default `claude-opus-5-5`, `high`). | | `LOGBOOK_AI_MODEL`, `LOGBOOK_AI_EFFORT` | Optional. The Claude model and effort used for transcription (default `claude-opus-5-5`, `high`). |
| `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. | | `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_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_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_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. | | `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. | | `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. | | `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_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. | | `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) ### Single sign-on (Authentik example)
@@ -120,7 +131,7 @@ The app also makes a verified copy of the main database every night in `storage/
For an off-site copy without extra tools, **Admin → Off-site Backup** connects a Google Drive account: each night the verified database copy and any new uploaded files are copied there, and a restore test checks them. Setup and restoring are in the [administration guide](docs/guide/administration.md#off-site-backup-to-google-drive). Keep `SECRET_KEY_BASE` somewhere safe off the server: stored secrets (API keys, the Drive connection) and electronic signature seals depend on it. For an off-site copy without extra tools, **Admin → Off-site Backup** connects a Google Drive account: each night the verified database copy and any new uploaded files are copied there, and a restore test checks them. Setup and restoring are in the [administration guide](docs/guide/administration.md#off-site-backup-to-google-drive). Keep `SECRET_KEY_BASE` somewhere safe off the server: stored secrets (API keys, the Drive connection) and electronic signature seals depend on it.
To back up or move a single aircraft with all its files, use **Access & Sharing → Download .sam.zip** (or `bin/rails "sam:export[N12345]"`). Import it from **Fleet → Import** (or `bin/rails "sam:import[file.sam.zip,owner@example.com]"`). The archive format is the original Simple Aircraft Manager's, so archives move between the two apps. To back up or move a single aircraft with all its files, use **More → Download .sam.zip** on the aircraft (or `bin/rails "sam:export[N12345]"`). Import it from **Fleet → More → Import from a .sam.zip archive** (or `bin/rails "sam:import[file.sam.zip,owner@example.com]"`). The archive format is the original Simple Aircraft Manager's, so archives move between the two apps.
## Features ## Features
@@ -129,9 +140,9 @@ To back up or move a single aircraft with all its files, use **Access & Sharing
| Fleet dashboard | Every aircraft you can access, with airworthiness status and its top issues. | | 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`. | | 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). | | 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). | | 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. | | 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. | | 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. | | 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. |
@@ -139,35 +150,40 @@ To back up or move a single aircraft with all its files, use **Access & Sharing
| 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. | | 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. | | 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. | | 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. | | 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. | | 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. | | 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. | | 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). | | 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. | | 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. | | 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). | | 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`. | | Activity log | Every write is recorded as an `AircraftEvent`; the Activity tab loads them as you scroll. |
| 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. | | 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. | | 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**. | | Help | The [user guide](docs/guide/README.md), shown in the app under **Help**. |
### Roles ### Roles
| Action | Admin | Owner | Pilot | 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:
|---|:-:|:-:|:-:|
| View everything on the aircraft | ✓ | ✓ | ✓ | | Action | Viewer | Pilot | Mechanic | Owner |
| Update hours, log flights, add squawks/notes/oil/fuel | ✓ | ✓ | ✓ | |---|:-:|:-:|:-:|:-:|
| Defer squawks (91.213(d)) | ✓ | ✓ | ✓ | | View everything on the aircraft | ✓ | ✓ | ✓ | ✓ |
| Sign logbook entries with their own certificate | ✓ | ✓ | ✓ | | Log flights, correct own flights | | ✓ | | ✓ |
| Edit or delete squawks and notes, resolve squawks | ✓ | ✓ | | | Update hours, report and defer squawks (91.213(d)), add notes/oil/fuel | | ✓ | ✓ | ✓ |
| Components, logbook, ADs, inspections, documents, major records | ✓ | ✓ | | | Sign logbook entries with their own certificate | | ✓ | ✓ | ✓ |
| Edit or delete aircraft, manage people and share links | ✓ | ✓ | | | Logbook, components, ADs, inspections, documents, major records, W&B; edit squawks, notes, oil/fuel | | | ✓ | ✓ |
| Create aircraft (creator becomes owner) | ✓ | ✓ | ✓ | | Reminders and overdue alerts | | | ✓ | ✓ |
| Users, component types, airports, templates, settings, off-site backup, procedures and audits | ✓ | | | | 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. Users who aren't on an aircraft get a 404 for it, identical to a missing record.
@@ -188,15 +204,27 @@ Users who aren't on an aircraft get a 404 for it, identical to a missing record.
Differences from the original: Differences from the original:
- Integer primary keys instead of UUIDs. Share tokens are 32-character random strings. - 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. - 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 ### 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 ### 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 PWA. 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
Every piece of text the app shows (pages, emails, messages, labels, printed logbook entries, the procedures and records-package text, and the scripts' messages) is in [`config/locales/en.yml`](config/locales/en.yml). To translate the app:
1. Copy `en.yml` to `<locale>.yml` (for example `es.yml`), change the top key from `en:` to `es:`, and translate the values. Keep the `%{name}` placeholders and any HTML tags in keys ending in `_html`. Keys with `one:` / `other:` are counted forms.
2. For month and day names in dates, also add that language's standard Rails translations (for example from the [rails-i18n](https://github.com/svenfuchs/rails-i18n) project).
3. Set `APP_LOCALE=es` and restart. Anything not yet translated shows in English.
Where the text lives in `en.yml`: `labels:` are the names of stored values (statuses, types, priorities); `activerecord:` holds field names and validation messages; `flash:` holds the messages shown after an action; `services:`, `models:` and `helpers:` hold text built in Ruby; `js:` holds the scripts' text; the rest are keyed by page (`<controller>.<view>.<key>`). The user guide under Help is Markdown in `docs/guide` and is translated separately.
In development and tests a missing translation raises an error, so a page that uses a key not in `en.yml` fails its test.
## Disclaimer ## Disclaimer
+1 -1
View File
@@ -1 +1 @@
2026.11.2 2026.11.7
+41 -1
View File
@@ -5,6 +5,7 @@
--color-page: oklch(96.8% 0.007 247.896); /* slate-100 */ --color-page: oklch(96.8% 0.007 247.896); /* slate-100 */
--color-surface: oklch(100% 0 0); /* white: cards, inputs, menus */ --color-surface: oklch(100% 0 0); /* white: cards, inputs, menus */
--color-header: oklch(20.8% 0.042 265.755); /* slate-900: top bar, dark in both themes */ --color-header: oklch(20.8% 0.042 265.755); /* slate-900: top bar, dark in both themes */
--color-header-offline: oklch(50.5% 0.213 27.518); /* red-700: top bar when the server can't be reached */
--color-accent: oklch(50% 0.134 242.749); /* sky-700: primary buttons */ --color-accent: oklch(50% 0.134 242.749); /* sky-700: primary buttons */
--color-accent-hover: oklch(44.3% 0.11 240.79); /* sky-800 */ --color-accent-hover: oklch(44.3% 0.11 240.79); /* sky-800 */
} }
@@ -15,6 +16,9 @@
@utility btn-danger { @apply btn bg-surface text-red-700 ring-1 ring-red-300 ring-inset hover:bg-red-50; } @utility btn-danger { @apply btn bg-surface text-red-700 ring-1 ring-red-300 ring-inset hover:bg-red-50; }
@utility btn-sm { @apply px-2 py-1 text-xs; } @utility btn-sm { @apply px-2 py-1 text-xs; }
@utility link { @apply text-sky-700 hover:underline; } @utility link { @apply text-sky-700 hover:underline; }
/* The "More" menu (ApplicationHelper#more_menu): secondary actions, one per row. */
@utility menu { @apply absolute right-0 z-30 mt-2 w-60 rounded-md bg-surface py-1 shadow-lg ring-1 ring-slate-200; }
@utility menu-item { @apply block w-full px-4 py-2 text-left text-sm text-slate-700 hover:bg-slate-100 cursor-pointer; }
@utility card { @apply rounded-lg bg-surface shadow-sm ring-1 ring-slate-200; } @utility card { @apply rounded-lg bg-surface shadow-sm ring-1 ring-slate-200; }
@utility card-header { @apply flex flex-wrap items-center justify-between gap-3 border-b border-slate-200 px-4 py-3; } @utility card-header { @apply flex flex-wrap items-center justify-between gap-3 border-b border-slate-200 px-4 py-3; }
@@ -22,7 +26,7 @@
@utility card-body { @apply p-4; } @utility card-body { @apply p-4; }
@utility label { @apply block text-sm font-medium text-slate-700 mb-1; } @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 hint { @apply mt-1 text-xs text-slate-500; }
@utility field-error { @apply mt-1 text-xs text-red-600; } @utility field-error { @apply mt-1 text-xs text-red-600; }
@@ -59,6 +63,7 @@
--color-page: oklch(15.5% 0.035 264); --color-page: oklch(15.5% 0.035 264);
--color-surface: oklch(20.8% 0.042 265.755); --color-surface: oklch(20.8% 0.042 265.755);
--color-header: oklch(12.9% 0.042 264.695); --color-header: oklch(12.9% 0.042 264.695);
--color-header-offline: oklch(44.4% 0.177 26.899); /* red-800 */
--color-accent: oklch(50% 0.134 242.749); /* same blue: white text stays ≥ 4.5:1 */ --color-accent: oklch(50% 0.134 242.749); /* same blue: white text stays ≥ 4.5:1 */
--color-accent-hover: oklch(54% 0.15 242); --color-accent-hover: oklch(54% 0.15 242);
@@ -181,3 +186,38 @@
.btn-sm { padding: 0.4rem 0.75rem; font-size: 0.8125rem; } .btn-sm { padding: 0.4rem 0.75rem; font-size: 0.8125rem; }
.btn-primary, .btn-secondary, .btn-danger { min-height: 2.5rem; } .btn-primary, .btn-secondary, .btn-danger { min-height: 2.5rem; }
} }
/* A label and its value on one row (label column, then value), e.g. a flight's details. */
@utility detail-row {
@apply grid grid-cols-[6.5rem_minmax(0,1fr)] items-baseline gap-x-3;
& > dt { @apply text-slate-500; }
}
/* The top bar's connection status (connection_controller.js, after
SilverBullet): red when the server can't be reached, and a ring that fills
with the percentage in its hole while saving for offline or sending. Amber
and full while flights or squawks wait to send, with how many. */
header.is-offline { --color-header: var(--color-header-offline); }
.sync-ring {
position: relative;
display: inline-block;
flex: none;
width: 24px;
height: 24px;
border-radius: 9999px;
background: conic-gradient(var(--ring-color, white) var(--progress, 0%), rgb(255 255 255 / 0.25) 0);
}
.sync-ring[hidden] { display: none; }
.sync-ring.is-waiting { --ring-color: oklch(87.9% 0.169 91.605); } /* amber-300 */
.sync-ring > span {
position: absolute;
inset: 2.5px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 9999px;
background-color: var(--color-header);
font-size: 9px;
font-variant-numeric: tabular-nums;
line-height: 1;
}
@@ -1,16 +0,0 @@
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
set_current_user || reject_unauthorized_connection
end
private
def set_current_user
if session = Session.find_by(id: cookies.signed[:session_id])
self.current_user = session.user
end
end
end
end
+8 -8
View File
@@ -2,33 +2,33 @@
# search terms used. # search terms used.
class AdAlertsController < ApplicationController class AdAlertsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! requires_permission :manage_ads
before_action :set_alert, only: %i[track dismiss] 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: "Try again in a minute." } 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") }
def check def check
found = AdWatch.new(@aircraft).check! found = AdWatch.new(@aircraft).check!
redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"), redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"),
notice: found.any? ? "Found #{helpers.pluralize(found.size, 'newly published AD')} to review." : "No new ADs found for #{AdWatch.new(@aircraft).terms.map(&:label).uniq.to_sentence}." notice: found.any? ? t("flash.ad_alerts.found", count: found.size) : t("flash.ad_alerts.none_found", terms: AdWatch.new(@aircraft).terms.map(&:label).uniq.to_sentence)
rescue AdWatch::Error => e rescue AdWatch::Error => e
redirect_to aircraft_airworthiness_directives_path(@aircraft), alert: "Couldn't check for new ADs: #{e.message}." redirect_to aircraft_airworthiness_directives_path(@aircraft), alert: t("flash.ad_alerts.couldn_t_check_for", message: e.message)
end end
def track def track
ad = @alert.track! ad = @alert.track!
log_event("ad", "AD tracked from the Federal Register: #{ad.name}") log_event("ad", t("flash.ad_alerts.ad_tracked_from_the", name: ad.name))
redirect_to edit_aircraft_airworthiness_directive_path(@aircraft, ad), redirect_to edit_aircraft_airworthiness_directive_path(@aircraft, ad),
notice: "#{ad.name} is now tracked. Set its applicability and recurrence from the AD's text, then record compliance or mark it not applicable." notice: t("flash.ad_alerts.is_now_tracked_set", name: ad.name)
end end
def dismiss def dismiss
@alert.dismiss! @alert.dismiss!
redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"), notice: "Dismissed." redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"), notice: t("flash.ad_alerts.dismissed")
end end
def terms def terms
@aircraft.update!(ad_watch_terms: params[:ad_watch_terms].to_s.strip.first(500).presence) @aircraft.update!(ad_watch_terms: params[:ad_watch_terms].to_s.strip.first(500).presence)
redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"), notice: "Search terms saved." redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"), notice: t("flash.ad_alerts.search_terms_saved")
end end
private private
+7 -7
View File
@@ -1,6 +1,6 @@
class AdCompliancesController < ApplicationController class AdCompliancesController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! requires_permission :manage_ads
before_action :set_compliance, only: %i[edit update destroy] before_action :set_compliance, only: %i[edit update destroy]
def new def new
@@ -9,7 +9,7 @@ class AdCompliancesController < ApplicationController
aircraft_hours_at_compliance: @aircraft.current_hours, aircraft_hours_at_compliance: @aircraft.current_hours,
compliance_method: params[:not_applicable] == "1" ? "not_applicable" : "inspection") compliance_method: params[:not_applicable] == "1" ? "not_applicable" : "inspection")
@compliance.apply_method @compliance.apply_method
@compliance.compliance_notes = "Not applicable: " if @compliance.not_applicable? @compliance.compliance_notes = t("flash.ad_compliances.not_applicable_prefix") if @compliance.not_applicable?
@compliance.fill_next_due @compliance.fill_next_due
end end
@@ -17,7 +17,7 @@ class AdCompliancesController < ApplicationController
@compliance = AdCompliance.new(compliance_params.merge(aircraft: @aircraft)) @compliance = AdCompliance.new(compliance_params.merge(aircraft: @aircraft))
if @compliance.save if @compliance.save
log_event("ad", "#{@compliance.not_applicable? ? "Marked N/A" : "Compliance recorded"}: #{@compliance.airworthiness_directive.name}") log_event("ad", "#{@compliance.not_applicable? ? "Marked N/A" : "Compliance recorded"}: #{@compliance.airworthiness_directive.name}")
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "Compliance recorded." redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: t("flash.ad_compliances.compliance_recorded")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -27,8 +27,8 @@ class AdCompliancesController < ApplicationController
def update def update
if @compliance.update(compliance_params) if @compliance.update(compliance_params)
log_event("ad", "Compliance updated: #{@compliance.airworthiness_directive.name}") log_event("ad", t("flash.ad_compliances.compliance_updated_2", name: @compliance.airworthiness_directive.name))
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "Compliance updated." redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: t("flash.ad_compliances.compliance_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -36,8 +36,8 @@ class AdCompliancesController < ApplicationController
def destroy def destroy
@compliance.destroy! @compliance.destroy!
log_event("ad", "Compliance deleted: #{@compliance.airworthiness_directive.name}") log_event("ad", t("flash.ad_compliances.compliance_deleted", name: @compliance.airworthiness_directive.name))
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "Compliance record deleted." redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: t("flash.ad_compliances.compliance_record_deleted")
end end
private private
+5 -5
View File
@@ -2,7 +2,7 @@
class AdImportsController < ApplicationController class AdImportsController < ApplicationController
include AircraftScoped include AircraftScoped
include StoredUpload include StoredUpload
before_action :require_owner! requires_permission :manage_ads
def new; end def new; end
@@ -14,7 +14,7 @@ class AdImportsController < ApplicationController
def show def show
@token = params[:token].to_s @token = params[:token].to_s
return redirect_to_upload("Upload expired. Please upload the file again.") unless stored_file?(@token) return redirect_to_upload(t("flash.uploads.expired")) unless stored_file?(@token)
@filename = params[:filename].to_s @filename = params[:filename].to_s
@import = AdImport.new(@aircraft, path: stored_path(@token), filename: @filename) @import = AdImport.new(@aircraft, path: stored_path(@token), filename: @filename)
@import.rows @import.rows
@@ -24,7 +24,7 @@ class AdImportsController < ApplicationController
def confirm def confirm
token = params[:token].to_s token = params[:token].to_s
return redirect_to_upload("Upload expired. Please upload the file again.") unless stored_file?(token) return redirect_to_upload(t("flash.uploads.expired")) unless stored_file?(token)
import = AdImport.new(@aircraft, path: stored_path(token), filename: params[:filename]) import = AdImport.new(@aircraft, path: stored_path(token), filename: params[:filename])
# Only AD numbers present in the uploaded file; values are checked against AdImport::ACTIONS. # Only AD numbers present in the uploaded file; values are checked against AdImport::ACTIONS.
decisions = params.fetch(:decisions, {}).permit(*import.rows.map(&:number)).to_h decisions = params.fetch(:decisions, {}).permit(*import.rows.map(&:number)).to_h
@@ -34,8 +34,8 @@ class AdImportsController < ApplicationController
models_covered: DrsImport.covered(@aircraft, import.rows.flat_map(&:models))) models_covered: DrsImport.covered(@aircraft, import.rows.flat_map(&:models)))
discard_upload(token) discard_upload(token)
redirect_to aircraft_airworthiness_directives_path(@aircraft), redirect_to aircraft_airworthiness_directives_path(@aircraft),
notice: "Imported #{result[:tracked]} ADs to track and #{result[:not_applicable]} marked N/A; " \ notice: t("flash.ad_imports.imported_ads_to_track", tracked: result[:tracked], not_applicable: result[:not_applicable],
"#{result[:updated]} existing ADs updated, #{result[:skipped]} skipped." updated: result[:updated], skipped: result[:skipped])
rescue AdImport::Error => e rescue AdImport::Error => e
redirect_to_upload(e.message) redirect_to_upload(e.message)
end end
+10 -10
View File
@@ -1,6 +1,6 @@
class Admin::AboutController < ApplicationController class Admin::AboutController < ApplicationController
before_action :require_admin! before_action :require_admin!
rate_limit to: 5, within: 1.minute, only: %i[test_email test_reminder check_records], with: -> { redirect_to admin_about_path, alert: "Try again in a minute." } rate_limit to: 5, within: 1.minute, only: %i[test_email test_reminder check_records], with: -> { redirect_to admin_about_path, alert: t("flash.admin_about.try_again_in_a") }
def show def show
@info = SystemInfo.new @info = SystemInfo.new
@@ -11,33 +11,33 @@ class Admin::AboutController < ApplicationController
backup = DatabaseBackup.run! backup = DatabaseBackup.run!
check = RecordsIntegrity.check! check = RecordsIntegrity.check!
if backup.ok && check.ok if backup.ok && check.ok
redirect_to admin_about_path(anchor: "records"), notice: "Backed up and checked: no problems found." redirect_to admin_about_path(anchor: "records"), notice: t("flash.admin_about.backed_up_and_checked")
else else
redirect_to admin_about_path(anchor: "records"), alert: "The records check found problems; see Records below." redirect_to admin_about_path(anchor: "records"), alert: t("flash.admin_about.the_records_check_found")
end end
end end
# This week's reminder for the current admin, now. # This week's reminder for the current admin, now.
def test_reminder def test_reminder
return redirect_to(admin_about_path, alert: "Email isn't set up yet.") unless MailSettings.configured? return redirect_to(admin_about_path, alert: t("flash.admin_about.email_isn_t_set")) unless MailSettings.configured?
unless ReminderMailer.anything_for?(current_user) unless ReminderMailer.anything_for?(current_user)
return redirect_to admin_about_path, notice: "Nothing needs attention on the aircraft you own or your certificates, so there's no reminder to send." return redirect_to admin_about_path, notice: t("flash.admin_about.nothing_needs_attention_on")
end end
ReminderMailer.weekly(current_user).deliver_now ReminderMailer.weekly(current_user).deliver_now
redirect_to admin_about_path, notice: "Reminder sent to #{current_user.email_address}." redirect_to admin_about_path, notice: t("flash.admin_about.reminder_sent_to", email_address: current_user.email_address)
rescue StandardError => e rescue StandardError => e
redirect_to admin_about_path, alert: "Sending failed: #{e.class.name.demodulize}: #{e.message.to_s.squish.truncate(240)}" redirect_to admin_about_path, alert: t("flash.admin_about.sending_failed", error: e.class.name.demodulize, message: e.message.to_s.squish.truncate(240))
end end
# Sends right away (not via the job queue) so problems show up here. # Sends right away (not via the job queue) so problems show up here.
def test_email def test_email
unless MailSettings.configured? unless MailSettings.configured?
return redirect_to admin_about_path, alert: "Email isn't set up yet: set SMTP_ADDRESS (and SMTP_PORT, SMTP_USERNAME, SMTP_PASSWORD, MAIL_FROM)." return redirect_to admin_about_path, alert: t("flash.admin_about.email_isn_t_set_2")
end end
AdminMailer.test_email(current_user).deliver_now AdminMailer.test_email(current_user).deliver_now
redirect_to admin_about_path, notice: "Test email sent to #{current_user.email_address}. If it doesn't arrive, check the spam folder." redirect_to admin_about_path, notice: t("flash.admin_about.test_email_sent_to", email_address: current_user.email_address)
rescue StandardError => e # SMTP, DNS, TLS and timeout errors alike rescue StandardError => e # SMTP, DNS, TLS and timeout errors alike
Rails.logger.warn("[test email] #{e.class}: #{e.message}") Rails.logger.warn("[test email] #{e.class}: #{e.message}")
redirect_to admin_about_path, alert: "Sending failed: #{e.class.name.demodulize}: #{e.message.to_s.squish.truncate(240)}" redirect_to admin_about_path, alert: t("flash.admin_about.sending_failed_2", error: e.class.name.demodulize, message: e.message.to_s.squish.truncate(240))
end end
end end
+5 -5
View File
@@ -16,11 +16,11 @@ class Admin::AirportsController < ApplicationController
# Queue a download + sync from OurAirports. # Queue a download + sync from OurAirports.
def refresh def refresh
if AirportUpdate.in_progress.exists? if AirportUpdate.in_progress.exists?
redirect_to admin_airports_path, alert: "An update is already running." redirect_to admin_airports_path, alert: t("flash.admin_airports.an_update_is_already")
else else
update = AirportUpdate.create!(source_url: AirportData::SOURCE_URL, requested_by: current_user) update = AirportUpdate.create!(source_url: AirportData::SOURCE_URL, requested_by: current_user)
AirportUpdateJob.perform_later(update.id) AirportUpdateJob.perform_later(update.id)
redirect_to admin_airports_path, notice: "Airport update started. Refresh this page in a minute or two." redirect_to admin_airports_path, notice: t("flash.admin_airports.airport_update_started_refresh")
end end
end end
@@ -31,7 +31,7 @@ class Admin::AirportsController < ApplicationController
def create def create
@airport = Airport.new(airport_params.merge(custom: true)) @airport = Airport.new(airport_params.merge(custom: true))
if @airport.save if @airport.save
redirect_to admin_airports_path, notice: "Custom airport #{@airport.ident} added." redirect_to admin_airports_path, notice: t("flash.admin_airports.custom_airport_added", ident: @airport.ident)
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -41,7 +41,7 @@ class Admin::AirportsController < ApplicationController
def update def update
if @airport.update(airport_params) if @airport.update(airport_params)
redirect_to admin_airports_path, notice: "#{@airport.ident} updated." redirect_to admin_airports_path, notice: t("flash.admin_airports.updated", ident: @airport.ident)
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -49,7 +49,7 @@ class Admin::AirportsController < ApplicationController
def destroy def destroy
@airport.destroy! @airport.destroy!
redirect_to admin_airports_path, notice: "#{@airport.ident} removed." redirect_to admin_airports_path, notice: t("flash.admin_airports.removed", ident: @airport.ident)
end end
private private
+1 -1
View File
@@ -12,7 +12,7 @@ class Admin::AuditsController < ApplicationController
def create def create
answers = params.fetch(:answers, {}).permit(RecordsAudit::MANUAL.keys.index_with { %i[passed note] }).to_h answers = params.fetch(:answers, {}).permit(RecordsAudit::MANUAL.keys.index_with { %i[passed note] }).to_h
run = RecordsAudit.new.record!(user: current_user, answers: answers, notes: params[:notes], sample_ids: Array(params[:sample_ids]).map(&:to_i)) run = RecordsAudit.new.record!(user: current_user, answers: answers, notes: params[:notes], sample_ids: Array(params[:sample_ids]).map(&:to_i))
redirect_to admin_audit_path(run), notice: run.passed ? "Audit recorded: everything passed." : "Audit recorded, with items that didn't pass. Note what's being done about them." redirect_to admin_audit_path(run), notice: run.passed ? t("flash.admin_audits.passed") : t("flash.admin_audits.not_passed")
end end
def show def show
@@ -13,7 +13,7 @@ class Admin::ComponentTypesController < ApplicationController
def create def create
@component_type = ComponentType.new(type_params) @component_type = ComponentType.new(type_params)
if @component_type.save if @component_type.save
redirect_to admin_component_types_path, notice: "Component type created." redirect_to admin_component_types_path, notice: t("flash.admin_component_types.component_type_created")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -23,7 +23,7 @@ class Admin::ComponentTypesController < ApplicationController
def update def update
if @component_type.update(type_params) if @component_type.update(type_params)
redirect_to admin_component_types_path, notice: "Component type updated." redirect_to admin_component_types_path, notice: t("flash.admin_component_types.component_type_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -31,7 +31,7 @@ class Admin::ComponentTypesController < ApplicationController
def destroy def destroy
if @component_type.destroy if @component_type.destroy
redirect_to admin_component_types_path, notice: "Component type deleted." redirect_to admin_component_types_path, notice: t("flash.admin_component_types.component_type_deleted")
else else
redirect_to admin_component_types_path, alert: @component_type.errors.full_messages.to_sentence redirect_to admin_component_types_path, alert: @component_type.errors.full_messages.to_sentence
end end
@@ -0,0 +1,93 @@
# Admin → Integrations: tokens for other systems (e.g. Redmine), limited to
# chosen aircraft and scopes, each with an optional webhook (docs/api.md).
# The token and webhook secret are shown once, right after they're made.
class Admin::IntegrationsController < ApplicationController
before_action :require_admin!
before_action :set_integration, only: %i[show edit update destroy new_secret]
def index
@integrations = ApiToken.integration.order(revoked_at: :desc, name: :asc).includes(:webhook_endpoints)
end
def new
@integration = ApiToken.new(kind: "integration", scopes: %w[read])
@endpoint = WebhookEndpoint.new(events: [])
end
def create
@integration = ApiToken.new(integration_params.merge(kind: "integration", user: current_user))
@endpoint = build_endpoint(@integration)
ApiToken.transaction do
@integration.save!
@endpoint&.save!
end
@secret = @endpoint&.secret
render :created
rescue ActiveRecord::RecordInvalid
@endpoint ||= WebhookEndpoint.new(events: [])
render :new, status: :unprocessable_entity
end
def show
@endpoint = @integration.webhook_endpoints.first
@deliveries = @endpoint ? @endpoint.deliveries.recent.limit(25) : []
end
def edit
@endpoint = @integration.webhook_endpoints.first || WebhookEndpoint.new(events: [])
end
def update
@endpoint = @integration.webhook_endpoints.first
ApiToken.transaction do
@integration.update!(integration_params)
if webhook_params[:url].present?
@endpoint ||= @integration.webhook_endpoints.new(secret: WebhookEndpoint.new_secret)
@endpoint.update!(webhook_params)
else
@endpoint&.destroy!
end
end
redirect_to admin_integration_path(@integration), notice: t("flash.admin_integrations.saved")
rescue ActiveRecord::RecordInvalid
@endpoint ||= WebhookEndpoint.new(events: [])
render :edit, status: :unprocessable_entity
end
# A new webhook secret, shown once.
def new_secret
@endpoint = @integration.webhook_endpoints.first or return redirect_to(admin_integration_path(@integration))
@endpoint.update!(secret: WebhookEndpoint.new_secret)
@secret = @endpoint.secret
render :created
end
def destroy
@integration.revoke!
@integration.webhook_endpoints.update_all(enabled: false)
redirect_to admin_integrations_path, notice: t("flash.admin_integrations.revoked", name: @integration.name)
end
private
def set_integration = @integration = ApiToken.integration.find(params[:id])
def integration_params
p = params.require(:api_token).permit(:name, scopes: [], aircraft_ids: [])
p[:scopes] = Array(p[:scopes]) & ApiToken::SCOPES.keys
p[:aircraft_ids] = Aircraft.where(id: Array(p[:aircraft_ids])).ids
p
end
def webhook_params
p = params.fetch(:webhook, {}).permit(:url, :enabled, events: [])
p[:events] = Array(p[:events]) & WebhookEndpoint::EVENTS.keys
p[:enabled] = p[:enabled] != "0"
p
end
def build_endpoint(integration)
return if webhook_params[:url].blank?
integration.webhook_endpoints.new(webhook_params.merge(secret: WebhookEndpoint.new_secret))
end
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
@@ -14,7 +14,7 @@ class Admin::LogbookTemplatesController < ApplicationController
def create def create
@template = LogbookTemplate.new(template_params) @template = LogbookTemplate.new(template_params)
if @template.save if @template.save
redirect_to admin_logbook_templates_path, notice: "Template added." redirect_to admin_logbook_templates_path, notice: t("flash.admin_logbook_templates.template_added")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -24,7 +24,7 @@ class Admin::LogbookTemplatesController < ApplicationController
def update def update
if @template.update(template_params) if @template.update(template_params)
redirect_to admin_logbook_templates_path, notice: "Template updated." redirect_to admin_logbook_templates_path, notice: t("flash.admin_logbook_templates.template_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -32,12 +32,12 @@ class Admin::LogbookTemplatesController < ApplicationController
def destroy def destroy
@template.destroy! @template.destroy!
redirect_to admin_logbook_templates_path, notice: "Template deleted." redirect_to admin_logbook_templates_path, notice: t("flash.admin_logbook_templates.template_deleted")
end end
def restore def restore
added = LogbookTemplate.restore_defaults! added = LogbookTemplate.restore_defaults!
redirect_to admin_logbook_templates_path, notice: added.positive? ? "Restored #{helpers.pluralize(added, 'built-in template')}." : "All the built-in templates are already here." redirect_to admin_logbook_templates_path, notice: added.positive? ? t("flash.admin_logbook_templates.restored", count: added) : t("flash.admin_logbook_templates.all_present")
end end
private private
@@ -16,12 +16,12 @@ class Admin::OffsiteBackupsController < ApplicationController
changed_client = attrs[:client_id].present? && attrs[:client_id].strip != @connection.client_id changed_client = attrs[:client_id].present? && attrs[:client_id].strip != @connection.client_id
@connection.disconnect! if changed_client && @connection.connected? @connection.disconnect! if changed_client && @connection.connected?
@connection.update!(attrs.transform_values(&:strip)) @connection.update!(attrs.transform_values(&:strip))
redirect_to admin_offsite_backup_path, notice: "Saved. Now connect your Google account." redirect_to admin_offsite_backup_path, notice: t("flash.admin_offsite_backups.saved_now_connect_your")
end end
# Off to Google to grant access (a link, so no form-action CSP entry is needed). # Off to Google to grant access (a link, so no form-action CSP entry is needed).
def connect def connect
return redirect_to(admin_offsite_backup_path, alert: "Enter the Google OAuth client ID and secret first.") unless @connection.configured? return redirect_to(admin_offsite_backup_path, alert: t("flash.admin_offsite_backups.enter_the_google_oauth")) unless @connection.configured?
session[:offsite_oauth_state] = state = SecureRandom.urlsafe_base64(24) session[:offsite_oauth_state] = state = SecureRandom.urlsafe_base64(24)
redirect_to GoogleDriveClient.authorize_url(client_id: @connection.client_id, redirect_uri: @connection.redirect_uri, state: state), redirect_to GoogleDriveClient.authorize_url(client_id: @connection.client_id, redirect_uri: @connection.redirect_uri, state: state),
allow_other_host: true allow_other_host: true
@@ -30,9 +30,9 @@ class Admin::OffsiteBackupsController < ApplicationController
def callback def callback
expected = session.delete(:offsite_oauth_state) expected = session.delete(:offsite_oauth_state)
unless expected.present? && params[:state].present? && ActiveSupport::SecurityUtils.secure_compare(expected, params[:state].to_s) unless expected.present? && params[:state].present? && ActiveSupport::SecurityUtils.secure_compare(expected, params[:state].to_s)
return redirect_to(admin_offsite_backup_path, alert: "That Google sign-in didn't match a request from here. Try connecting again.") return redirect_to(admin_offsite_backup_path, alert: t("flash.admin_offsite_backups.that_google_sign_in"))
end end
return redirect_to(admin_offsite_backup_path, alert: "Google Drive wasn't connected (#{params[:error]}).") if params[:error].present? || params[:code].blank? return redirect_to(admin_offsite_backup_path, alert: t("flash.admin_offsite_backups.google_drive_wasn_t", error: params[:error])) if params[:error].present? || params[:code].blank?
token = GoogleDriveClient.exchange_code(client_id: @connection.client_id, client_secret: @connection.client_secret, token = GoogleDriveClient.exchange_code(client_id: @connection.client_id, client_secret: @connection.client_secret,
code: params[:code].to_s, redirect_uri: @connection.redirect_uri) code: params[:code].to_s, redirect_uri: @connection.redirect_uri)
@@ -42,25 +42,25 @@ class Admin::OffsiteBackupsController < ApplicationController
@connection.ensure_folders!(drive) @connection.ensure_folders!(drive)
Rails.logger.info("[offsite] #{current_user.email_address} connected Google Drive #{@connection.account_email}") Rails.logger.info("[offsite] #{current_user.email_address} connected Google Drive #{@connection.account_email}")
OffsiteBackupJob.perform_later OffsiteBackupJob.perform_later
redirect_to admin_offsite_backup_path, notice: "Google Drive connected (#{@connection.account_email}). The first off-site backup has started; it copies every uploaded file, so it can take a while." redirect_to admin_offsite_backup_path, notice: t("flash.admin_offsite_backups.google_drive_connected_the", account_email: @connection.account_email)
rescue GoogleDriveClient::Error => e rescue GoogleDriveClient::Error => e
redirect_to admin_offsite_backup_path, alert: "Couldn't connect Google Drive: #{e.message}" redirect_to admin_offsite_backup_path, alert: t("flash.admin_offsite_backups.couldn_t_connect_google", message: e.message)
end end
def destroy def destroy
@connection.disconnect! @connection.disconnect!
Rails.logger.info("[offsite] #{current_user.email_address} disconnected Google Drive") Rails.logger.info("[offsite] #{current_user.email_address} disconnected Google Drive")
redirect_to admin_offsite_backup_path, notice: "Google Drive disconnected. The copies already there stay in your Drive." redirect_to admin_offsite_backup_path, notice: t("flash.admin_offsite_backups.google_drive_disconnected_the")
end end
def backup_now def backup_now
OffsiteBackupJob.perform_later OffsiteBackupJob.perform_later
redirect_to admin_offsite_backup_path, notice: "Off-site backup started. Refresh in a minute to see the result." redirect_to admin_offsite_backup_path, notice: t("flash.admin_offsite_backups.off_site_backup_started")
end end
def restore_test def restore_test
OffsiteBackupJob.perform_later("restore_test") OffsiteBackupJob.perform_later("restore_test")
redirect_to admin_offsite_backup_path, notice: "Restore test started. Refresh in a minute to see the result." redirect_to admin_offsite_backup_path, notice: t("flash.admin_offsite_backups.restore_test_started_refresh")
end end
private private
@@ -14,7 +14,7 @@ class Admin::ProceduresController < ApplicationController
if @policy.update(params.require(:recordkeeping_policy).permit(:operator_name, :responsible_name, :responsible_title, :hosting_description, if @policy.update(params.require(:recordkeeping_policy).permit(:operator_name, :responsible_name, :responsible_title, :hosting_description,
:offsite_backup_description, :audit_interval_months, :audit_sample_size, :offsite_backup_description, :audit_interval_months, :audit_sample_size,
:additional_procedures)) :additional_procedures))
redirect_to admin_procedures_path, notice: "Saved. Review the draft and adopt it as a new revision when it's right." redirect_to admin_procedures_path, notice: t("flash.admin_procedures.saved_review_the_draft")
else else
@revisions = ProceduresRevision.latest_first @revisions = ProceduresRevision.latest_first
render :show, status: :unprocessable_entity render :show, status: :unprocessable_entity
@@ -29,14 +29,14 @@ class Admin::ProceduresController < ApplicationController
def adopt def adopt
policy = RecordkeepingPolicy.current policy = RecordkeepingPolicy.current
if policy.unfilled_fields.any? if policy.unfilled_fields.any?
return redirect_to(admin_procedures_path, alert: "Fill in the [bracketed] blanks first: #{policy.unfilled_fields.to_sentence}.") return redirect_to(admin_procedures_path, alert: t("flash.admin_procedures.fill_in_the_bracketed", items: policy.unfilled_fields.to_sentence))
end end
return redirect_to(admin_procedures_path, alert: "Fill in the operator, responsible person, hosting and off-site backup (or connect Google Drive) first.") unless policy.complete? return redirect_to(admin_procedures_path, alert: t("flash.admin_procedures.fill_in_the_operator")) unless policy.complete?
number = (ProceduresRevision.maximum(:number) || 0) + 1 number = (ProceduresRevision.maximum(:number) || 0) + 1
revision = ProceduresRevision.create!(number: number, adopted_by: current_user, adopted_at: Time.current, revision = ProceduresRevision.create!(number: number, adopted_by: current_user, adopted_at: Time.current,
summary: params[:summary].to_s.strip.first(500).presence || "Revision #{number}", summary: params[:summary].to_s.strip.first(500).presence || "Revision #{number}",
content: draft_html(number: number, summary: params[:summary].to_s.strip.first(500))) content: draft_html(number: number, summary: params[:summary].to_s.strip.first(500)))
redirect_to admin_procedures_path, notice: "Revision #{revision.number} adopted. Print it or keep the PDF with your records." redirect_to admin_procedures_path, notice: t("flash.admin_procedures.revision_adopted_print_it", number: revision.number)
end end
def revision def revision
@@ -48,7 +48,7 @@ class Admin::ProceduresController < ApplicationController
def draft_html(number: nil, summary: nil) def draft_html(number: nil, summary: nil)
render_to_string(partial: "admin/procedures/document", render_to_string(partial: "admin/procedures/document",
locals: { policy: RecordkeepingPolicy.current, number: number || "#{(ProceduresRevision.maximum(:number) || 0) + 1} (draft)", locals: { policy: RecordkeepingPolicy.current, number: number || t("flash.admin_procedures.draft_number", number: (ProceduresRevision.maximum(:number) || 0) + 1),
adopted_at: number ? Time.current : nil, adopted_by: number ? current_user : nil, adopted_at: number ? Time.current : nil, adopted_by: number ? current_user : nil,
revisions: ProceduresRevision.latest_first.to_a, summary: summary }) revisions: ProceduresRevision.latest_first.to_a, summary: summary })
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
+4 -4
View File
@@ -2,18 +2,18 @@ class Admin::SettingsController < ApplicationController
before_action :require_admin! before_action :require_admin!
def edit 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 end
def update 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) records = Setting.update_integers(submitted)
@errors = records.flat_map { _1.errors.full_messages } @errors = records.flat_map { _1.errors.full_messages }
if @errors.empty? if @errors.empty?
Rails.logger.info("[settings] #{current_user.email_address} changed #{submitted.inspect}") Rails.logger.info("[settings] #{current_user.email_address} changed #{submitted.inspect}")
redirect_to edit_admin_settings_path, notice: "Settings saved." redirect_to edit_admin_settings_path, notice: t("flash.admin_settings.settings_saved")
else 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 render :edit, status: :unprocessable_entity
end end
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
+12 -12
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] before_action :set_user, only: %i[edit update destroy disable enable unlock reset_two_factor]
def index 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 end
def new def new
@@ -14,7 +14,7 @@ class Admin::UsersController < ApplicationController
@user = User.new(user_params) @user = User.new(user_params)
@user.admin = admin_flag @user.admin = admin_flag
if @user.save if @user.save
redirect_to admin_users_path, notice: "User #{@user.email_address} created." redirect_to admin_users_path, notice: t("flash.admin_users.user_created", email_address: @user.email_address)
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -26,12 +26,12 @@ class Admin::UsersController < ApplicationController
attrs = user_params attrs = user_params
attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank? attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank?
if @user == current_user && !admin_flag if @user == current_user && !admin_flag
return redirect_to admin_users_path, alert: "You can't remove your own admin rights." return redirect_to admin_users_path, alert: t("flash.admin_users.you_can_t_remove")
end end
@user.admin = admin_flag @user.admin = admin_flag
if @user.update(attrs) if @user.update(attrs)
@user.sessions.where.not(id: Current.session.id).destroy_all if attrs.key?(:password) # new password signs them out @user.sessions.where.not(id: Current.session.id).destroy_all if attrs.key?(:password) # new password signs them out
redirect_to admin_users_path, notice: "User updated." redirect_to admin_users_path, notice: t("flash.admin_users.user_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -41,7 +41,7 @@ class Admin::UsersController < ApplicationController
# keeping their account, so the signatures they made stay attributed. # keeping their account, so the signatures they made stay attributed.
def unlock def unlock
@user.unlock! @user.unlock!
redirect_to admin_users_path, notice: "#{@user.email_address} unlocked." redirect_to admin_users_path, notice: t("flash.admin_users.unlocked", email_address: @user.email_address)
end end
# For a user who lost their authenticator: they sign in with their password # For a user who lost their authenticator: they sign in with their password
@@ -49,28 +49,28 @@ class Admin::UsersController < ApplicationController
def reset_two_factor def reset_two_factor
@user.disable_otp! @user.disable_otp!
Rails.logger.info("[auth] #{current_user.email_address} turned off two-factor for #{@user.email_address}") Rails.logger.info("[auth] #{current_user.email_address} turned off two-factor for #{@user.email_address}")
redirect_to admin_users_path, notice: "Two-factor turned off for #{@user.email_address}. Ask them to set it up again from their profile." redirect_to admin_users_path, notice: t("flash.admin_users.two_factor_turned_off", email_address: @user.email_address)
end end
def disable def disable
return redirect_to admin_users_path, alert: "You can't disable yourself." if @user == current_user return redirect_to admin_users_path, alert: t("flash.admin_users.you_can_t_disable") if @user == current_user
@user.update!(disabled_at: Time.current) @user.update!(disabled_at: Time.current)
@user.sessions.destroy_all @user.sessions.destroy_all
redirect_to admin_users_path, notice: "#{@user.email_address} disabled: signed out, can't sign in or sign entries. Their past signatures are kept." redirect_to admin_users_path, notice: t("flash.admin_users.disabled_signed_out_can", email_address: @user.email_address)
end end
def enable def enable
@user.update!(disabled_at: nil) @user.update!(disabled_at: nil)
redirect_to admin_users_path, notice: "#{@user.email_address} enabled." redirect_to admin_users_path, notice: t("flash.admin_users.enabled", email_address: @user.email_address)
end end
def destroy def destroy
return redirect_to admin_users_path, alert: "You can't delete yourself." if @user == current_user return redirect_to admin_users_path, alert: t("flash.admin_users.you_can_t_delete") if @user == current_user
if @user.entry_signatures.exists? if @user.entry_signatures.exists?
return redirect_to admin_users_path, alert: "#{@user.email_address} has signed logbook entries; disable the account instead of deleting it." return redirect_to admin_users_path, alert: t("flash.admin_users.has_signed_logbook_entries", email_address: @user.email_address)
end end
@user.destroy! @user.destroy!
redirect_to admin_users_path, notice: "User deleted." redirect_to admin_users_path, notice: t("flash.admin_users.user_deleted")
end end
private private
@@ -33,7 +33,7 @@ class AirTrailConnectionsController < ApplicationController
# Link existing AirTrail flights and push everything else, in the background. # Link existing AirTrail flights and push everything else, in the background.
def sync def sync
AirTrailBackfillJob.perform_later(@connection.id) AirTrailBackfillJob.perform_later(@connection.id)
redirect_to air_trail_connection_path, notice: "Sync started. Refresh this page in a minute to see progress." redirect_to air_trail_connection_path, notice: t("flash.air_trail_connections.sync_started_refresh_this")
end end
def map_airport def map_airport
@@ -42,9 +42,9 @@ class AirTrailConnectionsController < ApplicationController
match = target.present? && AirTrailSyncer.new(@connection).map_airport(code, target) match = target.present? && AirTrailSyncer.new(@connection).map_airport(code, target)
if match if match
AirTrailBackfillJob.perform_later(@connection.id) # retry flights that needed it AirTrailBackfillJob.perform_later(@connection.id) # retry flights that needed it
redirect_to air_trail_connection_path, notice: "#{code} mapped to #{match['icao']} (#{match['name']}). Retrying affected flights." redirect_to air_trail_connection_path, notice: t("flash.air_trail_connections.mapped_to_retrying_affected", code: code, icao: match["icao"], name: match["name"])
else else
redirect_to air_trail_connection_path, alert: "AirTrail has no airport matching “#{target}”." redirect_to air_trail_connection_path, alert: t("flash.air_trail_connections.airtrail_has_no_airport", target: target)
end end
rescue AirTrailClient::Error => e rescue AirTrailClient::Error => e
redirect_to air_trail_connection_path, alert: e.message redirect_to air_trail_connection_path, alert: e.message
@@ -53,7 +53,7 @@ class AirTrailConnectionsController < ApplicationController
# Stops syncing. Flights already in AirTrail are left there. # Stops syncing. Flights already in AirTrail are left there.
def destroy def destroy
@connection.destroy! @connection.destroy!
redirect_to air_trail_connection_path, notice: "AirTrail disconnected. Flights already in AirTrail were left as they are." redirect_to air_trail_connection_path, notice: t("flash.air_trail_connections.airtrail_disconnected_flights_already")
end end
private private
@@ -81,9 +81,9 @@ class AirTrailConnectionsController < ApplicationController
missing = me.dig("credential", "kind") == "apiKey" ? AirTrailConnection::REQUIRED_SCOPES - scopes : [] missing = me.dig("credential", "kind") == "apiKey" ? AirTrailConnection::REQUIRED_SCOPES - scopes : []
@connection.update!(remote_user_id: me["id"], remote_username: me["username"], checked_at: Time.current, @connection.update!(remote_user_id: me["id"], remote_username: me["username"], checked_at: Time.current,
status: missing.empty? ? "ok" : "error", status: missing.empty? ? "ok" : "error",
last_error: missing.empty? ? nil : "API key is missing scopes: #{missing.join(', ')}") last_error: missing.empty? ? nil : t("flash.air_trail_connections.missing_scopes", scopes: missing.join(", ")))
if missing.empty? if missing.empty?
flash[:notice] = "Connected to AirTrail as #{me['username']}." flash[:notice] = t("flash.air_trail_connections.connected_to_airtrail_as", username: me["username"])
else else
flash[:alert] = @connection.last_error flash[:alert] = @connection.last_error
end end
@@ -1,6 +1,7 @@
# Download the aircraft's flights as an AirTrail import file. # Download the aircraft's flights as an AirTrail import file.
class AirTrailExportsController < ApplicationController class AirTrailExportsController < ApplicationController
include AircraftScoped include AircraftScoped
requires_permission :log_flights
def new def new
@export = build_export @export = build_export
+26 -11
View File
@@ -1,7 +1,10 @@
class AircraftController < ApplicationController class AircraftController < ApplicationController
include AircraftScoped include AircraftScoped
skip_before_action :set_aircraft, only: %i[index new create] skip_before_action :set_aircraft, :authorize_permission!, only: %i[index new create]
before_action :require_owner!, only: %i[edit update destroy] 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 def index
@aircraft_list = current_user.accessible_aircraft.ordered.with_attached_picture @aircraft_list = current_user.accessible_aircraft.ordered.with_attached_picture
@@ -29,7 +32,7 @@ class AircraftController < ApplicationController
@aircraft.roles.create!(user: current_user, role: "owner") @aircraft.roles.create!(user: current_user, role: "owner")
@aircraft.log_event!("aircraft", "Aircraft created") @aircraft.log_event!("aircraft", "Aircraft created")
end end
redirect_to @aircraft, notice: "#{@aircraft.tail_number} added." redirect_to @aircraft, notice: t("flash.aircraft.added", tail_number: @aircraft.tail_number)
rescue ActiveRecord::RecordInvalid rescue ActiveRecord::RecordInvalid
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -38,8 +41,8 @@ class AircraftController < ApplicationController
def update def update
if @aircraft.update(aircraft_params) if @aircraft.update(aircraft_params)
log_event("aircraft", "Aircraft details updated") log_event("aircraft", t("flash.aircraft.aircraft_details_updated"))
redirect_to @aircraft, notice: "Aircraft updated." redirect_to @aircraft, notice: t("flash.aircraft.aircraft_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -47,23 +50,35 @@ class AircraftController < ApplicationController
def destroy def destroy
@aircraft.destroy! @aircraft.destroy!
redirect_to root_path, notice: "#{@aircraft.tail_number} deleted." redirect_to root_path, notice: t("flash.aircraft.deleted", tail_number: @aircraft.tail_number)
end end
# Pilots and above: set absolute tach/hobbs readings. # Pilots and above: set absolute tach/hobbs readings.
def update_hours def update_hours
delta = HoursService.new(@aircraft).update_hours!( before = { tach: @aircraft.tach_time.to_d, hobbs: @aircraft.hobbs_time.to_d }
tach_time: params.require(:tach_time), hobbs_time: params[:hobbs_time] HoursService.new(@aircraft).update_hours!(tach_time: params.require(:tach_time), hobbs_time: params[:hobbs_time])
) redirect_to @aircraft, notice: hours_notice(before)
redirect_to @aircraft, notice: "Hours updated (#{delta >= 0 ? '+' : ''}#{delta})."
rescue AircraftGroundedError => e rescue AircraftGroundedError => e
redirect_to @aircraft, alert: e.message redirect_to @aircraft, alert: e.message
rescue ArgumentError rescue ArgumentError
redirect_to @aircraft, alert: "Enter a valid tach reading." redirect_to @aircraft, alert: t("flash.aircraft.enter_a_valid_tach")
end end
private private
# "Tach 4,211.6 → 4,213.0 (+1.4). In-service components moved +1.4 hrs; no flight was logged."
def hours_notice(before)
after = { tach: @aircraft.tach_time.to_d, hobbs: @aircraft.hobbs_time.to_d }
signed = ->(d) { "#{d.negative? ? '−' : '+'}#{helpers.hours(d.abs)}" }
changes = %i[tach hobbs].filter_map do |meter|
d = after[meter] - before[meter]
t("flash.aircraft.meter_changed", meter: Aircraft::TIME_BASES[meter.to_s], from: helpers.hours(before[meter]), to: helpers.hours(after[meter]), delta: signed.(d)) unless d.zero?
end
moved = @aircraft.hobbs? ? after[:hobbs] - before[:hobbs] : after[:tach] - before[:tach]
return t("flash.aircraft.hours_unchanged") if changes.empty?
t(moved.negative? ? "flash.aircraft.hours_corrected" : "flash.aircraft.hours_updated", changes: changes.join(" · "), delta: signed.(moved))
end
def aircraft_param = params[:id] def aircraft_param = params[:id]
def aircraft_params def aircraft_params
@@ -1,7 +1,7 @@
# Download an aircraft as a .sam.zip archive (owners and admins). # Download an aircraft as a .sam.zip archive (owners and admins).
class AircraftExportsController < ApplicationController class AircraftExportsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! requires_permission :export_data
EXPORT_DIR = Rails.root.join("tmp/exports") EXPORT_DIR = Rails.root.join("tmp/exports")
@@ -13,7 +13,7 @@ class AircraftExportsController < ApplicationController
Dir[EXPORT_DIR.join("*.zip")].each { |old| File.delete(old) if File.mtime(old) < 1.hour.ago } Dir[EXPORT_DIR.join("*.zip")].each { |old| File.delete(old) if File.mtime(old) < 1.hour.ago }
path = EXPORT_DIR.join("#{SecureRandom.hex(12)}.zip").to_s path = EXPORT_DIR.join("#{SecureRandom.hex(12)}.zip").to_s
exporter.write_to(path) exporter.write_to(path)
log_event("aircraft", "Aircraft exported (.sam.zip)") log_event("aircraft", t("flash.aircraft_exports.aircraft_exported_sam_zip"))
# Generic binary, not application/zip: Safari unzips zip downloads into a # Generic binary, not application/zip: Safari unzips zip downloads into a
# folder ("Open safe files"), and the archive must stay one file to import. # folder ("Open safe files"), and the archive must stay one file to import.
send_file path, filename: exporter.filename, type: "application/octet-stream", disposition: "attachment" send_file path, filename: exporter.filename, type: "application/octet-stream", disposition: "attachment"
@@ -2,20 +2,21 @@
# create an aircraft with all its records. The archive is checked right away; # create an aircraft with all its records. The archive is checked right away;
# the import itself runs in the background (AircraftImportJob). # the import itself runs in the background (AircraftImportJob).
class AircraftImportsController < ApplicationController class AircraftImportsController < ApplicationController
before_action :require_aircraft_adder!, only: %i[new create]
before_action :set_import, only: :show before_action :set_import, only: :show
def new; end def new; end
def create def create
file = params[:archive] file = params[:archive]
return redirect_to(new_aircraft_import_path, alert: "Choose a .sam.zip file.") if file.blank? return redirect_to(new_aircraft_import_path, alert: t("flash.aircraft_imports.choose_a_sam_zip")) unless file.respond_to?(:tempfile)
preview = AircraftArchive::Importer.check(file.tempfile.path) preview = AircraftArchive::Importer.check(file.tempfile.path)
tail = params[:tail_number].to_s.strip.upcase.presence || preview.tail_number.to_s.upcase tail = params[:tail_number].to_s.strip.upcase.presence || preview.tail_number.to_s.upcase
if Aircraft.where("UPPER(tail_number) = ?", tail).exists? if Aircraft.where("UPPER(tail_number) = ?", tail).exists?
@preview = preview @preview = preview
@conflict = tail @conflict = tail
flash.now[:alert] = "An aircraft #{tail} already exists. Choose another tail number for the imported one." flash.now[:alert] = t("flash.aircraft_imports.an_aircraft_already_exists", tail: tail)
return render :new, status: :unprocessable_entity return render :new, status: :unprocessable_entity
end end
@@ -24,7 +25,7 @@ class AircraftImportsController < ApplicationController
AircraftImportJob.perform_later(import.id) AircraftImportJob.perform_later(import.id)
redirect_to aircraft_import_path(import) redirect_to aircraft_import_path(import)
rescue AircraftArchive::Error => e rescue AircraftArchive::Error => e
redirect_to new_aircraft_import_path, alert: "That archive can't be imported: #{e.message}" redirect_to new_aircraft_import_path, alert: t("flash.aircraft_imports.that_archive_can_t", message: e.message)
end end
def show; end def show; 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 class AircraftRolesController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! checks_permission_itself only: :index
requires_permission :manage_people, only: %i[create update destroy]
def index 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) @share_tokens = @aircraft.share_tokens.order(created_at: :desc).includes(:created_by)
end end
def create def create
user = User.find_by(email_address: params[:email_address].to_s.strip.downcase) user = User.find_by(email_address: params[:email_address].to_s.strip.downcase)
unless user return back(alert: t("flash.aircraft_roles.no_user_with_that")) unless user
return redirect_to aircraft_aircraft_roles_path(@aircraft), error = access.add(user, Role.find_by(id: params[:role_id]))
alert: "No user with that email. Ask an administrator to create their account first." back(error ? { alert: error } : { notice: t("flash.aircraft_roles.added", display_name: user.display_name) })
end
role = @aircraft.roles.new(user: user, role: params[:role])
if role.save
log_event("role", "#{user.display_name} added as #{role.role}")
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "#{user.display_name} added."
else
redirect_to aircraft_aircraft_roles_path(@aircraft), alert: role.errors.full_messages.to_sentence
end
end end
def update def update
role = @aircraft.roles.find(params[:id]) error = access.change(@aircraft.roles.find(params[:id]), Role.find_by(id: params[:role_id]))
if demoting_last_owner?(role, params[:role]) back(error ? { alert: error } : { notice: t("flash.aircraft_roles.role_updated") })
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: "An aircraft must keep at least one owner."
end
role.update!(role: params[:role])
log_event("role", "#{role.user.display_name} changed to #{role.role}")
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Role updated."
end end
def destroy def destroy
role = @aircraft.roles.find(params[:id]) error = access.remove(@aircraft.roles.find(params[:id]))
if role.user == current_user back(error ? { alert: error } : { notice: t("flash.aircraft_roles.access_removed") })
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: "You can't remove yourself."
end
if demoting_last_owner?(role, nil)
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: "An aircraft must keep at least one owner."
end
role.destroy!
log_event("role", "#{role.user.display_name} removed")
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Access removed."
end end
private private
def demoting_last_owner?(role, new_role) def access = AircraftAccess.new(@aircraft, actor: current_user)
role.role == "owner" && new_role != "owner" && @aircraft.roles.owners.count <= 1 def back(flash) = redirect_to(aircraft_aircraft_roles_path(@aircraft), flash)
end
end end
+2 -2
View File
@@ -1,7 +1,7 @@
# Flights → Standardize airport codes (owners). # Flights → Standardize airport codes (owners).
class AirportCodesController < ApplicationController class AirportCodesController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! requires_permission :edit_any_flight
def show def show
@standardizer = AirportCodeStandardizer.new(@aircraft) @standardizer = AirportCodeStandardizer.new(@aircraft)
@@ -14,6 +14,6 @@ class AirportCodesController < ApplicationController
fixes = params.fetch(:fixes, {}).permit(*standardizer.unknown.map(&:code)).to_h fixes = params.fetch(:fixes, {}).permit(*standardizer.unknown.map(&:code)).to_h
.select { |code, _| Array(params[:fix]).include?(code) } .select { |code, _| Array(params[:fix]).include?(code) }
updated = standardizer.apply!(codes, fixes: fixes) updated = standardizer.apply!(codes, fixes: fixes)
redirect_to aircraft_flight_logs_path(@aircraft), notice: "Updated #{updated} airport entries across your flights." redirect_to aircraft_flight_logs_path(@aircraft), notice: t("flash.airport_codes.updated_airport_entries_across", count: updated)
end end
end end
@@ -1,14 +1,14 @@
class AirworthinessDirectivesController < ApplicationController class AirworthinessDirectivesController < ApplicationController
include AircraftScoped include AircraftScoped
include Applicability include Applicability
before_action :require_owner!, except: :index requires_permission :manage_ads, except: :index
before_action :set_ad, only: %i[edit update destroy] before_action :set_ad, only: %i[edit update destroy]
def index def index
@rows = Compliance.ad_rows(@aircraft) @rows = Compliance.ad_rows(@aircraft)
@history = AdCompliance.for_aircraft(@aircraft).recent_first @history = AdCompliance.for_aircraft(@aircraft).recent_first
.includes(:component, :logbook_entry, airworthiness_directive: :document, inspection_record: :inspection_type) .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 @alerts = @aircraft.ad_alerts.pending
end end
@@ -23,8 +23,8 @@ class AirworthinessDirectivesController < ApplicationController
@ad.save! @ad.save!
apply_applicability(@ad, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids) apply_applicability(@ad, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids)
end end
log_event("ad", "#{@ad.bulletin_label} added: #{@ad.name}") log_event("ad", t("flash.airworthiness_directives.added_2", bulletin_label: @ad.bulletin_label, name: @ad.name))
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{@ad.bulletin_label} added." redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: t("flash.airworthiness_directives.added", bulletin_label: @ad.bulletin_label)
rescue ActiveRecord::RecordInvalid rescue ActiveRecord::RecordInvalid
@applies_to_airframe = applies_to_airframe? @applies_to_airframe = applies_to_airframe?
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
@@ -34,8 +34,8 @@ class AirworthinessDirectivesController < ApplicationController
def attach def attach
ad = AirworthinessDirective.find(params[:airworthiness_directive_id]) ad = AirworthinessDirective.find(params[:airworthiness_directive_id])
ad.aircraft << @aircraft unless ad.aircraft.include?(@aircraft) ad.aircraft << @aircraft unless ad.aircraft.include?(@aircraft)
log_event("ad", "#{ad.bulletin_label} linked: #{ad.name}") log_event("ad", t("flash.airworthiness_directives.linked_2", bulletin_label: ad.bulletin_label, name: ad.name))
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{ad.name} linked." redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: t("flash.airworthiness_directives.linked", name: ad.name)
end end
def edit def edit
@@ -47,8 +47,8 @@ class AirworthinessDirectivesController < ApplicationController
@ad.update!(ad_params) @ad.update!(ad_params)
apply_applicability(@ad, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids) apply_applicability(@ad, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids)
end end
log_event("ad", "#{@ad.bulletin_label} updated: #{@ad.name}") log_event("ad", t("flash.airworthiness_directives.updated_2", bulletin_label: @ad.bulletin_label, name: @ad.name))
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{@ad.bulletin_label} updated." redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: t("flash.airworthiness_directives.updated", bulletin_label: @ad.bulletin_label)
rescue ActiveRecord::RecordInvalid rescue ActiveRecord::RecordInvalid
@applies_to_airframe = applies_to_airframe? @applies_to_airframe = applies_to_airframe?
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
@@ -57,8 +57,8 @@ class AirworthinessDirectivesController < ApplicationController
# Removes the AD from this aircraft (the shared AD record survives if other aircraft use it). # Removes the AD from this aircraft (the shared AD record survives if other aircraft use it).
def destroy def destroy
detach_from_aircraft(@ad) detach_from_aircraft(@ad)
log_event("ad", "#{@ad.bulletin_label} removed: #{@ad.name}") log_event("ad", t("flash.airworthiness_directives.removed", bulletin_label: @ad.bulletin_label, name: @ad.name))
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{@ad.name} removed from #{@aircraft.tail_number}." redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: t("flash.airworthiness_directives.removed_from", name: @ad.name, tail_number: @aircraft.tail_number)
end end
private private
@@ -0,0 +1,49 @@
module Api
module V1
# The fleet this token reaches, and each aircraft's own lists.
class AircraftController < BaseController
before_action -> { require_scope!(:read) }
def index
render_page(aircraft_scope) { ApiPresenter.aircraft(_1) }
end
def show
render json: { data: ApiPresenter.aircraft(find_aircraft(params[:id])) }
end
# The parts tree (?all=1 includes disposed parts).
def components
aircraft = find_aircraft(params[:id])
scope = aircraft.components.includes(:component_type)
scope = scope.where.not(status: "DISPOSED") unless params[:all].present?
render_page(scope) { ApiPresenter.component(_1) }
end
# Everything coming due, soonest first (hours projected to dates).
def due
aircraft = find_aircraft(params[:id])
render json: { data: DueList.new(aircraft).items.map { ApiPresenter.due_item(_1) } }
end
def inspections
aircraft = find_aircraft(params[:id])
render json: { data: Compliance.inspection_rows(aircraft).map { ApiPresenter.inspection(_1) } }
end
def ads
aircraft = find_aircraft(params[:id])
render json: { data: Compliance.ad_rows(aircraft).map { ApiPresenter.ad(_1) } }
end
# 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)
scope = scope.where(log_type: params[:log]) if params[:log].present?
scope = params[:signed] == "true" ? scope.where.associated(:signature) : scope.where.missing(:signature) if params[:signed].present?
render_page(scope) { ApiPresenter.logbook_entry(_1) }
end
end
end
end
+127
View File
@@ -0,0 +1,127 @@
# The REST API, version 1 (docs/api.md). JSON in and out; a token in
# "Authorization: Bearer sam_…" instead of a browser session, so no cookies
# and no CSRF tokens.
#
# A personal token acts as its owner. An integration token acts for the
# person named in "SAM-On-Behalf-Of: <email>" (required for writes), and
# reaches only its aircraft that person can also see.
module Api
module V1
class BaseController < ActionController::API
include RejectsNullBytes
MAX_PAGE = 200
before_action :authenticate
rate_limit to: 600, within: 1.minute, by: -> { @api_token&.id || request.remote_ip },
with: -> { render_error(:too_many_requests, "rate_limited", "Too many requests; slow down.") }
around_action :idempotent, if: -> { request.post? || request.patch? || request.delete? }
rescue_from ActiveRecord::RecordNotFound do
render_error(:not_found, "not_found", "Not found, or not available to this token.")
end
rescue_from ActionController::ParameterMissing, ActionDispatch::Http::Parameters::ParseError do |e|
render_error(:bad_request, "bad_request", e.message.truncate(200))
end
rescue_from ActiveRecord::RecordInvalid do |e|
render_invalid(e.record)
end
rescue_from ActiveSupport::MessageVerifier::InvalidSignature, ActiveModel::RangeError,
ActiveRecord::NotNullViolation, ActiveRecord::InvalidForeignKey do
render_error(:unprocessable_entity, "invalid", "Some values couldn't be saved.")
end
private
attr_reader :api_token
def acting_user = Current.api_user
def authenticate
token = request.authorization.to_s[/\ABearer\s+(\S+)\z/i, 1]
@api_token = ApiToken.authenticate(token)
return render_error(:unauthorized, "unauthorized", "A valid API token is required.") unless @api_token
Current.api_token = @api_token
Current.ip_address = request.remote_ip
Current.api_user = @api_token.personal? ? @api_token.user : on_behalf_of
@api_token.used!(request.remote_ip)
end
# The person an integration is acting for, if it named one.
def on_behalf_of
email = request.headers["SAM-On-Behalf-Of"].to_s.strip.downcase.presence or return
User.active.find_by(email_address: email) ||
render_error(:unprocessable_entity, "unknown_user", "SAM-On-Behalf-Of doesn't match an active user.")
end
def require_scope!(scope)
return if api_token.allows?(scope)
render_error(:forbidden, "missing_scope", "This token doesn't have the #{scope} scope.")
end
# Writes always name a person, so the record history shows who.
def require_person!
return if acting_user
render_error(:unprocessable_entity, "on_behalf_of_required", "Writes with an integration token need SAM-On-Behalf-Of.")
end
def aircraft_scope = api_token.aircraft_scope(acting_user)
def find_aircraft(id = params[:aircraft_id]) = aircraft_scope.find(id)
# 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)
limit = params.fetch(:limit, 50).to_i.clamp(1, MAX_PAGE)
scope = scope.where(scope.arel_table[:id].gt(params[:after].to_i)) if params[:after].present?
if params[:updated_since].present?
since = Time.iso8601(params[:updated_since].to_s) rescue (raise ActionController::BadRequest, "updated_since must be an ISO 8601 time")
scope = scope.where(scope.arel_table[:updated_at].gteq(since))
end
records = scope.reorder(:id).limit(limit + 1).to_a
more = records.size > limit
records = records.first(limit)
[ records, (records.last.id if more) ]
end
def render_page(scope, &present)
records, next_after = paginate(scope)
render json: { data: records.map(&present), next_after: next_after }
end
def render_error(status, code, message, fields: nil)
render json: { error: { code: code, message: message, fields: fields }.compact }, status: status
end
def render_invalid(record)
render_error(:unprocessable_entity, "invalid", record.errors.full_messages.to_sentence, fields: record.errors.to_hash)
end
# The same Idempotency-Key again (a retry) gets the first answer; the
# same key with a different request is a conflict.
def idempotent
key = request.headers["Idempotency-Key"].to_s.strip
return yield if key.empty? || api_token.nil?
return render_error(:bad_request, "bad_request", "Idempotency-Key is too long.") if key.length > 100
digest = OpenSSL::Digest::SHA256.hexdigest([ request.method, request.path, request.raw_post ].join("\n"))
if (seen = api_token.idempotency_keys.find_by(key: key))
return render_error(:conflict, "idempotency_conflict", "This Idempotency-Key was used for a different request.") if seen.request_digest != digest
response.headers["Idempotent-Replay"] = "true"
return render(json: seen.response_body, status: seen.response_status)
end
yield
return if response.status >= 500
api_token.idempotency_keys.create(key: key, request_digest: digest, response_status: response.status,
response_body: response.body, created_at: Time.current)
end
end
end
end
@@ -0,0 +1,129 @@
module Api
module V1
# Draft logbook entries for one visit (docs/api.md, "Draft entries"). The
# work items become one unsigned entry per logbook, signed in the app; the
# squawks they resolve and inspections they complete are held until every
# entry is signed. Like writing entries in the app, it's for the
# aircraft's owners.
class DraftBatchesController < BaseController
before_action -> { require_scope!(:read) }, only: %i[index show lookup]
before_action -> { require_scope!("drafts:write") }, :require_person!, only: %i[create destroy]
def index
scope = find_aircraft.draft_batches.includes(entries: :signature)
scope = scope.where(status: params[:status]) if params[:status].present?
render_page(scope) { ApiPresenter.draft_batch(_1) }
end
def lookup
scope = DraftBatch.where(aircraft: aircraft_scope, external_ref: params.require(:external_ref)).includes(entries: :signature)
render json: { data: scope.map { ApiPresenter.draft_batch(_1) } }
end
def show
render json: { data: ApiPresenter.draft_batch(find_batch) }
end
# POST /aircraft/:aircraft_id/draft_batches
def create
@aircraft = find_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: []) }
errors = check(input, items)
return render_error(:unprocessable_entity, "invalid", errors.values.flatten.to_sentence, fields: errors) if errors.any?
invitations = {}
batch = DraftBatch.transaction do
b = @aircraft.draft_batches.create!(api_token: api_token, created_by: acting_user, external_ref: input[:external_ref],
signer_email: signer_email(input), held: held(input, items))
items.group_by { _1[:log] }.each do |log, group|
entry = b.entries.create!(aircraft: @aircraft, log_type: log, date: input[:date], text: group.map { _1[:text].to_s.strip }.join("\n\n"),
entry_type: inspection_logs(input, items).include?(log) ? "INSPECTION" : "MAINTENANCE",
inspection_result: inspection_result_for(input, items, log),
aircraft_hours_at_entry: input[:aircraft_hours].presence, external_ref: group.filter_map { _1[:external_ref] }.join(",").presence)
invitations[entry.id] = invite(entry, b.signer_email, send: input.dig(:signer, :send_email).to_s == "true") if b.signer_email
end
b
end
@aircraft.log_event!("logbook", I18n.t("api.draft_batches.sent", count: batch.entries.size, name: api_token.name), notes: batch.external_ref)
render json: { data: ApiPresenter.draft_batch(batch.reload, invitations: invitations) }, status: :created
end
# DELETE /draft_batches/:id: withdraw it while nothing in it is signed.
def destroy
batch = find_batch
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
batch.withdraw!
render json: { data: ApiPresenter.draft_batch(batch.reload) }
end
private
def find_batch = DraftBatch.where(aircraft: aircraft_scope).includes(entries: :signature).find(params[:id])
def check(input, items)
errors = Hash.new { |h, k| h[k] = [] }
errors[:items] << "at least one item is needed" if items.empty?
items.each_with_index do |item, i|
errors[:"items.#{i}.log"] << "must be one of #{LogbookEntry::LOG_TYPES.keys.join(', ')}" unless LogbookEntry::LOG_TYPES.key?(item[:log])
errors[:"items.#{i}.text"] << "can't be blank" if item[:text].blank?
end
errors[:date] << "must be a date (YYYY-MM-DD)" unless (Date.iso8601(input[:date].to_s) rescue nil)
errors[:aircraft_hours] << "must be a number" if input[:aircraft_hours].present? && !input[:aircraft_hours].to_s.match?(/\A\d+(\.\d+)?\z/)
squawk_ids = items.flat_map { Array(_1[:resolves_squawks]) }.map(&:to_i)
missing = squawk_ids - @aircraft.squawks.active.where(id: squawk_ids).ids
errors[:resolves_squawks] << "no open squawk #{missing.join(', ')} on this aircraft" if missing.any?
Array(input[:completes_inspections]).each_with_index do |c, i|
id = c.respond_to?(:[]) ? c[:inspection_type_id].to_i : 0
errors[:"completes_inspections.#{i}"] << "no inspection #{id} applies to this aircraft" unless @aircraft.applicable_inspection_types.exists?(id: id)
log = inspection_log(c, items)
errors[:"completes_inspections.#{i}.log"] << "must be the log of one of the items" unless items.any? { _1[:log] == log }
unless LogbookEntry::INSPECTION_RESULTS.key?(c.respond_to?(:[]) ? c[:result].to_s : "")
errors[:"completes_inspections.#{i}.result"] << "must be #{LogbookEntry::INSPECTION_RESULTS.keys.join(' or ')}"
end
end
Array(input[:completes_inspections]).group_by { inspection_log(_1, items) }.each do |log, group|
errors[:completes_inspections] << "inspections in the #{log} log need the same result (one entry)" if group.map { _1[:result].to_s }.uniq.size > 1
end
errors[:aircraft_hours] << "is needed to record an inspection" if Array(input[:completes_inspections]).any? && input[:aircraft_hours].blank?
email = input.dig(:signer, :email).to_s.strip
errors[:"signer.email"] << "isn't an email address" if email.present? && !email.match?(URI::MailTo::EMAIL_REGEXP)
errors[:"signer.send_email"] << "needs email set up on the server" if input.dig(:signer, :send_email).to_s == "true" && !MailSettings.configured?
errors
end
# The inspection goes in the logbook named for it, else the airframe
# log if there's an item for it, else the first item's.
def inspection_log(c, items)
c[:log].presence || (items.any? { _1[:log] == "AC" } ? "AC" : items.first&.dig(:log))
end
def inspection_logs(input, items) = Array(input[:completes_inspections]).map { inspection_log(_1, items) }
# approved | discrepancies, for the entry in that log that records inspections.
def inspection_result_for(input, items, log)
Array(input[:completes_inspections]).find { inspection_log(_1, items) == log }&.dig(:result)
end
def held(input, items)
{ "squawks" => items.flat_map { |it| Array(it[:resolves_squawks]).map { |id| { "id" => id.to_i, "log" => it[:log] } } }.uniq { _1["id"] },
"inspections" => Array(input[:completes_inspections]).map { { "id" => _1[:inspection_type_id].to_i, "log" => inspection_log(_1, items) } } }
end
def signer_email(input) = input.dig(:signer, :email).to_s.strip.downcase.presence
# A link for the signer to sign this entry with their own account,
# returned to the caller to pass on; emailed too when asked.
def invite(entry, email, send: false)
invitation = entry.signing_invitations.create!(email: email, invited_by: acting_user)
SigningInvitationMailer.invite(invitation, invitation.token).deliver_later if send
invitation.token
end
end
end
end
+16
View File
@@ -0,0 +1,16 @@
module Api
module V1
# What this token is and who it's acting as: a quick check for a new integration.
class MeController < BaseController
def show
render json: { data: {
token: { name: api_token.name, kind: api_token.kind, hint: api_token.token_hint, scopes: api_token.scopes,
aircraft_ids: (api_token.aircraft_ids if api_token.integration?) }.compact,
acting_as: acting_user && { id: acting_user.id, name: acting_user.display_name, email: acting_user.email_address },
aircraft_ids: aircraft_scope.ids,
api_version: "v1", app_version: Rails.root.join("VERSION").read.strip
} }
end
end
end
end
@@ -0,0 +1,67 @@
module Api
module V1
# Squawks: list and report on an aircraft; find by external_ref; update.
# Resolving happens through a signed logbook entry, not here.
class SquawksController < BaseController
before_action -> { require_scope!(:read) }, only: %i[index show lookup]
before_action -> { require_scope!("squawks:write") }, :require_person!, only: %i[create update]
# GET /aircraft/:aircraft_id/squawks?status=open|resolved|all (default open)
def index
scope = find_aircraft.squawks.includes(:reported_by).with_attached_attachments
scope = case params.fetch(:status, "open")
when "open" then scope.active
when "resolved" then scope.resolved
else scope
end
render_page(scope) { ApiPresenter.squawk(_1) }
end
# GET /squawks?external_ref=redmine:issue:4512
def lookup
ref = params.require(:external_ref)
scope = Squawk.where(aircraft: aircraft_scope, external_ref: ref).includes(:reported_by).with_attached_attachments
render json: { data: scope.map { ApiPresenter.squawk(_1) } }
end
def show
render json: { data: ApiPresenter.squawk(find_squawk) }
end
# 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!
SquawkReported.call(squawk, by: acting_user)
render json: { data: ApiPresenter.squawk(squawk) }, status: :created
end
# PATCH /squawks/:id: external_ref by anyone who may write; the rest
# (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? && !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)
render json: { data: ApiPresenter.squawk(squawk) }
end
private
def find_squawk = Squawk.where(aircraft: aircraft_scope).find(params[:id])
def create_params
params.require(:squawk).permit(:issue_reported, :priority, :component_id, :external_ref).tap do |p|
p[:priority] = p.fetch(:priority, 2).to_i
end
end
end
end
end
+19
View File
@@ -0,0 +1,19 @@
# Profile → API tokens: personal tokens for the REST API (docs/api.md). The
# token is shown once, on the page right after it's made (not kept in the
# flash or anywhere else).
class ApiTokensController < ApplicationController
def create
@token = current_user.api_tokens.new(name: params.dig(:api_token, :name), kind: "personal",
scopes: Array(params.dig(:api_token, :scopes)) & ApiToken::SCOPES.keys)
if @token.save
render :created
else
redirect_to edit_profile_path(anchor: "api"), alert: @token.errors.full_messages.to_sentence
end
end
def destroy
current_user.api_tokens.personal.active.find(params[:id]).revoke!
redirect_to edit_profile_path(anchor: "api"), notice: t("flash.api_tokens.revoked")
end
end
+40 -1
View File
@@ -1,9 +1,12 @@
class ApplicationController < ActionController::Base class ApplicationController < ActionController::Base
default_form_builder AppFormBuilder default_form_builder AppFormBuilder
include Authentication include Authentication
include TimeZones
allow_browser versions: :modern allow_browser versions: :modern
include RejectsNullBytes
prepend_before_action :redirect_to_setup 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 before_action { Current.ip_address = request.remote_ip } # for record history
helper_method :current_user helper_method :current_user
@@ -14,16 +17,52 @@ class ApplicationController < ActionController::Base
end end
end end
# Asked for a format a page doesn't have (/aircraft/1/report.pdf): not a crash.
rescue_from ActionView::MissingTemplate do |error|
raise error if request.format.html?
head :not_acceptable
end
# Input no form produces: a tampered upload reference, a number too big to
# store, a missing required value or a link to a record that isn't there.
# The forms validate what people can enter; this is the safety net.
rescue_from ActiveSupport::MessageVerifier::InvalidSignature, ActiveModel::RangeError,
ActiveRecord::NotNullViolation, ActiveRecord::InvalidForeignKey do |error|
Rails.logger.warn("[input] #{error.class}: #{error.message.truncate(200)}")
respond_to do |format|
format.html { redirect_back_or_to root_path, alert: t("flash.application.invalid_input") }
format.any { head :unprocessable_entity }
end
end
private private
def current_user = Current.user def current_user = Current.user
# First run: no users yet → create the initial admin. # 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 def redirect_to_setup
redirect_to new_setup_path if !User.exists? && !is_a?(SetupController) redirect_to new_setup_path if !User.exists? && !is_a?(SetupController)
end 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! def require_admin!
redirect_to root_path, alert: "Admins only." unless current_user&.admin? redirect_to root_path, alert: t("flash.application.admins_only") unless current_user&.admin?
end end
end end
+4 -4
View File
@@ -8,14 +8,14 @@ class CalendarFeedsController < ApplicationController
def show def show
user = User.active.find_by(calendar_token: params[:token].to_s) or return head(:not_found) user = User.active.find_by(calendar_token: params[:token].to_s) or return head(:not_found)
cal = Ical.new("Aircraft maintenance") cal = Ical.new(t("flash.calendar_feeds.name"))
host = Sso.app_url host = Sso.app_url
user.accessible_aircraft.ordered.each do |aircraft| user.accessible_aircraft.ordered.each do |aircraft|
DueList.new(aircraft).items.each do |i| DueList.new(aircraft).items.each do |i|
when_text = [ ("projected from recent flying" if i.projected), ("at #{i.due_hours} hrs" if i.due_hours) ].compact.join(", ") when_text = [ (t("flash.calendar_feeds.projected") if i.projected), (t("flash.calendar_feeds.at_hours", hours: i.due_hours) if i.due_hours) ].compact.join(", ")
cal.add(uid: "#{aircraft.id}-#{i.key}@simple-aircraft-manager", date: i.date, cal.add(uid: "#{aircraft.id}-#{i.key}@simple-aircraft-manager", date: i.date,
summary: "#{aircraft.tail_number}: #{i.title}#{' (overdue)' if i.overdue?}", summary: t(i.overdue? ? "flash.calendar_feeds.summary_overdue" : "flash.calendar_feeds.summary", tail_number: aircraft.tail_number, title: i.title),
description: [ "#{aircraft.tail_number}: #{i.title}", when_text.presence ].compact.join("\n"), url: "#{host}#{i.path}") description: [ t("flash.calendar_feeds.summary", tail_number: aircraft.tail_number, title: i.title), when_text.presence ].compact.join("\n"), url: "#{host}#{i.path}")
end end
end end
send_data cal.to_s, type: "text/calendar; charset=utf-8", disposition: "inline", filename: "aircraft-maintenance.ics" send_data cal.to_s, type: "text/calendar; charset=utf-8", disposition: "inline", filename: "aircraft-maintenance.ics"
@@ -2,6 +2,6 @@
class CalendarTokensController < ApplicationController class CalendarTokensController < ApplicationController
def create def create
current_user.regenerate_calendar_token current_user.regenerate_calendar_token
redirect_to edit_profile_path(anchor: "calendar"), notice: "Calendar link ready. Any earlier link no longer works." redirect_to edit_profile_path(anchor: "calendar"), notice: t("flash.calendar_tokens.calendar_link_ready_any")
end end
end end
+9 -9
View File
@@ -1,6 +1,6 @@
class ComponentsController < ApplicationController class ComponentsController < ApplicationController
include AircraftScoped 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] before_action :set_component, only: %i[show edit update destroy reset_service]
def index def index
@@ -35,8 +35,8 @@ class ComponentsController < ApplicationController
def create def create
@component = @aircraft.components.new(component_params) @component = @aircraft.components.new(component_params)
if @component.save if @component.save
log_event("component", "Component added: #{@component}") log_event("component", t("flash.components.component_added_2", component: @component))
redirect_to aircraft_components_path(@aircraft), notice: "Component added." redirect_to aircraft_components_path(@aircraft), notice: t("flash.components.component_added")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -46,8 +46,8 @@ class ComponentsController < ApplicationController
def update def update
if @component.update(component_params) if @component.update(component_params)
log_event("component", "Component updated: #{@component}") log_event("component", t("flash.components.component_updated_2", component: @component))
redirect_to aircraft_components_path(@aircraft), notice: "Component updated." redirect_to aircraft_components_path(@aircraft), notice: t("flash.components.component_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -55,8 +55,8 @@ class ComponentsController < ApplicationController
def destroy def destroy
@component.destroy! @component.destroy!
log_event("component", "Component deleted: #{@component}") log_event("component", t("flash.components.component_deleted_2", component: @component))
redirect_to aircraft_components_path(@aircraft), notice: "Component deleted." redirect_to aircraft_components_path(@aircraft), notice: t("flash.components.component_deleted")
end end
# Always zeroes hours since overhaul; reset_in_service=1 also zeroes the # Always zeroes hours since overhaul; reset_in_service=1 also zeroes the
@@ -64,8 +64,8 @@ class ComponentsController < ApplicationController
def reset_service def reset_service
replaced = params[:reset_in_service] == "1" replaced = params[:reset_in_service] == "1"
@component.reset_service!(reset_in_service: replaced) @component.reset_service!(reset_in_service: replaced)
log_event("component", "#{replaced ? 'Replaced' : 'Serviced'}: #{@component}") log_event("component", t(replaced ? "flash.components.replaced_event" : "flash.components.serviced_event", component: @component))
redirect_to aircraft_components_path(@aircraft), notice: "#{@component} #{replaced ? 'replaced' : 'serviced'}." redirect_to aircraft_components_path(@aircraft), notice: t(replaced ? "flash.components.replaced" : "flash.components.serviced", component: @component)
end end
private private
+54 -15
View File
@@ -1,16 +1,38 @@
# Scopes a controller to one aircraft the current user can access and exposes # Scopes a controller to one aircraft the current user can access, and checks
# role helpers. Unknown and inaccessible aircraft both 404 (enumeration-safe). # what their role there allows (Role, Permission). Unknown and inaccessible
# aircraft both 404 (enumeration-safe). Administrators can do everything.
# #
# Access matrix (mirrors the original): # Each controller says which permission its actions need:
# admin – everything #
# owner – everything on their aircraft # requires_permission :manage_components, except: %i[index show]
# pilot – view all; update hours; create squawks, notes, oil/fuel, flight logs # 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 module AircraftScoped
extend ActiveSupport::Concern extend ActiveSupport::Concern
SELF_CHECKED = "(checked by the controller)".freeze
class MissingPermission < StandardError; end
included do included do
class_attribute :permission_rules, instance_accessor: false, default: []
before_action :set_aircraft 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 end
private private
@@ -21,18 +43,35 @@ module AircraftScoped
@aircraft = current_user.accessible_aircraft.find(aircraft_param) @aircraft = current_user.accessible_aircraft.find(aircraft_param)
end end
# Their Role here (nil for an administrator without one).
def current_role 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 end
# Owner-level write access (admins included). # Nothing in viewer mode (a read-only copy, see Viewer).
def owner? = current_role.in?(%w[admin owner]) def can?(permission) = !Viewer.enabled? && (current_user.admin? || current_role&.can?(permission) || false)
alias_method :can_write?, :owner?
def require_owner! # The Owner role (or an administrator): everything.
return if owner? def owner? = !Viewer.enabled? && (current_user.admin? || current_role&.owner? || false)
redirect_back fallback_location: aircraft_path(@aircraft),
alert: "Only owners can do that." 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 end
# Returns id only if it belongs to the given (aircraft-scoped) relation; else nil. # 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 end
def require_authentication 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 end
def resume_session def resume_session
+3 -3
View File
@@ -35,11 +35,11 @@ module EntrySigning
certificate = current_user.certificates.find_by(id: params[:certificate_id]) certificate = current_user.certificates.find_by(id: params[:certificate_id])
method = reauthenticated_method method = reauthenticated_method
unless params[:confirm] == "1" unless params[:confirm] == "1"
return signing_failed(entry, "Tick the box to confirm you're signing this entry.") return signing_failed(entry, t("flash.signing.confirm_box"))
end end
unless method unless method
return signing_failed(entry, "This account is locked for a few minutes after too many failed tries.") if current_user.reload.locked? return signing_failed(entry, t("flash.signing.locked")) if current_user.reload.locked?
return signing_failed(entry, "Re-enter your password#{' and a current authenticator code' if current_user.otp_enabled?} (or sign in again with #{Sso.label}) to sign.") return signing_failed(entry, t(current_user.otp_enabled? ? "flash.signing.reauth_otp" : "flash.signing.reauth", provider: Sso.label))
end end
current_user.clear_failed_sign_ins! current_user.clear_failed_sign_ins!
@@ -0,0 +1,22 @@
# No form or API client sends a null byte; some libraries (password hashing,
# file paths) raise on one, so such requests are refused up front.
module RejectsNullBytes
extend ActiveSupport::Concern
included { prepend_before_action :reject_null_bytes }
private
def reject_null_bytes
head :bad_request if contains_null_byte?(request.params)
end
def contains_null_byte?(value)
case value
when String then value.include?("\0")
when Hash then value.any? { |k, v| contains_null_byte?(k) || contains_null_byte?(v) }
when Array then value.any? { contains_null_byte?(_1) }
else false
end
end
end
+3 -3
View File
@@ -14,10 +14,10 @@ module StoredUpload
# Returns [token, nil] on success or [nil, error message]. # Returns [token, nil] on success or [nil, error message].
def store_upload(file) def store_upload(file)
return [ nil, "Choose a file to upload." ] unless file.respond_to?(:path) return [ nil, I18n.t("flash.uploads.choose_file") ] unless file.respond_to?(:path)
return [ nil, "File is too large." ] if file.size > UPLOAD_MAX_SIZE return [ nil, I18n.t("flash.uploads.too_large") ] if file.size > UPLOAD_MAX_SIZE
ext = File.extname(file.original_filename.to_s).delete(".").downcase ext = File.extname(file.original_filename.to_s).delete(".").downcase
return [ nil, "Upload an .xlsx or .csv file." ] unless ext.in?(UPLOAD_EXTENSIONS) return [ nil, I18n.t("flash.uploads.spreadsheet_only") ] unless ext.in?(UPLOAD_EXTENSIONS)
FileUtils.mkdir_p(UPLOAD_DIR) FileUtils.mkdir_p(UPLOAD_DIR)
Dir.glob(UPLOAD_DIR.join("*")).each { |f| File.delete(f) if File.mtime(f) < 1.day.ago } Dir.glob(UPLOAD_DIR.join("*")).each { |f| File.delete(f) if File.mtime(f) < 1.day.ago }
+31
View File
@@ -0,0 +1,31 @@
# Each request runs in the viewer's time zone: the one chosen in Profile, else
# the device's (a "tz" cookie the page sets from the browser), else the
# installation's default (TZ). That decides how times show and
# what "today" is (e.g. a new flight's date). Signatures, the record history
# and exports keep exact UTC timestamps.
module TimeZones
extend ActiveSupport::Concern
included do
around_action :use_time_zone
helper_method :device_time_zone, :device_time_zone_label
end
private
def use_time_zone(&)
Time.use_zone(Current.user&.time_zone.presence || device_time_zone || Time.zone_default, &)
end
# "(GMT-08:00) Pacific Time (US & Canada)" for America/Los_Angeles.
def device_time_zone_label
return unless (zone = ActiveSupport::TimeZone[device_time_zone.to_s])
(ActiveSupport::TimeZone.all.find { _1.tzinfo.identifier == zone.tzinfo.identifier } || zone).to_s
end
# The browser's zone, when it's one we know.
def device_time_zone
name = cookies[:tz].to_s.first(64)
ActiveSupport::TimeZone[name] && name if name.present?
end
end
@@ -1,6 +1,7 @@
class ConsumableRecordsController < ApplicationController class ConsumableRecordsController < ApplicationController
include AircraftScoped 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] before_action :set_record, only: %i[edit update destroy]
RECORDS_PER_PAGE = 50 RECORDS_PER_PAGE = 50
@@ -27,8 +28,8 @@ class ConsumableRecordsController < ApplicationController
def create def create
@record = @aircraft.consumable_records.new(record_params) @record = @aircraft.consumable_records.new(record_params)
if @record.save if @record.save
log_event(@record.record_type, "#{@record.record_type.capitalize} added: #{@record.quantity_added} #{@record.unit}") log_event(@record.record_type, t("flash.consumable_records.added_event", type: ConsumableRecord::TYPES[@record.record_type], quantity: @record.quantity_added, unit: @record.unit))
redirect_to aircraft_consumable_records_path(@aircraft), notice: "Record added." redirect_to aircraft_consumable_records_path(@aircraft), notice: t("flash.consumable_records.record_added")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -38,8 +39,8 @@ class ConsumableRecordsController < ApplicationController
def update def update
if @record.update(record_params) if @record.update(record_params)
log_event(@record.record_type, "#{@record.record_type.capitalize} record updated") log_event(@record.record_type, t("flash.consumable_records.updated_event", type: ConsumableRecord::TYPES[@record.record_type]))
redirect_to aircraft_consumable_records_path(@aircraft), notice: "Record updated." redirect_to aircraft_consumable_records_path(@aircraft), notice: t("flash.consumable_records.record_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -47,8 +48,8 @@ class ConsumableRecordsController < ApplicationController
def destroy def destroy
@record.destroy! @record.destroy!
log_event(@record.record_type, "#{@record.record_type.capitalize} record deleted") log_event(@record.record_type, t("flash.consumable_records.deleted_event", type: ConsumableRecord::TYPES[@record.record_type]))
redirect_to aircraft_consumable_records_path(@aircraft), notice: "Record deleted." redirect_to aircraft_consumable_records_path(@aircraft), notice: t("flash.consumable_records.record_deleted")
end end
private private
+2 -2
View File
@@ -16,9 +16,9 @@ class DirectUploadsController < ActiveStorage::DirectUploadsController
def check_upload def check_upload
error = error =
if !UploadValidation::ALLOWED_CONTENT_TYPES.include?(blob_args[:content_type]) if !UploadValidation::ALLOWED_CONTENT_TYPES.include?(blob_args[:content_type])
"#{blob_args[:filename]} isn't an allowed file type" t("errors.messages.file_type", file: blob_args[:filename])
elsif blob_args[:byte_size].to_i > UploadValidation.max_size elsif blob_args[:byte_size].to_i > UploadValidation.max_size
"#{blob_args[:filename]} is over the #{UploadValidation.max_size / 1.megabyte} MB upload limit" t("errors.messages.file_size", file: blob_args[:filename], limit: UploadValidation.max_size / 1.megabyte)
end end
render json: { error: error }, status: :unprocessable_entity if error render json: { error: error }, status: :unprocessable_entity if error
end end
@@ -1,6 +1,6 @@
class DocumentCollectionsController < ApplicationController class DocumentCollectionsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! requires_permission :manage_documents
before_action :set_collection, only: %i[edit update destroy] before_action :set_collection, only: %i[edit update destroy]
def new def new
@@ -10,8 +10,8 @@ class DocumentCollectionsController < ApplicationController
def create def create
@collection = @aircraft.document_collections.new(collection_params) @collection = @aircraft.document_collections.new(collection_params)
if @collection.save if @collection.save
log_event("document", "Collection created: #{@collection.name}") log_event("document", t("flash.document_collections.collection_created_2", name: @collection.name))
redirect_to aircraft_documents_path(@aircraft), notice: "Collection created." redirect_to aircraft_documents_path(@aircraft), notice: t("flash.document_collections.collection_created")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -21,8 +21,8 @@ class DocumentCollectionsController < ApplicationController
def update def update
if @collection.update(collection_params) if @collection.update(collection_params)
log_event("document", "Collection updated: #{@collection.name}") log_event("document", t("flash.document_collections.collection_updated_2", name: @collection.name))
redirect_to aircraft_documents_path(@aircraft), notice: "Collection updated." redirect_to aircraft_documents_path(@aircraft), notice: t("flash.document_collections.collection_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -30,8 +30,8 @@ class DocumentCollectionsController < ApplicationController
def destroy def destroy
@collection.destroy! @collection.destroy!
log_event("document", "Collection deleted: #{@collection.name}") log_event("document", t("flash.document_collections.collection_deleted", name: @collection.name))
redirect_to aircraft_documents_path(@aircraft), notice: "Collection and its documents deleted." redirect_to aircraft_documents_path(@aircraft), notice: t("flash.document_collections.collection_and_its_documents")
end end
private private
+17 -16
View File
@@ -1,6 +1,6 @@
class DocumentsController < ApplicationController class DocumentsController < ApplicationController
include AircraftScoped 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] before_action :set_document, only: %i[show edit update destroy]
def index def index
@@ -14,13 +14,14 @@ class DocumentsController < ApplicationController
def new def new
@document = @aircraft.documents.new(document_collection_id: params[:collection_id]) @document = @aircraft.documents.new(document_collection_id: params[:collection_id])
@document.doc_type = params[:doc_type] if Document::TYPES.key?(params[:doc_type])
end end
def create def create
@document = @aircraft.documents.new(document_params) @document = @aircraft.documents.new(document_params)
if @document.save if @document.save
log_event("document", "Document added: #{@document.name}") log_event("document", t("flash.documents.document_added_2", name: @document.name))
redirect_to aircraft_document_path(@aircraft, @document), notice: "Document added." redirect_to aircraft_document_path(@aircraft, @document), notice: t("flash.documents.document_added")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -36,15 +37,15 @@ class DocumentsController < ApplicationController
def bulk_create def bulk_create
@bulk = bulk_defaults.merge(params.slice(:doc_type, :visibility, :document_collection_id, :new_collection).permit!.to_h.symbolize_keys) @bulk = bulk_defaults.merge(params.slice(:doc_type, :visibility, :document_collection_id, :new_collection).permit!.to_h.symbolize_keys)
files = Array(params[:files]).compact_blank files = Array(params[:files]).compact_blank
return bulk_error("Choose some files to upload.") if files.empty? return bulk_error(t("flash.documents.choose_files")) if files.empty?
return bulk_error("Upload at most #{MAX_BULK_FILES} files at a time.") if files.size > MAX_BULK_FILES return bulk_error(t("flash.documents.too_many_files", max: MAX_BULK_FILES)) if files.size > MAX_BULK_FILES
names = Array(params[:names]) names = Array(params[:names])
rejected = [] rejected = []
groups = {} groups = {}
files.each_with_index do |file, i| files.each_with_index do |file, i|
upload = file.is_a?(String) ? unattached_blob(file) : file upload = file.is_a?(String) ? unattached_blob(file) : file
next rejected << "file #{i + 1} (upload expired, try again)" unless upload next rejected << t("flash.documents.upload_expired", number: i + 1) unless upload
name = names[i].to_s.squish.presence || File.basename(upload_filename(upload), ".*").tr("_", " ").squish.presence || "Untitled" name = names[i].to_s.squish.presence || File.basename(upload_filename(upload), ".*").tr("_", " ").squish.presence || "Untitled"
(groups[name.first(255)] ||= []) << upload (groups[name.first(255)] ||= []) << upload
end end
@@ -58,18 +59,18 @@ class DocumentsController < ApplicationController
if doc.save if doc.save
created << doc created << doc
else else
rejected << "#{name} (#{doc.errors.full_messages.to_sentence})" rejected << t("flash.documents.rejected_file", name: name, errors: doc.errors.full_messages.to_sentence)
pages.each { _1.purge_later if _1.is_a?(ActiveStorage::Blob) } pages.each { _1.purge_later if _1.is_a?(ActiveStorage::Blob) }
end end
end end
if created.empty? if created.empty?
@aircraft.document_collections.find_by(id: collection_id)&.destroy if @bulk[:new_collection].present? @aircraft.document_collections.find_by(id: collection_id)&.destroy if @bulk[:new_collection].present?
return bulk_error("Nothing was uploaded: #{rejected.to_sentence}.") return bulk_error(t("flash.documents.nothing_uploaded", items: rejected.to_sentence))
end end
log_event("document", "#{helpers.pluralize(created.size, 'document')} uploaded", notes: created.map(&:name).join(", ").truncate(1000)) log_event("document", t("flash.documents.bulk_uploaded_event", count: created.size), notes: created.map(&:name).join(", ").truncate(1000))
flash[:alert] = "Not uploaded: #{rejected.to_sentence}." if rejected.any? flash[:alert] = t("flash.documents.not_uploaded", items: rejected.to_sentence) if rejected.any?
redirect_to aircraft_documents_path(@aircraft), notice: "#{helpers.pluralize(created.size, 'document')} uploaded.", status: :see_other redirect_to aircraft_documents_path(@aircraft), notice: t("flash.documents.bulk_uploaded", count: created.size), status: :see_other
end end
def edit; end def edit; end
@@ -81,8 +82,8 @@ class DocumentsController < ApplicationController
@document.pages.attach(new_pages) if new_pages.present? @document.pages.attach(new_pages) if new_pages.present?
Array(params[:remove_page_ids]).each { |id| @document.pages.find_by(id: id)&.purge_later } Array(params[:remove_page_ids]).each { |id| @document.pages.find_by(id: id)&.purge_later }
if @document.save if @document.save
log_event("document", "Document updated: #{@document.name}") log_event("document", t("flash.documents.document_updated_2", name: @document.name))
redirect_to aircraft_document_path(@aircraft, @document), notice: "Document updated." redirect_to aircraft_document_path(@aircraft, @document), notice: t("flash.documents.document_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -90,8 +91,8 @@ class DocumentsController < ApplicationController
def destroy def destroy
@document.destroy! @document.destroy!
log_event("document", "Document deleted: #{@document.name}") log_event("document", t("flash.documents.document_deleted_2", name: @document.name))
redirect_to aircraft_documents_path(@aircraft), notice: "Document deleted." redirect_to aircraft_documents_path(@aircraft), notice: t("flash.documents.document_deleted")
end end
private private
@@ -120,7 +121,7 @@ class DocumentsController < ApplicationController
def bulk_collection def bulk_collection
return [ scoped_id(@aircraft.document_collections, @bulk[:document_collection_id]), nil ] if @bulk[:new_collection].blank? return [ scoped_id(@aircraft.document_collections, @bulk[:document_collection_id]), nil ] if @bulk[:new_collection].blank?
col = @aircraft.document_collections.create(name: @bulk[:new_collection].squish, visibility: @bulk[:visibility].presence || "private") col = @aircraft.document_collections.create(name: @bulk[:new_collection].squish, visibility: @bulk[:visibility].presence || "private")
col.persisted? ? [ col.id, nil ] : [ nil, "Couldn't create the collection: #{col.errors.full_messages.to_sentence}." ] col.persisted? ? [ col.id, nil ] : [ nil, t("flash.documents.collection_failed", errors: col.errors.full_messages.to_sentence) ]
end end
def set_document = @document = @aircraft.documents.find(params[:id]) def set_document = @document = @aircraft.documents.find(params[:id])
@@ -3,6 +3,7 @@
# who they are again (password, or single sign-on just now), and confirms. # who they are again (password, or single sign-on just now), and confirms.
class EntrySignaturesController < ApplicationController class EntrySignaturesController < ApplicationController
include AircraftScoped include AircraftScoped
requires_permission :sign_logbook
include EntrySigning include EntrySigning
before_action :set_entry before_action :set_entry
@@ -12,7 +13,7 @@ class EntrySignaturesController < ApplicationController
def create def create
sign_entry(@entry) do |signature| sign_entry(@entry) do |signature|
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: "Signed. #{EntrySignature::LABEL} #{signature.signer_name}, #{signature.certificate_label} #{signature.certificate_number}." redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: t("flash.entry_signatures.signed", label: EntrySignature.label, signer_name: signature.signer_name, certificate_label: signature.certificate_label, certificate_number: signature.certificate_number)
end end
end end
+10 -2
View File
@@ -1,10 +1,18 @@
class EventsController < ApplicationController class EventsController < ApplicationController
include AircraftScoped include AircraftScoped
EVENTS_PER_PAGE = 50
# A page at a time; the rest load as you scroll (each page ends in a lazy
# frame that fetches the next).
def index def index
@category = params[:category].presence_in(AircraftEvent::CATEGORIES.keys) @category = params[:category].presence_in(AircraftEvent::CATEGORIES.keys)
scope = @aircraft.events.includes(:user) @page = [ params[:page].to_i, 1 ].max
scope = @aircraft.events.includes(:user).reorder(created_at: :desc, id: :desc)
scope = scope.where(category: @category) if @category scope = scope.where(category: @category) if @category
@events = scope.limit(200) rows = scope.offset((@page - 1) * EVENTS_PER_PAGE).limit(EVENTS_PER_PAGE + 1).to_a
@more = rows.size > EVENTS_PER_PAGE
@events = rows.first(EVENTS_PER_PAGE)
render(partial: "events/page", locals: { events: @events, page: @page, more: @more, category: @category }) if turbo_frame_request?
end end
end end
+5 -5
View File
@@ -2,7 +2,7 @@
class FlightImportsController < ApplicationController class FlightImportsController < ApplicationController
include AircraftScoped include AircraftScoped
include StoredUpload include StoredUpload
before_action :require_owner! requires_permission :import_flights
def new; end def new; end
@@ -18,7 +18,7 @@ class FlightImportsController < ApplicationController
# Preview. # Preview.
def show def show
@token = params[:token].to_s @token = params[:token].to_s
return redirect_to_upload("Upload expired. Please upload the file again.") unless stored_file?(@token) return redirect_to_upload(t("flash.uploads.expired")) unless stored_file?(@token)
@filename = params[:filename].to_s @filename = params[:filename].to_s
@starting_tach = params[:starting_tach].presence @starting_tach = params[:starting_tach].presence
@@ -31,17 +31,17 @@ class FlightImportsController < ApplicationController
def confirm def confirm
token = params[:token].to_s token = params[:token].to_s
return redirect_to_upload("Upload expired. Please upload the file again.") unless stored_file?(token) return redirect_to_upload(t("flash.uploads.expired")) unless stored_file?(token)
import = build_import(token, params[:filename], starting_tach: params[:starting_tach], starting_hobbs: params[:starting_hobbs]) import = build_import(token, params[:filename], starting_tach: params[:starting_tach], starting_hobbs: params[:starting_hobbs])
count = import.import!(user: current_user, update_aircraft_hours: params[:update_aircraft_hours] == "1") count = import.import!(user: current_user, update_aircraft_hours: params[:update_aircraft_hours] == "1")
discard_upload(token) discard_upload(token)
redirect_to aircraft_flight_logs_path(@aircraft), notice: "Imported #{count} flights." redirect_to aircraft_flight_logs_path(@aircraft), notice: t("flash.flight_imports.imported_flights", count: count)
rescue FlightImport::Error => e rescue FlightImport::Error => e
redirect_to new_aircraft_flight_import_path(@aircraft), alert: e.message redirect_to new_aircraft_flight_import_path(@aircraft), alert: e.message
rescue AircraftGroundedError rescue AircraftGroundedError
redirect_to aircraft_flight_logs_path(@aircraft), redirect_to aircraft_flight_logs_path(@aircraft),
alert: "Flights imported, but aircraft hours weren't updated: the aircraft is grounded and enforcement is on." alert: t("flash.flight_imports.flights_imported_but_aircraft")
end end
private private
+55 -16
View File
@@ -1,7 +1,11 @@
class FlightLogsController < ApplicationController class FlightLogsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner!, only: :destroy requires_permission :log_flights, only: %i[new create]
before_action :set_flight_log, only: %i[show engine_data_series attach_engine_data remove_engine_data] 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] before_action :require_engine_data_access!, only: %i[attach_engine_data remove_engine_data]
helper_method :manage_engine_data? helper_method :manage_engine_data?
@@ -26,12 +30,12 @@ class FlightLogsController < ApplicationController
begin begin
@track = TrackParser.parse_attachment(@flight_log.track_log) @track = TrackParser.parse_attachment(@flight_log.track_log)
rescue TrackParser::Error => e rescue TrackParser::Error => e
@track_error = "Couldn't read track: #{e.message}" @track_error = t("flash.flight_logs.track_unreadable", message: e.message)
end end
begin begin
@engine_data = EngineDataParser.parse_attachment(@flight_log.engine_data) @engine_data = EngineDataParser.parse_attachment(@flight_log.engine_data)
rescue EngineDataParser::Error, ActiveStorage::FileNotFoundError => e rescue EngineDataParser::Error, ActiveStorage::FileNotFoundError => e
@engine_data_error = "Couldn't read engine data: #{e.message}" @engine_data_error = t("flash.flight_logs.engine_data_unreadable", message: e.message)
end end
@air_trail_connection = @flight_log.user&.air_trail_connection @air_trail_connection = @flight_log.user&.air_trail_connection
@air_trail_sync = @flight_log.air_trail_syncs.first @air_trail_sync = @flight_log.air_trail_syncs.first
@@ -49,7 +53,13 @@ class FlightLogsController < ApplicationController
def new def new
# Aircraft almost always depart from where they last landed. # Aircraft almost always depart from where they last landed.
last = @aircraft.flight_logs.where.not(destination_location: [ nil, "" ]).recent_first.first last = @aircraft.flight_logs.where.not(destination_location: [ nil, "" ]).recent_first.first
@flight_log = @aircraft.flight_logs.new(date: Date.current, tach_out: @aircraft.tach_time, # "Save and log next leg" comes back here with that flight's date.
date = begin
Date.iso8601(params[:date].to_s)
rescue Date::Error
Date.current
end
@flight_log = @aircraft.flight_logs.new(date: date, tach_out: @aircraft.tach_time,
hobbs_out: @aircraft.hobbs_time, hobbs_out: @aircraft.hobbs_time,
departure_location: last&.destination_location) departure_location: last&.destination_location)
end end
@@ -57,12 +67,17 @@ class FlightLogsController < ApplicationController
def create def create
# Already received (sent again from the offline queue): don't log it twice. # Already received (sent again from the offline queue): don't log it twice.
if (key = params.dig(:flight_log, :client_key).to_s.presence) && @aircraft.flight_logs.exists?(client_key: key.first(64)) if (key = params.dig(:flight_log, :client_key).to_s.presence) && @aircraft.flight_logs.exists?(client_key: key.first(64))
return redirect_to(aircraft_flight_logs_path(@aircraft), notice: "Flight already logged.") return redirect_to(aircraft_flight_logs_path(@aircraft), notice: t("flash.flight_logs.flight_already_logged"))
end end
@flight_log = @aircraft.flight_logs.new(flight_log_params) @flight_log = @aircraft.flight_logs.new(flight_log_params)
if @flight_log.valid? if @flight_log.valid?
HoursService.new(@aircraft).log_flight!(@flight_log) HoursService.new(@aircraft).log_flight!(@flight_log)
redirect_to aircraft_flight_logs_path(@aircraft), notice: "Flight logged (#{@flight_log.tach_time} hrs)." notice = t("flash.flight_logs.flight_logged_hrs", tach_time: @flight_log.tach_time)
if params[:next_leg].present?
redirect_to new_aircraft_flight_log_path(@aircraft, date: @flight_log.date.iso8601), notice: "#{notice} #{t('flash.flight_logs.next_leg')}"
else
redirect_to aircraft_flight_logs_path(@aircraft), notice: notice
end
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -73,11 +88,11 @@ class FlightLogsController < ApplicationController
def attach_engine_data def attach_engine_data
file = params.dig(:flight_log, :engine_data) file = params.dig(:flight_log, :engine_data)
return redirect_to(aircraft_flight_log_path(@aircraft, @flight_log), alert: "Choose an engine data file.") if file.blank? return redirect_to(aircraft_flight_log_path(@aircraft, @flight_log), alert: t("flash.flight_logs.choose_an_engine_data")) if file.blank?
@flight_log.engine_data = file @flight_log.engine_data = file
if @flight_log.save if @flight_log.save
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: "Engine data attached." redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: t("flash.flight_logs.engine_data_attached")
else else
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), alert: @flight_log.errors.full_messages.to_sentence redirect_to aircraft_flight_log_path(@aircraft, @flight_log), alert: @flight_log.errors.full_messages.to_sentence
end end
@@ -85,30 +100,54 @@ class FlightLogsController < ApplicationController
def remove_engine_data def remove_engine_data
@flight_log.engine_data.purge_later @flight_log.engine_data.purge_later
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: "Engine data removed." 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 end
# Deleting a flight does not roll back hours; correct those with an hours update. # Deleting a flight does not roll back hours; correct those with an hours update.
def destroy def destroy
@aircraft.flight_logs.find(params[:id]).destroy! @aircraft.flight_logs.find(params[:id]).destroy!
log_event("flight", "Flight log deleted") log_event("flight", t("flash.flight_logs.flight_log_deleted"))
redirect_to aircraft_flight_logs_path(@aircraft), notice: "Flight log deleted. Aircraft hours were not changed." redirect_to aircraft_flight_logs_path(@aircraft), notice: t("flash.flight_logs.flight_log_deleted_aircraft")
end end
private 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 def set_flight_log
@flight_log = @aircraft.flight_logs.find(params[:id]) @flight_log = @aircraft.flight_logs.find(params[:id])
end end
# Owners, or the pilot who logged the flight. # Owners, or the pilot who logged the flight.
def manage_engine_data? def manage_engine_data? = can_edit_flight?(@flight_log)
owner? || (@flight_log.user_id.present? && @flight_log.user_id == current_user.id)
end
def require_engine_data_access! def require_engine_data_access!
return if manage_engine_data? return if manage_engine_data?
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), alert: "Only owners or the flight's pilot can do that." redirect_to aircraft_flight_log_path(@aircraft, @flight_log), alert: t("flash.flight_logs.only_owners_or_the")
end end
def flight_log_params def flight_log_params
@@ -1,6 +1,6 @@
class InspectionRecordsController < ApplicationController class InspectionRecordsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! requires_permission :manage_inspections
before_action :set_record, only: %i[edit update destroy] before_action :set_record, only: %i[edit update destroy]
def new def new
@@ -12,8 +12,8 @@ class InspectionRecordsController < ApplicationController
def create def create
@record = InspectionRecord.new(record_params.merge(aircraft: @aircraft)) @record = InspectionRecord.new(record_params.merge(aircraft: @aircraft))
if @record.save if @record.save
log_event("inspection", "Inspection completed: #{@record.inspection_type.name}") log_event("inspection", t("flash.inspection_records.inspection_completed", name: @record.inspection_type.name))
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection recorded." redirect_to aircraft_inspections_path(@aircraft), notice: t("flash.inspection_records.inspection_recorded")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -23,8 +23,8 @@ class InspectionRecordsController < ApplicationController
def update def update
if @record.update(record_params) if @record.update(record_params)
log_event("inspection", "Inspection record updated: #{@record.inspection_type.name}") log_event("inspection", t("flash.inspection_records.inspection_record_updated_2", name: @record.inspection_type.name))
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection record updated." redirect_to aircraft_inspections_path(@aircraft), notice: t("flash.inspection_records.inspection_record_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -32,8 +32,8 @@ class InspectionRecordsController < ApplicationController
def destroy def destroy
@record.destroy! @record.destroy!
log_event("inspection", "Inspection record deleted: #{@record.inspection_type.name}") log_event("inspection", t("flash.inspection_records.inspection_record_deleted_2", name: @record.inspection_type.name))
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection record deleted." redirect_to aircraft_inspections_path(@aircraft), notice: t("flash.inspection_records.inspection_record_deleted")
end end
private private
+10 -10
View File
@@ -1,19 +1,19 @@
class InspectionTypesController < ApplicationController class InspectionTypesController < ApplicationController
include AircraftScoped include AircraftScoped
include Applicability include Applicability
before_action :require_owner! requires_permission :manage_inspections
before_action :set_type, only: %i[edit update destroy] before_action :set_type, only: %i[edit update destroy]
def new def new
@inspection_type = InspectionType.new(required: true, recurring: true) @inspection_type = InspectionType.new(required: true, recurring: true)
@applies_to_airframe = true @applies_to_airframe = true
if (@major_record = ica_record) if (@major_record = ica_record)
@inspection_type.name = "ICA: #{@major_record.title}".first(120) @inspection_type.name = t("flash.inspection_types.ica_name", title: @major_record.title).first(120)
@applies_to_airframe = @major_record.component.nil? @applies_to_airframe = @major_record.component.nil?
@inspection_type.components = [ @major_record.component ] if @major_record.component @inspection_type.components = [ @major_record.component ] if @major_record.component
elsif (component = @aircraft.components.find_by(id: params[:component_id])) elsif (component = @aircraft.components.find_by(id: params[:component_id]))
# From a component's page: applies to that part, e.g. "Magneto 500-hour inspection". # From a component's page: applies to that part, e.g. "Magneto 500-hour inspection".
@inspection_type.name = "#{component} inspection" @inspection_type.name = t("flash.inspection_types.component_name", component: component)
@inspection_type.components = [ component ] @inspection_type.components = [ component ]
@applies_to_airframe = false @applies_to_airframe = false
end end
@@ -26,11 +26,11 @@ class InspectionTypesController < ApplicationController
apply_applicability(@inspection_type, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids) apply_applicability(@inspection_type, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids)
ica_record&.update!(ica_inspection_type: @inspection_type) ica_record&.update!(ica_inspection_type: @inspection_type)
end end
log_event("inspection", "Inspection type added: #{@inspection_type.name}") log_event("inspection", t("flash.inspection_types.inspection_type_added_2", name: @inspection_type.name))
if (record = ica_record) if (record = ica_record)
redirect_to aircraft_major_record_path(@aircraft, record), notice: "ICA inspection added. Record when it was last done to see when it's next due." redirect_to aircraft_major_record_path(@aircraft, record), notice: t("flash.inspection_types.ica_inspection_added_record")
else else
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection type added." redirect_to aircraft_inspections_path(@aircraft), notice: t("flash.inspection_types.inspection_type_added")
end end
rescue ActiveRecord::RecordInvalid rescue ActiveRecord::RecordInvalid
@applies_to_airframe = applies_to_airframe? @applies_to_airframe = applies_to_airframe?
@@ -47,8 +47,8 @@ class InspectionTypesController < ApplicationController
@inspection_type.update!(type_params) @inspection_type.update!(type_params)
apply_applicability(@inspection_type, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids) apply_applicability(@inspection_type, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids)
end end
log_event("inspection", "Inspection type updated: #{@inspection_type.name}") log_event("inspection", t("flash.inspection_types.inspection_type_updated_2", name: @inspection_type.name))
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection type updated." redirect_to aircraft_inspections_path(@aircraft), notice: t("flash.inspection_types.inspection_type_updated")
rescue ActiveRecord::RecordInvalid rescue ActiveRecord::RecordInvalid
@applies_to_airframe = applies_to_airframe? @applies_to_airframe = applies_to_airframe?
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
@@ -56,8 +56,8 @@ class InspectionTypesController < ApplicationController
def destroy def destroy
detach_from_aircraft(@inspection_type) detach_from_aircraft(@inspection_type)
log_event("inspection", "Inspection type removed: #{@inspection_type.name}") log_event("inspection", t("flash.inspection_types.inspection_type_removed", name: @inspection_type.name))
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection removed from #{@aircraft.tail_number}." redirect_to aircraft_inspections_path(@aircraft), notice: t("flash.inspection_types.inspection_removed_from", tail_number: @aircraft.tail_number)
end end
private private
+11 -9
View File
@@ -1,17 +1,19 @@
# The invited signer's side: sign in (or create an account for the invited # The invited signer's side: sign in (or, from an Owner's invitation, create an
# address), add a certificate if needed, review the entry and sign it. The # account for the invited address: SigningInvitation#creates_account?), add a
# invitation gives access to that one entry only. # certificate if needed, review the entry and sign it. The invitation gives
# access to that one entry only.
class InvitedSigningsController < ApplicationController class InvitedSigningsController < ApplicationController
include EntrySigning include EntrySigning
allow_unauthenticated_access only: %i[show account] allow_unauthenticated_access only: %i[show account]
before_action :set_invitation before_action :set_invitation
rate_limit to: 10, within: 15.minutes, only: :account, with: -> { redirect_to new_session_path, alert: "Try again later." } rate_limit to: 10, within: 15.minutes, only: :account, with: -> { redirect_to new_session_path, alert: t("flash.invited_signings.try_again_later") }
def show def show
@entry = @invitation.logbook_entry @entry = @invitation.logbook_entry
@aircraft = @entry.aircraft @aircraft = @entry.aircraft
unless authenticated? unless authenticated?
session[:return_to_after_authenticating] = request.url session[:return_to_after_authenticating] = request.url
session[:signing_token] = params[:token] # for an account made by signing in with SSO
return render(:welcome) return render(:welcome)
end end
return render(:wrong_account) unless current_user.email_address == @invitation.email return render(:wrong_account) unless current_user.email_address == @invitation.email
@@ -20,17 +22,17 @@ class InvitedSigningsController < ApplicationController
render :new render :new
end end
# Creating an account for the invited email address. # Creating an account for the invited email address (an Owner's invitation).
def account def account
return redirect_to(invited_signing_path(params[:token])) if authenticated? 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: "Sign in to continue." return redirect_to invited_signing_path(params[:token]), alert: t("flash.invited_signings.sign_in_to_continue")
end end
user = User.new(params.permit(:name, :password, :password_confirmation).merge(email_address: @invitation.email)) user = User.new(params.permit(:name, :password, :password_confirmation).merge(email_address: @invitation.email))
if user.save if user.save
reset_session reset_session
start_new_session_for user start_new_session_for user
redirect_to invited_signing_path(params[:token]), notice: "Account created. Add your certificate, then sign." redirect_to invited_signing_path(params[:token]), notice: t("flash.invited_signings.account_created_add_your")
else else
@entry = @invitation.logbook_entry @entry = @invitation.logbook_entry
@account_errors = user.errors.full_messages @account_errors = user.errors.full_messages
@@ -44,7 +46,7 @@ class InvitedSigningsController < ApplicationController
return render(:wrong_account) unless current_user.email_address == @invitation.email return render(:wrong_account) unless current_user.email_address == @invitation.email
sign_entry(@entry) do |signature| sign_entry(@entry) do |signature|
@invitation.update!(used_at: Time.current, user: current_user) @invitation.update!(used_at: Time.current, user: current_user)
redirect_to invited_signing_path(params[:token]), notice: "Signed. #{EntrySignature::LABEL} #{signature.signer_name}, #{signature.certificate_label} #{signature.certificate_number}." redirect_to invited_signing_path(params[:token]), notice: t("flash.invited_signings.signed", label: EntrySignature.label, signer_name: signature.signer_name, certificate_label: signature.certificate_label, certificate_number: signature.certificate_number)
end end
end end
+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
+3 -3
View File
@@ -2,7 +2,7 @@
# the loading calculator. # the loading calculator.
class LoadingSetupsController < ApplicationController class LoadingSetupsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! requires_permission :manage_weight_balance
def edit def edit
@setup = @aircraft.loading_setup @setup = @aircraft.loading_setup
@@ -13,8 +13,8 @@ class LoadingSetupsController < ApplicationController
@setup = LoadingSetup.from_params(permitted.to_h) @setup = LoadingSetup.from_params(permitted.to_h)
if @setup.valid? if @setup.valid?
@aircraft.update!(loading_stations: @setup.stations_json, cg_envelope: @setup.envelope.map { |w, cg| [ w.to_f, cg.to_f ] }) @aircraft.update!(loading_stations: @setup.stations_json, cg_envelope: @setup.envelope.map { |w, cg| [ w.to_f, cg.to_f ] })
log_event("aircraft", "Loading stations and CG envelope updated") log_event("aircraft", t("flash.loading_setups.loading_stations_and_cg"))
redirect_to aircraft_weight_balance_records_path(@aircraft), notice: "Loading setup saved." redirect_to aircraft_weight_balance_records_path(@aircraft), notice: t("flash.loading_setups.loading_setup_saved")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
+14 -14
View File
@@ -1,6 +1,6 @@
class LogbookEntriesController < ApplicationController class LogbookEntriesController < ApplicationController
include AircraftScoped 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 :set_entry, only: %i[show edit update destroy verify]
before_action :require_unsigned, only: %i[edit update destroy] before_action :require_unsigned, only: %i[edit update destroy]
@@ -18,10 +18,10 @@ class LogbookEntriesController < ApplicationController
# Someone has checked a transcribed entry against the scan. # Someone has checked a transcribed entry against the scan.
def verify def verify
@entry.update!(verified: true) @entry.update!(verified: true)
log_event("logbook", "Transcribed logbook entry verified: #{@entry.date}") log_event("logbook", t("flash.logbook_entries.transcribed_logbook_entry_verified", date: l(@entry.date, format: :app)))
next_entry = @aircraft.logbook_entries.unverified.order(:date, :id).first next_entry = @aircraft.logbook_entries.unverified.order(:date, :id).first
redirect_to next_entry ? aircraft_logbook_entry_path(@aircraft, next_entry) : aircraft_logbook_entries_path(@aircraft), redirect_to next_entry ? aircraft_logbook_entry_path(@aircraft, next_entry) : aircraft_logbook_entries_path(@aircraft),
notice: next_entry ? "Verified. Here's the next one to check." : "Verified. All transcribed entries are checked." notice: next_entry ? t("flash.logbook_entries.verified_next") : t("flash.logbook_entries.verified_all")
end end
def show; end def show; end
@@ -36,11 +36,11 @@ class LogbookEntriesController < ApplicationController
@entry.supersedes = correctable(params.dig(:logbook_entry, :supersedes_id)) @entry.supersedes = correctable(params.dig(:logbook_entry, :supersedes_id))
@entry.assign_parts(parts_params, @aircraft) @entry.assign_parts(parts_params, @aircraft)
if @entry.save if @entry.save
log_event("logbook", "Logbook entry #{@entry.supersedes ? 'correction ' : ''}added (#{@entry.date})") log_event("logbook", t(@entry.supersedes ? "flash.logbook_entries.correction_added_event" : "flash.logbook_entries.logbook_entry_added", date: l(@entry.date, format: :app)))
record_parts_service record_parts_service
record_inspections record_inspections
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), redirect_to aircraft_logbook_entry_path(@aircraft, @entry),
notice: @entry.supersedes ? "Correction saved. Sign it to supersede the original entry." : "Logbook entry added." notice: @entry.supersedes ? t("flash.logbook_entries.correction_saved") : t("flash.logbook_entries.added")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -52,8 +52,8 @@ class LogbookEntriesController < ApplicationController
@entry.assign_attributes(entry_params) @entry.assign_attributes(entry_params)
@entry.assign_parts(parts_params, @aircraft) @entry.assign_parts(parts_params, @aircraft)
if @entry.save if @entry.save
log_event("logbook", "Logbook entry updated (#{@entry.date})") log_event("logbook", t("flash.logbook_entries.logbook_entry_updated_2", date: l(@entry.date, format: :app)))
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: "Logbook entry updated." redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: t("flash.logbook_entries.logbook_entry_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -61,8 +61,8 @@ class LogbookEntriesController < ApplicationController
def destroy def destroy
@entry.destroy! @entry.destroy!
log_event("logbook", "Logbook entry deleted (#{@entry.date})") log_event("logbook", t("flash.logbook_entries.logbook_entry_deleted_2", date: l(@entry.date, format: :app)))
redirect_to aircraft_logbook_entries_path(@aircraft), notice: "Logbook entry deleted." redirect_to aircraft_logbook_entries_path(@aircraft), notice: t("flash.logbook_entries.logbook_entry_deleted")
end end
private private
@@ -70,7 +70,7 @@ class LogbookEntriesController < ApplicationController
# Signed entries are locked (AC 120-78B 2.1.2.8): changes go in a correction. # Signed entries are locked (AC 120-78B 2.1.2.8): changes go in a correction.
def require_unsigned def require_unsigned
return unless @entry.signed? return unless @entry.signed?
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), alert: "This entry is signed, so it can't be changed or deleted. Make a correction entry instead." redirect_to aircraft_logbook_entry_path(@aircraft, @entry), alert: t("flash.logbook_entries.this_entry_is_signed")
end end
# A signed, not yet superseded entry of this aircraft. # A signed, not yet superseded entry of this aircraft.
@@ -98,8 +98,8 @@ class LogbookEntriesController < ApplicationController
next unless p["include"] == "1" && %w[serviced replaced].include?(p["service"]) next unless p["include"] == "1" && %w[serviced replaced].include?(p["service"])
part = @entry.parts.find { _1.component_id == id.to_i } or next part = @entry.parts.find { _1.component_id == id.to_i } or next
component = part.component component = part.component
component.service_from_entry!(date: @entry.date, hours_at_entry: part.hours_at_entry, flown_since: flown, replaced: p["service"] == "replaced") component.service_from_entry!(date: l(@entry.date, format: :app), hours_at_entry: part.hours_at_entry, flown_since: flown, replaced: p["service"] == "replaced")
log_event("component", "#{p['service'] == 'replaced' ? 'Replaced' : 'Serviced'}: #{component} (logbook entry #{@entry.date})") log_event("component", t(p["service"] == "replaced" ? "flash.logbook_entries.replaced_event" : "flash.logbook_entries.serviced_event", component: component, date: l(@entry.date, format: :app)))
end end
end end
@@ -108,9 +108,9 @@ class LogbookEntriesController < ApplicationController
def record_inspections def record_inspections
ids = Array(params.dig(:logbook_entry, :inspection_type_ids)).compact_blank ids = Array(params.dig(:logbook_entry, :inspection_type_ids)).compact_blank
@aircraft.applicable_inspection_types.where(id: ids).find_each do |type| @aircraft.applicable_inspection_types.where(id: ids).find_each do |type|
@aircraft.inspection_records.create!(inspection_type: type, logbook_entry: @entry, date: @entry.date, @aircraft.inspection_records.create!(inspection_type: type, logbook_entry: @entry, date: l(@entry.date, format: :app),
aircraft_hours: @entry.aircraft_hours_at_entry) aircraft_hours: @entry.aircraft_hours_at_entry)
log_event("inspection", "Inspection completed: #{type.name} (logbook entry #{@entry.date})") log_event("inspection", t("flash.logbook_entries.inspection_completed_logbook_entry", name: type.name, date: l(@entry.date, format: :app)))
end end
end end
@@ -3,15 +3,15 @@
# entries in the background (LogbookTranscriptionJob). # entries in the background (LogbookTranscriptionJob).
class LogbookImportsController < ApplicationController class LogbookImportsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! requires_permission :import_records
def new def new
@collections = @aircraft.document_collections.ordered @collections = @aircraft.document_collections.ordered
end end
def create def create
files = Array(params[:pages]).compact_blank files = Array(params[:pages]).select { _1.respond_to?(:original_filename) } # uploaded files only
return redirect_to(new_aircraft_logbook_import_path(@aircraft), alert: "Choose the scanned pages to upload.") if files.empty? return redirect_to(new_aircraft_logbook_import_path(@aircraft), alert: t("flash.logbook_imports.choose_the_scanned_pages")) if files.empty?
# Page order follows the file names ("page-002" before "page-010"). # Page order follows the file names ("page-002" before "page-010").
files = files.sort_by { |f| f.original_filename.to_s.downcase.scan(/\d+|\D+/).map { _1.match?(/\d/) ? [ 0, _1.to_i ] : [ 1, _1 ] } } files = files.sort_by { |f| f.original_filename.to_s.downcase.scan(/\d+|\D+/).map { _1.match?(/\d/) ? [ 0, _1.to_i ] : [ 1, _1 ] } }
@@ -32,7 +32,7 @@ class LogbookImportsController < ApplicationController
import = @aircraft.logbook_imports.create!(user: current_user, document: document, log_type: params[:log_type], import = @aircraft.logbook_imports.create!(user: current_user, document: document, log_type: params[:log_type],
transcribe: params[:transcribe] == "1" && LogbookImport.ai_available?) transcribe: params[:transcribe] == "1" && LogbookImport.ai_available?)
end end
log_event("document", "Logbook pages uploaded: #{document.name} (#{files.size} #{'page'.pluralize(files.size)})") log_event("document", t("flash.logbook_imports.pages_uploaded", name: document.name, count: files.size))
LogbookTranscriptionJob.perform_later(import.id) LogbookTranscriptionJob.perform_later(import.id)
redirect_to aircraft_logbook_import_path(@aircraft, import) redirect_to aircraft_logbook_import_path(@aircraft, import)
end end
+2 -2
View File
@@ -10,7 +10,7 @@ class LogbookPrintsController < ApplicationController
def show def show
pdf = LogbookEntryPdf.new(@aircraft, @entries, layout: params[:layout], start_at: params[:start_at]) pdf = LogbookEntryPdf.new(@aircraft, @entries, layout: params[:layout], start_at: params[:start_at])
log_event("logbook", "Logbook entries printed (#{@entries.size})") log_event("logbook", t("flash.logbook_prints.logbook_entries_printed", count: @entries.size))
send_data pdf.render, filename: pdf.filename, type: "application/pdf", disposition: "inline" send_data pdf.render, filename: pdf.filename, type: "application/pdf", disposition: "inline"
end end
@@ -19,6 +19,6 @@ class LogbookPrintsController < ApplicationController
def set_entries def set_entries
ids = Array(params[:ids]).map(&:to_i).first(200) ids = Array(params[:ids]).map(&:to_i).first(200)
@entries = @aircraft.logbook_entries.where(id: ids).includes(:component, :parts, :signature, inspection_records: :inspection_type).order(:date, :id).to_a @entries = @aircraft.logbook_entries.where(id: ids).includes(:component, :parts, :signature, inspection_records: :inspection_type).order(:date, :id).to_a
redirect_to aircraft_logbook_entries_path(@aircraft), alert: "Choose the entries to print." if @entries.empty? redirect_to aircraft_logbook_entries_path(@aircraft), alert: t("flash.logbook_prints.choose_the_entries_to") if @entries.empty?
end end
end end
@@ -4,7 +4,7 @@ class MaintenanceReportsController < ApplicationController
def show def show
@report = MaintenanceReport.new(@aircraft) @report = MaintenanceReport.new(@aircraft)
log_event("aircraft", "Maintenance status report viewed") if params[:print] log_event("aircraft", t("flash.maintenance_reports.maintenance_status_report_viewed")) if params[:print]
render layout: "report" render layout: "report"
end end
end end
+7 -7
View File
@@ -1,6 +1,6 @@
class MajorRecordsController < ApplicationController class MajorRecordsController < ApplicationController
include AircraftScoped 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] before_action :set_record, only: %i[show edit update destroy]
def index def index
@@ -17,8 +17,8 @@ class MajorRecordsController < ApplicationController
def create def create
@record = @aircraft.major_records.new(record_params) @record = @aircraft.major_records.new(record_params)
if @record.save if @record.save
log_event("major_record", "#{@record.type_label} added: #{@record.title}") log_event("major_record", t("flash.major_records.added", type_label: @record.type_label, title: @record.title))
redirect_to aircraft_major_records_path(@aircraft), notice: "Record added." redirect_to aircraft_major_records_path(@aircraft), notice: t("flash.major_records.record_added")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -28,8 +28,8 @@ class MajorRecordsController < ApplicationController
def update def update
if @record.update(record_params) if @record.update(record_params)
log_event("major_record", "#{@record.type_label} updated: #{@record.title}") log_event("major_record", t("flash.major_records.updated", type_label: @record.type_label, title: @record.title))
redirect_to aircraft_major_record_path(@aircraft, @record), notice: "Record updated." redirect_to aircraft_major_record_path(@aircraft, @record), notice: t("flash.major_records.record_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -37,8 +37,8 @@ class MajorRecordsController < ApplicationController
def destroy def destroy
@record.destroy! @record.destroy!
log_event("major_record", "#{@record.type_label} deleted: #{@record.title}") log_event("major_record", t("flash.major_records.deleted", type_label: @record.type_label, title: @record.title))
redirect_to aircraft_major_records_path(@aircraft), notice: "Record deleted." redirect_to aircraft_major_records_path(@aircraft), notice: t("flash.major_records.record_deleted")
end end
private private
+8 -7
View File
@@ -1,6 +1,7 @@
class NotesController < ApplicationController class NotesController < ApplicationController
include AircraftScoped 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] before_action :set_note, only: %i[edit update destroy]
def index def index
@@ -19,8 +20,8 @@ class NotesController < ApplicationController
def create def create
@note = @aircraft.notes.new(note_params.merge(user: current_user)) @note = @aircraft.notes.new(note_params.merge(user: current_user))
if @note.save if @note.save
log_event("note", "Note added") log_event("note", t("flash.notes.note_added_2"))
redirect_to aircraft_notes_path(@aircraft), notice: "Note added." redirect_to aircraft_notes_path(@aircraft), notice: t("flash.notes.note_added")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -30,8 +31,8 @@ class NotesController < ApplicationController
def update def update
if @note.update(note_params.merge(edited_at: Time.current)) if @note.update(note_params.merge(edited_at: Time.current))
log_event("note", "Note updated") log_event("note", t("flash.notes.note_updated_2"))
redirect_to aircraft_notes_path(@aircraft), notice: "Note updated." redirect_to aircraft_notes_path(@aircraft), notice: t("flash.notes.note_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -39,8 +40,8 @@ class NotesController < ApplicationController
def destroy def destroy
@note.destroy! @note.destroy!
log_event("note", "Note deleted") log_event("note", t("flash.notes.note_deleted_2"))
redirect_to aircraft_notes_path(@aircraft), notice: "Note deleted." redirect_to aircraft_notes_path(@aircraft), notice: t("flash.notes.note_deleted")
end end
private private
+11
View File
@@ -0,0 +1,11 @@
# The page the installed app shows without a connection. The service worker
# keeps a copy when it installs, so it's rendered in the app's language; it
# has no session data and inline styles only (nothing else may be cached).
class OfflineController < ApplicationController
allow_unauthenticated_access
skip_before_action :redirect_to_setup
def show
render layout: false
end
end
+14 -13
View File
@@ -1,6 +1,7 @@
class OilAnalysesController < ApplicationController class OilAnalysesController < ApplicationController
include AircraftScoped 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] before_action :set_analysis, only: %i[show edit update destroy]
COMPARE_SAMPLES = 6 # columns in the trend table, like the lab report's history COMPARE_SAMPLES = 6 # columns in the trend table, like the lab report's history
@@ -24,8 +25,8 @@ class OilAnalysesController < ApplicationController
def create def create
@analysis = @aircraft.oil_analyses.new(analysis_params) @analysis = @aircraft.oil_analyses.new(analysis_params)
if @analysis.save if @analysis.save
log_event("oil_analysis", "Oil analysis added (sampled #{@analysis.sample_date})") log_event("oil_analysis", t("flash.oil_analyses.oil_analysis_added_sampled", sample_date: l(@analysis.sample_date, format: :app)))
redirect_to aircraft_oil_analysis_path(@aircraft, @analysis), notice: "Oil analysis saved." redirect_to aircraft_oil_analysis_path(@aircraft, @analysis), notice: t("flash.oil_analyses.oil_analysis_saved")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -35,13 +36,13 @@ class OilAnalysesController < ApplicationController
# earlier samples, so samples already on file are skipped rather than duplicated. # earlier samples, so samples already on file are skipped rather than duplicated.
def import def import
file = params[:report] file = params[:report]
return redirect_to(new_aircraft_oil_analysis_path(@aircraft), alert: "Choose a lab report PDF.") if file.blank? return redirect_to(new_aircraft_oil_analysis_path(@aircraft), alert: t("flash.oil_analyses.choose_a_lab_report")) unless file.respond_to?(:tempfile)
report = OilReportParser.from_pdf(file.tempfile) report = OilReportParser.from_pdf(file.tempfile)
file.rewind file.rewind
if report.tail_number.present? && normalize_tail(report.tail_number) != normalize_tail(@aircraft.tail_number) if report.tail_number.present? && normalize_tail(report.tail_number) != normalize_tail(@aircraft.tail_number)
return redirect_to(new_aircraft_oil_analysis_path(@aircraft), return redirect_to(new_aircraft_oil_analysis_path(@aircraft),
alert: "That report is for #{report.tail_number}, not #{@aircraft.tail_number}.") alert: t("flash.oil_analyses.that_report_is_for", report_tail: report.tail_number, tail_number: @aircraft.tail_number))
end end
engine = engine_for(report) engine = engine_for(report)
@@ -57,20 +58,20 @@ class OilAnalysesController < ApplicationController
current_record.report.attach(file) if current_record && !current_record.report.attached? current_record.report.attach(file) if current_record && !current_record.report.attached?
skipped = report.samples.size - created.size skipped = report.samples.size - created.size
created.each { log_event("oil_analysis", "Oil analysis imported (sampled #{_1.sample_date})") } created.each { log_event("oil_analysis", t("flash.oil_analyses.oil_analysis_imported_sampled", sample_date: _1.sample_date)) }
notice = "Imported #{helpers.pluralize(created.size, 'sample')} from the #{report.lab} report." notice = t("flash.oil_analyses.imported", count: created.size, lab: report.lab)
notice += " #{helpers.pluralize(skipped, 'sample was', plural: 'samples were')} already recorded." if skipped.positive? notice += " #{t('flash.oil_analyses.already_recorded', count: skipped)}" if skipped.positive?
redirect_to aircraft_oil_analyses_path(@aircraft), notice: notice redirect_to aircraft_oil_analyses_path(@aircraft), notice: notice
rescue OilReportParser::Error => e rescue OilReportParser::Error => e
redirect_to new_aircraft_oil_analysis_path(@aircraft), alert: "Couldn't import that report: #{e.message}" redirect_to new_aircraft_oil_analysis_path(@aircraft), alert: t("flash.oil_analyses.couldn_t_import_that", message: e.message)
end end
def edit; end def edit; end
def update def update
if @analysis.update(analysis_params) if @analysis.update(analysis_params)
log_event("oil_analysis", "Oil analysis updated (sampled #{@analysis.sample_date})") log_event("oil_analysis", t("flash.oil_analyses.oil_analysis_updated_sampled", sample_date: l(@analysis.sample_date, format: :app)))
redirect_to aircraft_oil_analysis_path(@aircraft, @analysis), notice: "Oil analysis updated." redirect_to aircraft_oil_analysis_path(@aircraft, @analysis), notice: t("flash.oil_analyses.oil_analysis_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -78,8 +79,8 @@ class OilAnalysesController < ApplicationController
def destroy def destroy
@analysis.destroy! @analysis.destroy!
log_event("oil_analysis", "Oil analysis deleted (sampled #{@analysis.sample_date})") log_event("oil_analysis", t("flash.oil_analyses.oil_analysis_deleted_sampled", sample_date: l(@analysis.sample_date, format: :app)))
redirect_to aircraft_oil_analyses_path(@aircraft), notice: "Oil analysis deleted." redirect_to aircraft_oil_analyses_path(@aircraft), notice: t("flash.oil_analyses.oil_analysis_deleted")
end end
private private
+6 -6
View File
@@ -2,8 +2,8 @@ class PasswordsController < ApplicationController
allow_unauthenticated_access allow_unauthenticated_access
before_action :require_password_login before_action :require_password_login
before_action :set_user_by_token, only: %i[ edit update ] before_action :set_user_by_token, only: %i[ edit update ]
rate_limit to: 5, within: 15.minutes, only: :create, with: -> { redirect_to new_session_path, alert: "Try again later." } rate_limit to: 5, within: 15.minutes, only: :create, with: -> { redirect_to new_session_path, alert: t("flash.passwords.try_again_later") }
rate_limit to: 10, within: 15.minutes, only: :update, with: -> { redirect_to new_session_path, alert: "Try again later." } rate_limit to: 10, within: 15.minutes, only: :update, with: -> { redirect_to new_session_path, alert: t("flash.passwords.try_again_later_2") }
def new def new
end end
@@ -13,7 +13,7 @@ class PasswordsController < ApplicationController
PasswordsMailer.reset(user).deliver_later PasswordsMailer.reset(user).deliver_later
end end
redirect_to new_session_path, notice: "Password reset instructions sent (if user with that email address exists)." redirect_to new_session_path, notice: t("flash.passwords.password_reset_instructions_sent")
end end
def edit def edit
@@ -22,7 +22,7 @@ class PasswordsController < ApplicationController
def update def update
if params[:password].present? && @user.update(params.permit(:password, :password_confirmation)) if params[:password].present? && @user.update(params.permit(:password, :password_confirmation))
@user.sessions.destroy_all # a reset signs out every device @user.sessions.destroy_all # a reset signs out every device
redirect_to new_session_path, notice: "Password has been reset." redirect_to new_session_path, notice: t("flash.passwords.password_has_been_reset")
else else
redirect_to edit_password_path(params[:token]), alert: @user.errors.full_messages.to_sentence.presence || "Enter a new password." redirect_to edit_password_path(params[:token]), alert: @user.errors.full_messages.to_sentence.presence || "Enter a new password."
end end
@@ -30,12 +30,12 @@ class PasswordsController < ApplicationController
private private
def require_password_login def require_password_login
redirect_to new_session_path, alert: "Sign in with #{Sso.label}." unless Sso.password_login? redirect_to new_session_path, alert: t("flash.passwords.sign_in_with", label: Sso.label) unless Sso.password_login?
end end
def set_user_by_token def set_user_by_token
@user = User.find_by_password_reset_token!(params[:token]) @user = User.find_by_password_reset_token!(params[:token])
rescue ActiveSupport::MessageVerifier::InvalidSignature rescue ActiveSupport::MessageVerifier::InvalidSignature
redirect_to new_password_path, alert: "Password reset link is invalid or has expired." redirect_to new_password_path, alert: t("flash.passwords.password_reset_link_is")
end end
end end
+4 -4
View File
@@ -7,20 +7,20 @@ class ProfilesController < ApplicationController
# left open somewhere can't be turned into a takeover of the account. # left open somewhere can't be turned into a takeover of the account.
def update def update
@user = current_user @user = current_user
attrs = params.require(:user).permit(:name, :email_address, :password, :password_confirmation, :reminder_emails) attrs = params.require(:user).permit(:name, :email_address, :password, :password_confirmation, :reminder_emails, :time_zone)
attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank? attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank?
new_email = User.normalize_value_for(:email_address, attrs[:email_address].to_s) if attrs.key?(:email_address) new_email = User.normalize_value_for(:email_address, attrs[:email_address].to_s) if attrs.key?(:email_address)
sensitive = (new_email && new_email != @user.email_address) || attrs.key?(:password) sensitive = (new_email && new_email != @user.email_address) || attrs.key?(:password)
# Checked before assigning: setting a new password replaces the digest at once. # Checked before assigning: setting a new password replaces the digest at once.
if sensitive && !@user.authenticate_password(params.dig(:user, :current_password).to_s) if sensitive && !@user.authenticate_password(params.dig(:user, :current_password).to_s)
@user.assign_attributes(attrs.except(:password, :password_confirmation)) @user.assign_attributes(attrs.except(:password, :password_confirmation))
@user.errors.add(:base, "Enter your current password to change your email or password") @user.errors.add(:base, :current_password_needed)
return render :edit, status: :unprocessable_entity return render :edit, status: :unprocessable_entity
end end
@user.assign_attributes(attrs) @user.assign_attributes(attrs)
if @user.save if @user.save
@user.sessions.where.not(id: Current.session.id).destroy_all if attrs.key?(:password) @user.sessions.where.not(id: Current.session.id).destroy_all if attrs.key?(:password)
redirect_to root_path, notice: "Profile updated." redirect_to root_path, notice: t("flash.profiles.profile_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -28,6 +28,6 @@ class ProfilesController < ApplicationController
def sign_out_others def sign_out_others
count = current_user.sessions.where.not(id: Current.session.id).destroy_all.size count = current_user.sessions.where.not(id: Current.session.id).destroy_all.size
redirect_to edit_profile_path, notice: "Signed out #{helpers.pluralize(count, 'other session')}." redirect_to edit_profile_path, notice: t("flash.profiles.signed_out_others", count: count)
end end
end end
@@ -0,0 +1,54 @@
# Notifications on this device (Profile): the browser's push subscription is
# saved here when the user turns them on, and removed when they turn them off.
class PushSubscriptionsController < ApplicationController
def create
sub = params.require(:subscription).permit(:endpoint, keys: %i[p256dh auth])
record = PushSubscription.find_or_initialize_by(endpoint: sub[:endpoint].to_s)
record.assign_attributes(user: current_user, p256dh: sub.dig(:keys, :p256dh), auth: sub.dig(:keys, :auth),
user_agent: request.user_agent.to_s.first(250))
if record.save
head :created
else
render json: { error: t("flash.push_subscriptions.not_saved", host: URI.parse(record.endpoint).host.to_s) }, status: :unprocessable_entity
end
rescue URI::InvalidURIError
render json: { error: t("flash.push_subscriptions.not_saved", host: "?") }, status: :unprocessable_entity
end
def destroy
current_user.push_subscriptions.where(endpoint: params[:endpoint].to_s).destroy_all
head :no_content
end
# A notification to each of this user's devices, sent now so the page can
# say which push services took it (and why one didn't).
def test
message = PushNotificationJob.message("test", edit_profile_path, "test")
devices = current_user.push_subscriptions.order(:created_at).map do |sub|
{ device: device_name(sub.user_agent), error: PushNotificationJob.deliver(sub, message) }
end
render json: { devices: devices }
end
private
# "Chrome on Android" from the browser's description of itself.
def device_name(agent)
browser = case agent
when /Edg\//, /EdgA\// then "Edge"
when /SamsungBrowser/ then "Samsung Internet"
when /Firefox|FxiOS/ then "Firefox"
when /Chrome|CriOS/ then "Chrome"
when /Safari/ then "Safari"
end
system = case agent
when /Android/ then "Android"
when /iPhone/ then "iPhone"
when /iPad/ then "iPad"
when /Macintosh/ then "Mac"
when /Windows/ then "Windows"
when /Linux/ then "Linux"
end
[ browser, system ].compact.join(" · ").presence || t("flash.push_subscriptions.unknown_device")
end
end
@@ -1,7 +1,7 @@
# Every change to the aircraft's maintenance records (AC 120-78B 3.2.2). # Every change to the aircraft's maintenance records (AC 120-78B 3.2.2).
class RecordVersionsController < ApplicationController class RecordVersionsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner!, only: :restore requires_permission :restore_history, only: :restore
SHARED = { "AirworthinessDirective" => AirworthinessDirective, "InspectionType" => InspectionType }.freeze SHARED = { "AirworthinessDirective" => AirworthinessDirective, "InspectionType" => InspectionType }.freeze
@@ -18,17 +18,17 @@ class RecordVersionsController < ApplicationController
def restore def restore
version = RecordVersion.where(aircraft_id: @aircraft.id, event: "unlink", item_type: SHARED.keys).find(params[:id]) version = RecordVersion.where(aircraft_id: @aircraft.id, event: "unlink", item_type: SHARED.keys).find(params[:id])
record = SHARED.fetch(version.item_type).find_by(id: version.item_id) record = SHARED.fetch(version.item_type).find_by(id: version.item_id)
return redirect_to(aircraft_record_versions_path(@aircraft), alert: "That record no longer exists.") unless record return redirect_to(aircraft_record_versions_path(@aircraft), alert: t("flash.record_versions.that_record_no_longer")) unless record
c = version.changes_hash c = version.changes_hash
if c["applies_to"] == "component" if c["applies_to"] == "component"
component = @aircraft.components.find_by(id: c["component_id"]) component = @aircraft.components.find_by(id: c["component_id"])
return redirect_to(aircraft_record_versions_path(@aircraft), alert: "That component no longer exists; edit the record's applicability instead.") unless component return redirect_to(aircraft_record_versions_path(@aircraft), alert: t("flash.record_versions.that_component_no_longer")) unless component
record.components << component unless record.components.include?(component) record.components << component unless record.components.include?(component)
else else
record.aircraft << @aircraft unless record.aircraft.include?(@aircraft) record.aircraft << @aircraft unless record.aircraft.include?(@aircraft)
end end
log_event(version.item_type == "AirworthinessDirective" ? "ad" : "inspection", "Restored: #{record} applies again") log_event(version.item_type == "AirworthinessDirective" ? "ad" : "inspection", "Restored: #{record} applies again")
redirect_to aircraft_record_versions_path(@aircraft), notice: "#{record} applies to #{@aircraft.tail_number} again." redirect_to aircraft_record_versions_path(@aircraft), notice: t("flash.record_versions.applies_to_again", record: record, tail_number: @aircraft.tail_number)
end end
# Whether an unlink can still be undone (the record exists and isn't linked that way now). # Whether an unlink can still be undone (the record exists and isn't linked that way now).
@@ -1,7 +1,7 @@
# Download every record of an aircraft in one ZIP (owners). # Download every record of an aircraft in one ZIP (owners).
class RecordsPackagesController < ApplicationController class RecordsPackagesController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! requires_permission :export_data
def show def show
package = RecordsPackage.new(@aircraft, source: request.host) package = RecordsPackage.new(@aircraft, source: request.host)
@@ -10,7 +10,7 @@ class RecordsPackagesController < ApplicationController
Dir[dir.join("*.zip")].each { |old| File.delete(old) if File.mtime(old) < 1.hour.ago } Dir[dir.join("*.zip")].each { |old| File.delete(old) if File.mtime(old) < 1.hour.ago }
path = dir.join("#{SecureRandom.hex(12)}.zip").to_s path = dir.join("#{SecureRandom.hex(12)}.zip").to_s
package.write_to(path) package.write_to(path)
log_event("aircraft", "Records package downloaded") log_event("aircraft", t("flash.records_packages.records_package_downloaded"))
# Generic binary, not application/zip: Safari unzips zip downloads into a # Generic binary, not application/zip: Safari unzips zip downloads into a
# folder ("Open safe files"); the package should stay one file to hand over. # folder ("Open safe files"); the package should stay one file to hand over.
send_file path, filename: package.filename, type: "application/octet-stream", disposition: "attachment" send_file path, filename: package.filename, type: "application/octet-stream", disposition: "attachment"
+1 -1
View File
@@ -1,7 +1,7 @@
# One search box across the records of the aircraft the user can see # One search box across the records of the aircraft the user can see
# (or one aircraft, from its own pages). # (or one aircraft, from its own pages).
class SearchesController < ApplicationController class SearchesController < ApplicationController
rate_limit to: 60, within: 1.minute, with: -> { redirect_to root_path, alert: "Too many searches; wait a moment." } rate_limit to: 60, within: 1.minute, with: -> { redirect_to root_path, alert: t("flash.searches.too_many_searches_wait") }
def show def show
fleet = current_user.accessible_aircraft.ordered.to_a fleet = current_user.accessible_aircraft.ordered.to_a
+9 -10
View File
@@ -1,45 +1,44 @@
class SessionsController < ApplicationController class SessionsController < ApplicationController
allow_unauthenticated_access only: %i[new create two_factor verify_two_factor] allow_unauthenticated_access only: %i[new create two_factor verify_two_factor]
rate_limit to: 10, within: 3.minutes, only: %i[create verify_two_factor], with: -> { redirect_to new_session_url, alert: "Try again later." } rate_limit to: 10, within: 3.minutes, only: %i[create verify_two_factor], with: -> { redirect_to new_session_url, alert: t("flash.sessions.try_again_later") }
FAILED = "Try another email address or password. After #{User::LOCK_AFTER} failed tries in a row an account is locked for #{User::LOCK_FOR.inspect}.".freeze
def new def new
end end
def create def create
return redirect_to new_session_path, alert: "Sign in with #{Sso.label}." unless Sso.password_login? return redirect_to new_session_path, alert: t("flash.sessions.sign_in_with", label: Sso.label) unless Sso.password_login?
if (user = User.authenticate_with_lockout(email_address: params[:email_address], password: params[:password])) && user.disabled? if (user = User.authenticate_with_lockout(email_address: params[:email_address], password: params[:password])) && user.disabled?
redirect_to new_session_path, alert: "This account is disabled." redirect_to new_session_path, alert: t("flash.sessions.this_account_is_disabled")
elsif user elsif user
begin_sign_in user, return_to: after_authentication_url begin_sign_in user, return_to: after_authentication_url
else else
redirect_to new_session_path(email_address: params[:email_address].to_s.first(200)), alert: FAILED redirect_to new_session_path(email_address: params[:email_address].to_s.first(200)), alert: t("flash.sessions.failed", tries: User::LOCK_AFTER, minutes: User::LOCK_FOR.in_minutes.to_i)
end end
end end
# Second step for accounts with an authenticator app. # Second step for accounts with an authenticator app.
def two_factor def two_factor
redirect_to new_session_path, alert: "Sign in again." unless pending_otp_user redirect_to new_session_path, alert: t("flash.sessions.sign_in_again") unless pending_otp_user
end end
def verify_two_factor def verify_two_factor
user = pending_otp_user user = pending_otp_user
return redirect_to(new_session_path, alert: "That took too long. Sign in again.") unless user return redirect_to(new_session_path, alert: t("flash.sessions.that_took_too_long")) unless user
if user.locked? if user.locked?
reset_session reset_session
redirect_to new_session_path, alert: FAILED redirect_to new_session_path, alert: t("flash.sessions.failed", tries: User::LOCK_AFTER, minutes: User::LOCK_FOR.in_minutes.to_i)
elsif user.verify_second_factor(params[:code]) elsif user.verify_second_factor(params[:code])
user.clear_failed_sign_ins! user.clear_failed_sign_ins!
return_to = after_authentication_url return_to = after_authentication_url
reset_session reset_session
start_new_session_for user start_new_session_for user
notice = user.recovery_codes_left < 3 ? "Signed in. You have #{user.recovery_codes_left} recovery codes left: make new ones on your profile." : nil notice = user.recovery_codes_left < 3 ? t("flash.sessions.few_recovery_codes", count: user.recovery_codes_left) : nil
redirect_to return_to, notice: notice redirect_to return_to, notice: notice
else else
user.register_failed_sign_in! user.register_failed_sign_in!
redirect_to two_factor_session_path, alert: "That code didn't match. Try the current code from your authenticator app, or a recovery code." redirect_to two_factor_session_path, alert: t("flash.sessions.that_code_didn_t")
end end
end end
+9 -1
View File
@@ -1,18 +1,26 @@
class SetupController < ApplicationController class SetupController < ApplicationController
allow_unauthenticated_access allow_unauthenticated_access
before_action { redirect_to root_path if User.exists? } before_action { redirect_to root_path if User.exists? }
rate_limit to: 10, within: 15.minutes, only: :create, with: -> { redirect_to new_setup_path, alert: t("flash.setup.try_again_later") }
layout "public" layout "public"
def new def new
@user = User.new @user = User.new
SetupCode.announce
end end
def create def create
@user = User.new(params.require(:user).permit(:name, :email_address, :password, :password_confirmation)) @user = User.new(params.require(:user).permit(:name, :email_address, :password, :password_confirmation))
@user.admin = true @user.admin = true
unless SetupCode.matches?(params[:setup_code])
@user.errors.add(:base, t("flash.setup.wrong_code"))
SetupCode.announce
return render(:new, status: :unprocessable_entity)
end
if @user.save if @user.save
SetupCode.clear
start_new_session_for @user start_new_session_for @user
redirect_to root_path, notice: "Welcome! You're the administrator. Add your first aircraft." redirect_to root_path, notice: t("flash.setup.welcome_you_re_the")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
+5 -5
View File
@@ -1,13 +1,13 @@
class ShareTokensController < ApplicationController class ShareTokensController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! requires_permission :manage_sharing
def create def create
token = @aircraft.share_tokens.new(params.require(:share_token).permit(:label, :privilege, :expires_at)) token = @aircraft.share_tokens.new(params.require(:share_token).permit(:label, :privilege, :expires_at))
token.created_by = current_user token.created_by = current_user
if token.save if token.save
log_event("aircraft", "Share link created (#{token.privilege})", notes: token.label) log_event("aircraft", t("flash.share_tokens.share_link_created_2", privilege: token.privilege), notes: token.label)
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Share link created." redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.share_tokens.share_link_created")
else else
redirect_to aircraft_aircraft_roles_path(@aircraft), alert: token.errors.full_messages.to_sentence redirect_to aircraft_aircraft_roles_path(@aircraft), alert: token.errors.full_messages.to_sentence
end end
@@ -16,7 +16,7 @@ class ShareTokensController < ApplicationController
def destroy def destroy
token = @aircraft.share_tokens.find(params[:id]) token = @aircraft.share_tokens.find(params[:id])
token.destroy! token.destroy!
log_event("aircraft", "Share link revoked", notes: token.label) log_event("aircraft", t("flash.share_tokens.share_link_revoked_2"), notes: token.label)
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Share link revoked." redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.share_tokens.share_link_revoked")
end end
end end
+16
View File
@@ -0,0 +1,16 @@
# The installed app's home-screen shortcuts (Log Flight, Report Squawk): the
# form for your aircraft, or a list to choose from when you have several.
class ShortcutsController < ApplicationController
def log_flight = go(:log_flight, ->(a) { new_aircraft_flight_log_path(a) })
def report_squawk = go(:report_squawk, ->(a) { new_aircraft_squawk_path(a) })
private
def go(action, path)
aircraft = current_user.accessible_aircraft.ordered.to_a
return redirect_to(path.(aircraft.first)) if aircraft.one?
@title = t("shortcuts.choose.#{action}")
@choices = aircraft.map { [ _1, path.(_1) ] }
render :choose
end
end
+7 -7
View File
@@ -7,8 +7,8 @@ class SignInLinksController < ApplicationController
allow_unauthenticated_access allow_unauthenticated_access
before_action :require_email_sign_in before_action :require_email_sign_in
before_action :set_user_by_token, only: %i[show consume] before_action :set_user_by_token, only: %i[show consume]
rate_limit to: 5, within: 15.minutes, only: :create, with: -> { redirect_to new_sign_in_link_path, alert: "Try again later." } rate_limit to: 5, within: 15.minutes, only: :create, with: -> { redirect_to new_sign_in_link_path, alert: t("flash.sign_in_links.try_again_later") }
rate_limit to: 20, within: 15.minutes, only: :consume, with: -> { redirect_to new_session_path, alert: "Try again later." } rate_limit to: 20, within: 15.minutes, only: :consume, with: -> { redirect_to new_session_path, alert: t("flash.sign_in_links.try_again_later_2") }
def new def new
end end
@@ -18,25 +18,25 @@ class SignInLinksController < ApplicationController
SessionsMailer.sign_in_link(user).deliver_later SessionsMailer.sign_in_link(user).deliver_later
end end
# Same answer either way, so this can't be used to find accounts. # Same answer either way, so this can't be used to find accounts.
redirect_to new_session_path, notice: "If there's an account for that address, a sign-in link is on its way. It works once, for 15 minutes." redirect_to new_session_path, notice: t("flash.sign_in_links.if_there_s_an")
end end
def show def show
end end
def consume def consume
return redirect_to new_session_path, alert: "This account is disabled." if @user.disabled? return redirect_to new_session_path, alert: t("flash.sign_in_links.this_account_is_disabled") if @user.disabled?
begin_sign_in @user, return_to: root_path, notice: "Signed in." # signing in also spends the link begin_sign_in @user, return_to: root_path, notice: t("flash.sign_in_links.signed_in") # signing in also spends the link
end end
private private
def require_email_sign_in def require_email_sign_in
redirect_to new_session_path, alert: "Sign in with #{Sso.label}." unless Sso.password_login? redirect_to new_session_path, alert: t("flash.sign_in_links.sign_in_with", label: Sso.label) unless Sso.password_login?
end end
def set_user_by_token def set_user_by_token
@user = User.find_by_token_for(:email_sign_in, params[:token].to_s) @user = User.find_by_token_for(:email_sign_in, params[:token].to_s)
redirect_to new_sign_in_link_path, alert: "That sign-in link has expired or was already used. Get a new one below." unless @user redirect_to new_sign_in_link_path, alert: t("flash.sign_in_links.that_sign_in_link") unless @user
end end
end end
@@ -1,24 +1,30 @@
# An owner asks someone outside the aircraft (a mechanic) to sign an entry. # An owner asks someone outside the aircraft (a mechanic) to sign an entry.
class SigningInvitationsController < ApplicationController class SigningInvitationsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! requires_permission :write_logbook
before_action :set_entry before_action :set_entry
rate_limit to: 10, within: 1.hour, only: :create, with: -> { redirect_back fallback_location: root_path, alert: "Too many invitations; try again later." } 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") }
def new def new
@invitation = @entry.signing_invitations.new @invitation = @entry.signing_invitations.new
end end
def create def create
return redirect_to(aircraft_logbook_entry_path(@aircraft, @entry), alert: "This entry is already signed.") if @entry.signed? return redirect_to(aircraft_logbook_entry_path(@aircraft, @entry), alert: t("flash.signing_invitations.this_entry_is_already")) if @entry.signed?
unless MailSettings.configured? unless MailSettings.configured?
return redirect_to aircraft_logbook_entry_path(@aircraft, @entry), alert: "Email isn't set up, so invitations can't be sent (Admin → About)." return redirect_to aircraft_logbook_entry_path(@aircraft, @entry), alert: t("flash.signing_invitations.email_isn_t_set")
end end
@invitation = @entry.signing_invitations.new(params.require(:signing_invitation).permit(:email, :message).merge(invited_by: current_user)) @invitation = @entry.signing_invitations.new(params.require(:signing_invitation).permit(:email, :message).merge(invited_by: current_user))
if @invitation.save if @invitation.save
SigningInvitationMailer.invite(@invitation, @invitation.token).deliver_later SigningInvitationMailer.invite(@invitation, @invitation.token).deliver_later
log_event("logbook", "Signature requested from #{@invitation.email} (#{@entry.date} entry)") if (invitee = User.active.find_by(email_address: @invitation.email))
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: "Invitation sent to #{@invitation.email}. The link works once, for #{SigningInvitation::VALID_FOR.inspect}." PushNotifier.notify(invitee, :signing_request, path: invited_signing_path(@invitation.token), tag: "sign-#{@invitation.id}",
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)))
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 else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
+25 -18
View File
@@ -2,7 +2,9 @@ class SquawksController < ApplicationController
include AircraftScoped include AircraftScoped
# Pilots may create squawks and defer inoperative items (91.213(d) lets the # Pilots may create squawks and defer inoperative items (91.213(d) lets the
# pilot decide); editing and resolving need an owner. # 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] before_action :set_squawk, only: %i[edit update destroy resolution resolve reopen deferral defer undefer]
def index def index
@@ -15,10 +17,14 @@ class SquawksController < ApplicationController
end end
def create def create
# Already received (sent again from the offline queue): don't report it twice.
if (key = params.dig(:squawk, :client_key).to_s.presence) && @aircraft.squawks.exists?(client_key: key.first(64))
return redirect_to(aircraft_squawks_path(@aircraft), notice: t("flash.squawks.already_reported"))
end
@squawk = @aircraft.squawks.new(squawk_params.merge(reported_by: current_user)) @squawk = @aircraft.squawks.new(squawk_params.merge(reported_by: current_user))
if @squawk.save if @squawk.save
log_event("squawk", "Squawk reported: #{@squawk.priority_label}", notes: @squawk.issue_reported.truncate(200)) SquawkReported.call(@squawk, by: current_user)
redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk reported." redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_reported")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -30,8 +36,8 @@ class SquawksController < ApplicationController
@squawk.assign_attributes(squawk_params.except(:attachments)) @squawk.assign_attributes(squawk_params.except(:attachments))
change_attachments change_attachments
if @squawk.save if @squawk.save
log_event("squawk", "Squawk updated") log_event("squawk", t("flash.squawks.squawk_updated_2"))
redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk updated." redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -42,7 +48,7 @@ class SquawksController < ApplicationController
def resolution def resolution
@entry = @aircraft.logbook_entries.new(date: Date.current, entry_type: "MAINTENANCE", log_type: "AC", @entry = @aircraft.logbook_entries.new(date: Date.current, entry_type: "MAINTENANCE", log_type: "AC",
aircraft_hours_at_entry: @aircraft.current_hours, aircraft_hours_at_entry: @aircraft.current_hours,
text: "Corrected: #{@squawk.issue_reported}", component: @squawk.component, text: t("flash.squawks.corrected_text", issue: @squawk.issue_reported), component: @squawk.component,
component_hours_at_entry: @squawk.component&.hours_in_service, component_hours_at_entry: @squawk.component&.hours_in_service,
component_since_overhaul_at_entry: @squawk.component&.hours_since_overhaul) component_since_overhaul_at_entry: @squawk.component&.hours_since_overhaul)
@entry.log_type = "ENG" if @squawk.component&.engine? @entry.log_type = "ENG" if @squawk.component&.engine?
@@ -56,13 +62,13 @@ class SquawksController < ApplicationController
@entry = @aircraft.logbook_entries.new(resolution_entry_params.merge(entry_type: "MAINTENANCE")) @entry = @aircraft.logbook_entries.new(resolution_entry_params.merge(entry_type: "MAINTENANCE"))
@entry.assign_parts(params.fetch(:logbook_entry, {}).permit(parts: {})[:parts]&.to_h || {}, @aircraft) @entry.assign_parts(params.fetch(:logbook_entry, {}).permit(parts: {})[:parts]&.to_h || {}, @aircraft)
return render(:resolution, status: :unprocessable_entity) unless @entry.save return render(:resolution, status: :unprocessable_entity) unless @entry.save
log_event("logbook", "Logbook entry added: #{@entry.date}") log_event("logbook", t("flash.squawks.logbook_entry_added", date: l(@entry.date, format: :app)))
@entry @entry
when "existing" then @aircraft.logbook_entries.find_by(id: params[:logbook_entry_id]) when "existing" then @aircraft.logbook_entries.find_by(id: params[:logbook_entry_id])
end end
@squawk.resolve!(notes: params[:resolution_notes], logbook_entry: entry) @squawk.resolve!(notes: params[:resolution_notes], logbook_entry: entry)
log_event("squawk", "Squawk resolved", notes: @squawk.issue_reported.truncate(200)) log_event("squawk", t("flash.squawks.squawk_resolved_2"), notes: @squawk.issue_reported.truncate(200))
redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk resolved#{' and recorded in the logbook' if entry}." redirect_to aircraft_squawks_path(@aircraft), notice: t(entry ? "flash.squawks.resolved_logged" : "flash.squawks.squawk_resolved")
end end
def deferral; end def deferral; end
@@ -70,8 +76,8 @@ class SquawksController < ApplicationController
def defer def defer
if @squawk.defer(checks: params[:checks], name: params[:deferred_by_name], role: params[:deferred_by_role], if @squawk.defer(checks: params[:checks], name: params[:deferred_by_name], role: params[:deferred_by_role],
action: params[:deferral_action], notes: params[:deferral_notes]) action: params[:deferral_action], notes: params[:deferral_notes])
log_event("squawk", "Inoperative item deferred (91.213(d))", notes: @squawk.issue_reported.truncate(200)) log_event("squawk", t("flash.squawks.inoperative_item_deferred_91"), notes: @squawk.issue_reported.truncate(200))
redirect_to aircraft_squawks_path(@aircraft), notice: "Deferred. Keep the placard in place until it's fixed." redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.deferred_keep_the_placard")
else else
render :deferral, status: :unprocessable_entity render :deferral, status: :unprocessable_entity
end end
@@ -79,20 +85,20 @@ class SquawksController < ApplicationController
def undefer def undefer
@squawk.undefer! @squawk.undefer!
log_event("squawk", "Deferral removed", notes: @squawk.issue_reported.truncate(200)) log_event("squawk", t("flash.squawks.deferral_removed_2"), notes: @squawk.issue_reported.truncate(200))
redirect_to aircraft_squawks_path(@aircraft), notice: "Deferral removed." redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.deferral_removed")
end end
def reopen def reopen
@squawk.update!(resolved: false, resolved_at: nil) @squawk.update!(resolved: false, resolved_at: nil)
log_event("squawk", "Squawk reopened") log_event("squawk", t("flash.squawks.squawk_reopened_2"))
redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk reopened." redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_reopened")
end end
def destroy def destroy
@squawk.destroy! @squawk.destroy!
log_event("squawk", "Squawk deleted") log_event("squawk", t("flash.squawks.squawk_deleted_2"))
redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk deleted." redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_deleted")
end end
private private
@@ -118,7 +124,8 @@ class SquawksController < ApplicationController
end end
def squawk_params def squawk_params
params.require(:squawk).permit(:priority, :issue_reported, :component_id, :notes, attachments: []) params.require(:squawk).permit(:priority, :issue_reported, :component_id, :notes, :client_key, attachments: [])
.tap { |p| p[:component_id] = scoped_id(@aircraft.components, p[:component_id]) if p.key?(:component_id) } .tap { |p| p[:component_id] = scoped_id(@aircraft.components, p[:component_id]) if p.key?(:component_id) }
.tap { |p| p[:client_key] = p[:client_key].to_s.first(64).presence if p.key?(:client_key) }
end end
end end
+39 -16
View File
@@ -6,10 +6,15 @@
# email is verified (or OIDC_TRUST_EMAIL is on), since some providers let # 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 # users edit their email. Otherwise, sign in with a password once and link
# from the profile page. # 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 class SsoController < ApplicationController
allow_unauthenticated_access only: %i[callback failure] allow_unauthenticated_access only: %i[callback failure]
before_action :require_sso before_action :require_sso
rate_limit to: 20, within: 3.minutes, only: :callback, with: -> { redirect_to new_session_path, alert: "Try again later." } rate_limit to: 20, within: 3.minutes, only: :callback, with: -> { redirect_to new_session_path, alert: t("flash.sso.try_again_later") }
def callback def callback
auth = request.env["omniauth.auth"] auth = request.env["omniauth.auth"]
@@ -20,36 +25,35 @@ class SsoController < ApplicationController
user = User.find_by(sso_uid: auth.uid) || link_by_email(auth) || create_user(auth) user = User.find_by(sso_uid: auth.uid) || link_by_email(auth) || create_user(auth)
unless user unless user
email = auth.info&.email.presence email = auth.info&.email.presence
return redirect_to new_session_path, alert: "There's no account for #{email || 'that sign-in'} here yet. " \ return redirect_to new_session_path, alert: t("flash.sso.there_s_no_account", email: email || t("flash.sso.that_sign_in"), provider: Sso.label)
"Ask an administrator to add you, or sign in with your password and link #{Sso.label} from your profile."
end end
return redirect_to new_session_path, alert: "This account is disabled." if user.disabled? return redirect_to new_session_path, alert: t("flash.sso.this_account_is_disabled") if user.disabled?
sync_admin(user, auth) sync_admin(user, auth)
return_to = session[:return_to_after_authenticating] return_to = session[:return_to_after_authenticating]
reset_session # fresh session id after signing in reset_session # fresh session id after signing in
start_new_session_for user 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 redirect_to return_to || root_url
end end
# OmniAuth's error codes; anything else (network errors…) is logged, not shown. # OmniAuth's error codes; anything else (network errors…) is logged, not shown.
FAILURES = { "invalid_credentials" => "invalid credentials", "csrf_detected" => "the sign-in expired, try again", FAILURES = %w[invalid_credentials csrf_detected access_denied timeout].freeze
"access_denied" => "access denied", "timeout" => "timed out" }.freeze
def failure def failure
reason = FAILURES[params[:message].to_s] reason = t(params[:message], scope: "flash.sso.failures") if FAILURES.include?(params[:message].to_s)
Rails.logger.warn("[sso] sign-in failed: #{params[:message].to_s.truncate(300)}") unless reason Rails.logger.warn("[sso] sign-in failed: #{params[:message].to_s.truncate(300)}") unless reason
redirect_to(authenticated? ? edit_profile_path : new_session_path, redirect_to(authenticated? ? edit_profile_path : new_session_path,
alert: "#{Sso.label} sign-in failed (#{reason || "couldn't reach or verify #{Sso.label}; see the server log"}).") alert: t("flash.sso.failed", provider: Sso.label, reason: reason || t("flash.sso.unreachable", provider: Sso.label)))
end end
def destroy def destroy
unless Sso.password_login? unless Sso.password_login?
return redirect_to edit_profile_path, alert: "Password sign-in is off, so unlinking #{Sso.label} would lock you out." return redirect_to edit_profile_path, alert: t("flash.sso.password_sign_in_is", label: Sso.label)
end end
current_user.update!(sso_uid: nil) current_user.update!(sso_uid: nil)
redirect_to edit_profile_path, notice: "#{Sso.label} unlinked. Sign in with your email and password from now on." redirect_to edit_profile_path, notice: t("flash.sso.unlinked_sign_in_with", label: Sso.label)
end end
private private
@@ -61,16 +65,16 @@ class SsoController < ApplicationController
# Signed in again (e.g. to sign a logbook entry): note when, and go back. # Signed in again (e.g. to sign a logbook entry): note when, and go back.
def reauthenticated(auth) def reauthenticated(auth)
session[:reauthenticated_at] = Time.current.to_i session[:reauthenticated_at] = Time.current.to_i
redirect_to session.delete(:after_reauth).presence || edit_profile_path, notice: "Signed in again with #{Sso.label}." redirect_to session.delete(:after_reauth).presence || edit_profile_path, notice: t("flash.sso.signed_in_again_with", label: Sso.label)
end end
def link(auth) def link(auth)
owner = User.find_by(sso_uid: auth.uid) owner = User.find_by(sso_uid: auth.uid)
if owner && owner != current_user if owner && owner != current_user
redirect_to edit_profile_path, alert: "That #{Sso.label} account is already linked to another user." redirect_to edit_profile_path, alert: t("flash.sso.that_account_is_already", label: Sso.label)
else else
current_user.update!(sso_uid: auth.uid) current_user.update!(sso_uid: auth.uid)
redirect_to edit_profile_path, notice: "#{Sso.label} linked. You can now sign in with it." redirect_to edit_profile_path, notice: t("flash.sso.linked_you_can_now", label: Sso.label)
end end
end end
@@ -83,15 +87,34 @@ class SsoController < ApplicationController
end end
def create_user(auth) def create_user(auth)
return unless Sso.auto_create_users?
email = auth.info&.email.to_s.strip.downcase email = auth.info&.email.to_s.strip.downcase
return if email.blank? || User.exists?(email_address: email) return if email.blank? || User.exists?(email_address: email)
# The random password is never shown; a password reset can set a real one. invitation = invitation_making_account(email)
User.create!(email_address: email, name: auth.info&.name.presence, sso_uid: auth.uid, password: SecureRandom.base58(40)) 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 rescue ActiveRecord::RecordInvalid
nil nil
end 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) def email_verified?(auth)
[ true, "true" ].include?(raw_info(auth)["email_verified"]) [ true, "true" ].include?(raw_info(auth)["email_verified"])
end end
@@ -1,16 +1,16 @@
class StandardInspectionsController < ApplicationController class StandardInspectionsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! requires_permission :manage_inspections
def new; end def new; end
def create def create
added = StandardInspections.add!(@aircraft, params[:templates]) added = StandardInspections.add!(@aircraft, params[:templates])
if added.any? if added.any?
log_event("inspection", "Standard inspections added", notes: added.map(&:name).join(", ")) log_event("inspection", t("flash.standard_inspections.standard_inspections_added"), notes: added.map(&:name).join(", "))
redirect_to aircraft_inspections_path(@aircraft), notice: "Added #{added.map(&:name).to_sentence}. Record when each was last done to see when it's next due." redirect_to aircraft_inspections_path(@aircraft), notice: t("flash.standard_inspections.added_record_when_each", items: added.map(&:name).to_sentence)
else else
redirect_to new_aircraft_standard_inspections_path(@aircraft), alert: "Nothing new was chosen." redirect_to new_aircraft_standard_inspections_path(@aircraft), alert: t("flash.standard_inspections.nothing_new_was_chosen")
end end
end end
end end
+6 -6
View File
@@ -1,10 +1,10 @@
# Profile → Two-factor: set up an authenticator app (TOTP) for password and # Profile → Two-factor: set up an authenticator app (TOTP) for password and
# emailed-link sign-in, turn it off, or make new recovery codes. # emailed-link sign-in, turn it off, or make new recovery codes.
class TwoFactorsController < ApplicationController class TwoFactorsController < ApplicationController
rate_limit to: 10, within: 5.minutes, only: %i[create destroy recovery_codes], with: -> { redirect_to edit_profile_path(anchor: "two-factor"), alert: "Try again later." } rate_limit to: 10, within: 5.minutes, only: %i[create destroy recovery_codes], with: -> { redirect_to edit_profile_path(anchor: "two-factor"), alert: t("flash.two_factors.try_again_later") }
def new def new
return redirect_to(back_path, notice: "Two-factor is already on.") if current_user.otp_enabled? return redirect_to(back_path, notice: t("flash.two_factors.two_factor_is_already")) if current_user.otp_enabled?
session[:pending_otp_secret] ||= User.new_otp_secret session[:pending_otp_secret] ||= User.new_otp_secret
@secret = session[:pending_otp_secret] @secret = session[:pending_otp_secret]
svg = RQRCode::QRCode.new(User.otp_uri(@secret, current_user.email_address)).as_svg(module_size: 4, use_path: true, viewbox: true) svg = RQRCode::QRCode.new(User.otp_uri(@secret, current_user.email_address)).as_svg(module_size: 4, use_path: true, viewbox: true)
@@ -20,22 +20,22 @@ class TwoFactorsController < ApplicationController
log_security("turned on two-factor") log_security("turned on two-factor")
render :codes render :codes
else else
redirect_to new_two_factor_path(return_to: params[:return_to]), alert: "That code didn't match. Check the time on your phone and try the current code." redirect_to new_two_factor_path(return_to: params[:return_to]), alert: t("flash.two_factors.that_code_didn_t")
end end
end end
def recovery_codes def recovery_codes
return redirect_to(edit_profile_path(anchor: "two-factor"), alert: "That code didn't match.") unless current_user.verify_second_factor(params[:code]) return redirect_to(edit_profile_path(anchor: "two-factor"), alert: t("flash.two_factors.that_code_didn_t_2")) unless current_user.verify_second_factor(params[:code])
@codes = current_user.enable_otp!(current_user.otp_secret) @codes = current_user.enable_otp!(current_user.otp_secret)
log_security("made new recovery codes") log_security("made new recovery codes")
render :codes render :codes
end end
def destroy def destroy
return redirect_to(edit_profile_path(anchor: "two-factor"), alert: "That code didn't match.") unless current_user.verify_second_factor(params[:code]) return redirect_to(edit_profile_path(anchor: "two-factor"), alert: t("flash.two_factors.that_code_didn_t_3")) unless current_user.verify_second_factor(params[:code])
current_user.disable_otp! current_user.disable_otp!
log_security("turned off two-factor") log_security("turned off two-factor")
redirect_to edit_profile_path(anchor: "two-factor"), notice: "Two-factor is off." redirect_to edit_profile_path(anchor: "two-factor"), notice: t("flash.two_factors.two_factor_is_off")
end end
private private
@@ -6,23 +6,23 @@ class UserCertificatesController < ApplicationController
certificate = current_user.certificates.new(certificate_params) certificate = current_user.certificates.new(certificate_params)
back = safe_return_to || edit_profile_path(anchor: "certificates") back = safe_return_to || edit_profile_path(anchor: "certificates")
if certificate.save if certificate.save
redirect_to back, notice: "#{certificate.kind_label} certificate added." redirect_to back, notice: t("flash.user_certificates.certificate_added", kind_label: certificate.kind_label)
else else
redirect_to back, alert: "Certificate not added: #{certificate.errors.full_messages.to_sentence}." redirect_to back, alert: t("flash.user_certificates.certificate_not_added", items: certificate.errors.full_messages.to_sentence)
end end
end end
def update def update
if @certificate.update(certificate_params) if @certificate.update(certificate_params)
redirect_to edit_profile_path(anchor: "certificates"), notice: "Certificate updated." redirect_to edit_profile_path(anchor: "certificates"), notice: t("flash.user_certificates.certificate_updated")
else else
redirect_to edit_profile_path(anchor: "certificates"), alert: "Certificate not updated: #{@certificate.errors.full_messages.to_sentence}." redirect_to edit_profile_path(anchor: "certificates"), alert: t("flash.user_certificates.certificate_not_updated", items: @certificate.errors.full_messages.to_sentence)
end end
end end
def destroy def destroy
@certificate.destroy! @certificate.destroy!
redirect_to edit_profile_path(anchor: "certificates"), notice: "Certificate removed." redirect_to edit_profile_path(anchor: "certificates"), notice: t("flash.user_certificates.certificate_removed")
end end
private private
@@ -2,7 +2,7 @@
# keep the records and the loading setup). # keep the records and the loading setup).
class WeightBalanceRecordsController < ApplicationController class WeightBalanceRecordsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner!, except: :index requires_permission :manage_weight_balance, except: :index
before_action :set_record, only: %i[edit update destroy] before_action :set_record, only: %i[edit update destroy]
def index def index
@@ -19,8 +19,8 @@ class WeightBalanceRecordsController < ApplicationController
def create def create
@record = @aircraft.weight_balance_records.new(record_params) @record = @aircraft.weight_balance_records.new(record_params)
if @record.save if @record.save
log_event("aircraft", "Weight & balance recorded: #{@record.empty_weight} lb @ #{@record.empty_arm} in") log_event("aircraft", t("flash.weight_balance_records.weight_balance_recorded_lb", empty_weight: @record.empty_weight, empty_arm: @record.empty_arm))
redirect_to aircraft_weight_balance_records_path(@aircraft), notice: "Weight & balance saved." redirect_to aircraft_weight_balance_records_path(@aircraft), notice: t("flash.weight_balance_records.weight_balance_saved")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -30,8 +30,8 @@ class WeightBalanceRecordsController < ApplicationController
def update def update
if @record.update(record_params) if @record.update(record_params)
log_event("aircraft", "Weight & balance updated (#{@record.date})") log_event("aircraft", t("flash.weight_balance_records.weight_balance_updated_2", date: l(@record.date, format: :app)))
redirect_to aircraft_weight_balance_records_path(@aircraft), notice: "Weight & balance updated." redirect_to aircraft_weight_balance_records_path(@aircraft), notice: t("flash.weight_balance_records.weight_balance_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -39,8 +39,8 @@ class WeightBalanceRecordsController < ApplicationController
def destroy def destroy
@record.destroy! @record.destroy!
log_event("aircraft", "Weight & balance record deleted (#{@record.date})") log_event("aircraft", t("flash.weight_balance_records.weight_balance_record_deleted", date: l(@record.date, format: :app)))
redirect_to aircraft_weight_balance_records_path(@aircraft), notice: "Record deleted." redirect_to aircraft_weight_balance_records_path(@aircraft), notice: t("flash.weight_balance_records.record_deleted")
end end
private private
+4 -4
View File
@@ -5,7 +5,7 @@
# <%= f.field :public, as: :checkbox, label: "Show on share links" %> # <%= f.field :public, as: :checkbox, label: "Show on share links" %>
class AppFormBuilder < ActionView::Helpers::FormBuilder class AppFormBuilder < ActionView::Helpers::FormBuilder
def field(method, as: :text, label: nil, hint: nil, collection: nil, include_blank: false, wrapper: {}, **opts) def field(method, as: :text, label: nil, hint: nil, collection: nil, include_blank: false, wrapper: {}, **opts)
label_text = label || method.to_s.humanize label_text = label || (object.class.respond_to?(:human_attribute_name) ? object.class.human_attribute_name(method) : method.to_s.humanize)
errors = object.respond_to?(:errors) ? object.errors[method] : [] errors = object.respond_to?(:errors) ? object.errors[method] : []
if as == :checkbox if as == :checkbox
@@ -35,7 +35,7 @@ class AppFormBuilder < ActionView::Helpers::FormBuilder
@template.content_tag(:div, class: wrapper[:class]) do @template.content_tag(:div, class: wrapper[:class]) do
label(method, label_text, class: "label") + input + label(method, label_text, class: "label") + input +
(hint ? @template.content_tag(:p, hint, class: "hint") : "".html_safe) + (hint ? @template.content_tag(:p, hint, class: "hint") : "".html_safe) +
errors.map { |e| @template.content_tag(:p, "#{label_text} #{e}", class: "field-error") }.join.html_safe errors.map { |e| @template.content_tag(:p, I18n.t("errors.format", attribute: label_text, message: e), class: "field-error") }.join.html_safe
end end
end end
@@ -49,10 +49,10 @@ class AppFormBuilder < ActionView::Helpers::FormBuilder
label(every, label, class: "label") + label(every, label, class: "label") +
@template.content_tag(:div, class: "flex gap-2") do @template.content_tag(:div, class: "flex gap-2") do
number_field(every, class: "input min-w-0 flex-1", min: 1, step: 1, inputmode: "numeric") + number_field(every, class: "input min-w-0 flex-1", min: 1, step: 1, inputmode: "numeric") +
select(:"#{name}_unit", CalendarInterval::UNITS.invert, {}, class: "input w-auto", "aria-label": "#{label} unit") select(:"#{name}_unit", CalendarInterval::UNITS.invert, {}, class: "input w-auto", "aria-label": I18n.t("helpers.form.interval_unit", label: label))
end + end +
(hint ? @template.content_tag(:p, hint, class: "hint") : "".html_safe) + (hint ? @template.content_tag(:p, hint, class: "hint") : "".html_safe) +
errors.map { |e| @template.content_tag(:p, "#{label} #{e}", class: "field-error") }.join.html_safe errors.map { |e| @template.content_tag(:p, I18n.t("errors.format", attribute: label, message: e), class: "field-error") }.join.html_safe
end end
end end
+43 -19
View File
@@ -1,35 +1,59 @@
module AircraftHelper module AircraftHelper
OFFLINE_AIRCRAFT = 10
# 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 (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) 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
# Tabs on the aircraft pages: [label, path, controller names that highlight it, owner_only] # Tabs on the aircraft pages: [label, path, controller names that highlight it, owner_only]
def aircraft_tabs(aircraft) def aircraft_tabs(aircraft)
[ [
[ "Overview", aircraft_path(aircraft), %w[aircraft] ], [ I18n.t("helpers.aircraft.overview"), aircraft_path(aircraft), %w[aircraft] ],
[ "Components", aircraft_components_path(aircraft), %w[components] ], [ I18n.t("helpers.aircraft.components"), aircraft_components_path(aircraft), %w[components] ],
[ "Squawks", aircraft_squawks_path(aircraft), %w[squawks] ], [ I18n.t("helpers.aircraft.squawks"), aircraft_squawks_path(aircraft), %w[squawks] ],
[ "Flights", aircraft_flight_logs_path(aircraft), %w[flight_logs flight_imports air_trail_exports airport_codes] ], [ I18n.t("helpers.aircraft.flights"), aircraft_flight_logs_path(aircraft), %w[flight_logs flight_imports air_trail_exports airport_codes] ],
[ "Oil & Fuel", aircraft_consumable_records_path(aircraft), %w[consumable_records] ], [ I18n.t("helpers.aircraft.oil_fuel"), aircraft_consumable_records_path(aircraft), %w[consumable_records oil_analyses] ],
[ "Oil Analysis", aircraft_oil_analyses_path(aircraft), %w[oil_analyses] ], [ I18n.t("helpers.aircraft.logbook"), aircraft_logbook_entries_path(aircraft), %w[logbook_entries] ],
[ "Logbook", aircraft_logbook_entries_path(aircraft), %w[logbook_entries] ], [ I18n.t("helpers.aircraft.inspections"), aircraft_inspections_path(aircraft), %w[inspections inspection_types inspection_records] ],
[ "Inspections", aircraft_inspections_path(aircraft), %w[inspections inspection_types inspection_records] ], [ I18n.t("helpers.aircraft.ads"), aircraft_airworthiness_directives_path(aircraft), %w[airworthiness_directives ad_compliances ad_imports] ],
[ "ADs", aircraft_airworthiness_directives_path(aircraft), %w[airworthiness_directives ad_compliances ad_imports] ], [ I18n.t("helpers.aircraft.documents"), aircraft_documents_path(aircraft), %w[documents document_collections] ],
[ "Documents", aircraft_documents_path(aircraft), %w[documents document_collections] ], [ I18n.t("helpers.aircraft.major_records"), aircraft_major_records_path(aircraft), %w[major_records] ],
[ "Major Records", aircraft_major_records_path(aircraft), %w[major_records] ], [ I18n.t("helpers.aircraft.w_b"), aircraft_weight_balance_records_path(aircraft), %w[weight_balance_records loading_setups] ],
[ "W&B", aircraft_weight_balance_records_path(aircraft), %w[weight_balance_records loading_setups] ], [ I18n.t("helpers.aircraft.notes"), aircraft_notes_path(aircraft), %w[notes] ],
[ "Notes", aircraft_notes_path(aircraft), %w[notes] ], [ I18n.t("helpers.aircraft.activity"), aircraft_events_path(aircraft), %w[events record_versions] ]
[ "Activity", aircraft_events_path(aircraft), %w[events record_versions] ], ]
([ "Access & Sharing", aircraft_aircraft_roles_path(aircraft), %w[aircraft_roles share_tokens] ] if owner?) end
].compact
# Getting a new aircraft set up (Overview): [key, done?, path] for each step.
def setup_steps(aircraft)
[
[ :components, aircraft.components.exists?, new_aircraft_component_path(aircraft) ],
[ :inspections, aircraft.applicable_inspection_types.exists?, new_aircraft_standard_inspections_path(aircraft) ],
[ :ads, aircraft.drs_imports.exists? || aircraft.applicable_ads.exists?, new_aircraft_ad_import_path(aircraft) ],
[ :documents, aircraft.documents.where(doc_type: %w[REGISTRATION AIRWORTHINESS_CERT]).exists?, new_aircraft_document_path(aircraft, doc_type: "REGISTRATION") ],
[ :weight_balance, aircraft.weight_balance_records.exists?, new_aircraft_weight_balance_record_path(aircraft) ]
]
end end
def component_options(aircraft, include_blank: true) def component_options(aircraft, include_blank: true)
opts = aircraft.components.where.not(status: "DISPOSED").includes(:component_type).map { [ _1.to_s, _1.id ] } opts = aircraft.components.where.not(status: "DISPOSED").includes(:component_type).map { [ _1.to_s, _1.id ] }
include_blank ? [ [ "— None —", nil ] ] + opts : opts include_blank ? [ [ I18n.t("helpers.aircraft.none"), nil ] ] + opts : opts
end end
def document_options(aircraft) def document_options(aircraft)
[ [ "— None —", nil ] ] + aircraft.documents.ordered.map { [ _1.name, _1.id ] } [ [ I18n.t("helpers.aircraft.none"), nil ] ] + aircraft.documents.ordered.map { [ _1.name, _1.id ] }
end end
def logbook_options(aircraft) def logbook_options(aircraft)
[ [ "— None —", nil ] ] + aircraft.logbook_entries.recent_first.limit(300).map { [ "#{_1.date} – #{_1.text.truncate(60)}", _1.id ] } [ [ I18n.t("helpers.aircraft.none"), nil ] ] + aircraft.logbook_entries.recent_first.limit(300).map { [ I18n.t("helpers.aircraft.entry_option", date: fmt_date(_1.date), text: _1.text.truncate(60)), _1.id ] }
end end
end end
+21 -19
View File
@@ -7,23 +7,29 @@ module ApplicationHelper
# How dates and times read across the app: "Nov 8, 2026", "Nov 8, 2026 14:05". # How dates and times read across the app: "Nov 8, 2026", "Nov 8, 2026 14:05".
# (Signatures and the record history keep exact UTC timestamps, 2026-11-08 14:05 UTC.) # (Signatures and the record history keep exact UTC timestamps, 2026-11-08 14:05 UTC.)
def fmt_date(value) def fmt_date(value)
value ? value.to_date.strftime("%b %-d, %Y") : "—" value ? l(value.to_date, format: :app) : "—"
end end
def fmt_time(value) def fmt_time(value)
value ? value.in_time_zone.strftime("%b %-d, %Y %H:%M") : "—" value ? l(value.in_time_zone, format: :app) : "—"
end
# Secondary actions (imports, exports, printing, tools) behind one I18n.t("helpers.application.more")
# button, so each section shows only its main action. The block gives the
# items: links or button_to forms with class "menu-item".
def more_menu(label = I18n.t("helpers.application.more"), small: false, &block)
tag.details(class: "relative", data: { controller: "dropdown", action: "click@window->dropdown#closeOutside keydown.esc@window->dropdown#close" }) do
tag.summary(class: [ "btn-secondary list-none [&::-webkit-details-marker]:hidden", ("btn-sm" if small) ], title: I18n.t("helpers.application.more_actions")) do
safe_join([ label, tag.span("▾", class: "text-xs", "aria-hidden": true) ], " ")
end + tag.div(capture(&block), class: "menu")
end
end end
AIRWORTHINESS_COLORS = { "RED" => "red", "LIMITED" => "blue", "ORANGE" => "orange", "GREEN" => "green", "INFO" => "gray" }.freeze AIRWORTHINESS_COLORS = { "RED" => "red", "LIMITED" => "blue", "ORANGE" => "orange", "GREEN" => "green", "INFO" => "gray" }.freeze
def airworthiness_badge(status, large: false) def airworthiness_badge(status, large: false)
tag.span(status.label, class: [ "badge-#{AIRWORTHINESS_COLORS[status.status]}", ("text-sm px-3 py-1" if large) ], tag.span(status.label, class: [ "badge-#{AIRWORTHINESS_COLORS[status.status]}", ("text-sm px-3 py-1" if large) ],
title: Airworthiness::DISCLAIMER) title: Airworthiness.disclaimer)
end
def airworthiness_dot(status)
color = { "RED" => "bg-red-500", "LIMITED" => "bg-sky-500", "ORANGE" => "bg-amber-400", "GREEN" => "bg-emerald-500" }[status.status]
tag.span(class: "inline-block h-3 w-3 rounded-full #{color}", title: status.label)
end end
# Badge class (or text class) for one airworthiness issue. # Badge class (or text class) for one airworthiness issue.
@@ -33,22 +39,18 @@ module ApplicationHelper
{ "RED" => "text-red-700", "LIMITED" => "text-sky-700", "INFO" => "text-slate-600" }.fetch(issue.severity, "text-amber-700") { "RED" => "text-red-700", "LIMITED" => "text-sky-700", "INFO" => "text-slate-600" }.fetch(issue.severity, "text-amber-700")
end end
COMPLIANCE_BADGES = { COMPLIANCE_COLORS = { "compliant" => "green", "due_soon" => "orange", "overdue" => "red", "no_compliance" => "red",
"compliant" => [ "green", "Compliant" ], "due_soon" => [ "orange", "Due Soon" ], "never_completed" => "red", "conditional" => "gray", "not_applicable" => "gray" }.freeze
"overdue" => [ "red", "Overdue" ], "no_compliance" => [ "red", "No Record" ],
"never_completed" => [ "red", "Never Completed" ], "conditional" => [ "gray", "Conditional" ],
"not_applicable" => [ "gray", "N/A" ]
}.freeze
def compliance_badge(status) def compliance_badge(status)
color, text = COMPLIANCE_BADGES.fetch(status, [ "gray", status.to_s.humanize ]) color = COMPLIANCE_COLORS.fetch(status, "gray")
tag.span(text, class: "badge-#{color}") tag.span(t(status, scope: "helpers.application.compliance", default: status.to_s.humanize), class: "badge-#{color}")
end end
def life_badge(status) def life_badge(status)
return "" unless status return "" unless status
color, text = { overdue: [ "red", "Overdue" ], due_soon: [ "orange", "Due Soon" ], ok: [ "green", "OK" ] }[status] color = { overdue: "red", due_soon: "orange", ok: "green" }[status]
tag.span(text, class: "badge-#{color}") tag.span(t(status, scope: "helpers.application.life"), class: "badge-#{color}")
end end
def squawk_priority_badge(squawk) def squawk_priority_badge(squawk)
@@ -72,7 +74,7 @@ module ApplicationHelper
link_to ad.name, link[0], class: "link", target: "_blank", rel: "noopener noreferrer", title: link[1] link_to ad.name, link[0], class: "link", target: "_blank", rel: "noopener noreferrer", title: link[1]
end end
def delete_button(label, path, confirm: "Are you sure?", **opts) def delete_button(label, path, confirm: I18n.t("helpers.application.are_you_sure"), **opts)
button_to label, path, method: :delete, form: { data: { turbo_confirm: confirm }, class: "inline" }, button_to label, path, method: :delete, form: { data: { turbo_confirm: confirm }, class: "inline" },
class: opts[:class] || "btn-danger btn-sm" class: opts[:class] || "btn-danger btn-sm"
end end
+5 -5
View File
@@ -21,11 +21,11 @@ module FlightLogsHelper
[ "CHT", recording.cht_keys, "°F", CYLINDER_COLORS ], [ "CHT", recording.cht_keys, "°F", CYLINDER_COLORS ],
[ "EGT", recording.egt_keys, "°F", CYLINDER_COLORS ], [ "EGT", recording.egt_keys, "°F", CYLINDER_COLORS ],
[ "RPM", [ :rpm ], "rpm" ], [ "RPM", [ :rpm ], "rpm" ],
[ "Manifold pressure", [ :map ], "inHg" ], [ I18n.t("helpers.flight_logs.manifold_pressure"), [ :map ], "inHg" ],
[ "Fuel flow", [ :fuel_flow ], "gph" ], [ I18n.t("helpers.flight_logs.fuel_flow"), [ :fuel_flow ], "gph" ],
[ "Oil temp", [ :oil_t ], "°F" ], [ I18n.t("helpers.flight_logs.oil_temp"), [ :oil_t ], "°F" ],
[ "Oil pressure", [ :oil_p ], "psi" ], [ I18n.t("helpers.flight_logs.oil_pressure"), [ :oil_p ], "psi" ],
[ "Volts", [ :volts ], "V" ] [ I18n.t("helpers.flight_logs.volts"), [ :volts ], "V" ]
].filter_map do |title, keys, unit, colors| ].filter_map do |title, keys, unit, colors|
keys = keys.select { recording.channels.key?(_1) } keys = keys.select { recording.channels.key?(_1) }
{ title: title, keys: keys, unit: unit, colors: colors || [ CHART_COLOR ] } if keys.any? { title: title, keys: keys, unit: unit, colors: colors || [ CHART_COLOR ] } if keys.any?
+11
View File
@@ -7,4 +7,15 @@ module HelpHelper
html = HelpGuide.html(page, title: title, link: (links ? method(:help_page_url_for) : nil)) html = HelpGuide.html(page, title: title, link: (links ? method(:help_page_url_for) : nil))
tag.div(html.html_safe, class: "markdown guide") # rubocop:disable Rails/OutputSafety -- sanitized in HelpGuide tag.div(html.html_safe, class: "markdown guide") # rubocop:disable Rails/OutputSafety -- sanitized in HelpGuide
end end
# A piece of the guide's Markdown (an intro, one release's notes).
def guide_markdown(markdown, class: nil)
html = HelpGuide.render(markdown, link: method(:help_page_url_for))
tag.div(html.html_safe, class: [ "markdown guide", binding.local_variable_get(:class) ]) # rubocop:disable Rails/OutputSafety -- sanitized in HelpGuide
end
# "4 changes · 3 fixes · 2 for administrators"
def release_summary(release)
release.counts.map { |key, count| t("help.changelog.counts.#{key}", count: count) }.join(" · ")
end
end end
+1 -1
View File
@@ -9,7 +9,7 @@ module MarkdownHelper
extension: { strikethrough: true, tagfilter: true, table: true, autolink: true, tasklist: true, header_ids: nil, footnotes: false } extension: { strikethrough: true, tagfilter: true, table: true, autolink: true, tasklist: true, header_ids: nil, footnotes: false }
}.freeze }.freeze
TAGS = %w[p br strong em del a ul ol li blockquote code pre h1 h2 h3 h4 h5 h6 hr table thead tbody tr th td input span].freeze TAGS = %w[p br strong em del a ul ol li blockquote code pre h1 h2 h3 h4 h5 h6 hr table thead tbody tr th td input span].freeze
ATTRIBUTES = %w[href title type checked disabled align class].freeze ATTRIBUTES = %w[href title type checked disabled align].freeze
def markdown(text) def markdown(text)
return "".html_safe if text.blank? return "".html_safe if text.blank?
+2 -2
View File
@@ -10,7 +10,7 @@ module OilAnalysesHelper
def oil_property(analysis, key) def oil_property(analysis, key)
value = analysis.property(key) or return "—" value = analysis.property(key) or return "—"
_, unit = OilAnalysis::PROPERTIES.fetch(key) unit = OilAnalysis::PROPERTY_UNITS.fetch(key)
number = number_with_precision(value, precision: 2, strip_insignificant_zeros: true) number = number_with_precision(value, precision: 2, strip_insignificant_zeros: true)
unit.present? ? "#{number} #{unit}" : number unit.present? ? "#{number} #{unit}" : number
end end
@@ -24,7 +24,7 @@ module OilAnalysesHelper
value = analysis.value(element) value = analysis.value(element)
flagged = analysis.flagged?(element) flagged = analysis.flagged?(element)
content = tag.span(ppm(value), class: [ "tabular-nums", ("font-semibold text-red-700" if flagged) ], content = tag.span(ppm(value), class: [ "tabular-nums", ("font-semibold text-red-700" if flagged) ],
title: ("Over #{OilAnalysis::FLAG_RATIO}× the lab average" if flagged)) title: (I18n.t("helpers.oil_analyses.over_the_lab_average", ratio: OilAnalysis::FLAG_RATIO) if flagged))
avg = analysis.average(element) avg = analysis.average(element)
avg ? safe_join([ content, tag.div("(#{ppm(avg)})", class: "text-xs text-slate-500 tabular-nums") ]) : content avg ? safe_join([ content, tag.div("(#{ppm(avg)})", class: "text-xs text-slate-500 tabular-nums") ]) : content
end end
+37 -1
View File
@@ -20,11 +20,37 @@ styleCharts()
document.addEventListener("turbo:load", restyleCharts) document.addEventListener("turbo:load", restyleCharts)
window.addEventListener("theme:change", restyleCharts) window.addEventListener("theme:change", restyleCharts)
// Installable app (PWA): the service worker adds an offline page and caches static assets. // Installable app (PWA): the service worker keeps an offline page, forms and
// pre-flight pages, sends saved items in the background and shows notifications.
if ("serviceWorker" in navigator) { if ("serviceWorker" in navigator) {
// A new release's worker takes over open pages: offer a reload (not on the first install).
const hadWorker = !!navigator.serviceWorker.controller
navigator.serviceWorker.addEventListener("controllerchange", () => {
if (hadWorker) document.dispatchEvent(new CustomEvent("app:updated"))
})
// The worker sent saved items in the background: refresh the counts.
navigator.serviceWorker.addEventListener("message", (event) => {
if (event.data?.type === "queue-changed") document.dispatchEvent(new CustomEvent("offline-queue:changed"))
})
window.addEventListener("load", () => navigator.serviceWorker.register("/service-worker.js", { scope: "/" }).catch(() => {})) window.addEventListener("load", () => navigator.serviceWorker.register("/service-worker.js", { scope: "/" }).catch(() => {}))
} }
// Chrome and Android offer to install the app; keep the offer for the button on the profile page.
window.addEventListener("beforeinstallprompt", (event) => {
event.preventDefault()
window.samInstallPrompt = event
document.dispatchEvent(new CustomEvent("install:available"))
})
// The device's time zone, so times show in it and "today" is the local date
// (unless a zone is chosen in Profile).
try {
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone
if (zone && !document.cookie.split("; ").includes(`tz=${encodeURIComponent(zone)}`)) {
document.cookie = `tz=${encodeURIComponent(zone)}; path=/; max-age=31536000; samesite=lax`
}
} catch (_) { /* no Intl */ }
// Label each table cell with its column header, so phone CSS can show rows as // Label each table cell with its column header, so phone CSS can show rows as
// cards ("Status: In Service"). Skips tables marked .table-keep. // cards ("Status: In Service"). Skips tables marked .table-keep.
function labelTableCells(root = document) { function labelTableCells(root = document) {
@@ -51,8 +77,18 @@ document.addEventListener("click", (event) => {
if (target.matches("[data-check-all]")) { if (target.matches("[data-check-all]")) {
target.closest("table")?.querySelectorAll("tbody input[type=checkbox]").forEach((box) => { box.checked = target.checked }) target.closest("table")?.querySelectorAll("tbody input[type=checkbox]").forEach((box) => { box.checked = target.checked })
} }
if (target.type === "checkbox") showSelectionActions()
}) })
// Actions on ticked rows (e.g. "Print selected") appear once a row is ticked:
// data-needs-selection names the form the row checkboxes belong to.
function showSelectionActions() {
document.querySelectorAll("[data-needs-selection]").forEach((el) => {
el.hidden = !document.querySelector(`input[form="${el.dataset.needsSelection}"]:checked`)
})
}
document.addEventListener("turbo:load", showSelectionActions)
document.addEventListener("change", (event) => { document.addEventListener("change", (event) => {
if (event.target.matches?.("[data-submit-on-change]")) event.target.form?.requestSubmit() if (event.target.matches?.("[data-submit-on-change]")) event.target.form?.requestSubmit()
}) })
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
// Airport code field with suggestions from the airport database. // Airport code field with suggestions from the airport database.
// <div data-controller="airport-autocomplete" data-airport-autocomplete-url-value="/airports/search?aircraft_id=1"> // <div data-controller="airport-autocomplete" data-airport-autocomplete-url-value="/airports/search?aircraft_id=1">
@@ -108,7 +109,7 @@ export default class extends Controller {
const code = this.inputTarget.value.trim().toUpperCase() const code = this.inputTarget.value.trim().toUpperCase()
const match = this.results.find((a) => a.code === code || (a.aka || []).includes(code)) const match = this.results.find((a) => a.code === code || (a.aka || []).includes(code))
if (match) this.setHint(this.describeAirport(match)) if (match) this.setHint(this.describeAirport(match))
else if (code.length >= 2 && code.length <= 4 && !code.includes(" ")) this.setHint("Not in the airport database", true) else if (code.length >= 2 && code.length <= 4 && !code.includes(" ")) this.setHint(t("airports.not_found"), true)
else this.setHint("") else this.setHint("")
} }
@@ -0,0 +1,15 @@
import { Controller } from "@hotwired/stimulus"
// After a release, offers to reload so this page picks up the new version.
export default class extends Controller {
static targets = [ "banner" ]
connect() {
this.show = () => this.bannerTarget.classList.remove("hidden")
document.addEventListener("app:updated", this.show)
}
disconnect() { document.removeEventListener("app:updated", this.show) }
reload() { location.reload() }
}
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { DirectUpload } from "@rails/activestorage" import { DirectUpload } from "@rails/activestorage"
// Bulk document upload. Picked files (or a whole folder) are listed with an // Bulk document upload. Picked files (or a whole folder) are listed with an
@@ -29,7 +30,7 @@ export default class extends Controller {
add(event) { add(event) {
for (const file of event.target.files) { for (const file of event.target.files) {
const item = { file, path: file.webkitRelativePath || file.name, state: "pending", progress: 0 } const item = { file, path: file.webkitRelativePath || file.name, state: "pending", progress: 0 }
if (file.size > this.maxBytesValue) Object.assign(item, { state: "error", error: `over the ${Math.round(this.maxBytesValue / 1048576)} MB limit` }) if (file.size > this.maxBytesValue) Object.assign(item, { state: "error", error: t("bulk_upload.over_limit", { mb: Math.round(this.maxBytesValue / 1048576) }) })
this.items.push(item) this.items.push(item)
} }
event.target.value = "" event.target.value = ""
@@ -53,7 +54,7 @@ export default class extends Controller {
defaultName(item) { defaultName(item) {
const parts = item.path.split("/") const parts = item.path.split("/")
if (this.groupTarget.checked && parts.length > 1) return parts[parts.length - 2] if (this.groupTarget.checked && parts.length > 1) return parts[parts.length - 2]
return parts[parts.length - 1].replace(/\.[^.]+$/, "").replace(/_/g, " ").replace(/\s+/g, " ").trim() || "Untitled" return parts[parts.length - 1].replace(/\.[^.]+$/, "").replace(/_/g, " ").replace(/\s+/g, " ").trim() || t("bulk_upload.untitled")
} }
render() { render() {
@@ -72,7 +73,7 @@ export default class extends Controller {
name.type = "text" name.type = "text"
name.className = "input" name.className = "input"
name.value = item.name name.value = item.name
name.setAttribute("aria-label", `Document name for ${item.path}`) name.setAttribute("aria-label", t("bulk_upload.name_for", { path: item.path }))
name.disabled = this.uploading name.disabled = this.uploading
name.addEventListener("input", () => { item.name = name.value; item.custom = true; this.updateSummary() }) name.addEventListener("input", () => { item.name = name.value; item.custom = true; this.updateSummary() })
@@ -90,7 +91,7 @@ export default class extends Controller {
remove.type = "button" remove.type = "button"
remove.className = "btn-secondary btn-sm" remove.className = "btn-secondary btn-sm"
remove.textContent = "✕" remove.textContent = "✕"
remove.setAttribute("aria-label", `Remove ${item.path}`) remove.setAttribute("aria-label", t("bulk_upload.remove", { path: item.path }))
remove.disabled = this.uploading remove.disabled = this.uploading
remove.addEventListener("click", () => { this.items.splice(index, 1); this.render() }) remove.addEventListener("click", () => { this.items.splice(index, 1); this.render() })
@@ -109,9 +110,9 @@ export default class extends Controller {
updateSummary() { updateSummary() {
const files = this.items.length const files = this.items.length
const docs = new Set(this.items.map((item) => item.name.trim() || "Untitled")).size const docs = new Set(this.items.map((item) => item.name.trim() || t("bulk_upload.untitled"))).size
this.summaryTarget.textContent = `${files} ${files === 1 ? "file" : "files"} → ${docs} ${docs === 1 ? "document" : "documents"}` this.summaryTarget.textContent = `${files} ${files === 1 ? "file" : "files"} → ${docs} ${docs === 1 ? "document" : "documents"}`
this.submitTarget.textContent = files ? `Upload ${docs} ${docs === 1 ? "document" : "documents"}` : "Upload" this.submitTarget.textContent = files ? t("bulk_upload.upload_count", { count: docs }) : t("bulk_upload.upload")
} }
size(bytes) { size(bytes) {
@@ -124,9 +125,9 @@ export default class extends Controller {
if (this.ready) return if (this.ready) return
event.preventDefault() event.preventDefault()
if (this.uploading) return if (this.uploading) return
if (this.items.length === 0) return this.say("Choose some files to upload.") if (this.items.length === 0) return this.say(t("bulk_upload.choose_files"))
if (this.items.some((item) => item.file.size > this.maxBytesValue)) { if (this.items.some((item) => item.file.size > this.maxBytesValue)) {
return this.say("Remove the files marked in red first.") return this.say(t("bulk_upload.remove_red"))
} }
this.items.forEach((item) => { if (item.state === "error") item.state = "pending" }) this.items.forEach((item) => { if (item.state === "error") item.state = "pending" })
@@ -134,11 +135,11 @@ export default class extends Controller {
const queue = this.items.filter((item) => item.state === "pending") const queue = this.items.filter((item) => item.state === "pending")
const total = queue.length const total = queue.length
let finished = 0 let finished = 0
this.say(`Uploading 0 of ${total}…`) this.say(t("bulk_upload.uploading", { done: 0, total }))
const worker = async () => { const worker = async () => {
for (let item = queue.shift(); item; item = queue.shift()) { for (let item = queue.shift(); item; item = queue.shift()) {
await this.upload(item) await this.upload(item)
this.say(`Uploading ${++finished} of ${total}…`) this.say(t("bulk_upload.uploading", { done: ++finished, total }))
} }
} }
await Promise.all([ worker(), worker(), worker() ]) await Promise.all([ worker(), worker(), worker() ])
@@ -156,7 +157,7 @@ export default class extends Controller {
} }
this.uploading = false this.uploading = false
this.ready = true this.ready = true
this.say("Saving…") this.say(t("bulk_upload.saving"))
// When nothing was left to upload this all ran inside the click's submit // When nothing was left to upload this all ran inside the click's submit
// event, during which the browser ignores requestSubmit, so wait a tick. // event, during which the browser ignores requestSubmit, so wait a tick.
setTimeout(() => this.element.requestSubmit()) setTimeout(() => this.element.requestSubmit())
Loaded 100 of 553 files, more files were not shown because too many files have changed in this diff. Show more