mirror of
https://github.com/rickbarrette/simple-aircraft-manager-rails.git
synced 2026-11-17 23:50:36 -05:00
Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
34879e7310 | ||
|
|
e8b0cd030e | ||
|
|
e4bc3a5b7b | ||
|
|
d9de1be562 | ||
|
|
66fa5f4423 | ||
|
|
2e8d789975 | ||
|
|
e4c27c6ff7 | ||
|
|
bffdea937c | ||
|
|
ec0f43019f | ||
|
|
291990412e | ||
|
|
a2672b99a3 | ||
|
|
908c943e21 | ||
|
|
5876c07a1a | ||
|
|
faae719b12 | ||
|
|
e199e6feeb | ||
|
|
d4b71d17a1 | ||
|
|
3f314a13bb | ||
|
|
9662c7ae16 | ||
|
|
03b9ad65cb | ||
|
|
3452a35896 | ||
|
|
79a64cc208 | ||
|
|
9d3643df33 | ||
|
|
cce1ce51b5 |
No files matched your search
+26
-5
@@ -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 ----------------------------------------------------
|
||||||
|
|||||||
@@ -2,6 +2,66 @@
|
|||||||
|
|
||||||
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.6
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
- **PDFs show on phones.** Android showed nothing for a PDF document and iPhones only its first page. On phones and tablets every page is now drawn in the app, as it scrolls into view, downloading only the parts of the file those pages need (a long manual opens quickly and doesn't use up mobile data). Computers keep the browser's own PDF viewer.
|
||||||
|
- **Connection status in the top bar.** It turns red when the server can't be reached, and back on its own when it can. A ring fills while pages are saved for offline use or what was logged offline is sent; it's amber with a count while flights or squawks wait to send.
|
||||||
|
- **A weak signal counts as no signal.** Log Flight and Report Squawk say "Sending…" and, if the server doesn't answer within 10 seconds (a minute with photos), keep the entry on the phone and send it when the connection's back. If it got through after all, it isn't logged twice. Every page falls back to its offline copy or the offline page instead of loading forever.
|
||||||
|
- **The activity log loads as you scroll** (it stopped at 200 events).
|
||||||
|
- **What's new** shows the running version's notes on Admin → About; older releases fold to one line each.
|
||||||
|
- **REST API** for other programs, such as a script that pulls what's coming due or a work-order system: read aircraft, parts, due items, inspections, ADs, squawks and logbook entries; report and update squawks; send draft logbook entries to be signed in the app. Webhooks announce squawks reported, updated and resolved, entries signed, and drafts completed. Personal tokens are made in Profile. The API never signs an entry; see Help → REST API.
|
||||||
|
|
||||||
|
### For administrators
|
||||||
|
|
||||||
|
- **Admin → Integrations** makes tokens for other systems, acting for the person each request names, limited to the aircraft chosen, plus webhook endpoints.
|
||||||
|
- The update adds the API's tables; they're created automatically when the new version starts.
|
||||||
|
|
||||||
|
## 2026.11.5
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
- **Faster photos.** Aircraft photos load as small copies on the Fleet page and the aircraft header (they were the full original, slow on mobile). The offline copies use the small versions too.
|
||||||
|
- **Detail cards read one item per row on a phone**: flights, engine data, components and major repairs and alterations. Wider screens show two columns.
|
||||||
|
- **Profile uses the width of a desktop screen**: your account and its security on the left; calendar, certificates, this device and integrations on the right.
|
||||||
|
- **Notifications:** opening Profile on a device records its notification subscription again, so a device whose subscription was never saved starts receiving them. **Send test** lists each device and whether its push service accepted the notification, with the reason if not. If turning notifications on fails, the browser's error is shown.
|
||||||
|
|
||||||
|
### For administrators
|
||||||
|
|
||||||
|
- **The app won't start with a placeholder or short `SECRET_KEY_BASE`** (under 32 characters), since anyone who knows it can sign in as anyone. `sam:doctor` flags one under 64 characters. Use the output of `bin/rails secret`.
|
||||||
|
- **First-run setup asks for a one-time code** printed in the server log (`docker compose logs web | grep "Setup code"`), so only whoever runs the server can create the admin account.
|
||||||
|
- **HTTPS without a proxy:** `docker-compose.direct.yml` with `TLS_DOMAIN` gets and renews a Let's Encrypt certificate by itself.
|
||||||
|
- **The app answers only for its own names** when `APP_HOST` is set: `APP_HOST`, the `APP_URL` host, `localhost`, IP addresses, and any names listed in the new `ALLOWED_HOSTS`. Other names get a short explanation. If you reach the app by another name (such as a LAN name), add it to `ALLOWED_HOSTS`.
|
||||||
|
- **AirTrail servers on a private network** can be connected only by an administrator, or by anyone when listed in `AIRTRAIL_ALLOWED_HOSTS`. The server itself and link-local addresses are always refused.
|
||||||
|
- The project is released into the public domain (LICENSE, The Unlicense).
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- A file that isn't a photo, or an empty one, chosen as the aircraft photo now shows "must be an image" instead of an error page. An image that can't be read is shown as the original file.
|
||||||
|
- A component can't be set as a part of its own parts; that made the logbook entry and squawk resolution pages fail.
|
||||||
|
- Many malformed requests that caused error pages now get a proper answer: pages requested in another format, blank required values, links to records that don't exist, numbers too large to store, and text sent where a file belongs.
|
||||||
|
|
||||||
|
## 2026.11.4
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
- **Time zones.** Times show in your own zone and "today" is your local date (a new flight no longer defaults to tomorrow in the evening). It follows your device automatically, or choose one in Profile. The administrator sets the installation's zone with `TZ` (e.g. `America/New_York`), which also sets when the nightly and weekly jobs run. Signatures and the record history still show UTC.
|
||||||
|
- **Update Hours asks first**, showing each reading's change and that every in-service component moves without logging a flight; the message afterwards says exactly what changed. A lowered reading is marked as a correction.
|
||||||
|
- **Squawk photos show as thumbnails** that open the photo viewer.
|
||||||
|
- **Save and log next leg** on Log Flight: saves the flight and opens the form for the next one, starting where it ended.
|
||||||
|
- **Setup checklist** on a new aircraft's Overview: components, standard inspections, ADs from DRS, registration and airworthiness certificate, weight and balance.
|
||||||
|
- The component form groups its limits into **Replacement and expiry** and **Overhaul and TBO**, opened only when used.
|
||||||
|
- Choosing **Ground Aircraft** on a squawk says what it does before you submit.
|
||||||
|
- The logbook entry form shows **Inspection result** only for inspection entries.
|
||||||
|
- A new document is named from its file when you leave the name blank.
|
||||||
|
- Dates read the same way everywhere, including the logbook-entry pickers, the activity log and the airworthiness list.
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- On iPad and iPhone home-screen apps, the top bar stays sharp (it's now fixed to the top of the screen).
|
||||||
|
- An aircraft's description stays inside the Details card.
|
||||||
|
|
||||||
## 2026.11.3
|
## 2026.11.3
|
||||||
|
|
||||||
### Installed app
|
### Installed app
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -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`). |
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
--color-page: oklch(96.8% 0.007 247.896); /* slate-100 */
|
--color-page: oklch(96.8% 0.007 247.896); /* slate-100 */
|
||||||
--color-surface: oklch(100% 0 0); /* white: cards, inputs, menus */
|
--color-surface: oklch(100% 0 0); /* white: cards, inputs, menus */
|
||||||
--color-header: oklch(20.8% 0.042 265.755); /* slate-900: top bar, dark in both themes */
|
--color-header: oklch(20.8% 0.042 265.755); /* slate-900: top bar, dark in both themes */
|
||||||
|
--color-header-offline: oklch(50.5% 0.213 27.518); /* red-700: top bar when the server can't be reached */
|
||||||
--color-accent: oklch(50% 0.134 242.749); /* sky-700: primary buttons */
|
--color-accent: oklch(50% 0.134 242.749); /* sky-700: primary buttons */
|
||||||
--color-accent-hover: oklch(44.3% 0.11 240.79); /* sky-800 */
|
--color-accent-hover: oklch(44.3% 0.11 240.79); /* sky-800 */
|
||||||
}
|
}
|
||||||
@@ -62,6 +63,7 @@
|
|||||||
--color-page: oklch(15.5% 0.035 264);
|
--color-page: oklch(15.5% 0.035 264);
|
||||||
--color-surface: oklch(20.8% 0.042 265.755);
|
--color-surface: oklch(20.8% 0.042 265.755);
|
||||||
--color-header: oklch(12.9% 0.042 264.695);
|
--color-header: oklch(12.9% 0.042 264.695);
|
||||||
|
--color-header-offline: oklch(44.4% 0.177 26.899); /* red-800 */
|
||||||
--color-accent: oklch(50% 0.134 242.749); /* same blue: white text stays ≥ 4.5:1 */
|
--color-accent: oklch(50% 0.134 242.749); /* same blue: white text stays ≥ 4.5:1 */
|
||||||
--color-accent-hover: oklch(54% 0.15 242);
|
--color-accent-hover: oklch(54% 0.15 242);
|
||||||
|
|
||||||
@@ -184,3 +186,38 @@
|
|||||||
.btn-sm { padding: 0.4rem 0.75rem; font-size: 0.8125rem; }
|
.btn-sm { padding: 0.4rem 0.75rem; font-size: 0.8125rem; }
|
||||||
.btn-primary, .btn-secondary, .btn-danger { min-height: 2.5rem; }
|
.btn-primary, .btn-secondary, .btn-danger { min-height: 2.5rem; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* A label and its value on one row (label column, then value), e.g. a flight's details. */
|
||||||
|
@utility detail-row {
|
||||||
|
@apply grid grid-cols-[6.5rem_minmax(0,1fr)] items-baseline gap-x-3;
|
||||||
|
& > dt { @apply text-slate-500; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The top bar's connection status (connection_controller.js, after
|
||||||
|
SilverBullet): red when the server can't be reached, and a ring that fills
|
||||||
|
with the percentage in its hole while saving for offline or sending. Amber
|
||||||
|
and full while flights or squawks wait to send, with how many. */
|
||||||
|
header.is-offline { --color-header: var(--color-header-offline); }
|
||||||
|
.sync-ring {
|
||||||
|
position: relative;
|
||||||
|
display: inline-block;
|
||||||
|
flex: none;
|
||||||
|
width: 24px;
|
||||||
|
height: 24px;
|
||||||
|
border-radius: 9999px;
|
||||||
|
background: conic-gradient(var(--ring-color, white) var(--progress, 0%), rgb(255 255 255 / 0.25) 0);
|
||||||
|
}
|
||||||
|
.sync-ring[hidden] { display: none; }
|
||||||
|
.sync-ring.is-waiting { --ring-color: oklch(87.9% 0.169 91.605); } /* amber-300 */
|
||||||
|
.sync-ring > span {
|
||||||
|
position: absolute;
|
||||||
|
inset: 2.5px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border-radius: 9999px;
|
||||||
|
background-color: var(--color-header);
|
||||||
|
font-size: 9px;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# Admin → Integrations: tokens for other systems (e.g. Redmine), limited to
|
||||||
|
# chosen aircraft and scopes, each with an optional webhook (docs/api.md).
|
||||||
|
# The token and webhook secret are shown once, right after they're made.
|
||||||
|
class Admin::IntegrationsController < ApplicationController
|
||||||
|
before_action :require_admin!
|
||||||
|
before_action :set_integration, only: %i[show edit update destroy new_secret]
|
||||||
|
|
||||||
|
def index
|
||||||
|
@integrations = ApiToken.integration.order(revoked_at: :desc, name: :asc).includes(:webhook_endpoints)
|
||||||
|
end
|
||||||
|
|
||||||
|
def new
|
||||||
|
@integration = ApiToken.new(kind: "integration", scopes: %w[read])
|
||||||
|
@endpoint = WebhookEndpoint.new(events: [])
|
||||||
|
end
|
||||||
|
|
||||||
|
def create
|
||||||
|
@integration = ApiToken.new(integration_params.merge(kind: "integration", user: current_user))
|
||||||
|
@endpoint = build_endpoint(@integration)
|
||||||
|
ApiToken.transaction do
|
||||||
|
@integration.save!
|
||||||
|
@endpoint&.save!
|
||||||
|
end
|
||||||
|
@secret = @endpoint&.secret
|
||||||
|
render :created
|
||||||
|
rescue ActiveRecord::RecordInvalid
|
||||||
|
@endpoint ||= WebhookEndpoint.new(events: [])
|
||||||
|
render :new, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
def show
|
||||||
|
@endpoint = @integration.webhook_endpoints.first
|
||||||
|
@deliveries = @endpoint ? @endpoint.deliveries.recent.limit(25) : []
|
||||||
|
end
|
||||||
|
|
||||||
|
def edit
|
||||||
|
@endpoint = @integration.webhook_endpoints.first || WebhookEndpoint.new(events: [])
|
||||||
|
end
|
||||||
|
|
||||||
|
def update
|
||||||
|
@endpoint = @integration.webhook_endpoints.first
|
||||||
|
ApiToken.transaction do
|
||||||
|
@integration.update!(integration_params)
|
||||||
|
if webhook_params[:url].present?
|
||||||
|
@endpoint ||= @integration.webhook_endpoints.new(secret: WebhookEndpoint.new_secret)
|
||||||
|
@endpoint.update!(webhook_params)
|
||||||
|
else
|
||||||
|
@endpoint&.destroy!
|
||||||
|
end
|
||||||
|
end
|
||||||
|
redirect_to admin_integration_path(@integration), notice: t("flash.admin_integrations.saved")
|
||||||
|
rescue ActiveRecord::RecordInvalid
|
||||||
|
@endpoint ||= WebhookEndpoint.new(events: [])
|
||||||
|
render :edit, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
|
||||||
|
# A new webhook secret, shown once.
|
||||||
|
def new_secret
|
||||||
|
@endpoint = @integration.webhook_endpoints.first or return redirect_to(admin_integration_path(@integration))
|
||||||
|
@endpoint.update!(secret: WebhookEndpoint.new_secret)
|
||||||
|
@secret = @endpoint.secret
|
||||||
|
render :created
|
||||||
|
end
|
||||||
|
|
||||||
|
def destroy
|
||||||
|
@integration.revoke!
|
||||||
|
@integration.webhook_endpoints.update_all(enabled: false)
|
||||||
|
redirect_to admin_integrations_path, notice: t("flash.admin_integrations.revoked", name: @integration.name)
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def set_integration = @integration = ApiToken.integration.find(params[:id])
|
||||||
|
|
||||||
|
def integration_params
|
||||||
|
p = params.require(:api_token).permit(:name, scopes: [], aircraft_ids: [])
|
||||||
|
p[:scopes] = Array(p[:scopes]) & ApiToken::SCOPES.keys
|
||||||
|
p[:aircraft_ids] = Aircraft.where(id: Array(p[:aircraft_ids])).ids
|
||||||
|
p
|
||||||
|
end
|
||||||
|
|
||||||
|
def webhook_params
|
||||||
|
p = params.fetch(:webhook, {}).permit(:url, :enabled, events: [])
|
||||||
|
p[:events] = Array(p[:events]) & WebhookEndpoint::EVENTS.keys
|
||||||
|
p[:enabled] = p[:enabled] != "0"
|
||||||
|
p
|
||||||
|
end
|
||||||
|
|
||||||
|
def build_endpoint(integration)
|
||||||
|
return if webhook_params[:url].blank?
|
||||||
|
integration.webhook_endpoints.new(webhook_params.merge(secret: WebhookEndpoint.new_secret))
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
module Api
|
||||||
|
module V1
|
||||||
|
# The fleet this token reaches, and each aircraft's own lists.
|
||||||
|
class AircraftController < BaseController
|
||||||
|
before_action -> { require_scope!(:read) }
|
||||||
|
|
||||||
|
def index
|
||||||
|
render_page(aircraft_scope) { ApiPresenter.aircraft(_1) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def show
|
||||||
|
render json: { data: ApiPresenter.aircraft(find_aircraft(params[:id])) }
|
||||||
|
end
|
||||||
|
|
||||||
|
# The parts tree (?all=1 includes disposed parts).
|
||||||
|
def components
|
||||||
|
aircraft = find_aircraft(params[:id])
|
||||||
|
scope = aircraft.components.includes(:component_type)
|
||||||
|
scope = scope.where.not(status: "DISPOSED") unless params[:all].present?
|
||||||
|
render_page(scope) { ApiPresenter.component(_1) }
|
||||||
|
end
|
||||||
|
|
||||||
|
# Everything coming due, soonest first (hours projected to dates).
|
||||||
|
def due
|
||||||
|
aircraft = find_aircraft(params[:id])
|
||||||
|
render json: { data: DueList.new(aircraft).items.map { ApiPresenter.due_item(_1) } }
|
||||||
|
end
|
||||||
|
|
||||||
|
def inspections
|
||||||
|
aircraft = find_aircraft(params[:id])
|
||||||
|
render json: { data: Compliance.inspection_rows(aircraft).map { ApiPresenter.inspection(_1) } }
|
||||||
|
end
|
||||||
|
|
||||||
|
def ads
|
||||||
|
aircraft = find_aircraft(params[:id])
|
||||||
|
render json: { data: Compliance.ad_rows(aircraft).map { ApiPresenter.ad(_1) } }
|
||||||
|
end
|
||||||
|
|
||||||
|
# Logbook entries, oldest first (paged); ?log=AC|ENG|PROP|OTHER, ?signed=true|false.
|
||||||
|
def logbook_entries
|
||||||
|
aircraft = find_aircraft(params[:id])
|
||||||
|
scope = aircraft.logbook_entries.includes(:signature)
|
||||||
|
scope = scope.where(log_type: params[:log]) if params[:log].present?
|
||||||
|
scope = params[:signed] == "true" ? scope.where.associated(:signature) : scope.where.missing(:signature) if params[:signed].present?
|
||||||
|
render_page(scope) { ApiPresenter.logbook_entry(_1) }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
# The REST API, version 1 (docs/api.md). JSON in and out; a token in
|
||||||
|
# "Authorization: Bearer sam_…" instead of a browser session, so no cookies
|
||||||
|
# and no CSRF tokens.
|
||||||
|
#
|
||||||
|
# A personal token acts as its owner. An integration token acts for the
|
||||||
|
# person named in "SAM-On-Behalf-Of: <email>" (required for writes), and
|
||||||
|
# reaches only its aircraft that person can also see.
|
||||||
|
module Api
|
||||||
|
module V1
|
||||||
|
class BaseController < ActionController::API
|
||||||
|
include RejectsNullBytes
|
||||||
|
|
||||||
|
MAX_PAGE = 200
|
||||||
|
|
||||||
|
before_action :authenticate
|
||||||
|
rate_limit to: 600, within: 1.minute, by: -> { @api_token&.id || request.remote_ip },
|
||||||
|
with: -> { render_error(:too_many_requests, "rate_limited", "Too many requests; slow down.") }
|
||||||
|
around_action :idempotent, if: -> { request.post? || request.patch? || request.delete? }
|
||||||
|
|
||||||
|
rescue_from ActiveRecord::RecordNotFound do
|
||||||
|
render_error(:not_found, "not_found", "Not found, or not available to this token.")
|
||||||
|
end
|
||||||
|
rescue_from ActionController::ParameterMissing, ActionDispatch::Http::Parameters::ParseError do |e|
|
||||||
|
render_error(:bad_request, "bad_request", e.message.truncate(200))
|
||||||
|
end
|
||||||
|
rescue_from ActiveRecord::RecordInvalid do |e|
|
||||||
|
render_invalid(e.record)
|
||||||
|
end
|
||||||
|
rescue_from ActiveSupport::MessageVerifier::InvalidSignature, ActiveModel::RangeError,
|
||||||
|
ActiveRecord::NotNullViolation, ActiveRecord::InvalidForeignKey do
|
||||||
|
render_error(:unprocessable_entity, "invalid", "Some values couldn't be saved.")
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
attr_reader :api_token
|
||||||
|
|
||||||
|
def acting_user = Current.api_user
|
||||||
|
|
||||||
|
def authenticate
|
||||||
|
token = request.authorization.to_s[/\ABearer\s+(\S+)\z/i, 1]
|
||||||
|
@api_token = ApiToken.authenticate(token)
|
||||||
|
return render_error(:unauthorized, "unauthorized", "A valid API token is required.") unless @api_token
|
||||||
|
|
||||||
|
Current.api_token = @api_token
|
||||||
|
Current.ip_address = request.remote_ip
|
||||||
|
Current.api_user = @api_token.personal? ? @api_token.user : on_behalf_of
|
||||||
|
@api_token.used!(request.remote_ip)
|
||||||
|
end
|
||||||
|
|
||||||
|
# The person an integration is acting for, if it named one.
|
||||||
|
def on_behalf_of
|
||||||
|
email = request.headers["SAM-On-Behalf-Of"].to_s.strip.downcase.presence or return
|
||||||
|
User.active.find_by(email_address: email) ||
|
||||||
|
render_error(:unprocessable_entity, "unknown_user", "SAM-On-Behalf-Of doesn't match an active user.")
|
||||||
|
end
|
||||||
|
|
||||||
|
def require_scope!(scope)
|
||||||
|
return if api_token.allows?(scope)
|
||||||
|
render_error(:forbidden, "missing_scope", "This token doesn't have the #{scope} scope.")
|
||||||
|
end
|
||||||
|
|
||||||
|
# Writes always name a person, so the record history shows who.
|
||||||
|
def require_person!
|
||||||
|
return if acting_user
|
||||||
|
render_error(:unprocessable_entity, "on_behalf_of_required", "Writes with an integration token need SAM-On-Behalf-Of.")
|
||||||
|
end
|
||||||
|
|
||||||
|
def aircraft_scope = api_token.aircraft_scope(acting_user)
|
||||||
|
|
||||||
|
def find_aircraft(id = params[:aircraft_id]) = aircraft_scope.find(id)
|
||||||
|
|
||||||
|
def role_on(aircraft) = acting_user&.role_for(aircraft)
|
||||||
|
def owner_of?(aircraft) = role_on(aircraft).in?(%w[admin owner])
|
||||||
|
|
||||||
|
# ?limit= (1–200, default 50), ?after=<id> to continue, ?updated_since=<ISO time>.
|
||||||
|
def paginate(scope)
|
||||||
|
limit = params.fetch(:limit, 50).to_i.clamp(1, MAX_PAGE)
|
||||||
|
scope = scope.where(scope.arel_table[:id].gt(params[:after].to_i)) if params[:after].present?
|
||||||
|
if params[:updated_since].present?
|
||||||
|
since = Time.iso8601(params[:updated_since].to_s) rescue (raise ActionController::BadRequest, "updated_since must be an ISO 8601 time")
|
||||||
|
scope = scope.where(scope.arel_table[:updated_at].gteq(since))
|
||||||
|
end
|
||||||
|
records = scope.reorder(:id).limit(limit + 1).to_a
|
||||||
|
more = records.size > limit
|
||||||
|
records = records.first(limit)
|
||||||
|
[ records, (records.last.id if more) ]
|
||||||
|
end
|
||||||
|
|
||||||
|
def render_page(scope, &present)
|
||||||
|
records, next_after = paginate(scope)
|
||||||
|
render json: { data: records.map(&present), next_after: next_after }
|
||||||
|
end
|
||||||
|
|
||||||
|
def render_error(status, code, message, fields: nil)
|
||||||
|
render json: { error: { code: code, message: message, fields: fields }.compact }, status: status
|
||||||
|
end
|
||||||
|
|
||||||
|
def render_invalid(record)
|
||||||
|
render_error(:unprocessable_entity, "invalid", record.errors.full_messages.to_sentence, fields: record.errors.to_hash)
|
||||||
|
end
|
||||||
|
|
||||||
|
# The same Idempotency-Key again (a retry) gets the first answer; the
|
||||||
|
# same key with a different request is a conflict.
|
||||||
|
def idempotent
|
||||||
|
key = request.headers["Idempotency-Key"].to_s.strip
|
||||||
|
return yield if key.empty? || api_token.nil?
|
||||||
|
return render_error(:bad_request, "bad_request", "Idempotency-Key is too long.") if key.length > 100
|
||||||
|
|
||||||
|
digest = OpenSSL::Digest::SHA256.hexdigest([ request.method, request.path, request.raw_post ].join("\n"))
|
||||||
|
if (seen = api_token.idempotency_keys.find_by(key: key))
|
||||||
|
return render_error(:conflict, "idempotency_conflict", "This Idempotency-Key was used for a different request.") if seen.request_digest != digest
|
||||||
|
response.headers["Idempotent-Replay"] = "true"
|
||||||
|
return render(json: seen.response_body, status: seen.response_status)
|
||||||
|
end
|
||||||
|
yield
|
||||||
|
return if response.status >= 500
|
||||||
|
api_token.idempotency_keys.create(key: key, request_digest: digest, response_status: response.status,
|
||||||
|
response_body: response.body, created_at: Time.current)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
module Api
|
||||||
|
module V1
|
||||||
|
# Draft logbook entries for one visit (docs/api.md, "Draft entries"). The
|
||||||
|
# work items become one unsigned entry per logbook, signed in the app; the
|
||||||
|
# squawks they resolve and inspections they complete are held until every
|
||||||
|
# entry is signed. Like writing entries in the app, it's for the
|
||||||
|
# aircraft's owners.
|
||||||
|
class DraftBatchesController < BaseController
|
||||||
|
before_action -> { require_scope!(:read) }, only: %i[index show lookup]
|
||||||
|
before_action -> { require_scope!("drafts:write") }, :require_person!, only: %i[create destroy]
|
||||||
|
|
||||||
|
def index
|
||||||
|
scope = find_aircraft.draft_batches.includes(entries: :signature)
|
||||||
|
scope = scope.where(status: params[:status]) if params[:status].present?
|
||||||
|
render_page(scope) { ApiPresenter.draft_batch(_1) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def lookup
|
||||||
|
scope = DraftBatch.where(aircraft: aircraft_scope, external_ref: params.require(:external_ref)).includes(entries: :signature)
|
||||||
|
render json: { data: scope.map { ApiPresenter.draft_batch(_1) } }
|
||||||
|
end
|
||||||
|
|
||||||
|
def show
|
||||||
|
render json: { data: ApiPresenter.draft_batch(find_batch) }
|
||||||
|
end
|
||||||
|
|
||||||
|
# POST /aircraft/:aircraft_id/draft_batches
|
||||||
|
def create
|
||||||
|
@aircraft = find_aircraft
|
||||||
|
return render_error(:forbidden, "owners_only", "Draft entries are for the aircraft's owners (act for an owner).") unless owner_of?(@aircraft)
|
||||||
|
|
||||||
|
input = params.require(:draft_batch)
|
||||||
|
items = Array(input[:items]).map { _1.permit(:log, :text, :external_ref, resolves_squawks: []) }
|
||||||
|
errors = check(input, items)
|
||||||
|
return render_error(:unprocessable_entity, "invalid", errors.values.flatten.to_sentence, fields: errors) if errors.any?
|
||||||
|
|
||||||
|
invitations = {}
|
||||||
|
batch = DraftBatch.transaction do
|
||||||
|
b = @aircraft.draft_batches.create!(api_token: api_token, created_by: acting_user, external_ref: input[:external_ref],
|
||||||
|
signer_email: signer_email(input), held: held(input, items))
|
||||||
|
items.group_by { _1[:log] }.each do |log, group|
|
||||||
|
entry = b.entries.create!(aircraft: @aircraft, log_type: log, date: input[:date], text: group.map { _1[:text].to_s.strip }.join("\n\n"),
|
||||||
|
entry_type: inspection_logs(input, items).include?(log) ? "INSPECTION" : "MAINTENANCE",
|
||||||
|
inspection_result: inspection_result_for(input, items, log),
|
||||||
|
aircraft_hours_at_entry: input[:aircraft_hours].presence, external_ref: group.filter_map { _1[:external_ref] }.join(",").presence)
|
||||||
|
invitations[entry.id] = invite(entry, b.signer_email, send: input.dig(:signer, :send_email).to_s == "true") if b.signer_email
|
||||||
|
end
|
||||||
|
b
|
||||||
|
end
|
||||||
|
@aircraft.log_event!("logbook", I18n.t("api.draft_batches.sent", count: batch.entries.size, name: api_token.name), notes: batch.external_ref)
|
||||||
|
render json: { data: ApiPresenter.draft_batch(batch.reload, invitations: invitations) }, status: :created
|
||||||
|
end
|
||||||
|
|
||||||
|
# DELETE /draft_batches/:id: withdraw it while nothing in it is signed.
|
||||||
|
def destroy
|
||||||
|
batch = find_batch
|
||||||
|
return render_error(:forbidden, "owners_only", "Only the aircraft's owners can withdraw a draft.") unless owner_of?(batch.aircraft)
|
||||||
|
unless batch.awaiting? && batch.entries.none?(&:signed?)
|
||||||
|
return render_error(:conflict, "signed", "Part of this draft is signed (or it's no longer awaiting signature); correct it in the app instead.")
|
||||||
|
end
|
||||||
|
batch.withdraw!
|
||||||
|
render json: { data: ApiPresenter.draft_batch(batch.reload) }
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def find_batch = DraftBatch.where(aircraft: aircraft_scope).includes(entries: :signature).find(params[:id])
|
||||||
|
|
||||||
|
def check(input, items)
|
||||||
|
errors = Hash.new { |h, k| h[k] = [] }
|
||||||
|
errors[:items] << "at least one item is needed" if items.empty?
|
||||||
|
items.each_with_index do |item, i|
|
||||||
|
errors[:"items.#{i}.log"] << "must be one of #{LogbookEntry::LOG_TYPES.keys.join(', ')}" unless LogbookEntry::LOG_TYPES.key?(item[:log])
|
||||||
|
errors[:"items.#{i}.text"] << "can't be blank" if item[:text].blank?
|
||||||
|
end
|
||||||
|
errors[:date] << "must be a date (YYYY-MM-DD)" unless (Date.iso8601(input[:date].to_s) rescue nil)
|
||||||
|
errors[:aircraft_hours] << "must be a number" if input[:aircraft_hours].present? && !input[:aircraft_hours].to_s.match?(/\A\d+(\.\d+)?\z/)
|
||||||
|
squawk_ids = items.flat_map { Array(_1[:resolves_squawks]) }.map(&:to_i)
|
||||||
|
missing = squawk_ids - @aircraft.squawks.active.where(id: squawk_ids).ids
|
||||||
|
errors[:resolves_squawks] << "no open squawk #{missing.join(', ')} on this aircraft" if missing.any?
|
||||||
|
Array(input[:completes_inspections]).each_with_index do |c, i|
|
||||||
|
id = c.respond_to?(:[]) ? c[:inspection_type_id].to_i : 0
|
||||||
|
errors[:"completes_inspections.#{i}"] << "no inspection #{id} applies to this aircraft" unless @aircraft.applicable_inspection_types.exists?(id: id)
|
||||||
|
log = inspection_log(c, items)
|
||||||
|
errors[:"completes_inspections.#{i}.log"] << "must be the log of one of the items" unless items.any? { _1[:log] == log }
|
||||||
|
unless LogbookEntry::INSPECTION_RESULTS.key?(c.respond_to?(:[]) ? c[:result].to_s : "")
|
||||||
|
errors[:"completes_inspections.#{i}.result"] << "must be #{LogbookEntry::INSPECTION_RESULTS.keys.join(' or ')}"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
Array(input[:completes_inspections]).group_by { inspection_log(_1, items) }.each do |log, group|
|
||||||
|
errors[:completes_inspections] << "inspections in the #{log} log need the same result (one entry)" if group.map { _1[:result].to_s }.uniq.size > 1
|
||||||
|
end
|
||||||
|
errors[:aircraft_hours] << "is needed to record an inspection" if Array(input[:completes_inspections]).any? && input[:aircraft_hours].blank?
|
||||||
|
email = input.dig(:signer, :email).to_s.strip
|
||||||
|
errors[:"signer.email"] << "isn't an email address" if email.present? && !email.match?(URI::MailTo::EMAIL_REGEXP)
|
||||||
|
errors[:"signer.send_email"] << "needs email set up on the server" if input.dig(:signer, :send_email).to_s == "true" && !MailSettings.configured?
|
||||||
|
errors
|
||||||
|
end
|
||||||
|
|
||||||
|
# The inspection goes in the logbook named for it, else the airframe
|
||||||
|
# log if there's an item for it, else the first item's.
|
||||||
|
def inspection_log(c, items)
|
||||||
|
c[:log].presence || (items.any? { _1[:log] == "AC" } ? "AC" : items.first&.dig(:log))
|
||||||
|
end
|
||||||
|
|
||||||
|
def inspection_logs(input, items) = Array(input[:completes_inspections]).map { inspection_log(_1, items) }
|
||||||
|
|
||||||
|
# approved | discrepancies, for the entry in that log that records inspections.
|
||||||
|
def inspection_result_for(input, items, log)
|
||||||
|
Array(input[:completes_inspections]).find { inspection_log(_1, items) == log }&.dig(:result)
|
||||||
|
end
|
||||||
|
|
||||||
|
def held(input, items)
|
||||||
|
{ "squawks" => items.flat_map { |it| Array(it[:resolves_squawks]).map { |id| { "id" => id.to_i, "log" => it[:log] } } }.uniq { _1["id"] },
|
||||||
|
"inspections" => Array(input[:completes_inspections]).map { { "id" => _1[:inspection_type_id].to_i, "log" => inspection_log(_1, items) } } }
|
||||||
|
end
|
||||||
|
|
||||||
|
def signer_email(input) = input.dig(:signer, :email).to_s.strip.downcase.presence
|
||||||
|
|
||||||
|
# A link for the signer to sign this entry with their own account,
|
||||||
|
# returned to the caller to pass on; emailed too when asked.
|
||||||
|
def invite(entry, email, send: false)
|
||||||
|
invitation = entry.signing_invitations.create!(email: email, invited_by: acting_user)
|
||||||
|
SigningInvitationMailer.invite(invitation, invitation.token).deliver_later if send
|
||||||
|
invitation.token
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
module Api
|
||||||
|
module V1
|
||||||
|
# What this token is and who it's acting as: a quick check for a new integration.
|
||||||
|
class MeController < BaseController
|
||||||
|
def show
|
||||||
|
render json: { data: {
|
||||||
|
token: { name: api_token.name, kind: api_token.kind, hint: api_token.token_hint, scopes: api_token.scopes,
|
||||||
|
aircraft_ids: (api_token.aircraft_ids if api_token.integration?) }.compact,
|
||||||
|
acting_as: acting_user && { id: acting_user.id, name: acting_user.display_name, email: acting_user.email_address },
|
||||||
|
aircraft_ids: aircraft_scope.ids,
|
||||||
|
api_version: "v1", app_version: Rails.root.join("VERSION").read.strip
|
||||||
|
} }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
module Api
|
||||||
|
module V1
|
||||||
|
# Squawks: list and report on an aircraft; find by external_ref; update.
|
||||||
|
# Resolving happens through a signed logbook entry, not here.
|
||||||
|
class SquawksController < BaseController
|
||||||
|
before_action -> { require_scope!(:read) }, only: %i[index show lookup]
|
||||||
|
before_action -> { require_scope!("squawks:write") }, :require_person!, only: %i[create update]
|
||||||
|
|
||||||
|
# GET /aircraft/:aircraft_id/squawks?status=open|resolved|all (default open)
|
||||||
|
def index
|
||||||
|
scope = find_aircraft.squawks.includes(:reported_by).with_attached_attachments
|
||||||
|
scope = case params.fetch(:status, "open")
|
||||||
|
when "open" then scope.active
|
||||||
|
when "resolved" then scope.resolved
|
||||||
|
else scope
|
||||||
|
end
|
||||||
|
render_page(scope) { ApiPresenter.squawk(_1) }
|
||||||
|
end
|
||||||
|
|
||||||
|
# GET /squawks?external_ref=redmine:issue:4512
|
||||||
|
def lookup
|
||||||
|
ref = params.require(:external_ref)
|
||||||
|
scope = Squawk.where(aircraft: aircraft_scope, external_ref: ref).includes(:reported_by).with_attached_attachments
|
||||||
|
render json: { data: scope.map { ApiPresenter.squawk(_1) } }
|
||||||
|
end
|
||||||
|
|
||||||
|
def show
|
||||||
|
render json: { data: ApiPresenter.squawk(find_squawk) }
|
||||||
|
end
|
||||||
|
|
||||||
|
# POST /aircraft/:aircraft_id/squawks
|
||||||
|
def create
|
||||||
|
aircraft = find_aircraft
|
||||||
|
squawk = aircraft.squawks.new(create_params.merge(reported_by: acting_user, resolved: false))
|
||||||
|
squawk.component_id = nil unless aircraft.components.exists?(id: squawk.component_id)
|
||||||
|
squawk.save!
|
||||||
|
SquawkReported.call(squawk, by: acting_user)
|
||||||
|
render json: { data: ApiPresenter.squawk(squawk) }, status: :created
|
||||||
|
end
|
||||||
|
|
||||||
|
# PATCH /squawks/:id: external_ref by anyone who may write; the rest
|
||||||
|
# (issue, priority, component, notes) by the aircraft's owners, as in the app.
|
||||||
|
def update
|
||||||
|
squawk = find_squawk
|
||||||
|
return render_error(:unprocessable_entity, "resolved", "A resolved squawk can't be changed.") if squawk.resolved?
|
||||||
|
attrs = params.require(:squawk).permit(:external_ref, :issue_reported, :priority, :component_id, :notes)
|
||||||
|
if (attrs.keys - %w[external_ref]).any? && !owner_of?(squawk.aircraft)
|
||||||
|
return render_error(:forbidden, "owners_only", "Only the aircraft's owners can change a squawk's details.")
|
||||||
|
end
|
||||||
|
attrs[:component_id] = nil if attrs.key?(:component_id) && !squawk.aircraft.components.exists?(id: attrs[:component_id])
|
||||||
|
squawk.update!(attrs)
|
||||||
|
render json: { data: ApiPresenter.squawk(squawk) }
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def find_squawk = Squawk.where(aircraft: aircraft_scope).find(params[:id])
|
||||||
|
|
||||||
|
def create_params
|
||||||
|
params.require(:squawk).permit(:issue_reported, :priority, :component_id, :external_ref).tap do |p|
|
||||||
|
p[:priority] = p.fetch(:priority, 2).to_i
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# Profile → API tokens: personal tokens for the REST API (docs/api.md). The
|
||||||
|
# token is shown once, on the page right after it's made (not kept in the
|
||||||
|
# flash or anywhere else).
|
||||||
|
class ApiTokensController < ApplicationController
|
||||||
|
def create
|
||||||
|
@token = current_user.api_tokens.new(name: params.dig(:api_token, :name), kind: "personal",
|
||||||
|
scopes: Array(params.dig(:api_token, :scopes)) & ApiToken::SCOPES.keys)
|
||||||
|
if @token.save
|
||||||
|
render :created
|
||||||
|
else
|
||||||
|
redirect_to edit_profile_path(anchor: "api"), alert: @token.errors.full_messages.to_sentence
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def destroy
|
||||||
|
current_user.api_tokens.personal.active.find(params[:id]).revoke!
|
||||||
|
redirect_to edit_profile_path(anchor: "api"), notice: t("flash.api_tokens.revoked")
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
class ApplicationController < ActionController::Base
|
class ApplicationController < ActionController::Base
|
||||||
default_form_builder AppFormBuilder
|
default_form_builder AppFormBuilder
|
||||||
include Authentication
|
include Authentication
|
||||||
|
include TimeZones
|
||||||
allow_browser versions: :modern
|
allow_browser versions: :modern
|
||||||
|
|
||||||
|
include RejectsNullBytes
|
||||||
prepend_before_action :redirect_to_setup
|
prepend_before_action :redirect_to_setup
|
||||||
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,27 @@ class ApplicationController < ActionController::Base
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Asked for a format a page doesn't have (/aircraft/1/report.pdf): not a crash.
|
||||||
|
rescue_from ActionView::MissingTemplate do |error|
|
||||||
|
raise error if request.format.html?
|
||||||
|
head :not_acceptable
|
||||||
|
end
|
||||||
|
|
||||||
|
# Input no form produces: a tampered upload reference, a number too big to
|
||||||
|
# store, a missing required value or a link to a record that isn't there.
|
||||||
|
# The forms validate what people can enter; this is the safety net.
|
||||||
|
rescue_from ActiveSupport::MessageVerifier::InvalidSignature, ActiveModel::RangeError,
|
||||||
|
ActiveRecord::NotNullViolation, ActiveRecord::InvalidForeignKey do |error|
|
||||||
|
Rails.logger.warn("[input] #{error.class}: #{error.message.truncate(200)}")
|
||||||
|
respond_to do |format|
|
||||||
|
format.html { redirect_back_or_to root_path, alert: t("flash.application.invalid_input") }
|
||||||
|
format.any { head :unprocessable_entity }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
|
|
||||||
def current_user = Current.user
|
def current_user = Current.user
|
||||||
|
|
||||||
# First run: no users yet → create the initial admin.
|
# First run: no users yet → create the initial admin.
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# No form or API client sends a null byte; some libraries (password hashing,
|
||||||
|
# file paths) raise on one, so such requests are refused up front.
|
||||||
|
module RejectsNullBytes
|
||||||
|
extend ActiveSupport::Concern
|
||||||
|
|
||||||
|
included { prepend_before_action :reject_null_bytes }
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def reject_null_bytes
|
||||||
|
head :bad_request if contains_null_byte?(request.params)
|
||||||
|
end
|
||||||
|
|
||||||
|
def contains_null_byte?(value)
|
||||||
|
case value
|
||||||
|
when String then value.include?("\0")
|
||||||
|
when Hash then value.any? { |k, v| contains_null_byte?(k) || contains_null_byte?(v) }
|
||||||
|
when Array then value.any? { contains_null_byte?(_1) }
|
||||||
|
else false
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -1,10 +1,18 @@
|
|||||||
class EventsController < ApplicationController
|
class EventsController < ApplicationController
|
||||||
include AircraftScoped
|
include AircraftScoped
|
||||||
|
|
||||||
|
EVENTS_PER_PAGE = 50
|
||||||
|
|
||||||
|
# A page at a time; the rest load as you scroll (each page ends in a lazy
|
||||||
|
# frame that fetches the next).
|
||||||
def index
|
def index
|
||||||
@category = params[:category].presence_in(AircraftEvent::CATEGORIES.keys)
|
@category = params[:category].presence_in(AircraftEvent::CATEGORIES.keys)
|
||||||
scope = @aircraft.events.includes(:user)
|
@page = [ params[:page].to_i, 1 ].max
|
||||||
|
scope = @aircraft.events.includes(:user).reorder(created_at: :desc, id: :desc)
|
||||||
scope = scope.where(category: @category) if @category
|
scope = scope.where(category: @category) if @category
|
||||||
@events = scope.limit(200)
|
rows = scope.offset((@page - 1) * EVENTS_PER_PAGE).limit(EVENTS_PER_PAGE + 1).to_a
|
||||||
|
@more = rows.size > EVENTS_PER_PAGE
|
||||||
|
@events = rows.first(EVENTS_PER_PAGE)
|
||||||
|
render(partial: "events/page", locals: { events: @events, page: @page, more: @more, category: @category }) if turbo_frame_request?
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@@ -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").
|
||||||
|
|||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -21,11 +21,7 @@ class SquawksController < ApplicationController
|
|||||||
end
|
end
|
||||||
@squawk = @aircraft.squawks.new(squawk_params.merge(reported_by: current_user))
|
@squawk = @aircraft.squawks.new(squawk_params.merge(reported_by: current_user))
|
||||||
if @squawk.save
|
if @squawk.save
|
||||||
log_event("squawk", t("flash.squawks.squawk_reported_2", priority_label: @squawk.priority_label), notes: @squawk.issue_reported.truncate(200))
|
SquawkReported.call(@squawk, by: current_user)
|
||||||
if @squawk.grounding?
|
|
||||||
PushNotifier.notify(@aircraft.users.merge(User.active).where.not(id: current_user.id), :grounding_squawk, path: aircraft_squawks_path(@aircraft),
|
|
||||||
tag: "squawk-#{@squawk.id}", tail: @aircraft.tail_number, issue: @squawk.issue_reported.truncate(120))
|
|
||||||
end
|
|
||||||
redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_reported")
|
redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_reported")
|
||||||
else
|
else
|
||||||
render :new, status: :unprocessable_entity
|
render :new, status: :unprocessable_entity
|
||||||
@@ -64,7 +60,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
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -7,4 +7,15 @@ module HelpHelper
|
|||||||
html = HelpGuide.html(page, title: title, link: (links ? method(:help_page_url_for) : nil))
|
html = HelpGuide.html(page, title: title, link: (links ? method(:help_page_url_for) : nil))
|
||||||
tag.div(html.html_safe, class: "markdown guide") # rubocop:disable Rails/OutputSafety -- sanitized in HelpGuide
|
tag.div(html.html_safe, class: "markdown guide") # rubocop:disable Rails/OutputSafety -- sanitized in HelpGuide
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# A piece of the guide's Markdown (an intro, one release's notes).
|
||||||
|
def guide_markdown(markdown, class: nil)
|
||||||
|
html = HelpGuide.render(markdown, link: method(:help_page_url_for))
|
||||||
|
tag.div(html.html_safe, class: [ "markdown guide", binding.local_variable_get(:class) ]) # rubocop:disable Rails/OutputSafety -- sanitized in HelpGuide
|
||||||
|
end
|
||||||
|
|
||||||
|
# "4 changes · 3 fixes · 2 for administrators"
|
||||||
|
def release_summary(release)
|
||||||
|
release.counts.map { |key, count| t("help.changelog.counts.#{key}", count: count) }.join(" · ")
|
||||||
|
end
|
||||||
end
|
end
|
||||||
@@ -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?
|
||||||
|
|||||||
@@ -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,118 @@
|
|||||||
|
import { Controller } from "@hotwired/stimulus"
|
||||||
|
import { t } from "i18n"
|
||||||
|
|
||||||
|
// The top bar shows the connection at a glance (as SilverBullet does):
|
||||||
|
// - it turns red when the server can't be reached: the device is offline, or
|
||||||
|
// a request failed (signal but no internet, or the proxy answering for the
|
||||||
|
// app). While red it checks /up every so often and turns back on its own;
|
||||||
|
// - a ring fills while pages are being saved for offline use or flights and
|
||||||
|
// squawks logged offline are being sent, with the percentage in its middle;
|
||||||
|
// - while some are waiting to send, the ring is amber with how many.
|
||||||
|
// Others report with events on document:
|
||||||
|
// sam:progress { source, done, total } (done >= total when finished)
|
||||||
|
// sam:waiting { count }
|
||||||
|
// sam:unreachable / sam:reachable
|
||||||
|
// and it says when the server answers again with sam:back-online (what was
|
||||||
|
// logged offline is sent then).
|
||||||
|
// The header is replaced on every page, so the state and the listeners live
|
||||||
|
// in this module and the header on the page just shows them.
|
||||||
|
const RETRY_EVERY = 15 * 1000
|
||||||
|
const UNREACHABLE = [ 502, 503, 504 ]
|
||||||
|
const OFFLINE_COLOR = "#b91c1c" // red-700, for the phone's status bar
|
||||||
|
const state = { online: navigator.onLine, progress: {}, waiting: 0 }
|
||||||
|
let header = null // the controller on the page
|
||||||
|
let checking = null
|
||||||
|
let timer = null
|
||||||
|
let normalColor = null
|
||||||
|
|
||||||
|
// Any answer from the app (even a sign-in redirect) means it's reachable.
|
||||||
|
async function check() {
|
||||||
|
checking ||= fetch("/up", { cache: "no-store", redirect: "manual", credentials: "same-origin" })
|
||||||
|
.then((response) => !UNREACHABLE.includes(response.status), () => false)
|
||||||
|
.finally(() => { checking = null })
|
||||||
|
setOnline(await checking)
|
||||||
|
}
|
||||||
|
|
||||||
|
function setOnline(online) {
|
||||||
|
clearTimeout(timer)
|
||||||
|
if (!online) timer = setTimeout(check, RETRY_EVERY)
|
||||||
|
if (state.online === online) return
|
||||||
|
state.online = online
|
||||||
|
header?.announce(online ? t("connection.back_online") : t("connection.offline"))
|
||||||
|
update()
|
||||||
|
if (online) document.dispatchEvent(new CustomEvent("sam:back-online"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Several reports often arrive together (done sending, then none waiting):
|
||||||
|
// show them once, on the next frame, so the ring doesn't flicker between.
|
||||||
|
let frame = null
|
||||||
|
function update() {
|
||||||
|
frame ||= requestAnimationFrame(() => { frame = null; header?.render() })
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener("online", check)
|
||||||
|
window.addEventListener("offline", () => setOnline(false))
|
||||||
|
document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible" && !state.online) check() })
|
||||||
|
document.addEventListener("sam:unreachable", () => setOnline(false))
|
||||||
|
document.addEventListener("turbo:fetch-request-error", () => setOnline(false))
|
||||||
|
document.addEventListener("sam:reachable", () => setOnline(true))
|
||||||
|
document.addEventListener("sam:progress", ({ detail }) => { state.progress[detail.source] = detail; update() })
|
||||||
|
document.addEventListener("sam:waiting", ({ detail }) => { state.waiting = detail.count; update() })
|
||||||
|
|
||||||
|
// Whether the server answered last time (false while the top bar is red).
|
||||||
|
export const serverReachable = () => state.online
|
||||||
|
|
||||||
|
export default class extends Controller {
|
||||||
|
static targets = [ "ring", "label", "announce" ]
|
||||||
|
|
||||||
|
connect() {
|
||||||
|
header = this
|
||||||
|
this.themeColor = document.querySelector("meta[name=theme-color]")
|
||||||
|
normalColor ||= this.themeColor?.content
|
||||||
|
if (!navigator.onLine) setOnline(false)
|
||||||
|
else if (!state.online || this.fromSavedCopy()) check() // a fresh page, or maybe the offline copy
|
||||||
|
this.render()
|
||||||
|
}
|
||||||
|
|
||||||
|
disconnect() {
|
||||||
|
if (header === this) header = null
|
||||||
|
}
|
||||||
|
|
||||||
|
fromSavedCopy() {
|
||||||
|
const rendered = Date.parse(document.querySelector("meta[name=rendered-at]")?.content || "")
|
||||||
|
return rendered && Date.now() - rendered > 60 * 1000
|
||||||
|
}
|
||||||
|
|
||||||
|
announce(text) {
|
||||||
|
if (this.hasAnnounceTarget) this.announceTarget.textContent = text
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
this.element.classList.toggle("is-offline", !state.online)
|
||||||
|
this.element.title = state.online ? "" : t("connection.offline")
|
||||||
|
if (this.themeColor && normalColor) this.themeColor.content = state.online ? normalColor : OFFLINE_COLOR
|
||||||
|
|
||||||
|
const busy = Object.values(state.progress).filter((p) => p.total && p.done < p.total)
|
||||||
|
if (busy.length) {
|
||||||
|
const done = busy.reduce((sum, p) => sum + p.done, 0)
|
||||||
|
const total = busy.reduce((sum, p) => sum + p.total, 0)
|
||||||
|
const percent = Math.floor((done / total) * 100)
|
||||||
|
const what = busy.some((p) => p.source === "send") ? "sending" : "saving"
|
||||||
|
this.showRing({ percent, number: percent, waiting: false, text: t(`connection.${what}`, { percent }) })
|
||||||
|
} else if (state.waiting) {
|
||||||
|
this.showRing({ percent: 100, number: state.waiting, waiting: true, text: t("connection.waiting", { count: state.waiting }) })
|
||||||
|
} else {
|
||||||
|
this.ringTarget.hidden = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
showRing({ percent, number, waiting, text }) {
|
||||||
|
const ring = this.ringTarget
|
||||||
|
ring.hidden = false
|
||||||
|
ring.classList.toggle("is-waiting", waiting)
|
||||||
|
ring.style.setProperty("--progress", `${percent}%`)
|
||||||
|
ring.title = text
|
||||||
|
ring.setAttribute("aria-label", text)
|
||||||
|
this.labelTarget.textContent = number
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,18 @@
|
|||||||
import { Controller } from "@hotwired/stimulus"
|
import { Controller } from "@hotwired/stimulus"
|
||||||
import { t } from "i18n"
|
import { t } from "i18n"
|
||||||
import { queue, formFields, newKey, currentUser } from "controllers/offline_queue"
|
import { queue, formFields, newKey, currentUser } from "controllers/offline_queue"
|
||||||
|
import { serverReachable } from "controllers/connection_controller"
|
||||||
|
|
||||||
|
// How long to wait for the server before keeping it here instead. Photos
|
||||||
|
// on a squawk take longer to send.
|
||||||
|
const WAIT = 10 * 1000
|
||||||
|
const WAIT_WITH_FILES = 60 * 1000
|
||||||
|
|
||||||
// Log Flight and Report Squawk: with no connection, the form is kept on this
|
// Log Flight and Report Squawk: with no connection, the form is kept on this
|
||||||
// device and sent later (see offline_sync_controller). For flights, the next
|
// device and sent later (see offline_sync_controller). For flights, the next
|
||||||
// leg starts where the last saved one ended.
|
// leg starts where the last saved one ended. A signal so weak the server
|
||||||
|
// doesn't answer counts as none: it's kept here too, and if it got through
|
||||||
|
// after all, the server drops the copy sent later (same client_key).
|
||||||
export default class extends Controller {
|
export default class extends Controller {
|
||||||
static targets = [ "key", "notice" ]
|
static targets = [ "key", "notice" ]
|
||||||
static values = { kind: { type: String, default: "flight" }, tail: String }
|
static values = { kind: { type: String, default: "flight" }, tail: String }
|
||||||
@@ -23,14 +31,21 @@ export default class extends Controller {
|
|||||||
|
|
||||||
get flight() { return this.kindValue === "flight" }
|
get flight() { return this.kindValue === "flight" }
|
||||||
|
|
||||||
// No connection: keep it here instead of submitting.
|
// No connection (or the top bar is red): keep it here instead of submitting.
|
||||||
async submit(event) {
|
async submit(event) {
|
||||||
if (navigator.onLine) return
|
if (navigator.onLine && serverReachable()) return
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
event.stopImmediatePropagation()
|
event.stopImmediatePropagation()
|
||||||
await this.save(formFields(this.element))
|
await this.save(formFields(this.element))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Give up waiting after a while; the request then fails (networkFailed).
|
||||||
|
limit(event) {
|
||||||
|
const options = event.detail.fetchOptions
|
||||||
|
const files = [ ...this.element.querySelectorAll("input[type=file]") ].some((input) => input.files?.length)
|
||||||
|
options.signal = AbortSignal.any([ options.signal, AbortSignal.timeout(files ? WAIT_WITH_FILES : WAIT) ].filter(Boolean))
|
||||||
|
}
|
||||||
|
|
||||||
// Kept in case the request fails on the way (no signal but the browser thinks it's online).
|
// Kept in case the request fails on the way (no signal but the browser thinks it's online).
|
||||||
remember() { this.pending = formFields(this.element) }
|
remember() { this.pending = formFields(this.element) }
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ import { currentUser } from "controllers/offline_queue"
|
|||||||
// your aircraft change. Signing out clears it.
|
// your aircraft change. Signing out clears it.
|
||||||
const EVERY = 60 * 60 * 1000
|
const EVERY = 60 * 60 * 1000
|
||||||
|
|
||||||
|
// How far along it is, for the ring in the top bar (connection_controller.js).
|
||||||
|
const progress = (done, total) => document.dispatchEvent(new CustomEvent("sam:progress", { detail: { source: "prep", done, total } }))
|
||||||
|
|
||||||
export default class extends Controller {
|
export default class extends Controller {
|
||||||
static values = { aircraft: Array }
|
static values = { aircraft: Array }
|
||||||
|
|
||||||
@@ -30,13 +33,22 @@ export default class extends Controller {
|
|||||||
forms[a.flight] = { tail: a.tail, kind: "flight" }
|
forms[a.flight] = { tail: a.tail, kind: "flight" }
|
||||||
forms[a.squawk] = { tail: a.tail, kind: "squawk" }
|
forms[a.squawk] = { tail: a.tail, kind: "squawk" }
|
||||||
}
|
}
|
||||||
for (const path of paths) {
|
const pictures = this.aircraftValue.flatMap((a) => a.pictures || [])
|
||||||
if (!navigator.onLine) return
|
const total = paths.length + 1
|
||||||
// One at a time, after the page has settled, so it never competes with what you're doing.
|
try {
|
||||||
await new Promise((resolve) => (window.requestIdleCallback || setTimeout)(resolve, { timeout: 2000 }))
|
for (const [ index, path ] of paths.entries()) {
|
||||||
try { await fetch(path, { credentials: "same-origin", headers: { Accept: "text/html" } }) } catch (_) { return }
|
progress(index, total)
|
||||||
}
|
if (!navigator.onLine) return
|
||||||
await this.savePictures(this.aircraftValue.map((a) => a.picture).filter(Boolean))
|
// One at a time, after the page has settled, so it never competes with what you're doing.
|
||||||
|
await new Promise((resolve) => (window.requestIdleCallback || setTimeout)(resolve, { timeout: 2000 }))
|
||||||
|
try { await fetch(path, { credentials: "same-origin", headers: { Accept: "text/html" } }) } catch (_) {
|
||||||
|
document.dispatchEvent(new CustomEvent("sam:unreachable"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
progress(paths.length, total)
|
||||||
|
await this.savePictures(pictures)
|
||||||
|
} finally { progress(total, total) }
|
||||||
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 +70,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 }
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,20 @@
|
|||||||
import { Controller } from "@hotwired/stimulus"
|
import { Controller } from "@hotwired/stimulus"
|
||||||
import { t } from "i18n"
|
import { t } from "i18n"
|
||||||
import { queue } from "controllers/offline_queue"
|
import { queue } from "controllers/offline_queue"
|
||||||
|
import { serverReachable } from "controllers/connection_controller"
|
||||||
|
|
||||||
|
// How long to wait for the server to take one before trying again later
|
||||||
|
// (a weak signal can leave a request hanging for minutes). Photos take longer.
|
||||||
|
const WAIT = 15 * 1000
|
||||||
|
const WAIT_WITH_FILES = 60 * 1000
|
||||||
|
|
||||||
|
const report = (name, detail) => document.dispatchEvent(new CustomEvent(name, { detail }))
|
||||||
|
|
||||||
// On every page: sends the flights and squawks this user saved offline once
|
// On every page: sends the flights and squawks this user saved offline once
|
||||||
// there's a connection, says what happened, and shows the count on the app
|
// there's a connection, says what happened, and shows the count on the app
|
||||||
// icon. A rejected item stays until it's discarded.
|
// icon. A rejected item stays until it's discarded. Nothing is tried while
|
||||||
|
// the top bar is red; it goes again as soon as it turns back
|
||||||
|
// (connection_controller.js), signal or not.
|
||||||
export default class extends Controller {
|
export default class extends Controller {
|
||||||
static targets = [ "banner" ]
|
static targets = [ "banner" ]
|
||||||
|
|
||||||
@@ -12,30 +22,37 @@ export default class extends Controller {
|
|||||||
this.sync = this.sync.bind(this)
|
this.sync = this.sync.bind(this)
|
||||||
window.addEventListener("online", this.sync)
|
window.addEventListener("online", this.sync)
|
||||||
document.addEventListener("offline-queue:changed", this.sync)
|
document.addEventListener("offline-queue:changed", this.sync)
|
||||||
|
document.addEventListener("sam:back-online", this.sync)
|
||||||
this.sync()
|
this.sync()
|
||||||
}
|
}
|
||||||
|
|
||||||
disconnect() {
|
disconnect() {
|
||||||
window.removeEventListener("online", this.sync)
|
window.removeEventListener("online", this.sync)
|
||||||
document.removeEventListener("offline-queue:changed", this.sync)
|
document.removeEventListener("offline-queue:changed", this.sync)
|
||||||
|
document.removeEventListener("sam:back-online", this.sync)
|
||||||
}
|
}
|
||||||
|
|
||||||
async sync() {
|
async sync() {
|
||||||
let items
|
let items
|
||||||
try { items = await queue.mine() } catch (_) { return }
|
try { items = await queue.mine() } catch (_) { return }
|
||||||
if (!items.length) { this.badge(0); return this.show("") }
|
if (!items.length) { this.badge(0); report("sam:waiting", { count: 0 }); return this.show("") }
|
||||||
if (!navigator.onLine || this.running) return this.status(items)
|
if (!navigator.onLine || !serverReachable() || this.running) return this.status(items)
|
||||||
this.running = true
|
this.running = true
|
||||||
const sent = []
|
const sent = []
|
||||||
|
const sending = items.filter((i) => !i.error)
|
||||||
try {
|
try {
|
||||||
for (const item of items.filter((i) => !i.error)) {
|
for (const [ index, item ] of sending.entries()) {
|
||||||
|
report("sam:progress", { source: "send", done: index, total: sending.length })
|
||||||
const result = await this.send(item)
|
const result = await this.send(item)
|
||||||
if (result === "sent") { await queue.remove(item.id); sent.push(item) }
|
if (result === "sent") { await queue.remove(item.id); sent.push(item); report("sam:reachable") }
|
||||||
else if (result === "signin") { this.show(t("offline.sign_in")); return }
|
else if (result === "signin") { this.show(t("offline.sign_in")); return }
|
||||||
else if (result === "offline") break
|
else if (result === "offline") { report("sam:unreachable"); break }
|
||||||
else { item.error = result; await queue.put(item) }
|
else { item.error = result; await queue.put(item) }
|
||||||
}
|
}
|
||||||
} finally { this.running = false }
|
} finally {
|
||||||
|
this.running = false
|
||||||
|
report("sam:progress", { source: "send", done: 0, total: 0 })
|
||||||
|
}
|
||||||
this.status(await queue.mine(), sent)
|
this.status(await queue.mine(), sent)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,7 +63,9 @@ export default class extends Controller {
|
|||||||
if (token) body.append("authenticity_token", token)
|
if (token) body.append("authenticity_token", token)
|
||||||
let response
|
let response
|
||||||
try {
|
try {
|
||||||
response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" } })
|
const files = item.fields.some(([ , value ]) => value instanceof Blob)
|
||||||
|
response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" },
|
||||||
|
signal: AbortSignal.timeout(files ? WAIT_WITH_FILES : WAIT) })
|
||||||
} catch (_) { return "offline" }
|
} catch (_) { return "offline" }
|
||||||
if ([ 502, 503, 504 ].includes(response.status)) return "offline"
|
if ([ 502, 503, 504 ].includes(response.status)) return "offline"
|
||||||
if (response.url.includes("/session/new")) return "signin"
|
if (response.url.includes("/session/new")) return "signin"
|
||||||
@@ -68,6 +87,7 @@ export default class extends Controller {
|
|||||||
}
|
}
|
||||||
this.show(parts.join(" "), failed)
|
this.show(parts.join(" "), failed)
|
||||||
this.badge(items.length)
|
this.badge(items.length)
|
||||||
|
report("sam:waiting", { count: waiting.length })
|
||||||
}
|
}
|
||||||
|
|
||||||
// The number of unsent items on the installed app's icon.
|
// The number of unsent items on the installed app's icon.
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import { Controller } from "@hotwired/stimulus"
|
||||||
|
import { t } from "i18n"
|
||||||
|
|
||||||
|
// A PDF in the document viewer. Desktop browsers show it in their own viewer,
|
||||||
|
// in a frame. Phones don't: Android shows nothing in a frame and iPhones only
|
||||||
|
// the first page, so there every page is drawn with PDF.js (public/pdfjs,
|
||||||
|
// loaded only here), each one as it scrolls into view, fetching only the
|
||||||
|
// parts of the file those pages need.
|
||||||
|
export default class extends Controller {
|
||||||
|
static targets = [ "frame", "status", "pages" ]
|
||||||
|
static values = { url: String, pdfjs: String }
|
||||||
|
|
||||||
|
// Starts over each time, as a page restored from Turbo's cache comes back
|
||||||
|
// with blank pages.
|
||||||
|
connect() {
|
||||||
|
this.pagesTarget.replaceChildren()
|
||||||
|
this.statusTarget.replaceChildren(t("pdf.loading"))
|
||||||
|
this.statusTarget.hidden = false
|
||||||
|
if (navigator.pdfViewerEnabled && !matchMedia("(pointer: coarse)").matches) return this.showFrame()
|
||||||
|
this.draw().catch((error) => this.failed(error))
|
||||||
|
}
|
||||||
|
|
||||||
|
disconnect() {
|
||||||
|
this.observer?.disconnect()
|
||||||
|
this.loading?.destroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
showFrame() {
|
||||||
|
this.statusTarget.hidden = true
|
||||||
|
this.pagesTarget.append(this.frameTarget.content.cloneNode(true))
|
||||||
|
}
|
||||||
|
|
||||||
|
async draw() {
|
||||||
|
const base = this.pdfjsValue
|
||||||
|
const pdfjs = await import(`${base}pdf.min.mjs`)
|
||||||
|
pdfjs.GlobalWorkerOptions.workerSrc = `${base}pdf.worker.min.mjs`
|
||||||
|
this.loading = pdfjs.getDocument({
|
||||||
|
url: this.urlValue,
|
||||||
|
withCredentials: true,
|
||||||
|
// Only the parts needed for the pages being drawn, not the whole file
|
||||||
|
// in the background (a long manual on a phone's data plan).
|
||||||
|
disableAutoFetch: true,
|
||||||
|
disableStream: true,
|
||||||
|
wasmUrl: `${base}wasm/`,
|
||||||
|
standardFontDataUrl: `${base}standard_fonts/`,
|
||||||
|
iccUrl: `${base}iccs/`
|
||||||
|
})
|
||||||
|
const pdf = await this.loading.promise
|
||||||
|
if (!this.element.isConnected) return
|
||||||
|
|
||||||
|
// Placeholders the size of the first page keep the scroll position steady
|
||||||
|
// while pages are drawn; each takes its own shape once it's drawn.
|
||||||
|
const first = (await pdf.getPage(1)).getViewport({ scale: 1 })
|
||||||
|
// Pages are drawn as they come near the screen and let go once they're
|
||||||
|
// far from it, so a long manual doesn't use up a phone's memory.
|
||||||
|
this.observer = new IntersectionObserver((entries) => {
|
||||||
|
for (const { target, isIntersecting } of entries) {
|
||||||
|
target.dataset.near = isIntersecting
|
||||||
|
if (isIntersecting && !target.dataset.drawn) this.drawPage(pdf, target)
|
||||||
|
else if (!isIntersecting && target.dataset.drawn) { delete target.dataset.drawn; target.replaceChildren() }
|
||||||
|
}
|
||||||
|
}, { rootMargin: "200% 0px" })
|
||||||
|
|
||||||
|
for (let number = 1; number <= pdf.numPages; number++) {
|
||||||
|
const page = document.createElement("div")
|
||||||
|
page.className = "relative w-full bg-white shadow-sm ring-1 ring-slate-200"
|
||||||
|
page.style.aspectRatio = `${first.width} / ${first.height}`
|
||||||
|
page.dataset.page = number
|
||||||
|
page.setAttribute("role", "img")
|
||||||
|
page.setAttribute("aria-label", t("pdf.page", { page: number, pages: pdf.numPages }))
|
||||||
|
this.pagesTarget.append(page)
|
||||||
|
this.observer.observe(page)
|
||||||
|
}
|
||||||
|
this.statusTarget.hidden = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async drawPage(pdf, holder) {
|
||||||
|
holder.dataset.drawn = "drawing"
|
||||||
|
try {
|
||||||
|
const page = await pdf.getPage(Number(holder.dataset.page))
|
||||||
|
const natural = page.getViewport({ scale: 1 })
|
||||||
|
holder.style.aspectRatio = `${natural.width} / ${natural.height}`
|
||||||
|
// Sharp on the screen and when pinched in a little.
|
||||||
|
const density = Math.min((window.devicePixelRatio || 1) * 1.25, 2.5)
|
||||||
|
const viewport = page.getViewport({ scale: (holder.clientWidth * density) / natural.width })
|
||||||
|
const canvas = document.createElement("canvas")
|
||||||
|
canvas.width = Math.floor(viewport.width)
|
||||||
|
canvas.height = Math.floor(viewport.height)
|
||||||
|
canvas.className = "block h-auto w-full"
|
||||||
|
await page.render({ canvas, canvasContext: canvas.getContext("2d"), viewport }).promise
|
||||||
|
page.cleanup()
|
||||||
|
if (holder.dataset.near !== "true") { canvas.width = canvas.height = 0; delete holder.dataset.drawn; return } // scrolled away meanwhile
|
||||||
|
holder.dataset.drawn = "drawn"
|
||||||
|
holder.replaceChildren(canvas)
|
||||||
|
} catch (_) {
|
||||||
|
holder.dataset.drawn = "failed"
|
||||||
|
holder.replaceChildren(Object.assign(document.createElement("p"), { className: "p-6 text-center text-sm text-slate-500", textContent: t("pdf.page_failed") }))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Can't draw it here (an old browser, or not a readable PDF): the browser's own viewer is one tap away.
|
||||||
|
failed(error) {
|
||||||
|
if (!this.element.isConnected) return
|
||||||
|
console.warn("PDF viewer:", error)
|
||||||
|
this.statusTarget.hidden = false
|
||||||
|
this.statusTarget.replaceChildren(t("pdf.failed"), " ")
|
||||||
|
this.statusTarget.append(Object.assign(document.createElement("a"), { href: this.urlValue, target: "_blank", rel: "noopener", className: "link", textContent: t("pdf.open") }))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
require "net/http"
|
||||||
|
|
||||||
|
# Posts one webhook delivery. The body is signed so the receiver can check
|
||||||
|
# it came from here and wasn't replayed:
|
||||||
|
# SAM-Signature: t=<unix time>,v1=<hex HMAC-SHA256 of "<t>.<body>" with the endpoint's secret>
|
||||||
|
# Anything but a 2xx answer is retried with growing waits, then marked failed.
|
||||||
|
class WebhookDeliveryJob < ApplicationJob
|
||||||
|
queue_as :default
|
||||||
|
ATTEMPTS = 8
|
||||||
|
|
||||||
|
class Failed < StandardError; end
|
||||||
|
|
||||||
|
retry_on Failed, wait: :polynomially_longer, attempts: ATTEMPTS do |job, error|
|
||||||
|
WebhookDelivery.find_by(id: job.arguments.first)&.update!(status: "failed", last_error: error.message.truncate(250))
|
||||||
|
end
|
||||||
|
|
||||||
|
def perform(delivery_id)
|
||||||
|
delivery = WebhookDelivery.includes(:webhook_endpoint).find_by(id: delivery_id) or return
|
||||||
|
return if delivery.status == "delivered"
|
||||||
|
endpoint = delivery.webhook_endpoint
|
||||||
|
delivery.increment!(:attempts)
|
||||||
|
response = post(endpoint, delivery)
|
||||||
|
if response.code.to_i.between?(200, 299)
|
||||||
|
delivery.update!(status: "delivered", response_status: response.code.to_i, delivered_at: Time.current, last_error: nil)
|
||||||
|
else
|
||||||
|
delivery.update!(response_status: response.code.to_i, last_error: "HTTP #{response.code}")
|
||||||
|
raise Failed, "HTTP #{response.code}"
|
||||||
|
end
|
||||||
|
rescue OutboundAddress::Blocked => e
|
||||||
|
# Pointed at an address the server won't send to: retrying won't help.
|
||||||
|
delivery.update!(status: "failed", last_error: "blocked address (#{e.reason})")
|
||||||
|
rescue Timeout::Error, SocketError, SystemCallError, OpenSSL::SSL::SSLError, EOFError, IOError => e
|
||||||
|
delivery.update!(last_error: "#{e.class.name.demodulize}: #{e.message}".truncate(250))
|
||||||
|
raise Failed, e.message
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def post(endpoint, delivery)
|
||||||
|
uri = URI.parse(endpoint.url)
|
||||||
|
timestamp = Time.current.to_i
|
||||||
|
signature = OpenSSL::HMAC.hexdigest("SHA256", endpoint.secret, "#{timestamp}.#{delivery.payload}")
|
||||||
|
req = Net::HTTP::Post.new(uri)
|
||||||
|
req["Content-Type"] = "application/json"
|
||||||
|
req["User-Agent"] = "SimpleAircraftManager-Webhooks"
|
||||||
|
req["SAM-Event"] = delivery.event
|
||||||
|
req["SAM-Delivery"] = delivery.id.to_s
|
||||||
|
req["SAM-Signature"] = "t=#{timestamp},v1=#{signature}"
|
||||||
|
req.body = delivery.payload
|
||||||
|
http = Net::HTTP.new(uri.host, uri.port)
|
||||||
|
http.ipaddr = OutboundAddress.resolve!(uri.host, allow_private: true) # set up by an admin: the private network is fine
|
||||||
|
http.use_ssl = uri.scheme == "https"
|
||||||
|
http.open_timeout = 5
|
||||||
|
http.read_timeout = 10
|
||||||
|
http.start { _1.request(req) }
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -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)
|
||||||
|
|||||||
@@ -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"
|
||||||
|
|
||||||
|
|||||||
+19
-2
@@ -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
|
||||||
@@ -11,6 +16,7 @@ class Aircraft < ApplicationRecord
|
|||||||
has_many :components, dependent: :destroy
|
has_many :components, dependent: :destroy
|
||||||
has_many :squawks, dependent: :destroy
|
has_many :squawks, dependent: :destroy
|
||||||
has_many :logbook_entries, dependent: :destroy
|
has_many :logbook_entries, dependent: :destroy
|
||||||
|
has_many :draft_batches, dependent: :destroy
|
||||||
has_many :logbook_imports, dependent: :destroy
|
has_many :logbook_imports, dependent: :destroy
|
||||||
has_many :document_collections, dependent: :destroy
|
has_many :document_collections, dependent: :destroy
|
||||||
has_many :documents, dependent: :destroy
|
has_many :documents, dependent: :destroy
|
||||||
@@ -77,10 +83,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
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# A write sent with an Idempotency-Key header, and the answer it got: the
|
||||||
|
# same key again (a retry) gets the same answer instead of a second record.
|
||||||
|
class ApiIdempotencyKey < ApplicationRecord
|
||||||
|
KEEP_FOR = 24.hours
|
||||||
|
|
||||||
|
belongs_to :api_token
|
||||||
|
|
||||||
|
def self.purge_old = where(created_at: ...KEEP_FOR.ago).delete_all
|
||||||
|
end
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# A key for the REST API (docs/api.md). Only its SHA-256 digest is kept; the
|
||||||
|
# token itself is shown once, when it's made.
|
||||||
|
#
|
||||||
|
# personal: acts as its owner, with exactly their aircraft and role.
|
||||||
|
# integration: made by an admin for another system (e.g. Redmine), limited to
|
||||||
|
# chosen aircraft and scopes. Its writes name the person they're
|
||||||
|
# for (SAM-On-Behalf-Of), so the record history always shows who.
|
||||||
|
class ApiToken < ApplicationRecord
|
||||||
|
KINDS = %w[personal integration].freeze
|
||||||
|
SCOPES = LabelSet.new("api_token.scopes", %w[read squawks:write drafts:write])
|
||||||
|
PREFIX = "sam_"
|
||||||
|
|
||||||
|
belongs_to :user
|
||||||
|
has_many :webhook_endpoints, dependent: :destroy
|
||||||
|
has_many :idempotency_keys, class_name: "ApiIdempotencyKey", dependent: :delete_all
|
||||||
|
|
||||||
|
attr_reader :token # the plain token, only right after create
|
||||||
|
|
||||||
|
normalizes :name, with: ->(n) { n.to_s.strip }
|
||||||
|
validates :name, presence: true, length: { maximum: 80 }
|
||||||
|
validates :kind, inclusion: { in: KINDS }
|
||||||
|
validate :scopes_known
|
||||||
|
validate :integration_made_by_admin, on: :create
|
||||||
|
|
||||||
|
before_validation :generate, on: :create
|
||||||
|
|
||||||
|
scope :active, -> { where(revoked_at: nil) }
|
||||||
|
scope :personal, -> { where(kind: "personal") }
|
||||||
|
scope :integration, -> { where(kind: "integration") }
|
||||||
|
|
||||||
|
def self.digest(token) = OpenSSL::Digest::SHA256.hexdigest(token.to_s)
|
||||||
|
|
||||||
|
# The token for this string, if it's in use (and its owner is too).
|
||||||
|
def self.authenticate(token)
|
||||||
|
return unless token.to_s.start_with?(PREFIX)
|
||||||
|
found = active.includes(:user).find_by(token_digest: digest(token))
|
||||||
|
found if found && (found.integration? || !found.user.disabled?)
|
||||||
|
end
|
||||||
|
|
||||||
|
def personal? = kind == "personal"
|
||||||
|
def integration? = kind == "integration"
|
||||||
|
def revoked? = revoked_at.present?
|
||||||
|
def revoke! = update!(revoked_at: Time.current)
|
||||||
|
def allows?(scope) = scopes.include?(scope.to_s)
|
||||||
|
|
||||||
|
# The aircraft this token reaches, acting for `user` (who must also have
|
||||||
|
# access, for an integration acting on someone's behalf).
|
||||||
|
def aircraft_scope(acting_user)
|
||||||
|
if personal?
|
||||||
|
user.accessible_aircraft
|
||||||
|
else
|
||||||
|
reachable = Aircraft.where(id: Array(aircraft_ids))
|
||||||
|
acting_user ? reachable.where(id: acting_user.accessible_aircraft.select(:id)) : reachable
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# Last use, at most once a minute (no write per request).
|
||||||
|
def used!(ip)
|
||||||
|
return if last_used_at && last_used_at > 1.minute.ago && last_used_ip == ip
|
||||||
|
update_columns(last_used_at: Time.current, last_used_ip: ip)
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def generate
|
||||||
|
@token = "#{PREFIX}#{SecureRandom.base58(40)}"
|
||||||
|
self.token_digest = self.class.digest(@token)
|
||||||
|
self.token_hint = @token.first(PREFIX.length + 6)
|
||||||
|
self.scopes = Array(scopes).map(&:to_s).compact_blank.uniq
|
||||||
|
end
|
||||||
|
|
||||||
|
def scopes_known
|
||||||
|
errors.add(:scopes, :blank) if scopes.blank?
|
||||||
|
errors.add(:scopes, :inclusion) if (Array(scopes) - SCOPES.keys).any?
|
||||||
|
end
|
||||||
|
|
||||||
|
def integration_made_by_admin
|
||||||
|
errors.add(:kind, :admins_only) if integration? && !user&.admin?
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# The release notes (CHANGELOG.md) split into releases, so the app can show
|
||||||
|
# the running version's notes on their own and fold away older ones. The
|
||||||
|
# file stays one plain Markdown document (it reads the same on GitHub):
|
||||||
|
#
|
||||||
|
# # What's new
|
||||||
|
# intro...
|
||||||
|
# ## 2026.11.5
|
||||||
|
# ### Changes
|
||||||
|
# - ...
|
||||||
|
# ### Fixes
|
||||||
|
# - ...
|
||||||
|
class Changelog
|
||||||
|
PATH = Rails.root.join("CHANGELOG.md")
|
||||||
|
# The section headings counted in a release's one-line summary; items
|
||||||
|
# under any other heading (the first release's highlights) count as notes.
|
||||||
|
SECTIONS = { "Changes" => :changes, "Fixes" => :fixes, "For administrators" => :administrators }.freeze
|
||||||
|
|
||||||
|
Release = Data.define(:version, :markdown) do
|
||||||
|
def year = version.split(".")[0].to_i
|
||||||
|
def month = version.split(".")[1].to_i
|
||||||
|
def month_start = Date.new(year, month, 1)
|
||||||
|
def anchor = "v#{version.tr('.', '-')}"
|
||||||
|
|
||||||
|
# { changes: 4, fixes: 3 }: the top-level items under each heading.
|
||||||
|
def counts
|
||||||
|
counts = markdown.split(/^### /).drop(1).each_with_object(Hash.new(0)) do |section, tally|
|
||||||
|
heading, body = section.split("\n", 2)
|
||||||
|
tally[SECTIONS.fetch(heading.strip, :notes)] += body.to_s.scan(/^- /).size
|
||||||
|
end
|
||||||
|
(SECTIONS.values + [ :notes ]).filter_map { |key| [ key, counts[key] ] if counts[key].positive? }.to_h
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.load = new(PATH.file? ? PATH.read : "")
|
||||||
|
|
||||||
|
attr_reader :title, :intro, :releases
|
||||||
|
|
||||||
|
def initialize(markdown)
|
||||||
|
head, *parts = markdown.split(/^## /)
|
||||||
|
@title = head[/\A# (.+)$/, 1] || "What's new"
|
||||||
|
@intro = head.sub(/\A# .+\n+/, "").strip
|
||||||
|
@releases = parts.filter_map do |part|
|
||||||
|
version, body = part.split("\n", 2)
|
||||||
|
version = version.strip
|
||||||
|
Release.new(version: version, markdown: body.to_s.strip) if version.match?(/\A\d{4}\.\d{1,2}\.\d+\z/)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def release(version) = releases.find { _1.version == version }
|
||||||
|
|
||||||
|
# Shown open: the running version and any newer (or the newest, when the
|
||||||
|
# running version has no notes, such as in development).
|
||||||
|
def open?(release, running:)
|
||||||
|
index = releases.index { _1.version == running } || 0
|
||||||
|
releases.index(release) <= index
|
||||||
|
end
|
||||||
|
end
|
||||||
+15
-4
@@ -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,4 +1,7 @@
|
|||||||
class Current < ActiveSupport::CurrentAttributes
|
class Current < ActiveSupport::CurrentAttributes
|
||||||
attribute :session, :ip_address
|
# api_token / api_user: an API request (see Api::V1::BaseController), which
|
||||||
delegate :user, to: :session, allow_nil: true
|
# acts as a person without a browser session.
|
||||||
|
attribute :session, :ip_address, :api_token, :api_user
|
||||||
|
|
||||||
|
def user = api_user || session&.user
|
||||||
end
|
end
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# One visit's work sent through the API as draft logbook entries: an
|
||||||
|
# unsigned entry for each logbook it touches, signed in the app like any
|
||||||
|
# other entry (by an aircraft user, or a mechanic invited to sign).
|
||||||
|
#
|
||||||
|
# What the work resolves (squawks, inspections) is held until every entry in
|
||||||
|
# the batch is signed: a draft never clears a squawk or completes an
|
||||||
|
# inspection on its own.
|
||||||
|
class DraftBatch < ApplicationRecord
|
||||||
|
include Versioned
|
||||||
|
|
||||||
|
STATUSES = %w[awaiting_signature completed withdrawn].freeze
|
||||||
|
|
||||||
|
belongs_to :aircraft
|
||||||
|
belongs_to :api_token, optional: true
|
||||||
|
belongs_to :created_by, class_name: "User", optional: true
|
||||||
|
has_many :entries, class_name: "LogbookEntry", dependent: :nullify
|
||||||
|
|
||||||
|
validates :status, inclusion: { in: STATUSES }
|
||||||
|
|
||||||
|
def awaiting? = status == "awaiting_signature"
|
||||||
|
|
||||||
|
def held_squawks = Array(held["squawks"])
|
||||||
|
def held_inspections = Array(held["inspections"])
|
||||||
|
|
||||||
|
# What signing will do, for the signer to see before they sign.
|
||||||
|
def held_effects_for(entry)
|
||||||
|
squawks = aircraft.squawks.where(id: held_squawks.select { _1["log"] == entry.log_type }.map { _1["id"] })
|
||||||
|
types = aircraft.applicable_inspection_types.where(id: held_inspections.select { _1["log"] == entry.log_type }.map { _1["id"] })
|
||||||
|
{ squawks: squawks.to_a, inspections: types.to_a }
|
||||||
|
end
|
||||||
|
|
||||||
|
# Called when one of its entries is signed: once they all are, the held
|
||||||
|
# changes are made, attributed to the person who signed last.
|
||||||
|
def entry_signed!
|
||||||
|
return unless awaiting?
|
||||||
|
with_lock do
|
||||||
|
return unless awaiting? && entries.reload.all?(&:signed?)
|
||||||
|
by_log = entries.index_by(&:log_type)
|
||||||
|
aircraft.squawks.active.where(id: held_squawks.map { _1["id"] }).find_each do |squawk|
|
||||||
|
entry = by_log[held_squawks.find { _1["id"] == squawk.id }["log"]]
|
||||||
|
squawk.resolve!(logbook_entry: entry)
|
||||||
|
aircraft.log_event!("squawk", I18n.t("flash.squawks.squawk_resolved_2"), notes: squawk.issue_reported.truncate(200))
|
||||||
|
end
|
||||||
|
aircraft.applicable_inspection_types.where(id: held_inspections.map { _1["id"] }).find_each do |type|
|
||||||
|
entry = by_log[held_inspections.find { _1["id"] == type.id }["log"]]
|
||||||
|
aircraft.inspection_records.create!(inspection_type: type, logbook_entry: entry, date: entry.date, aircraft_hours: entry.aircraft_hours_at_entry)
|
||||||
|
aircraft.log_event!("inspection", I18n.t("flash.logbook_entries.inspection_completed_logbook_entry",
|
||||||
|
name: type.name, date: I18n.l(entry.date, format: :app)))
|
||||||
|
end
|
||||||
|
update!(status: "completed", completed_at: Time.current)
|
||||||
|
end
|
||||||
|
Webhooks.publish("draft_batch.completed", aircraft: aircraft, data: ApiPresenter.draft_batch(self))
|
||||||
|
end
|
||||||
|
|
||||||
|
# Withdraws an unsigned batch: its entries are removed (kept in the record history).
|
||||||
|
def withdraw!
|
||||||
|
transaction do
|
||||||
|
raise ActiveRecord::RecordInvalid, self if entries.any?(&:signed?)
|
||||||
|
entries.each(&:destroy!)
|
||||||
|
update!(status: "withdrawn")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -18,6 +18,13 @@ class EntrySignature < ApplicationRecord
|
|||||||
validates :auth_method, inclusion: { in: AUTH_METHODS.keys + [ "imported" ] }
|
validates :auth_method, inclusion: { in: AUTH_METHODS.keys + [ "imported" ] }
|
||||||
validates :logbook_entry_id, uniqueness: true
|
validates :logbook_entry_id, uniqueness: true
|
||||||
before_create { self.seal ||= compute_seal unless imported? }
|
before_create { self.seal ||= compute_seal unless imported? }
|
||||||
|
# Integrations hear about it (webhooks); not for signatures carried over by an import.
|
||||||
|
after_create_commit do
|
||||||
|
next if imported?
|
||||||
|
entry = logbook_entry
|
||||||
|
Webhooks.publish("entry.signed", aircraft: entry.aircraft, data: ApiPresenter.logbook_entry(entry))
|
||||||
|
entry.draft_batch&.entry_signed! # a draft from the API: its held changes once all its entries are signed
|
||||||
|
end
|
||||||
before_update { throw :abort } # signatures are permanent (2.1.2.7)
|
before_update { throw :abort } # signatures are permanent (2.1.2.7)
|
||||||
before_destroy { throw :abort unless destroyed_by_association }
|
before_destroy { throw :abort unless destroyed_by_association }
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
class HelpGuide
|
class HelpGuide
|
||||||
DIR = Rails.root.join("docs/guide")
|
DIR = Rails.root.join("docs/guide")
|
||||||
ORDER = %w[README getting-started profile aircraft flights squawks oil-and-fuel components logbook records
|
ORDER = %w[README getting-started profile aircraft flights squawks oil-and-fuel components logbook records
|
||||||
inspections ads documents major-records sharing administration disclaimer changelog].freeze
|
inspections ads documents major-records sharing administration api disclaimer changelog].freeze
|
||||||
OPTIONS = {
|
OPTIONS = {
|
||||||
parse: { smart: true },
|
parse: { smart: true },
|
||||||
render: { hardbreaks: false, unsafe: false },
|
render: { hardbreaks: false, unsafe: false },
|
||||||
@@ -27,7 +27,11 @@ class HelpGuide
|
|||||||
# Sanitized HTML. Links to other guide pages ("records.md#mistakes") go
|
# Sanitized HTML. Links to other guide pages ("records.md#mistakes") go
|
||||||
# through `link` (slug, anchor) -> URL, or become plain text when nil.
|
# through `link` (slug, anchor) -> URL, or become plain text when nil.
|
||||||
def self.html(page, link:, title: true)
|
def self.html(page, link:, title: true)
|
||||||
source = title ? page.markdown : page.markdown.sub(/\A# .+\n+/, "")
|
render(title ? page.markdown : page.markdown.sub(/\A# .+\n+/, ""), link: link)
|
||||||
|
end
|
||||||
|
|
||||||
|
# Any Markdown from the guide (or a part of it, such as one release of the changelog).
|
||||||
|
def self.render(source, link:)
|
||||||
html = Commonmarker.to_html(source, options: OPTIONS, plugins: { syntax_highlighter: nil })
|
html = Commonmarker.to_html(source, options: OPTIONS, plugins: { syntax_highlighter: nil })
|
||||||
html = Rails::HTML5::SafeListSanitizer.new.sanitize(html, tags: TAGS, attributes: ATTRIBUTES)
|
html = Rails::HTML5::SafeListSanitizer.new.sanitize(html, tags: TAGS, attributes: ATTRIBUTES)
|
||||||
html.gsub(%r{<a href="([a-z-]+|README)\.md(?:#([a-z0-9-]+))?">(.*?)</a>}m) do
|
html.gsub(%r{<a href="([a-z-]+|README)\.md(?:#([a-z0-9-]+))?">(.*?)</a>}m) do
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ class LogbookEntry < ApplicationRecord
|
|||||||
belongs_to :document, optional: true
|
belongs_to :document, optional: true
|
||||||
# For engine / propeller logs: which one, and its times at this entry.
|
# For engine / propeller logs: which one, and its times at this entry.
|
||||||
belongs_to :component, optional: true
|
belongs_to :component, optional: true
|
||||||
|
belongs_to :draft_batch, optional: true # made through the API, see DraftBatch
|
||||||
# Sub-components it also covers (the oil filter on the engine…).
|
# Sub-components it also covers (the oil filter on the engine…).
|
||||||
has_many :parts, -> { includes(component: :component_type).order(:id) }, class_name: "LogbookEntryPart",
|
has_many :parts, -> { includes(component: :component_type).order(:id) }, class_name: "LogbookEntryPart",
|
||||||
dependent: :destroy, autosave: true
|
dependent: :destroy, autosave: true
|
||||||
@@ -33,6 +34,7 @@ class LogbookEntry < ApplicationRecord
|
|||||||
validates :signoff_certificate_type, inclusion: { in: CERTIFICATE_TYPES.keys }, allow_blank: true
|
validates :signoff_certificate_type, inclusion: { in: CERTIFICATE_TYPES.keys }, allow_blank: true
|
||||||
validates :inspection_result, inclusion: { in: INSPECTION_RESULTS.keys }, allow_blank: true
|
validates :inspection_result, inclusion: { in: INSPECTION_RESULTS.keys }, allow_blank: true
|
||||||
validates :component_hours_at_entry, :component_since_overhaul_at_entry, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
|
validates :component_hours_at_entry, :component_since_overhaul_at_entry, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
|
||||||
|
normalizes :external_ref, with: ->(r) { r.to_s.strip.first(200).presence }
|
||||||
normalizes :signoff_certificate_type, :inspection_result, :signoff_certificate_number, with: ->(v) { v.strip.presence }
|
normalizes :signoff_certificate_type, :inspection_result, :signoff_certificate_number, with: ->(v) { v.strip.presence }
|
||||||
|
|
||||||
# Fields that may still change on a signed entry: its link to a scanned
|
# Fields that may still change on a signed entry: its link to a scanned
|
||||||
|
|||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
# editing a version breaks the chain and the nightly check reports it.
|
# editing a version breaks the chain and the nightly check reports it.
|
||||||
class RecordVersion < ApplicationRecord
|
class RecordVersion < ApplicationRecord
|
||||||
belongs_to :user, optional: true
|
belongs_to :user, optional: true
|
||||||
|
belongs_to :api_token, optional: true
|
||||||
|
|
||||||
scope :chronological, -> { order(:id) }
|
scope :chronological, -> { order(:id) }
|
||||||
|
|
||||||
@@ -15,10 +16,12 @@ class RecordVersion < ApplicationRecord
|
|||||||
def self.append!(item:, aircraft_id:, event:, changes:)
|
def self.append!(item:, aircraft_id:, event:, changes:)
|
||||||
now = Time.current
|
now = Time.current
|
||||||
payload = { "item_type" => item.class.name, "item_id" => item.id, "event" => event, "changes" => changes,
|
payload = { "item_type" => item.class.name, "item_id" => item.id, "event" => event, "changes" => changes,
|
||||||
"user_id" => Current.user&.id, "at" => now.utc.iso8601(6) }.to_json
|
"user_id" => Current.user&.id, "at" => now.utc.iso8601(6) }
|
||||||
|
payload["api_token_id"] = Current.api_token.id if Current.api_token # made through the API (part of the hashed payload)
|
||||||
|
payload = payload.to_json
|
||||||
prev = where(aircraft_id: aircraft_id).order(:id).last&.chain_hash
|
prev = where(aircraft_id: aircraft_id).order(:id).last&.chain_hash
|
||||||
create!(aircraft_id: aircraft_id, item_type: item.class.name, item_id: item.id, event: event, user_id: Current.user&.id,
|
create!(aircraft_id: aircraft_id, item_type: item.class.name, item_id: item.id, event: event, user_id: Current.user&.id,
|
||||||
ip_address: Current.ip_address, payload: payload, prev_hash: prev, chain_hash: digest(prev, payload), created_at: now)
|
ip_address: Current.ip_address, api_token_id: Current.api_token&.id, payload: payload, prev_hash: prev, chain_hash: digest(prev, payload), created_at: now)
|
||||||
end
|
end
|
||||||
|
|
||||||
def changes_hash = JSON.parse(payload)["changes"]
|
def changes_hash = JSON.parse(payload)["changes"]
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -11,6 +11,15 @@ class Squawk < ApplicationRecord
|
|||||||
belongs_to :logbook_entry, optional: true
|
belongs_to :logbook_entry, optional: true
|
||||||
has_many_attached :attachments
|
has_many_attached :attachments
|
||||||
|
|
||||||
|
# Integrations hear about squawks (webhooks), once the change is saved.
|
||||||
|
after_create_commit { Webhooks.publish("squawk.created", aircraft: aircraft, data: ApiPresenter.squawk(self)) }
|
||||||
|
after_update_commit do
|
||||||
|
next if (saved_changes.keys - %w[updated_at]).empty?
|
||||||
|
event = saved_change_to_resolved? && resolved? ? "squawk.resolved" : "squawk.updated"
|
||||||
|
Webhooks.publish(event, aircraft: aircraft, data: ApiPresenter.squawk(self))
|
||||||
|
end
|
||||||
|
|
||||||
|
normalizes :external_ref, with: ->(r) { r.to_s.strip.first(200).presence }
|
||||||
validates :priority, inclusion: { in: PRIORITIES.keys }
|
validates :priority, inclusion: { in: PRIORITIES.keys }
|
||||||
validates :issue_reported, presence: true
|
validates :issue_reported, presence: true
|
||||||
validates_uploads :attachments
|
validates_uploads :attachments
|
||||||
|
|||||||
@@ -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,6 +3,10 @@ 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
|
||||||
|
has_many :api_tokens, dependent: :destroy
|
||||||
|
|
||||||
|
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
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# One event sent (or being sent) to a webhook endpoint; the recent ones are
|
||||||
|
# listed for the admin, with the answer the other system gave.
|
||||||
|
class WebhookDelivery < ApplicationRecord
|
||||||
|
KEEP_FOR = 30.days
|
||||||
|
|
||||||
|
belongs_to :webhook_endpoint
|
||||||
|
|
||||||
|
scope :recent, -> { order(created_at: :desc) }
|
||||||
|
|
||||||
|
def self.purge_old = where(created_at: ...KEEP_FOR.ago).delete_all
|
||||||
|
end
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Where an integration wants to hear about changes (squawks, signed entries):
|
||||||
|
# SAM posts JSON there, signed with the shared secret (see WebhookDeliveryJob).
|
||||||
|
class WebhookEndpoint < ApplicationRecord
|
||||||
|
EVENTS = LabelSet.new("webhook_endpoint.events", %w[squawk.created squawk.updated squawk.resolved entry.signed draft_batch.completed])
|
||||||
|
|
||||||
|
belongs_to :api_token
|
||||||
|
has_many :deliveries, class_name: "WebhookDelivery", dependent: :delete_all
|
||||||
|
|
||||||
|
encrypts :secret
|
||||||
|
|
||||||
|
normalizes :url, with: ->(u) { u.to_s.strip }
|
||||||
|
validates :url, presence: true, format: { with: %r{\Ahttps?://[^\s/]+(:\d+)?(/\S*)?\z}i }
|
||||||
|
validates :secret, presence: true, length: { minimum: 16 }
|
||||||
|
validate :events_known
|
||||||
|
|
||||||
|
scope :enabled, -> { where(enabled: true) }
|
||||||
|
|
||||||
|
def self.new_secret = SecureRandom.hex(32)
|
||||||
|
|
||||||
|
def subscribed?(event) = events.include?(event.to_s)
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def events_known
|
||||||
|
errors.add(:events, :blank) if events.blank?
|
||||||
|
errors.add(:events, :inclusion) if (Array(events) - EVENTS.keys).any?
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# What the API and webhooks send for each kind of record (docs/api.md).
|
||||||
|
# Times are ISO 8601 UTC, hours decimals, codes rather than translated labels.
|
||||||
|
module ApiPresenter
|
||||||
|
module_function
|
||||||
|
|
||||||
|
def aircraft(a)
|
||||||
|
aw = a.airworthiness
|
||||||
|
{ id: a.id, tail_number: a.tail_number, make: a.make, model: a.model, serial_number: a.serial_number,
|
||||||
|
icao_type: a.icao_type, status: a.status,
|
||||||
|
airworthiness: { status: aw.status, issues: aw.issues.map { { category: _1.category, severity: _1.severity, title: _1.title } } },
|
||||||
|
time_basis: a.time_basis, hours: dec(a.current_hours), tach: dec(a.tach_time), hobbs: dec(a.hobbs_time),
|
||||||
|
updated_at: time(a.updated_at) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def component(c)
|
||||||
|
{ id: c.id, aircraft_id: c.aircraft_id, parent_id: c.parent_component_id, type: c.component_type&.name,
|
||||||
|
manufacturer: c.manufacturer, model: c.model, serial_number: c.serial_number.presence,
|
||||||
|
location: c.install_location.presence, status: c.status, date_in_service: c.date_in_service&.iso8601,
|
||||||
|
hours_in_service: dec(c.hours_in_service), hours_since_overhaul: dec(c.hours_since_overhaul),
|
||||||
|
overhaul_date: c.overhaul_date&.iso8601, overhaul_kind: c.overhaul_kind.presence,
|
||||||
|
tbo: { hours: c.tbo_hours, days: c.tbo_days, months: c.tbo_months, on_condition: c.on_condition, critical: c.tbo_critical }.compact,
|
||||||
|
replacement: { hours: c.replacement_hours, days: c.replacement_days, months: c.replacement_months, critical: c.replacement_critical }.compact,
|
||||||
|
expires_on: c.expires_on&.iso8601, updated_at: time(c.updated_at) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def due_item(i)
|
||||||
|
{ key: i.key, title: i.title, kind: i.kind, due_date: i.date.iso8601, projected: i.projected,
|
||||||
|
due_hours: dec(i.due_hours), overdue: i.overdue? }
|
||||||
|
end
|
||||||
|
|
||||||
|
def squawk(s)
|
||||||
|
{ id: s.id, aircraft_id: s.aircraft_id, component_id: s.component_id, issue_reported: s.issue_reported,
|
||||||
|
priority: s.priority, grounding: s.grounding?, deferred: s.deferred?, resolved: !!s.resolved,
|
||||||
|
resolved_at: time(s.resolved_at), notes: s.notes.presence, logbook_entry_id: s.logbook_entry_id,
|
||||||
|
reported_by: s.reported_by&.display_name, external_ref: s.external_ref,
|
||||||
|
attachments: s.attachments.map { _1.filename.to_s },
|
||||||
|
created_at: time(s.created_at), updated_at: time(s.updated_at) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def logbook_entry(e)
|
||||||
|
sig = e.signature
|
||||||
|
{ id: e.id, aircraft_id: e.aircraft_id, component_id: e.component_id, log: e.log_type, entry_type: e.entry_type,
|
||||||
|
date: e.date.iso8601, text: e.text, aircraft_hours: dec(e.aircraft_hours_at_entry),
|
||||||
|
inspection_result: e.inspection_result.presence, verified: e.verified, superseded: e.superseded_at.present?,
|
||||||
|
signed: sig.present?, signature: sig && signature(sig), draft_batch_id: e.draft_batch_id, external_ref: e.external_ref,
|
||||||
|
signoff: sig ? nil : { person: e.signoff_person.presence, certificate_type: e.signoff_certificate_type.presence,
|
||||||
|
certificate_number: e.signoff_certificate_number.presence }.compact.presence,
|
||||||
|
created_at: time(e.created_at), updated_at: time(e.updated_at) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def draft_batch(b, invitations: {})
|
||||||
|
urls = Rails.application.routes.url_helpers
|
||||||
|
{ id: b.id, aircraft_id: b.aircraft_id, status: b.status, external_ref: b.external_ref, signer_email: b.signer_email,
|
||||||
|
held: { resolves_squawks: b.held_squawks.map { _1["id"] }, completes_inspections: b.held_inspections.map { _1["id"] } },
|
||||||
|
entries: b.entries.sort_by(&:log_type).map do |e|
|
||||||
|
logbook_entry(e).merge(sign_url: "#{Sso.app_url}#{urls.new_aircraft_logbook_entry_signature_path(b.aircraft_id, e)}",
|
||||||
|
invitation_url: invitations[e.id] && "#{Sso.app_url}#{urls.invited_signing_path(invitations[e.id])}")
|
||||||
|
end,
|
||||||
|
completed_at: time(b.completed_at), created_at: time(b.created_at) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def signature(sig)
|
||||||
|
{ signer_name: sig.signer_name, certificate_kind: sig.certificate_kind, certificate_number: sig.certificate_number,
|
||||||
|
signed_at: time(sig.signed_at) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def inspection(row)
|
||||||
|
{ inspection_type_id: row.type.id, name: row.type.name, status: row.status, next_due_date: row.next_due_date&.iso8601,
|
||||||
|
next_due_hours: dec(row.next_due_hours), last_done: row.latest&.date&.iso8601 }
|
||||||
|
end
|
||||||
|
|
||||||
|
def ad(row)
|
||||||
|
{ airworthiness_directive_id: row.ad.id, name: row.ad.name, description: row.ad.short_description.presence,
|
||||||
|
status: row.status, next_due_date: row.next_due_date&.iso8601, next_due_hours: dec(row.next_due_hours),
|
||||||
|
last_complied: row.latest&.date_complied&.iso8601 }
|
||||||
|
end
|
||||||
|
|
||||||
|
def dec(value) = value&.to_d&.round(1)&.to_f
|
||||||
|
def time(value) = value&.utc&.iso8601
|
||||||
|
end
|
||||||
@@ -16,12 +16,22 @@ 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
|
||||||
|
|
||||||
|
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 +73,22 @@ 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 (see OutboundAddress).
|
||||||
|
def address(host)
|
||||||
|
OutboundAddress.resolve!(host, allow_private: @allow_private)
|
||||||
|
rescue OutboundAddress::Blocked => e
|
||||||
|
raise BlockedAddress, I18n.t("services.air_trail.blocked_#{e.reason}", host: host)
|
||||||
|
end
|
||||||
|
|
||||||
def handle(response)
|
def handle(response)
|
||||||
status = response.code.to_i
|
status = response.code.to_i
|
||||||
json = begin
|
json = begin
|
||||||
|
|||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# Checks where the server is about to send a request (AirTrail, webhooks):
|
||||||
|
# resolves the host and returns the address to connect to, so the name can't
|
||||||
|
# be pointed elsewhere in between. Never the server itself, link-local
|
||||||
|
# addresses (cloud metadata) or multicast; the private network only when
|
||||||
|
# allowed (admins, or hosts the admin listed).
|
||||||
|
module OutboundAddress
|
||||||
|
class Blocked < StandardError
|
||||||
|
attr_reader :reason # :never | :private
|
||||||
|
|
||||||
|
def initialize(reason, host)
|
||||||
|
@reason = reason
|
||||||
|
super("#{host}: #{reason}")
|
||||||
|
end
|
||||||
|
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
|
||||||
|
|
||||||
|
# Host name → IP addresses (replaceable in tests, which have no DNS).
|
||||||
|
mattr_accessor :resolver, default: ->(host) { Addrinfo.getaddrinfo(host, nil, nil, :STREAM).map(&:ip_address) }
|
||||||
|
|
||||||
|
module_function
|
||||||
|
|
||||||
|
def resolve!(host, allow_private:)
|
||||||
|
ips = resolver.call(host).map { IPAddr.new(_1.sub(/%.*/, "")) }.uniq
|
||||||
|
raise SocketError, "no address for #{host}" if ips.empty?
|
||||||
|
ips.each do |ip|
|
||||||
|
ip = ip.native # ::ffff:10.0.0.1 → 10.0.0.1
|
||||||
|
raise Blocked.new(:never, host) if ip.loopback? || ip.link_local? || UNREACHABLE.any? { _1.include?(ip) }
|
||||||
|
raise Blocked.new(:private, host) if (ip.private? || CGNAT.include?(ip)) && !allow_private
|
||||||
|
end
|
||||||
|
ips.first.to_s
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -12,9 +12,10 @@ module ProceduresTemplates
|
|||||||
t(:sign_in, sentence: sign_in_sentence, min: User::PASSWORD_MIN, minutes: User::LOCK_FOR.in_minutes.to_i,
|
t(:sign_in, sentence: sign_in_sentence, min: User::PASSWORD_MIN, minutes: User::LOCK_FOR.in_minutes.to_i,
|
||||||
tries: User::LOCK_AFTER, days: Authentication::SESSION_IDLE_TIMEOUT.in_days.to_i),
|
tries: User::LOCK_AFTER, days: Authentication::SESSION_IDLE_TIMEOUT.in_days.to_i),
|
||||||
t(Sso.enabled? ? :signing_sso : :signing),
|
t(Sso.enabled? ? :signing_sso : :signing),
|
||||||
|
api_sentence,
|
||||||
t(:updates),
|
t(:updates),
|
||||||
t(:secret_key)
|
t(:secret_key)
|
||||||
].join("\n\n")
|
].compact.join("\n\n")
|
||||||
end
|
end
|
||||||
|
|
||||||
def additional
|
def additional
|
||||||
@@ -37,6 +38,13 @@ module ProceduresTemplates
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Only when the API is in use: who can reach the records through it, and that signing stays in the app.
|
||||||
|
def api_sentence
|
||||||
|
integrations = ApiToken.integration.active.order(:name).pluck(:name)
|
||||||
|
return if integrations.empty? && !ApiToken.personal.active.exists?
|
||||||
|
t(:api, integrations: integrations.any? ? t(:api_integrations, names: integrations.to_sentence) : t(:api_no_integrations))
|
||||||
|
end
|
||||||
|
|
||||||
def docker? = File.exist?("/.dockerenv")
|
def docker? = File.exist?("/.dockerenv")
|
||||||
|
|
||||||
def t(key, **opts) = I18n.t(key, scope: "services.procedures_templates", **opts)
|
def t(key, **opts) = I18n.t(key, scope: "services.procedures_templates", **opts)
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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))
|
||||||
|
|||||||
@@ -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) ] },
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# What happens when a squawk is reported, from the form or the API: the
|
||||||
|
# aircraft's activity log, and a push notification to its other people when
|
||||||
|
# it grounds the aircraft.
|
||||||
|
module SquawkReported
|
||||||
|
module_function
|
||||||
|
|
||||||
|
def call(squawk, by:)
|
||||||
|
aircraft = squawk.aircraft
|
||||||
|
aircraft.log_event!("squawk", I18n.t("flash.squawks.squawk_reported_2", priority_label: squawk.priority_label),
|
||||||
|
user: by, notes: squawk.issue_reported.truncate(200))
|
||||||
|
return unless squawk.grounding?
|
||||||
|
PushNotifier.notify(aircraft.users.merge(User.active).where.not(id: by&.id), :grounding_squawk,
|
||||||
|
path: Rails.application.routes.url_helpers.aircraft_squawks_path(aircraft),
|
||||||
|
tag: "squawk-#{squawk.id}", tail: aircraft.tail_number, issue: squawk.issue_reported.truncate(120))
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Tells integrations about changes (docs/api.md, "Webhooks"): each enabled
|
||||||
|
# endpoint subscribed to the event, whose token is active and reaches the
|
||||||
|
# aircraft, gets a delivery, sent by WebhookDeliveryJob after the change is
|
||||||
|
# saved.
|
||||||
|
module Webhooks
|
||||||
|
module_function
|
||||||
|
|
||||||
|
def publish(event, aircraft:, data:)
|
||||||
|
endpoints = WebhookEndpoint.enabled.joins(:api_token).merge(ApiToken.active).includes(:api_token)
|
||||||
|
.select { _1.subscribed?(event) && Array(_1.api_token.aircraft_ids).include?(aircraft.id) }
|
||||||
|
return if endpoints.empty?
|
||||||
|
body = { event: event, id: SecureRandom.uuid, created_at: Time.current.utc.iso8601, aircraft_id: aircraft.id, data: data }.to_json
|
||||||
|
endpoints.each do |endpoint|
|
||||||
|
delivery = endpoint.deliveries.create!(event: event, payload: body)
|
||||||
|
WebhookDeliveryJob.perform_later(delivery.id)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -20,6 +20,17 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<% if (notes = Changelog.load.release(info.version)) %>
|
||||||
|
<%# This version's release notes; older ones are on the What's new page. %>
|
||||||
|
<section class="card mb-5" id="whats-new">
|
||||||
|
<div class="card-header">
|
||||||
|
<h2 class="card-title"><%= t(".whats_new_in", version: info.version) %></h2>
|
||||||
|
<%= link_to t(".all_releases"), help_page_path("changelog"), class: "link text-sm" %>
|
||||||
|
</div>
|
||||||
|
<%= guide_markdown(notes.markdown, class: "card-body") %>
|
||||||
|
</section>
|
||||||
|
<% end %>
|
||||||
|
|
||||||
<div class="grid gap-5 lg:grid-cols-2">
|
<div class="grid gap-5 lg:grid-cols-2">
|
||||||
<section class="card">
|
<section class="card">
|
||||||
<div class="card-header"><h2 class="card-title"><%= t(".runtime") %></h2></div>
|
<div class="card-header"><h2 class="card-title"><%= t(".runtime") %></h2></div>
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<%= form_with model: integration, url: (integration.persisted? ? admin_integration_path(integration) : admin_integrations_path), scope: :api_token,
|
||||||
|
class: "card card-body max-w-2xl space-y-5", data: { turbo: false } do |f| %>
|
||||||
|
<%= f.errors_summary %>
|
||||||
|
<% if endpoint&.errors&.any? %><div class="rounded-md bg-red-50 p-3 text-sm text-red-700"><%= endpoint.errors.full_messages.to_sentence %></div><% end %>
|
||||||
|
<%= f.field :name, hint: t(".name_hint") %>
|
||||||
|
<fieldset>
|
||||||
|
<legend class="label"><%= t(".scopes") %></legend>
|
||||||
|
<% ApiToken::SCOPES.each do |key, label| %>
|
||||||
|
<label class="flex items-start gap-2 text-sm"><%= check_box_tag "api_token[scopes][]", key, integration.scopes.include?(key), id: "scope_#{key.parameterize}", class: "mt-1" %> <span><%= label %></span></label>
|
||||||
|
<% end %>
|
||||||
|
</fieldset>
|
||||||
|
<fieldset>
|
||||||
|
<legend class="label"><%= t(".aircraft") %></legend>
|
||||||
|
<p class="hint mb-1"><%= t(".aircraft_hint") %></p>
|
||||||
|
<% Aircraft.ordered.each do |a| %>
|
||||||
|
<label class="mr-4 inline-flex items-center gap-2 text-sm"><%= check_box_tag "api_token[aircraft_ids][]", a.id, Array(integration.aircraft_ids).include?(a.id), id: "aircraft_#{a.id}" %> <%= a.tail_number %></label>
|
||||||
|
<% end %>
|
||||||
|
</fieldset>
|
||||||
|
<fieldset class="space-y-2 border-t border-slate-200 pt-4">
|
||||||
|
<legend class="label"><%= t(".webhook") %></legend>
|
||||||
|
<p class="hint"><%= t(".webhook_hint") %></p>
|
||||||
|
<%= url_field_tag "webhook[url]", endpoint&.url, class: "input", placeholder: "https://redmine.example.com/sam/webhook", "aria-label": t(".webhook_url") %>
|
||||||
|
<% WebhookEndpoint::EVENTS.each do |key, label| %>
|
||||||
|
<label class="flex items-start gap-2 text-sm"><%= check_box_tag "webhook[events][]", key, Array(endpoint&.events).include?(key), id: "event_#{key.parameterize}", class: "mt-1" %> <span><%= label %> <code class="text-xs text-slate-500"><%= key %></code></span></label>
|
||||||
|
<% end %>
|
||||||
|
<% if endpoint&.persisted? %>
|
||||||
|
<%= hidden_field_tag "webhook[enabled]", "0", id: nil %>
|
||||||
|
<label class="flex items-center gap-2 text-sm"><%= check_box_tag "webhook[enabled]", "1", endpoint.enabled %> <%= t(".webhook_enabled") %></label>
|
||||||
|
<% end %>
|
||||||
|
</fieldset>
|
||||||
|
<%= f.submit integration.persisted? ? t(".save") : t(".create"), class: "btn-primary" %>
|
||||||
|
<% end %>
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<% content_for :title, @integration.name %>
|
||||||
|
<section class="card card-body max-w-xl space-y-3">
|
||||||
|
<h1 class="card-title"><%= @integration.name %></h1>
|
||||||
|
<p class="text-sm text-slate-600"><%= t(".copy_now") %></p>
|
||||||
|
<% if @integration.token %>
|
||||||
|
<label class="label" for="integration_token"><%= t(".token") %></label>
|
||||||
|
<input id="integration_token" class="input font-mono text-sm" value="<%= @integration.token %>" readonly>
|
||||||
|
<% end %>
|
||||||
|
<% if @secret %>
|
||||||
|
<label class="label" for="webhook_secret"><%= t(".webhook_secret") %></label>
|
||||||
|
<input id="webhook_secret" class="input font-mono text-sm" value="<%= @secret %>" readonly>
|
||||||
|
<p class="hint"><%= t(".secret_hint") %></p>
|
||||||
|
<% end %>
|
||||||
|
<p><%= link_to t(".done"), admin_integration_path(@integration), class: "btn-primary" %></p>
|
||||||
|
</section>
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<% content_for :title, @integration.name %>
|
||||||
|
<h1 class="mb-4 text-2xl font-bold"><%= @integration.name %></h1>
|
||||||
|
<%= render "form", integration: @integration, endpoint: @endpoint %>
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<% content_for :title, t(".integrations") %>
|
||||||
|
<div class="mb-4 flex items-center justify-between"><h1 class="text-2xl font-bold"><%= t(".integrations") %></h1><%= link_to t(".new_integration"), new_admin_integration_path, class: "btn-primary" %></div>
|
||||||
|
<p class="mb-4 max-w-3xl text-sm text-slate-600"><%= t(".what_html", docs: link_to(t(".api_docs"), help_page_path("api"), class: "link")) %></p>
|
||||||
|
<% if @integrations.any? %>
|
||||||
|
<section class="card"><table class="table">
|
||||||
|
<thead><tr><th><%= t(".name") %></th><th><%= t(".aircraft") %></th><th><%= t(".webhook") %></th><th><%= t(".last_used") %></th></tr></thead>
|
||||||
|
<tbody><% @integrations.each do |i| %><tr>
|
||||||
|
<td><%= link_to i.name, admin_integration_path(i), class: "link font-medium" %> <% if i.revoked? %><span class="badge-red"><%= t(".revoked") %></span><% end %>
|
||||||
|
<div class="text-xs text-slate-500"><code><%= i.token_hint %>…</code></div></td>
|
||||||
|
<td class="text-xs"><%= Aircraft.where(id: Array(i.aircraft_ids)).order(:tail_number).pluck(:tail_number).join(", ").presence || "—" %></td>
|
||||||
|
<td class="text-xs"><%= (e = i.webhook_endpoints.first) ? e.url : "—" %></td>
|
||||||
|
<td class="text-xs text-slate-500"><%= i.last_used_at ? t(".ago", ago: time_ago_in_words(i.last_used_at)) : t(".never") %></td>
|
||||||
|
</tr><% end %></tbody>
|
||||||
|
</table></section>
|
||||||
|
<% else %>
|
||||||
|
<%= empty_state t(".none_yet") %>
|
||||||
|
<% end %>
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<% content_for :title, t(".new_integration") %>
|
||||||
|
<h1 class="mb-4 text-2xl font-bold"><%= t(".new_integration") %></h1>
|
||||||
|
<%= render "form", integration: @integration, endpoint: @endpoint %>
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
<% content_for :title, @integration.name %>
|
||||||
|
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<h1 class="text-2xl font-bold"><%= @integration.name %> <% if @integration.revoked? %><span class="badge-red align-middle text-sm"><%= t(".revoked") %></span><% end %></h1>
|
||||||
|
<% unless @integration.revoked? %>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<%= link_to t(".edit"), edit_admin_integration_path(@integration), class: "btn-secondary" %>
|
||||||
|
<%= button_to t(".revoke"), admin_integration_path(@integration), method: :delete, class: "btn-danger",
|
||||||
|
form: { data: { turbo_confirm: t(".revoke_confirm", name: @integration.name) } } %>
|
||||||
|
</div>
|
||||||
|
<% end %>
|
||||||
|
</div>
|
||||||
|
<div class="grid max-w-5xl items-start gap-5 lg:grid-cols-2">
|
||||||
|
<section class="card card-body">
|
||||||
|
<h2 class="card-title"><%= t(".token") %></h2>
|
||||||
|
<dl class="mt-2 grid gap-y-2 text-sm">
|
||||||
|
<div class="detail-row"><dt><%= t(".hint") %></dt><dd><code><%= @integration.token_hint %>…</code></dd></div>
|
||||||
|
<div class="detail-row"><dt><%= t(".scopes") %></dt><dd><%= @integration.scopes.map { ApiToken::SCOPES[_1] }.to_sentence %></dd></div>
|
||||||
|
<div class="detail-row"><dt><%= t(".aircraft") %></dt><dd><%= Aircraft.where(id: Array(@integration.aircraft_ids)).order(:tail_number).pluck(:tail_number).join(", ").presence || "—" %></dd></div>
|
||||||
|
<div class="detail-row"><dt><%= t(".created") %></dt><dd><%= fmt_time(@integration.created_at) %> · <%= @integration.user.display_name %></dd></div>
|
||||||
|
<div class="detail-row"><dt><%= t(".last_used") %></dt><dd><%= @integration.last_used_at ? "#{fmt_time(@integration.last_used_at)} · #{@integration.last_used_ip}" : t(".never") %></dd></div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
<section class="card card-body">
|
||||||
|
<h2 class="card-title"><%= t(".webhook") %></h2>
|
||||||
|
<% if @endpoint %>
|
||||||
|
<dl class="mt-2 grid gap-y-2 text-sm">
|
||||||
|
<div class="detail-row"><dt><%= t(".url") %></dt><dd class="break-all"><%= @endpoint.url %> <% unless @endpoint.enabled %><span class="badge-gray"><%= t(".paused") %></span><% end %></dd></div>
|
||||||
|
<div class="detail-row"><dt><%= t(".events") %></dt><dd><%= @endpoint.events.map { WebhookEndpoint::EVENTS[_1] }.to_sentence %></dd></div>
|
||||||
|
</dl>
|
||||||
|
<% unless @integration.revoked? %>
|
||||||
|
<div class="mt-3"><%= button_to t(".new_secret"), new_secret_admin_integration_path(@integration), class: "btn-secondary btn-sm",
|
||||||
|
form: { data: { turbo: false, turbo_confirm: t(".new_secret_confirm") } } %></div>
|
||||||
|
<% end %>
|
||||||
|
<% else %>
|
||||||
|
<p class="mt-1 text-sm text-slate-600"><%= t(".no_webhook") %></p>
|
||||||
|
<% end %>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<% if @deliveries.any? %>
|
||||||
|
<section class="card mt-5 max-w-5xl">
|
||||||
|
<div class="card-header"><h2 class="card-title"><%= t(".recent_deliveries") %></h2></div>
|
||||||
|
<table class="table"><thead><tr><th><%= t(".when") %></th><th><%= t(".event") %></th><th><%= t(".result") %></th></tr></thead>
|
||||||
|
<tbody><% @deliveries.each do |d| %><tr>
|
||||||
|
<td class="text-xs"><%= fmt_time(d.created_at) %></td><td><code class="text-xs"><%= d.event %></code></td>
|
||||||
|
<td class="text-xs"><span class="<%= { "delivered" => "badge-green", "failed" => "badge-red" }.fetch(d.status, "badge-gray") %>"><%= t(".status.#{d.status}") %></span>
|
||||||
|
<%= d.response_status %> <%= d.last_error %> <% if d.attempts > 1 %>· <%= t(".attempts", count: d.attempts) %><% end %></td>
|
||||||
|
</tr><% end %></tbody></table>
|
||||||
|
</section>
|
||||||
|
<% end %>
|
||||||
@@ -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 %>
|
||||||
@@ -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 %>
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<% content_for :title, t(".title") %>
|
||||||
|
<section class="card card-body max-w-xl space-y-3">
|
||||||
|
<h1 class="card-title"><%= t(".title") %></h1>
|
||||||
|
<p class="text-sm text-slate-600"><%= t(".copy_now", name: @token.name) %></p>
|
||||||
|
<input class="input font-mono text-sm" value="<%= @token.token %>" readonly aria-label="<%= t(".token") %>">
|
||||||
|
<p class="hint"><%= t(".how_to_use_html") %></p>
|
||||||
|
<p><%= link_to t(".done"), edit_profile_path(anchor: "api"), class: "btn-primary" %></p>
|
||||||
|
</section>
|
||||||
@@ -21,30 +21,40 @@
|
|||||||
<%= 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 %>
|
||||||
<%= f.field :replacement_hours, as: :number, label: t(".replace_every_hrs") %>
|
<% replacement_open = c.replacement_hours.present? || c.replacement_calendar? || c.replacement_critical? || c.expires_on.present? ||
|
||||||
<%= f.interval :replacement, label: t(".replace_every") %>
|
%i[replacement_hours replacement_every expires_on].any? { c.errors[_1].any? } %>
|
||||||
<%= f.field :replacement_from_install, as: :select, label: t(".replacement_counts_from"),
|
<% 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? } %>
|
||||||
collection: [ [ t(".last_service"), false ], [ t(".installation_life_limit"), true ] ],
|
<details class="rounded-md ring-1 ring-slate-200" <%= "open" if replacement_open %>>
|
||||||
hint: t(".installation_for_a_part_that") %>
|
<summary class="cursor-pointer px-3 py-2 text-sm font-semibold text-slate-900"><%= t(".replacement_group") %>
|
||||||
<%= f.field :replacement_critical, as: :checkbox, label: t(".replacement_critical"), hint: t(".overdue_replacement_or_expiry_grounds") %>
|
<span class="font-normal text-slate-500"><%= t(".replacement_group_hint") %></span></summary>
|
||||||
<%= f.field :expires_on, as: :date, label: t(".expires_on"),
|
<div class="grid gap-4 border-t border-slate-200 p-3 sm:grid-cols-3">
|
||||||
hint: t(".the_date_marked_on_the") %>
|
<%= f.field :replacement_hours, as: :number, label: t(".replace_every_hrs") %>
|
||||||
<%= f.field :tbo_hours, as: :number, label: t(".tbo_hrs") %>
|
<%= f.interval :replacement, label: t(".replace_every") %>
|
||||||
<%= f.interval :tbo, label: t(".tbo_calendar") %>
|
<%= f.field :replacement_from_install, as: :select, label: t(".replacement_counts_from"),
|
||||||
<div class="space-y-2">
|
collection: [ [ t(".last_service"), false ], [ t(".installation_life_limit"), true ] ],
|
||||||
<%= f.field :tbo_critical, as: :checkbox, label: t(".treat_tbo_as_a_hard"),
|
hint: t(".installation_for_a_part_that") %>
|
||||||
hint: t(".under_part_91_tbo_is") %>
|
<%= f.field :replacement_critical, as: :checkbox, label: t(".replacement_critical"), hint: t(".overdue_replacement_or_expiry_grounds") %>
|
||||||
<%= f.field :on_condition, as: :checkbox, label: t(".on_condition_part_91"),
|
<%= f.field :expires_on, as: :date, label: t(".expires_on"),
|
||||||
hint: t(".run_past_tbo_based_on") %>
|
hint: t(".the_date_marked_on_the") %>
|
||||||
</div>
|
</div>
|
||||||
<p class="hint sm:col-span-3"><%= t(".recurring_inspections_of_this_part") %></p>
|
</details>
|
||||||
</fieldset>
|
<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.interval :tbo, label: t(".tbo_calendar") %>
|
||||||
|
<%= f.field :overhaul_kind, as: :select, label: t(".overhaul_type"), include_blank: "—", collection: Component::OVERHAUL_KINDS.invert,
|
||||||
|
hint: t(".for_engines_and_propellers_printed") %>
|
||||||
|
<%= 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"), hint: t(".run_past_tbo_based_on") %>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
<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">
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -13,7 +13,14 @@
|
|||||||
<% if current.image? %>
|
<% if current.image? %>
|
||||||
<%= image_tag rails_blob_path(current, disposition: :inline), alt: current.filename.to_s, class: "max-h-[80vh] max-w-full" %>
|
<%= image_tag rails_blob_path(current, disposition: :inline), alt: current.filename.to_s, class: "max-h-[80vh] max-w-full" %>
|
||||||
<% elsif current.content_type == "application/pdf" %>
|
<% elsif current.content_type == "application/pdf" %>
|
||||||
<iframe src="<%= rails_blob_path(current, disposition: :inline) %>" class="h-[80vh] w-full"></iframe>
|
<% pdf_url = rails_blob_path(current, disposition: :inline) %>
|
||||||
|
<%# Phones get the pages drawn by PDF.js; browsers with a PDF viewer of their own get it in the frame. %>
|
||||||
|
<div class="w-full space-y-2" data-controller="pdf-viewer" data-pdf-viewer-url-value="<%= pdf_url %>" data-pdf-viewer-pdfjs-value="<%= Rails.application.config.x.pdfjs_path %>">
|
||||||
|
<template data-pdf-viewer-target="frame"><iframe src="<%= pdf_url %>" title="<%= current.filename %>" class="h-[80vh] w-full"></iframe></template>
|
||||||
|
<p class="p-6 text-center text-sm text-slate-500" role="status" data-pdf-viewer-target="status"><%= t("js.pdf.loading") %></p>
|
||||||
|
<div class="space-y-2" data-pdf-viewer-target="pages"></div>
|
||||||
|
<noscript><iframe src="<%= pdf_url %>" title="<%= current.filename %>" class="h-[80vh] w-full"></iframe></noscript>
|
||||||
|
</div>
|
||||||
<% else %>
|
<% else %>
|
||||||
<p class="p-6 text-sm"><%= link_to t(".download", filename: current.filename), rails_blob_path(current, disposition: :attachment), class: "link" %></p>
|
<p class="p-6 text-sm"><%= link_to t(".download", filename: current.filename), rails_blob_path(current, disposition: :attachment), class: "link" %></p>
|
||||||
<% end %>
|
<% end %>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
<div class="card-body space-y-4">
|
<div class="card-body space-y-4">
|
||||||
<p class="text-sm text-slate-600"><%= t(".review_the_entry_your_signature_html", link: (link_to t(".how_signing_works"), records_help_path, class: "link", target: "_blank")) %></p>
|
<p class="text-sm text-slate-600"><%= t(".review_the_entry_your_signature_html", link: (link_to t(".how_signing_works"), records_help_path, class: "link", target: "_blank")) %></p>
|
||||||
<%= render "logbook_entries/content", entry: entry %>
|
<%= render "logbook_entries/content", entry: entry %>
|
||||||
|
<%= render "logbook_entries/draft_batch", entry: entry %>
|
||||||
<% if @signing_error %>
|
<% if @signing_error %>
|
||||||
<div class="rounded-md bg-red-50 p-3 text-sm text-red-700 ring-1 ring-red-200" role="alert"><%= @signing_error %></div>
|
<div class="rounded-md bg-red-50 p-3 text-sm text-red-700 ring-1 ring-red-200" role="alert"><%= @signing_error %></div>
|
||||||
<% end %>
|
<% end %>
|
||||||
|
|||||||
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user