mirror of
https://github.com/rickbarrette/simple-aircraft-manager-rails.git
synced 2026-11-17 15:50:36 -05:00
Compare commits
38
Commits
v2026.11.3
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6697e835c8 | ||
|
|
acb8b87ca3 | ||
|
|
a5ca534fd1 | ||
|
|
d956cfbe83 | ||
|
|
34e3232350 | ||
|
|
3ad6b9493a | ||
|
|
9adbc3d0a8 | ||
|
|
c360edfce0 | ||
|
|
9a20c91f5e | ||
|
|
19bc3efa19 | ||
|
|
b4c7aaa3ff | ||
|
|
a645778f26 | ||
|
|
3e5d896662 | ||
|
|
d8cd462194 | ||
|
|
d2cd60c6a7 | ||
|
|
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
+35
-6
@@ -2,16 +2,32 @@
|
||||
# block is required. Every setting is explained in the README.
|
||||
|
||||
# --- Required ----------------------------------------------------------
|
||||
# Generate with: bin/rails secret (or: openssl rand -hex 64)
|
||||
# Keep a copy somewhere safe off the server: signatures and stored secrets
|
||||
# depend on it, and a restore needs the same one.
|
||||
SECRET_KEY_BASE=change-me
|
||||
# Generate with: bin/rails secret (or: openssl rand -hex 64). Anyone who knows
|
||||
# it can sign in as anyone, so the app won't start with a placeholder or a
|
||||
# short one. Keep a copy somewhere safe off the server: signatures and stored
|
||||
# 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).
|
||||
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
|
||||
# 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
|
||||
|
||||
# --- 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 -----------------------------------------------------------
|
||||
# Full public URL, if it isn't https://APP_HOST (used for the single sign-on
|
||||
# and Google Drive redirect URIs).
|
||||
@@ -30,9 +46,14 @@ FORCE_SSL=true
|
||||
# OIDC_CLIENT_ID=
|
||||
# OIDC_CLIENT_SECRET=
|
||||
# OIDC_PROVIDER_NAME=Authentik
|
||||
# OIDC_AUTO_CREATE_USERS=false # true: create an account at first sign-in
|
||||
# OIDC_AUTO_CREATE_USERS=false # true: an account at first sign-in for anyone the provider lets in, without an invitation
|
||||
# OIDC_TRUST_EMAIL=false # true: link accounts by unverified email
|
||||
# OIDC_ADMIN_GROUP= # members become admins (synced at sign-in)
|
||||
|
||||
# --- 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)
|
||||
|
||||
# --- Sign-in security ----------------------------------------------------
|
||||
@@ -43,6 +64,14 @@ FORCE_SSL=true
|
||||
# LOGBOOK_AI_MODEL=claude-opus-5-5
|
||||
# LOGBOOK_AI_EFFORT=high
|
||||
|
||||
# --- Push notifications --------------------------------------------------
|
||||
# Optional: without them the app makes a pair once and keeps it in storage/vapid_keys.json.
|
||||
# Changing the pair turns notifications off on every device until turned on again.
|
||||
# VAPID_PUBLIC_KEY=
|
||||
# VAPID_PRIVATE_KEY= # bin/rails runner 'k = WebPush.generate_key; puts k.public_key, k.private_key'
|
||||
|
||||
# --- Other ---------------------------------------------------------------
|
||||
# APP_LOCALE=en # language, e.g. es for config/locales/es.yml
|
||||
# APP_REPOSITORY_URL= # source link on Admin → About (for a fork)
|
||||
# APP_IMAGE= # image for the records package's viewer, used as is (for a fork); default: the published one at this release
|
||||
# RAILS_LOG_LEVEL=info
|
||||
@@ -2,6 +2,91 @@
|
||||
|
||||
Each release has a **version** (year.month.release, e.g. 2026.11.0) and a **build** (the exact source commit, shown on Admin → About). The newest release is first.
|
||||
|
||||
## 2026.11.7
|
||||
|
||||
### Changes
|
||||
|
||||
- **Correct a flight.** Open it and choose **Edit**: the date, airports, route, notes, oil and fuel (its oil and fuel records follow) and its files can always be fixed. The meter readings only on the latest flight, while nothing else has changed the hours; the aircraft and its components then move by the difference. On earlier flights the readings are shown locked. Owners can correct any flight; pilots, the ones they logged.
|
||||
- **Roles you can set up.** Each person has a role on each aircraft: **Owner**, **Mechanic** (maintenance records, signing, components, inspections, ADs, squawks, reminders), **Pilot** (as before) or **Viewer** (sees everything, changes nothing). Owners and pilots keep exactly what they could do. Buttons for what your role doesn't allow aren't shown.
|
||||
- **Reminders and overdue alerts** go to the roles that get them: Owners and Mechanics, as roles come.
|
||||
- **Records package viewer, with no account.** The package's `viewer/docker-compose.yml` now runs a read-only copy on the recipient's computer: `docker compose up`, open http://localhost:3000, and the records are there (imported by itself, nothing can be changed, reachable only from that computer). It runs the release that made the package.
|
||||
|
||||
### For administrators
|
||||
|
||||
- **Admin → Roles**: change what Mechanic, Pilot and Viewer can do (31 permissions, grouped), or add your own roles (a partner, an instructor). Owner always has everything. **Admin → Users → Edit** lists each person's role on every aircraft, to add, change or remove. Only an Owner (or an administrator) can give the Owner role, nobody changes their own, and every aircraft keeps an Owner.
|
||||
- **Admin → Invitations**: a link that makes an account (or is accepted with one) and gives roles on aircraft; limited uses, an expiry, optionally one email address (and then emailed). With single sign-on, **Continue with** on the invitation makes the account.
|
||||
- **New accounts come only from an administrator**, an administrator's invitation, or an Owner's signing invitation to an outside mechanic (for that address). Signing invitations from others need an existing account.
|
||||
- **Who can add aircraft** (Admin → Settings) is **administrators only** by default: adding or importing an aircraft makes you its Owner, who can bring in mechanics. **After this update, other users can't add aircraft** until you choose *Everyone* there.
|
||||
- `OIDC_AUTO_CREATE_USERS=true` still gives an account to anyone the identity provider lets in, without an invitation; leave it off to keep accounts to administrators and their invitations.
|
||||
- The REST API follows the person's role; its `owners_only` error is now `not_permitted`.
|
||||
- The update adds the roles and invitations tables, filled in automatically when the new version starts.
|
||||
- The compose files and `.env.example` mention the first-run setup code and the push notification, language and image settings.
|
||||
|
||||
### Fixes
|
||||
|
||||
- Disabled fields look disabled (they looked like any other).
|
||||
- The records package's viewer said to just create an account (it needs the setup code since 2026.11.5) and named the wrong menu.
|
||||
|
||||
## 2026.11.6
|
||||
|
||||
### Changes
|
||||
|
||||
- **PDFs show on phones.** Android showed nothing for a PDF document and iPhones only its first page. On phones and tablets every page is now drawn in the app, as it scrolls into view, downloading only the parts of the file those pages need (a long manual opens quickly and doesn't use up mobile data). Computers keep the browser's own PDF viewer.
|
||||
- **Connection status in the top bar.** It turns red when the server can't be reached, and back on its own when it can. A ring fills while pages are saved for offline use or what was logged offline is sent; it's amber with a count while flights or squawks wait to send.
|
||||
- **A weak signal counts as no signal.** Log Flight and Report Squawk say "Sending…" and, if the server doesn't answer within 10 seconds (a minute with photos), keep the entry on the phone and send it when the connection's back. If it got through after all, it isn't logged twice. Every page falls back to its offline copy or the offline page instead of loading forever.
|
||||
- **The activity log loads as you scroll** (it stopped at 200 events).
|
||||
- **What's new** shows the running version's notes on Admin → About; older releases fold to one line each.
|
||||
- **REST API** for other programs, such as a script that pulls what's coming due or a work-order system: read aircraft, parts, due items, inspections, ADs, squawks and logbook entries; report and update squawks; send draft logbook entries to be signed in the app. Webhooks announce squawks reported, updated and resolved, entries signed, and drafts completed. Personal tokens are made in Profile. The API never signs an entry; see Help → REST API.
|
||||
|
||||
### For administrators
|
||||
|
||||
- **Admin → Integrations** makes tokens for other systems, acting for the person each request names, limited to the aircraft chosen, plus webhook endpoints.
|
||||
- The update adds the API's tables; they're created automatically when the new version starts.
|
||||
|
||||
## 2026.11.5
|
||||
|
||||
### Changes
|
||||
|
||||
- **Faster photos.** Aircraft photos load as small copies on the Fleet page and the aircraft header (they were the full original, slow on mobile). The offline copies use the small versions too.
|
||||
- **Detail cards read one item per row on a phone**: flights, engine data, components and major repairs and alterations. Wider screens show two columns.
|
||||
- **Profile uses the width of a desktop screen**: your account and its security on the left; calendar, certificates, this device and integrations on the right.
|
||||
- **Notifications:** opening Profile on a device records its notification subscription again, so a device whose subscription was never saved starts receiving them. **Send test** lists each device and whether its push service accepted the notification, with the reason if not. If turning notifications on fails, the browser's error is shown.
|
||||
|
||||
### For administrators
|
||||
|
||||
- **The app won't start with a placeholder or short `SECRET_KEY_BASE`** (under 32 characters), since anyone who knows it can sign in as anyone. `sam:doctor` flags one under 64 characters. Use the output of `bin/rails secret`.
|
||||
- **First-run setup asks for a one-time code** printed in the server log (`docker compose logs web | grep "Setup code"`), so only whoever runs the server can create the admin account.
|
||||
- **HTTPS without a proxy:** `docker-compose.direct.yml` with `TLS_DOMAIN` gets and renews a Let's Encrypt certificate by itself.
|
||||
- **The app answers only for its own names** when `APP_HOST` is set: `APP_HOST`, the `APP_URL` host, `localhost`, IP addresses, and any names listed in the new `ALLOWED_HOSTS`. Other names get a short explanation. If you reach the app by another name (such as a LAN name), add it to `ALLOWED_HOSTS`.
|
||||
- **AirTrail servers on a private network** can be connected only by an administrator, or by anyone when listed in `AIRTRAIL_ALLOWED_HOSTS`. The server itself and link-local addresses are always refused.
|
||||
- The project is released into the public domain (LICENSE, The Unlicense).
|
||||
|
||||
### Fixes
|
||||
|
||||
- A file that isn't a photo, or an empty one, chosen as the aircraft photo now shows "must be an image" instead of an error page. An image that can't be read is shown as the original file.
|
||||
- A component can't be set as a part of its own parts; that made the logbook entry and squawk resolution pages fail.
|
||||
- Many malformed requests that caused error pages now get a proper answer: pages requested in another format, blank required values, links to records that don't exist, numbers too large to store, and text sent where a file belongs.
|
||||
|
||||
## 2026.11.4
|
||||
|
||||
### Changes
|
||||
|
||||
- **Time zones.** Times show in your own zone and "today" is your local date (a new flight no longer defaults to tomorrow in the evening). It follows your device automatically, or choose one in Profile. The administrator sets the installation's zone with `TZ` (e.g. `America/New_York`), which also sets when the nightly and weekly jobs run. Signatures and the record history still show UTC.
|
||||
- **Update Hours asks first**, showing each reading's change and that every in-service component moves without logging a flight; the message afterwards says exactly what changed. A lowered reading is marked as a correction.
|
||||
- **Squawk photos show as thumbnails** that open the photo viewer.
|
||||
- **Save and log next leg** on Log Flight: saves the flight and opens the form for the next one, starting where it ended.
|
||||
- **Setup checklist** on a new aircraft's Overview: components, standard inspections, ADs from DRS, registration and airworthiness certificate, weight and balance.
|
||||
- The component form groups its limits into **Replacement and expiry** and **Overhaul and TBO**, opened only when used.
|
||||
- Choosing **Ground Aircraft** on a squawk says what it does before you submit.
|
||||
- The logbook entry form shows **Inspection result** only for inspection entries.
|
||||
- A new document is named from its file when you leave the name blank.
|
||||
- Dates read the same way everywhere, including the logbook-entry pickers, the activity log and the airworthiness list.
|
||||
|
||||
### Fixes
|
||||
|
||||
- On iPad and iPhone home-screen apps, the top bar stays sharp (it's now fixed to the top of the screen).
|
||||
- An aircraft's description stays inside the Details card.
|
||||
|
||||
## 2026.11.3
|
||||
|
||||
### Installed app
|
||||
|
||||
@@ -37,7 +37,7 @@ gem "kamal", require: false
|
||||
gem "thruster", require: false
|
||||
|
||||
# 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
|
||||
# See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
|
||||
|
||||
@@ -141,6 +141,14 @@ GEM
|
||||
faraday (>= 1, < 3)
|
||||
faraday-net_http (3.5.0)
|
||||
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)
|
||||
et-orbi (~> 1.4)
|
||||
raabro (~> 1.4)
|
||||
@@ -153,6 +161,9 @@ GEM
|
||||
htmlentities (4.4.2)
|
||||
i18n (1.15.2)
|
||||
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)
|
||||
actionpack (>= 6.0.0)
|
||||
activesupport (>= 6.0.0)
|
||||
@@ -198,6 +209,8 @@ GEM
|
||||
net-smtp
|
||||
marcel (1.2.1)
|
||||
matrix (0.4.3)
|
||||
mini_magick (5.4.0)
|
||||
logger
|
||||
mini_mime (1.1.5)
|
||||
minitest (6.1.0)
|
||||
drb (~> 2.0)
|
||||
@@ -396,6 +409,9 @@ GEM
|
||||
rubocop-performance (>= 1.24)
|
||||
rubocop-rails (>= 2.30)
|
||||
ruby-progressbar (1.13.0)
|
||||
ruby-vips (2.3.0)
|
||||
ffi (~> 1.12)
|
||||
logger
|
||||
rubyzip (3.7.0)
|
||||
securerandom (0.4.1)
|
||||
solid_cache (1.0.10)
|
||||
@@ -507,6 +523,7 @@ DEPENDENCIES
|
||||
commonmarker (~> 2.10)
|
||||
csv (~> 3.3)
|
||||
debug
|
||||
image_processing (~> 1.2)
|
||||
importmap-rails
|
||||
json (~> 3.1)
|
||||
kamal
|
||||
@@ -593,6 +610,14 @@ CHECKSUMS
|
||||
faraday (2.15.1) sha256=8708154deda739c5e86cc42b74960e23e8491fce0eba9e11639a6a34b1ac288f
|
||||
faraday-follow_redirects (0.5.0) sha256=5cde93c894b30943a5d2b93c2fe9284216a6b756f7af406a1e55f211d97d10ad
|
||||
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
|
||||
globalid (1.4.0) sha256=037f12fbf1d9d7a014d501c2d5c77356fd4ddd96d7a7991d6700bba96706f427
|
||||
hashdiff (1.2.1) sha256=9c079dbc513dfc8833ab59c0c2d8f230fa28499cc5efb4b8dd276cf931457cd1
|
||||
@@ -600,6 +625,7 @@ CHECKSUMS
|
||||
hashie (5.2.0) sha256=357a22635195c2e3911fbbc3de9a7d528843d1f42ab0aae02171048f16332d72
|
||||
htmlentities (4.4.2) sha256=bbafbdf69f2eca9262be4efef7e43e6a1de54c95eb600f26984f71d2fe96c5c3
|
||||
i18n (1.15.2) sha256=00f9eb62412fe593b2a65a97daa75300d37abb8f7202ec748e94b6d46a9dd1b5
|
||||
image_processing (1.14.0) sha256=754cc169c9c262980889bec6bfd325ed1dafad34f85242b5a07b60af004742fb
|
||||
importmap-rails (2.2.3) sha256=7101be2a4dc97cf1558fb8f573a718404c5f6bcfe94f304bf1f39e444feeb16a
|
||||
io-console (0.9.5) sha256=83dd9bbf4c4680416629245b39cd4212eb5f4d9a4ea91804870c1f6b846414d5
|
||||
irb (1.18.0) sha256=de9454a0703a54704b9811a5ef31a60c86949fbf4013fcf244fabc7c775248e3
|
||||
@@ -614,6 +640,7 @@ CHECKSUMS
|
||||
mail (2.9.1) sha256=06574eca475253d6c18145dd70af80d0eb970182d55053497c5f4d797ea160e8
|
||||
marcel (1.2.1) sha256=1678e9360e32f9eafa917c80029e2f6d10b2715c66a4b87b6d0da9b9cd1f859f
|
||||
matrix (0.4.3) sha256=a0d5ab7ddcc1973ff690ab361b67f359acbb16958d1dc072b8b956a286564c5b
|
||||
mini_magick (5.4.0) sha256=f120af581d9ed4ec52c57f35a67a605d112bb1d8f582d1415b147fda42d11d78
|
||||
mini_mime (1.1.5) sha256=8681b7e2e4215f2a159f9400b5816d85e9d8c6c6b491e96a12797e798f8bccef
|
||||
minitest (6.1.0) sha256=ff373595aa8888631e8a5463986a76b3845346ae6d7fa46e139c1633d418076e
|
||||
msgpack (1.8.7) sha256=dfefec761b5f9047e6e8d95d2c7f8af4b3725d984a01942adc533aa819a2df33
|
||||
@@ -681,6 +708,7 @@ CHECKSUMS
|
||||
rubocop-rails (2.38.0) sha256=6e2b7c532efa95e3050371bec20b8f5b025662acead8bc70ee31f0e3e6fa2f06
|
||||
rubocop-rails-omakase (1.1.0) sha256=2af73ac8ee5852de2919abbd2618af9c15c19b512c4cfc1f9a5d3b6ef009109d
|
||||
ruby-progressbar (1.13.0) sha256=80fc9c47a9b640d6834e0dc7b3c94c9df37f08cb072b7761e4a71e22cff29b33
|
||||
ruby-vips (2.3.0) sha256=e685ec02c13969912debbd98019e50492e12989282da5f37d05f5471442f5374
|
||||
rubyzip (3.7.0) sha256=65c19294da75297a939006f3516deacc33185fbd721ff1954f7a231db6d3e121
|
||||
securerandom (0.4.1) sha256=cc5193d414a4341b6e225f0cb4446aceca8e50d5e1888743fac16987638ea0b1
|
||||
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.
|
||||
- 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.
|
||||
- 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.
|
||||
@@ -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).
|
||||
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`
|
||||
|
||||
@@ -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
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
- [`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)).
|
||||
|
||||
[`.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,24 +72,30 @@ The app is a standard Rails app. Run `bin/rails db:prepare && bin/thrust bin/rai
|
||||
|
||||
| Variable | Purpose |
|
||||
|---|---|
|
||||
| `SECRET_KEY_BASE` | Required in production (`bin/rails secret`). Alternatively provide `RAILS_MASTER_KEY`. |
|
||||
| `FORCE_SSL` | `true` (default) redirects to HTTPS and sets secure cookies. Use `false` for plain HTTP. |
|
||||
| `APP_HOST` | Host name the app is reached at, used in email links (password resets, sign-in links, signing invitations, reminders). |
|
||||
| `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, only on a private network. |
|
||||
| `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_TLS` | `true` for servers that use TLS from the start. That's the default on port 465; other ports upgrade with STARTTLS. |
|
||||
| `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` | Optional. The key pair that signs push notifications (generate with `bin/rails runner 'k = WebPush.generate_key; puts k.public_key, k.private_key'`). Without them the app generates a pair once and keeps it in `storage/vapid_keys.json`. Changing it turns notifications off on every device until they're turned on again. |
|
||||
| `TZ` | Optional. The installation's time zone, Docker's standard setting, e.g. `America/New_York`: scheduled jobs (nightly backup, the 7am overdue check, Monday reminders) run on its clock, and it's used for anyone whose device zone isn't known yet. Each person sees times in their own zone (Profile, or their device). Default `UTC`. |
|
||||
| `APP_LOCALE` | Optional. The app's language, e.g. `es` for `config/locales/es.yml` (see [Translating](#translating)). Default `en`. |
|
||||
| `ANTHROPIC_API_KEY` | Optional. Lets Claude transcribe scanned logbook pages into entries (**Logbook → Import scans**). Without it, scans are only uploaded. |
|
||||
| `LOGBOOK_AI_MODEL`, `LOGBOOK_AI_EFFORT` | Optional. The Claude model and effort used for transcription (default `claude-opus-5-5`, `high`). |
|
||||
| `APP_URL` | Optional public base URL, e.g. `https://aircraft.example.com` (default `https://APP_HOST`). Used for the SSO and Google Drive redirect URIs. |
|
||||
| `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` | Optional. Turn on single sign-on with an OpenID Connect provider (see below). |
|
||||
| `OIDC_PROVIDER_NAME` | Button label, e.g. `Authentik` (default `SSO`). |
|
||||
| `OIDC_AUTO_CREATE_USERS` | `true` creates an account for anyone the provider lets in. New accounts start with no aircraft. Default off: an admin adds users first. |
|
||||
| `OIDC_AUTO_CREATE_USERS` | `true` creates an account for anyone the provider lets in, without an invitation. New accounts start with no aircraft. Default off: accounts come only from an admin, an admin's invitation, or an Owner's signing invitation (signing in with SSO from the link makes the account). |
|
||||
| `OIDC_TRUST_EMAIL` | `true` links existing accounts by email even if the provider doesn't mark it verified. Only use it if users can't edit their own email at the provider. |
|
||||
| `OIDC_ADMIN_GROUP` | Optional. Members of this provider group become admins and others lose admin, synced at each sign-in. |
|
||||
| `PWNED_PASSWORDS_CHECK` | `false` turns off the check of new passwords against Have I Been Pwned (only the first 5 characters of the password's SHA-1 are sent). Use it if the server has no outbound internet access; the check also allows the password if the service can't be reached. |
|
||||
| `PASSWORD_LOGIN` | `false` hides email/password sign-in, emailed sign-in links and password resets once SSO works. It's ignored while SSO isn't configured, so you can't lock yourself out. |
|
||||
| `APP_REPOSITORY_URL` | Optional. The source code link on Admin → About, for a fork. |
|
||||
| `APP_IMAGE` | Optional. The image the records package's viewer runs, used as is (for a fork). Default: the published image at the release that made the package. |
|
||||
| `SAM_VIEWER`, `SAM_VIEWER_ARCHIVE` | **Only for the records package's viewer** (its `viewer/docker-compose.yml` sets them). `SAM_VIEWER=true` makes the app a read-only copy with no sign-in: it imports the `.sam.zip` at `SAM_VIEWER_ARCHIVE` at start, everyone browses as a built-in account, and nothing can be changed. It refuses to start on a database with any user account, so turning it on for a real installation stops the app instead of exposing its records. |
|
||||
| `APP_REVISION`, `APP_BUILT_AT` | Set as Docker build arguments (see the `Dockerfile`) so Admin → About shows the version and the records keep a software version history. |
|
||||
|
||||
### Single sign-on (Authentik example)
|
||||
@@ -131,9 +140,9 @@ To back up or move a single aircraft with all its files, use **More → Download
|
||||
| Fleet dashboard | Every aircraft you can access, with airworthiness status and its top issues. |
|
||||
| Airworthiness | Grounded / limited (e.g. "VFR only" for an overdue 91.411 check) / due soon / current, from AD compliance, grounding squawks, inspections, replacement-critical and expiring parts, and expiring documents (an expired registration grounds). Warnings start 10 hours or 30 days ahead. The pilot in command still decides airworthiness (91.7). Logic: `app/services/airworthiness.rb`, `app/services/compliance.rb`. |
|
||||
| Hours | Absolute tach/hobbs updates or per-flight logs. Both apply the delta to every in-service component. Downward corrections are clamped at 0. Each aircraft picks tach or Hobbs as its maintenance clock (time in service). |
|
||||
| Flight import | Owners can import historical flights from `.xlsx` or `.csv` (Date, From, To, Tach, Hobbs, Oil Added, Fuel Added). Each flight's time is derived from the previous row's reading. A preview flags typos such as a tach going backwards, and rows already imported are skipped. History only: component hours aren't changed unless you choose to advance the aircraft's meters. |
|
||||
| Flight import | Import historical flights from `.xlsx` or `.csv` (Date, From, To, Tach, Hobbs, Oil Added, Fuel Added). Each flight's time is derived from the previous row's reading. A preview flags typos such as a tach going backwards, and rows already imported are skipped. History only: component hours aren't changed unless you choose to advance the aircraft's meters. |
|
||||
| Airworthiness enforcement | Optional per aircraft. It blocks flight logs and hours updates while the aircraft is grounded (not for limitations). |
|
||||
| Components | Tree of parent and child parts, TBO and replacement limits, and service/replace reset. Owners can create new component types inline. |
|
||||
| Components | Tree of parent and child parts, TBO and replacement limits, and service/replace reset. New component types can be created inline. |
|
||||
| Squawks | Four priorities. "Ground Aircraft" grounds the aircraft. Inoperative items can be deferred under 91.213(d) after confirming each condition; resolving can record the fix as a logbook entry. Attachments, reopen. |
|
||||
| Notes | Per-aircraft notes in Markdown, with a preview; shown on share links. |
|
||||
| ADs and bulletins | Shared across aircraft and applicable to the airframe or to specific components. Hour- and month-based recurrence (due at end of month), conditional and non-mandatory types, per-aircraft "not applicable" determinations, and compliance history with method of compliance and the revision complied with. |
|
||||
@@ -141,35 +150,40 @@ To back up or move a single aircraft with all its files, use **More → Download
|
||||
| AD import | Import ADs from an FAA DRS export (`.xlsx` recommended: its AD numbers link to each AD's DRS page, which the import keeps; `.csv` works without links). ADs are matched by number, so nothing is duplicated. The preview suggests Track, Not applicable or Skip for each AD, and flags superseded or non-current ADs, model mismatches, appliance or STC-only ADs, and repetitive actions. |
|
||||
| Inspections | Shared inspection types with hour, month, and day recurrence, plus history. Each says what overdue means (grounded, no IFR, no transponder, advisory); an annual can also count as the 100-hour, and the 100-hour's 10-hour overrun is credited (91.409(b)). One click adds the standard Part 91 set. |
|
||||
| Logbook | Maintenance entries with search and a link to a scanned document page. Records the signer's certificate kind and number and an inspection's result, and flags what 43.9 / 43.11 needs that's missing. Entries transcribed by Claude stay "unverified" until someone checks them against the scan. Entry templates (built-in pilot preventive maintenance per 43.3(g) and Part 43 Appendix A(c); admins add and edit their own under Admin → Logbook templates). Engine and propeller entries link the component and record its total time and time since overhaul (SMOH/SFOH/SNEW) at the entry, worked out from the entry's airframe total time; sub-components (an oil filter on the engine…) can be included with their own times. Print entries as a PDF on Avery 5163/8163 or 5164/8164 labels or half-letter/letter pages (boxed) to sign and put in the paper logbook. |
|
||||
| Documents | Collections, multi-file documents with a page viewer, per-document share visibility, bulk upload, and expiration dates (registration, insurance…). Their text is read for search: PDF text layers directly, scans by Tesseract OCR (in the image) or optionally Claude. |
|
||||
| Documents | Collections, multi-file documents with a page viewer (PDFs drawn page by page with PDF.js on phones, fetching only the pages viewed), per-document share visibility, bulk upload, and expiration dates (registration, insurance…). Their text is read for search: PDF text layers directly, scans by Tesseract OCR (in the image) or optionally Claude. |
|
||||
| Electronic signatures | Logbook entries can be signed electronically along the lines of AC 120-78B chapter 2: the signer reviews the entry, picks their certificate, re-enters their password (or signs in again with SSO) and confirms a "Certified by" statement. The signature records who, which certificate, the statement, the time and a SHA-256 fingerprint of the entry, sealed by the server; the signer gets an email. Signed entries are locked: a correction is a new signed entry that supersedes the original. Owners can invite an outside mechanic to sign one entry with their own account. Disabled accounts can't sign; their past signatures stay. |
|
||||
| Records integrity | Every change to maintenance records is kept (who, when, field by field) in a hash chain per aircraft (Activity → Record history). Nightly: a verified SQLite backup in `storage/backups` (how many are kept: Admin → Settings), then a check of the history chains and every signature; admins are emailed on a problem (Admin → About). Software versions are recorded. A records package (Access & Sharing) bundles every entry as a PDF with signatures, a signature register, the history, the status report and the `.sam.zip` for the FAA or a buyer, with a README (and a ready-to-run `viewer/docker-compose.yml`) so the recipient can browse the data in their own local copy of the app. Scans of paper logbooks can be marked as legacy records, with an "electronic records since" date per aircraft. |
|
||||
| Records integrity | Every change to maintenance records is kept (who, when, field by field) in a hash chain per aircraft (Activity → Record history). Nightly: a verified SQLite backup in `storage/backups` (how many are kept: Admin → Settings), then a check of the history chains and every signature; admins are emailed on a problem (Admin → About). Software versions are recorded. A records package (Access & Sharing) bundles every entry as a PDF with signatures, a signature register, the history, the status report and the `.sam.zip` for the FAA or a buyer, with a README and a ready-to-run `viewer/docker-compose.yml`: `docker compose up` gives the recipient a read-only copy of the app on their own computer, with the archive imported and no sign-in (`SAM_VIEWER`). Scans of paper logbooks can be marked as legacy records, with an "electronic records since" date per aircraft. |
|
||||
| Off-site backup | Nightly copy of the verified database snapshot (newest 30 kept) and every new uploaded file to Google Drive, using your own Google OAuth client and the `drive.file` scope (the app sees only its own files). Restore test from the admin page; failures emailed to admins; `bin/rails offsite:restore_files` brings files back after a restore. |
|
||||
| Recordkeeping procedures and audits | Admin → Recordkeeping Procedures generates the procedures document AC 120-78B asks for (who is responsible, who may sign, signing, corrections, backups, access, audits, transfer, legacy records) from the system setup plus a few details you fill in (with suggested text built from the installation's settings; a revision can't be adopted while a [bracketed] blank is left); adopt it as numbered, unchangeable revisions, included in the records package. Admin → Records Audits is a periodic QC checklist (app checks plus a restore test, a sample of entries against source documents and a user review); admins get the due date in the weekly reminder. The users' instructions are the guide's [Electronic records and signing](docs/guide/records.md) page. |
|
||||
| Major repairs and alterations | Form 337, STC, and ICA tracking; an STC's ICA can become a tracked recurring inspection. |
|
||||
| Weight & balance | History of empty weight and CG (linked to the alteration that changed them) and a loading calculator: takeoff and landing weight and CG against max gross and the CG envelope. The envelope can be entered as CG (inches) or as moment (lb-in/1000, as in POH moment charts and Garmin Pilot). |
|
||||
| Status report | A printable maintenance status (91.417(a)(2)): total times, life-limited parts, time since overhaul, inspections, ADs with method and revision, major alterations, open discrepancies. Also on maintenance share links. |
|
||||
| Calendar feed | A private iCalendar link (Profile) with everything coming due on your aircraft as all-day events; hour-based items get a date projected from the past year's flying. |
|
||||
| Reminders | A Monday email to owners when something is overdue or coming due, and to anyone whose certificate (e.g. an IA) is about to expire; admins also get the records audit due date (needs SMTP; users can turn it off). |
|
||||
| Reminders | A Monday email to those whose role gets reminders (Owners and Mechanics by default) when something is overdue or coming due, plus push alerts when something becomes overdue, and to anyone whose certificate (e.g. an IA) is about to expire; admins also get the records audit due date (needs SMTP; users can turn it off). |
|
||||
| Oil and fuel | Records, trend charts, and averages (last 20 intervals, IQR outlier filtering, manual exclusion). |
|
||||
| Activity log | Every write is recorded as an `AircraftEvent`. |
|
||||
| Access | Admin, owner, and pilot roles, plus share links (Current Status or Maintenance Detail, optional expiry, at most 10 per aircraft). Admins can disable accounts; a disabled account can't sign in or sign entries, and its past signatures stay. |
|
||||
| Activity log | Every write is recorded as an `AircraftEvent`; the Activity tab loads them as you scroll. |
|
||||
| Access | Configurable roles per aircraft (see [Roles](#roles)), admins' invitation links (limited uses, expiry, optionally one email address) that give an account and roles, plus share links (Current Status or Maintenance Detail, optional expiry, at most 10 per aircraft). Admins can disable accounts; a disabled account can't sign in or sign entries, and its past signatures stay. |
|
||||
| Sign-in security | Passwords of at least 12 characters, checked against known breaches (Have I Been Pwned, k-anonymity). 10 failed sign-ins in a row lock an account for 15 minutes from any address, and the user is emailed; admins can unlock. Optional authenticator-app (TOTP) codes with recovery codes for password and emailed-link sign-in and for signing entries; admins can reset them. Rate limits per address on every sign-in form. |
|
||||
| Phones and offline | Installable (PWA). Flights and squawks logged without signal, or with one too weak to answer within 10 seconds, are kept on the device and sent later, never twice. The Fleet, Overview, W&B, Log Flight and Report Squawk pages are saved ahead of time; any other page falls back to an offline page. The top bar turns red when the server can't be reached, and a ring shows saving and sending progress. |
|
||||
| REST API | Personal and integration tokens with scopes, read endpoints, squawks, draft logbook entries for signing in the app, and signed webhooks ([docs](docs/guide/api.md)). Follows the person's role. |
|
||||
| Help | The [user guide](docs/guide/README.md), shown in the app under **Help**. |
|
||||
|
||||
### Roles
|
||||
|
||||
| Action | Admin | Owner | Pilot |
|
||||
|---|:-:|:-:|:-:|
|
||||
| View everything on the aircraft | ✓ | ✓ | ✓ |
|
||||
| Update hours, log flights, add squawks/notes/oil/fuel | ✓ | ✓ | ✓ |
|
||||
| Defer squawks (91.213(d)) | ✓ | ✓ | ✓ |
|
||||
| Sign logbook entries with their own certificate | ✓ | ✓ | ✓ |
|
||||
| Edit or delete squawks and notes, resolve squawks | ✓ | ✓ | |
|
||||
| Components, logbook, ADs, inspections, documents, major records | ✓ | ✓ | |
|
||||
| Edit or delete aircraft, manage people and share links | ✓ | ✓ | |
|
||||
| Create aircraft (creator becomes owner) | ✓ | ✓ | ✓ |
|
||||
| Users, component types, airports, templates, settings, off-site backup, procedures and audits | ✓ | | |
|
||||
Each person has a role on each aircraft, and a role is a set of permissions (`app/models/permission.rb`) that administrators change under **Admin → Roles**, where they can also add their own. The built-in roles as they come:
|
||||
|
||||
| Action | Viewer | Pilot | Mechanic | Owner |
|
||||
|---|:-:|:-:|:-:|:-:|
|
||||
| View everything on the aircraft | ✓ | ✓ | ✓ | ✓ |
|
||||
| Log flights, correct own flights | | ✓ | | ✓ |
|
||||
| Update hours, report and defer squawks (91.213(d)), add notes/oil/fuel | | ✓ | ✓ | ✓ |
|
||||
| Sign logbook entries with their own certificate | | ✓ | ✓ | ✓ |
|
||||
| Logbook, components, ADs, inspections, documents, major records, W&B; edit squawks, notes, oil/fuel | | | ✓ | ✓ |
|
||||
| Reminders and overdue alerts | | | ✓ | ✓ |
|
||||
| Correct or delete any flight, imports, exports, restore from history | | | | ✓ |
|
||||
| Edit or delete the aircraft, manage people and share links | | | | ✓ |
|
||||
|
||||
Owner always has every permission. Only an Owner can give the Owner role, nobody changes their own, and every aircraft keeps an Owner. Administrators can do everything on every aircraft and manage users, roles, component types, airports, templates, settings, off-site backup, procedures and audits. Whoever adds an aircraft becomes its Owner (who can add aircraft is an admin setting: administrators only by default). Controllers declare the permission each action needs (`requires_permission`); a write with none declared is refused.
|
||||
|
||||
Users who aren't on an aircraft get a 404 for it, identical to a missing record.
|
||||
|
||||
@@ -190,15 +204,15 @@ Users who aren't on an aircraft get a 404 for it, identical to a missing record.
|
||||
Differences from the original:
|
||||
- Integer primary keys instead of UUIDs. Share tokens are 32-character random strings.
|
||||
- Logbook entries and inspection records don't keep many-to-many links to components. An inspection record or AD compliance can reference one component.
|
||||
- Accounts are created by an admin, by the first-run setup, at first SSO sign-in (if `OIDC_AUTO_CREATE_USERS` is on), or by an outside mechanic accepting a signing invitation. The original's invitation codes aren't implemented yet.
|
||||
- Accounts are created only by an admin, by the first-run setup, by someone opening an admin's invitation link (with a password, or SSO), by an outside mechanic from an Owner's signing invitation (for its address), or at first SSO sign-in when `OIDC_AUTO_CREATE_USERS` is on. Who can add aircraft, and so become an Owner, is an admin setting (administrators only by default).
|
||||
|
||||
### Not yet ported
|
||||
|
||||
The MCP server for AI agents, invitation codes, per-aircraft feature switches, the plugin system, and the desktop builds.
|
||||
The MCP server for AI agents, Prometheus metrics, per-aircraft feature switches (only airworthiness enforcement is here, as an aircraft setting), the plugin system, and the desktop builds.
|
||||
|
||||
### Added in this port
|
||||
|
||||
AirTrail sync and export, an airport database, FAA DRS AD import, spreadsheet flight import, engine monitor data (CGR-30P/C) with interactive charts, AvLab and Blackstone oil analysis import with trends, multiple squawk attachments with a photo viewer, AI logbook transcription with Claude (images and PDFs), printable logbook entries, electronic signatures and recordkeeping along the lines of AC 120-78B (record history, nightly integrity checks, records package, procedures and audits), off-site backup to Google Drive, a user guide, and an installable app (PWA) that logs flights and squawks offline, keeps pre-flight pages for use without signal, and sends push notifications.
|
||||
AirTrail sync and export, an airport database, FAA DRS AD import, spreadsheet flight import, engine monitor data (CGR-30P/C) with interactive charts, multiple squawk attachments with a photo viewer, AI logbook transcription with Claude (images and PDFs), printable logbook entries, electronic signatures and recordkeeping along the lines of AC 120-78B (record history, nightly integrity checks, records package, procedures and audits), off-site backup to Google Drive, a user guide, and an installable app (PWA) that logs flights and squawks offline, keeps pre-flight pages for use without signal, and sends push notifications.
|
||||
|
||||
## Translating
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
--color-page: oklch(96.8% 0.007 247.896); /* slate-100 */
|
||||
--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-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-hover: oklch(44.3% 0.11 240.79); /* sky-800 */
|
||||
}
|
||||
@@ -25,7 +26,7 @@
|
||||
@utility card-body { @apply p-4; }
|
||||
|
||||
@utility label { @apply block text-sm font-medium text-slate-700 mb-1; }
|
||||
@utility input { @apply block w-full rounded-md border-0 px-2.5 py-1.5 text-sm text-slate-900 shadow-sm ring-1 ring-slate-300 ring-inset placeholder:text-slate-400 focus:ring-2 focus:ring-sky-600 focus:outline-none bg-surface; }
|
||||
@utility input { @apply block w-full rounded-md border-0 px-2.5 py-1.5 text-sm text-slate-900 shadow-sm ring-1 ring-slate-300 ring-inset placeholder:text-slate-400 focus:ring-2 focus:ring-sky-600 focus:outline-none bg-surface disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-500 disabled:shadow-none disabled:ring-slate-200; }
|
||||
@utility hint { @apply mt-1 text-xs text-slate-500; }
|
||||
@utility field-error { @apply mt-1 text-xs text-red-600; }
|
||||
|
||||
@@ -62,6 +63,7 @@
|
||||
--color-page: oklch(15.5% 0.035 264);
|
||||
--color-surface: oklch(20.8% 0.042 265.755);
|
||||
--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-hover: oklch(54% 0.15 242);
|
||||
|
||||
@@ -184,3 +186,38 @@
|
||||
.btn-sm { padding: 0.4rem 0.75rem; font-size: 0.8125rem; }
|
||||
.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;
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
# search terms used.
|
||||
class AdAlertsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_ads
|
||||
before_action :set_alert, only: %i[track dismiss]
|
||||
rate_limit to: 5, within: 1.minute, only: :check, with: -> { redirect_to aircraft_airworthiness_directives_path(@aircraft), alert: t("flash.ad_alerts.try_again_in_a") }
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class AdCompliancesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_ads
|
||||
before_action :set_compliance, only: %i[edit update destroy]
|
||||
|
||||
def new
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
class AdImportsController < ApplicationController
|
||||
include AircraftScoped
|
||||
include StoredUpload
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_ads
|
||||
|
||||
def new; end
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
# Admin → Integrations: tokens for other systems (e.g. Redmine), limited to
|
||||
# chosen aircraft and scopes, each with an optional webhook (docs/api.md).
|
||||
# The token and webhook secret are shown once, right after they're made.
|
||||
class Admin::IntegrationsController < ApplicationController
|
||||
before_action :require_admin!
|
||||
before_action :set_integration, only: %i[show edit update destroy new_secret]
|
||||
|
||||
def index
|
||||
@integrations = ApiToken.integration.order(revoked_at: :desc, name: :asc).includes(:webhook_endpoints)
|
||||
end
|
||||
|
||||
def new
|
||||
@integration = ApiToken.new(kind: "integration", scopes: %w[read])
|
||||
@endpoint = WebhookEndpoint.new(events: [])
|
||||
end
|
||||
|
||||
def create
|
||||
@integration = ApiToken.new(integration_params.merge(kind: "integration", user: current_user))
|
||||
@endpoint = build_endpoint(@integration)
|
||||
ApiToken.transaction do
|
||||
@integration.save!
|
||||
@endpoint&.save!
|
||||
end
|
||||
@secret = @endpoint&.secret
|
||||
render :created
|
||||
rescue ActiveRecord::RecordInvalid
|
||||
@endpoint ||= WebhookEndpoint.new(events: [])
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def show
|
||||
@endpoint = @integration.webhook_endpoints.first
|
||||
@deliveries = @endpoint ? @endpoint.deliveries.recent.limit(25) : []
|
||||
end
|
||||
|
||||
def edit
|
||||
@endpoint = @integration.webhook_endpoints.first || WebhookEndpoint.new(events: [])
|
||||
end
|
||||
|
||||
def update
|
||||
@endpoint = @integration.webhook_endpoints.first
|
||||
ApiToken.transaction do
|
||||
@integration.update!(integration_params)
|
||||
if webhook_params[:url].present?
|
||||
@endpoint ||= @integration.webhook_endpoints.new(secret: WebhookEndpoint.new_secret)
|
||||
@endpoint.update!(webhook_params)
|
||||
else
|
||||
@endpoint&.destroy!
|
||||
end
|
||||
end
|
||||
redirect_to admin_integration_path(@integration), notice: t("flash.admin_integrations.saved")
|
||||
rescue ActiveRecord::RecordInvalid
|
||||
@endpoint ||= WebhookEndpoint.new(events: [])
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
# A new webhook secret, shown once.
|
||||
def new_secret
|
||||
@endpoint = @integration.webhook_endpoints.first or return redirect_to(admin_integration_path(@integration))
|
||||
@endpoint.update!(secret: WebhookEndpoint.new_secret)
|
||||
@secret = @endpoint.secret
|
||||
render :created
|
||||
end
|
||||
|
||||
def destroy
|
||||
@integration.revoke!
|
||||
@integration.webhook_endpoints.update_all(enabled: false)
|
||||
redirect_to admin_integrations_path, notice: t("flash.admin_integrations.revoked", name: @integration.name)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_integration = @integration = ApiToken.integration.find(params[:id])
|
||||
|
||||
def integration_params
|
||||
p = params.require(:api_token).permit(:name, scopes: [], aircraft_ids: [])
|
||||
p[:scopes] = Array(p[:scopes]) & ApiToken::SCOPES.keys
|
||||
p[:aircraft_ids] = Aircraft.where(id: Array(p[:aircraft_ids])).ids
|
||||
p
|
||||
end
|
||||
|
||||
def webhook_params
|
||||
p = params.fetch(:webhook, {}).permit(:url, :enabled, events: [])
|
||||
p[:events] = Array(p[:events]) & WebhookEndpoint::EVENTS.keys
|
||||
p[:enabled] = p[:enabled] != "0"
|
||||
p
|
||||
end
|
||||
|
||||
def build_endpoint(integration)
|
||||
return if webhook_params[:url].blank?
|
||||
integration.webhook_endpoints.new(webhook_params.merge(secret: WebhookEndpoint.new_secret))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,32 @@
|
||||
# Invitation codes for any aircraft, or none (an account only), by
|
||||
# administrators (AccessInvitation).
|
||||
class Admin::InvitationsController < ApplicationController
|
||||
before_action :require_admin!
|
||||
|
||||
def index
|
||||
@invitations = AccessInvitation.recent_first.includes(:created_by, grants: %i[aircraft role]).limit(200)
|
||||
end
|
||||
|
||||
def new
|
||||
@invitation = AccessInvitation.new(max_uses: 1, expires_at: AccessInvitation::VALID_FOR.from_now.change(sec: 0))
|
||||
end
|
||||
|
||||
def create
|
||||
roles = Role.all.index_by(&:id)
|
||||
grants = Aircraft.where(id: params.fetch(:roles, {}).keys).filter_map do |aircraft|
|
||||
role = roles[params[:roles][aircraft.id.to_s].to_i]
|
||||
[ aircraft, role ] if role
|
||||
end
|
||||
@invitation = AccessInvitation.create_for(current_user, params.require(:access_invitation).permit(:label, :email, :name, :max_uses, :expires_at), grants)
|
||||
if @invitation.persisted?
|
||||
render :created
|
||||
else
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
AccessInvitation.find(params[:id]).update!(revoked_at: Time.current)
|
||||
redirect_to admin_invitations_path, notice: t("flash.admin_invitations.revoked")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,57 @@
|
||||
# The roles people can have on an aircraft and what each allows (Role,
|
||||
# Permission). Owner always has every permission; the other built-in roles
|
||||
# can be changed but not deleted; administrators can add their own.
|
||||
class Admin::RolesController < ApplicationController
|
||||
before_action :require_admin!
|
||||
before_action :set_role, only: %i[edit update destroy]
|
||||
|
||||
def index
|
||||
Role.ensure_built_in!
|
||||
@roles = Role.ordered
|
||||
@counts = AircraftRole.group(:role_id).count
|
||||
end
|
||||
|
||||
def new
|
||||
@role = Role.new(permissions: Permission::DEFAULTS["viewer"])
|
||||
end
|
||||
|
||||
def create
|
||||
@role = Role.new(role_params)
|
||||
if @role.save
|
||||
redirect_to admin_roles_path, notice: t("flash.admin_roles.created", name: @role.name)
|
||||
else
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def edit; end
|
||||
|
||||
def update
|
||||
attributes = @role.owner? ? role_params.except(:permissions) : role_params
|
||||
if @role.update(attributes)
|
||||
redirect_to admin_roles_path, notice: t("flash.admin_roles.updated", name: @role.name)
|
||||
else
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
if @role.built_in?
|
||||
redirect_to admin_roles_path, alert: t("flash.admin_roles.built_in")
|
||||
elsif @role.aircraft_roles.exists?
|
||||
redirect_to admin_roles_path, alert: t("flash.admin_roles.in_use", name: @role.name, count: @role.aircraft_roles.count)
|
||||
else
|
||||
@role.destroy!
|
||||
redirect_to admin_roles_path, notice: t("flash.admin_roles.deleted", name: @role.name)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_role = @role = Role.find(params[:id])
|
||||
|
||||
# Unticking every box sends none, so an empty list is always sent too.
|
||||
def role_params
|
||||
params.require(:role).permit(:name, :description, permissions: []).tap { _1[:permissions] = Array(_1[:permissions]).compact_blank }
|
||||
end
|
||||
end
|
||||
@@ -2,18 +2,18 @@ class Admin::SettingsController < ApplicationController
|
||||
before_action :require_admin!
|
||||
|
||||
def edit
|
||||
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text].index_with { Setting.integer(_1) }
|
||||
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text anyone_adds_aircraft].index_with { Setting.integer(_1) }
|
||||
end
|
||||
|
||||
def update
|
||||
submitted = params.fetch(:settings, {}).permit(:max_upload_mb, :backups_kept, :offsite_backups_kept, :documents_claude_text).to_h
|
||||
submitted = params.fetch(:settings, {}).permit(:max_upload_mb, :backups_kept, :offsite_backups_kept, :documents_claude_text, :anyone_adds_aircraft).to_h
|
||||
records = Setting.update_integers(submitted)
|
||||
@errors = records.flat_map { _1.errors.full_messages }
|
||||
if @errors.empty?
|
||||
Rails.logger.info("[settings] #{current_user.email_address} changed #{submitted.inspect}")
|
||||
redirect_to edit_admin_settings_path, notice: t("flash.admin_settings.settings_saved")
|
||||
else
|
||||
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text].index_with { Setting.integer(_1) }.merge(submitted)
|
||||
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text anyone_adds_aircraft].index_with { Setting.integer(_1) }.merge(submitted)
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# Administrators give people roles on any aircraft (from Admin → Users),
|
||||
# under the same rules as the aircraft's Access page (AircraftAccess).
|
||||
class Admin::UserAircraftRolesController < ApplicationController
|
||||
before_action :require_admin!
|
||||
before_action :set_user
|
||||
|
||||
def create
|
||||
aircraft = Aircraft.find_by(id: params[:aircraft_id])
|
||||
return back(alert: t("services.aircraft_access.not_found")) unless aircraft
|
||||
back_with AircraftAccess.new(aircraft, actor: current_user).add(@user, Role.find_by(id: params[:role_id])),
|
||||
t("flash.admin_users.access_added", tail_number: aircraft.tail_number)
|
||||
end
|
||||
|
||||
def update
|
||||
membership = @user.aircraft_roles.find(params[:id])
|
||||
back_with AircraftAccess.new(membership.aircraft, actor: current_user).change(membership, Role.find_by(id: params[:role_id])),
|
||||
t("flash.admin_users.access_changed", tail_number: membership.aircraft.tail_number)
|
||||
end
|
||||
|
||||
def destroy
|
||||
membership = @user.aircraft_roles.find(params[:id])
|
||||
back_with AircraftAccess.new(membership.aircraft, actor: current_user).remove(membership),
|
||||
t("flash.admin_users.access_removed", tail_number: membership.aircraft.tail_number)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_user = @user = User.find(params[:user_id])
|
||||
def back(flash) = redirect_to(edit_admin_user_path(@user, anchor: "access"), flash)
|
||||
def back_with(error, notice) = back(error ? { alert: error } : { notice: notice })
|
||||
end
|
||||
@@ -3,7 +3,7 @@ class Admin::UsersController < ApplicationController
|
||||
before_action :set_user, only: %i[edit update destroy disable enable unlock reset_two_factor]
|
||||
|
||||
def index
|
||||
@users = User.order(:email_address).includes(:certificates, aircraft_roles: :aircraft)
|
||||
@users = User.order(:email_address).includes(:certificates, aircraft_roles: %i[aircraft role])
|
||||
end
|
||||
|
||||
def new
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# Download the aircraft's flights as an AirTrail import file.
|
||||
class AirTrailExportsController < ApplicationController
|
||||
include AircraftScoped
|
||||
requires_permission :log_flights
|
||||
|
||||
def new
|
||||
@export = build_export
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
class AircraftController < ApplicationController
|
||||
include AircraftScoped
|
||||
skip_before_action :set_aircraft, only: %i[index new create]
|
||||
before_action :require_owner!, only: %i[edit update destroy]
|
||||
skip_before_action :set_aircraft, :authorize_permission!, only: %i[index new create]
|
||||
before_action :require_aircraft_adder!, only: %i[new create]
|
||||
requires_permission :edit_aircraft, only: %i[edit update]
|
||||
requires_permission :delete_aircraft, only: :destroy
|
||||
requires_permission :update_hours, only: :update_hours
|
||||
|
||||
def index
|
||||
@aircraft_list = current_user.accessible_aircraft.ordered.with_attached_picture
|
||||
@@ -52,10 +55,9 @@ class AircraftController < ApplicationController
|
||||
|
||||
# Pilots and above: set absolute tach/hobbs readings.
|
||||
def update_hours
|
||||
delta = HoursService.new(@aircraft).update_hours!(
|
||||
tach_time: params.require(:tach_time), hobbs_time: params[:hobbs_time]
|
||||
)
|
||||
redirect_to @aircraft, notice: t("flash.aircraft.hours_updated", delta: "#{'+' if delta >= 0}#{delta}")
|
||||
before = { tach: @aircraft.tach_time.to_d, hobbs: @aircraft.hobbs_time.to_d }
|
||||
HoursService.new(@aircraft).update_hours!(tach_time: params.require(:tach_time), hobbs_time: params[:hobbs_time])
|
||||
redirect_to @aircraft, notice: hours_notice(before)
|
||||
rescue AircraftGroundedError => e
|
||||
redirect_to @aircraft, alert: e.message
|
||||
rescue ArgumentError
|
||||
@@ -64,6 +66,19 @@ class AircraftController < ApplicationController
|
||||
|
||||
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_params
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Download an aircraft as a .sam.zip archive (owners and admins).
|
||||
class AircraftExportsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :export_data
|
||||
|
||||
EXPORT_DIR = Rails.root.join("tmp/exports")
|
||||
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
# create an aircraft with all its records. The archive is checked right away;
|
||||
# the import itself runs in the background (AircraftImportJob).
|
||||
class AircraftImportsController < ApplicationController
|
||||
before_action :require_aircraft_adder!, only: %i[new create]
|
||||
before_action :set_import, only: :show
|
||||
|
||||
def new; end
|
||||
|
||||
def create
|
||||
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)
|
||||
tail = params[:tail_number].to_s.strip.upcase.presence || preview.tail_number.to_s.upcase
|
||||
|
||||
@@ -1,54 +1,37 @@
|
||||
# Owner-only: manage who can access the aircraft, and its public share links.
|
||||
# Who can access the aircraft, with which role ("manage people"), and its
|
||||
# public share links ("manage sharing", see ShareTokensController). The rules
|
||||
# for changing roles are in AircraftAccess.
|
||||
class AircraftRolesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
checks_permission_itself only: :index
|
||||
requires_permission :manage_people, only: %i[create update destroy]
|
||||
|
||||
def index
|
||||
@roles = @aircraft.roles.includes(:user).order(:role, :created_at)
|
||||
return permission_denied unless can?(:manage_people) || can?(:manage_sharing) || can?(:export_data)
|
||||
@access = AircraftAccess.new(@aircraft, actor: current_user)
|
||||
@roles = @aircraft.roles.includes(:user, :role).joins(:role).order("roles.position", :created_at)
|
||||
@share_tokens = @aircraft.share_tokens.order(created_at: :desc).includes(:created_by)
|
||||
end
|
||||
|
||||
def create
|
||||
user = User.find_by(email_address: params[:email_address].to_s.strip.downcase)
|
||||
unless user
|
||||
return redirect_to aircraft_aircraft_roles_path(@aircraft),
|
||||
alert: t("flash.aircraft_roles.no_user_with_that")
|
||||
end
|
||||
role = @aircraft.roles.new(user: user, role: params[:role])
|
||||
if role.save
|
||||
log_event("role", t("flash.aircraft_roles.added_as", display_name: user.display_name, role: role.role))
|
||||
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.added", display_name: user.display_name)
|
||||
else
|
||||
redirect_to aircraft_aircraft_roles_path(@aircraft), alert: role.errors.full_messages.to_sentence
|
||||
end
|
||||
return back(alert: t("flash.aircraft_roles.no_user_with_that")) unless user
|
||||
error = access.add(user, Role.find_by(id: params[:role_id]))
|
||||
back(error ? { alert: error } : { notice: t("flash.aircraft_roles.added", display_name: user.display_name) })
|
||||
end
|
||||
|
||||
def update
|
||||
role = @aircraft.roles.find(params[:id])
|
||||
if demoting_last_owner?(role, params[:role])
|
||||
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.an_aircraft_must_keep")
|
||||
end
|
||||
role.update!(role: params[:role])
|
||||
log_event("role", t("flash.aircraft_roles.changed_to", display_name: role.user.display_name, role: role.role))
|
||||
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.role_updated")
|
||||
error = access.change(@aircraft.roles.find(params[:id]), Role.find_by(id: params[:role_id]))
|
||||
back(error ? { alert: error } : { notice: t("flash.aircraft_roles.role_updated") })
|
||||
end
|
||||
|
||||
def destroy
|
||||
role = @aircraft.roles.find(params[:id])
|
||||
if role.user == current_user
|
||||
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.you_can_t_remove")
|
||||
end
|
||||
if demoting_last_owner?(role, nil)
|
||||
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.an_aircraft_must_keep_2")
|
||||
end
|
||||
role.destroy!
|
||||
log_event("role", t("flash.aircraft_roles.removed", display_name: role.user.display_name))
|
||||
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.access_removed")
|
||||
error = access.remove(@aircraft.roles.find(params[:id]))
|
||||
back(error ? { alert: error } : { notice: t("flash.aircraft_roles.access_removed") })
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def demoting_last_owner?(role, new_role)
|
||||
role.role == "owner" && new_role != "owner" && @aircraft.roles.owners.count <= 1
|
||||
end
|
||||
def access = AircraftAccess.new(@aircraft, actor: current_user)
|
||||
def back(flash) = redirect_to(aircraft_aircraft_roles_path(@aircraft), flash)
|
||||
end
|
||||
@@ -1,7 +1,7 @@
|
||||
# Flights → Standardize airport codes (owners).
|
||||
class AirportCodesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :edit_any_flight
|
||||
|
||||
def show
|
||||
@standardizer = AirportCodeStandardizer.new(@aircraft)
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
class AirworthinessDirectivesController < ApplicationController
|
||||
include AircraftScoped
|
||||
include Applicability
|
||||
before_action :require_owner!, except: :index
|
||||
requires_permission :manage_ads, except: :index
|
||||
before_action :set_ad, only: %i[edit update destroy]
|
||||
|
||||
def index
|
||||
@rows = Compliance.ad_rows(@aircraft)
|
||||
@history = AdCompliance.for_aircraft(@aircraft).recent_first
|
||||
.includes(:component, :logbook_entry, airworthiness_directive: :document, inspection_record: :inspection_type)
|
||||
@attachable = AirworthinessDirective.where.not(id: @aircraft.applicable_ads.select(:id)).ordered if owner?
|
||||
@attachable = AirworthinessDirective.where.not(id: @aircraft.applicable_ads.select(:id)).ordered if can?(:manage_ads)
|
||||
@alerts = @aircraft.ad_alerts.pending
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
module Api
|
||||
module V1
|
||||
# The fleet this token reaches, and each aircraft's own lists.
|
||||
class AircraftController < BaseController
|
||||
before_action -> { require_scope!(:read) }
|
||||
|
||||
def index
|
||||
render_page(aircraft_scope) { ApiPresenter.aircraft(_1) }
|
||||
end
|
||||
|
||||
def show
|
||||
render json: { data: ApiPresenter.aircraft(find_aircraft(params[:id])) }
|
||||
end
|
||||
|
||||
# The parts tree (?all=1 includes disposed parts).
|
||||
def components
|
||||
aircraft = find_aircraft(params[:id])
|
||||
scope = aircraft.components.includes(:component_type)
|
||||
scope = scope.where.not(status: "DISPOSED") unless params[:all].present?
|
||||
render_page(scope) { ApiPresenter.component(_1) }
|
||||
end
|
||||
|
||||
# Everything coming due, soonest first (hours projected to dates).
|
||||
def due
|
||||
aircraft = find_aircraft(params[:id])
|
||||
render json: { data: DueList.new(aircraft).items.map { ApiPresenter.due_item(_1) } }
|
||||
end
|
||||
|
||||
def inspections
|
||||
aircraft = find_aircraft(params[:id])
|
||||
render json: { data: Compliance.inspection_rows(aircraft).map { ApiPresenter.inspection(_1) } }
|
||||
end
|
||||
|
||||
def ads
|
||||
aircraft = find_aircraft(params[:id])
|
||||
render json: { data: Compliance.ad_rows(aircraft).map { ApiPresenter.ad(_1) } }
|
||||
end
|
||||
|
||||
# Logbook entries, oldest first (paged); ?log=AC|ENG|PROP|AVIONICS|OTHER, ?signed=true|false.
|
||||
def logbook_entries
|
||||
aircraft = find_aircraft(params[:id])
|
||||
scope = aircraft.logbook_entries.includes(:signature)
|
||||
scope = scope.where(log_type: params[:log]) if params[:log].present?
|
||||
scope = params[:signed] == "true" ? scope.where.associated(:signature) : scope.where.missing(:signature) if params[:signed].present?
|
||||
render_page(scope) { ApiPresenter.logbook_entry(_1) }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,127 @@
|
||||
# The REST API, version 1 (docs/api.md). JSON in and out; a token in
|
||||
# "Authorization: Bearer sam_…" instead of a browser session, so no cookies
|
||||
# and no CSRF tokens.
|
||||
#
|
||||
# A personal token acts as its owner. An integration token acts for the
|
||||
# person named in "SAM-On-Behalf-Of: <email>" (required for writes), and
|
||||
# reaches only its aircraft that person can also see.
|
||||
module Api
|
||||
module V1
|
||||
class BaseController < ActionController::API
|
||||
include RejectsNullBytes
|
||||
|
||||
MAX_PAGE = 200
|
||||
|
||||
before_action :authenticate
|
||||
rate_limit to: 600, within: 1.minute, by: -> { @api_token&.id || request.remote_ip },
|
||||
with: -> { render_error(:too_many_requests, "rate_limited", "Too many requests; slow down.") }
|
||||
around_action :idempotent, if: -> { request.post? || request.patch? || request.delete? }
|
||||
|
||||
rescue_from ActiveRecord::RecordNotFound do
|
||||
render_error(:not_found, "not_found", "Not found, or not available to this token.")
|
||||
end
|
||||
rescue_from ActionController::ParameterMissing, ActionDispatch::Http::Parameters::ParseError do |e|
|
||||
render_error(:bad_request, "bad_request", e.message.truncate(200))
|
||||
end
|
||||
rescue_from ActiveRecord::RecordInvalid do |e|
|
||||
render_invalid(e.record)
|
||||
end
|
||||
rescue_from ActiveSupport::MessageVerifier::InvalidSignature, ActiveModel::RangeError,
|
||||
ActiveRecord::NotNullViolation, ActiveRecord::InvalidForeignKey do
|
||||
render_error(:unprocessable_entity, "invalid", "Some values couldn't be saved.")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
attr_reader :api_token
|
||||
|
||||
def acting_user = Current.api_user
|
||||
|
||||
def authenticate
|
||||
token = request.authorization.to_s[/\ABearer\s+(\S+)\z/i, 1]
|
||||
@api_token = ApiToken.authenticate(token)
|
||||
return render_error(:unauthorized, "unauthorized", "A valid API token is required.") unless @api_token
|
||||
|
||||
Current.api_token = @api_token
|
||||
Current.ip_address = request.remote_ip
|
||||
Current.api_user = @api_token.personal? ? @api_token.user : on_behalf_of
|
||||
@api_token.used!(request.remote_ip)
|
||||
end
|
||||
|
||||
# The person an integration is acting for, if it named one.
|
||||
def on_behalf_of
|
||||
email = request.headers["SAM-On-Behalf-Of"].to_s.strip.downcase.presence or return
|
||||
User.active.find_by(email_address: email) ||
|
||||
render_error(:unprocessable_entity, "unknown_user", "SAM-On-Behalf-Of doesn't match an active user.")
|
||||
end
|
||||
|
||||
def require_scope!(scope)
|
||||
return if api_token.allows?(scope)
|
||||
render_error(:forbidden, "missing_scope", "This token doesn't have the #{scope} scope.")
|
||||
end
|
||||
|
||||
# Writes always name a person, so the record history shows who.
|
||||
def require_person!
|
||||
return if acting_user
|
||||
render_error(:unprocessable_entity, "on_behalf_of_required", "Writes with an integration token need SAM-On-Behalf-Of.")
|
||||
end
|
||||
|
||||
def aircraft_scope = api_token.aircraft_scope(acting_user)
|
||||
|
||||
def find_aircraft(id = params[:aircraft_id]) = aircraft_scope.find(id)
|
||||
|
||||
# What the person it's acting for can do on the aircraft, as in the app (Role).
|
||||
def can?(permission, aircraft) = acting_user&.can?(permission, aircraft) || false
|
||||
|
||||
def not_permitted(permission)
|
||||
render_error(:forbidden, "not_permitted", "This needs the \"#{Permission.label(permission)}\" permission on the aircraft.")
|
||||
end
|
||||
|
||||
# ?limit= (1–200, default 50), ?after=<id> to continue, ?updated_since=<ISO time>.
|
||||
def paginate(scope)
|
||||
limit = params.fetch(:limit, 50).to_i.clamp(1, MAX_PAGE)
|
||||
scope = scope.where(scope.arel_table[:id].gt(params[:after].to_i)) if params[:after].present?
|
||||
if params[:updated_since].present?
|
||||
since = Time.iso8601(params[:updated_since].to_s) rescue (raise ActionController::BadRequest, "updated_since must be an ISO 8601 time")
|
||||
scope = scope.where(scope.arel_table[:updated_at].gteq(since))
|
||||
end
|
||||
records = scope.reorder(:id).limit(limit + 1).to_a
|
||||
more = records.size > limit
|
||||
records = records.first(limit)
|
||||
[ records, (records.last.id if more) ]
|
||||
end
|
||||
|
||||
def render_page(scope, &present)
|
||||
records, next_after = paginate(scope)
|
||||
render json: { data: records.map(&present), next_after: next_after }
|
||||
end
|
||||
|
||||
def render_error(status, code, message, fields: nil)
|
||||
render json: { error: { code: code, message: message, fields: fields }.compact }, status: status
|
||||
end
|
||||
|
||||
def render_invalid(record)
|
||||
render_error(:unprocessable_entity, "invalid", record.errors.full_messages.to_sentence, fields: record.errors.to_hash)
|
||||
end
|
||||
|
||||
# The same Idempotency-Key again (a retry) gets the first answer; the
|
||||
# same key with a different request is a conflict.
|
||||
def idempotent
|
||||
key = request.headers["Idempotency-Key"].to_s.strip
|
||||
return yield if key.empty? || api_token.nil?
|
||||
return render_error(:bad_request, "bad_request", "Idempotency-Key is too long.") if key.length > 100
|
||||
|
||||
digest = OpenSSL::Digest::SHA256.hexdigest([ request.method, request.path, request.raw_post ].join("\n"))
|
||||
if (seen = api_token.idempotency_keys.find_by(key: key))
|
||||
return render_error(:conflict, "idempotency_conflict", "This Idempotency-Key was used for a different request.") if seen.request_digest != digest
|
||||
response.headers["Idempotent-Replay"] = "true"
|
||||
return render(json: seen.response_body, status: seen.response_status)
|
||||
end
|
||||
yield
|
||||
return if response.status >= 500
|
||||
api_token.idempotency_keys.create(key: key, request_digest: digest, response_status: response.status,
|
||||
response_body: response.body, created_at: Time.current)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,129 @@
|
||||
module Api
|
||||
module V1
|
||||
# Draft logbook entries for one visit (docs/api.md, "Draft entries"). The
|
||||
# work items become one unsigned entry per logbook, signed in the app; the
|
||||
# squawks they resolve and inspections they complete are held until every
|
||||
# entry is signed. Like writing entries in the app, it's for the
|
||||
# aircraft's owners.
|
||||
class DraftBatchesController < BaseController
|
||||
before_action -> { require_scope!(:read) }, only: %i[index show lookup]
|
||||
before_action -> { require_scope!("drafts:write") }, :require_person!, only: %i[create destroy]
|
||||
|
||||
def index
|
||||
scope = find_aircraft.draft_batches.includes(entries: :signature)
|
||||
scope = scope.where(status: params[:status]) if params[:status].present?
|
||||
render_page(scope) { ApiPresenter.draft_batch(_1) }
|
||||
end
|
||||
|
||||
def lookup
|
||||
scope = DraftBatch.where(aircraft: aircraft_scope, external_ref: params.require(:external_ref)).includes(entries: :signature)
|
||||
render json: { data: scope.map { ApiPresenter.draft_batch(_1) } }
|
||||
end
|
||||
|
||||
def show
|
||||
render json: { data: ApiPresenter.draft_batch(find_batch) }
|
||||
end
|
||||
|
||||
# POST /aircraft/:aircraft_id/draft_batches
|
||||
def create
|
||||
@aircraft = find_aircraft
|
||||
return not_permitted(:write_logbook) unless can?(:write_logbook, @aircraft)
|
||||
|
||||
input = params.require(:draft_batch)
|
||||
items = Array(input[:items]).map { _1.permit(:log, :text, :external_ref, resolves_squawks: []) }
|
||||
errors = check(input, items)
|
||||
return render_error(:unprocessable_entity, "invalid", errors.values.flatten.to_sentence, fields: errors) if errors.any?
|
||||
|
||||
invitations = {}
|
||||
batch = DraftBatch.transaction do
|
||||
b = @aircraft.draft_batches.create!(api_token: api_token, created_by: acting_user, external_ref: input[:external_ref],
|
||||
signer_email: signer_email(input), held: held(input, items))
|
||||
items.group_by { _1[:log] }.each do |log, group|
|
||||
entry = b.entries.create!(aircraft: @aircraft, log_type: log, date: input[:date], text: group.map { _1[:text].to_s.strip }.join("\n\n"),
|
||||
entry_type: inspection_logs(input, items).include?(log) ? "INSPECTION" : "MAINTENANCE",
|
||||
inspection_result: inspection_result_for(input, items, log),
|
||||
aircraft_hours_at_entry: input[:aircraft_hours].presence, external_ref: group.filter_map { _1[:external_ref] }.join(",").presence)
|
||||
invitations[entry.id] = invite(entry, b.signer_email, send: input.dig(:signer, :send_email).to_s == "true") if b.signer_email
|
||||
end
|
||||
b
|
||||
end
|
||||
@aircraft.log_event!("logbook", I18n.t("api.draft_batches.sent", count: batch.entries.size, name: api_token.name), notes: batch.external_ref)
|
||||
render json: { data: ApiPresenter.draft_batch(batch.reload, invitations: invitations) }, status: :created
|
||||
end
|
||||
|
||||
# DELETE /draft_batches/:id: withdraw it while nothing in it is signed.
|
||||
def destroy
|
||||
batch = find_batch
|
||||
return not_permitted(:write_logbook) unless can?(:write_logbook, batch.aircraft)
|
||||
unless batch.awaiting? && batch.entries.none?(&:signed?)
|
||||
return render_error(:conflict, "signed", "Part of this draft is signed (or it's no longer awaiting signature); correct it in the app instead.")
|
||||
end
|
||||
batch.withdraw!
|
||||
render json: { data: ApiPresenter.draft_batch(batch.reload) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def find_batch = DraftBatch.where(aircraft: aircraft_scope).includes(entries: :signature).find(params[:id])
|
||||
|
||||
def check(input, items)
|
||||
errors = Hash.new { |h, k| h[k] = [] }
|
||||
errors[:items] << "at least one item is needed" if items.empty?
|
||||
items.each_with_index do |item, i|
|
||||
errors[:"items.#{i}.log"] << "must be one of #{LogbookEntry::LOG_TYPES.keys.join(', ')}" unless LogbookEntry::LOG_TYPES.key?(item[:log])
|
||||
errors[:"items.#{i}.text"] << "can't be blank" if item[:text].blank?
|
||||
end
|
||||
errors[:date] << "must be a date (YYYY-MM-DD)" unless (Date.iso8601(input[:date].to_s) rescue nil)
|
||||
errors[:aircraft_hours] << "must be a number" if input[:aircraft_hours].present? && !input[:aircraft_hours].to_s.match?(/\A\d+(\.\d+)?\z/)
|
||||
squawk_ids = items.flat_map { Array(_1[:resolves_squawks]) }.map(&:to_i)
|
||||
missing = squawk_ids - @aircraft.squawks.active.where(id: squawk_ids).ids
|
||||
errors[:resolves_squawks] << "no open squawk #{missing.join(', ')} on this aircraft" if missing.any?
|
||||
Array(input[:completes_inspections]).each_with_index do |c, i|
|
||||
id = c.respond_to?(:[]) ? c[:inspection_type_id].to_i : 0
|
||||
errors[:"completes_inspections.#{i}"] << "no inspection #{id} applies to this aircraft" unless @aircraft.applicable_inspection_types.exists?(id: id)
|
||||
log = inspection_log(c, items)
|
||||
errors[:"completes_inspections.#{i}.log"] << "must be the log of one of the items" unless items.any? { _1[:log] == log }
|
||||
unless LogbookEntry::INSPECTION_RESULTS.key?(c.respond_to?(:[]) ? c[:result].to_s : "")
|
||||
errors[:"completes_inspections.#{i}.result"] << "must be #{LogbookEntry::INSPECTION_RESULTS.keys.join(' or ')}"
|
||||
end
|
||||
end
|
||||
Array(input[:completes_inspections]).group_by { inspection_log(_1, items) }.each do |log, group|
|
||||
errors[:completes_inspections] << "inspections in the #{log} log need the same result (one entry)" if group.map { _1[:result].to_s }.uniq.size > 1
|
||||
end
|
||||
errors[:aircraft_hours] << "is needed to record an inspection" if Array(input[:completes_inspections]).any? && input[:aircraft_hours].blank?
|
||||
email = input.dig(:signer, :email).to_s.strip
|
||||
errors[:"signer.email"] << "isn't an email address" if email.present? && !email.match?(URI::MailTo::EMAIL_REGEXP)
|
||||
errors[:"signer.send_email"] << "needs email set up on the server" if input.dig(:signer, :send_email).to_s == "true" && !MailSettings.configured?
|
||||
errors
|
||||
end
|
||||
|
||||
# The inspection goes in the logbook named for it, else the airframe
|
||||
# log if there's an item for it, else the first item's.
|
||||
def inspection_log(c, items)
|
||||
c[:log].presence || (items.any? { _1[:log] == "AC" } ? "AC" : items.first&.dig(:log))
|
||||
end
|
||||
|
||||
def inspection_logs(input, items) = Array(input[:completes_inspections]).map { inspection_log(_1, items) }
|
||||
|
||||
# approved | discrepancies, for the entry in that log that records inspections.
|
||||
def inspection_result_for(input, items, log)
|
||||
Array(input[:completes_inspections]).find { inspection_log(_1, items) == log }&.dig(:result)
|
||||
end
|
||||
|
||||
def held(input, items)
|
||||
{ "squawks" => items.flat_map { |it| Array(it[:resolves_squawks]).map { |id| { "id" => id.to_i, "log" => it[:log] } } }.uniq { _1["id"] },
|
||||
"inspections" => Array(input[:completes_inspections]).map { { "id" => _1[:inspection_type_id].to_i, "log" => inspection_log(_1, items) } } }
|
||||
end
|
||||
|
||||
def signer_email(input) = input.dig(:signer, :email).to_s.strip.downcase.presence
|
||||
|
||||
# A link for the signer to sign this entry with their own account,
|
||||
# returned to the caller to pass on; emailed too when asked.
|
||||
def invite(entry, email, send: false)
|
||||
invitation = entry.signing_invitations.create!(email: email, invited_by: acting_user)
|
||||
SigningInvitationMailer.invite(invitation, invitation.token).deliver_later if send
|
||||
invitation.token
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,16 @@
|
||||
module Api
|
||||
module V1
|
||||
# What this token is and who it's acting as: a quick check for a new integration.
|
||||
class MeController < BaseController
|
||||
def show
|
||||
render json: { data: {
|
||||
token: { name: api_token.name, kind: api_token.kind, hint: api_token.token_hint, scopes: api_token.scopes,
|
||||
aircraft_ids: (api_token.aircraft_ids if api_token.integration?) }.compact,
|
||||
acting_as: acting_user && { id: acting_user.id, name: acting_user.display_name, email: acting_user.email_address },
|
||||
aircraft_ids: aircraft_scope.ids,
|
||||
api_version: "v1", app_version: Rails.root.join("VERSION").read.strip
|
||||
} }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,67 @@
|
||||
module Api
|
||||
module V1
|
||||
# Squawks: list and report on an aircraft; find by external_ref; update.
|
||||
# Resolving happens through a signed logbook entry, not here.
|
||||
class SquawksController < BaseController
|
||||
before_action -> { require_scope!(:read) }, only: %i[index show lookup]
|
||||
before_action -> { require_scope!("squawks:write") }, :require_person!, only: %i[create update]
|
||||
|
||||
# GET /aircraft/:aircraft_id/squawks?status=open|resolved|all (default open)
|
||||
def index
|
||||
scope = find_aircraft.squawks.includes(:reported_by).with_attached_attachments
|
||||
scope = case params.fetch(:status, "open")
|
||||
when "open" then scope.active
|
||||
when "resolved" then scope.resolved
|
||||
else scope
|
||||
end
|
||||
render_page(scope) { ApiPresenter.squawk(_1) }
|
||||
end
|
||||
|
||||
# GET /squawks?external_ref=redmine:issue:4512
|
||||
def lookup
|
||||
ref = params.require(:external_ref)
|
||||
scope = Squawk.where(aircraft: aircraft_scope, external_ref: ref).includes(:reported_by).with_attached_attachments
|
||||
render json: { data: scope.map { ApiPresenter.squawk(_1) } }
|
||||
end
|
||||
|
||||
def show
|
||||
render json: { data: ApiPresenter.squawk(find_squawk) }
|
||||
end
|
||||
|
||||
# POST /aircraft/:aircraft_id/squawks
|
||||
def create
|
||||
aircraft = find_aircraft
|
||||
return not_permitted(:report_squawks) unless can?(:report_squawks, aircraft)
|
||||
squawk = aircraft.squawks.new(create_params.merge(reported_by: acting_user, resolved: false))
|
||||
squawk.component_id = nil unless aircraft.components.exists?(id: squawk.component_id)
|
||||
squawk.save!
|
||||
SquawkReported.call(squawk, by: acting_user)
|
||||
render json: { data: ApiPresenter.squawk(squawk) }, status: :created
|
||||
end
|
||||
|
||||
# PATCH /squawks/:id: external_ref by anyone who may write; the rest
|
||||
# (issue, priority, component, notes) with "manage squawks", as in the app.
|
||||
def update
|
||||
squawk = find_squawk
|
||||
return render_error(:unprocessable_entity, "resolved", "A resolved squawk can't be changed.") if squawk.resolved?
|
||||
attrs = params.require(:squawk).permit(:external_ref, :issue_reported, :priority, :component_id, :notes)
|
||||
if (attrs.keys - %w[external_ref]).any? && !can?(:manage_squawks, squawk.aircraft)
|
||||
return not_permitted(:manage_squawks)
|
||||
end
|
||||
attrs[:component_id] = nil if attrs.key?(:component_id) && !squawk.aircraft.components.exists?(id: attrs[:component_id])
|
||||
squawk.update!(attrs)
|
||||
render json: { data: ApiPresenter.squawk(squawk) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def find_squawk = Squawk.where(aircraft: aircraft_scope).find(params[:id])
|
||||
|
||||
def create_params
|
||||
params.require(:squawk).permit(:issue_reported, :priority, :component_id, :external_ref).tap do |p|
|
||||
p[:priority] = p.fetch(:priority, 2).to_i
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -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,9 +1,12 @@
|
||||
class ApplicationController < ActionController::Base
|
||||
default_form_builder AppFormBuilder
|
||||
include Authentication
|
||||
include TimeZones
|
||||
allow_browser versions: :modern
|
||||
|
||||
include RejectsNullBytes
|
||||
prepend_before_action :redirect_to_setup
|
||||
prepend_before_action :viewer_guard # first (see Viewer)
|
||||
before_action { Current.ip_address = request.remote_ip } # for record history
|
||||
helper_method :current_user
|
||||
|
||||
@@ -14,15 +17,51 @@ class ApplicationController < ActionController::Base
|
||||
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
|
||||
|
||||
|
||||
def current_user = Current.user
|
||||
|
||||
# First run: no users yet → create the initial admin.
|
||||
# Viewer mode: never with real accounts, and nothing can be changed.
|
||||
def viewer_guard
|
||||
return unless Viewer.enabled?
|
||||
return render(plain: Viewer::RealAccounts.new.message, status: :service_unavailable) if Viewer.real_accounts?
|
||||
Viewer.user
|
||||
return if request.get? || request.head?
|
||||
respond_to do |format|
|
||||
format.html { redirect_back fallback_location: root_path, alert: t("viewer.read_only") }
|
||||
format.any { head :forbidden }
|
||||
end
|
||||
end
|
||||
|
||||
def redirect_to_setup
|
||||
redirect_to new_setup_path if !User.exists? && !is_a?(SetupController)
|
||||
end
|
||||
|
||||
# Adding or importing an aircraft (User#can_add_aircraft?).
|
||||
def require_aircraft_adder!
|
||||
redirect_to root_path, alert: t("flash.aircraft.ask_an_administrator") unless current_user.can_add_aircraft?
|
||||
end
|
||||
|
||||
def require_admin!
|
||||
redirect_to root_path, alert: t("flash.application.admins_only") unless current_user&.admin?
|
||||
end
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class ComponentsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, except: %i[index show]
|
||||
requires_permission :manage_components, except: %i[index show]
|
||||
before_action :set_component, only: %i[show edit update destroy reset_service]
|
||||
|
||||
def index
|
||||
|
||||
@@ -1,16 +1,38 @@
|
||||
# Scopes a controller to one aircraft the current user can access and exposes
|
||||
# role helpers. Unknown and inaccessible aircraft both 404 (enumeration-safe).
|
||||
# Scopes a controller to one aircraft the current user can access, and checks
|
||||
# what their role there allows (Role, Permission). Unknown and inaccessible
|
||||
# aircraft both 404 (enumeration-safe). Administrators can do everything.
|
||||
#
|
||||
# Access matrix (mirrors the original):
|
||||
# admin – everything
|
||||
# owner – everything on their aircraft
|
||||
# pilot – view all; update hours; create squawks, notes, oil/fuel, flight logs
|
||||
# Each controller says which permission its actions need:
|
||||
#
|
||||
# requires_permission :manage_components, except: %i[index show]
|
||||
# requires_permission :report_squawks, only: %i[new create]
|
||||
# checks_permission_itself only: %i[edit update] # decided in the controller
|
||||
#
|
||||
# Looking needs no permission. A request that changes something (anything but
|
||||
# GET/HEAD) with no permission declared for its action is refused, so nothing
|
||||
# is left open by mistake; in development and tests it raises instead.
|
||||
module AircraftScoped
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
SELF_CHECKED = "(checked by the controller)".freeze
|
||||
|
||||
class MissingPermission < StandardError; end
|
||||
|
||||
included do
|
||||
class_attribute :permission_rules, instance_accessor: false, default: []
|
||||
before_action :set_aircraft
|
||||
helper_method :current_role, :owner?, :can_write?
|
||||
before_action :authorize_permission!
|
||||
helper_method :current_role, :can?, :owner?
|
||||
end
|
||||
|
||||
class_methods do
|
||||
def requires_permission(permission, only: nil, except: nil)
|
||||
self.permission_rules += [ [ permission.to_s, only && Array(only).map(&:to_s), except && Array(except).map(&:to_s) ] ]
|
||||
end
|
||||
|
||||
def checks_permission_itself(only:)
|
||||
requires_permission(SELF_CHECKED, only: only)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
@@ -21,18 +43,35 @@ module AircraftScoped
|
||||
@aircraft = current_user.accessible_aircraft.find(aircraft_param)
|
||||
end
|
||||
|
||||
# Their Role here (nil for an administrator without one).
|
||||
def current_role
|
||||
@current_role ||= current_user.role_for(@aircraft)
|
||||
return @current_role if defined?(@current_role)
|
||||
@current_role = current_user.role_for(@aircraft)
|
||||
end
|
||||
|
||||
# Owner-level write access (admins included).
|
||||
def owner? = current_role.in?(%w[admin owner])
|
||||
alias_method :can_write?, :owner?
|
||||
# Nothing in viewer mode (a read-only copy, see Viewer).
|
||||
def can?(permission) = !Viewer.enabled? && (current_user.admin? || current_role&.can?(permission) || false)
|
||||
|
||||
def require_owner!
|
||||
return if owner?
|
||||
redirect_back fallback_location: aircraft_path(@aircraft),
|
||||
alert: t("flash.common.only_owners_can_do")
|
||||
# The Owner role (or an administrator): everything.
|
||||
def owner? = !Viewer.enabled? && (current_user.admin? || current_role&.owner? || false)
|
||||
|
||||
def authorize_permission!
|
||||
rules = self.class.permission_rules.select do |_, only, except|
|
||||
(only.nil? || only.include?(action_name)) && (except.nil? || except.exclude?(action_name))
|
||||
end
|
||||
if rules.empty?
|
||||
return if request.get? || request.head?
|
||||
raise MissingPermission, "#{self.class.name}##{action_name} changes data without declaring a permission" if Rails.env.local?
|
||||
return permission_denied
|
||||
end
|
||||
permission_denied unless rules.all? { |permission, *| permission == SELF_CHECKED || can?(permission) }
|
||||
end
|
||||
|
||||
def permission_denied
|
||||
respond_to do |format|
|
||||
format.html { redirect_back fallback_location: aircraft_path(@aircraft), alert: t("flash.common.not_allowed") }
|
||||
format.any { head :forbidden }
|
||||
end
|
||||
end
|
||||
|
||||
# Returns id only if it belongs to the given (aircraft-scoped) relation; else nil.
|
||||
|
||||
@@ -21,7 +21,12 @@ module Authentication
|
||||
end
|
||||
|
||||
def require_authentication
|
||||
resume_session || request_authentication
|
||||
resume_session || start_viewer_session || request_authentication
|
||||
end
|
||||
|
||||
# Viewer mode: everyone is its built-in account, without signing in.
|
||||
def start_viewer_session
|
||||
start_new_session_for(Viewer.user) if Viewer.enabled? && !Viewer.real_accounts?
|
||||
end
|
||||
|
||||
def resume_session
|
||||
|
||||
@@ -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
|
||||
@@ -1,6 +1,7 @@
|
||||
class ConsumableRecordsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, only: %i[edit update destroy]
|
||||
requires_permission :record_consumables, only: %i[new create]
|
||||
requires_permission :manage_consumables, only: %i[edit update destroy]
|
||||
before_action :set_record, only: %i[edit update destroy]
|
||||
|
||||
RECORDS_PER_PAGE = 50
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class DocumentCollectionsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_documents
|
||||
before_action :set_collection, only: %i[edit update destroy]
|
||||
|
||||
def new
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class DocumentsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, except: %i[index show]
|
||||
requires_permission :manage_documents, except: %i[index show]
|
||||
before_action :set_document, only: %i[show edit update destroy]
|
||||
|
||||
def index
|
||||
@@ -14,6 +14,7 @@ class DocumentsController < ApplicationController
|
||||
|
||||
def new
|
||||
@document = @aircraft.documents.new(document_collection_id: params[:collection_id])
|
||||
@document.doc_type = params[:doc_type] if Document::TYPES.key?(params[:doc_type])
|
||||
end
|
||||
|
||||
def create
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
# who they are again (password, or single sign-on just now), and confirms.
|
||||
class EntrySignaturesController < ApplicationController
|
||||
include AircraftScoped
|
||||
requires_permission :sign_logbook
|
||||
include EntrySigning
|
||||
before_action :set_entry
|
||||
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
class EventsController < ApplicationController
|
||||
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
|
||||
@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
|
||||
@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
|
||||
@@ -2,7 +2,7 @@
|
||||
class FlightImportsController < ApplicationController
|
||||
include AircraftScoped
|
||||
include StoredUpload
|
||||
before_action :require_owner!
|
||||
requires_permission :import_flights
|
||||
|
||||
def new; end
|
||||
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
class FlightLogsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, only: :destroy
|
||||
before_action :set_flight_log, only: %i[show engine_data_series attach_engine_data remove_engine_data]
|
||||
requires_permission :log_flights, only: %i[new create]
|
||||
requires_permission :delete_flights, only: :destroy
|
||||
checks_permission_itself only: %i[edit update attach_engine_data remove_engine_data]
|
||||
before_action :set_flight_log, only: %i[show edit update engine_data_series attach_engine_data remove_engine_data]
|
||||
before_action :require_flight_editor!, only: %i[edit update]
|
||||
helper_method :can_edit_flight?
|
||||
before_action :require_engine_data_access!, only: %i[attach_engine_data remove_engine_data]
|
||||
helper_method :manage_engine_data?
|
||||
|
||||
@@ -49,7 +53,13 @@ class FlightLogsController < ApplicationController
|
||||
def new
|
||||
# Aircraft almost always depart from where they last landed.
|
||||
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,
|
||||
departure_location: last&.destination_location)
|
||||
end
|
||||
@@ -62,7 +72,12 @@ class FlightLogsController < ApplicationController
|
||||
@flight_log = @aircraft.flight_logs.new(flight_log_params)
|
||||
if @flight_log.valid?
|
||||
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
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
@@ -88,6 +103,22 @@ class FlightLogsController < ApplicationController
|
||||
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: t("flash.flight_logs.engine_data_removed")
|
||||
end
|
||||
|
||||
def edit
|
||||
@meters_editable = @flight_log.meters_editable?
|
||||
end
|
||||
|
||||
# A correction. The readings only change on the latest flight (see
|
||||
# FlightLog#meters_editable?); on earlier ones they're left as they are.
|
||||
def update
|
||||
@meters_editable = @flight_log.meters_editable?
|
||||
attributes = flight_log_params.except(:client_key)
|
||||
attributes = attributes.except(*FlightLog::METERS) unless @meters_editable
|
||||
HoursService.new(@aircraft).update_flight!(@flight_log, attributes)
|
||||
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: t("flash.flight_logs.flight_corrected")
|
||||
rescue ActiveRecord::RecordInvalid
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
# Deleting a flight does not roll back hours; correct those with an hours update.
|
||||
def destroy
|
||||
@aircraft.flight_logs.find(params[:id]).destroy!
|
||||
@@ -97,14 +128,22 @@ class FlightLogsController < ApplicationController
|
||||
|
||||
private
|
||||
|
||||
# Any flight with "correct any flight"; the ones they logged with "correct own flights".
|
||||
def can_edit_flight?(flight)
|
||||
can?(:edit_any_flight) || (can?(:edit_own_flights) && flight.user_id.present? && flight.user_id == current_user.id)
|
||||
end
|
||||
|
||||
def require_flight_editor!
|
||||
return if can_edit_flight?(@flight_log)
|
||||
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), alert: t("flash.flight_logs.only_owners_or_the")
|
||||
end
|
||||
|
||||
def set_flight_log
|
||||
@flight_log = @aircraft.flight_logs.find(params[:id])
|
||||
end
|
||||
|
||||
# Owners, or the pilot who logged the flight.
|
||||
def manage_engine_data?
|
||||
owner? || (@flight_log.user_id.present? && @flight_log.user_id == current_user.id)
|
||||
end
|
||||
def manage_engine_data? = can_edit_flight?(@flight_log)
|
||||
|
||||
def require_engine_data_access!
|
||||
return if manage_engine_data?
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class InspectionRecordsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_inspections
|
||||
before_action :set_record, only: %i[edit update destroy]
|
||||
|
||||
def new
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
class InspectionTypesController < ApplicationController
|
||||
include AircraftScoped
|
||||
include Applicability
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_inspections
|
||||
before_action :set_type, only: %i[edit update destroy]
|
||||
|
||||
def new
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# The invited signer's side: sign in (or create an account for the invited
|
||||
# address), add a certificate if needed, review the entry and sign it. The
|
||||
# invitation gives access to that one entry only.
|
||||
# The invited signer's side: sign in (or, from an Owner's invitation, create an
|
||||
# account for the invited address: SigningInvitation#creates_account?), add a
|
||||
# certificate if needed, review the entry and sign it. The invitation gives
|
||||
# access to that one entry only.
|
||||
class InvitedSigningsController < ApplicationController
|
||||
include EntrySigning
|
||||
allow_unauthenticated_access only: %i[show account]
|
||||
@@ -12,6 +13,7 @@ class InvitedSigningsController < ApplicationController
|
||||
@aircraft = @entry.aircraft
|
||||
unless authenticated?
|
||||
session[:return_to_after_authenticating] = request.url
|
||||
session[:signing_token] = params[:token] # for an account made by signing in with SSO
|
||||
return render(:welcome)
|
||||
end
|
||||
return render(:wrong_account) unless current_user.email_address == @invitation.email
|
||||
@@ -20,10 +22,10 @@ class InvitedSigningsController < ApplicationController
|
||||
render :new
|
||||
end
|
||||
|
||||
# Creating an account for the invited email address.
|
||||
# Creating an account for the invited email address (an Owner's invitation).
|
||||
def account
|
||||
return redirect_to(invited_signing_path(params[:token])) if authenticated?
|
||||
if User.exists?(email_address: @invitation.email) || !Sso.password_login?
|
||||
if User.exists?(email_address: @invitation.email) || !Sso.password_login? || !@invitation.creates_account?
|
||||
return redirect_to invited_signing_path(params[:token]), alert: t("flash.invited_signings.sign_in_to_continue")
|
||||
end
|
||||
user = User.new(params.permit(:name, :password, :password_confirmation).merge(email_address: @invitation.email))
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# Opening an invitation link (AccessInvitation): see what it gives, then sign
|
||||
# in and accept. Only an administrator's invitation can make a new account
|
||||
# (with a password here, or by signing in with SSO: SsoController); others
|
||||
# need an existing one. An invitation for one email address only works for
|
||||
# that address. Any invalid link (unknown, expired, used up, revoked) gets
|
||||
# one answer.
|
||||
class JoinsController < ApplicationController
|
||||
allow_unauthenticated_access only: %i[show account]
|
||||
before_action :set_invitation
|
||||
rate_limit to: 10, within: 15.minutes, only: %i[account accept],
|
||||
with: -> { redirect_to join_path(params[:token]), alert: t("flash.joins.try_again_later") }
|
||||
|
||||
def show
|
||||
unless current_user
|
||||
session[:return_to_after_authenticating] = request.url
|
||||
session[:join_token] = params[:token] # for an account made by signing in with SSO
|
||||
return render(:welcome)
|
||||
end
|
||||
return redirect_to(root_path, notice: t("flash.joins.already_accepted")) if @invitation.redeemed_by?(current_user)
|
||||
return render(:wrong_account) unless @invitation.for?(current_user)
|
||||
render :accept
|
||||
end
|
||||
|
||||
# A new account, then the invitation accepted with it.
|
||||
def account
|
||||
return redirect_to(join_path(params[:token])) if current_user
|
||||
unless Sso.password_login? && @invitation.creates_accounts?
|
||||
return redirect_to(join_path(params[:token]), alert: t("flash.joins.sign_in_to_continue"))
|
||||
end
|
||||
email = @invitation.email || params[:email_address].to_s.strip.downcase
|
||||
if User.exists?(email_address: email)
|
||||
return redirect_to join_path(params[:token]), alert: t("flash.joins.account_exists")
|
||||
end
|
||||
user = User.new(params.permit(:name, :password, :password_confirmation).merge(email_address: email))
|
||||
results = nil
|
||||
User.transaction do
|
||||
raise ActiveRecord::Rollback unless user.save
|
||||
results = @invitation.redeem!(user)
|
||||
end
|
||||
if results
|
||||
reset_session
|
||||
start_new_session_for user
|
||||
redirect_to root_path, notice: [ t("flash.joins.welcome"), AccessInvitation.describe(results) ].join(" ").strip
|
||||
else
|
||||
@account_errors = user.errors.full_messages
|
||||
render :welcome, status: :unprocessable_entity
|
||||
end
|
||||
rescue ActiveRecord::RecordInvalid
|
||||
render :invalid, layout: "public", status: :not_found
|
||||
end
|
||||
|
||||
def accept
|
||||
return redirect_to(root_path, notice: t("flash.joins.already_accepted")) if @invitation.redeemed_by?(current_user)
|
||||
return render(:wrong_account) unless @invitation.for?(current_user)
|
||||
redirect_to root_path, notice: [ t("flash.joins.accepted"), AccessInvitation.describe(@invitation.redeem!(current_user)) ].join(" ").strip
|
||||
rescue ActiveRecord::RecordInvalid
|
||||
render :invalid, layout: "public", status: :not_found
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_invitation
|
||||
@invitation = AccessInvitation.find_by_token(params[:token])
|
||||
render :invalid, layout: "public", status: :not_found unless @invitation&.usable?
|
||||
end
|
||||
|
||||
def current_user = Current.user || (resume_session && Current.user)
|
||||
end
|
||||
@@ -2,7 +2,7 @@
|
||||
# the loading calculator.
|
||||
class LoadingSetupsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_weight_balance
|
||||
|
||||
def edit
|
||||
@setup = @aircraft.loading_setup
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class LogbookEntriesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, except: %i[index show]
|
||||
requires_permission :write_logbook, except: %i[index show]
|
||||
before_action :set_entry, only: %i[show edit update destroy verify]
|
||||
before_action :require_unsigned, only: %i[edit update destroy]
|
||||
|
||||
@@ -18,7 +18,7 @@ class LogbookEntriesController < ApplicationController
|
||||
# Someone has checked a transcribed entry against the scan.
|
||||
def verify
|
||||
@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
|
||||
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")
|
||||
@@ -36,7 +36,7 @@ class LogbookEntriesController < ApplicationController
|
||||
@entry.supersedes = correctable(params.dig(:logbook_entry, :supersedes_id))
|
||||
@entry.assign_parts(parts_params, @aircraft)
|
||||
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_inspections
|
||||
redirect_to aircraft_logbook_entry_path(@aircraft, @entry),
|
||||
@@ -52,7 +52,7 @@ class LogbookEntriesController < ApplicationController
|
||||
@entry.assign_attributes(entry_params)
|
||||
@entry.assign_parts(parts_params, @aircraft)
|
||||
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")
|
||||
else
|
||||
render :edit, status: :unprocessable_entity
|
||||
@@ -61,7 +61,7 @@ class LogbookEntriesController < ApplicationController
|
||||
|
||||
def 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")
|
||||
end
|
||||
|
||||
@@ -98,8 +98,8 @@ class LogbookEntriesController < ApplicationController
|
||||
next unless p["include"] == "1" && %w[serviced replaced].include?(p["service"])
|
||||
part = @entry.parts.find { _1.component_id == id.to_i } or next
|
||||
component = part.component
|
||||
component.service_from_entry!(date: @entry.date, 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))
|
||||
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: l(@entry.date, format: :app)))
|
||||
end
|
||||
end
|
||||
|
||||
@@ -108,9 +108,9 @@ class LogbookEntriesController < ApplicationController
|
||||
def record_inspections
|
||||
ids = Array(params.dig(:logbook_entry, :inspection_type_ids)).compact_blank
|
||||
@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)
|
||||
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
|
||||
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
# entries in the background (LogbookTranscriptionJob).
|
||||
class LogbookImportsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :import_records
|
||||
|
||||
def new
|
||||
@collections = @aircraft.document_collections.ordered
|
||||
end
|
||||
|
||||
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?
|
||||
|
||||
# Page order follows the file names ("page-002" before "page-010").
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class MajorRecordsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, except: %i[index show]
|
||||
requires_permission :manage_major_records, except: %i[index show]
|
||||
before_action :set_record, only: %i[show edit update destroy]
|
||||
|
||||
def index
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
class NotesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, only: %i[edit update destroy]
|
||||
requires_permission :write_notes, only: %i[new create preview]
|
||||
requires_permission :manage_notes, only: %i[edit update destroy]
|
||||
before_action :set_note, only: %i[edit update destroy]
|
||||
|
||||
def index
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
class OilAnalysesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, only: %i[edit update destroy]
|
||||
requires_permission :record_oil_analyses, only: %i[new create import]
|
||||
requires_permission :manage_oil_analyses, only: %i[edit update destroy]
|
||||
before_action :set_analysis, only: %i[show edit update destroy]
|
||||
|
||||
COMPARE_SAMPLES = 6 # columns in the trend table, like the lab report's history
|
||||
@@ -24,7 +25,7 @@ class OilAnalysesController < ApplicationController
|
||||
def create
|
||||
@analysis = @aircraft.oil_analyses.new(analysis_params)
|
||||
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")
|
||||
else
|
||||
render :new, status: :unprocessable_entity
|
||||
@@ -35,7 +36,7 @@ class OilAnalysesController < ApplicationController
|
||||
# earlier samples, so samples already on file are skipped rather than duplicated.
|
||||
def import
|
||||
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)
|
||||
file.rewind
|
||||
@@ -69,7 +70,7 @@ class OilAnalysesController < ApplicationController
|
||||
|
||||
def update
|
||||
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")
|
||||
else
|
||||
render :edit, status: :unprocessable_entity
|
||||
@@ -78,7 +79,7 @@ class OilAnalysesController < ApplicationController
|
||||
|
||||
def 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")
|
||||
end
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ class ProfilesController < ApplicationController
|
||||
# left open somewhere can't be turned into a takeover of the account.
|
||||
def update
|
||||
@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?
|
||||
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)
|
||||
|
||||
@@ -6,7 +6,13 @@ class PushSubscriptionsController < ApplicationController
|
||||
record = PushSubscription.find_or_initialize_by(endpoint: sub[:endpoint].to_s)
|
||||
record.assign_attributes(user: current_user, p256dh: sub.dig(:keys, :p256dh), auth: sub.dig(:keys, :auth),
|
||||
user_agent: request.user_agent.to_s.first(250))
|
||||
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
|
||||
|
||||
def destroy
|
||||
@@ -14,9 +20,35 @@ class PushSubscriptionsController < ApplicationController
|
||||
head :no_content
|
||||
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
|
||||
PushNotifier.notify(current_user, :test, path: edit_profile_path, tag: "test")
|
||||
head :accepted
|
||||
message = PushNotificationJob.message("test", edit_profile_path, "test")
|
||||
devices = current_user.push_subscriptions.order(:created_at).map do |sub|
|
||||
{ device: device_name(sub.user_agent), error: PushNotificationJob.deliver(sub, message) }
|
||||
end
|
||||
render json: { devices: devices }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# "Chrome on Android" from the browser's description of itself.
|
||||
def device_name(agent)
|
||||
browser = case agent
|
||||
when /Edg\//, /EdgA\// then "Edge"
|
||||
when /SamsungBrowser/ then "Samsung Internet"
|
||||
when /Firefox|FxiOS/ then "Firefox"
|
||||
when /Chrome|CriOS/ then "Chrome"
|
||||
when /Safari/ then "Safari"
|
||||
end
|
||||
system = case agent
|
||||
when /Android/ then "Android"
|
||||
when /iPhone/ then "iPhone"
|
||||
when /iPad/ then "iPad"
|
||||
when /Macintosh/ then "Mac"
|
||||
when /Windows/ then "Windows"
|
||||
when /Linux/ then "Linux"
|
||||
end
|
||||
[ browser, system ].compact.join(" · ").presence || t("flash.push_subscriptions.unknown_device")
|
||||
end
|
||||
end
|
||||
@@ -1,7 +1,7 @@
|
||||
# Every change to the aircraft's maintenance records (AC 120-78B 3.2.2).
|
||||
class RecordVersionsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, only: :restore
|
||||
requires_permission :restore_history, only: :restore
|
||||
|
||||
SHARED = { "AirworthinessDirective" => AirworthinessDirective, "InspectionType" => InspectionType }.freeze
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Download every record of an aircraft in one ZIP (owners).
|
||||
class RecordsPackagesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :export_data
|
||||
|
||||
def show
|
||||
package = RecordsPackage.new(@aircraft, source: request.host)
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
class SetupController < ApplicationController
|
||||
allow_unauthenticated_access
|
||||
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"
|
||||
|
||||
def new
|
||||
@user = User.new
|
||||
SetupCode.announce
|
||||
end
|
||||
|
||||
def create
|
||||
@user = User.new(params.require(:user).permit(:name, :email_address, :password, :password_confirmation))
|
||||
@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
|
||||
SetupCode.clear
|
||||
start_new_session_for @user
|
||||
redirect_to root_path, notice: t("flash.setup.welcome_you_re_the")
|
||||
else
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class ShareTokensController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_sharing
|
||||
|
||||
def create
|
||||
token = @aircraft.share_tokens.new(params.require(:share_token).permit(:label, :privilege, :expires_at))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# An owner asks someone outside the aircraft (a mechanic) to sign an entry.
|
||||
class SigningInvitationsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :write_logbook
|
||||
before_action :set_entry
|
||||
rate_limit to: 10, within: 1.hour, only: :create, with: -> { redirect_back fallback_location: root_path, alert: t("flash.signing_invitations.too_many_invitations_try") }
|
||||
|
||||
@@ -21,8 +21,10 @@ class SigningInvitationsController < ApplicationController
|
||||
PushNotifier.notify(invitee, :signing_request, path: invited_signing_path(@invitation.token), tag: "sign-#{@invitation.id}",
|
||||
tail: @aircraft.tail_number, name: current_user.display_name)
|
||||
end
|
||||
log_event("logbook", t("flash.signing_invitations.signature_requested_from_entry", email: @invitation.email, date: @entry.date))
|
||||
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)
|
||||
log_event("logbook", t("flash.signing_invitations.signature_requested_from_entry", email: @invitation.email, date: l(@entry.date, format: :app)))
|
||||
notice = t("flash.signing_invitations.invitation_sent_to_the", email: @invitation.email, days: SigningInvitation::VALID_FOR.in_days.to_i)
|
||||
notice = "#{notice} #{t('flash.signing_invitations.no_account_yet')}" unless invitee || @invitation.creates_account?
|
||||
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: notice
|
||||
else
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
@@ -2,7 +2,9 @@ class SquawksController < ApplicationController
|
||||
include AircraftScoped
|
||||
# Pilots may create squawks and defer inoperative items (91.213(d) lets the
|
||||
# pilot decide); editing and resolving need an owner.
|
||||
before_action :require_owner!, except: %i[index new create deferral defer]
|
||||
requires_permission :report_squawks, only: %i[new create]
|
||||
requires_permission :defer_squawks, only: %i[deferral defer]
|
||||
requires_permission :manage_squawks, except: %i[index new create deferral defer]
|
||||
before_action :set_squawk, only: %i[edit update destroy resolution resolve reopen deferral defer undefer]
|
||||
|
||||
def index
|
||||
@@ -21,11 +23,7 @@ class SquawksController < ApplicationController
|
||||
end
|
||||
@squawk = @aircraft.squawks.new(squawk_params.merge(reported_by: current_user))
|
||||
if @squawk.save
|
||||
log_event("squawk", t("flash.squawks.squawk_reported_2", priority_label: @squawk.priority_label), notes: @squawk.issue_reported.truncate(200))
|
||||
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
|
||||
SquawkReported.call(@squawk, by: current_user)
|
||||
redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_reported")
|
||||
else
|
||||
render :new, status: :unprocessable_entity
|
||||
@@ -64,7 +62,7 @@ class SquawksController < ApplicationController
|
||||
@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)
|
||||
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
|
||||
when "existing" then @aircraft.logbook_entries.find_by(id: params[:logbook_entry_id])
|
||||
end
|
||||
|
||||
@@ -6,6 +6,11 @@
|
||||
# email is verified (or OIDC_TRUST_EMAIL is on), since some providers let
|
||||
# users edit their email. Otherwise, sign in with a password once and link
|
||||
# from the profile page.
|
||||
#
|
||||
# Someone without an account gets one only from an invitation they opened
|
||||
# first that can make one (an administrator's AccessInvitation, accepted at
|
||||
# once; an Owner's SigningInvitation, for its address), or for anyone the
|
||||
# provider lets in when OIDC_AUTO_CREATE_USERS is on.
|
||||
class SsoController < ApplicationController
|
||||
allow_unauthenticated_access only: %i[callback failure]
|
||||
before_action :require_sso
|
||||
@@ -29,6 +34,7 @@ class SsoController < ApplicationController
|
||||
return_to = session[:return_to_after_authenticating]
|
||||
reset_session # fresh session id after signing in
|
||||
start_new_session_for user
|
||||
return redirect_to(root_url, notice: [ t("flash.joins.welcome"), AccessInvitation.describe(@joined) ].join(" ").strip) if @joined
|
||||
redirect_to return_to || root_url
|
||||
end
|
||||
|
||||
@@ -81,15 +87,34 @@ class SsoController < ApplicationController
|
||||
end
|
||||
|
||||
def create_user(auth)
|
||||
return unless Sso.auto_create_users?
|
||||
email = auth.info&.email.to_s.strip.downcase
|
||||
return if email.blank? || User.exists?(email_address: email)
|
||||
# The random password is never shown; a password reset can set a real one.
|
||||
User.create!(email_address: email, name: auth.info&.name.presence, sso_uid: auth.uid, password: SecureRandom.base58(40))
|
||||
invitation = invitation_making_account(email)
|
||||
return unless invitation || signing_invitation_making_account?(email) || Sso.auto_create_users?
|
||||
User.transaction do
|
||||
# The random password is never shown; a password reset can set a real one.
|
||||
user = User.create!(email_address: email, name: auth.info&.name.presence, sso_uid: auth.uid, password: SecureRandom.base58(40))
|
||||
@joined = invitation&.redeem!(user)
|
||||
user
|
||||
end
|
||||
rescue ActiveRecord::RecordInvalid
|
||||
nil
|
||||
end
|
||||
|
||||
# A signing invitation opened in this browser before signing in, from an
|
||||
# Owner, for this email address.
|
||||
def signing_invitation_making_account?(email)
|
||||
invitation = SigningInvitation.find_usable(session[:signing_token])
|
||||
invitation.present? && invitation.creates_account? && invitation.email == email
|
||||
end
|
||||
|
||||
# The invitation opened in this browser before signing in, when it can
|
||||
# make an account (an administrator's) for this email address.
|
||||
def invitation_making_account(email)
|
||||
invitation = AccessInvitation.find_by_token(session[:join_token])
|
||||
invitation if invitation&.usable? && invitation.creates_accounts? && invitation.for_email?(email)
|
||||
end
|
||||
|
||||
def email_verified?(auth)
|
||||
[ true, "true" ].include?(raw_info(auth)["email_verified"])
|
||||
end
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class StandardInspectionsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!
|
||||
requires_permission :manage_inspections
|
||||
|
||||
def new; end
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# keep the records and the loading setup).
|
||||
class WeightBalanceRecordsController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, except: :index
|
||||
requires_permission :manage_weight_balance, except: :index
|
||||
before_action :set_record, only: %i[edit update destroy]
|
||||
|
||||
def index
|
||||
@@ -30,7 +30,7 @@ class WeightBalanceRecordsController < ApplicationController
|
||||
|
||||
def update
|
||||
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")
|
||||
else
|
||||
render :edit, status: :unprocessable_entity
|
||||
@@ -39,7 +39,7 @@ class WeightBalanceRecordsController < ApplicationController
|
||||
|
||||
def 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")
|
||||
end
|
||||
|
||||
|
||||
@@ -3,12 +3,15 @@ module AircraftHelper
|
||||
|
||||
# What the app saves ahead of time for use without signal (see
|
||||
# offline_prep_controller.js): for each of your aircraft, the Overview, W&B,
|
||||
# Log Flight and Report Squawk pages, and its photo.
|
||||
# Log Flight and Report Squawk pages (when their role allows them), and its
|
||||
# photo (at both page sizes).
|
||||
def offline_pages
|
||||
current_user.accessible_aircraft.ordered.limit(OFFLINE_AIRCRAFT).map do |a|
|
||||
role = current_user.role_for(a)
|
||||
can = ->(permission) { current_user.admin? || role&.can?(permission) }
|
||||
{ tail: a.tail_number, pages: [ aircraft_path(a), aircraft_weight_balance_records_path(a) ],
|
||||
flight: new_aircraft_flight_log_path(a), squawk: new_aircraft_squawk_path(a),
|
||||
picture: (url_for(a.picture) if a.picture.attached?) }.compact
|
||||
flight: (new_aircraft_flight_log_path(a) if can.(:log_flights)), squawk: (new_aircraft_squawk_path(a) if can.(:report_squawks)),
|
||||
pictures: (%i[thumb card].map { url_for(a.picture_for(_1)) }.uniq if a.picture_shown?) }.compact
|
||||
end
|
||||
end
|
||||
# Tabs on the aircraft pages: [label, path, controller names that highlight it, owner_only]
|
||||
@@ -30,6 +33,17 @@ module AircraftHelper
|
||||
]
|
||||
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)
|
||||
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
|
||||
@@ -40,6 +54,6 @@ module AircraftHelper
|
||||
end
|
||||
|
||||
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
|
||||
@@ -7,4 +7,15 @@ module HelpHelper
|
||||
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
|
||||
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
|
||||
@@ -9,7 +9,7 @@ module MarkdownHelper
|
||||
extension: { strikethrough: true, tagfilter: true, table: true, autolink: true, tasklist: true, header_ids: nil, footnotes: false }
|
||||
}.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)
|
||||
return "".html_safe if text.blank?
|
||||
|
||||
@@ -42,6 +42,15 @@ window.addEventListener("beforeinstallprompt", (event) => {
|
||||
document.dispatchEvent(new CustomEvent("install:available"))
|
||||
})
|
||||
|
||||
// The device's time zone, so times show in it and "today" is the local date
|
||||
// (unless a zone is chosen in Profile).
|
||||
try {
|
||||
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone
|
||||
if (zone && !document.cookie.split("; ").includes(`tz=${encodeURIComponent(zone)}`)) {
|
||||
document.cookie = `tz=${encodeURIComponent(zone)}; path=/; max-age=31536000; samesite=lax`
|
||||
}
|
||||
} catch (_) { /* no Intl */ }
|
||||
|
||||
// Label each table cell with its column header, so phone CSS can show rows as
|
||||
// cards ("Status: In Service"). Skips tables marked .table-keep.
|
||||
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
|
||||
const { text, entryType, logType, certificate } = option.dataset
|
||||
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) {
|
||||
this.logTypeTarget.value = logType
|
||||
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 { t } from "i18n"
|
||||
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
|
||||
// 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 {
|
||||
static targets = [ "key", "notice" ]
|
||||
static values = { kind: { type: String, default: "flight" }, tail: String }
|
||||
@@ -23,14 +31,21 @@ export default class extends Controller {
|
||||
|
||||
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) {
|
||||
if (navigator.onLine) return
|
||||
if (navigator.onLine && serverReachable()) return
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
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).
|
||||
remember() { this.pending = formFields(this.element) }
|
||||
|
||||
|
||||
@@ -8,6 +8,9 @@ import { currentUser } from "controllers/offline_queue"
|
||||
// your aircraft change. Signing out clears it.
|
||||
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 {
|
||||
static values = { aircraft: Array }
|
||||
|
||||
@@ -26,17 +29,26 @@ export default class extends Controller {
|
||||
const forms = {}
|
||||
const paths = [ "/" ]
|
||||
for (const a of this.aircraftValue) {
|
||||
paths.push(...a.pages, a.flight, a.squawk)
|
||||
forms[a.flight] = { tail: a.tail, kind: "flight" }
|
||||
forms[a.squawk] = { tail: a.tail, kind: "squawk" }
|
||||
paths.push(...a.pages)
|
||||
if (a.flight) { paths.push(a.flight); forms[a.flight] = { tail: a.tail, kind: "flight" } }
|
||||
if (a.squawk) { paths.push(a.squawk); forms[a.squawk] = { tail: a.tail, kind: "squawk" } }
|
||||
}
|
||||
for (const path of paths) {
|
||||
if (!navigator.onLine) return
|
||||
// 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 (_) { return }
|
||||
}
|
||||
await this.savePictures(this.aircraftValue.map((a) => a.picture).filter(Boolean))
|
||||
const pictures = this.aircraftValue.flatMap((a) => a.pictures || [])
|
||||
const total = paths.length + 1
|
||||
try {
|
||||
for (const [ index, path ] of paths.entries()) {
|
||||
progress(index, total)
|
||||
if (!navigator.onLine) return
|
||||
// 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 {
|
||||
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() }))
|
||||
@@ -58,10 +70,11 @@ export default class extends Controller {
|
||||
}
|
||||
|
||||
// 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) {
|
||||
try {
|
||||
const signed = new URL(url, location.origin).pathname.match(/\/blobs\/redirect\/([^/]+?)--/)[1]
|
||||
return `${location.origin}/offline-image/${JSON.parse(atob(decodeURIComponent(signed)))._rails.data}`
|
||||
const [ , signed, size ] = new URL(url, location.origin).pathname.match(/\/(?:blobs|representations)\/redirect\/([^/]+?)--[^/]+\/(?:([^/]+)\/)?/)
|
||||
const id = JSON.parse(atob(decodeURIComponent(signed)))._rails.data
|
||||
return `${location.origin}/offline-image/${id}${size ? `/${size}` : ""}`
|
||||
} catch (_) { return null }
|
||||
}
|
||||
@@ -1,10 +1,20 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { t } from "i18n"
|
||||
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
|
||||
// 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 {
|
||||
static targets = [ "banner" ]
|
||||
|
||||
@@ -12,30 +22,37 @@ export default class extends Controller {
|
||||
this.sync = this.sync.bind(this)
|
||||
window.addEventListener("online", this.sync)
|
||||
document.addEventListener("offline-queue:changed", this.sync)
|
||||
document.addEventListener("sam:back-online", this.sync)
|
||||
this.sync()
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
window.removeEventListener("online", this.sync)
|
||||
document.removeEventListener("offline-queue:changed", this.sync)
|
||||
document.removeEventListener("sam:back-online", this.sync)
|
||||
}
|
||||
|
||||
async sync() {
|
||||
let items
|
||||
try { items = await queue.mine() } catch (_) { return }
|
||||
if (!items.length) { this.badge(0); return this.show("") }
|
||||
if (!navigator.onLine || this.running) return this.status(items)
|
||||
if (!items.length) { this.badge(0); report("sam:waiting", { count: 0 }); return this.show("") }
|
||||
if (!navigator.onLine || !serverReachable() || this.running) return this.status(items)
|
||||
this.running = true
|
||||
const sent = []
|
||||
const sending = items.filter((i) => !i.error)
|
||||
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)
|
||||
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 === "offline") break
|
||||
else if (result === "offline") { report("sam:unreachable"); break }
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -46,7 +63,9 @@ export default class extends Controller {
|
||||
if (token) body.append("authenticity_token", token)
|
||||
let response
|
||||
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" }
|
||||
if ([ 502, 503, 504 ].includes(response.status)) return "offline"
|
||||
if (response.url.includes("/session/new")) return "signin"
|
||||
@@ -68,6 +87,7 @@ export default class extends Controller {
|
||||
}
|
||||
this.show(parts.join(" "), failed)
|
||||
this.badge(items.length)
|
||||
report("sam:waiting", { count: waiting.length })
|
||||
}
|
||||
|
||||
// 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
|
||||
const subscription = await this.registration.pushManager.getSubscription()
|
||||
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() {
|
||||
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 {
|
||||
const subscription = await this.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: this.keyBytes() })
|
||||
const response = await this.request("POST", this.urlValue, { subscription: subscription.toJSON() })
|
||||
if (!response.ok) throw new Error(response.status)
|
||||
this.show(t("push.on"), true)
|
||||
} catch (_) {
|
||||
this.show(t("push.failed"), false)
|
||||
if (response.ok) return null
|
||||
return (await response.json().catch(() => ({}))).error || `HTTP ${response.status}`
|
||||
} catch (e) {
|
||||
return e.message
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,9 +54,18 @@ export default class extends Controller {
|
||||
this.show(t("push.off"), false)
|
||||
}
|
||||
|
||||
// Sends one to each of your devices and lists which push services took it.
|
||||
async sendTest() {
|
||||
await this.request("POST", this.testUrlValue, {})
|
||||
this.statusTarget.textContent = t("push.test_sent")
|
||||
this.statusTarget.textContent = t("push.test_sending")
|
||||
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.
|
||||
|
||||
@@ -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")
|
||||
unless date
|
||||
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))
|
||||
end
|
||||
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"]))
|
||||
)
|
||||
@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
|
||||
|
||||
def note_skipped(result, label)
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
# Daily: tells owners about items that have newly become overdue or limit
|
||||
# Daily: tells those who get its reminders (Role "gets reminders") about items that have newly become overdue or limit
|
||||
# the aircraft (grounded, VFR only…). Each is sent once; one that's fixed and
|
||||
# becomes overdue again is sent again.
|
||||
class OverdueNotificationJob < ApplicationJob
|
||||
queue_as :default
|
||||
|
||||
def perform
|
||||
Aircraft.includes(roles: :user).find_each do |aircraft|
|
||||
Aircraft.includes(roles: %i[user role]).find_each do |aircraft|
|
||||
issues = aircraft.airworthiness.issues.select { _1.severity.in?([ Airworthiness::RED, Airworthiness::LIMITED ]) }
|
||||
keys = issues.map { |i| "#{i.category}:#{i.item.class.name}:#{i.item.id}" }
|
||||
fresh = issues.reject.with_index { |_, n| aircraft.notified_issue_keys.include?(keys[n]) }
|
||||
owners = aircraft.roles.select { _1.role == "owner" }.map(&:user).reject(&:disabled?)
|
||||
recipients = aircraft.roles.select { _1.role.can?(:receive_reminders) }.map(&:user).reject(&:disabled?)
|
||||
if fresh.any?
|
||||
PushNotifier.notify(owners, :overdue, path: Rails.application.routes.url_helpers.aircraft_path(aircraft), tag: "overdue-#{aircraft.id}",
|
||||
PushNotifier.notify(recipients, :overdue, path: Rails.application.routes.url_helpers.aircraft_path(aircraft), tag: "overdue-#{aircraft.id}",
|
||||
tail: aircraft.tail_number, items: fresh.map(&:title).to_sentence, count: fresh.size)
|
||||
end
|
||||
aircraft.update_column(:notified_issue_keys, keys) if keys.sort != aircraft.notified_issue_keys.sort
|
||||
|
||||
@@ -4,20 +4,32 @@ class PushNotificationJob < ApplicationJob
|
||||
queue_as :default
|
||||
|
||||
def perform(user_ids, key, path, tag, vars)
|
||||
vars = vars.symbolize_keys
|
||||
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 { deliver(_1, message) }
|
||||
message = self.class.message(key, path, tag, vars)
|
||||
PushSubscription.where(user_id: user_ids).find_each { self.class.deliver(_1, message) }
|
||||
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,
|
||||
ttl: 1.day.to_i, urgency: "high",
|
||||
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
|
||||
failure(subscription, 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
|
||||
|
||||
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
|
||||
@@ -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
|
||||
@@ -1,4 +1,4 @@
|
||||
# Weekly email to aircraft owners listing what's overdue or coming due
|
||||
# Weekly email to those who get an aircraft's reminders (Role "gets reminders") listing what's overdue or coming due
|
||||
# (inspections, ADs, components, expiring documents), deferred items, new
|
||||
# ADs, and the user's own certificates that are about to expire.
|
||||
# Nothing is sent when nothing needs attention, or when email isn't set up.
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# The link of an invitation made for one email address (AccessInvitation).
|
||||
class AccessInvitationMailer < ApplicationMailer
|
||||
def invite(invitation, token)
|
||||
@invitation = invitation
|
||||
@grants = invitation.grants.includes(:aircraft, :role).sort_by { _1.aircraft.tail_number }
|
||||
@url = join_url(token)
|
||||
mail subject: t(".subject", who: invitation.created_by&.display_name || t(".an_administrator")), to: invitation.email
|
||||
end
|
||||
end
|
||||
@@ -1,8 +1,13 @@
|
||||
class ReminderMailer < ApplicationMailer
|
||||
# [[aircraft, issues, new AD alerts], …] for the aircraft the user owns
|
||||
# that need attention.
|
||||
# Aircraft where the user's role includes the permission.
|
||||
def self.aircraft_where(user, permission)
|
||||
Aircraft.where(id: AircraftRole.with_permission(permission).where(user_id: user.id).select(:aircraft_id)).ordered
|
||||
end
|
||||
|
||||
# [[aircraft, issues, new AD alerts], …] for the aircraft the user gets
|
||||
# reminders for (their role's "gets reminders") that need attention.
|
||||
def self.items_for(user)
|
||||
Aircraft.joins(:roles).where(aircraft_roles: { user_id: user.id, role: "owner" }).ordered
|
||||
aircraft_where(user, :receive_reminders)
|
||||
.map { [ _1, _1.airworthiness.issues, _1.ad_alerts.pending.to_a ] }.reject { _2.empty? && _3.empty? }
|
||||
end
|
||||
|
||||
@@ -10,10 +15,11 @@ class ReminderMailer < ApplicationMailer
|
||||
|
||||
def self.audit_due_for?(user) = user.admin? && AuditRun.due_soon?
|
||||
|
||||
# Owned aircraft whose AD baseline needs a (new) DRS import: none yet, a
|
||||
# year old, or a model never covered.
|
||||
# Aircraft they get reminders for and manage the ADs of, whose AD baseline
|
||||
# needs a (new) DRS import: none yet, a year old, or a model never covered.
|
||||
def self.drs_due_for(user)
|
||||
Aircraft.joins(:roles).where(aircraft_roles: { user_id: user.id, role: "owner" }).ordered
|
||||
aircraft_where(user, :receive_reminders)
|
||||
.where(id: AircraftRole.with_permission(:manage_ads).where(user_id: user.id).select(:aircraft_id))
|
||||
.select { DrsImport.renewal_due?(_1) || DrsImport.missing_models(_1).any? }
|
||||
end
|
||||
|
||||
@@ -25,6 +31,12 @@ class ReminderMailer < ApplicationMailer
|
||||
end
|
||||
|
||||
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
|
||||
@items = self.class.items_for(user)
|
||||
@certificates = self.class.expiring_certificates_for(user)
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
# An invitation code: a link someone opens to create an account (or accept
|
||||
# with the one they have) and get roles on aircraft. Made by administrators
|
||||
# (Admin → Invitations, any aircraft) or by whoever manages an aircraft's
|
||||
# people (its Access page, that aircraft). Limited by number of uses, an
|
||||
# expiry, and optionally to one email address; it can be revoked. Only a
|
||||
# digest of the code is kept, so the link is shown once, when it's made.
|
||||
#
|
||||
# New accounts are only ever made by an administrator or from an
|
||||
# administrator's invitation: anyone can add an aircraft and so manage its
|
||||
# people, so other invitations are for people who already have an account.
|
||||
class AccessInvitation < ApplicationRecord
|
||||
VALID_FOR = 14.days
|
||||
|
||||
belongs_to :created_by, class_name: "User", optional: true
|
||||
has_many :grants, class_name: "AccessInvitationRole", dependent: :delete_all
|
||||
has_many :redemptions, class_name: "AccessInvitationRedemption", dependent: :delete_all
|
||||
has_many :aircraft, through: :grants
|
||||
|
||||
attr_reader :token
|
||||
|
||||
normalizes :email, with: ->(email) { email.strip.downcase.presence }
|
||||
normalizes :label, :name, with: ->(text) { text.squish.presence }
|
||||
validates :label, presence: true, length: { maximum: 100 }
|
||||
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }, allow_nil: true
|
||||
validates :max_uses, numericality: { only_integer: true, greater_than: 0, less_than_or_equal_to: 1000 }, allow_nil: true
|
||||
before_validation(on: :create) do
|
||||
@token = SecureRandom.urlsafe_base64(24)
|
||||
self.token_digest = self.class.digest(@token)
|
||||
end
|
||||
|
||||
scope :recent_first, -> { order(created_at: :desc) }
|
||||
scope :usable, -> {
|
||||
where(revoked_at: nil).where("expires_at IS NULL OR expires_at > ?", Time.current).where("max_uses IS NULL OR uses_count < max_uses")
|
||||
}
|
||||
|
||||
# A new invitation by creator giving roles ([[aircraft, role], …]); its
|
||||
# link is emailed when it's for one address and email is set up.
|
||||
def self.create_for(creator, attributes, grants)
|
||||
invitation = new(attributes.merge(created_by: creator))
|
||||
grants.each { |aircraft, role| invitation.grants.build(aircraft: aircraft, role: role) }
|
||||
if invitation.save && invitation.email && MailSettings.configured?
|
||||
AccessInvitationMailer.invite(invitation, invitation.token).deliver_later
|
||||
end
|
||||
invitation
|
||||
end
|
||||
|
||||
# "N12345: Mechanic. N54321: already Owner, unchanged" (from #redeem!).
|
||||
def self.describe(results)
|
||||
results.map { |aircraft, role, message| "#{aircraft.tail_number}: #{[ role&.name, message ].compact.join(', ')}" }.join(" ")
|
||||
end
|
||||
|
||||
def self.digest(token) = OpenSSL::Digest::SHA256.hexdigest(token.to_s)
|
||||
def self.find_by_token(token) = token.present? ? find_by(token_digest: digest(token)) : nil
|
||||
|
||||
def usable? = !revoked? && !expired? && !used_up?
|
||||
# Whether someone without an account can make one with it (see above),
|
||||
# decided when it's used: its creator must still be an administrator.
|
||||
def creates_accounts? = created_by.present? && created_by.admin? && !created_by.disabled?
|
||||
def for_email?(email) = self.email.nil? || self.email == email.to_s.strip.downcase
|
||||
def revoked? = revoked_at.present?
|
||||
def expired? = expires_at.present? && expires_at <= Time.current
|
||||
def used_up? = max_uses.present? && uses_count >= max_uses
|
||||
def for?(user) = for_email?(user.email_address)
|
||||
def redeemed_by?(user) = redemptions.exists?(user: user)
|
||||
|
||||
# Gives the person the invitation's roles, as if its creator added them
|
||||
# (AircraftAccess: so it can't give more than they could, then or now).
|
||||
# A role they already have on an aircraft stays as it is. Returns
|
||||
# [[aircraft, role or nil, message or nil], …].
|
||||
def redeem!(user)
|
||||
with_lock do
|
||||
raise ActiveRecord::RecordInvalid, self unless usable? && for?(user)
|
||||
redemptions.create!(user: user)
|
||||
increment!(:uses_count)
|
||||
grants.includes(:aircraft, :role).map do |grant|
|
||||
if (existing = grant.aircraft.roles.find_by(user: user))
|
||||
[ grant.aircraft, nil, I18n.t("models.access_invitation.already_has", role: existing.role.name) ]
|
||||
elsif created_by.nil? || created_by.disabled? || !created_by.can?(:manage_people, grant.aircraft)
|
||||
[ grant.aircraft, nil, I18n.t("models.access_invitation.creator_gone") ]
|
||||
else
|
||||
error = AircraftAccess.new(grant.aircraft, actor: created_by).add(user, grant.role)
|
||||
[ grant.aircraft, (grant.role unless error), error ]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,7 @@
|
||||
# Who used an invitation, and when (once per person).
|
||||
class AccessInvitationRedemption < ApplicationRecord
|
||||
belongs_to :access_invitation
|
||||
belongs_to :user
|
||||
|
||||
validates :user_id, uniqueness: { scope: :access_invitation_id }
|
||||
end
|
||||
@@ -0,0 +1,8 @@
|
||||
# A role an invitation gives on one aircraft.
|
||||
class AccessInvitationRole < ApplicationRecord
|
||||
belongs_to :access_invitation
|
||||
belongs_to :aircraft
|
||||
belongs_to :role
|
||||
|
||||
validates :aircraft_id, uniqueness: { scope: :access_invitation_id }
|
||||
end
|
||||
@@ -20,7 +20,7 @@ class AirTrailConnection < ApplicationRecord
|
||||
|
||||
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"
|
||||
|
||||
|
||||
+20
-2
@@ -1,9 +1,15 @@
|
||||
class Aircraft < ApplicationRecord
|
||||
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 :invitation_grants, class_name: "AccessInvitationRole", dependent: :delete_all
|
||||
has_many :users, through: :roles
|
||||
has_many :notes, class_name: "AircraftNote", dependent: :destroy
|
||||
has_many :events, class_name: "AircraftEvent", dependent: :delete_all
|
||||
@@ -11,6 +17,7 @@ class Aircraft < ApplicationRecord
|
||||
has_many :components, dependent: :destroy
|
||||
has_many :squawks, dependent: :destroy
|
||||
has_many :logbook_entries, dependent: :destroy
|
||||
has_many :draft_batches, dependent: :destroy
|
||||
has_many :logbook_imports, dependent: :destroy
|
||||
has_many :document_collections, dependent: :destroy
|
||||
has_many :documents, dependent: :destroy
|
||||
@@ -77,10 +84,21 @@ class Aircraft < ApplicationRecord
|
||||
events.create!(category: category, event_name: event_name, user: user, notes: notes)
|
||||
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
|
||||
|
||||
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)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
# Someone's role on an aircraft (Role), which decides what they can do there.
|
||||
class AircraftRole < ApplicationRecord
|
||||
ROLES = LabelSet.new("aircraft_role.roles", %w[owner pilot])
|
||||
|
||||
belongs_to :aircraft
|
||||
belongs_to :user
|
||||
belongs_to :role
|
||||
|
||||
validates :role, inclusion: { in: ROLES.keys }
|
||||
validates :user_id, uniqueness: { scope: :aircraft_id, message: "already has a role on this aircraft" }
|
||||
|
||||
scope :owners, -> { where(role: "owner") }
|
||||
scope :owners, -> { joins(:role).where(roles: { key: "owner" }) }
|
||||
# Whose role includes a permission (Owner always does).
|
||||
scope :with_permission, ->(permission) {
|
||||
joins(:role).where("roles.key = 'owner' OR EXISTS (SELECT 1 FROM json_each(roles.permissions) WHERE json_each.value = ?)", permission.to_s)
|
||||
}
|
||||
|
||||
# A Role, or a built-in role's key ("owner", "pilot").
|
||||
def role=(value)
|
||||
super(value.is_a?(Role) || value.nil? ? value : Role.for_key(value))
|
||||
end
|
||||
|
||||
def owner? = role&.owner?
|
||||
end
|
||||
@@ -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
|
||||
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
|
||||
@@ -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") }
|
||||
end
|
||||
|
||||
# Its sub-components, and theirs.
|
||||
def descendant_ids
|
||||
child_components.flat_map { [ _1.id, *_1.descendant_ids ] }
|
||||
# Its sub-components, and theirs. (Stops at a loop, should one exist.)
|
||||
def descendant_ids(seen = Set[id])
|
||||
child_components.flat_map do |child|
|
||||
next [] unless seen.add?(child.id)
|
||||
[ child.id, *child.descendant_ids(seen) ]
|
||||
end
|
||||
end
|
||||
|
||||
# Its parent, the parent's parent, and so on up.
|
||||
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
|
||||
def engine? = component_type&.name.to_s.match?(/engine/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
|
||||
return unless parent_component
|
||||
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
|
||||
end
|
||||
end
|
||||
@@ -1,4 +1,7 @@
|
||||
class Current < ActiveSupport::CurrentAttributes
|
||||
attribute :session, :ip_address
|
||||
delegate :user, to: :session, allow_nil: true
|
||||
# api_token / api_user: an API request (see Api::V1::BaseController), which
|
||||
# acts as a person without a browser session.
|
||||
attribute :session, :ip_address, :api_token, :api_user
|
||||
|
||||
def user = api_user || session&.user
|
||||
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 :logbook_entry_id, uniqueness: true
|
||||
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_destroy { throw :abort unless destroyed_by_association }
|
||||
|
||||
|
||||
Loaded 100 of 327 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user