14 Commits
Author SHA1 Message Date
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
100 changed files with 1454 additions and 268 deletions

No files matched your search

+26 -5
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).
@@ -33,6 +49,11 @@ FORCE_SSL=true
# OIDC_AUTO_CREATE_USERS=false # true: create an account at first sign-in # OIDC_AUTO_CREATE_USERS=false # true: create an account at first sign-in
# 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 ----------------------------------------------------
+44
View File
@@ -2,6 +2,50 @@
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.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 ## 2026.11.3
### Installed app ### Installed app
+1 -1
View File
@@ -37,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
+28
View File
@@ -141,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)
@@ -153,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)
@@ -198,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)
@@ -396,6 +409,9 @@ 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)
solid_cache (1.0.10) solid_cache (1.0.10)
@@ -507,6 +523,7 @@ DEPENDENCIES
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
@@ -593,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
@@ -600,6 +625,7 @@ 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
@@ -614,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
@@ -681,6 +708,7 @@ 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
solid_cache (1.0.10) sha256=bc05a2fb3ac78a6f43cbb5946679cf9db67dd30d22939ededc385cb93e120d41 solid_cache (1.0.10) sha256=bc05a2fb3ac78a6f43cbb5946679cf9db67dd30d22939ededc385cb93e120d41
+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>
+13 -6
View File
@@ -10,7 +10,7 @@ The port aims to be **easy to host**. It runs as one process with one SQLite dat
- 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. - 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,12 +72,16 @@ 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. | | `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`. | | `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`). |
+1 -1
View File
@@ -1 +1 @@
2026.11.3 2026.11.5
+6
View File
@@ -184,3 +184,9 @@
.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; }
}
+16 -4
View File
@@ -52,10 +52,9 @@ class AircraftController < ApplicationController
# 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: t("flash.aircraft.hours_updated", delta: "#{'+' if 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
@@ -64,6 +63,19 @@ class AircraftController < ApplicationController
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
@@ -8,7 +8,7 @@ class AircraftImportsController < ApplicationController
def create def create
file = params[:archive] file = params[:archive]
return redirect_to(new_aircraft_import_path, alert: t("flash.aircraft_imports.choose_a_sam_zip")) 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
+35
View File
@@ -1,9 +1,11 @@
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
prepend_before_action :redirect_to_setup prepend_before_action :redirect_to_setup
prepend_before_action :reject_null_bytes
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,8 +16,41 @@ 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
# No form sends a null byte; some libraries (password hashing, file paths)
# raise on one, so refuse the request up front.
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
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.
+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
View File
@@ -14,6 +14,7 @@ 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
+13 -2
View File
@@ -49,7 +49,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
@@ -62,7 +68,12 @@ class FlightLogsController < ApplicationController
@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: t("flash.flight_logs.flight_logged_hrs", tach_time: @flight_log.tach_time) 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
@@ -18,7 +18,7 @@ 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", t("flash.logbook_entries.transcribed_logbook_entry_verified", date: @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 ? t("flash.logbook_entries.verified_next") : t("flash.logbook_entries.verified_all") notice: next_entry ? t("flash.logbook_entries.verified_next") : t("flash.logbook_entries.verified_all")
@@ -36,7 +36,7 @@ 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", t(@entry.supersedes ? "flash.logbook_entries.correction_added_event" : "flash.logbook_entries.logbook_entry_added", date: @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),
@@ -52,7 +52,7 @@ 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", t("flash.logbook_entries.logbook_entry_updated_2", date: @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: t("flash.logbook_entries.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
@@ -61,7 +61,7 @@ class LogbookEntriesController < ApplicationController
def destroy def destroy
@entry.destroy! @entry.destroy!
log_event("logbook", t("flash.logbook_entries.logbook_entry_deleted_2", date: @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: t("flash.logbook_entries.logbook_entry_deleted") redirect_to aircraft_logbook_entries_path(@aircraft), notice: t("flash.logbook_entries.logbook_entry_deleted")
end end
@@ -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", t(p["service"] == "replaced" ? "flash.logbook_entries.replaced_event" : "flash.logbook_entries.serviced_event", component: component, date: @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", t("flash.logbook_entries.inspection_completed_logbook_entry", name: type.name, date: @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
@@ -10,7 +10,7 @@ class LogbookImportsController < ApplicationController
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: t("flash.logbook_imports.choose_the_scanned_pages")) 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").
+4 -4
View File
@@ -24,7 +24,7 @@ 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", t("flash.oil_analyses.oil_analysis_added_sampled", sample_date: @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: t("flash.oil_analyses.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
@@ -35,7 +35,7 @@ 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: t("flash.oil_analyses.choose_a_lab_report")) 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
@@ -69,7 +69,7 @@ class OilAnalysesController < ApplicationController
def update def update
if @analysis.update(analysis_params) if @analysis.update(analysis_params)
log_event("oil_analysis", t("flash.oil_analyses.oil_analysis_updated_sampled", sample_date: @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: t("flash.oil_analyses.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
@@ -78,7 +78,7 @@ class OilAnalysesController < ApplicationController
def destroy def destroy
@analysis.destroy! @analysis.destroy!
log_event("oil_analysis", t("flash.oil_analyses.oil_analysis_deleted_sampled", sample_date: @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: t("flash.oil_analyses.oil_analysis_deleted") redirect_to aircraft_oil_analyses_path(@aircraft), notice: t("flash.oil_analyses.oil_analysis_deleted")
end end
+1 -1
View File
@@ -7,7 +7,7 @@ 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)
@@ -6,7 +6,13 @@ class PushSubscriptionsController < ApplicationController
record = PushSubscription.find_or_initialize_by(endpoint: sub[:endpoint].to_s) 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), 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)) user_agent: request.user_agent.to_s.first(250))
record.save ? head(:created) : head(:unprocessable_entity) 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 end
def destroy def destroy
@@ -14,9 +20,35 @@ class PushSubscriptionsController < ApplicationController
head :no_content head :no_content
end end
# A notification to this user's devices, to check they arrive. # 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 def test
PushNotifier.notify(current_user, :test, path: edit_profile_path, tag: "test") message = PushNotificationJob.message("test", edit_profile_path, "test")
head :accepted 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
end end
+8
View File
@@ -1,16 +1,24 @@
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: t("flash.setup.welcome_you_re_the") redirect_to root_path, notice: t("flash.setup.welcome_you_re_the")
else else
@@ -21,7 +21,7 @@ class SigningInvitationsController < ApplicationController
PushNotifier.notify(invitee, :signing_request, path: invited_signing_path(@invitation.token), tag: "sign-#{@invitation.id}", PushNotifier.notify(invitee, :signing_request, path: invited_signing_path(@invitation.token), tag: "sign-#{@invitation.id}",
tail: @aircraft.tail_number, name: current_user.display_name) tail: @aircraft.tail_number, name: current_user.display_name)
end end
log_event("logbook", t("flash.signing_invitations.signature_requested_from_entry", email: @invitation.email, date: @entry.date)) log_event("logbook", t("flash.signing_invitations.signature_requested_from_entry", email: @invitation.email, date: l(@entry.date, format: :app)))
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: t("flash.signing_invitations.invitation_sent_to_the", email: @invitation.email, days: SigningInvitation::VALID_FOR.in_days.to_i) redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: t("flash.signing_invitations.invitation_sent_to_the", email: @invitation.email, days: SigningInvitation::VALID_FOR.in_days.to_i)
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
+1 -1
View File
@@ -64,7 +64,7 @@ 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", t("flash.squawks.logbook_entry_added", date: @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
@@ -30,7 +30,7 @@ class WeightBalanceRecordsController < ApplicationController
def update def update
if @record.update(record_params) if @record.update(record_params)
log_event("aircraft", t("flash.weight_balance_records.weight_balance_updated_2", date: @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: t("flash.weight_balance_records.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
@@ -39,7 +39,7 @@ class WeightBalanceRecordsController < ApplicationController
def destroy def destroy
@record.destroy! @record.destroy!
log_event("aircraft", t("flash.weight_balance_records.weight_balance_record_deleted", date: @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: t("flash.weight_balance_records.record_deleted") redirect_to aircraft_weight_balance_records_path(@aircraft), notice: t("flash.weight_balance_records.record_deleted")
end end
+14 -3
View File
@@ -3,12 +3,12 @@ module AircraftHelper
# What the app saves ahead of time for use without signal (see # 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, # offline_prep_controller.js): for each of your aircraft, the Overview, W&B,
# Log Flight and Report Squawk pages, and its photo. # Log Flight and Report Squawk pages, and its photo (at both page sizes).
def offline_pages def offline_pages
current_user.accessible_aircraft.ordered.limit(OFFLINE_AIRCRAFT).map do |a| current_user.accessible_aircraft.ordered.limit(OFFLINE_AIRCRAFT).map do |a|
{ tail: a.tail_number, pages: [ aircraft_path(a), aircraft_weight_balance_records_path(a) ], { tail: a.tail_number, pages: [ aircraft_path(a), aircraft_weight_balance_records_path(a) ],
flight: new_aircraft_flight_log_path(a), squawk: new_aircraft_squawk_path(a), flight: new_aircraft_flight_log_path(a), squawk: new_aircraft_squawk_path(a),
picture: (url_for(a.picture) if a.picture.attached?) }.compact pictures: (%i[thumb card].map { url_for(a.picture_for(_1)) }.uniq if a.picture_shown?) }.compact
end end
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]
@@ -30,6 +30,17 @@ module AircraftHelper
] ]
end end
# 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
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 ? [ [ I18n.t("helpers.aircraft.none"), nil ] ] + opts : opts include_blank ? [ [ I18n.t("helpers.aircraft.none"), nil ] ] + opts : opts
@@ -40,6 +51,6 @@ module AircraftHelper
end end
def logbook_options(aircraft) def logbook_options(aircraft)
[ [ I18n.t("helpers.aircraft.none"), nil ] ] + aircraft.logbook_entries.recent_first.limit(300).map { [ I18n.t("helpers.aircraft.text", date: _1.date, truncate: (_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
+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?
+9
View File
@@ -42,6 +42,15 @@ window.addEventListener("beforeinstallprompt", (event) => {
document.dispatchEvent(new CustomEvent("install:available")) 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) {
@@ -0,0 +1,15 @@
import { Controller } from "@hotwired/stimulus"
// A card that can be hidden for good on this device (e.g. the setup checklist).
export default class extends Controller {
static values = { key: String }
connect() {
try { if (localStorage.getItem(this.keyValue)) this.element.hidden = true } catch (_) { /* storage off */ }
}
hide() {
try { localStorage.setItem(this.keyValue, "1") } catch (_) { /* storage off */ }
this.element.hidden = true
}
}
@@ -13,7 +13,10 @@ export default class extends Controller {
if (this.textTarget.value.trim() && !confirm(t("entry_template.confirm"))) return if (this.textTarget.value.trim() && !confirm(t("entry_template.confirm"))) return
const { text, entryType, logType, certificate } = option.dataset const { text, entryType, logType, certificate } = option.dataset
this.textTarget.value = text this.textTarget.value = text
if (entryType && this.hasEntryTypeTarget) this.entryTypeTarget.value = entryType if (entryType && this.hasEntryTypeTarget) {
this.entryTypeTarget.value = entryType
this.entryTypeTarget.dispatchEvent(new Event("change", { bubbles: true }))
}
if (logType && this.hasLogTypeTarget && this.logTypeTarget.value !== logType) { if (logType && this.hasLogTypeTarget && this.logTypeTarget.value !== logType) {
this.logTypeTarget.value = logType this.logTypeTarget.value = logType
this.logTypeTarget.dispatchEvent(new Event("change", { bubbles: true })) this.logTypeTarget.dispatchEvent(new Event("change", { bubbles: true }))
@@ -0,0 +1,30 @@
import { Controller } from "@hotwired/stimulus"
import { t, locale } from "i18n"
// Update Hours (Overview): confirms the new meter readings first, since they
// change every in-service component's hours and log no flight.
export default class extends Controller {
static targets = [ "tach", "hobbs" ]
static values = { tach: Number, hobbs: Number }
confirm(event) {
const lines = [ this.line("tach", this.tachValue, this.tachTarget.value),
this.hasHobbsTarget ? this.line("hobbs", this.hobbsValue, this.hobbsTarget.value) : null ].filter(Boolean)
if (!lines.length) {
event.preventDefault()
return alert(t("hours.no_change"))
}
const lower = parseFloat(this.tachTarget.value) < this.tachValue
const message = [ ...lines, "", t("hours.effect"), lower ? t("hours.lower") : null ].filter((l) => l !== null).join("\n")
if (!confirm(message)) event.preventDefault()
}
// "Tach 4,211.6 → 4,213.0 (+1.4)", or null when unchanged or blank.
line(meter, now, entered) {
const value = parseFloat(entered)
if (Number.isNaN(value) || Math.abs(value - now) < 0.05) return null
const fmt = (n) => n.toLocaleString(locale(), { minimumFractionDigits: 1, maximumFractionDigits: 1 })
const delta = value - now
return t(`hours.${meter}`, { from: fmt(now), to: fmt(value), delta: `${delta > 0 ? "+" : "−"}${fmt(Math.abs(delta))}` })
}
}
@@ -0,0 +1,13 @@
import { Controller } from "@hotwired/stimulus"
// A new document's name, when left blank, comes from its first file's name
// ("annual-2026_scan.pdf" → "annual 2026 scan").
export default class extends Controller {
static targets = [ "name", "file" ]
fill() {
const file = this.fileTarget.files[0]
if (!file || this.nameTarget.value.trim()) return
this.nameTarget.value = file.name.replace(/\.[^.]+$/, "").replace(/[_-]+/g, " ").replace(/\s+/g, " ").trim()
}
}
@@ -36,7 +36,7 @@ export default class extends Controller {
await new Promise((resolve) => (window.requestIdleCallback || setTimeout)(resolve, { timeout: 2000 })) await new Promise((resolve) => (window.requestIdleCallback || setTimeout)(resolve, { timeout: 2000 }))
try { await fetch(path, { credentials: "same-origin", headers: { Accept: "text/html" } }) } catch (_) { return } try { await fetch(path, { credentials: "same-origin", headers: { Accept: "text/html" } }) } catch (_) { return }
} }
await this.savePictures(this.aircraftValue.map((a) => a.picture).filter(Boolean)) await this.savePictures(this.aircraftValue.flatMap((a) => a.pictures || []))
try { try {
localStorage.setItem("sam-offline-forms", JSON.stringify({ ...JSON.parse(localStorage.getItem("sam-offline-forms") || "{}"), ...forms })) localStorage.setItem("sam-offline-forms", JSON.stringify({ ...JSON.parse(localStorage.getItem("sam-offline-forms") || "{}"), ...forms }))
localStorage.setItem("sam-offline-prep", JSON.stringify({ signature, at: Date.now() })) localStorage.setItem("sam-offline-prep", JSON.stringify({ signature, at: Date.now() }))
@@ -58,10 +58,11 @@ export default class extends Controller {
} }
// Photo links carry an expiry, so they change with every page; the saved copy // Photo links carry an expiry, so they change with every page; the saved copy
// is filed under the upload's id instead (same rule in service-worker.js). // is filed under the upload's id (and size) instead (same rule in service-worker.js).
function imageKey(url) { function imageKey(url) {
try { try {
const signed = new URL(url, location.origin).pathname.match(/\/blobs\/redirect\/([^/]+?)--/)[1] const [ , signed, size ] = new URL(url, location.origin).pathname.match(/\/(?:blobs|representations)\/redirect\/([^/]+?)--[^/]+\/(?:([^/]+)\/)?/)
return `${location.origin}/offline-image/${JSON.parse(atob(decodeURIComponent(signed)))._rails.data}` const id = JSON.parse(atob(decodeURIComponent(signed)))._rails.data
return `${location.origin}/offline-image/${id}${size ? `/${size}` : ""}`
} catch (_) { return null } } catch (_) { return null }
} }
+33 -8
View File
@@ -14,18 +14,34 @@ export default class extends Controller {
this.registration = await navigator.serviceWorker.ready this.registration = await navigator.serviceWorker.ready
const subscription = await this.registration.pushManager.getSubscription() const subscription = await this.registration.pushManager.getSubscription()
if (Notification.permission === "denied") return this.show(t("push.blocked"), null) if (Notification.permission === "denied") return this.show(t("push.blocked"), null)
this.show(t(subscription ? "push.on" : "push.off"), !!subscription) if (!subscription) return this.show(t("push.off"), false)
// The browser keeps its subscription even if the app never recorded it
// (or forgot it), so record it again on every visit.
const error = await this.save(subscription)
this.show(error ? t("push.not_saved", { reason: error }) : t("push.on"), true)
} }
async turnOn() { async turnOn() {
if (await Notification.requestPermission() !== "granted") return this.show(t("push.blocked"), null) if (await Notification.requestPermission() !== "granted") return this.show(t("push.blocked"), null)
let subscription
try {
subscription = await this.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: this.keyBytes() })
} catch (e) {
return this.show(t("push.failed", { reason: e.message || e.name }), false)
}
const error = await this.save(subscription)
this.show(error ? t("push.failed", { reason: error }) : t("push.on"), !error)
if (error) await subscription.unsubscribe()
}
// Records the subscription with the app: null, or why it couldn't.
async save(subscription) {
try { try {
const subscription = await this.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: this.keyBytes() })
const response = await this.request("POST", this.urlValue, { subscription: subscription.toJSON() }) const response = await this.request("POST", this.urlValue, { subscription: subscription.toJSON() })
if (!response.ok) throw new Error(response.status) if (response.ok) return null
this.show(t("push.on"), true) return (await response.json().catch(() => ({}))).error || `HTTP ${response.status}`
} catch (_) { } catch (e) {
this.show(t("push.failed"), false) return e.message
} }
} }
@@ -38,9 +54,18 @@ export default class extends Controller {
this.show(t("push.off"), false) this.show(t("push.off"), false)
} }
// Sends one to each of your devices and lists which push services took it.
async sendTest() { async sendTest() {
await this.request("POST", this.testUrlValue, {}) this.statusTarget.textContent = t("push.test_sending")
this.statusTarget.textContent = t("push.test_sent") try {
const { devices } = await (await this.request("POST", this.testUrlValue, {})).json()
const lines = devices.length
? [ ...devices.map((d) => d.error ? t("push.test_failed", { device: d.device, reason: d.error }) : t("push.test_ok", { device: d.device })), t("push.test_hint") ]
: [ t("push.test_none") ]
this.statusTarget.textContent = lines.join("\n")
} catch (e) {
this.statusTarget.textContent = t("push.failed", { reason: e.message })
}
} }
// on: true / false, or null when it can't be changed here. // on: true / false, or null when it can't be changed here.
@@ -0,0 +1,20 @@
import { Controller } from "@hotwired/stimulus"
// Shows parts of a form only when a select has a given value, e.g. the
// inspection result only for inspection entries. A part hidden by changing
// the select is cleared, so it isn't saved.
// <select data-show-when-target="source" data-action="show-when#update">
// <div data-show-when-target="item" data-show-when-value="INSPECTION">
export default class extends Controller {
static targets = [ "source", "item" ]
connect() { this.update() }
update(event) {
for (const item of this.itemTargets) {
const show = item.dataset.showWhenValue.split(" ").includes(this.sourceTarget.value)
if (event && !show && !item.hidden) item.querySelectorAll("select, input:not([type=hidden]), textarea").forEach((el) => { el.value = "" })
item.hidden = !show
}
}
}
+2 -2
View File
@@ -112,7 +112,7 @@ class LogbookTranscriptionJob < ApplicationJob
text = entry["text"].to_s.strip.presence || I18n.t("jobs.logbook_transcription.no_text") text = entry["text"].to_s.strip.presence || I18n.t("jobs.logbook_transcription.no_text")
unless date unless date
text = "#{I18n.t('jobs.logbook_transcription.date_unreadable')} #{text}" text = "#{I18n.t('jobs.logbook_transcription.date_unreadable')} #{text}"
warn(@last_date ? I18n.t("jobs.logbook_transcription.no_date_previous", page: page_number, date: @last_date) warn(@last_date ? I18n.t("jobs.logbook_transcription.no_date_previous", page: page_number, date: I18n.l(@last_date, format: :app))
: I18n.t("jobs.logbook_transcription.no_date_today", page: page_number)) : I18n.t("jobs.logbook_transcription.no_date_today", page: page_number))
end end
date ||= @last_date || Date.current date ||= @last_date || Date.current
@@ -129,7 +129,7 @@ class LogbookTranscriptionJob < ApplicationJob
verified: false, transcription_confidence: (entry["confidence"] if %w[high medium low].include?(entry["confidence"])) verified: false, transcription_confidence: (entry["confidence"] if %w[high medium low].include?(entry["confidence"]))
) )
@import.increment!(:entries_created) @import.increment!(:entries_created)
warn(I18n.t("jobs.logbook_transcription.hard_to_read", date: date, page: page_number)) if entry["confidence"] == "low" warn(I18n.t("jobs.logbook_transcription.hard_to_read", date: I18n.l(date, format: :app), page: page_number)) if entry["confidence"] == "low"
end end
def note_skipped(result, label) def note_skipped(result, label)
+19 -7
View File
@@ -4,20 +4,32 @@ class PushNotificationJob < ApplicationJob
queue_as :default queue_as :default
def perform(user_ids, key, path, tag, vars) def perform(user_ids, key, path, tag, vars)
vars = vars.symbolize_keys message = self.class.message(key, path, tag, vars)
message = JSON.generate(title: I18n.t("push.#{key}.title", **vars), body: I18n.t("push.#{key}.body", **vars), path: path, tag: tag) PushSubscription.where(user_id: user_ids).find_each { self.class.deliver(_1, message) }
PushSubscription.where(user_id: user_ids).find_each { deliver(_1, message) }
end end
private def self.message(key, path, tag, vars = {})
vars = vars.symbolize_keys
JSON.generate(title: I18n.t("push.#{key}.title", **vars), body: I18n.t("push.#{key}.body", **vars), path: path, tag: tag)
end
def deliver(subscription, message) # Sends to one device: nil when the push service took it, else why not.
def self.deliver(subscription, message)
WebPush.payload_send(message: message, endpoint: subscription.endpoint, p256dh: subscription.p256dh, auth: subscription.auth, WebPush.payload_send(message: message, endpoint: subscription.endpoint, p256dh: subscription.p256dh, auth: subscription.auth,
ttl: 1.day.to_i, urgency: "high", ttl: 1.day.to_i, urgency: "high",
vapid: { subject: PushKeys.subject, public_key: PushKeys.public_key, private_key: PushKeys.private_key }) vapid: { subject: PushKeys.subject, public_key: PushKeys.public_key, private_key: PushKeys.private_key })
rescue WebPush::ExpiredSubscription, WebPush::InvalidSubscription, WebPush::Unauthorized nil
rescue WebPush::ExpiredSubscription, WebPush::InvalidSubscription, WebPush::Unauthorized => e
subscription.destroy subscription.destroy
failure(subscription, e)
rescue WebPush::Error, SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError => e rescue WebPush::Error, SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError => e
Rails.logger.warn("[push] #{subscription.endpoint.truncate(60)}: #{e.class}: #{e.message.truncate(200)}") failure(subscription, e)
end end
def self.failure(subscription, error)
reason = "#{error.class.name.demodulize}: #{error.message.truncate(200)}"
Rails.logger.warn("[push] #{subscription.endpoint.truncate(60)}: #{reason}")
reason
end
private_class_method :failure
end end
+6
View File
@@ -25,6 +25,12 @@ class ReminderMailer < ApplicationMailer
end end
def weekly(user) def weekly(user)
Time.use_zone(user.time_zone.presence || Time.zone_default) { weekly_in_zone(user) }
end
private
def weekly_in_zone(user)
@user = user @user = user
@items = self.class.items_for(user) @items = self.class.items_for(user)
@certificates = self.class.expiring_certificates_for(user) @certificates = self.class.expiring_certificates_for(user)
+1 -1
View File
@@ -20,7 +20,7 @@ class AirTrailConnection < ApplicationRecord
scope :active, -> { where(enabled: true) } scope :active, -> { where(enabled: true) }
def client = AirTrailClient.new(base_url: base_url, api_key: api_key) def client = AirTrailClient.new(base_url: base_url, api_key: api_key, allow_private: user&.admin?)
def ok? = status == "ok" def ok? = status == "ok"
+18 -2
View File
@@ -1,7 +1,12 @@
class Aircraft < ApplicationRecord class Aircraft < ApplicationRecord
STATUSES = LabelSet.new("aircraft.statuses", %w[AVAILABLE MX GROUND UNAVAILABLE]) STATUSES = LabelSet.new("aircraft.statuses", %w[AVAILABLE MX GROUND UNAVAILABLE])
has_one_attached :picture # Small copies of the photo for the pages (the original can be several MB):
# made when it's uploaded; see #picture_for.
has_one_attached :picture do |picture|
picture.variant :thumb, resize_to_fill: [ 192, 192 ], preprocessed: true
picture.variant :card, resize_to_fill: [ 960, 432 ], preprocessed: true
end
has_many :roles, class_name: "AircraftRole", dependent: :destroy has_many :roles, class_name: "AircraftRole", dependent: :destroy
has_many :users, through: :roles has_many :users, through: :roles
@@ -77,10 +82,21 @@ class Aircraft < ApplicationRecord
events.create!(category: category, event_name: event_name, user: user, notes: notes) events.create!(category: category, event_name: event_name, user: user, notes: notes)
end end
# A saved photo to show (not one just rejected by validation, which has no
# address yet).
def picture_shown? = picture.attached? && picture.attachment.persisted?
# The photo at a page's size (:thumb or :card), or the original when it
# isn't a kind that can be resized. (One that can't be read is sent as the
# original too: see config/initializers/active_storage_images.rb.)
def picture_for(size)
picture.variable? ? picture.variant(size) : picture
end
private private
def picture_is_image def picture_is_image
if picture.attached? && !picture.content_type.to_s.start_with?("image/") if picture.attached? && (!picture.content_type.to_s.start_with?("image/") || picture.blob.byte_size.zero?)
errors.add(:picture, :not_image) errors.add(:picture, :not_image)
end end
end end
+25
View File
@@ -1,3 +1,28 @@
class ApplicationRecord < ActiveRecord::Base class ApplicationRecord < ActiveRecord::Base
primary_abstract_class primary_abstract_class
before_validation :default_blank_required_columns
validate :optional_references_exist
private
# A blank form field arrives as nil; for a column that can't be empty and has
# a default (a checkbox, a count, a position), use the default rather than
# failing in the database.
def default_blank_required_columns
self.class.columns.each do |column|
next if column.null || column.default.nil? || !self[column.name].nil?
self[column.name] = self.class.type_for_attribute(column.name).cast(column.default)
end
end
# An optional link (a parent part, a collection…) given an id that doesn't
# exist is a mistake in the form, not something to store.
def optional_references_exist
self.class.reflect_on_all_associations(:belongs_to).each do |assoc|
next if assoc.polymorphic? || !assoc.options[:optional]
next if self[assoc.foreign_key].blank? || !attribute_changed?(assoc.foreign_key)
errors.add(assoc.name, :invalid) unless public_send(assoc.name)
end
end
end end
+15 -4
View File
@@ -44,13 +44,23 @@ class Component < ApplicationRecord
OVERHAUL_ABBREVIATIONS.fetch(overhaul_kind) { engine? || propeller? ? "TSO" : I18n.t("models.component.since_service") } OVERHAUL_ABBREVIATIONS.fetch(overhaul_kind) { engine? || propeller? ? "TSO" : I18n.t("models.component.since_service") }
end end
# Its sub-components, and theirs. # Its sub-components, and theirs. (Stops at a loop, should one exist.)
def descendant_ids def descendant_ids(seen = Set[id])
child_components.flat_map { [ _1.id, *_1.descendant_ids ] } child_components.flat_map do |child|
next [] unless seen.add?(child.id)
[ child.id, *child.descendant_ids(seen) ]
end
end end
# Its parent, the parent's parent, and so on up.
def ancestor_ids def ancestor_ids
parent_component ? [ parent_component_id, *parent_component.ancestor_ids ] : [] ids = []
node = self
while (parent_id = node.parent_component_id) && parent_id != id && !ids.include?(parent_id)
ids << parent_id
node = Component.find_by(id: parent_id) or break
end
ids
end end
def engine? = component_type&.name.to_s.match?(/engine/i) def engine? = component_type&.name.to_s.match?(/engine/i)
def propeller? = component_type&.name.to_s.match?(/propell?er|\bprop\b/i) def propeller? = component_type&.name.to_s.match?(/propell?er|\bprop\b/i)
@@ -133,6 +143,7 @@ class Component < ApplicationRecord
def parent_on_same_aircraft def parent_on_same_aircraft
return unless parent_component return unless parent_component
errors.add(:parent_component, :itself) if parent_component_id == id && id errors.add(:parent_component, :itself) if parent_component_id == id && id
errors.add(:parent_component, :own_part) if id && parent_component.ancestor_ids.include?(id) # would make a loop
errors.add(:parent_component, :other_aircraft) if parent_component.aircraft_id != aircraft_id errors.add(:parent_component, :other_aircraft) if parent_component.aircraft_id != aircraft_id
end end
end end
+1 -1
View File
@@ -2,7 +2,7 @@
class PushSubscription < ApplicationRecord class PushSubscription < ApplicationRecord
# The browsers' push services. The server posts to the endpoint, so only # The browsers' push services. The server posts to the endpoint, so only
# these hosts are accepted (not, say, an address inside the network). # these hosts are accepted (not, say, an address inside the network).
PUSH_SERVICES = /\A(fcm\.googleapis\.com|updates\.push\.services\.mozilla\.com|([\w-]+\.)*push\.apple\.com|([\w-]+\.)*notify\.windows\.com)\z/ PUSH_SERVICES = /\A(([\w-]+\.)*googleapis\.com|([\w-]+\.)*google\.com|updates\.push\.services\.mozilla\.com|([\w-]+\.)*push\.apple\.com|([\w-]+\.)*notify\.windows\.com)\z/
belongs_to :user belongs_to :user
+27
View File
@@ -0,0 +1,27 @@
# The application secret key signs the sign-in cookie and protects stored
# secrets (two-factor keys, API keys), so anyone who can guess it can sign in
# as anyone. A placeholder or short key stops the app from starting; one
# shorter than what `bin/rails secret` makes is reported by sam:doctor.
module SecretKeyCheck
MIN = 32 # below this, refuse to start
RECOMMENDED = 64 # below this, warn
PLACEHOLDERS = %w[change-me changeme change_me secret password your-secret-key replace-me example].freeze
module_function
# :ok, :weak or :unsafe
def strength(key = ENV["SECRET_KEY_BASE"].to_s)
return :unsafe if PLACEHOLDERS.include?(key.strip.downcase) || key.length < MIN || key.chars.uniq.size < 10
key.length < RECOMMENDED ? :weak : :ok
end
def verify!(key = ENV["SECRET_KEY_BASE"].to_s)
case strength(key)
when :unsafe
abort "SECRET_KEY_BASE is a placeholder or too short (#{key.length} characters). " \
"Set it to the output of `bin/rails secret` (128 random characters) and start again."
when :weak
Rails.logger.warn("[security] SECRET_KEY_BASE is only #{key.length} characters; `bin/rails secret` makes 128.")
end
end
end
+33
View File
@@ -0,0 +1,33 @@
# Until the first account exists, whoever reaches the server could create the
# admin account. The setup page asks for this one-time code, which is only in
# the server's log, so only whoever runs the server can finish setup.
module SetupCode
ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789".chars.freeze # no look-alikes (0/O, 1/I/L)
module_function
# (Each parallel test process has its own.)
def file = Rails.env.test? ? Rails.root.join("tmp", "setup_code-#{Process.pid}") : Rails.root.join("storage", "setup_code")
# The code, made the first time it's needed and kept until setup is done.
def current
return file.read.strip if file.exist?
code = Array.new(8) { ALPHABET[SecureRandom.random_number(ALPHABET.size)] }.join.insert(4, "-")
file.dirname.mkpath
File.write(file, code, perm: 0o600)
code
end
def announce
Rails.logger.warn("Setup code: #{current} (enter it on the setup page to create the admin account)")
end
def matches?(given)
normalize = ->(s) { s.to_s.upcase.gsub(/[^A-Z0-9]/, "") }
ActiveSupport::SecurityUtils.secure_compare(normalize.(given), normalize.(current))
end
def clear
file.delete if file.exist?
end
end
+1 -1
View File
@@ -52,7 +52,7 @@ class SystemInfo
"SQLite" => SQLite3::SQLITE_VERSION, "SQLite" => SQLite3::SQLITE_VERSION,
"Bundler" => Bundler::VERSION, "Bundler" => Bundler::VERSION,
t(:environment) => Rails.env, t(:environment) => Rails.env,
t(:time_zone) => Time.zone.name t(:time_zone) => Time.zone_default.name
} }
end end
+3
View File
@@ -3,6 +3,9 @@ class User < ApplicationRecord
has_many :sessions, dependent: :destroy has_many :sessions, dependent: :destroy
has_many :aircraft_roles, dependent: :destroy has_many :aircraft_roles, dependent: :destroy
has_many :push_subscriptions, dependent: :delete_all has_many :push_subscriptions, dependent: :delete_all
normalizes :time_zone, with: ->(z) { z.strip.presence }
validates :time_zone, inclusion: { in: ->(_) { ActiveSupport::TimeZone.all.map(&:name) } }, allow_nil: true
has_many :aircraft, through: :aircraft_roles has_many :aircraft, through: :aircraft_roles
has_one :air_trail_connection, dependent: :destroy has_one :air_trail_connection, dependent: :destroy
has_many :certificates, -> { ordered }, class_name: "UserCertificate", dependent: :destroy has_many :certificates, -> { ordered }, class_name: "UserCertificate", dependent: :destroy
+37 -4
View File
@@ -16,12 +16,25 @@ class AirTrailClient
class NotFound < Error; end class NotFound < Error; end
class ValidationError < Error; end # 400/422 class ValidationError < Error; end # 400/422
def initialize(base_url:, api_key:, timeout: 20) # An address the server won't send to (see #address). Like a bad key, the
# user has to fix the connection, so it's recorded there and not retried.
class BlockedAddress < AuthError; end
# allow_private: may reach addresses on the private network (admins; and
# hosts listed in AIRTRAIL_ALLOWED_HOSTS for everyone). The server itself
# and link-local addresses (cloud metadata) are never reached.
def initialize(base_url:, api_key:, timeout: 20, allow_private: false)
@base = URI.parse(base_url.to_s.chomp("/")) @base = URI.parse(base_url.to_s.chomp("/"))
@api_key = api_key @api_key = api_key
@timeout = timeout @timeout = timeout
@allow_private = allow_private || self.class.allowed_hosts.include?(@base.host.to_s.downcase)
end end
# Host name → IP addresses (replaceable in tests, which have no DNS).
class_attribute :resolver, default: ->(host) { Addrinfo.getaddrinfo(host, nil, nil, :STREAM).map(&:ip_address) }
def self.allowed_hosts = ENV.fetch("AIRTRAIL_ALLOWED_HOSTS", "").split(",").map { _1.strip.downcase }.compact_blank
def me = request(:get, "/api/v1/me").fetch("data") def me = request(:get, "/api/v1/me").fetch("data")
def search_airports(query) = request(:get, "/api/v1/airports", query: { query: query }).fetch("data") def search_airports(query) = request(:get, "/api/v1/airports", query: { query: query }).fetch("data")
@@ -63,13 +76,33 @@ class AirTrailClient
req.body = JSON.generate(body) req.body = JSON.generate(body)
end end
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", http = Net::HTTP.new(uri.host, uri.port)
open_timeout: @timeout, read_timeout: @timeout) { _1.request(req) } http.ipaddr = address(uri.host) # connect to the address that was checked (the name can't be re-pointed in between)
handle(response) http.use_ssl = uri.scheme == "https"
http.open_timeout = http.read_timeout = @timeout
handle(http.start { _1.request(req) })
rescue Timeout::Error, SocketError, SystemCallError, OpenSSL::SSL::SSLError, EOFError, IOError => e rescue Timeout::Error, SocketError, SystemCallError, OpenSSL::SSL::SSLError, EOFError, IOError => e
raise NetworkError, I18n.t("services.air_trail.can_t_reach_airtrail_at", host: @base.host, message: e.message) raise NetworkError, I18n.t("services.air_trail.can_t_reach_airtrail_at", host: @base.host, message: e.message)
end end
# The address to connect to: the host's first, once all of its addresses are
# ones this connection may reach.
def address(host)
ips = resolver.call(host).map { IPAddr.new(_1.sub(/%.*/, "")) }.uniq
raise SocketError, "no address" if ips.empty?
ips.each do |ip|
ip = ip.native # ::ffff:10.0.0.1 → 10.0.0.1
reason = if ip.loopback? || ip.link_local? || UNREACHABLE.any? { _1.include?(ip) } then :never
elsif (ip.private? || CGNAT.include?(ip)) && !@allow_private then :private
end
raise BlockedAddress, I18n.t("services.air_trail.blocked_#{reason}", host: host) if reason
end
ips.first.to_s
end
UNREACHABLE = [ IPAddr.new("0.0.0.0/8"), IPAddr.new("::/128"), IPAddr.new("224.0.0.0/4"), IPAddr.new("ff00::/8") ].freeze
CGNAT = IPAddr.new("100.64.0.0/10") # shared address space, e.g. Tailscale
def handle(response) def handle(response)
status = response.code.to_i status = response.code.to_i
json = begin json = begin
+6 -6
View File
@@ -95,7 +95,7 @@ class Airworthiness
end end
@aircraft.squawks.deferred.find_each do |squawk| @aircraft.squawks.deferred.find_each do |squawk|
add("DEFERRED", INFO, t(:inoperative, issue: squawk.issue_reported.to_s.truncate(80)), add("DEFERRED", INFO, t(:inoperative, issue: squawk.issue_reported.to_s.truncate(80)),
t(:deferred, date: squawk.deferred_at.to_date, name: squawk.deferred_by_name), squawk) t(:deferred, date: I18n.l(squawk.deferred_at.to_date, format: :app), name: squawk.deferred_by_name), squawk)
end end
end end
@@ -134,9 +134,9 @@ class Airworthiness
grounds = Document::GROUNDING_EXPIRY_TYPES.include?(doc.doc_type) grounds = Document::GROUNDING_EXPIRY_TYPES.include?(doc.doc_type)
if doc.expired?(@today) if doc.expired?(@today)
add("DOCUMENT", grounds ? RED : ORANGE, t(:expired_title, name: doc.name), add("DOCUMENT", grounds ? RED : ORANGE, t(:expired_title, name: doc.name),
t(grounds ? :document_expired_grounds : :document_expired, type: doc.type_label, date: doc.expires_on), doc) t(grounds ? :document_expired_grounds : :document_expired, type: doc.type_label, date: I18n.l(doc.expires_on, format: :app)), doc)
elsif @today + doc.expiry_warning_days >= doc.expires_on elsif @today + doc.expiry_warning_days >= doc.expires_on
add("DOCUMENT", ORANGE, t(:expires_soon_title, name: doc.name), t(:document_expires, type: doc.type_label, date: doc.expires_on), doc) add("DOCUMENT", ORANGE, t(:expires_soon_title, name: doc.name), t(:document_expires, type: doc.type_label, date: I18n.l(doc.expires_on, format: :app)), doc)
end end
end end
end end
@@ -163,7 +163,7 @@ class Airworthiness
if c.replacement_critical? && (due = c.next_replacement_date) if c.replacement_critical? && (due = c.next_replacement_date)
if @today >= due if @today >= due
overdue = true overdue = true
desc = t(c.replacement_from_install? ? :replace_every_installed : :replace_every_serviced, interval: c.replacement_interval_label, date: c.replacement_counted_from) desc = t(c.replacement_from_install? ? :replace_every_installed : :replace_every_serviced, interval: c.replacement_interval_label, date: c.replacement_counted_from && I18n.l(c.replacement_counted_from, format: :app))
elsif @today + DAYS_WARNING >= due elsif @today + DAYS_WARNING >= due
approaching = true approaching = true
desc = t(:replace_in_days, count: (due - @today).to_i) desc = t(:replace_in_days, count: (due - @today).to_i)
@@ -174,11 +174,11 @@ class Airworthiness
if c.expires_on if c.expires_on
if c.expired?(@today) if c.expired?(@today)
expired = true expired = true
desc = t(:component_expired, date: c.expires_on) desc = t(:component_expired, date: I18n.l(c.expires_on, format: :app))
elsif @today + DAYS_WARNING >= c.expires_on elsif @today + DAYS_WARNING >= c.expires_on
approaching = true approaching = true
expiring = true expiring = true
desc = t(:component_expires, date: c.expires_on) desc = t(:component_expires, date: I18n.l(c.expires_on, format: :app))
end end
end end
+1 -1
View File
@@ -33,7 +33,7 @@ class EntrySigner
auth_method: @auth_method, ip_address: @request&.remote_ip, user_agent: @request&.user_agent.to_s.first(255) auth_method: @auth_method, ip_address: @request&.remote_ip, user_agent: @request&.user_agent.to_s.first(255)
) )
@entry.supersedes&.update_column(:superseded_at, signature.signed_at) @entry.supersedes&.update_column(:superseded_at, signature.signed_at)
@entry.aircraft.log_event!("logbook", "Logbook entry signed electronically (#{@entry.date})", @entry.aircraft.log_event!("logbook", I18n.t("services.entry_signer.signed_event", date: I18n.l(@entry.date, format: :app)),
notes: I18n.t("services.entry_signer.text", signer_name: signature.signer_name, certificate_label: signature.certificate_label, certificate_number: signature.certificate_number), user: @user) notes: I18n.t("services.entry_signer.text", signer_name: signature.signer_name, certificate_label: signature.certificate_label, certificate_number: signature.certificate_number), user: @user)
signature signature
end end
+1 -1
View File
@@ -27,7 +27,7 @@ class RecordsAudit
drs_item, drs_item,
Item.new("procedures", t(:procedures), true, Item.new("procedures", t(:procedures), true,
revision.present? && @policy.complete?, revision.present? && @policy.complete?,
revision ? t(:revision, number: revision.number, date: revision.adopted_at.to_date) : t(:not_adopted)), revision ? t(:revision, number: revision.number, date: I18n.l(revision.adopted_at.to_date, format: :app)) : t(:not_adopted)),
Item.new("signatures", t(:signatures), true, Item.new("signatures", t(:signatures), true,
check.present? && check.ok, t(:signed_since, count: signatures_since.count, since: since_label)), check.present? && check.ok, t(:signed_since, count: signatures_since.count, since: since_label)),
Item.new("certificates", t(:certificates), true, true, Item.new("certificates", t(:certificates), true, true,
+1 -1
View File
@@ -23,7 +23,7 @@ class RecordsIntegrity
next if sig.imported? || sig.status != :altered next if sig.imported? || sig.status != :altered
entry = sig.logbook_entry entry = sig.logbook_entry
problems << I18n.t(sig.seal_valid? ? "services.records_integrity.entry_changed" : "services.records_integrity.signature_altered", problems << I18n.t(sig.seal_valid? ? "services.records_integrity.entry_changed" : "services.records_integrity.signature_altered",
tail_number: entry.aircraft.tail_number, date: entry.date, signer: sig.signer_name) tail_number: entry.aircraft.tail_number, date: I18n.l(entry.date, format: :app), signer: sig.signer_name)
end end
AppRevision.touch_current! AppRevision.touch_current!
IntegrityCheck.create!(ok: problems.empty?, versions_checked: versions, signatures_checked: signatures, problems: problems.first(200)) IntegrityCheck.create!(ok: problems.empty?, versions_checked: versions, signatures_checked: signatures, problems: problems.first(200))
+2 -2
View File
@@ -23,11 +23,11 @@ class SiteSearch
return {} unless searchable? return {} unless searchable?
@results ||= { @results ||= {
"logbook" => find(LogbookEntry.where(aircraft_id: @ids).order(date: :desc), %w[text signoff_person signoff_location]) { |e, s| "logbook" => find(LogbookEntry.where(aircraft_id: @ids).order(date: :desc), %w[text signoff_person signoff_location]) { |e, s|
[ I18n.t("services.site_search.logbook", date: e.date, log: LogbookEntry::LOG_TYPES[e.log_type]), s, @urls.aircraft_logbook_entry_path(e.aircraft_id, e) ] }, [ I18n.t("services.site_search.logbook", date: I18n.l(e.date, format: :app), log: LogbookEntry::LOG_TYPES[e.log_type]), s, @urls.aircraft_logbook_entry_path(e.aircraft_id, e) ] },
"squawk" => find(Squawk.where(aircraft_id: @ids).order(created_at: :desc), %w[issue_reported notes deferral_notes]) { |q, s| "squawk" => find(Squawk.where(aircraft_id: @ids).order(created_at: :desc), %w[issue_reported notes deferral_notes]) { |q, s|
[ q.resolved? ? I18n.t("services.site_search.resolved", issue: q.issue_reported.truncate(80)) : q.issue_reported.truncate(80), s, @urls.aircraft_squawks_path(q.aircraft_id) ] }, [ q.resolved? ? I18n.t("services.site_search.resolved", issue: q.issue_reported.truncate(80)) : q.issue_reported.truncate(80), s, @urls.aircraft_squawks_path(q.aircraft_id) ] },
"note" => find(AircraftNote.where(aircraft_id: @ids).order(created_at: :desc), %w[text]) { |n, s| "note" => find(AircraftNote.where(aircraft_id: @ids).order(created_at: :desc), %w[text]) { |n, s|
[ I18n.t("services.site_search.note", date: n.created_at.to_date), s, @urls.aircraft_notes_path(n.aircraft_id) ] }, [ I18n.t("services.site_search.note", date: I18n.l(n.created_at.to_date, format: :app)), s, @urls.aircraft_notes_path(n.aircraft_id) ] },
"ad" => ads, "ad" => ads,
"document" => find(Document.where(aircraft_id: @ids).order(:name), %w[name description pages_text]) { |d, s| "document" => find(Document.where(aircraft_id: @ids).order(:name), %w[name description pages_text]) { |d, s|
[ d.name, s, @urls.aircraft_document_path(d.aircraft_id, d) ] }, [ d.name, s, @urls.aircraft_document_path(d.aircraft_id, d) ] },
+6 -1
View File
@@ -28,7 +28,12 @@ class SystemDoctor
def secret_key def secret_key
return ok("Secret key", "development/test key") unless production? return ok("Secret key", "development/test key") unless production?
ENV["SECRET_KEY_BASE"].present? || ENV["RAILS_MASTER_KEY"].present? ? ok("Secret key", "set (keep a copy off the server)") : warning("Secret key", "SECRET_KEY_BASE isn't set in the environment") return warning("Secret key", "SECRET_KEY_BASE isn't set in the environment") if ENV["SECRET_KEY_BASE"].blank? && ENV["RAILS_MASTER_KEY"].blank?
return ok("Secret key", "set (keep a copy off the server)") if ENV["SECRET_KEY_BASE"].blank?
case SecretKeyCheck.strength
when :ok then ok("Secret key", "set (keep a copy off the server)")
else failed("Secret key", "only #{ENV['SECRET_KEY_BASE'].length} characters: replace it with the output of bin/rails secret")
end
end end
def host def host
+28
View File
@@ -0,0 +1,28 @@
<%# Shown to owners until the aircraft is set up; Hide keeps it hidden on this device. %>
<% steps = setup_steps(aircraft) %>
<% if steps.any? { !_2 } %>
<section class="card" data-controller="dismiss" data-dismiss-key-value="sam-setup-hidden-<%= aircraft.id %>">
<div class="card-header">
<div>
<h2 class="card-title"><%= t(".title", tail_number: aircraft.tail_number) %></h2>
<p class="text-xs text-slate-500"><%= t(".progress", done: steps.count { _2 }, total: steps.size) %></p>
</div>
<button type="button" class="btn-secondary btn-sm" data-action="dismiss#hide"><%= t(".hide") %></button>
</div>
<ol class="divide-y divide-slate-100">
<% steps.each do |key, done, path| %>
<li class="flex items-start gap-3 px-4 py-3">
<span aria-hidden="true" class="<%= done ? "text-emerald-600" : "text-slate-400" %>"><%= done ? "✓" : "○" %></span>
<div class="min-w-0 flex-1 text-sm">
<% if done %>
<span class="text-slate-500 line-through"><%= t(".#{key}.title") %></span>
<% else %>
<%= link_to t(".#{key}.title"), path, class: "link font-medium" %>
<p class="hint"><%= t(".#{key}.why") %></p>
<% end %>
</div>
</li>
<% end %>
</ol>
</section>
<% end %>
+2 -2
View File
@@ -18,8 +18,8 @@
<% aw = aircraft.airworthiness %> <% aw = aircraft.airworthiness %>
<%= link_to aircraft_path(aircraft), class: "card block overflow-hidden transition hover:shadow-md" do %> <%= link_to aircraft_path(aircraft), class: "card block overflow-hidden transition hover:shadow-md" do %>
<div class="flex h-36 items-center justify-center bg-slate-200"> <div class="flex h-36 items-center justify-center bg-slate-200">
<% if aircraft.picture.attached? %> <% if aircraft.picture_shown? %>
<%= image_tag aircraft.picture, class: "h-full w-full object-cover", alt: t(".photo_of", tail_number: aircraft.tail_number) %> <%= image_tag aircraft.picture_for(:card), class: "h-full w-full object-cover", loading: "lazy", alt: t(".photo_of", tail_number: aircraft.tail_number) %>
<% else %> <% else %>
<span class="text-5xl text-slate-400" aria-hidden="true">✈</span> <span class="text-5xl text-slate-400" aria-hidden="true">✈</span>
<% end %> <% end %>
+7 -4
View File
@@ -4,6 +4,7 @@
<div class="grid gap-5 lg:grid-cols-3"> <div class="grid gap-5 lg:grid-cols-3">
<div class="space-y-5 lg:col-span-2"> <div class="space-y-5 lg:col-span-2">
<% if owner? %><%= render "aircraft/setup", aircraft: @aircraft %><% end %>
<section class="card"> <section class="card">
<div class="card-header"> <div class="card-header">
<h2 class="card-title"><%= t(".airworthiness") %></h2> <h2 class="card-title"><%= t(".airworthiness") %></h2>
@@ -59,12 +60,14 @@
<div class="space-y-5"> <div class="space-y-5">
<section class="card"> <section class="card">
<div class="card-header"><h2 class="card-title"><%= t(".update_hours") %></h2></div> <div class="card-header"><h2 class="card-title"><%= t(".update_hours") %></h2></div>
<%= form_with url: hours_aircraft_path(@aircraft), method: :patch, class: "card-body space-y-3" do |f| %> <%= form_with url: hours_aircraft_path(@aircraft), method: :patch, class: "card-body space-y-3",
data: { controller: "hours-confirm", action: "submit->hours-confirm#confirm",
hours_confirm_tach_value: @aircraft.tach_time.to_f, hours_confirm_hobbs_value: @aircraft.hobbs_time.to_f } do |f| %>
<div class="grid grid-cols-2 gap-3"> <div class="grid grid-cols-2 gap-3">
<div><%= f.label :tach_time, t(".tach"), class: "label" %> <div><%= f.label :tach_time, t(".tach"), class: "label" %>
<%= f.number_field :tach_time, value: @aircraft.tach_time, step: 0.1, class: "input", required: true %></div> <%= f.number_field :tach_time, value: @aircraft.tach_time, step: 0.1, class: "input", required: true, data: { hours_confirm_target: "tach" } %></div>
<div><%= f.label :hobbs_time, t(".hobbs"), class: "label" %> <div><%= f.label :hobbs_time, t(".hobbs"), class: "label" %>
<%= f.number_field :hobbs_time, value: @aircraft.hobbs_time, step: 0.1, class: "input" %></div> <%= f.number_field :hobbs_time, value: @aircraft.hobbs_time, step: 0.1, class: "input", data: { hours_confirm_target: "hobbs" } %></div>
</div> </div>
<p class="hint"><%= t(".enter_the_current_meter_readings_html", link: (link_to t(".log_flight"), new_aircraft_flight_log_path(@aircraft), class: "link")) %></p> <p class="hint"><%= t(".enter_the_current_meter_readings_html", link: (link_to t(".log_flight"), new_aircraft_flight_log_path(@aircraft), class: "link")) %></p>
<%= f.submit t(".update_hours"), class: "btn-primary" %> <%= f.submit t(".update_hours"), class: "btn-primary" %>
@@ -85,7 +88,7 @@
<dt class="text-slate-500"><%= t(".hobbs_offset") %></dt><dd><%= hours(@aircraft.hobbs_time_offset) %></dd> <dt class="text-slate-500"><%= t(".hobbs_offset") %></dt><dd><%= hours(@aircraft.hobbs_time_offset) %></dd>
</dl> </dl>
<% if @aircraft.description.present? %> <% if @aircraft.description.present? %>
<p class="border-t border-slate-100 px-4 py-3 text-sm text-slate-600"><%= simple_format @aircraft.description %></p> <div class="space-y-2 border-t border-slate-100 px-4 py-3 text-sm text-slate-600"><%= simple_format @aircraft.description %></div>
<% end %> <% end %>
</section> </section>
+21 -11
View File
@@ -21,12 +21,17 @@
<%= f.field :hours_in_service, as: :number, step: 0.1, label: t(".total_time_hours") %> <%= f.field :hours_in_service, as: :number, step: 0.1, label: t(".total_time_hours") %>
<%= f.field :overhaul_date, as: :date, label: t(".last_overhaul_service") %> <%= f.field :overhaul_date, as: :date, label: t(".last_overhaul_service") %>
<%= f.field :hours_since_overhaul, as: :number, step: 0.1, label: t(".hours_since_oh_service") %> <%= f.field :hours_since_overhaul, as: :number, step: 0.1, label: t(".hours_since_oh_service") %>
<%= f.field :overhaul_kind, as: :select, label: t(".overhaul_type"), include_blank: "—", collection: Component::OVERHAUL_KINDS.invert,
wrapper: { class: "sm:col-span-2" }, hint: t(".for_engines_and_propellers_printed") %>
</fieldset> </fieldset>
<fieldset class="grid gap-4 sm:grid-cols-3"> <%# Limits, in two groups that open when they're in use (most parts need one or neither). %>
<legend class="mb-2 text-sm font-semibold text-slate-900"><%= t(".limits") %></legend> <% c = component %>
<% replacement_open = c.replacement_hours.present? || c.replacement_calendar? || c.replacement_critical? || c.expires_on.present? ||
%i[replacement_hours replacement_every expires_on].any? { c.errors[_1].any? } %>
<% tbo_open = c.tbo_hours.present? || c.tbo_calendar? || c.overhaul_kind.present? || c.on_condition? || %i[tbo_hours tbo_every].any? { c.errors[_1].any? } %>
<details class="rounded-md ring-1 ring-slate-200" <%= "open" if replacement_open %>>
<summary class="cursor-pointer px-3 py-2 text-sm font-semibold text-slate-900"><%= t(".replacement_group") %>
<span class="font-normal text-slate-500"><%= t(".replacement_group_hint") %></span></summary>
<div class="grid gap-4 border-t border-slate-200 p-3 sm:grid-cols-3">
<%= f.field :replacement_hours, as: :number, label: t(".replace_every_hrs") %> <%= f.field :replacement_hours, as: :number, label: t(".replace_every_hrs") %>
<%= f.interval :replacement, label: t(".replace_every") %> <%= f.interval :replacement, label: t(".replace_every") %>
<%= f.field :replacement_from_install, as: :select, label: t(".replacement_counts_from"), <%= f.field :replacement_from_install, as: :select, label: t(".replacement_counts_from"),
@@ -35,16 +40,21 @@
<%= f.field :replacement_critical, as: :checkbox, label: t(".replacement_critical"), hint: t(".overdue_replacement_or_expiry_grounds") %> <%= f.field :replacement_critical, as: :checkbox, label: t(".replacement_critical"), hint: t(".overdue_replacement_or_expiry_grounds") %>
<%= f.field :expires_on, as: :date, label: t(".expires_on"), <%= f.field :expires_on, as: :date, label: t(".expires_on"),
hint: t(".the_date_marked_on_the") %> hint: t(".the_date_marked_on_the") %>
</div>
</details>
<details class="rounded-md ring-1 ring-slate-200" <%= "open" if tbo_open %>>
<summary class="cursor-pointer px-3 py-2 text-sm font-semibold text-slate-900"><%= t(".tbo_group") %>
<span class="font-normal text-slate-500"><%= t(".tbo_group_hint") %></span></summary>
<div class="grid gap-4 border-t border-slate-200 p-3 sm:grid-cols-3">
<%= f.field :tbo_hours, as: :number, label: t(".tbo_hrs") %> <%= f.field :tbo_hours, as: :number, label: t(".tbo_hrs") %>
<%= f.interval :tbo, label: t(".tbo_calendar") %> <%= f.interval :tbo, label: t(".tbo_calendar") %>
<div class="space-y-2"> <%= f.field :overhaul_kind, as: :select, label: t(".overhaul_type"), include_blank: "—", collection: Component::OVERHAUL_KINDS.invert,
<%= f.field :tbo_critical, as: :checkbox, label: t(".treat_tbo_as_a_hard"), hint: t(".for_engines_and_propellers_printed") %>
hint: t(".under_part_91_tbo_is") %> <%= f.field :tbo_critical, as: :checkbox, label: t(".treat_tbo_as_a_hard"), hint: t(".under_part_91_tbo_is") %>
<%= f.field :on_condition, as: :checkbox, label: t(".on_condition_part_91"), <%= f.field :on_condition, as: :checkbox, label: t(".on_condition_part_91"), hint: t(".run_past_tbo_based_on") %>
hint: t(".run_past_tbo_based_on") %>
</div> </div>
<p class="hint sm:col-span-3"><%= t(".recurring_inspections_of_this_part") %></p> </details>
</fieldset> <p class="hint"><%= t(".recurring_inspections_of_this_part") %></p>
<%= f.field :notes, as: :textarea, rows: 3 %> <%= f.field :notes, as: :textarea, rows: 3 %>
<div class="flex gap-2"> <div class="flex gap-2">
+17 -17
View File
@@ -11,28 +11,28 @@
</div> </div>
<% end %> <% end %>
</div> </div>
<dl class="card-body grid grid-cols-2 gap-x-4 gap-y-2 text-sm sm:grid-cols-4"> <dl class="card-body grid gap-x-8 gap-y-3 text-sm sm:grid-cols-2">
<dt class="text-slate-500"><%= t(".manufacturer") %></dt><dd><%= @component.manufacturer %></dd> <div class="detail-row"><dt><%= t(".manufacturer") %></dt><dd><%= @component.manufacturer %></dd></div>
<dt class="text-slate-500"><%= t(".model") %></dt><dd><%= @component.model %></dd> <div class="detail-row"><dt><%= t(".model") %></dt><dd><%= @component.model %></dd></div>
<dt class="text-slate-500"><%= t(".serial") %></dt><dd><%= @component.serial_number.presence || "—" %></dd> <div class="detail-row"><dt><%= t(".serial") %></dt><dd><%= @component.serial_number.presence || "—" %></dd></div>
<dt class="text-slate-500"><%= t(".status") %></dt><dd><%= @component.status_label %></dd> <div class="detail-row"><dt><%= t(".status") %></dt><dd><%= @component.status_label %></dd></div>
<dt class="text-slate-500"><%= t(".parent") %></dt><dd><%= @component.parent_component ? link_to(@component.parent_component, aircraft_component_path(@aircraft, @component.parent_component), class: "link") : "—" %></dd> <div class="detail-row"><dt><%= t(".parent") %></dt><dd><%= @component.parent_component ? link_to(@component.parent_component, aircraft_component_path(@aircraft, @component.parent_component), class: "link") : "—" %></dd></div>
<dt class="text-slate-500"><%= t(".location") %></dt><dd><%= @component.install_location.presence || "—" %></dd> <div class="detail-row"><dt><%= t(".location") %></dt><dd><%= @component.install_location.presence || "—" %></dd></div>
<dt class="text-slate-500"><%= t(".in_service_since") %></dt><dd><%= fmt_date(@component.date_in_service) %></dd> <div class="detail-row"><dt><%= t(".in_service_since") %></dt><dd><%= fmt_date(@component.date_in_service) %></dd></div>
<dt class="text-slate-500"><%= t(".last_oh_service") %></dt><dd><%= fmt_date(@component.overhaul_date) %></dd> <div class="detail-row"><dt><%= t(".last_oh_service") %></dt><dd><%= fmt_date(@component.overhaul_date) %></dd></div>
<dt class="text-slate-500"><%= t(".hours_in_service") %></dt><dd><%= hours(@component.hours_in_service) %></dd> <div class="detail-row"><dt><%= t(".hours_in_service") %></dt><dd><%= hours(@component.hours_in_service) %></dd></div>
<dt class="text-slate-500"><%= t(".since_oh_service") %></dt><dd><%= hours(@component.hours_since_overhaul) %></dd> <div class="detail-row"><dt><%= t(".since_oh_service") %></dt><dd><%= hours(@component.hours_since_overhaul) %></dd></div>
<dt class="text-slate-500"><%= t(".tbo") %></dt><dd><%= @component.tbo_hours ? t(".h_remaining", tbo_hours: @component.tbo_hours, hours_to_tbo: (hours(@component.hours_to_tbo))) : "—" %></dd> <div class="detail-row"><dt><%= t(".tbo") %></dt><dd><%= @component.tbo_hours ? t(".h_remaining", tbo_hours: @component.tbo_hours, hours_to_tbo: (hours(@component.hours_to_tbo))) : "—" %></dd></div>
<dt class="text-slate-500"><%= t(".replacement") %></dt><dd> <div class="detail-row"><dt><%= t(".replacement") %></dt><dd>
<%= [@component.replacement_hours && "#{@component.replacement_hours} h", @component.replacement_interval_label].compact.join(" / ").presence&.then { @component.replacement_from_install? ? t(".since_installed", interval: _1) : _1 } || "—" %> <%= [@component.replacement_hours && "#{@component.replacement_hours} h", @component.replacement_interval_label].compact.join(" / ").presence&.then { @component.replacement_from_install? ? t(".since_installed", interval: _1) : _1 } || "—" %>
<% if (d = @component.next_replacement_date) %><div class="text-xs text-slate-500"><%= t(".next_by_html", d: (fmt_date(d))) %></div><% end %> <% if (d = @component.next_replacement_date) %><div class="text-xs text-slate-500"><%= t(".next_by_html", d: (fmt_date(d))) %></div><% end %>
</dd> </dd></div>
<dt class="text-slate-500"><%= t(".flags") %></dt> <div class="detail-row sm:col-span-2"><dt><%= t(".flags") %></dt>
<dd class="col-span-3 flex flex-wrap gap-1"> <dd class="flex flex-wrap gap-1">
<% { tbo_critical: t(".tbo_critical"), replacement_critical: t(".replacement_critical"), on_condition: t(".on_condition") }.each do |flag, label| %> <% { tbo_critical: t(".tbo_critical"), replacement_critical: t(".replacement_critical"), on_condition: t(".on_condition") }.each do |flag, label| %>
<% if @component.public_send("#{flag}?") %><span class="badge-blue"><%= label %></span><% end %> <% if @component.public_send("#{flag}?") %><span class="badge-blue"><%= label %></span><% end %>
<% end %> <% end %>
</dd> </dd></div>
</dl> </dl>
<% if @component.notes.present? %><div class="border-t border-slate-100 px-4 py-3 text-sm"><%= simple_format @component.notes %></div><% end %> <% if @component.notes.present? %><div class="border-t border-slate-100 px-4 py-3 text-sm"><%= simple_format @component.notes %></div><% end %>
</section> </section>
+3 -3
View File
@@ -1,7 +1,7 @@
<%= form_with model: [aircraft, document], class: "card card-body space-y-4 max-w-3xl", multipart: true do |f| %> <%= form_with model: [aircraft, document], class: "card card-body space-y-4 max-w-3xl", multipart: true, data: { controller: "name-from-file" } do |f| %>
<%= f.errors_summary %> <%= f.errors_summary %>
<div class="grid gap-4 sm:grid-cols-2"> <div class="grid gap-4 sm:grid-cols-2">
<%= f.field :name, required: true %> <%= f.field :name, required: true, data: { name_from_file_target: "name" } %>
<%= f.field :doc_type, as: :select, label: t(".type"), collection: Document::TYPES.invert %> <%= f.field :doc_type, as: :select, label: t(".type"), collection: Document::TYPES.invert %>
<%= f.field :document_collection_id, as: :select, label: t(".collection"), <%= f.field :document_collection_id, as: :select, label: t(".collection"),
collection: [[t(".none"), nil]] + aircraft.document_collections.ordered.map { [_1.name, _1.id] } %> collection: [[t(".none"), nil]] + aircraft.document_collections.ordered.map { [_1.name, _1.id] } %>
@@ -14,7 +14,7 @@
hint: t(".optional_registration_good_for_7") %> hint: t(".optional_registration_good_for_7") %>
<%= f.field :description, as: :textarea, rows: 2 %> <%= f.field :description, as: :textarea, rows: 2 %>
<%= f.field :pages, as: :file, multiple: true, label: document.persisted? ? t(".add_files") : t(".files"), <%= f.field :pages, as: :file, multiple: true, label: document.persisted? ? t(".add_files") : t(".files"),
hint: t(".images_pdfs_or_text_up", max_upload_mb: Setting.max_upload_mb) %> hint: t(".images_pdfs_or_text_up", max_upload_mb: Setting.max_upload_mb), data: { name_from_file_target: "file", action: "name-from-file#fill" } %>
<% if document.persisted? && document.pages.any? %> <% if document.persisted? && document.pages.any? %>
<div> <div>
<p class="label"><%= t(".remove_existing_files") %></p> <p class="label"><%= t(".remove_existing_files") %></p>
+9 -9
View File
@@ -17,15 +17,15 @@
<% if tail.present? && tail.upcase != @aircraft.tail_number.to_s.upcase %> <% if tail.present? && tail.upcase != @aircraft.tail_number.to_s.upcase %>
<p class="border-b border-slate-100 bg-amber-50 px-4 py-2 text-xs text-amber-800"><%= t(".this_recording_is_from_not_html", tail: tail, tail_number: @aircraft.tail_number) %></p> <p class="border-b border-slate-100 bg-amber-50 px-4 py-2 text-xs text-amber-800"><%= t(".this_recording_is_from_not_html", tail: tail, tail_number: @aircraft.tail_number) %></p>
<% end %> <% end %>
<dl class="card-body grid grid-cols-2 gap-x-4 gap-y-2 text-sm sm:grid-cols-4"> <dl class="card-body grid gap-x-8 gap-y-3 text-sm sm:grid-cols-2">
<dt class="text-slate-500"><%= t(".recorded") %></dt> <div class="detail-row sm:col-span-2"><dt><%= t(".recorded") %></dt>
<dd class="col-span-3"><%= t(".monitor_time_html", start: (recording.local(recording.started_at).strftime("%Y-%m-%d %H:%M")), end: (recording.local(recording.ended_at).strftime("%H:%M"))) %> <dd><%= t(".monitor_time_html", start: (recording.local(recording.started_at).strftime("%Y-%m-%d %H:%M")), end: (recording.local(recording.ended_at).strftime("%H:%M"))) %>
<span class="text-xs text-slate-500"><%= t(".samples_html", file_format: recording.format, flight_number: (" flight ##{recording.metadata[:flight_number]}" if recording.metadata[:flight_number]), samples: (number_with_delimiter(recording.samples))) %></span></dd> <span class="text-xs text-slate-500"><%= t(".samples_html", file_format: recording.format, flight_number: (" flight ##{recording.metadata[:flight_number]}" if recording.metadata[:flight_number]), samples: (number_with_delimiter(recording.samples))) %></span></dd></div>
<dt class="text-slate-500"><%= t(".engine_run") %></dt><dd><%= recording.engine_start ? run_duration(recording.run_time) : t(".engine_not_run") %></dd> <div class="detail-row"><dt><%= t(".engine_run") %></dt><dd><%= recording.engine_start ? run_duration(recording.run_time) : t(".engine_not_run") %></dd></div>
<dt class="text-slate-500"><%= t(".fuel_burned") %></dt><dd><%= engine_value(recording.fuel_burned, "gal", precision: 1) %></dd> <div class="detail-row"><dt><%= t(".fuel_burned") %></dt><dd><%= engine_value(recording.fuel_burned, "gal", precision: 1) %></dd></div>
<dt class="text-slate-500"><%= t(".tach") %></dt><dd class="tabular-nums"><%= hours_line.(:tach, 2) %></dd> <div class="detail-row"><dt><%= t(".tach") %></dt><dd class="tabular-nums"><%= hours_line.(:tach, 2) %></dd></div>
<dt class="text-slate-500"><%= t(".engine_hrs") %></dt><dd class="tabular-nums"><%= hours_line.(:engine_hours, 2) %></dd> <div class="detail-row"><dt><%= t(".engine_hrs") %></dt><dd class="tabular-nums"><%= hours_line.(:engine_hours, 2) %></dd></div>
<% if (flt = recording.last(:flight_hours)) %><dt class="text-slate-500"><%= t(".airborne") %></dt><dd><%= flt.zero? ? t(".no_ground_run") : "#{number_with_precision(flt, precision: 2)} hrs" %></dd><% end %> <% if (flt = recording.last(:flight_hours)) %><div class="detail-row"><dt><%= t(".airborne") %></dt><dd><%= flt.zero? ? t(".no_ground_run") : "#{number_with_precision(flt, precision: 2)} hrs" %></dd></div><% end %>
</dl> </dl>
<div class="overflow-x-auto border-t border-slate-100"> <div class="overflow-x-auto border-t border-slate-100">
+5 -1
View File
@@ -39,5 +39,9 @@
<%= f.field :engine_data, as: :file, label: t(".engine_monitor_data"), hint: t(".cgr_30p_cgr_30c_flight"), accept: ".csv,text/csv" %> <%= f.field :engine_data, as: :file, label: t(".engine_monitor_data"), hint: t(".cgr_30p_cgr_30c_flight"), accept: ".csv,text/csv" %>
</div> </div>
<p class="hint"><%= t(".saving_adds_the_tach_time") %></p> <p class="hint"><%= t(".saving_adds_the_tach_time") %></p>
<div class="flex gap-2"><%= f.submit t(".log_flight") %><%= link_to t(".cancel"), aircraft_flight_logs_path(@aircraft), class: "btn-secondary" %></div> <div class="flex flex-wrap gap-2">
<%= f.submit t(".log_flight") %>
<%= f.submit t(".log_and_next_leg"), name: "next_leg", class: "btn-secondary", title: t(".log_and_next_leg_title") %>
<%= link_to t(".cancel"), aircraft_flight_logs_path(@aircraft), class: "btn-secondary" %>
</div>
<% end %> <% end %>
+13 -12
View File
@@ -3,23 +3,24 @@
<section class="card max-w-3xl"> <section class="card max-w-3xl">
<div class="card-header"><h2 class="card-title"><%= t(".flight_on_html", date: (fmt_date(@flight_log.date))) %></h2> <div class="card-header"><h2 class="card-title"><%= t(".flight_on_html", date: (fmt_date(@flight_log.date))) %></h2>
<% if owner? %><%= delete_button t(".delete"), aircraft_flight_log_path(@aircraft, @flight_log), confirm: t(".delete_this_flight_log_aircraft") %><% end %></div> <% if owner? %><%= delete_button t(".delete"), aircraft_flight_log_path(@aircraft, @flight_log), confirm: t(".delete_this_flight_log_aircraft") %><% end %></div>
<dl class="card-body grid grid-cols-2 gap-x-4 gap-y-2 text-sm sm:grid-cols-4"> <%# One item per row on a phone (label, then value); two columns on wider screens. %>
<dt class="text-slate-500"><%= t(".tach") %></dt><dd><%= hours(@flight_log.tach_time) %> <span class="text-xs text-slate-500"><%= "(#{@flight_log.tach_out} → #{@flight_log.tach_in})" if @flight_log.tach_out && @flight_log.tach_in %></span></dd> <dl class="card-body grid gap-x-8 gap-y-3 text-sm sm:grid-cols-2">
<dt class="text-slate-500"><%= t(".hobbs") %></dt><dd><%= hours(@flight_log.hobbs_time) %> <span class="text-xs text-slate-500"><%= "(#{@flight_log.hobbs_out} → #{@flight_log.hobbs_in})" if @flight_log.hobbs_out && @flight_log.hobbs_in %></span></dd> <div class="detail-row"><dt><%= t(".tach") %></dt><dd><%= hours(@flight_log.tach_time) %> <span class="text-xs text-slate-500"><%= "(#{@flight_log.tach_out} → #{@flight_log.tach_in})" if @flight_log.tach_out && @flight_log.tach_in %></span></dd></div>
<dt class="text-slate-500"><%= t(".route") %></dt><dd class="col-span-3"><%= @flight_log.route_summary.presence || "—" %> <%= @flight_log.route %></dd> <div class="detail-row"><dt><%= t(".hobbs") %></dt><dd><%= hours(@flight_log.hobbs_time) %> <span class="text-xs text-slate-500"><%= "(#{@flight_log.hobbs_out} → #{@flight_log.hobbs_in})" if @flight_log.hobbs_out && @flight_log.hobbs_in %></span></dd></div>
<dt class="text-slate-500"><%= t(".oil_added") %></dt><dd><%= @flight_log.oil_added ? "#{@flight_log.oil_added} qt #{@flight_log.oil_added_type}" : "—" %></dd> <div class="detail-row sm:col-span-2"><dt><%= t(".route") %></dt><dd><%= @flight_log.route_summary.presence || "—" %> <%= @flight_log.route %></dd></div>
<dt class="text-slate-500"><%= t(".fuel_added") %></dt><dd><%= @flight_log.fuel_added ? "#{@flight_log.fuel_added} gal #{@flight_log.fuel_added_type}" : "—" %></dd> <div class="detail-row"><dt><%= t(".oil_added") %></dt><dd><%= @flight_log.oil_added ? "#{@flight_log.oil_added} qt #{@flight_log.oil_added_type}" : "—" %></dd></div>
<dt class="text-slate-500"><%= t(".pilot") %></dt><dd><%= @flight_log.user&.display_name || "—" %></dd> <div class="detail-row"><dt><%= t(".fuel_added") %></dt><dd><%= @flight_log.fuel_added ? "#{@flight_log.fuel_added} gal #{@flight_log.fuel_added_type}" : "—" %></dd></div>
<dt class="text-slate-500"><%= t(".track_log") %></dt><dd class="col-span-3"><%= @flight_log.track_log.attached? ? link_to(@flight_log.track_log.filename, rails_blob_path(@flight_log.track_log, disposition: :attachment), class: "link") : "—" %> <div class="detail-row"><dt><%= t(".pilot") %></dt><dd><%= @flight_log.user&.display_name || "—" %></dd></div>
<div class="detail-row sm:col-span-2"><dt><%= t(".track_log") %></dt><dd class="min-w-0 break-words"><%= @flight_log.track_log.attached? ? link_to(@flight_log.track_log.filename, rails_blob_path(@flight_log.track_log, disposition: :attachment), class: "link") : "—" %>
<% if @track %><span class="text-xs text-slate-500"> <%= t(".gps_points_html", points: (number_with_delimiter(@track.points)), max_altitude_ft: (t(".max_ft", max_altitude_ft: (number_with_delimiter(@track.max_altitude_ft))) if @track.max_altitude_ft)) %></span> <% if @track %><span class="text-xs text-slate-500"> <%= t(".gps_points_html", points: (number_with_delimiter(@track.points)), max_altitude_ft: (t(".max_ft", max_altitude_ft: (number_with_delimiter(@track.max_altitude_ft))) if @track.max_altitude_ft)) %></span>
<% elsif @track_error %><span class="text-xs text-amber-700"> · <%= @track_error %></span><% end %></dd> <% elsif @track_error %><span class="text-xs text-amber-700"> · <%= @track_error %></span><% end %></dd></div>
<% if @air_trail_sync || @air_trail_connection %> <% if @air_trail_sync || @air_trail_connection %>
<dt class="text-slate-500"><%= t(".airtrail") %></dt> <div class="detail-row sm:col-span-2"><dt><%= t(".airtrail") %></dt>
<dd class="col-span-3 text-xs"> <dd class="text-xs">
<% if @air_trail_sync&.status == "synced" %><span class="badge-green"><%= t(".synced") %></span> <%= t(".ago_html", synced_at: (time_ago_in_words(@air_trail_sync.synced_at))) %> <% if @air_trail_sync&.status == "synced" %><span class="badge-green"><%= t(".synced") %></span> <%= t(".ago_html", synced_at: (time_ago_in_words(@air_trail_sync.synced_at))) %>
<% elsif @air_trail_sync&.status == "error" %><span class="badge-red"><%= t(".not_synced") %></span> <%= @air_trail_sync.last_error %> <% elsif @air_trail_sync&.status == "error" %><span class="badge-red"><%= t(".not_synced") %></span> <%= @air_trail_sync.last_error %>
<% else %><span class="badge-gray"><%= t(".pending") %></span><% end %> <% else %><span class="badge-gray"><%= t(".pending") %></span><% end %>
</dd> </dd></div>
<% end %> <% end %>
</dl> </dl>
<% if @flight_log.notes.present? %><div class="border-t border-slate-100 px-4 py-3 text-sm"><%= simple_format @flight_log.notes %></div><% end %> <% if @flight_log.notes.present? %><div class="border-t border-slate-100 px-4 py-3 text-sm"><%= simple_format @flight_log.notes %></div><% end %>
+7 -6
View File
@@ -25,12 +25,8 @@
<body class="min-h-full text-slate-800" data-controller="offline-sync page-age app-update<%= " offline-prep" if current_user %>"<% if current_user %> data-offline-prep-aircraft-value="<%= offline_pages.to_json %>"<% end %>> <body class="min-h-full text-slate-800" data-controller="offline-sync page-age app-update<%= " offline-prep" if current_user %>"<% if current_user %> data-offline-prep-aircraft-value="<%= offline_pages.to_json %>"<% end %>>
<%= t(".skip_to_content_html") %> <%= t(".skip_to_content_html") %>
<div class="hidden bg-sky-50 px-4 py-2 text-center text-sm text-sky-900 ring-1 ring-sky-200" data-page-age-target="banner" role="status"></div> <%# Solid and stuck to the top: iOS 26 home-screen apps then extend its color under the status bar instead of blurring it. %>
<div class="hidden bg-sky-50 px-4 py-2 text-center text-sm text-sky-900 ring-1 ring-sky-200" data-app-update-target="banner" role="status"> <header class="sticky top-0 z-40 bg-header text-white">
<%= t(".updated") %> <button type="button" class="btn-secondary btn-sm ml-1" data-action="app-update#reload"><%= t(".reload") %></button>
</div>
<div class="hidden space-y-1 bg-amber-50 px-4 py-2 text-center text-sm text-amber-900 ring-1 ring-amber-200" data-offline-sync-target="banner" role="status"></div>
<header class="bg-header text-white">
<div class="mx-auto flex max-w-7xl items-center justify-between gap-4 px-4 py-3"> <div class="mx-auto flex max-w-7xl items-center justify-between gap-4 px-4 py-3">
<%= link_to root_path, class: "flex items-center gap-2 font-semibold tracking-tight whitespace-nowrap" do %> <%= link_to root_path, class: "flex items-center gap-2 font-semibold tracking-tight whitespace-nowrap" do %>
<span class="text-xl">✈</span> <span class="hidden sm:inline"><%= t(".simple_aircraft_manager") %></span><span class="sm:hidden" aria-label="<%= t(".simple_aircraft_manager") %>"><%= t(".sam") %></span> <span class="text-xl">✈</span> <span class="hidden sm:inline"><%= t(".simple_aircraft_manager") %></span><span class="sm:hidden" aria-label="<%= t(".simple_aircraft_manager") %>"><%= t(".sam") %></span>
@@ -84,6 +80,11 @@
<% end %> <% end %>
</div> </div>
</header> </header>
<div class="hidden bg-sky-50 px-4 py-2 text-center text-sm text-sky-900 ring-1 ring-sky-200" data-page-age-target="banner" role="status"></div>
<div class="hidden bg-sky-50 px-4 py-2 text-center text-sm text-sky-900 ring-1 ring-sky-200" data-app-update-target="banner" role="status">
<%= t(".updated") %> <button type="button" class="btn-secondary btn-sm ml-1" data-action="app-update#reload"><%= t(".reload") %></button>
</div>
<div class="hidden space-y-1 bg-amber-50 px-4 py-2 text-center text-sm text-amber-900 ring-1 ring-amber-200" data-offline-sync-target="banner" role="status"></div>
<main id="main" tabindex="-1" class="mx-auto max-w-7xl px-4 py-6 focus:outline-none"> <main id="main" tabindex="-1" class="mx-auto max-w-7xl px-4 py-6 focus:outline-none">
<%= render "shared/flash" %> <%= render "shared/flash" %>
+2 -1
View File
@@ -20,7 +20,8 @@
</head> </head>
<body class="min-h-full text-slate-800"> <body class="min-h-full text-slate-800">
<%= t(".skip_to_content_html") %> <%= t(".skip_to_content_html") %>
<header class="bg-header text-white"> <%# Solid and stuck to the top: iOS 26 home-screen apps then extend its color under the status bar instead of blurring it. %>
<header class="sticky top-0 z-40 bg-header text-white">
<div class="mx-auto flex max-w-7xl items-center justify-between px-4 py-3"><span class="font-semibold"><span class="text-xl">✈</span> <%= t(".simple_aircraft_manager") %></span><%= render "shared/theme_toggle" %></div> <div class="mx-auto flex max-w-7xl items-center justify-between px-4 py-3"><span class="font-semibold"><span class="text-xl">✈</span> <%= t(".simple_aircraft_manager") %></span><%= render "shared/theme_toggle" %></div>
</header> </header>
<main id="main" tabindex="-1" class="mx-auto max-w-7xl px-4 py-6 focus:outline-none"> <main id="main" tabindex="-1" class="mx-auto max-w-7xl px-4 py-6 focus:outline-none">
+5 -2
View File
@@ -1,4 +1,4 @@
<%= form_with model: [aircraft, entry], class: "card card-body space-y-4 max-w-3xl", data: { controller: "entry-template signer component-times", component_times_aircraft_hours_value: aircraft.current_hours.to_f } do |f| %> <%= form_with model: [aircraft, entry], class: "card card-body space-y-4 max-w-3xl", data: { controller: "entry-template signer component-times show-when", component_times_aircraft_hours_value: aircraft.current_hours.to_f } do |f| %>
<%= f.errors_summary %> <%= f.errors_summary %>
<% if entry.supersedes %> <% if entry.supersedes %>
<%= f.hidden_field :supersedes_id %> <%= f.hidden_field :supersedes_id %>
@@ -25,7 +25,8 @@
<%= f.field :date, as: :date %> <%= f.field :date, as: :date %>
<%= f.field :log_type, as: :select, label: t(".logbook"), collection: LogbookEntry::LOG_TYPES.invert, <%= f.field :log_type, as: :select, label: t(".logbook"), collection: LogbookEntry::LOG_TYPES.invert,
data: { component_times_target: "logType", entry_template_target: "logType", action: "component-times#logTypeChanged" } %> data: { component_times_target: "logType", entry_template_target: "logType", action: "component-times#logTypeChanged" } %>
<%= f.field :entry_type, as: :select, label: t(".entry_type"), collection: LogbookEntry::ENTRY_TYPES.invert, data: { entry_template_target: "entryType" } %> <%= f.field :entry_type, as: :select, label: t(".entry_type"), collection: LogbookEntry::ENTRY_TYPES.invert,
data: { entry_template_target: "entryType", show_when_target: "source", action: "show-when#update" } %>
<%= f.field :aircraft_hours_at_entry, as: :number, step: 0.1, label: t(".airframe_total_time"), <%= f.field :aircraft_hours_at_entry, as: :number, step: 0.1, label: t(".airframe_total_time"),
data: { component_times_target: "airframe", action: "input->component-times#airframeChanged" } %> data: { component_times_target: "airframe", action: "input->component-times#airframeChanged" } %>
</div> </div>
@@ -57,8 +58,10 @@
<%= f.field :signoff_certificate_number, label: t(".certificate_number"), placeholder: "e.g. 1234567", data: { signer_target: "number" } %> <%= f.field :signoff_certificate_number, label: t(".certificate_number"), placeholder: "e.g. 1234567", data: { signer_target: "number" } %>
</div> </div>
<div class="grid gap-4 sm:grid-cols-2"> <div class="grid gap-4 sm:grid-cols-2">
<div data-show-when-target="item" data-show-when-value="INSPECTION">
<%= f.field :inspection_result, as: :select, label: t(".inspection_result"), include_blank: t(".not_an_inspection"), <%= f.field :inspection_result, as: :select, label: t(".inspection_result"), include_blank: t(".not_an_inspection"),
collection: LogbookEntry::INSPECTION_RESULTS.invert, hint: t(".for_inspection_entries_43_11") %> collection: LogbookEntry::INSPECTION_RESULTS.invert, hint: t(".for_inspection_entries_43_11") %>
</div>
<%= f.field :signoff_location, label: t(".location_shop") %> <%= f.field :signoff_location, label: t(".location_shop") %>
<%= f.field :document_id, as: :select, label: t(".scanned_page_document"), collection: document_options(aircraft) %> <%= f.field :document_id, as: :select, label: t(".scanned_page_document"), collection: document_options(aircraft) %>
<%= f.field :page_number, as: :number, label: t(".page_in_document") %> <%= f.field :page_number, as: :number, label: t(".page_in_document") %>
+13 -13
View File
@@ -2,24 +2,24 @@
<section class="card max-w-4xl"> <section class="card max-w-4xl">
<div class="card-header"><h2 class="card-title"><%= @record.type_label %>: <%= @record.title %></h2> <div class="card-header"><h2 class="card-title"><%= @record.type_label %>: <%= @record.title %></h2>
<% if owner? %><%= link_to t(".edit"), edit_aircraft_major_record_path(@aircraft, @record), class: "btn-secondary btn-sm" %><% end %></div> <% if owner? %><%= link_to t(".edit"), edit_aircraft_major_record_path(@aircraft, @record), class: "btn-secondary btn-sm" %><% end %></div>
<dl class="card-body grid grid-cols-2 gap-x-4 gap-y-2 text-sm sm:grid-cols-4"> <dl class="card-body grid gap-x-8 gap-y-3 text-sm sm:grid-cols-2">
<dt class="text-slate-500"><%= t(".date") %></dt><dd><%= fmt_date(@record.date_performed) %></dd> <div class="detail-row"><dt><%= t(".date") %></dt><dd><%= fmt_date(@record.date_performed) %></dd></div>
<dt class="text-slate-500"><%= t(".aircraft_hours") %></dt><dd><%= hours(@record.aircraft_hours) %></dd> <div class="detail-row"><dt><%= t(".aircraft_hours") %></dt><dd><%= hours(@record.aircraft_hours) %></dd></div>
<dt class="text-slate-500"><%= t(".performed_by") %></dt><dd><%= @record.performed_by.presence || "—" %></dd> <div class="detail-row"><dt><%= t(".performed_by") %></dt><dd><%= @record.performed_by.presence || "—" %></dd></div>
<dt class="text-slate-500"><%= t(".component") %></dt><dd><%= @record.component || "—" %></dd> <div class="detail-row"><dt><%= t(".component") %></dt><dd><%= @record.component || "—" %></dd></div>
<dt class="text-slate-500"><%= t(".form_337") %></dt><dd><%= @record.form_337_document ? link_to(@record.form_337_document.name, aircraft_document_path(@aircraft, @record.form_337_document), class: "link") : "—" %></dd> <div class="detail-row"><dt><%= t(".form_337") %></dt><dd><%= @record.form_337_document ? link_to(@record.form_337_document.name, aircraft_document_path(@aircraft, @record.form_337_document), class: "link") : "—" %></dd></div>
<dt class="text-slate-500"><%= t(".stc") %></dt><dd><%= [@record.stc_number, @record.stc_holder].compact_blank.join(" · ").presence || "—" %> <div class="detail-row"><dt><%= t(".stc") %></dt><dd><%= [@record.stc_number, @record.stc_holder].compact_blank.join(" · ").presence || "—" %>
<%= link_to(t(".docs"), aircraft_document_path(@aircraft, @record.stc_document), class: "link") if @record.stc_document %></dd> <%= link_to(t(".docs"), aircraft_document_path(@aircraft, @record.stc_document), class: "link") if @record.stc_document %></dd></div>
<dt class="text-slate-500"><%= t(".logbook") %></dt><dd><%= @record.logbook_entry ? link_to(@record.logbook_entry.date, aircraft_logbook_entry_path(@aircraft, @record.logbook_entry), class: "link") : "—" %></dd> <div class="detail-row"><dt><%= t(".logbook") %></dt><dd><%= @record.logbook_entry ? link_to(@record.logbook_entry.date, aircraft_logbook_entry_path(@aircraft, @record.logbook_entry), class: "link") : "—" %></dd></div>
<dt class="text-slate-500"><%= t(".weight_balance") %></dt> <div class="detail-row"><dt><%= t(".weight_balance") %></dt>
<dd> <dd>
<% if (wb = @aircraft.weight_balance_records.where(major_record: @record).recent_first.first) %> <% if (wb = @aircraft.weight_balance_records.where(major_record: @record).recent_first.first) %>
<%= link_to t(".lb_in", date: fmt_date(wb.date), weight: number_with_precision(wb.empty_weight, precision: 1), arm: number_with_precision(wb.empty_arm, precision: 2)), aircraft_weight_balance_records_path(@aircraft), class: "link" %> <%= link_to t(".lb_in", date: fmt_date(wb.date), weight: number_with_precision(wb.empty_weight, precision: 1), arm: number_with_precision(wb.empty_arm, precision: 2)), aircraft_weight_balance_records_path(@aircraft), class: "link" %>
<% elsif owner? %> <% elsif owner? %>
<%= link_to t(".record_the_new_w_b"), new_aircraft_weight_balance_record_path(@aircraft, major_record_id: @record.id), class: "link" %> <%= link_to t(".record_the_new_w_b"), new_aircraft_weight_balance_record_path(@aircraft, major_record_id: @record.id), class: "link" %>
<% else %>—<% end %> <% else %>—<% end %>
</dd> </dd></div>
<dt class="text-slate-500"><%= t(".icas") %></dt> <div class="detail-row"><dt><%= t(".icas") %></dt>
<dd> <dd>
<%= @record.has_ica? ? t(".yes") : t(".no") %> <%= @record.has_ica? ? t(".yes") : t(".no") %>
<% if (ica = @record.ica_inspection_type) %> <% if (ica = @record.ica_inspection_type) %>
@@ -28,7 +28,7 @@
<% elsif @record.has_ica? && owner? %> <% elsif @record.has_ica? && owner? %>
· <%= link_to t(".add_the_ica_s_recurring"), new_aircraft_inspection_type_path(@aircraft, major_record_id: @record.id), class: "link" %> · <%= link_to t(".add_the_ica_s_recurring"), new_aircraft_inspection_type_path(@aircraft, major_record_id: @record.id), class: "link" %>
<% end %> <% end %>
</dd> </dd></div>
</dl> </dl>
<% [[t(".description"), @record.description], [t(".ica_notes"), @record.ica_notes], [t(".notes"), @record.notes]].each do |title, text| %> <% [[t(".description"), @record.description], [t(".ica_notes"), @record.ica_notes], [t(".notes"), @record.notes]].each do |title, text| %>
<% if text.present? %><div class="border-t border-slate-100 px-4 py-3 text-sm"><h3 class="mb-1 font-medium"><%= title %></h3><%= simple_format text %></div><% end %> <% if text.present? %><div class="border-t border-slate-100 px-4 py-3 text-sm"><h3 class="mb-1 font-medium"><%= title %></h3><%= simple_format text %></div><% end %>
+36 -20
View File
@@ -1,10 +1,22 @@
<h1 class="mb-4 text-2xl font-bold"><%= t(".your_profile") %></h1> <h1 class="mb-4 text-2xl font-bold"><%= t(".your_profile") %></h1>
<%= form_with model: @user, url: profile_path, method: :patch, class: "card card-body space-y-4 max-w-md" do |f| %> <%# One column on a phone; on a wide screen, the account and its security on
the left and everything else on the right. %>
<div class="grid max-w-5xl items-start gap-5 lg:grid-cols-2">
<div class="space-y-5">
<%= form_with model: @user, url: profile_path, method: :patch, class: "card card-body space-y-4" do |f| %>
<h2 class="card-title"><%= t(".account") %></h2>
<%= f.errors_summary %> <%= f.errors_summary %>
<%= f.field :name %> <%= f.field :name %>
<%= f.field :email_address, as: :email, label: t(".email") %> <%= f.field :email_address, as: :email, label: t(".email") %>
<%= f.field :reminder_emails, as: :checkbox, label: t(".weekly_maintenance_reminders"), <%= f.field :reminder_emails, as: :checkbox, label: t(".weekly_maintenance_reminders"),
hint: t(MailSettings.configured? ? ".a_monday_email_about_overdue" : ".reminders_once_email_set_up") %> hint: t(MailSettings.configured? ? ".a_monday_email_about_overdue" : ".reminders_once_email_set_up") %>
<div>
<%= f.label :time_zone, t(".time_zone"), class: "label" %>
<%= f.time_zone_select :time_zone, ActiveSupport::TimeZone.us_zones,
{ include_blank: t(".time_zone_automatic", zone: device_time_zone_label || t(".time_zone_unknown")) },
class: "input" %>
<p class="hint"><%= t(".time_zone_hint", now: fmt_time(Time.current)) %></p>
</div>
<%= f.field :password, as: :password, label: t(".new_password"), hint: t(".leave_blank_to_keep_your", min: User::PASSWORD_MIN), autocomplete: "new-password" %> <%= f.field :password, as: :password, label: t(".new_password"), hint: t(".leave_blank_to_keep_your", min: User::PASSWORD_MIN), autocomplete: "new-password" %>
<%= f.field :password_confirmation, as: :password, label: t(".confirm_new_password"), autocomplete: "new-password" %> <%= f.field :password_confirmation, as: :password, label: t(".confirm_new_password"), autocomplete: "new-password" %>
<div> <div>
@@ -16,7 +28,7 @@
<% end %> <% end %>
<% if Sso.enabled? %> <% if Sso.enabled? %>
<section class="card card-body mt-5 max-w-md"> <section class="card card-body">
<h2 class="card-title"><%= t(".single_sign_on") %></h2> <h2 class="card-title"><%= t(".single_sign_on") %></h2>
<% if @user.sso_uid? %> <% if @user.sso_uid? %>
<p class="mt-1 text-sm text-slate-600"><%= t(".your_account_is_linked_to_html", so: Sso.label) %></p> <p class="mt-1 text-sm text-slate-600"><%= t(".your_account_is_linked_to_html", so: Sso.label) %></p>
@@ -31,7 +43,7 @@
</section> </section>
<% end %> <% end %>
<section class="card card-body mt-5 max-w-md" id="two-factor"> <section class="card card-body" id="two-factor">
<h2 class="card-title"><%= t(".two_factor_sign_in") %></h2> <h2 class="card-title"><%= t(".two_factor_sign_in") %></h2>
<% if @user.otp_enabled? %> <% if @user.otp_enabled? %>
<p class="mt-1 text-sm text-slate-600"><span class="badge-green"><%= t(".on") %></span> <%= t(".since_signing_in_with_your_html", to_date: (fmt_date(@user.otp_enabled_at.to_date)), recovery_codes_left: @user.recovery_codes_left) %></p> <p class="mt-1 text-sm text-slate-600"><span class="badge-green"><%= t(".on") %></span> <%= t(".since_signing_in_with_your_html", to_date: (fmt_date(@user.otp_enabled_at.to_date)), recovery_codes_left: @user.recovery_codes_left) %></p>
@@ -46,7 +58,21 @@
<% end %> <% end %>
</section> </section>
<section class="card card-body mt-5 max-w-md" id="calendar"> <section class="card card-body">
<h2 class="card-title"><%= t(".sessions") %></h2>
<% others = @user.sessions.where.not(id: Current.session.id).count %>
<p class="mt-1 text-sm text-slate-600">
<%= t(".you_re_signed_in_on", count: others) %>
<%= t(".sessions_unused_for_sign_out_html", days: (Authentication::SESSION_IDLE_TIMEOUT.in_days.to_i)) %>
</p>
<% if others.positive? %>
<div class="mt-3"><%= button_to t(".sign_out_everywhere_else"), other_sessions_path, method: :delete, class: "btn-secondary btn-sm" %></div>
<% end %>
</section>
</div>
<div class="space-y-5">
<section class="card card-body" id="calendar">
<h2 class="card-title"><%= t(".calendar_feed") %></h2> <h2 class="card-title"><%= t(".calendar_feed") %></h2>
<p class="mt-1 text-sm text-slate-600"><%= t(".what_s_coming_due_on") %></p> <p class="mt-1 text-sm text-slate-600"><%= t(".what_s_coming_due_on") %></p>
<% if @user.calendar_token.present? %> <% if @user.calendar_token.present? %>
@@ -63,7 +89,7 @@
<% end %> <% end %>
</section> </section>
<section class="card card-body mt-5 max-w-md" id="certificates"> <section class="card card-body" id="certificates">
<h2 class="card-title"><%= t(".certificates") %></h2> <h2 class="card-title"><%= t(".certificates") %></h2>
<p class="mt-1 text-sm text-slate-600"><%= t(".your_faa_certificates_for_signing") %></p> <p class="mt-1 text-sm text-slate-600"><%= t(".your_faa_certificates_for_signing") %></p>
<% if @user.certificates.any? %> <% if @user.certificates.any? %>
@@ -88,7 +114,7 @@
<% end %> <% end %>
</section> </section>
<section class="card card-body mt-5 max-w-md space-y-4" id="device"> <section class="card card-body space-y-4" id="device">
<h2 class="card-title"><%= t(".this_device") %></h2> <h2 class="card-title"><%= t(".this_device") %></h2>
<div data-controller="install"> <div data-controller="install">
<h3 class="text-sm font-semibold"><%= t(".install_heading") %></h3> <h3 class="text-sm font-semibold"><%= t(".install_heading") %></h3>
@@ -101,7 +127,7 @@
<div data-controller="push" data-push-key-value="<%= PushKeys.public_key %>" data-push-url-value="<%= push_subscription_path %>" data-push-test-url-value="<%= test_push_subscription_path %>"> <div data-controller="push" data-push-key-value="<%= PushKeys.public_key %>" data-push-url-value="<%= push_subscription_path %>" data-push-test-url-value="<%= test_push_subscription_path %>">
<h3 class="text-sm font-semibold"><%= t(".notifications_heading") %></h3> <h3 class="text-sm font-semibold"><%= t(".notifications_heading") %></h3>
<p class="hint"><%= t(".notifications_what") %></p> <p class="hint"><%= t(".notifications_what") %></p>
<p class="mt-2 text-sm text-slate-600" data-push-target="status" role="status"></p> <p class="mt-2 whitespace-pre-line text-sm text-slate-600" data-push-target="status" role="status"></p>
<div class="mt-2 flex flex-wrap gap-2"> <div class="mt-2 flex flex-wrap gap-2">
<button type="button" class="btn-secondary btn-sm" data-push-target="on" data-action="push#turnOn" hidden><%= t(".notifications_on") %></button> <button type="button" class="btn-secondary btn-sm" data-push-target="on" data-action="push#turnOn" hidden><%= t(".notifications_on") %></button>
<button type="button" class="btn-secondary btn-sm" data-push-target="off" data-action="push#turnOff" hidden><%= t(".notifications_off") %></button> <button type="button" class="btn-secondary btn-sm" data-push-target="off" data-action="push#turnOff" hidden><%= t(".notifications_off") %></button>
@@ -110,22 +136,12 @@
</div> </div>
</section> </section>
<section class="card card-body mt-5 max-w-md"> <section class="card card-body">
<h2 class="card-title"><%= t(".sessions") %></h2>
<% others = @user.sessions.where.not(id: Current.session.id).count %>
<p class="mt-1 text-sm text-slate-600">
<%= t(".you_re_signed_in_on", count: others) %>
<%= t(".sessions_unused_for_sign_out_html", days: (Authentication::SESSION_IDLE_TIMEOUT.in_days.to_i)) %>
</p>
<% if others.positive? %>
<div class="mt-3"><%= button_to t(".sign_out_everywhere_else"), other_sessions_path, method: :delete, class: "btn-secondary btn-sm" %></div>
<% end %>
</section>
<section class="card card-body mt-5 max-w-md">
<h2 class="card-title"><%= t(".integrations") %></h2> <h2 class="card-title"><%= t(".integrations") %></h2>
<p class="mt-1 text-sm text-slate-600"> <p class="mt-1 text-sm text-slate-600">
<%= link_to t(".airtrail_sync"), air_trail_connection_path, class: "link" %>: <%= link_to t(".airtrail_sync"), air_trail_connection_path, class: "link" %>:
<%= t(".push_the_flights_you_log_html", off: (current_user.air_trail_connection&.enabled? ? "on" : "off")) %> <%= t(".push_the_flights_you_log_html", off: (current_user.air_trail_connection&.enabled? ? "on" : "off")) %>
</p> </p>
</section> </section>
</div>
</div>
+5 -4
View File
@@ -64,7 +64,7 @@ self.addEventListener("fetch", (event) => {
.catch(() => caches.match(url.pathname))) .catch(() => caches.match(url.pathname)))
} else if (url.pathname.startsWith("/assets/")) { } else if (url.pathname.startsWith("/assets/")) {
event.respondWith(cachedAsset(request)) event.respondWith(cachedAsset(request))
} else if (url.pathname.startsWith("/rails/active_storage/blobs/redirect/")) { } else if (/^\/rails\/active_storage\/(blobs|representations)\/redirect\//.test(url.pathname)) {
// Uploaded files come from the network; an aircraft photo saved for // Uploaded files come from the network; an aircraft photo saved for
// offline use stands in when there's none. // offline use stands in when there's none.
event.respondWith(fetch(request) event.respondWith(fetch(request)
@@ -80,11 +80,12 @@ const savedImage = async (request, response) => {
} }
// Photo links carry an expiry, so they change with every page; the saved copy // Photo links carry an expiry, so they change with every page; the saved copy
// is filed under the upload's id instead (same rule in offline_prep_controller.js). // is filed under the upload's id (and size) instead (same rule in offline_prep_controller.js).
function imageKey(url) { function imageKey(url) {
try { try {
const signed = new URL(url, self.location.origin).pathname.match(/\/blobs\/redirect\/([^/]+?)--/)[1] const [ , signed, size ] = new URL(url, self.location.origin).pathname.match(/\/(?:blobs|representations)\/redirect\/([^/]+?)--[^/]+\/(?:([^/]+)\/)?/)
return `${self.location.origin}/offline-image/${JSON.parse(atob(decodeURIComponent(signed)))._rails.data}` const id = JSON.parse(atob(decodeURIComponent(signed)))._rails.data
return `${self.location.origin}/offline-image/${id}${size ? `/${size}` : ""}`
} catch (_) { return null } } catch (_) { return null }
} }
+6
View File
@@ -3,6 +3,12 @@
<p class="mb-4 text-sm text-slate-600"><%= t(".create_the_administrator_account_to") %></p> <p class="mb-4 text-sm text-slate-600"><%= t(".create_the_administrator_account_to") %></p>
<%= form_with model: @user, url: setup_path, class: "card card-body space-y-4" do |f| %> <%= form_with model: @user, url: setup_path, class: "card card-body space-y-4" do |f| %>
<%= f.errors_summary %> <%= f.errors_summary %>
<div>
<%= label_tag :setup_code, t(".setup_code"), class: "label" %>
<%= text_field_tag :setup_code, params[:setup_code], required: true, autocomplete: "off", autocapitalize: "characters", spellcheck: false,
class: "input font-mono tracking-widest", placeholder: "XXXX-XXXX" %>
<p class="hint"><%= t(".setup_code_hint_html") %></p>
</div>
<%= f.field :name %> <%= f.field :name %>
<%= f.field :email_address, as: :email, label: t(".email"), required: true %> <%= f.field :email_address, as: :email, label: t(".email"), required: true %>
<%= f.field :password, as: :password, required: true, hint: t(".at_least_characters_not_one", min: User::PASSWORD_MIN) %> <%= f.field :password, as: :password, required: true, hint: t(".at_least_characters_not_one", min: User::PASSWORD_MIN) %>
+2 -2
View File
@@ -2,8 +2,8 @@
<% aw = aircraft.airworthiness %> <% aw = aircraft.airworthiness %>
<div class="mb-4 flex flex-wrap items-center justify-between gap-3"> <div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
<% if aircraft.picture.attached? %> <% if aircraft.picture_shown? %>
<%= image_tag aircraft.picture, class: "h-12 w-12 rounded-md object-cover", alt: "" %> <%= image_tag aircraft.picture_for(:thumb), width: 48, height: 48, class: "h-12 w-12 rounded-md object-cover", alt: "" %>
<% end %> <% end %>
<div> <div>
<h1 class="text-2xl font-bold tracking-tight"> <h1 class="text-2xl font-bold tracking-tight">
+1 -1
View File
@@ -1,7 +1,7 @@
<% content_for :title, @aircraft.tail_number %> <% content_for :title, @aircraft.tail_number %>
<div class="mb-5 flex flex-wrap items-center justify-between gap-3"> <div class="mb-5 flex flex-wrap items-center justify-between gap-3">
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
<% if @aircraft.picture.attached? %><%= image_tag rails_blob_path(@aircraft.picture, disposition: :inline), class: "h-16 w-16 rounded-md object-cover", alt: t(".photo_of", tail_number: @aircraft.tail_number) %><% end %> <% if @aircraft.picture_shown? %><%= image_tag @aircraft.picture_for(:thumb), width: 64, height: 64, class: "h-16 w-16 rounded-md object-cover", alt: t(".photo_of", tail_number: @aircraft.tail_number) %><% end %>
<div> <div>
<h1 class="text-2xl font-bold"><%= @aircraft.tail_number %> <span class="text-base font-normal text-slate-500"><%= [@aircraft.make, @aircraft.model].compact_blank.join(" ") %></span></h1> <h1 class="text-2xl font-bold"><%= @aircraft.tail_number %> <span class="text-base font-normal text-slate-500"><%= [@aircraft.make, @aircraft.model].compact_blank.join(" ") %></span></h1>
<div class="mt-1 flex flex-wrap items-center gap-2 text-sm"> <div class="mt-1 flex flex-wrap items-center gap-2 text-sm">
+8 -9
View File
@@ -1,21 +1,20 @@
<%# A squawk's files: photos open in the in-app viewer, everything else opens in <%# A squawk's files: photos show as thumbnails that open the in-app viewer
a new tab. Every file has a download link. %> (which has Download); other files open in a new tab and have a download link. %>
<% files = squawk.attachments.to_a %> <% files = squawk.attachments.to_a %>
<% if files.any? %> <% if files.any? %>
<% photos, others = files.partition(&:image?) %> <% photos, others = files.partition { _1.image? && _1.variable? } %>
<div class="mt-1" data-controller="gallery"> <div class="mt-1" data-controller="gallery">
<ul class="flex flex-wrap gap-1.5"> <ul class="flex flex-wrap gap-1.5">
<% photos.each do |file| %> <% photos.each do |file| %>
<li class="inline-flex items-center overflow-hidden rounded-md text-xs ring-1 ring-slate-300"> <li>
<%= link_to rails_blob_path(file, disposition: :inline), class: "px-2 py-1 text-sky-700 hover:bg-slate-100", <%= link_to rails_blob_path(file, disposition: :inline),
class: "block overflow-hidden rounded-md ring-1 ring-slate-300 hover:ring-2 hover:ring-sky-500 focus-visible:ring-2 focus-visible:ring-sky-500",
title: t(".preview", filename: file.filename), title: t(".preview", filename: file.filename),
data: { gallery_target: "item", action: "gallery#open", gallery_name: file.filename.to_s, data: { gallery_target: "item", action: "gallery#open", gallery_name: file.filename.to_s,
gallery_download: rails_blob_path(file, disposition: :attachment) } do %> gallery_download: rails_blob_path(file, disposition: :attachment) } do %>
🖼 <%= file.filename.to_s.truncate(28, omission: "…") %> <%= image_tag file.variant(resize_to_fill: [ 160, 160 ]), alt: file.filename.to_s, loading: "lazy", width: 64, height: 64,
class: "block h-16 w-16 bg-slate-100 object-cover" %>
<% end %> <% end %>
<%= link_to "⬇", rails_blob_path(file, disposition: :attachment), download: file.filename.to_s,
class: "border-l border-slate-300 px-1.5 py-1 text-slate-500 hover:bg-slate-100 hover:text-sky-700",
title: t(".download", filename: file.filename), aria: { label: t(".download", filename: file.filename) } %>
</li> </li>
<% end %> <% end %>
<% others.each do |file| %> <% others.each do |file| %>
+7 -3
View File
@@ -1,12 +1,16 @@
<%= form_with model: [aircraft, squawk], multipart: true, class: "card card-body space-y-4 max-w-2xl", <%= form_with model: [aircraft, squawk], multipart: true, class: "card card-body space-y-4 max-w-2xl",
data: (squawk.new_record? ? { controller: "offline-form", offline_form_kind_value: "squawk", offline_form_tail_value: aircraft.tail_number, data: (squawk.new_record? ? { controller: "offline-form show-when", offline_form_kind_value: "squawk", offline_form_tail_value: aircraft.tail_number,
action: "submit->offline-form#submit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } : {}) do |f| %> action: "submit->offline-form#submit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } : { controller: "show-when" }) do |f| %>
<% if squawk.new_record? %> <% if squawk.new_record? %>
<%= f.hidden_field :client_key, data: { offline_form_target: "key" } %> <%= f.hidden_field :client_key, data: { offline_form_target: "key" } %>
<div class="hidden rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200" data-offline-form-target="notice" role="status"></div> <div class="hidden rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200" data-offline-form-target="notice" role="status"></div>
<% end %> <% end %>
<%= f.errors_summary %> <%= f.errors_summary %>
<%= f.field :priority, as: :select, collection: Squawk::PRIORITIES.invert, hint: t(".ground_aircraft_makes_the_aircraft") %> <%= f.field :priority, as: :select, collection: Squawk::PRIORITIES.invert, hint: t(".ground_aircraft_makes_the_aircraft"),
data: { show_when_target: "source", action: "show-when#update" } %>
<p class="rounded-md bg-red-50 px-3 py-2 text-sm text-red-800 ring-1 ring-red-200" role="alert" data-show-when-target="item" data-show-when-value="0" hidden>
<%= t(".grounding_warning", tail_number: aircraft.tail_number) %>
</p>
<%= f.field :issue_reported, as: :textarea, label: t(".issue"), required: true, autofocus: true %> <%= f.field :issue_reported, as: :textarea, label: t(".issue"), required: true, autofocus: true %>
<%= f.field :component_id, as: :select, label: t(".component_optional"), collection: component_options(aircraft) %> <%= f.field :component_id, as: :select, label: t(".component_optional"), collection: component_options(aircraft) %>
<%= f.field :attachments, as: :file, multiple: true, label: squawk.attachments.attached? ? t(".add_photos_files") : t(".photos_files"), <%= f.field :attachments, as: :file, multiple: true, label: squawk.attachments.attached? ? t(".add_photos_files") : t(".photos_files"),
-1
View File
@@ -3,7 +3,6 @@
<section class="card"> <section class="card">
<div class="card-header"> <div class="card-header">
<h2 class="card-title"><%= t(".open_squawks") %></h2> <h2 class="card-title"><%= t(".open_squawks") %></h2>
<%= link_to t(".report_squawk"), new_aircraft_squawk_path(@aircraft), class: "btn-primary" %>
</div> </div>
<% if @active.any? %><%= render "squawks/table", squawks: @active, aircraft: @aircraft %><% else %><%= empty_state t(".no_open_squawks") %><% end %> <% if @active.any? %><%= render "squawks/table", squawks: @active, aircraft: @aircraft %><% else %><%= empty_state t(".no_open_squawks") %><% end %>
</section> </section>
+7 -3
View File
@@ -36,10 +36,14 @@ module SimpleAircraftManager
# These settings can be overridden in specific environments using the files # These settings can be overridden in specific environments using the files
# in config/environments, which are processed later. # in config/environments, which are processed later.
# #
# config.time_zone = "Central Time (US & Canada)" # The installation's time zone, from Docker's standard TZ (e.g.
# "America/New_York"): for scheduled jobs and for anyone whose device zone
# isn't known yet. Each person's own zone comes from Profile or their
# device (TimeZones). Not a zone name (unset, or e.g. ":/etc/localtime"): UTC.
config.time_zone = ActiveSupport::TimeZone[ENV["TZ"].to_s] ? ENV["TZ"] : "UTC"
# config.eager_load_paths << Rails.root.join("extras") # config.eager_load_paths << Rails.root.join("extras")
# Uploads are served as-is (no image variants), so libvips/image_processing is not needed. # Small resized copies of photos (squawk thumbnails), made with libvips.
config.active_storage.variant_processor = :disabled config.active_storage.variant_processor = :vips
end end
end end
+22 -8
View File
@@ -100,12 +100,26 @@ Rails.application.configure do
# Only use :id for inspections in production. # Only use :id for inspections in production.
config.active_record.attributes_for_inspect = [ :id ] config.active_record.attributes_for_inspect = [ :id ]
# Enable DNS rebinding protection and other `Host` header attacks. # Answer only for the app's own names (stops DNS rebinding and forged Host
# config.hosts = [ # headers): APP_HOST, the APP_URL host, ALLOWED_HOSTS, localhost and IP
# "example.com", # Allow requests from example.com # addresses (a rebinding attack needs a name). Off when APP_HOST isn't set.
# /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` if ENV["APP_HOST"].present?
# ] config.hosts = [
# ENV["APP_HOST"].sub(/:\d+\z/, ""),
# Skip DNS rebinding protection for the default health check endpoint. (URI.parse(ENV["APP_URL"]).host if ENV["APP_URL"].present?),
# config.host_authorization = { exclude: ->(request) { request.path == "/up" } } *ENV.fetch("ALLOWED_HOSTS", "").split(",").map(&:strip),
"localhost",
IPAddr.new("0.0.0.0/0"),
IPAddr.new("::/0")
].compact_blank
config.host_authorization = {
exclude: ->(request) { request.path == "/up" },
# Say why, rather than a blank page: usually a name that's simply missing.
response_app: ->(env) {
host = ActionDispatch::Request.new(env).host.to_s.gsub(/[^a-z0-9.\-:\[\]]/i, "").first(253)
[ 403, { "content-type" => "text/plain; charset=utf-8" },
[ "This server doesn't answer for \"#{host}\". If that's a name for this app, add it to ALLOWED_HOSTS (comma-separated) and restart.\n" ] ]
}
}
end
end end
@@ -0,0 +1,8 @@
# Uploads that claim to be images but can't be read as one (empty, corrupt,
# or another kind of file with an image name): if resizing fails, send the
# original rather than an error.
Rails.application.config.to_prepare do
ActiveStorage::Representations::BaseController.rescue_from(Vips::Error, ActiveStorage::InvariableError) do
redirect_to Rails.application.routes.url_helpers.rails_blob_path(@blob, disposition: params[:disposition], only_path: true)
end
end
+5
View File
@@ -0,0 +1,5 @@
# Refuse to run in production with a guessable secret key (see SecretKeyCheck).
# Skipped for the image build's asset step, which uses a throwaway key.
if Rails.env.production? && ENV["SECRET_KEY_BASE"].present? && ENV["SECRET_KEY_BASE_DUMMY"].blank?
Rails.application.config.after_initialize { SecretKeyCheck.verify! }
end
+64 -8
View File
@@ -301,6 +301,7 @@ en:
attributes: attributes:
parent_component: parent_component:
itself: can't be itself itself: can't be itself
own_part: can't be one of its own parts
other_aircraft: must be on the same aircraft other_aircraft: must be on the same aircraft
user: user:
attributes: attributes:
@@ -654,7 +655,7 @@ en:
'yes': 'yes' 'yes': 'yes'
'no': 'no' 'no': 'no'
environment: Environment environment: Environment
time_zone: Time zone time_zone: Default time zone
sso: Single sign-on sso: Single sign-on
sso_only: "%{provider}, password sign-in off" sso_only: "%{provider}, password sign-in off"
not_configured: not configured not_configured: not configured
@@ -704,6 +705,9 @@ en:
envelope_weights: Envelope weights must be more than 0 envelope_weights: Envelope weights must be more than 0
fuel_weight: Fuel weight per gallon must be between 4 and 9 lb fuel_weight: Fuel weight per gallon must be between 4 and 9 lb
flash: flash:
push_subscriptions:
not_saved: "This browser's push service (%{host}) isn't one the app sends to."
unknown_device: Unknown browser
sign_in_links: sign_in_links:
try_again_later: Try again later. try_again_later: Try again later.
try_again_later_2: Try again later. try_again_later_2: Try again later.
@@ -789,6 +793,7 @@ en:
flight_log_deleted: Flight log deleted flight_log_deleted: Flight log deleted
track_unreadable: 'Couldn''t read track: %{message}' track_unreadable: 'Couldn''t read track: %{message}'
engine_data_unreadable: 'Couldn''t read engine data: %{message}' engine_data_unreadable: 'Couldn''t read engine data: %{message}'
next_leg: The next leg starts where it ended.
inspection_records: inspection_records:
inspection_recorded: Inspection recorded. inspection_recorded: Inspection recorded.
inspection_record_updated: Inspection record updated. inspection_record_updated: Inspection record updated.
@@ -800,9 +805,12 @@ en:
added: "%{tail_number} added." added: "%{tail_number} added."
aircraft_updated: Aircraft updated. aircraft_updated: Aircraft updated.
deleted: "%{tail_number} deleted." deleted: "%{tail_number} deleted."
hours_updated: Hours updated (%{delta}). hours_updated: "%{changes}. In-service components moved %{delta} hrs; no flight was logged."
enter_a_valid_tach: Enter a valid tach reading. enter_a_valid_tach: Enter a valid tach reading.
aircraft_details_updated: Aircraft details updated aircraft_details_updated: Aircraft details updated
meter_changed: "%{meter} %{from} → %{to} (%{delta})"
hours_corrected: 'Corrected: %{changes}. In-service components moved %{delta} hrs; no flight was logged.'
hours_unchanged: The readings didn't change.
sso: sso:
try_again_later: Try again later. try_again_later: Try again later.
there_s_no_account: There's no account for %{email} here yet. Ask an administrator to add you, or sign in with your password and link %{provider} from your profile. there_s_no_account: There's no account for %{email} here yet. Ask an administrator to add you, or sign in with your password and link %{provider} from your profile.
@@ -822,6 +830,8 @@ en:
unreachable: couldn't reach or verify %{provider}; see the server log unreachable: couldn't reach or verify %{provider}; see the server log
setup: setup:
welcome_you_re_the: Welcome! You're the administrator. Add your first aircraft. welcome_you_re_the: Welcome! You're the administrator. Add your first aircraft.
wrong_code: That setup code isn't right. It's in the server's log, on the line starting "Setup code".
try_again_later: Too many tries. Wait a few minutes and try again.
invited_signings: invited_signings:
try_again_later: Try again later. try_again_later: Try again later.
sign_in_to_continue: Sign in to continue. sign_in_to_continue: Sign in to continue.
@@ -910,6 +920,7 @@ en:
certificate_removed: Certificate removed. certificate_removed: Certificate removed.
application: application:
admins_only: Admins only. admins_only: Admins only.
invalid_input: Something in that form couldn't be saved. Check what you entered and try again.
oil_analyses: oil_analyses:
oil_analysis_saved: Oil analysis saved. oil_analysis_saved: Oil analysis saved.
choose_a_lab_report: Choose a lab report PDF. choose_a_lab_report: Choose a lab report PDF.
@@ -1687,6 +1698,25 @@ en:
recent_activity: Recent Activity recent_activity: Recent Activity
all: All → all: All →
public: "· public" public: "· public"
setup:
title: Set up %{tail_number}
progress: "%{done} of %{total} done"
hide: Hide
components:
title: Add the components you track
why: 'The engine and propeller, and parts with limits: oil, filters, the ELT battery, magnetos. Flight hours are added to each one.'
inspections:
title: Add the standard inspections
why: 'Annual, 100-hour, transponder, pitot-static, ELT: pick the ones that apply, then record when each was last done.'
ads:
title: Import the ADs from FAA DRS
why: Export the ADs for the aircraft, engine and propeller from drs.faa.gov and upload the file.
documents:
title: Upload the registration and airworthiness certificate
why: With the registration's expiry date, you're reminded before it lapses.
weight_balance:
title: Enter the weight and balance
why: The empty weight and CG from the latest W&B, for the loading calculator.
aircraft_imports: aircraft_imports:
new: new:
import_aircraft: Import Aircraft import_aircraft: Import Aircraft
@@ -1917,7 +1947,6 @@ en:
hours_since_oh_service: Hours since OH / service hours_since_oh_service: Hours since OH / service
overhaul_type: Overhaul type overhaul_type: Overhaul type
for_engines_and_propellers_printed: 'For engines and propellers: printed in logbook entries as SMOH, SFOH or SNEW.' for_engines_and_propellers_printed: 'For engines and propellers: printed in logbook entries as SMOH, SFOH or SNEW.'
limits: Limits
replace_every_hrs: Replace every (hrs) replace_every_hrs: Replace every (hrs)
replace_every: Replace every replace_every: Replace every
replacement_counts_from: Replacement counts from replacement_counts_from: Replacement counts from
@@ -1941,6 +1970,10 @@ en:
last_service: Last service last_service: Last service
none: "— None —" none: "— None —"
save: Save save: Save
replacement_group: Replacement and expiry
replacement_group_hint: "· oil, filters, ELT battery, life-limited parts"
tbo_group: Overhaul and TBO
tbo_group_hint: "· engines and propellers"
index: index:
components: "%{tail_number} Components" components: "%{tail_number} Components"
components_2: Components components_2: Components
@@ -1957,7 +1990,7 @@ en:
tbo_h_html: 'TBO: %{tbo_hours} h%{on_condition}<br>' tbo_h_html: 'TBO: %{tbo_hours} h%{on_condition}<br>'
expires_html: 'Expires: %{expires_on}' expires_html: 'Expires: %{expires_on}'
edit: Edit edit: Edit
service: Service service: Record service
since_installed: " since installed" since_installed: " since installed"
on_condition: " (on condition)" on_condition: " (on condition)"
hide_disposed: Hide disposed hide_disposed: Hide disposed
@@ -2293,6 +2326,8 @@ en:
cgr_30p_cgr_30c_flight: CGR-30P / CGR-30C flight recording (.csv). cgr_30p_cgr_30c_flight: CGR-30P / CGR-30C flight recording (.csv).
saving_adds_the_tach_time: Saving adds the tach time to the aircraft and all in-service components, and records any oil/fuel added. saving_adds_the_tach_time: Saving adds the tach time to the aircraft and all in-service components, and records any oil/fuel added.
cancel: Cancel cancel: Cancel
log_and_next_leg: Save and log next leg
log_and_next_leg_title: Saves this flight and opens the form for the next one, starting where it ended
show: show:
flight_on_html: Flight on %{date} flight_on_html: Flight on %{date}
delete_this_flight_log_aircraft: Delete this flight log? Aircraft and component hours will NOT be rolled back. delete_this_flight_log_aircraft: Delete this flight log? Aircraft and component hours will NOT be rolled back.
@@ -2912,6 +2947,7 @@ en:
profiles: profiles:
edit: edit:
your_profile: Your Profile your_profile: Your Profile
account: Account
email: Email email: Email
weekly_maintenance_reminders: Weekly maintenance reminders weekly_maintenance_reminders: Weekly maintenance reminders
a_monday_email_about_overdue: A Monday email about overdue and upcoming inspections, ADs, parts and documents on aircraft you own, and certificates of yours about to expire. Only sent when something needs attention. a_monday_email_about_overdue: A Monday email about overdue and upcoming inspections, ADs, parts and documents on aircraft you own, and certificates of yours about to expire. Only sent when something needs attention.
@@ -2980,6 +3016,10 @@ en:
notifications_on: Turn on notifications_on: Turn on
notifications_off: Turn off notifications_off: Turn off
notifications_test: Send a test notifications_test: Send a test
time_zone: Time zone
time_zone_automatic: 'Automatic: this device (%{zone})'
time_zone_unknown: not known yet
time_zone_hint: 'How times show and what “today” is, for example a new flight''s date. Now: %{now}. Signatures and the record history always show UTC.'
record_versions: record_versions:
index: index:
record_history: "%{tail_number} Record history" record_history: "%{tail_number} Record history"
@@ -3073,6 +3113,8 @@ en:
new: new:
welcome: Welcome welcome: Welcome
create_the_administrator_account_to: Create the administrator account to get started. create_the_administrator_account_to: Create the administrator account to get started.
setup_code: Setup code
setup_code_hint_html: 'Shown in the server''s log, so only whoever runs the server can finish setup. With Docker: <code>docker compose logs web | grep "Setup code"</code>'
email: Email email: Email
at_least_characters_not_one: At least %{min} characters; not one known from a data breach. at_least_characters_not_one: At least %{min} characters; not one known from a data breach.
simple_aircraft_manager_is_provided: Simple Aircraft Manager is provided as is, without warranty, and is not approved by the FAA or any other aviation authority. It is up to you to verify that using it for your aircraft and operation is legal and suitable. The full disclaimer is under Help once you're signed in. simple_aircraft_manager_is_provided: Simple Aircraft Manager is provided as is, without warranty, and is not approved by the FAA or any other aviation authority. It is up to you to verify that using it for your aircraft and operation is legal and suitable. The full disclaimer is under Help once you're signed in.
@@ -3232,10 +3274,10 @@ en:
photos_files: Photos / files photos_files: Photos / files
report_squawk: Report Squawk report_squawk: Report Squawk
save: Save save: Save
grounding_warning: 'This grounds %{tail_number}: it shows Grounded until the squawk is resolved or deferred, and its owners and pilots who turned on notifications are told.'
index: index:
squawks: "%{tail_number} Squawks" squawks: "%{tail_number} Squawks"
open_squawks: Open Squawks open_squawks: Open Squawks
report_squawk: "+ Report Squawk"
no_open_squawks: No open squawks. no_open_squawks: No open squawks.
resolved: Resolved resolved: Resolved
priority: Priority priority: Priority
@@ -3370,8 +3412,8 @@ en:
notes: Notes notes: Notes
activity: Activity activity: Activity
none: "— None —" none: "— None —"
text: "%{date} – %{truncate}"
w_b: W&B w_b: W&B
entry_option: "%{date} – %{text}"
application: application:
more: More more: More
are_you_sure: Are you sure? are_you_sure: Are you sure?
@@ -3632,8 +3674,11 @@ en:
that_certificate_isn_t_yours: That certificate isn't yours that_certificate_isn_t_yours: That certificate isn't yours
this_entry_can_t_be: 'This entry can''t be signed: %{to_sentence}' this_entry_can_t_be: 'This entry can''t be signed: %{to_sentence}'
text: "%{signer_name}, %{certificate_label} %{certificate_number}" text: "%{signer_name}, %{certificate_label} %{certificate_number}"
signed_event: Logbook entry signed electronically (%{date})
air_trail: air_trail:
can_t_reach_airtrail_at: 'Can''t reach AirTrail at %{host}: %{message}' can_t_reach_airtrail_at: 'Can''t reach AirTrail at %{host}: %{message}'
blocked_never: "%{host} is this server or a link-local address, which AirTrail can't be."
blocked_private: "%{host} is on the private network. Ask an administrator to connect it, or to list it in AIRTRAIL_ALLOWED_HOSTS."
airtrail_username_must_be_3: AirTrail username must be 3–20 letters, numbers, “.”, “_” or “-” airtrail_username_must_be_3: AirTrail username must be 3–20 letters, numbers, “.”, “_” or “-”
aircraft_type_must_be_an: Aircraft type must be an ICAO type designator like C150 (up to 4 letters/numbers) aircraft_type_must_be_an: Aircraft type must be an ICAO type designator like C150 (up to 4 letters/numbers)
no_flights_to_export: No flights to export no_flights_to_export: No flights to export
@@ -3843,8 +3888,19 @@ en:
blocked: Notifications are blocked for this site in the browser's settings. blocked: Notifications are blocked for this site in the browser's settings.
unsupported: This browser can't show notifications from the app. unsupported: This browser can't show notifications from the app.
ios_install_first: On iPhone and iPad, install the app first (above); notifications can then be turned on in it. ios_install_first: On iPhone and iPad, install the app first (above); notifications can then be turned on in it.
failed: Couldn't turn notifications on. Try again. failed: "Couldn't turn notifications on: %{reason}"
test_sent: Test notification sent; it should arrive in a few seconds. not_saved: "Notifications are on in this browser, but the app couldn't record it: %{reason}"
test_sending: Sending…
test_none: No device has notifications on. Turn them on again here.
test_ok: "%{device}: sent"
test_failed: "%{device}: not sent (%{reason})"
test_hint: Sent ones should arrive within a few seconds. If this device's doesn't, check that notifications are allowed for the app in the phone's settings.
hours:
tach: Tach %{from} → %{to} (%{delta})
hobbs: Hobbs %{from} → %{to} (%{delta})
effect: Every in-service component's hours change by the same amount, and no flight is logged. To record a flight, use Log Flight instead.
lower: 'This lowers the reading: use it only to correct a mistake.'
no_change: 'These are the current readings: nothing to update.'
counts: counts:
problem: problem:
one: "%{count} problem" one: "%{count} problem"
+9 -7
View File
@@ -9,28 +9,30 @@
# priority: 2 # priority: 2
# schedule: at 5am every day # schedule: at 5am every day
# Times are in the installation's time zone (TZ, default UTC).
<% zone = ActiveSupport::TimeZone[ENV["TZ"].to_s]&.tzinfo&.identifier || "UTC" %>
production: production:
clear_solid_queue_finished_jobs: clear_solid_queue_finished_jobs:
command: "SolidQueue::Job.clear_finished_in_batches(sleep_between_batches: 0.3)" command: "SolidQueue::Job.clear_finished_in_batches(sleep_between_batches: 0.3)"
schedule: every hour at minute 12 schedule: every hour at minute 12
purge_abandoned_uploads: purge_abandoned_uploads:
command: "ActiveStorage::Blob.unattached.where(created_at: ..2.days.ago).find_each(&:purge_later)" command: "ActiveStorage::Blob.unattached.where(created_at: ..2.days.ago).find_each(&:purge_later)"
schedule: every day at 4am schedule: every day at 4am <%= zone %>
dedupe_storage: dedupe_storage:
command: "ActiveStorage::Blob.service.try(:sweep)" command: "ActiveStorage::Blob.service.try(:sweep)"
schedule: every day at 4:30am schedule: every day at 4:30am <%= zone %>
weekly_reminders: weekly_reminders:
class: WeeklyReminderJob class: WeeklyReminderJob
schedule: every monday at 12pm schedule: every monday at 12pm <%= zone %>
ad_watch: ad_watch:
class: AdWatchJob class: AdWatchJob
schedule: every sunday at 10am schedule: every sunday at 10am <%= zone %>
document_text: document_text:
class: DocumentTextJob class: DocumentTextJob
schedule: every day at 2am schedule: every day at 2am <%= zone %>
overdue_notifications: overdue_notifications:
class: OverdueNotificationJob class: OverdueNotificationJob
schedule: every day at 7am schedule: every day at 7am <%= zone %>
records_integrity: records_integrity:
class: RecordsIntegrityJob class: RecordsIntegrityJob
schedule: every day at 3:30am schedule: every day at 3:30am <%= zone %>
@@ -0,0 +1,6 @@
class AddTimeZoneToUsers < ActiveRecord::Migration[8.1]
def change
# The user's time zone for showing times; blank follows their device.
add_column :users, :time_zone, :string
end
end
Generated
+2 -1
View File
@@ -10,7 +10,7 @@
# #
# It's strongly recommended that you check this file into your version control system. # It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.1].define(version: 2026_11_13_010000) do ActiveRecord::Schema[8.1].define(version: 2026_11_14_010000) do
create_table "active_storage_attachments", force: :cascade do |t| create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false t.string "name", null: false
t.string "record_type", null: false t.string "record_type", null: false
@@ -837,6 +837,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_13_010000) do
t.integer "otp_last_used_at" t.integer "otp_last_used_at"
t.json "otp_recovery_codes" t.json "otp_recovery_codes"
t.string "calendar_token" t.string "calendar_token"
t.string "time_zone"
t.index ["calendar_token"], name: "index_users_on_calendar_token", unique: true t.index ["calendar_token"], name: "index_users_on_calendar_token", unique: true
t.index ["email_address"], name: "index_users_on_email_address", unique: true t.index ["email_address"], name: "index_users_on_email_address", unique: true
t.index ["sso_uid"], name: "index_users_on_sso_uid", unique: true t.index ["sso_uid"], name: "index_users_on_sso_uid", unique: true
+33
View File
@@ -0,0 +1,33 @@
# Directly on the internet, with HTTPS and no proxy in front: the image's web
# server (Thruster) gets and renews a Let's Encrypt certificate by itself.
#
# 1. Point a DNS name (A/AAAA record) at this server, and open ports 80 and
# 443 to it (80 is needed for the certificate check and redirects).
# 2. In .env: APP_HOST and TLS_DOMAIN set to that name, FORCE_SSL=true, and
# a SECRET_KEY_BASE from `bin/rails secret`.
# 3. docker compose -f docker-compose.direct.yml up -d
# 4. Open https://<name>, and create the admin account with the setup code
# from: docker compose -f docker-compose.direct.yml logs web | grep "Setup code"
#
# The certificate is kept in the storage volume, so it isn't requested again
# on every start.
services:
web:
image: barrettefab/simple-aircraft-manager-rails:latest # or your own image, or: build: .
restart: unless-stopped
ports:
- "80:80"
- "443:443"
env_file: .env
environment:
SOLID_QUEUE_IN_PUMA: "true" # nightly backup, reminders and AD search run in the web process
FORCE_SSL: "true"
volumes:
- sam_storage:/rails/storage # databases, uploaded files, nightly backups and the certificate: back this up
healthcheck:
test: ["CMD", "curl", "-fsS", "http://localhost/up"]
interval: 30s
timeout: 5s
retries: 3
volumes:
sam_storage:
+1 -1
View File
@@ -103,7 +103,7 @@ Run on the server like the account recovery commands (`docker compose exec web`
| Command | What it does | | Command | What it does |
|---|---| |---|---|
| `bin/rails sam:doctor` | Health report: secret key, address, HTTPS, email (SMTP reachable), single sign-on (issuer reachable), Google Drive, migrations, disk space, background jobs, and how recent the backup, records check, off-site copy, procedures and audit are. Exits non-zero if something fails | | `bin/rails sam:doctor` | Health report: secret key (set and long enough), address, HTTPS, email (SMTP reachable), single sign-on (issuer reachable), Google Drive, migrations, disk space, background jobs, and how recent the backup, records check, off-site copy, procedures and audit are. Exits non-zero if something fails |
| `bin/rails records:check` | Backs up the database now and checks the record history and every signature; prints any problems and exits non-zero | | `bin/rails records:check` | Backs up the database now and checks the record history and every signature; prints any problems and exits non-zero |
| `bin/rails backups:list` | Lists the nightly database copies | | `bin/rails backups:list` | Lists the nightly database copies |
| `bin/rails "backups:restore[file]"` | Replaces the database with a backup (newest nightly copy if no file; a Google Drive `.sqlite3.gz` works too). The app must be stopped: `docker compose stop web`, then `docker compose run --rm web bin/rails backups:restore`. The current database is moved to `storage/pre-restore-…`, never deleted. `CONFIRM=yes` skips the question | | `bin/rails "backups:restore[file]"` | Replaces the database with a backup (newest nightly copy if no file; a Google Drive `.sqlite3.gz` works too). The app must be stopped: `docker compose stop web`, then `docker compose run --rm web bin/rails backups:restore`. The current database is moved to `storage/pre-restore-…`, never deleted. `CONFIRM=yes` skips the question |
+1 -1
View File
@@ -12,7 +12,7 @@ If you've set up an authenticator app (see [Your profile](profile.md#two-factor-
After 10 failed tries in a row (wrong passwords or codes), an account is locked for 15 minutes and its owner is emailed. Wait, or ask the administrator to unlock it. After 10 failed tries in a row (wrong passwords or codes), an account is locked for 15 minutes and its owner is emailed. Wait, or ask the administrator to unlock it.
The very first visit to a new installation asks for the administrator account instead. The very first visit to a new installation asks for the administrator account instead. It also asks for a one-time setup code, which is printed only in the server's log (the line starting `Setup code`; with Docker, `docker compose logs web | grep "Setup code"`), so only whoever runs the server can create that account.
## Roles ## Roles
+4
View File
@@ -8,6 +8,8 @@ Change your name, email and password. Leave the password blank to keep the curre
**Weekly maintenance reminders**: on Mondays the app emails owners about anything overdue or coming due on their aircraft, and certificates about to expire. Untick it to stop them. (Emails need the administrator to have set up email.) **Weekly maintenance reminders**: on Mondays the app emails owners about anything overdue or coming due on their aircraft, and certificates about to expire. Untick it to stop them. (Emails need the administrator to have set up email.)
**Time zone** is *Automatic* by default: times show in your device's zone, and "today" (for example a new flight's date) is your local date. Choose a zone to use it on every device. Signatures and the record history always show UTC.
## Two-factor sign-in ## Two-factor sign-in
**Set up** adds a code from an authenticator app on your phone (Google Authenticator, Microsoft Authenticator, 1Password, Authy…) to password and emailed-link sign-in, so a stolen password alone can't get in. It also asks for the code when you sign a logbook entry with your password. **Set up** adds a code from an authenticator app on your phone (Google Authenticator, Microsoft Authenticator, 1Password, Authy…) to password and emailed-link sign-in, so a stolen password alone can't get in. It also asks for the code when you sign a logbook entry with your password.
@@ -53,3 +55,5 @@ Turn it on on each phone or computer you want them on; **Send a test** checks it
## Integrations: AirTrail ## Integrations: AirTrail
**AirTrail sync** pushes the flights you log to your AirTrail flight map, with their GPS tracks. In AirTrail, create an API key (Settings → Security) with the scopes shown, then paste your AirTrail address and key here. A full sync first links flights already in AirTrail, so nothing is duplicated. If an airport code can't be matched, enter the code AirTrail uses for it. **AirTrail sync** pushes the flights you log to your AirTrail flight map, with their GPS tracks. In AirTrail, create an API key (Settings → Security) with the scopes shown, then paste your AirTrail address and key here. A full sync first links flights already in AirTrail, so nothing is duplicated. If an airport code can't be matched, enter the code AirTrail uses for it.
If your AirTrail server is on your private network (an address like 192.168.x.x or 10.x.x.x), only an administrator can connect to it, unless the administrator lists it in `AIRTRAIL_ALLOWED_HOSTS`. This stops accounts from using the app to probe the private network. The app's own server and link-local addresses can't be used at all.
@@ -44,7 +44,7 @@ class ElectronicSignaturesTest < ActionDispatch::IntegrationTest
assert_equal [ @entry.content_digest, :valid ], [ sig.content_digest, sig.status ] assert_equal [ @entry.content_digest, :valid ], [ sig.content_digest, sig.status ]
assert_equal "Replaced left landing light lamp P/N 4509.", JSON.parse(sig.content_snapshot)["text"] assert_equal "Replaced left landing light lamp P/N 4509.", JSON.parse(sig.content_snapshot)["text"]
assert_equal "You signed a logbook entry for N12345", ActionMailer::Base.deliveries.last.subject assert_equal "You signed a logbook entry for N12345", ActionMailer::Base.deliveries.last.subject
assert_equal "Logbook entry signed electronically (2026-10-01)", @a.events.last.event_name assert_equal "Logbook entry signed electronically (Oct 1, 2026)", @a.events.last.event_name
get aircraft_logbook_entry_path(@a, @entry) get aircraft_logbook_entry_path(@a, @entry)
assert_includes response.body, "Certified by Sam Mechanic, A&amp;P 7654321" assert_includes response.body, "Certified by Sam Mechanic, A&amp;P 7654321"
@@ -0,0 +1,84 @@
require "test_helper"
# Protections for an installation reachable from the internet with nothing in
# front of it: secret key strength, the setup code, the AirTrail address check
# and the allowed host names.
class InternetExposureTest < ActionDispatch::IntegrationTest
test "a placeholder or short secret key is refused; one shorter than recommended is weak" do
assert_equal :unsafe, SecretKeyCheck.strength("change-me")
assert_equal :unsafe, SecretKeyCheck.strength("x")
assert_equal :unsafe, SecretKeyCheck.strength("a" * 80)
assert_equal :weak, SecretKeyCheck.strength(SecureRandom.hex(20))
assert_equal :ok, SecretKeyCheck.strength(SecureRandom.hex(64))
end
test "the setup code is required, shown only in the log, and used up" do
SetupCode.clear
logged = capture_log { get new_setup_path }
assert_match(/Setup code: #{Regexp.escape(SetupCode.current)}/, logged)
assert_no_match SetupCode.current, response.body
end
test "AirTrail can't be pointed at the server itself or link-local addresses, nor the private network by non-admins" do
{ "http://127.0.0.1:8080" => :never, "http://169.254.169.254" => :never, "http://[::1]" => :never,
"http://10.0.0.5" => :private, "http://192.168.1.20:3000" => :private, "http://100.100.1.1" => :private }.each do |url, reason|
error = assert_raises(AirTrailClient::BlockedAddress, url) { AirTrailClient.new(base_url: url, api_key: "k").me }
assert_match(reason == :never ? "link-local" : "private network", error.message)
end
end
test "admins and listed hosts may use private addresses, but never the server itself" do
stub_request(:get, "http://192.168.1.20:3000/api/v1/me").to_return(status: 200, body: { data: { username: "u" } }.to_json)
assert_equal "u", AirTrailClient.new(base_url: "http://192.168.1.20:3000", api_key: "k", allow_private: true).me["username"]
assert_raises(AirTrailClient::BlockedAddress) { AirTrailClient.new(base_url: "http://127.0.0.1", api_key: "k", allow_private: true).me }
with_env("AIRTRAIL_ALLOWED_HOSTS" => "airtrail.lan") do
resolving_to("192.168.1.30") do
stub_request(:get, "http://airtrail.lan/api/v1/me").to_return(status: 200, body: { data: { username: "v" } }.to_json)
assert_equal "v", AirTrailClient.new(base_url: "http://airtrail.lan", api_key: "k").me["username"]
end
end
end
test "a name that resolves to a private address is checked by its address" do
resolving_to("203.0.113.5", "10.1.2.3") do
assert_raises(AirTrailClient::BlockedAddress) { AirTrailClient.new(base_url: "https://rebind.example.com", api_key: "k").me }
end
end
test "a non-admin's connection to a private address is refused with a reason" do
pilot = create_user
sign_in pilot
post air_trail_connection_path, params: { air_trail_connection: { base_url: "http://192.168.1.20", api_key: "k" } }
follow_redirect! if response.redirect?
assert_match "private network", flash[:alert].to_s + response.body
end
private
def resolving_to(*ips)
old = AirTrailClient.resolver
AirTrailClient.resolver = ->(_) { ips }
yield
ensure
AirTrailClient.resolver = old
end
def with_env(vars)
old = vars.keys.to_h { [ _1, ENV[_1] ] }
vars.each { ENV[_1] = _2 }
yield
ensure
old.each { ENV[_1] = _2 }
end
def capture_log
io = StringIO.new
logger = ActiveSupport::Logger.new(io)
old, Rails.logger = Rails.logger, logger
yield
io.string
ensure
Rails.logger = old
end
end
+2 -2
View File
@@ -61,7 +61,7 @@ class LogbookEntryPartsTest < ActionDispatch::IntegrationTest
# dated to the entry; the 10 hours flown since the entry carry over # dated to the entry; the 10 hours flown since the entry carry over
assert_equal [ Date.new(2026, 8, 20), 10.0, 120.5 ], [ @filter.overhaul_date, @filter.hours_since_overhaul.to_f, @filter.hours_in_service.to_f ] assert_equal [ Date.new(2026, 8, 20), 10.0, 120.5 ], [ @filter.overhaul_date, @filter.hours_since_overhaul.to_f, @filter.hours_in_service.to_f ]
assert_equal [ 10.0, 10.0, Date.new(2026, 8, 20) ], [ oil.hours_since_overhaul.to_f, oil.hours_in_service.to_f, oil.date_in_service ] assert_equal [ 10.0, 10.0, Date.new(2026, 8, 20) ], [ oil.hours_since_overhaul.to_f, oil.hours_in_service.to_f, oil.date_in_service ]
assert @a.events.exists?(event_name: "Replaced: #{oil} (logbook entry 2026-08-20)") assert @a.events.exists?(event_name: "Replaced: #{oil} (logbook entry Aug 20, 2026)")
entry = @a.logbook_entries.last # editing doesn't offer it again (it would apply twice) entry = @a.logbook_entries.last # editing doesn't offer it again (it would apply twice)
get edit_aircraft_logbook_entry_path(@a, entry) get edit_aircraft_logbook_entry_path(@a, entry)
@@ -84,7 +84,7 @@ class LogbookEntryPartsTest < ActionDispatch::IntegrationTest
entry = @a.logbook_entries.sole entry = @a.logbook_entries.sole
record = @a.inspection_records.sole record = @a.inspection_records.sole
assert_equal [ oil_change, entry, Date.new(2026, 8, 20), 4200.3 ], [ record.inspection_type, record.logbook_entry, record.date, record.aircraft_hours.to_f ] assert_equal [ oil_change, entry, Date.new(2026, 8, 20), 4200.3 ], [ record.inspection_type, record.logbook_entry, record.date, record.aircraft_hours.to_f ]
assert @a.events.exists?(event_name: "Inspection completed: Oil Change (logbook entry 2026-08-20)") assert @a.events.exists?(event_name: "Inspection completed: Oil Change (logbook entry Aug 20, 2026)")
get edit_aircraft_logbook_entry_path(@a, entry) # not offered again on edit (it would record twice) get edit_aircraft_logbook_entry_path(@a, entry) # not offered again on edit (it would record twice)
assert_select "input[name='logbook_entry[inspection_type_ids][]']", 0 assert_select "input[name='logbook_entry[inspection_type_ids][]']", 0
+98
View File
@@ -0,0 +1,98 @@
require "test_helper"
# Requests no form sends, found by fuzzing: each used to be a server error.
class MalformedInputTest < ActionDispatch::IntegrationTest
setup do
@owner = create_user("owner@example.com")
@a = create_aircraft(owner: @owner)
sign_in @owner
end
test "a page in a format it doesn't have is 'not acceptable', not an error" do
%w[pdf json csv zip xml].each do |ext|
get "/aircraft/#{@a.id}/report.#{ext}"
assert_response :not_acceptable, ext
end
end
test "parts can't be made into a loop, and an existing loop doesn't break the pages" do
engine = @a.components.create!(component_type: ComponentType.create!(name: "Engine"), manufacturer: "L", model: "O-320", date_in_service: Date.current)
mag = @a.components.create!(component_type: ComponentType.create!(name: "Magneto"), manufacturer: "S", model: "4370", date_in_service: Date.current, parent_component: engine)
patch aircraft_component_path(@a, engine), params: { component: { parent_component_id: mag.id } }
assert_response :unprocessable_entity
assert_nil engine.reload.parent_component_id
engine.update_column(:parent_component_id, mag.id) # as if made before the check existed
assert_equal [ mag.id ], engine.reload.ancestor_ids
assert_equal [ mag.id ], engine.descendant_ids
get new_aircraft_logbook_entry_path(@a)
assert_response :success
end
test "a link to a record that doesn't exist is a validation error" do
part = @a.components.create!(component_type: ComponentType.create!(name: "Alternator"), manufacturer: "P", model: "ALX", date_in_service: Date.current)
patch aircraft_component_path(@a, part), params: { component: { parent_component_id: 999_999 } }
assert_response :unprocessable_entity
end
test "a blank required checkbox or number takes its default" do
post aircraft_notes_path(@a), params: { aircraft_note: { text: "Blank public", public: "" } }
assert_equal false, @a.notes.last.public
end
test "text where a file belongs, or a tampered upload reference, is turned away politely" do
post import_aircraft_oil_analyses_path(@a), params: { report: "not a file" }
assert_redirected_to new_aircraft_oil_analysis_path(@a)
post aircraft_imports_path, params: { archive: "not a file" }
assert_redirected_to new_aircraft_import_path
post aircraft_logbook_imports_path(@a), params: { pages: [ "not a file" ] }
assert_redirected_to new_aircraft_logbook_import_path(@a)
post aircraft_squawks_path(@a), params: { squawk: { issue_reported: "Leak", attachments: [ "eyJfcmFpbHMiOnt9fQ==--forged" ] } }
assert_response :redirect
assert_equal "Something in that form couldn't be saved. Check what you entered and try again.", flash[:alert]
end
test "a null byte is refused up front" do
post aircraft_notes_path(@a), params: { aircraft_note: { text: "a\u0000b" } }
assert_response :bad_request
assert_equal 0, @a.notes.count
end
test "a number too big to store is turned away politely" do
admin = create_user("admin@example.com", admin: true)
sign_in admin
template = LogbookTemplate.create!(name: "T", log_type: "AC", entry_type: "MAINTENANCE", text: "x")
patch admin_logbook_template_path(template), params: { logbook_template: { position: "9" * 40 } }
assert_response :redirect
assert_match "couldn't be saved", flash[:alert]
end
test "a rejected photo shows the form's error, not a server error" do
patch aircraft_path(@a), params: { aircraft: { picture: Rack::Test::UploadedFile.new(StringIO.new("<html>not a photo</html>"), "text/html", original_filename: "photo.html") } }
assert_response :unprocessable_entity
patch aircraft_path(@a), params: { aircraft: { picture: Rack::Test::UploadedFile.new(StringIO.new(""), "image/jpeg", original_filename: "empty.jpg") } }
assert_response :unprocessable_entity
end
test "photos measured without dimensions (uploaded before image processing) still get thumbnails" do
jpeg = Vips::Image.black(400, 300).jpegsave_buffer
@a.picture.attach(io: StringIO.new(jpeg), filename: "old.jpg", content_type: "image/jpeg")
@a.picture.blob.update!(metadata: { identified: true, analyzed: true }) # as older uploads were recorded
get aircraft_path(@a)
assert_select "img[src*='/representations/']"
squawk = @a.squawks.create!(issue_reported: "Leak", reported_by: @owner)
squawk.attachments.attach(io: StringIO.new(jpeg), filename: "PXL_1.jpg", content_type: "image/jpeg")
squawk.attachments.first.blob.update!(metadata: { identified: true, analyzed: true })
get aircraft_squawks_path(@a)
assert_select "a[data-gallery-target=item] img[src*='/representations/']"
end
test "if resizing a photo fails anyway, the original is sent instead of an error" do
@a.picture.attach(io: StringIO.new("GIF89a not really"), filename: "broken.gif", content_type: "image/gif")
get url_for(@a.picture.variant(:thumb))
assert_response :redirect
assert_match %r{/rails/active_storage/blobs/redirect/}, response.location
end
end
+8
View File
@@ -43,4 +43,12 @@ class MoreMenuTest < ActionDispatch::IntegrationTest
assert_select "span[title='Your access to this aircraft']", "Owner" assert_select "span[title='Your access to this aircraft']", "Owner"
assert_select "span.badge-green", text: "Available", count: 0 assert_select "span.badge-green", text: "Available", count: 0
end end
test "the description keeps its paragraphs inside the Details card" do
@a.update!(description: "First line.\n\nSecond paragraph.")
sign_in @owner
get aircraft_path(@a)
# simple_format makes <p>s, so the box around them must not be a <p> (they'd spill out of it).
assert_select "div.border-t > p", 2
end
end end
+1 -1
View File
@@ -26,7 +26,7 @@ class OilAnalysisFlowTest < ActionDispatch::IntegrationTest
latest = @aircraft.oil_analyses.recent_first.first latest = @aircraft.oil_analyses.recent_first.first
assert_redirected_to aircraft_oil_analysis_path(@aircraft, latest) assert_redirected_to aircraft_oil_analysis_path(@aircraft, latest)
assert latest.report.attached? assert latest.report.attached?
assert_equal [ "Oil analysis added (sampled 2026-08-01)" ], @aircraft.events.where(category: "oil_analysis").limit(1).pluck(:event_name) assert_equal [ "Oil analysis added (sampled Aug 1, 2026)" ], @aircraft.events.where(category: "oil_analysis").limit(1).pluck(:event_name)
get aircraft_oil_analyses_path(@aircraft) get aircraft_oil_analyses_path(@aircraft)
assert_response :success assert_response :success
+46 -9
View File
@@ -31,6 +31,20 @@ class PwaFeaturesTest < ActionDispatch::IntegrationTest
assert_select "form[action='#{session_path}'][data-controller=sign-out]", minimum: 1 assert_select "form[action='#{session_path}'][data-controller=sign-out]", minimum: 1
end end
test "updating the meters without a flight asks for confirmation, showing the change" do
sign_in @owner
get aircraft_path(@a)
assert_select "form[action='#{hours_aircraft_path(@a)}'][data-controller=hours-confirm][data-action='submit->hours-confirm#confirm'][data-hours-confirm-tach-value='1000.0']" do
assert_select "input[name=tach_time][data-hours-confirm-target=tach]"
assert_select "input[name=hobbs_time][data-hours-confirm-target=hobbs]"
end
patch hours_aircraft_path(@a), params: { tach_time: "1001.4", hobbs_time: "1.2" }
assert_equal "Tach 1,000.0 → 1,001.4 (+1.4) · Hobbs 0.0 → 1.2 (+1.2). In-service components moved +1.4 hrs; no flight was logged.", flash[:notice]
patch hours_aircraft_path(@a), params: { tach_time: "1001.0" }
assert_equal "Corrected: Tach 1,001.4 → 1,001.0 (−0.4). In-service components moved −0.4 hrs; no flight was logged.", flash[:notice]
end
test "every page lists what to save ahead of time for working offline: each of your aircraft's forms and pages" do test "every page lists what to save ahead of time for working offline: each of your aircraft's forms and pages" do
other = create_aircraft(tail_number: "N99999") # not this pilot's other = create_aircraft(tail_number: "N99999") # not this pilot's
sign_in @pilot sign_in @pilot
@@ -43,18 +57,20 @@ class PwaFeaturesTest < ActionDispatch::IntegrationTest
@a.picture.attach(io: StringIO.new(file_fixture_png), filename: "plane.png", content_type: "image/png") @a.picture.attach(io: StringIO.new(file_fixture_png), filename: "plane.png", content_type: "image/png")
get root_path get root_path
picture = JSON.parse(css_select("body").first["data-offline-prep-aircraft-value"]).first["picture"] pictures = JSON.parse(css_select("body").first["data-offline-prep-aircraft-value"]).first["pictures"]
shown = css_select("img[src*='/rails/active_storage/blobs/redirect/']").first["src"] shown = css_select("img[src*='/rails/active_storage/representations/redirect/']").first["src"]
# Links expire, so they differ; both carry the same upload id, which the saved copy is filed under. # Links expire, so they differ; both carry the same upload id and size,
blob_id = ->(url) { JSON.parse(Base64.decode64(CGI.unescape(url[%r{/blobs/redirect/([^/]+?)--}, 1])))["_rails"]["data"] } # which the saved copy is filed under (the thumbnail and the Fleet card).
assert_equal @a.picture.blob.id, blob_id.(picture) key = ->(url) { url.match(%r{/representations/redirect/([^/]+?)--[^/]+/([^/]+)/}).then { [ JSON.parse(Base64.decode64(CGI.unescape(_1[1])))["_rails"]["data"], _1[2] ] } }
assert_equal @a.picture.blob.id, blob_id.(shown) assert_equal 2, pictures.size
assert_equal [ @a.picture.blob.id ], pictures.map { key.(_1).first }.uniq
assert_includes pictures.map(&key), key.(shown)
end end
test "squawks can be reported offline and are received once" do test "squawks can be reported offline and are received once" do
sign_in @pilot sign_in @pilot
get new_aircraft_squawk_path(@a) get new_aircraft_squawk_path(@a)
assert_select "form[data-controller=offline-form][data-offline-form-kind-value=squawk][data-offline-form-tail-value=N12345]" assert_select "form[data-controller~=offline-form][data-offline-form-kind-value=squawk][data-offline-form-tail-value=N12345]"
assert_select "input[type=hidden][name='squawk[client_key]']" assert_select "input[type=hidden][name='squawk[client_key]']"
params = { squawk: { priority: 1, issue_reported: "Left landing light inop", client_key: "sq-1" } } params = { squawk: { priority: 1, issue_reported: "Left landing light inop", client_key: "sq-1" } }
@@ -64,7 +80,7 @@ class PwaFeaturesTest < ActionDispatch::IntegrationTest
get edit_aircraft_squawk_path(@a, @a.squawks.last) # pilots can't edit; owners' edit form isn't queued get edit_aircraft_squawk_path(@a, @a.squawks.last) # pilots can't edit; owners' edit form isn't queued
sign_in @owner sign_in @owner
get edit_aircraft_squawk_path(@a, @a.squawks.last) get edit_aircraft_squawk_path(@a, @a.squawks.last)
assert_select "form[data-controller=offline-form]", count: 0 assert_select "form[data-controller~=offline-form]", count: 0
end end
test "home-screen shortcuts open the form for your only aircraft, or let you choose" do test "home-screen shortcuts open the form for your only aircraft, or let you choose" do
@@ -107,13 +123,34 @@ class PwaFeaturesTest < ActionDispatch::IntegrationTest
assert_response :created assert_response :created
post push_subscription_path, params: { subscription: subscription_params("https://internal.example.com/b") }, as: :json post push_subscription_path, params: { subscription: subscription_params("https://internal.example.com/b") }, as: :json
assert_response :unprocessable_entity assert_response :unprocessable_entity
assert_includes response.parsed_body["error"], "internal.example.com"
assert_equal [ "https://fcm.googleapis.com/fcm/send/a" ], @owner.push_subscriptions.pluck(:endpoint) assert_equal [ "https://fcm.googleapis.com/fcm/send/a" ], @owner.push_subscriptions.pluck(:endpoint)
assert_enqueued_with(job: PushNotificationJob) { post test_push_subscription_path, as: :json }
delete push_subscription_path, params: { endpoint: "https://fcm.googleapis.com/fcm/send/a" }, as: :json delete push_subscription_path, params: { endpoint: "https://fcm.googleapis.com/fcm/send/a" }, as: :json
assert_empty @owner.push_subscriptions.reload assert_empty @owner.push_subscriptions.reload
end end
test "the test notification is sent now and says which devices took it" do
sign_in @owner
ok = subscribe(@owner, "https://fcm.googleapis.com/fcm/send/phone")
ok.update!(user_agent: "Mozilla/5.0 (Linux; Android 16; Pixel) AppleWebKit/537.36 Chrome/142.0 Mobile Safari/537.36")
refused = subscribe(@owner, "https://web.push.apple.com/tablet")
refused.update!(user_agent: "Mozilla/5.0 (iPad; CPU OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Safari/604.1")
stub_request(:post, ok.endpoint).to_return(status: 201)
stub_request(:post, refused.endpoint).to_return(status: 400, body: "BadJwtToken")
post test_push_subscription_path, as: :json
devices = response.parsed_body["devices"]
assert_equal [ "Chrome · Android", nil ], devices.first.values_at("device", "error")
assert_equal "Safari · iPad", devices.last["device"]
assert_match "BadJwtToken", devices.last["error"]
end
test "Google's other push hosts are accepted" do
assert subscribe(@owner, "https://jmt17.google.com/fcm/send/x").persisted?
assert subscribe(@owner, "https://fcm.googleapis.com/wp/y").persisted?
end
test "notifications are encrypted to each device; gone devices are forgotten" do test "notifications are encrypted to each device; gone devices are forgotten" do
live = subscribe(@pilot, "https://fcm.googleapis.com/fcm/send/live") live = subscribe(@pilot, "https://fcm.googleapis.com/fcm/send/live")
gone = subscribe(@pilot, "https://fcm.googleapis.com/fcm/send/gone") gone = subscribe(@pilot, "https://fcm.googleapis.com/fcm/send/gone")
+1 -1
View File
@@ -51,7 +51,7 @@ class RecordsIntegrityTest < ActionDispatch::IntegrationTest
RecordVersion.where(id: victim.id).delete_all RecordVersion.where(id: victim.id).delete_all
check = RecordsIntegrity.check! check = RecordsIntegrity.check!
refute check.ok refute check.ok
assert(check.problems.any? { _1.include?("the 2026-10-01 logbook entry (signed by Sam Mechanic) changed after it was signed") }) assert(check.problems.any? { _1.include?("the Oct 1, 2026 logbook entry (signed by Sam Mechanic) changed after it was signed") })
assert(check.problems.any? { _1.include?("doesn't follow the one before it") || _1.include?("missing") } || RecordVersion.where(aircraft_id: other.id).count.zero?) assert(check.problems.any? { _1.include?("doesn't follow the one before it") || _1.include?("missing") } || RecordVersion.where(aircraft_id: other.id).count.zero?)
RecordVersion.where(aircraft_id: @a.id).last.then { RecordVersion.where(id: _1.id).update_all(payload: _1.payload.sub("Changed oil", "Changed gas")) } RecordVersion.where(aircraft_id: @a.id).last.then { RecordVersion.where(id: _1.id).update_all(payload: _1.payload.sub("Changed oil", "Changed gas")) }
+11 -2
View File
@@ -1,11 +1,20 @@
require "test_helper" require "test_helper"
class SetupTest < ActionDispatch::IntegrationTest class SetupTest < ActionDispatch::IntegrationTest
test "first run creates admin, then setup is closed" do test "first run creates admin with the code from the server log, then setup is closed" do
get root_path get root_path
assert_redirected_to new_setup_path assert_redirected_to new_setup_path
post setup_path, params: { user: { name: "Jane", email_address: "a@b.com", password: "test-password-123", password_confirmation: "test-password-123" } } get new_setup_path
assert_select "input[name=setup_code]"
admin = { name: "Jane", email_address: "a@b.com", password: "test-password-123", password_confirmation: "test-password-123" }
post setup_path, params: { user: admin, setup_code: "AAAA-AAAA" }
assert_response :unprocessable_entity
assert_not User.exists?
post setup_path, params: { user: admin, setup_code: SetupCode.current.downcase.delete("-") } # forgiving about case and the dash
assert_redirected_to root_path assert_redirected_to root_path
assert_not SetupCode.file.exist?, "the code is used up"
assert User.last.admin? assert User.last.admin?
get new_setup_path get new_setup_path
assert_redirected_to root_path assert_redirected_to root_path
+21 -7
View File
@@ -20,26 +20,40 @@ class SquawkAttachmentsTest < ActionDispatch::IntegrationTest
get aircraft_squawks_path(@a) get aircraft_squawks_path(@a)
assert_select "[data-controller=gallery]" do assert_select "[data-controller=gallery]" do
assert_select "a[data-gallery-target=item][data-action='gallery#open'][href*='front.jpg']", text: /🖼/ assert_select "a[data-gallery-target=item][data-action='gallery#open'][href*='front.jpg'] img[alt='front.jpg'][loading=lazy][src*='/representations/']"
assert_select "a[data-gallery-target=item]", 1 # only photos open in the viewer assert_select "a[data-gallery-target=item]", 1 # only photos open in the viewer
assert_select "a[target=_blank][href*='notes.txt']", text: /📎/ assert_select "a[target=_blank][href*='notes.txt']", text: /📎/
assert_select "dialog[data-gallery-target=dialog] a[data-gallery-target=download]" assert_select "dialog[data-gallery-target=dialog] a[data-gallery-target=download]"
end end
end end
test "every file has a download link that forces a download" do test "every file can be downloaded: other files from their link, photos from the viewer" do
@a.squawks.create!(priority: 1, issue_reported: "x", attachments: [ upload("pic.png", "image/png"), upload("log.pdf", "application/pdf") ]) @a.squawks.create!(priority: 1, issue_reported: "x", attachments: [ upload("pic.png", "image/png", png), upload("log.pdf", "application/pdf") ])
sign_in @pilot sign_in @pilot
get aircraft_squawks_path(@a) get aircraft_squawks_path(@a)
downloads = css_select("a[download]").reject { _1["data-gallery-target"] } downloads = css_select("a[download]").reject { _1["data-gallery-target"] }.map { _1["href"] }
assert_equal %w[log.pdf pic.png], downloads.map { _1["download"] }.sort downloads << css_select("a[data-gallery-target=item]").sole["data-gallery-download"]
downloads.each do |link| assert_equal 2, downloads.size
get link["href"] downloads.each do |href|
get href
follow_redirect! while response.redirect? follow_redirect! while response.redirect?
assert_match(/\Aattachment;/, response.headers["Content-Disposition"]) assert_match(/\Aattachment;/, response.headers["Content-Disposition"])
end end
end end
test "photo thumbnails are small resized copies" do
@a.squawks.create!(priority: 1, issue_reported: "x", attachments: [ upload("pic.png", "image/png", png) ])
sign_in @pilot
get aircraft_squawks_path(@a)
get css_select("a[data-gallery-target=item] img").sole["src"]
follow_redirect! while response.redirect?
assert_response :success
assert_equal [ 160, 160 ], Vips::Image.new_from_buffer(response.body, "").then { [ _1.width, _1.height ] }
end
# A 200 × 120 PNG (made when first needed: libvips must not start before the test processes fork).
def png = @png ||= Vips::Image.black(200, 120).write_to_buffer(".png")
test "squawks with no photos get no viewer" do test "squawks with no photos get no viewer" do
@a.squawks.create!(priority: 1, issue_reported: "x", attachments: [ upload("notes.txt") ]) @a.squawks.create!(priority: 1, issue_reported: "x", attachments: [ upload("notes.txt") ])
sign_in @pilot sign_in @pilot
+63
View File
@@ -0,0 +1,63 @@
require "test_helper"
# Times show in the viewer's zone (Profile, else their device, else the
# installation default), and "today" is their local date.
class TimeZonesTest < ActionDispatch::IntegrationTest
setup do
@user = create_user("pilot@example.com")
@a = create_aircraft(pilot: @user)
end
# 02:00 UTC on Nov 15 is still Nov 14 in the US.
def at_night_utc(&) = travel_to(Time.utc(2026, 11, 15, 2, 0), &)
def new_flight_date
get new_aircraft_flight_log_path(@a)
css_select("input[name='flight_log[date]']").first["value"]
end
test "a zone chosen in Profile sets today's date and how times show" do
@user.update!(time_zone: "Eastern Time (US & Canada)")
at_night_utc do
sign_in @user
assert_equal "2026-11-14", new_flight_date
get edit_profile_path
assert_select "select[name='user[time_zone]'] option[selected][value='Eastern Time (US & Canada)']"
assert_match "Nov 14, 2026 21:00", response.body # the profile's "Now:"
end
end
test "without a choice, the device's zone is used; without that, the default" do
at_night_utc do
sign_in @user
assert_equal "2026-11-15", new_flight_date # UTC: device not known yet
cookies[:tz] = "America/Los_Angeles"
assert_equal "2026-11-14", new_flight_date
get edit_profile_path
assert_select "select[name='user[time_zone]'] option[value='']", /Automatic: this device \(.*Pacific/
cookies[:tz] = "Not/AZone"
assert_equal "2026-11-15", new_flight_date # unknown names are ignored
end
end
test "the time zone is saved from Profile, and unknown ones are refused" do
sign_in @user
patch profile_path, params: { user: { time_zone: "Alaska" } }
assert_equal "Alaska", @user.reload.time_zone
patch profile_path, params: { user: { time_zone: "Mars/Olympus" } }
assert_equal "Alaska", @user.reload.time_zone
patch profile_path, params: { user: { time_zone: "" } }
assert_nil @user.reload.time_zone # back to automatic
end
test "the weekly email works out dates in the recipient's zone" do
@user.update!(time_zone: "Hawaii")
zone = nil
original = ReminderMailer.method(:items_for)
ReminderMailer.define_singleton_method(:items_for) { |_| (zone = Time.zone.name) && [] }
at_night_utc { ReminderMailer.weekly(@user).message }
assert_equal "Hawaii", zone
ensure
ReminderMailer.define_singleton_method(:items_for, original) if original
end
end
+1 -1
View File
@@ -36,7 +36,7 @@ class UserCertificatesTest < ActionDispatch::IntegrationTest
@owner.certificates.create!(kind: "IA", number: "7654321", expires_on: 1.day.ago.to_date) # expired: not offered @owner.certificates.create!(kind: "IA", number: "7654321", expires_on: 1.day.ago.to_date) # expired: not offered
sign_in @owner sign_in @owner
get new_aircraft_logbook_entry_path(@a) get new_aircraft_logbook_entry_path(@a)
assert_select "form[data-controller='entry-template signer component-times']" assert_select "form[data-controller~=signer]"
assert_select "select[data-signer-target=choice] option[data-kind=AP][data-number='7654321'][data-name='Sam Mechanic']" assert_select "select[data-signer-target=choice] option[data-kind=AP][data-number='7654321'][data-name='Sam Mechanic']"
assert_select "select[data-signer-target=choice] option[data-kind=IA]", 0 assert_select "select[data-signer-target=choice] option[data-kind=IA]", 0
assert_select "input[name='logbook_entry[signoff_person]'][data-signer-target=name]" assert_select "input[name='logbook_entry[signoff_person]'][data-signer-target=name]"
+104
View File
@@ -0,0 +1,104 @@
require "test_helper"
# Small workflow refinements: readable dates in pickers and the activity log,
# fields that appear when they apply, the next-leg button, grouped component
# limits and the setup checklist for a new aircraft.
class WorkflowPolishTest < ActionDispatch::IntegrationTest
setup do
@owner = create_user("owner@example.com")
@pilot = create_user("pilot@example.com")
@a = create_aircraft(owner: @owner, pilot: @pilot, tail_number: "N12345", tach_time: 1000)
end
test "logbook entry pickers and activity show dates the app's way" do
entry = @a.logbook_entries.create!(date: Date.new(2025, 12, 14), entry_type: "MAINTENANCE", log_type: "AC", text: "Oil changed")
sign_in @owner
get new_aircraft_inspection_record_path(@a)
assert_select "select[name='inspection_record[logbook_entry_id]'] option[value='#{entry.id}']", text: /\ADec 14, 2025 – Oil changed/
end
test "the inspection result appears only for inspection entries" do
sign_in @owner
get new_aircraft_logbook_entry_path(@a)
assert_select "form[data-controller~=show-when] select[name='logbook_entry[entry_type]'][data-show-when-target=source]"
assert_select "[data-show-when-target=item][data-show-when-value=INSPECTION] select[name='logbook_entry[inspection_result]']"
end
test "choosing Ground Aircraft warns what it does" do
sign_in @pilot
get new_aircraft_squawk_path(@a)
assert_select "[data-show-when-target=item][data-show-when-value='0'][hidden]", /This grounds N12345/
get aircraft_squawks_path(@a)
assert_select "main a[href='#{new_aircraft_squawk_path(@a)}']", 1 # just the header's Report Squawk
end
test "Save and log next leg comes back to the form, starting where the flight ended" do
sign_in @pilot
post aircraft_flight_logs_path(@a), params: { next_leg: "1", flight_log: { date: "2026-11-08", tach_out: 1000, tach_in: 1001.2, departure_location: "KOQU", destination_location: "KBID" } }
assert_redirected_to new_aircraft_flight_log_path(@a, date: "2026-11-08")
follow_redirect!
assert_match "The next leg starts where it ended.", flash[:notice]
assert_select "input[name='flight_log[date]'][value='2026-11-08']"
assert_select "input[name='flight_log[tach_out]'][value='1001.2']"
assert_select "input[name='flight_log[departure_location]'][value=KBID]"
end
test "a new document is named from its file, and the setup checklist can preset its type" do
sign_in @owner
get new_aircraft_document_path(@a, doc_type: "REGISTRATION")
assert_select "form[data-controller=name-from-file] input[name='document[name]'][data-name-from-file-target=name]"
assert_select "input[type=file][data-action='name-from-file#fill']"
assert_select "select[name='document[doc_type]'] option[selected][value=REGISTRATION]"
end
test "component limits are grouped and open when in use" do
sign_in @owner
get new_aircraft_component_path(@a)
assert_select "form details:not([open])", 2 # replacement and expiry; overhaul and TBO
engine = @a.components.create!(component_type: ComponentType.find_or_create_by!(name: "Engine"), manufacturer: "Continental", model: "O-200", date_in_service: Date.current, status: "IN-USE", tbo_hours: 1800)
get edit_aircraft_component_path(@a, engine)
assert_select "details[open] input[name='component[tbo_hours]']"
get aircraft_components_path(@a)
assert_select "a", text: "Record service"
end
test "owners see what's left to set up a new aircraft; pilots don't" do
sign_in @owner
get aircraft_path(@a)
assert_select "[data-controller=dismiss] li", 5
assert_select "[data-controller=dismiss]", /0 of 5 done/
@a.components.create!(component_type: ComponentType.find_or_create_by!(name: "Engine"), manufacturer: "Continental", model: "O-200", date_in_service: Date.current, status: "IN-USE")
get aircraft_path(@a)
assert_select "[data-controller=dismiss]", /1 of 5 done/
sign_in @pilot
get aircraft_path(@a)
assert_select "[data-controller=dismiss]", 0
end
test "aircraft pages show a small copy of the photo, made when it's uploaded" do
perform_enqueued_jobs { @a.picture.attach(io: StringIO.new(Vips::Image.black(1200, 900).jpegsave_buffer), filename: "plane.jpg", content_type: "image/jpeg") }
assert_equal 2, @a.picture.blob.variant_records.count, "both sizes are made on upload"
sign_in @owner
get aircraft_path(@a)
assert_select "img[src*='/representations/'][width='48']"
get aircraft_index_path
assert_select "img[src*='/representations/'][loading='lazy']"
end
test "a flight's details are one label and value per row" do
flight = @a.flight_logs.create!(date: Date.current, tach_out: 100, tach_in: 101, hobbs_out: 50, hobbs_in: 51, user: @owner)
sign_in @owner
get aircraft_flight_log_path(@a, flight)
assert_select "dl > div.detail-row > dt", minimum: 6
assert_select "dl dd.col-span-3", 0
end
test "the profile is two columns on a wide screen: the account and its security, then the rest" do
sign_in @owner
get edit_profile_path
assert_select "div.max-w-5xl > div", 2
assert_select "div.max-w-5xl > div:first-child h2", text: "Account"
assert_select "div.max-w-5xl > div:first-child #two-factor"
assert_select "div.max-w-5xl > div:last-child #device"
end
end
+1 -1
View File
@@ -208,7 +208,7 @@ class AircraftArchiveTest < ActiveSupport::TestCase
assert_raises(RuntimeError) { importer.run } assert_raises(RuntimeError) { importer.run }
assert_equal before[0, 2], [ Aircraft.count, Component.count ] assert_equal before[0, 2], [ Aircraft.count, Component.count ]
assert_equal 0, Aircraft.where(tail_number: "N999").count assert_equal 0, Aircraft.where(tail_number: "N999").count
perform_enqueued_jobs perform_enqueued_jobs(only: ActiveStorage::PurgeJob) # (the stand-in photo isn't a real image to resize)
assert_equal before[2], ActiveStorage::Blob.count assert_equal before[2], ActiveStorage::Blob.count
end end
end end
+2
View File
@@ -5,6 +5,8 @@ require "webmock/minitest"
WebMock.disable_net_connect!(allow_localhost: true) WebMock.disable_net_connect!(allow_localhost: true)
Dir[File.expand_path("support/**/*.rb", __dir__)].each { require _1 } Dir[File.expand_path("support/**/*.rb", __dir__)].each { require _1 }
PwnedPasswords.checker = ->(password) { password == "breached-password-1" } # no network in tests PwnedPasswords.checker = ->(password) { password == "breached-password-1" } # no network in tests
# No DNS in tests: names resolve to a public address, IP addresses to themselves.
AirTrailClient.resolver = ->(host) { host.match?(/\A[\d.]+\z|:/) ? [ host.delete("[]") ] : [ "203.0.113.10" ] }
module ActiveSupport module ActiveSupport
class TestCase class TestCase