mirror of
https://github.com/rickbarrette/simple-aircraft-manager-rails.git
synced 2026-11-17 23:50:36 -05:00
Compare commits
16
Commits
v2026.11.4
...
v2026.11.6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
34879e7310 | ||
|
|
e8b0cd030e | ||
|
|
e4bc3a5b7b | ||
|
|
d9de1be562 | ||
|
|
66fa5f4423 | ||
|
|
2e8d789975 | ||
|
|
e4c27c6ff7 | ||
|
|
bffdea937c | ||
|
|
ec0f43019f | ||
|
|
291990412e | ||
|
|
a2672b99a3 | ||
|
|
908c943e21 | ||
|
|
5876c07a1a | ||
|
|
faae719b12 | ||
|
|
e199e6feeb | ||
|
|
d4b71d17a1 |
No files matched your search
+22
-5
@@ -2,10 +2,11 @@
|
||||
# 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
|
||||
|
||||
@@ -13,9 +14,20 @@ APP_HOST=aircraft.example.com
|
||||
# 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).
|
||||
@@ -37,6 +49,11 @@ FORCE_SSL=true
|
||||
# OIDC_AUTO_CREATE_USERS=false # true: create an account at first sign-in
|
||||
# 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 ----------------------------------------------------
|
||||
|
||||
@@ -2,6 +2,46 @@
|
||||
|
||||
Each release has a **version** (year.month.release, e.g. 2026.11.0) and a **build** (the exact source commit, shown on Admin → About). The newest release is first.
|
||||
|
||||
## 2026.11.6
|
||||
|
||||
### Changes
|
||||
|
||||
- **PDFs show on phones.** Android showed nothing for a PDF document and iPhones only its first page. On phones and tablets every page is now drawn in the app, as it scrolls into view, downloading only the parts of the file those pages need (a long manual opens quickly and doesn't use up mobile data). Computers keep the browser's own PDF viewer.
|
||||
- **Connection status in the top bar.** It turns red when the server can't be reached, and back on its own when it can. A ring fills while pages are saved for offline use or what was logged offline is sent; it's amber with a count while flights or squawks wait to send.
|
||||
- **A weak signal counts as no signal.** Log Flight and Report Squawk say "Sending…" and, if the server doesn't answer within 10 seconds (a minute with photos), keep the entry on the phone and send it when the connection's back. If it got through after all, it isn't logged twice. Every page falls back to its offline copy or the offline page instead of loading forever.
|
||||
- **The activity log loads as you scroll** (it stopped at 200 events).
|
||||
- **What's new** shows the running version's notes on Admin → About; older releases fold to one line each.
|
||||
- **REST API** for other programs, such as a script that pulls what's coming due or a work-order system: read aircraft, parts, due items, inspections, ADs, squawks and logbook entries; report and update squawks; send draft logbook entries to be signed in the app. Webhooks announce squawks reported, updated and resolved, entries signed, and drafts completed. Personal tokens are made in Profile. The API never signs an entry; see Help → REST API.
|
||||
|
||||
### For administrators
|
||||
|
||||
- **Admin → Integrations** makes tokens for other systems, acting for the person each request names, limited to the aircraft chosen, plus webhook endpoints.
|
||||
- The update adds the API's tables; they're created automatically when the new version starts.
|
||||
|
||||
## 2026.11.5
|
||||
|
||||
### Changes
|
||||
|
||||
- **Faster photos.** Aircraft photos load as small copies on the Fleet page and the aircraft header (they were the full original, slow on mobile). The offline copies use the small versions too.
|
||||
- **Detail cards read one item per row on a phone**: flights, engine data, components and major repairs and alterations. Wider screens show two columns.
|
||||
- **Profile uses the width of a desktop screen**: your account and its security on the left; calendar, certificates, this device and integrations on the right.
|
||||
- **Notifications:** opening Profile on a device records its notification subscription again, so a device whose subscription was never saved starts receiving them. **Send test** lists each device and whether its push service accepted the notification, with the reason if not. If turning notifications on fails, the browser's error is shown.
|
||||
|
||||
### For administrators
|
||||
|
||||
- **The app won't start with a placeholder or short `SECRET_KEY_BASE`** (under 32 characters), since anyone who knows it can sign in as anyone. `sam:doctor` flags one under 64 characters. Use the output of `bin/rails secret`.
|
||||
- **First-run setup asks for a one-time code** printed in the server log (`docker compose logs web | grep "Setup code"`), so only whoever runs the server can create the admin account.
|
||||
- **HTTPS without a proxy:** `docker-compose.direct.yml` with `TLS_DOMAIN` gets and renews a Let's Encrypt certificate by itself.
|
||||
- **The app answers only for its own names** when `APP_HOST` is set: `APP_HOST`, the `APP_URL` host, `localhost`, IP addresses, and any names listed in the new `ALLOWED_HOSTS`. Other names get a short explanation. If you reach the app by another name (such as a LAN name), add it to `ALLOWED_HOSTS`.
|
||||
- **AirTrail servers on a private network** can be connected only by an administrator, or by anyone when listed in `AIRTRAIL_ALLOWED_HOSTS`. The server itself and link-local addresses are always refused.
|
||||
- The project is released into the public domain (LICENSE, The Unlicense).
|
||||
|
||||
### Fixes
|
||||
|
||||
- A file that isn't a photo, or an empty one, chosen as the aircraft photo now shows "must be an image" instead of an error page. An image that can't be read is shown as the original file.
|
||||
- A component can't be set as a part of its own parts; that made the logbook entry and squawk resolution pages fail.
|
||||
- Many malformed requests that caused error pages now get a proper answer: pages requested in another format, blank required values, links to records that don't exist, numbers too large to store, and text sent where a file belongs.
|
||||
|
||||
## 2026.11.4
|
||||
|
||||
### Changes
|
||||
|
||||
@@ -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>
|
||||
@@ -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,9 +72,12 @@ 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. |
|
||||
|
||||
@@ -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 */
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
@@ -8,7 +8,7 @@ class AircraftImportsController < ApplicationController
|
||||
|
||||
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
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
module Api
|
||||
module V1
|
||||
# The fleet this token reaches, and each aircraft's own lists.
|
||||
class AircraftController < BaseController
|
||||
before_action -> { require_scope!(:read) }
|
||||
|
||||
def index
|
||||
render_page(aircraft_scope) { ApiPresenter.aircraft(_1) }
|
||||
end
|
||||
|
||||
def show
|
||||
render json: { data: ApiPresenter.aircraft(find_aircraft(params[:id])) }
|
||||
end
|
||||
|
||||
# The parts tree (?all=1 includes disposed parts).
|
||||
def components
|
||||
aircraft = find_aircraft(params[:id])
|
||||
scope = aircraft.components.includes(:component_type)
|
||||
scope = scope.where.not(status: "DISPOSED") unless params[:all].present?
|
||||
render_page(scope) { ApiPresenter.component(_1) }
|
||||
end
|
||||
|
||||
# Everything coming due, soonest first (hours projected to dates).
|
||||
def due
|
||||
aircraft = find_aircraft(params[:id])
|
||||
render json: { data: DueList.new(aircraft).items.map { ApiPresenter.due_item(_1) } }
|
||||
end
|
||||
|
||||
def inspections
|
||||
aircraft = find_aircraft(params[:id])
|
||||
render json: { data: Compliance.inspection_rows(aircraft).map { ApiPresenter.inspection(_1) } }
|
||||
end
|
||||
|
||||
def ads
|
||||
aircraft = find_aircraft(params[:id])
|
||||
render json: { data: Compliance.ad_rows(aircraft).map { ApiPresenter.ad(_1) } }
|
||||
end
|
||||
|
||||
# Logbook entries, oldest first (paged); ?log=AC|ENG|PROP|OTHER, ?signed=true|false.
|
||||
def logbook_entries
|
||||
aircraft = find_aircraft(params[:id])
|
||||
scope = aircraft.logbook_entries.includes(:signature)
|
||||
scope = scope.where(log_type: params[:log]) if params[:log].present?
|
||||
scope = params[:signed] == "true" ? scope.where.associated(:signature) : scope.where.missing(:signature) if params[:signed].present?
|
||||
render_page(scope) { ApiPresenter.logbook_entry(_1) }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,123 @@
|
||||
# The REST API, version 1 (docs/api.md). JSON in and out; a token in
|
||||
# "Authorization: Bearer sam_…" instead of a browser session, so no cookies
|
||||
# and no CSRF tokens.
|
||||
#
|
||||
# A personal token acts as its owner. An integration token acts for the
|
||||
# person named in "SAM-On-Behalf-Of: <email>" (required for writes), and
|
||||
# reaches only its aircraft that person can also see.
|
||||
module Api
|
||||
module V1
|
||||
class BaseController < ActionController::API
|
||||
include RejectsNullBytes
|
||||
|
||||
MAX_PAGE = 200
|
||||
|
||||
before_action :authenticate
|
||||
rate_limit to: 600, within: 1.minute, by: -> { @api_token&.id || request.remote_ip },
|
||||
with: -> { render_error(:too_many_requests, "rate_limited", "Too many requests; slow down.") }
|
||||
around_action :idempotent, if: -> { request.post? || request.patch? || request.delete? }
|
||||
|
||||
rescue_from ActiveRecord::RecordNotFound do
|
||||
render_error(:not_found, "not_found", "Not found, or not available to this token.")
|
||||
end
|
||||
rescue_from ActionController::ParameterMissing, ActionDispatch::Http::Parameters::ParseError do |e|
|
||||
render_error(:bad_request, "bad_request", e.message.truncate(200))
|
||||
end
|
||||
rescue_from ActiveRecord::RecordInvalid do |e|
|
||||
render_invalid(e.record)
|
||||
end
|
||||
rescue_from ActiveSupport::MessageVerifier::InvalidSignature, ActiveModel::RangeError,
|
||||
ActiveRecord::NotNullViolation, ActiveRecord::InvalidForeignKey do
|
||||
render_error(:unprocessable_entity, "invalid", "Some values couldn't be saved.")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
attr_reader :api_token
|
||||
|
||||
def acting_user = Current.api_user
|
||||
|
||||
def authenticate
|
||||
token = request.authorization.to_s[/\ABearer\s+(\S+)\z/i, 1]
|
||||
@api_token = ApiToken.authenticate(token)
|
||||
return render_error(:unauthorized, "unauthorized", "A valid API token is required.") unless @api_token
|
||||
|
||||
Current.api_token = @api_token
|
||||
Current.ip_address = request.remote_ip
|
||||
Current.api_user = @api_token.personal? ? @api_token.user : on_behalf_of
|
||||
@api_token.used!(request.remote_ip)
|
||||
end
|
||||
|
||||
# The person an integration is acting for, if it named one.
|
||||
def on_behalf_of
|
||||
email = request.headers["SAM-On-Behalf-Of"].to_s.strip.downcase.presence or return
|
||||
User.active.find_by(email_address: email) ||
|
||||
render_error(:unprocessable_entity, "unknown_user", "SAM-On-Behalf-Of doesn't match an active user.")
|
||||
end
|
||||
|
||||
def require_scope!(scope)
|
||||
return if api_token.allows?(scope)
|
||||
render_error(:forbidden, "missing_scope", "This token doesn't have the #{scope} scope.")
|
||||
end
|
||||
|
||||
# Writes always name a person, so the record history shows who.
|
||||
def require_person!
|
||||
return if acting_user
|
||||
render_error(:unprocessable_entity, "on_behalf_of_required", "Writes with an integration token need SAM-On-Behalf-Of.")
|
||||
end
|
||||
|
||||
def aircraft_scope = api_token.aircraft_scope(acting_user)
|
||||
|
||||
def find_aircraft(id = params[:aircraft_id]) = aircraft_scope.find(id)
|
||||
|
||||
def role_on(aircraft) = acting_user&.role_for(aircraft)
|
||||
def owner_of?(aircraft) = role_on(aircraft).in?(%w[admin owner])
|
||||
|
||||
# ?limit= (1–200, default 50), ?after=<id> to continue, ?updated_since=<ISO time>.
|
||||
def paginate(scope)
|
||||
limit = params.fetch(:limit, 50).to_i.clamp(1, MAX_PAGE)
|
||||
scope = scope.where(scope.arel_table[:id].gt(params[:after].to_i)) if params[:after].present?
|
||||
if params[:updated_since].present?
|
||||
since = Time.iso8601(params[:updated_since].to_s) rescue (raise ActionController::BadRequest, "updated_since must be an ISO 8601 time")
|
||||
scope = scope.where(scope.arel_table[:updated_at].gteq(since))
|
||||
end
|
||||
records = scope.reorder(:id).limit(limit + 1).to_a
|
||||
more = records.size > limit
|
||||
records = records.first(limit)
|
||||
[ records, (records.last.id if more) ]
|
||||
end
|
||||
|
||||
def render_page(scope, &present)
|
||||
records, next_after = paginate(scope)
|
||||
render json: { data: records.map(&present), next_after: next_after }
|
||||
end
|
||||
|
||||
def render_error(status, code, message, fields: nil)
|
||||
render json: { error: { code: code, message: message, fields: fields }.compact }, status: status
|
||||
end
|
||||
|
||||
def render_invalid(record)
|
||||
render_error(:unprocessable_entity, "invalid", record.errors.full_messages.to_sentence, fields: record.errors.to_hash)
|
||||
end
|
||||
|
||||
# The same Idempotency-Key again (a retry) gets the first answer; the
|
||||
# same key with a different request is a conflict.
|
||||
def idempotent
|
||||
key = request.headers["Idempotency-Key"].to_s.strip
|
||||
return yield if key.empty? || api_token.nil?
|
||||
return render_error(:bad_request, "bad_request", "Idempotency-Key is too long.") if key.length > 100
|
||||
|
||||
digest = OpenSSL::Digest::SHA256.hexdigest([ request.method, request.path, request.raw_post ].join("\n"))
|
||||
if (seen = api_token.idempotency_keys.find_by(key: key))
|
||||
return render_error(:conflict, "idempotency_conflict", "This Idempotency-Key was used for a different request.") if seen.request_digest != digest
|
||||
response.headers["Idempotent-Replay"] = "true"
|
||||
return render(json: seen.response_body, status: seen.response_status)
|
||||
end
|
||||
yield
|
||||
return if response.status >= 500
|
||||
api_token.idempotency_keys.create(key: key, request_digest: digest, response_status: response.status,
|
||||
response_body: response.body, created_at: Time.current)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,129 @@
|
||||
module Api
|
||||
module V1
|
||||
# Draft logbook entries for one visit (docs/api.md, "Draft entries"). The
|
||||
# work items become one unsigned entry per logbook, signed in the app; the
|
||||
# squawks they resolve and inspections they complete are held until every
|
||||
# entry is signed. Like writing entries in the app, it's for the
|
||||
# aircraft's owners.
|
||||
class DraftBatchesController < BaseController
|
||||
before_action -> { require_scope!(:read) }, only: %i[index show lookup]
|
||||
before_action -> { require_scope!("drafts:write") }, :require_person!, only: %i[create destroy]
|
||||
|
||||
def index
|
||||
scope = find_aircraft.draft_batches.includes(entries: :signature)
|
||||
scope = scope.where(status: params[:status]) if params[:status].present?
|
||||
render_page(scope) { ApiPresenter.draft_batch(_1) }
|
||||
end
|
||||
|
||||
def lookup
|
||||
scope = DraftBatch.where(aircraft: aircraft_scope, external_ref: params.require(:external_ref)).includes(entries: :signature)
|
||||
render json: { data: scope.map { ApiPresenter.draft_batch(_1) } }
|
||||
end
|
||||
|
||||
def show
|
||||
render json: { data: ApiPresenter.draft_batch(find_batch) }
|
||||
end
|
||||
|
||||
# POST /aircraft/:aircraft_id/draft_batches
|
||||
def create
|
||||
@aircraft = find_aircraft
|
||||
return render_error(:forbidden, "owners_only", "Draft entries are for the aircraft's owners (act for an owner).") unless owner_of?(@aircraft)
|
||||
|
||||
input = params.require(:draft_batch)
|
||||
items = Array(input[:items]).map { _1.permit(:log, :text, :external_ref, resolves_squawks: []) }
|
||||
errors = check(input, items)
|
||||
return render_error(:unprocessable_entity, "invalid", errors.values.flatten.to_sentence, fields: errors) if errors.any?
|
||||
|
||||
invitations = {}
|
||||
batch = DraftBatch.transaction do
|
||||
b = @aircraft.draft_batches.create!(api_token: api_token, created_by: acting_user, external_ref: input[:external_ref],
|
||||
signer_email: signer_email(input), held: held(input, items))
|
||||
items.group_by { _1[:log] }.each do |log, group|
|
||||
entry = b.entries.create!(aircraft: @aircraft, log_type: log, date: input[:date], text: group.map { _1[:text].to_s.strip }.join("\n\n"),
|
||||
entry_type: inspection_logs(input, items).include?(log) ? "INSPECTION" : "MAINTENANCE",
|
||||
inspection_result: inspection_result_for(input, items, log),
|
||||
aircraft_hours_at_entry: input[:aircraft_hours].presence, external_ref: group.filter_map { _1[:external_ref] }.join(",").presence)
|
||||
invitations[entry.id] = invite(entry, b.signer_email, send: input.dig(:signer, :send_email).to_s == "true") if b.signer_email
|
||||
end
|
||||
b
|
||||
end
|
||||
@aircraft.log_event!("logbook", I18n.t("api.draft_batches.sent", count: batch.entries.size, name: api_token.name), notes: batch.external_ref)
|
||||
render json: { data: ApiPresenter.draft_batch(batch.reload, invitations: invitations) }, status: :created
|
||||
end
|
||||
|
||||
# DELETE /draft_batches/:id: withdraw it while nothing in it is signed.
|
||||
def destroy
|
||||
batch = find_batch
|
||||
return render_error(:forbidden, "owners_only", "Only the aircraft's owners can withdraw a draft.") unless owner_of?(batch.aircraft)
|
||||
unless batch.awaiting? && batch.entries.none?(&:signed?)
|
||||
return render_error(:conflict, "signed", "Part of this draft is signed (or it's no longer awaiting signature); correct it in the app instead.")
|
||||
end
|
||||
batch.withdraw!
|
||||
render json: { data: ApiPresenter.draft_batch(batch.reload) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def find_batch = DraftBatch.where(aircraft: aircraft_scope).includes(entries: :signature).find(params[:id])
|
||||
|
||||
def check(input, items)
|
||||
errors = Hash.new { |h, k| h[k] = [] }
|
||||
errors[:items] << "at least one item is needed" if items.empty?
|
||||
items.each_with_index do |item, i|
|
||||
errors[:"items.#{i}.log"] << "must be one of #{LogbookEntry::LOG_TYPES.keys.join(', ')}" unless LogbookEntry::LOG_TYPES.key?(item[:log])
|
||||
errors[:"items.#{i}.text"] << "can't be blank" if item[:text].blank?
|
||||
end
|
||||
errors[:date] << "must be a date (YYYY-MM-DD)" unless (Date.iso8601(input[:date].to_s) rescue nil)
|
||||
errors[:aircraft_hours] << "must be a number" if input[:aircraft_hours].present? && !input[:aircraft_hours].to_s.match?(/\A\d+(\.\d+)?\z/)
|
||||
squawk_ids = items.flat_map { Array(_1[:resolves_squawks]) }.map(&:to_i)
|
||||
missing = squawk_ids - @aircraft.squawks.active.where(id: squawk_ids).ids
|
||||
errors[:resolves_squawks] << "no open squawk #{missing.join(', ')} on this aircraft" if missing.any?
|
||||
Array(input[:completes_inspections]).each_with_index do |c, i|
|
||||
id = c.respond_to?(:[]) ? c[:inspection_type_id].to_i : 0
|
||||
errors[:"completes_inspections.#{i}"] << "no inspection #{id} applies to this aircraft" unless @aircraft.applicable_inspection_types.exists?(id: id)
|
||||
log = inspection_log(c, items)
|
||||
errors[:"completes_inspections.#{i}.log"] << "must be the log of one of the items" unless items.any? { _1[:log] == log }
|
||||
unless LogbookEntry::INSPECTION_RESULTS.key?(c.respond_to?(:[]) ? c[:result].to_s : "")
|
||||
errors[:"completes_inspections.#{i}.result"] << "must be #{LogbookEntry::INSPECTION_RESULTS.keys.join(' or ')}"
|
||||
end
|
||||
end
|
||||
Array(input[:completes_inspections]).group_by { inspection_log(_1, items) }.each do |log, group|
|
||||
errors[:completes_inspections] << "inspections in the #{log} log need the same result (one entry)" if group.map { _1[:result].to_s }.uniq.size > 1
|
||||
end
|
||||
errors[:aircraft_hours] << "is needed to record an inspection" if Array(input[:completes_inspections]).any? && input[:aircraft_hours].blank?
|
||||
email = input.dig(:signer, :email).to_s.strip
|
||||
errors[:"signer.email"] << "isn't an email address" if email.present? && !email.match?(URI::MailTo::EMAIL_REGEXP)
|
||||
errors[:"signer.send_email"] << "needs email set up on the server" if input.dig(:signer, :send_email).to_s == "true" && !MailSettings.configured?
|
||||
errors
|
||||
end
|
||||
|
||||
# The inspection goes in the logbook named for it, else the airframe
|
||||
# log if there's an item for it, else the first item's.
|
||||
def inspection_log(c, items)
|
||||
c[:log].presence || (items.any? { _1[:log] == "AC" } ? "AC" : items.first&.dig(:log))
|
||||
end
|
||||
|
||||
def inspection_logs(input, items) = Array(input[:completes_inspections]).map { inspection_log(_1, items) }
|
||||
|
||||
# approved | discrepancies, for the entry in that log that records inspections.
|
||||
def inspection_result_for(input, items, log)
|
||||
Array(input[:completes_inspections]).find { inspection_log(_1, items) == log }&.dig(:result)
|
||||
end
|
||||
|
||||
def held(input, items)
|
||||
{ "squawks" => items.flat_map { |it| Array(it[:resolves_squawks]).map { |id| { "id" => id.to_i, "log" => it[:log] } } }.uniq { _1["id"] },
|
||||
"inspections" => Array(input[:completes_inspections]).map { { "id" => _1[:inspection_type_id].to_i, "log" => inspection_log(_1, items) } } }
|
||||
end
|
||||
|
||||
def signer_email(input) = input.dig(:signer, :email).to_s.strip.downcase.presence
|
||||
|
||||
# A link for the signer to sign this entry with their own account,
|
||||
# returned to the caller to pass on; emailed too when asked.
|
||||
def invite(entry, email, send: false)
|
||||
invitation = entry.signing_invitations.create!(email: email, invited_by: acting_user)
|
||||
SigningInvitationMailer.invite(invitation, invitation.token).deliver_later if send
|
||||
invitation.token
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,16 @@
|
||||
module Api
|
||||
module V1
|
||||
# What this token is and who it's acting as: a quick check for a new integration.
|
||||
class MeController < BaseController
|
||||
def show
|
||||
render json: { data: {
|
||||
token: { name: api_token.name, kind: api_token.kind, hint: api_token.token_hint, scopes: api_token.scopes,
|
||||
aircraft_ids: (api_token.aircraft_ids if api_token.integration?) }.compact,
|
||||
acting_as: acting_user && { id: acting_user.id, name: acting_user.display_name, email: acting_user.email_address },
|
||||
aircraft_ids: aircraft_scope.ids,
|
||||
api_version: "v1", app_version: Rails.root.join("VERSION").read.strip
|
||||
} }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,66 @@
|
||||
module Api
|
||||
module V1
|
||||
# Squawks: list and report on an aircraft; find by external_ref; update.
|
||||
# Resolving happens through a signed logbook entry, not here.
|
||||
class SquawksController < BaseController
|
||||
before_action -> { require_scope!(:read) }, only: %i[index show lookup]
|
||||
before_action -> { require_scope!("squawks:write") }, :require_person!, only: %i[create update]
|
||||
|
||||
# GET /aircraft/:aircraft_id/squawks?status=open|resolved|all (default open)
|
||||
def index
|
||||
scope = find_aircraft.squawks.includes(:reported_by).with_attached_attachments
|
||||
scope = case params.fetch(:status, "open")
|
||||
when "open" then scope.active
|
||||
when "resolved" then scope.resolved
|
||||
else scope
|
||||
end
|
||||
render_page(scope) { ApiPresenter.squawk(_1) }
|
||||
end
|
||||
|
||||
# GET /squawks?external_ref=redmine:issue:4512
|
||||
def lookup
|
||||
ref = params.require(:external_ref)
|
||||
scope = Squawk.where(aircraft: aircraft_scope, external_ref: ref).includes(:reported_by).with_attached_attachments
|
||||
render json: { data: scope.map { ApiPresenter.squawk(_1) } }
|
||||
end
|
||||
|
||||
def show
|
||||
render json: { data: ApiPresenter.squawk(find_squawk) }
|
||||
end
|
||||
|
||||
# POST /aircraft/:aircraft_id/squawks
|
||||
def create
|
||||
aircraft = find_aircraft
|
||||
squawk = aircraft.squawks.new(create_params.merge(reported_by: acting_user, resolved: false))
|
||||
squawk.component_id = nil unless aircraft.components.exists?(id: squawk.component_id)
|
||||
squawk.save!
|
||||
SquawkReported.call(squawk, by: acting_user)
|
||||
render json: { data: ApiPresenter.squawk(squawk) }, status: :created
|
||||
end
|
||||
|
||||
# PATCH /squawks/:id: external_ref by anyone who may write; the rest
|
||||
# (issue, priority, component, notes) by the aircraft's owners, as in the app.
|
||||
def update
|
||||
squawk = find_squawk
|
||||
return render_error(:unprocessable_entity, "resolved", "A resolved squawk can't be changed.") if squawk.resolved?
|
||||
attrs = params.require(:squawk).permit(:external_ref, :issue_reported, :priority, :component_id, :notes)
|
||||
if (attrs.keys - %w[external_ref]).any? && !owner_of?(squawk.aircraft)
|
||||
return render_error(:forbidden, "owners_only", "Only the aircraft's owners can change a squawk's details.")
|
||||
end
|
||||
attrs[:component_id] = nil if attrs.key?(:component_id) && !squawk.aircraft.components.exists?(id: attrs[:component_id])
|
||||
squawk.update!(attrs)
|
||||
render json: { data: ApiPresenter.squawk(squawk) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def find_squawk = Squawk.where(aircraft: aircraft_scope).find(params[:id])
|
||||
|
||||
def create_params
|
||||
params.require(:squawk).permit(:issue_reported, :priority, :component_id, :external_ref).tap do |p|
|
||||
p[:priority] = p.fetch(:priority, 2).to_i
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,19 @@
|
||||
# Profile → API tokens: personal tokens for the REST API (docs/api.md). The
|
||||
# token is shown once, on the page right after it's made (not kept in the
|
||||
# flash or anywhere else).
|
||||
class ApiTokensController < ApplicationController
|
||||
def create
|
||||
@token = current_user.api_tokens.new(name: params.dig(:api_token, :name), kind: "personal",
|
||||
scopes: Array(params.dig(:api_token, :scopes)) & ApiToken::SCOPES.keys)
|
||||
if @token.save
|
||||
render :created
|
||||
else
|
||||
redirect_to edit_profile_path(anchor: "api"), alert: @token.errors.full_messages.to_sentence
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
current_user.api_tokens.personal.active.find(params[:id]).revoke!
|
||||
redirect_to edit_profile_path(anchor: "api"), notice: t("flash.api_tokens.revoked")
|
||||
end
|
||||
end
|
||||
@@ -4,6 +4,7 @@ class ApplicationController < ActionController::Base
|
||||
include TimeZones
|
||||
allow_browser versions: :modern
|
||||
|
||||
include RejectsNullBytes
|
||||
prepend_before_action :redirect_to_setup
|
||||
before_action { Current.ip_address = request.remote_ip } # for record history
|
||||
helper_method :current_user
|
||||
@@ -15,8 +16,27 @@ 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.
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -10,7 +10,7 @@ class LogbookImportsController < ApplicationController
|
||||
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").
|
||||
|
||||
@@ -35,7 +35,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
|
||||
|
||||
@@ -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,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
|
||||
|
||||
@@ -21,11 +21,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
|
||||
|
||||
@@ -3,12 +3,12 @@ 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, and its photo (at both page sizes).
|
||||
def offline_pages
|
||||
current_user.accessible_aircraft.ordered.limit(OFFLINE_AIRCRAFT).map do |a|
|
||||
{ tail: a.tail_number, pages: [ aircraft_path(a), aircraft_weight_balance_records_path(a) ],
|
||||
flight: new_aircraft_flight_log_path(a), squawk: new_aircraft_squawk_path(a),
|
||||
picture: (url_for(a.picture) if a.picture.attached?) }.compact
|
||||
pictures: (%i[thumb card].map { url_for(a.picture_for(_1)) }.uniq if a.picture_shown?) }.compact
|
||||
end
|
||||
end
|
||||
# Tabs on the aircraft pages: [label, path, controller names that highlight it, owner_only]
|
||||
|
||||
@@ -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?
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
|
||||
@@ -30,13 +33,22 @@ export default class extends Controller {
|
||||
forms[a.flight] = { tail: a.tail, kind: "flight" }
|
||||
forms[a.squawk] = { tail: a.tail, kind: "squawk" }
|
||||
}
|
||||
for (const path of paths) {
|
||||
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 (_) { return }
|
||||
try { await fetch(path, { credentials: "same-origin", headers: { Accept: "text/html" } }) } catch (_) {
|
||||
document.dispatchEvent(new CustomEvent("sam:unreachable"))
|
||||
return
|
||||
}
|
||||
await this.savePictures(this.aircraftValue.map((a) => a.picture).filter(Boolean))
|
||||
}
|
||||
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.
|
||||
|
||||
@@ -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
|
||||
@@ -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"
|
||||
|
||||
|
||||
+19
-2
@@ -1,7 +1,12 @@
|
||||
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 :users, through: :roles
|
||||
@@ -11,6 +16,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 +83,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
|
||||
|
||||
@@ -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 }
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
class HelpGuide
|
||||
DIR = Rails.root.join("docs/guide")
|
||||
ORDER = %w[README getting-started profile aircraft flights squawks oil-and-fuel components logbook records
|
||||
inspections ads documents major-records sharing administration disclaimer changelog].freeze
|
||||
inspections ads documents major-records sharing administration api disclaimer changelog].freeze
|
||||
OPTIONS = {
|
||||
parse: { smart: true },
|
||||
render: { hardbreaks: false, unsafe: false },
|
||||
@@ -27,7 +27,11 @@ class HelpGuide
|
||||
# Sanitized HTML. Links to other guide pages ("records.md#mistakes") go
|
||||
# through `link` (slug, anchor) -> URL, or become plain text when nil.
|
||||
def self.html(page, link:, title: true)
|
||||
source = title ? page.markdown : page.markdown.sub(/\A# .+\n+/, "")
|
||||
render(title ? page.markdown : page.markdown.sub(/\A# .+\n+/, ""), link: link)
|
||||
end
|
||||
|
||||
# Any Markdown from the guide (or a part of it, such as one release of the changelog).
|
||||
def self.render(source, link:)
|
||||
html = Commonmarker.to_html(source, options: OPTIONS, plugins: { syntax_highlighter: nil })
|
||||
html = Rails::HTML5::SafeListSanitizer.new.sanitize(html, tags: TAGS, attributes: ATTRIBUTES)
|
||||
html.gsub(%r{<a href="([a-z-]+|README)\.md(?:#([a-z0-9-]+))?">(.*?)</a>}m) do
|
||||
|
||||
@@ -14,6 +14,7 @@ class LogbookEntry < ApplicationRecord
|
||||
belongs_to :document, optional: true
|
||||
# For engine / propeller logs: which one, and its times at this entry.
|
||||
belongs_to :component, optional: true
|
||||
belongs_to :draft_batch, optional: true # made through the API, see DraftBatch
|
||||
# Sub-components it also covers (the oil filter on the engine…).
|
||||
has_many :parts, -> { includes(component: :component_type).order(:id) }, class_name: "LogbookEntryPart",
|
||||
dependent: :destroy, autosave: true
|
||||
@@ -33,6 +34,7 @@ class LogbookEntry < ApplicationRecord
|
||||
validates :signoff_certificate_type, inclusion: { in: CERTIFICATE_TYPES.keys }, allow_blank: true
|
||||
validates :inspection_result, inclusion: { in: INSPECTION_RESULTS.keys }, allow_blank: true
|
||||
validates :component_hours_at_entry, :component_since_overhaul_at_entry, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
|
||||
normalizes :external_ref, with: ->(r) { r.to_s.strip.first(200).presence }
|
||||
normalizes :signoff_certificate_type, :inspection_result, :signoff_certificate_number, with: ->(v) { v.strip.presence }
|
||||
|
||||
# Fields that may still change on a signed entry: its link to a scanned
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
class PushSubscription < ApplicationRecord
|
||||
# The browsers' push services. The server posts to the endpoint, so only
|
||||
# these hosts are accepted (not, say, an address inside the network).
|
||||
PUSH_SERVICES = /\A(fcm\.googleapis\.com|updates\.push\.services\.mozilla\.com|([\w-]+\.)*push\.apple\.com|([\w-]+\.)*notify\.windows\.com)\z/
|
||||
PUSH_SERVICES = /\A(([\w-]+\.)*googleapis\.com|([\w-]+\.)*google\.com|updates\.push\.services\.mozilla\.com|([\w-]+\.)*push\.apple\.com|([\w-]+\.)*notify\.windows\.com)\z/
|
||||
|
||||
belongs_to :user
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
# editing a version breaks the chain and the nightly check reports it.
|
||||
class RecordVersion < ApplicationRecord
|
||||
belongs_to :user, optional: true
|
||||
belongs_to :api_token, optional: true
|
||||
|
||||
scope :chronological, -> { order(:id) }
|
||||
|
||||
@@ -15,10 +16,12 @@ class RecordVersion < ApplicationRecord
|
||||
def self.append!(item:, aircraft_id:, event:, changes:)
|
||||
now = Time.current
|
||||
payload = { "item_type" => item.class.name, "item_id" => item.id, "event" => event, "changes" => changes,
|
||||
"user_id" => Current.user&.id, "at" => now.utc.iso8601(6) }.to_json
|
||||
"user_id" => Current.user&.id, "at" => now.utc.iso8601(6) }
|
||||
payload["api_token_id"] = Current.api_token.id if Current.api_token # made through the API (part of the hashed payload)
|
||||
payload = payload.to_json
|
||||
prev = where(aircraft_id: aircraft_id).order(:id).last&.chain_hash
|
||||
create!(aircraft_id: aircraft_id, item_type: item.class.name, item_id: item.id, event: event, user_id: Current.user&.id,
|
||||
ip_address: Current.ip_address, payload: payload, prev_hash: prev, chain_hash: digest(prev, payload), created_at: now)
|
||||
ip_address: Current.ip_address, api_token_id: Current.api_token&.id, payload: payload, prev_hash: prev, chain_hash: digest(prev, payload), created_at: now)
|
||||
end
|
||||
|
||||
def changes_hash = JSON.parse(payload)["changes"]
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# The application secret key signs the sign-in cookie and protects stored
|
||||
# secrets (two-factor keys, API keys), so anyone who can guess it can sign in
|
||||
# as anyone. A placeholder or short key stops the app from starting; one
|
||||
# shorter than what `bin/rails secret` makes is reported by sam:doctor.
|
||||
module SecretKeyCheck
|
||||
MIN = 32 # below this, refuse to start
|
||||
RECOMMENDED = 64 # below this, warn
|
||||
PLACEHOLDERS = %w[change-me changeme change_me secret password your-secret-key replace-me example].freeze
|
||||
|
||||
module_function
|
||||
|
||||
# :ok, :weak or :unsafe
|
||||
def strength(key = ENV["SECRET_KEY_BASE"].to_s)
|
||||
return :unsafe if PLACEHOLDERS.include?(key.strip.downcase) || key.length < MIN || key.chars.uniq.size < 10
|
||||
key.length < RECOMMENDED ? :weak : :ok
|
||||
end
|
||||
|
||||
def verify!(key = ENV["SECRET_KEY_BASE"].to_s)
|
||||
case strength(key)
|
||||
when :unsafe
|
||||
abort "SECRET_KEY_BASE is a placeholder or too short (#{key.length} characters). " \
|
||||
"Set it to the output of `bin/rails secret` (128 random characters) and start again."
|
||||
when :weak
|
||||
Rails.logger.warn("[security] SECRET_KEY_BASE is only #{key.length} characters; `bin/rails secret` makes 128.")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,33 @@
|
||||
# Until the first account exists, whoever reaches the server could create the
|
||||
# admin account. The setup page asks for this one-time code, which is only in
|
||||
# the server's log, so only whoever runs the server can finish setup.
|
||||
module SetupCode
|
||||
ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789".chars.freeze # no look-alikes (0/O, 1/I/L)
|
||||
|
||||
module_function
|
||||
|
||||
# (Each parallel test process has its own.)
|
||||
def file = Rails.env.test? ? Rails.root.join("tmp", "setup_code-#{Process.pid}") : Rails.root.join("storage", "setup_code")
|
||||
|
||||
# The code, made the first time it's needed and kept until setup is done.
|
||||
def current
|
||||
return file.read.strip if file.exist?
|
||||
code = Array.new(8) { ALPHABET[SecureRandom.random_number(ALPHABET.size)] }.join.insert(4, "-")
|
||||
file.dirname.mkpath
|
||||
File.write(file, code, perm: 0o600)
|
||||
code
|
||||
end
|
||||
|
||||
def announce
|
||||
Rails.logger.warn("Setup code: #{current} (enter it on the setup page to create the admin account)")
|
||||
end
|
||||
|
||||
def matches?(given)
|
||||
normalize = ->(s) { s.to_s.upcase.gsub(/[^A-Z0-9]/, "") }
|
||||
ActiveSupport::SecurityUtils.secure_compare(normalize.(given), normalize.(current))
|
||||
end
|
||||
|
||||
def clear
|
||||
file.delete if file.exist?
|
||||
end
|
||||
end
|
||||
@@ -11,6 +11,15 @@ class Squawk < ApplicationRecord
|
||||
belongs_to :logbook_entry, optional: true
|
||||
has_many_attached :attachments
|
||||
|
||||
# Integrations hear about squawks (webhooks), once the change is saved.
|
||||
after_create_commit { Webhooks.publish("squawk.created", aircraft: aircraft, data: ApiPresenter.squawk(self)) }
|
||||
after_update_commit do
|
||||
next if (saved_changes.keys - %w[updated_at]).empty?
|
||||
event = saved_change_to_resolved? && resolved? ? "squawk.resolved" : "squawk.updated"
|
||||
Webhooks.publish(event, aircraft: aircraft, data: ApiPresenter.squawk(self))
|
||||
end
|
||||
|
||||
normalizes :external_ref, with: ->(r) { r.to_s.strip.first(200).presence }
|
||||
validates :priority, inclusion: { in: PRIORITIES.keys }
|
||||
validates :issue_reported, presence: true
|
||||
validates_uploads :attachments
|
||||
|
||||
@@ -3,6 +3,7 @@ class User < ApplicationRecord
|
||||
has_many :sessions, dependent: :destroy
|
||||
has_many :aircraft_roles, dependent: :destroy
|
||||
has_many :push_subscriptions, dependent: :delete_all
|
||||
has_many :api_tokens, dependent: :destroy
|
||||
|
||||
normalizes :time_zone, with: ->(z) { z.strip.presence }
|
||||
validates :time_zone, inclusion: { in: ->(_) { ActiveSupport::TimeZone.all.map(&:name) } }, allow_nil: true
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# One event sent (or being sent) to a webhook endpoint; the recent ones are
|
||||
# listed for the admin, with the answer the other system gave.
|
||||
class WebhookDelivery < ApplicationRecord
|
||||
KEEP_FOR = 30.days
|
||||
|
||||
belongs_to :webhook_endpoint
|
||||
|
||||
scope :recent, -> { order(created_at: :desc) }
|
||||
|
||||
def self.purge_old = where(created_at: ...KEEP_FOR.ago).delete_all
|
||||
end
|
||||
@@ -0,0 +1,28 @@
|
||||
# Where an integration wants to hear about changes (squawks, signed entries):
|
||||
# SAM posts JSON there, signed with the shared secret (see WebhookDeliveryJob).
|
||||
class WebhookEndpoint < ApplicationRecord
|
||||
EVENTS = LabelSet.new("webhook_endpoint.events", %w[squawk.created squawk.updated squawk.resolved entry.signed draft_batch.completed])
|
||||
|
||||
belongs_to :api_token
|
||||
has_many :deliveries, class_name: "WebhookDelivery", dependent: :delete_all
|
||||
|
||||
encrypts :secret
|
||||
|
||||
normalizes :url, with: ->(u) { u.to_s.strip }
|
||||
validates :url, presence: true, format: { with: %r{\Ahttps?://[^\s/]+(:\d+)?(/\S*)?\z}i }
|
||||
validates :secret, presence: true, length: { minimum: 16 }
|
||||
validate :events_known
|
||||
|
||||
scope :enabled, -> { where(enabled: true) }
|
||||
|
||||
def self.new_secret = SecureRandom.hex(32)
|
||||
|
||||
def subscribed?(event) = events.include?(event.to_s)
|
||||
|
||||
private
|
||||
|
||||
def events_known
|
||||
errors.add(:events, :blank) if events.blank?
|
||||
errors.add(:events, :inclusion) if (Array(events) - EVENTS.keys).any?
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,80 @@
|
||||
# What the API and webhooks send for each kind of record (docs/api.md).
|
||||
# Times are ISO 8601 UTC, hours decimals, codes rather than translated labels.
|
||||
module ApiPresenter
|
||||
module_function
|
||||
|
||||
def aircraft(a)
|
||||
aw = a.airworthiness
|
||||
{ id: a.id, tail_number: a.tail_number, make: a.make, model: a.model, serial_number: a.serial_number,
|
||||
icao_type: a.icao_type, status: a.status,
|
||||
airworthiness: { status: aw.status, issues: aw.issues.map { { category: _1.category, severity: _1.severity, title: _1.title } } },
|
||||
time_basis: a.time_basis, hours: dec(a.current_hours), tach: dec(a.tach_time), hobbs: dec(a.hobbs_time),
|
||||
updated_at: time(a.updated_at) }
|
||||
end
|
||||
|
||||
def component(c)
|
||||
{ id: c.id, aircraft_id: c.aircraft_id, parent_id: c.parent_component_id, type: c.component_type&.name,
|
||||
manufacturer: c.manufacturer, model: c.model, serial_number: c.serial_number.presence,
|
||||
location: c.install_location.presence, status: c.status, date_in_service: c.date_in_service&.iso8601,
|
||||
hours_in_service: dec(c.hours_in_service), hours_since_overhaul: dec(c.hours_since_overhaul),
|
||||
overhaul_date: c.overhaul_date&.iso8601, overhaul_kind: c.overhaul_kind.presence,
|
||||
tbo: { hours: c.tbo_hours, days: c.tbo_days, months: c.tbo_months, on_condition: c.on_condition, critical: c.tbo_critical }.compact,
|
||||
replacement: { hours: c.replacement_hours, days: c.replacement_days, months: c.replacement_months, critical: c.replacement_critical }.compact,
|
||||
expires_on: c.expires_on&.iso8601, updated_at: time(c.updated_at) }
|
||||
end
|
||||
|
||||
def due_item(i)
|
||||
{ key: i.key, title: i.title, kind: i.kind, due_date: i.date.iso8601, projected: i.projected,
|
||||
due_hours: dec(i.due_hours), overdue: i.overdue? }
|
||||
end
|
||||
|
||||
def squawk(s)
|
||||
{ id: s.id, aircraft_id: s.aircraft_id, component_id: s.component_id, issue_reported: s.issue_reported,
|
||||
priority: s.priority, grounding: s.grounding?, deferred: s.deferred?, resolved: !!s.resolved,
|
||||
resolved_at: time(s.resolved_at), notes: s.notes.presence, logbook_entry_id: s.logbook_entry_id,
|
||||
reported_by: s.reported_by&.display_name, external_ref: s.external_ref,
|
||||
attachments: s.attachments.map { _1.filename.to_s },
|
||||
created_at: time(s.created_at), updated_at: time(s.updated_at) }
|
||||
end
|
||||
|
||||
def logbook_entry(e)
|
||||
sig = e.signature
|
||||
{ id: e.id, aircraft_id: e.aircraft_id, component_id: e.component_id, log: e.log_type, entry_type: e.entry_type,
|
||||
date: e.date.iso8601, text: e.text, aircraft_hours: dec(e.aircraft_hours_at_entry),
|
||||
inspection_result: e.inspection_result.presence, verified: e.verified, superseded: e.superseded_at.present?,
|
||||
signed: sig.present?, signature: sig && signature(sig), draft_batch_id: e.draft_batch_id, external_ref: e.external_ref,
|
||||
signoff: sig ? nil : { person: e.signoff_person.presence, certificate_type: e.signoff_certificate_type.presence,
|
||||
certificate_number: e.signoff_certificate_number.presence }.compact.presence,
|
||||
created_at: time(e.created_at), updated_at: time(e.updated_at) }
|
||||
end
|
||||
|
||||
def draft_batch(b, invitations: {})
|
||||
urls = Rails.application.routes.url_helpers
|
||||
{ id: b.id, aircraft_id: b.aircraft_id, status: b.status, external_ref: b.external_ref, signer_email: b.signer_email,
|
||||
held: { resolves_squawks: b.held_squawks.map { _1["id"] }, completes_inspections: b.held_inspections.map { _1["id"] } },
|
||||
entries: b.entries.sort_by(&:log_type).map do |e|
|
||||
logbook_entry(e).merge(sign_url: "#{Sso.app_url}#{urls.new_aircraft_logbook_entry_signature_path(b.aircraft_id, e)}",
|
||||
invitation_url: invitations[e.id] && "#{Sso.app_url}#{urls.invited_signing_path(invitations[e.id])}")
|
||||
end,
|
||||
completed_at: time(b.completed_at), created_at: time(b.created_at) }
|
||||
end
|
||||
|
||||
def signature(sig)
|
||||
{ signer_name: sig.signer_name, certificate_kind: sig.certificate_kind, certificate_number: sig.certificate_number,
|
||||
signed_at: time(sig.signed_at) }
|
||||
end
|
||||
|
||||
def inspection(row)
|
||||
{ inspection_type_id: row.type.id, name: row.type.name, status: row.status, next_due_date: row.next_due_date&.iso8601,
|
||||
next_due_hours: dec(row.next_due_hours), last_done: row.latest&.date&.iso8601 }
|
||||
end
|
||||
|
||||
def ad(row)
|
||||
{ airworthiness_directive_id: row.ad.id, name: row.ad.name, description: row.ad.short_description.presence,
|
||||
status: row.status, next_due_date: row.next_due_date&.iso8601, next_due_hours: dec(row.next_due_hours),
|
||||
last_complied: row.latest&.date_complied&.iso8601 }
|
||||
end
|
||||
|
||||
def dec(value) = value&.to_d&.round(1)&.to_f
|
||||
def time(value) = value&.utc&.iso8601
|
||||
end
|
||||
@@ -16,12 +16,22 @@ class AirTrailClient
|
||||
class NotFound < Error; end
|
||||
class ValidationError < Error; end # 400/422
|
||||
|
||||
def initialize(base_url:, api_key:, timeout: 20)
|
||||
# An address the server won't send to (see #address). Like a bad key, the
|
||||
# user has to fix the connection, so it's recorded there and not retried.
|
||||
class BlockedAddress < AuthError; end
|
||||
|
||||
# allow_private: may reach addresses on the private network (admins; and
|
||||
# hosts listed in AIRTRAIL_ALLOWED_HOSTS for everyone). The server itself
|
||||
# and link-local addresses (cloud metadata) are never reached.
|
||||
def initialize(base_url:, api_key:, timeout: 20, allow_private: false)
|
||||
@base = URI.parse(base_url.to_s.chomp("/"))
|
||||
@api_key = api_key
|
||||
@timeout = timeout
|
||||
@allow_private = allow_private || self.class.allowed_hosts.include?(@base.host.to_s.downcase)
|
||||
end
|
||||
|
||||
def self.allowed_hosts = ENV.fetch("AIRTRAIL_ALLOWED_HOSTS", "").split(",").map { _1.strip.downcase }.compact_blank
|
||||
|
||||
def me = request(:get, "/api/v1/me").fetch("data")
|
||||
|
||||
def search_airports(query) = request(:get, "/api/v1/airports", query: { query: query }).fetch("data")
|
||||
@@ -63,13 +73,22 @@ class AirTrailClient
|
||||
req.body = JSON.generate(body)
|
||||
end
|
||||
|
||||
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
|
||||
open_timeout: @timeout, read_timeout: @timeout) { _1.request(req) }
|
||||
handle(response)
|
||||
http = Net::HTTP.new(uri.host, uri.port)
|
||||
http.ipaddr = address(uri.host) # connect to the address that was checked (the name can't be re-pointed in between)
|
||||
http.use_ssl = uri.scheme == "https"
|
||||
http.open_timeout = http.read_timeout = @timeout
|
||||
handle(http.start { _1.request(req) })
|
||||
rescue Timeout::Error, SocketError, SystemCallError, OpenSSL::SSL::SSLError, EOFError, IOError => e
|
||||
raise NetworkError, I18n.t("services.air_trail.can_t_reach_airtrail_at", host: @base.host, message: e.message)
|
||||
end
|
||||
|
||||
# The address to connect to (see OutboundAddress).
|
||||
def address(host)
|
||||
OutboundAddress.resolve!(host, allow_private: @allow_private)
|
||||
rescue OutboundAddress::Blocked => e
|
||||
raise BlockedAddress, I18n.t("services.air_trail.blocked_#{e.reason}", host: host)
|
||||
end
|
||||
|
||||
def handle(response)
|
||||
status = response.code.to_i
|
||||
json = begin
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Checks where the server is about to send a request (AirTrail, webhooks):
|
||||
# resolves the host and returns the address to connect to, so the name can't
|
||||
# be pointed elsewhere in between. Never the server itself, link-local
|
||||
# addresses (cloud metadata) or multicast; the private network only when
|
||||
# allowed (admins, or hosts the admin listed).
|
||||
module OutboundAddress
|
||||
class Blocked < StandardError
|
||||
attr_reader :reason # :never | :private
|
||||
|
||||
def initialize(reason, host)
|
||||
@reason = reason
|
||||
super("#{host}: #{reason}")
|
||||
end
|
||||
end
|
||||
|
||||
UNREACHABLE = [ IPAddr.new("0.0.0.0/8"), IPAddr.new("::/128"), IPAddr.new("224.0.0.0/4"), IPAddr.new("ff00::/8") ].freeze
|
||||
CGNAT = IPAddr.new("100.64.0.0/10") # shared address space, e.g. Tailscale
|
||||
|
||||
# Host name → IP addresses (replaceable in tests, which have no DNS).
|
||||
mattr_accessor :resolver, default: ->(host) { Addrinfo.getaddrinfo(host, nil, nil, :STREAM).map(&:ip_address) }
|
||||
|
||||
module_function
|
||||
|
||||
def resolve!(host, allow_private:)
|
||||
ips = resolver.call(host).map { IPAddr.new(_1.sub(/%.*/, "")) }.uniq
|
||||
raise SocketError, "no address for #{host}" if ips.empty?
|
||||
ips.each do |ip|
|
||||
ip = ip.native # ::ffff:10.0.0.1 → 10.0.0.1
|
||||
raise Blocked.new(:never, host) if ip.loopback? || ip.link_local? || UNREACHABLE.any? { _1.include?(ip) }
|
||||
raise Blocked.new(:private, host) if (ip.private? || CGNAT.include?(ip)) && !allow_private
|
||||
end
|
||||
ips.first.to_s
|
||||
end
|
||||
end
|
||||
@@ -12,9 +12,10 @@ module ProceduresTemplates
|
||||
t(:sign_in, sentence: sign_in_sentence, min: User::PASSWORD_MIN, minutes: User::LOCK_FOR.in_minutes.to_i,
|
||||
tries: User::LOCK_AFTER, days: Authentication::SESSION_IDLE_TIMEOUT.in_days.to_i),
|
||||
t(Sso.enabled? ? :signing_sso : :signing),
|
||||
api_sentence,
|
||||
t(:updates),
|
||||
t(:secret_key)
|
||||
].join("\n\n")
|
||||
].compact.join("\n\n")
|
||||
end
|
||||
|
||||
def additional
|
||||
@@ -37,6 +38,13 @@ module ProceduresTemplates
|
||||
end
|
||||
end
|
||||
|
||||
# Only when the API is in use: who can reach the records through it, and that signing stays in the app.
|
||||
def api_sentence
|
||||
integrations = ApiToken.integration.active.order(:name).pluck(:name)
|
||||
return if integrations.empty? && !ApiToken.personal.active.exists?
|
||||
t(:api, integrations: integrations.any? ? t(:api_integrations, names: integrations.to_sentence) : t(:api_no_integrations))
|
||||
end
|
||||
|
||||
def docker? = File.exist?("/.dockerenv")
|
||||
|
||||
def t(key, **opts) = I18n.t(key, scope: "services.procedures_templates", **opts)
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# What happens when a squawk is reported, from the form or the API: the
|
||||
# aircraft's activity log, and a push notification to its other people when
|
||||
# it grounds the aircraft.
|
||||
module SquawkReported
|
||||
module_function
|
||||
|
||||
def call(squawk, by:)
|
||||
aircraft = squawk.aircraft
|
||||
aircraft.log_event!("squawk", I18n.t("flash.squawks.squawk_reported_2", priority_label: squawk.priority_label),
|
||||
user: by, notes: squawk.issue_reported.truncate(200))
|
||||
return unless squawk.grounding?
|
||||
PushNotifier.notify(aircraft.users.merge(User.active).where.not(id: by&.id), :grounding_squawk,
|
||||
path: Rails.application.routes.url_helpers.aircraft_squawks_path(aircraft),
|
||||
tag: "squawk-#{squawk.id}", tail: aircraft.tail_number, issue: squawk.issue_reported.truncate(120))
|
||||
end
|
||||
end
|
||||
@@ -28,7 +28,12 @@ class SystemDoctor
|
||||
|
||||
def secret_key
|
||||
return ok("Secret key", "development/test key") unless production?
|
||||
ENV["SECRET_KEY_BASE"].present? || ENV["RAILS_MASTER_KEY"].present? ? ok("Secret key", "set (keep a copy off the server)") : warning("Secret key", "SECRET_KEY_BASE isn't set in the environment")
|
||||
return warning("Secret key", "SECRET_KEY_BASE isn't set in the environment") if ENV["SECRET_KEY_BASE"].blank? && ENV["RAILS_MASTER_KEY"].blank?
|
||||
return ok("Secret key", "set (keep a copy off the server)") if ENV["SECRET_KEY_BASE"].blank?
|
||||
case SecretKeyCheck.strength
|
||||
when :ok then ok("Secret key", "set (keep a copy off the server)")
|
||||
else failed("Secret key", "only #{ENV['SECRET_KEY_BASE'].length} characters: replace it with the output of bin/rails secret")
|
||||
end
|
||||
end
|
||||
|
||||
def host
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# Tells integrations about changes (docs/api.md, "Webhooks"): each enabled
|
||||
# endpoint subscribed to the event, whose token is active and reaches the
|
||||
# aircraft, gets a delivery, sent by WebhookDeliveryJob after the change is
|
||||
# saved.
|
||||
module Webhooks
|
||||
module_function
|
||||
|
||||
def publish(event, aircraft:, data:)
|
||||
endpoints = WebhookEndpoint.enabled.joins(:api_token).merge(ApiToken.active).includes(:api_token)
|
||||
.select { _1.subscribed?(event) && Array(_1.api_token.aircraft_ids).include?(aircraft.id) }
|
||||
return if endpoints.empty?
|
||||
body = { event: event, id: SecureRandom.uuid, created_at: Time.current.utc.iso8601, aircraft_id: aircraft.id, data: data }.to_json
|
||||
endpoints.each do |endpoint|
|
||||
delivery = endpoint.deliveries.create!(event: event, payload: body)
|
||||
WebhookDeliveryJob.perform_later(delivery.id)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -20,6 +20,17 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<% if (notes = Changelog.load.release(info.version)) %>
|
||||
<%# This version's release notes; older ones are on the What's new page. %>
|
||||
<section class="card mb-5" id="whats-new">
|
||||
<div class="card-header">
|
||||
<h2 class="card-title"><%= t(".whats_new_in", version: info.version) %></h2>
|
||||
<%= link_to t(".all_releases"), help_page_path("changelog"), class: "link text-sm" %>
|
||||
</div>
|
||||
<%= guide_markdown(notes.markdown, class: "card-body") %>
|
||||
</section>
|
||||
<% end %>
|
||||
|
||||
<div class="grid gap-5 lg:grid-cols-2">
|
||||
<section class="card">
|
||||
<div class="card-header"><h2 class="card-title"><%= t(".runtime") %></h2></div>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<%= form_with model: integration, url: (integration.persisted? ? admin_integration_path(integration) : admin_integrations_path), scope: :api_token,
|
||||
class: "card card-body max-w-2xl space-y-5", data: { turbo: false } do |f| %>
|
||||
<%= f.errors_summary %>
|
||||
<% if endpoint&.errors&.any? %><div class="rounded-md bg-red-50 p-3 text-sm text-red-700"><%= endpoint.errors.full_messages.to_sentence %></div><% end %>
|
||||
<%= f.field :name, hint: t(".name_hint") %>
|
||||
<fieldset>
|
||||
<legend class="label"><%= t(".scopes") %></legend>
|
||||
<% ApiToken::SCOPES.each do |key, label| %>
|
||||
<label class="flex items-start gap-2 text-sm"><%= check_box_tag "api_token[scopes][]", key, integration.scopes.include?(key), id: "scope_#{key.parameterize}", class: "mt-1" %> <span><%= label %></span></label>
|
||||
<% end %>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend class="label"><%= t(".aircraft") %></legend>
|
||||
<p class="hint mb-1"><%= t(".aircraft_hint") %></p>
|
||||
<% Aircraft.ordered.each do |a| %>
|
||||
<label class="mr-4 inline-flex items-center gap-2 text-sm"><%= check_box_tag "api_token[aircraft_ids][]", a.id, Array(integration.aircraft_ids).include?(a.id), id: "aircraft_#{a.id}" %> <%= a.tail_number %></label>
|
||||
<% end %>
|
||||
</fieldset>
|
||||
<fieldset class="space-y-2 border-t border-slate-200 pt-4">
|
||||
<legend class="label"><%= t(".webhook") %></legend>
|
||||
<p class="hint"><%= t(".webhook_hint") %></p>
|
||||
<%= url_field_tag "webhook[url]", endpoint&.url, class: "input", placeholder: "https://redmine.example.com/sam/webhook", "aria-label": t(".webhook_url") %>
|
||||
<% WebhookEndpoint::EVENTS.each do |key, label| %>
|
||||
<label class="flex items-start gap-2 text-sm"><%= check_box_tag "webhook[events][]", key, Array(endpoint&.events).include?(key), id: "event_#{key.parameterize}", class: "mt-1" %> <span><%= label %> <code class="text-xs text-slate-500"><%= key %></code></span></label>
|
||||
<% end %>
|
||||
<% if endpoint&.persisted? %>
|
||||
<%= hidden_field_tag "webhook[enabled]", "0", id: nil %>
|
||||
<label class="flex items-center gap-2 text-sm"><%= check_box_tag "webhook[enabled]", "1", endpoint.enabled %> <%= t(".webhook_enabled") %></label>
|
||||
<% end %>
|
||||
</fieldset>
|
||||
<%= f.submit integration.persisted? ? t(".save") : t(".create"), class: "btn-primary" %>
|
||||
<% end %>
|
||||
@@ -0,0 +1,15 @@
|
||||
<% content_for :title, @integration.name %>
|
||||
<section class="card card-body max-w-xl space-y-3">
|
||||
<h1 class="card-title"><%= @integration.name %></h1>
|
||||
<p class="text-sm text-slate-600"><%= t(".copy_now") %></p>
|
||||
<% if @integration.token %>
|
||||
<label class="label" for="integration_token"><%= t(".token") %></label>
|
||||
<input id="integration_token" class="input font-mono text-sm" value="<%= @integration.token %>" readonly>
|
||||
<% end %>
|
||||
<% if @secret %>
|
||||
<label class="label" for="webhook_secret"><%= t(".webhook_secret") %></label>
|
||||
<input id="webhook_secret" class="input font-mono text-sm" value="<%= @secret %>" readonly>
|
||||
<p class="hint"><%= t(".secret_hint") %></p>
|
||||
<% end %>
|
||||
<p><%= link_to t(".done"), admin_integration_path(@integration), class: "btn-primary" %></p>
|
||||
</section>
|
||||
@@ -0,0 +1,3 @@
|
||||
<% content_for :title, @integration.name %>
|
||||
<h1 class="mb-4 text-2xl font-bold"><%= @integration.name %></h1>
|
||||
<%= render "form", integration: @integration, endpoint: @endpoint %>
|
||||
@@ -0,0 +1,17 @@
|
||||
<% content_for :title, t(".integrations") %>
|
||||
<div class="mb-4 flex items-center justify-between"><h1 class="text-2xl font-bold"><%= t(".integrations") %></h1><%= link_to t(".new_integration"), new_admin_integration_path, class: "btn-primary" %></div>
|
||||
<p class="mb-4 max-w-3xl text-sm text-slate-600"><%= t(".what_html", docs: link_to(t(".api_docs"), help_page_path("api"), class: "link")) %></p>
|
||||
<% if @integrations.any? %>
|
||||
<section class="card"><table class="table">
|
||||
<thead><tr><th><%= t(".name") %></th><th><%= t(".aircraft") %></th><th><%= t(".webhook") %></th><th><%= t(".last_used") %></th></tr></thead>
|
||||
<tbody><% @integrations.each do |i| %><tr>
|
||||
<td><%= link_to i.name, admin_integration_path(i), class: "link font-medium" %> <% if i.revoked? %><span class="badge-red"><%= t(".revoked") %></span><% end %>
|
||||
<div class="text-xs text-slate-500"><code><%= i.token_hint %>…</code></div></td>
|
||||
<td class="text-xs"><%= Aircraft.where(id: Array(i.aircraft_ids)).order(:tail_number).pluck(:tail_number).join(", ").presence || "—" %></td>
|
||||
<td class="text-xs"><%= (e = i.webhook_endpoints.first) ? e.url : "—" %></td>
|
||||
<td class="text-xs text-slate-500"><%= i.last_used_at ? t(".ago", ago: time_ago_in_words(i.last_used_at)) : t(".never") %></td>
|
||||
</tr><% end %></tbody>
|
||||
</table></section>
|
||||
<% else %>
|
||||
<%= empty_state t(".none_yet") %>
|
||||
<% end %>
|
||||
@@ -0,0 +1,3 @@
|
||||
<% content_for :title, t(".new_integration") %>
|
||||
<h1 class="mb-4 text-2xl font-bold"><%= t(".new_integration") %></h1>
|
||||
<%= render "form", integration: @integration, endpoint: @endpoint %>
|
||||
@@ -0,0 +1,49 @@
|
||||
<% content_for :title, @integration.name %>
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 class="text-2xl font-bold"><%= @integration.name %> <% if @integration.revoked? %><span class="badge-red align-middle text-sm"><%= t(".revoked") %></span><% end %></h1>
|
||||
<% unless @integration.revoked? %>
|
||||
<div class="flex gap-2">
|
||||
<%= link_to t(".edit"), edit_admin_integration_path(@integration), class: "btn-secondary" %>
|
||||
<%= button_to t(".revoke"), admin_integration_path(@integration), method: :delete, class: "btn-danger",
|
||||
form: { data: { turbo_confirm: t(".revoke_confirm", name: @integration.name) } } %>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
<div class="grid max-w-5xl items-start gap-5 lg:grid-cols-2">
|
||||
<section class="card card-body">
|
||||
<h2 class="card-title"><%= t(".token") %></h2>
|
||||
<dl class="mt-2 grid gap-y-2 text-sm">
|
||||
<div class="detail-row"><dt><%= t(".hint") %></dt><dd><code><%= @integration.token_hint %>…</code></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".scopes") %></dt><dd><%= @integration.scopes.map { ApiToken::SCOPES[_1] }.to_sentence %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".aircraft") %></dt><dd><%= Aircraft.where(id: Array(@integration.aircraft_ids)).order(:tail_number).pluck(:tail_number).join(", ").presence || "—" %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".created") %></dt><dd><%= fmt_time(@integration.created_at) %> · <%= @integration.user.display_name %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".last_used") %></dt><dd><%= @integration.last_used_at ? "#{fmt_time(@integration.last_used_at)} · #{@integration.last_used_ip}" : t(".never") %></dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
<section class="card card-body">
|
||||
<h2 class="card-title"><%= t(".webhook") %></h2>
|
||||
<% if @endpoint %>
|
||||
<dl class="mt-2 grid gap-y-2 text-sm">
|
||||
<div class="detail-row"><dt><%= t(".url") %></dt><dd class="break-all"><%= @endpoint.url %> <% unless @endpoint.enabled %><span class="badge-gray"><%= t(".paused") %></span><% end %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".events") %></dt><dd><%= @endpoint.events.map { WebhookEndpoint::EVENTS[_1] }.to_sentence %></dd></div>
|
||||
</dl>
|
||||
<% unless @integration.revoked? %>
|
||||
<div class="mt-3"><%= button_to t(".new_secret"), new_secret_admin_integration_path(@integration), class: "btn-secondary btn-sm",
|
||||
form: { data: { turbo: false, turbo_confirm: t(".new_secret_confirm") } } %></div>
|
||||
<% end %>
|
||||
<% else %>
|
||||
<p class="mt-1 text-sm text-slate-600"><%= t(".no_webhook") %></p>
|
||||
<% end %>
|
||||
</section>
|
||||
</div>
|
||||
<% if @deliveries.any? %>
|
||||
<section class="card mt-5 max-w-5xl">
|
||||
<div class="card-header"><h2 class="card-title"><%= t(".recent_deliveries") %></h2></div>
|
||||
<table class="table"><thead><tr><th><%= t(".when") %></th><th><%= t(".event") %></th><th><%= t(".result") %></th></tr></thead>
|
||||
<tbody><% @deliveries.each do |d| %><tr>
|
||||
<td class="text-xs"><%= fmt_time(d.created_at) %></td><td><code class="text-xs"><%= d.event %></code></td>
|
||||
<td class="text-xs"><span class="<%= { "delivered" => "badge-green", "failed" => "badge-red" }.fetch(d.status, "badge-gray") %>"><%= t(".status.#{d.status}") %></span>
|
||||
<%= d.response_status %> <%= d.last_error %> <% if d.attempts > 1 %>· <%= t(".attempts", count: d.attempts) %><% end %></td>
|
||||
</tr><% end %></tbody></table>
|
||||
</section>
|
||||
<% end %>
|
||||
@@ -18,8 +18,8 @@
|
||||
<% aw = aircraft.airworthiness %>
|
||||
<%= link_to aircraft_path(aircraft), class: "card block overflow-hidden transition hover:shadow-md" do %>
|
||||
<div class="flex h-36 items-center justify-center bg-slate-200">
|
||||
<% if aircraft.picture.attached? %>
|
||||
<%= image_tag aircraft.picture, class: "h-full w-full object-cover", alt: t(".photo_of", tail_number: aircraft.tail_number) %>
|
||||
<% if aircraft.picture_shown? %>
|
||||
<%= image_tag aircraft.picture_for(:card), class: "h-full w-full object-cover", loading: "lazy", alt: t(".photo_of", tail_number: aircraft.tail_number) %>
|
||||
<% else %>
|
||||
<span class="text-5xl text-slate-400" aria-hidden="true">✈</span>
|
||||
<% end %>
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<% content_for :title, t(".title") %>
|
||||
<section class="card card-body max-w-xl space-y-3">
|
||||
<h1 class="card-title"><%= t(".title") %></h1>
|
||||
<p class="text-sm text-slate-600"><%= t(".copy_now", name: @token.name) %></p>
|
||||
<input class="input font-mono text-sm" value="<%= @token.token %>" readonly aria-label="<%= t(".token") %>">
|
||||
<p class="hint"><%= t(".how_to_use_html") %></p>
|
||||
<p><%= link_to t(".done"), edit_profile_path(anchor: "api"), class: "btn-primary" %></p>
|
||||
</section>
|
||||
@@ -11,28 +11,28 @@
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
<dl class="card-body grid grid-cols-2 gap-x-4 gap-y-2 text-sm sm:grid-cols-4">
|
||||
<dt class="text-slate-500"><%= t(".manufacturer") %></dt><dd><%= @component.manufacturer %></dd>
|
||||
<dt class="text-slate-500"><%= t(".model") %></dt><dd><%= @component.model %></dd>
|
||||
<dt class="text-slate-500"><%= t(".serial") %></dt><dd><%= @component.serial_number.presence || "—" %></dd>
|
||||
<dt class="text-slate-500"><%= t(".status") %></dt><dd><%= @component.status_label %></dd>
|
||||
<dt class="text-slate-500"><%= t(".parent") %></dt><dd><%= @component.parent_component ? link_to(@component.parent_component, aircraft_component_path(@aircraft, @component.parent_component), class: "link") : "—" %></dd>
|
||||
<dt class="text-slate-500"><%= t(".location") %></dt><dd><%= @component.install_location.presence || "—" %></dd>
|
||||
<dt class="text-slate-500"><%= t(".in_service_since") %></dt><dd><%= fmt_date(@component.date_in_service) %></dd>
|
||||
<dt class="text-slate-500"><%= t(".last_oh_service") %></dt><dd><%= fmt_date(@component.overhaul_date) %></dd>
|
||||
<dt class="text-slate-500"><%= t(".hours_in_service") %></dt><dd><%= hours(@component.hours_in_service) %></dd>
|
||||
<dt class="text-slate-500"><%= t(".since_oh_service") %></dt><dd><%= hours(@component.hours_since_overhaul) %></dd>
|
||||
<dt class="text-slate-500"><%= t(".tbo") %></dt><dd><%= @component.tbo_hours ? t(".h_remaining", tbo_hours: @component.tbo_hours, hours_to_tbo: (hours(@component.hours_to_tbo))) : "—" %></dd>
|
||||
<dt class="text-slate-500"><%= t(".replacement") %></dt><dd>
|
||||
<dl class="card-body grid gap-x-8 gap-y-3 text-sm sm:grid-cols-2">
|
||||
<div class="detail-row"><dt><%= t(".manufacturer") %></dt><dd><%= @component.manufacturer %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".model") %></dt><dd><%= @component.model %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".serial") %></dt><dd><%= @component.serial_number.presence || "—" %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".status") %></dt><dd><%= @component.status_label %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".parent") %></dt><dd><%= @component.parent_component ? link_to(@component.parent_component, aircraft_component_path(@aircraft, @component.parent_component), class: "link") : "—" %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".location") %></dt><dd><%= @component.install_location.presence || "—" %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".in_service_since") %></dt><dd><%= fmt_date(@component.date_in_service) %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".last_oh_service") %></dt><dd><%= fmt_date(@component.overhaul_date) %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".hours_in_service") %></dt><dd><%= hours(@component.hours_in_service) %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".since_oh_service") %></dt><dd><%= hours(@component.hours_since_overhaul) %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".tbo") %></dt><dd><%= @component.tbo_hours ? t(".h_remaining", tbo_hours: @component.tbo_hours, hours_to_tbo: (hours(@component.hours_to_tbo))) : "—" %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".replacement") %></dt><dd>
|
||||
<%= [@component.replacement_hours && "#{@component.replacement_hours} h", @component.replacement_interval_label].compact.join(" / ").presence&.then { @component.replacement_from_install? ? t(".since_installed", interval: _1) : _1 } || "—" %>
|
||||
<% if (d = @component.next_replacement_date) %><div class="text-xs text-slate-500"><%= t(".next_by_html", d: (fmt_date(d))) %></div><% end %>
|
||||
</dd>
|
||||
<dt class="text-slate-500"><%= t(".flags") %></dt>
|
||||
<dd class="col-span-3 flex flex-wrap gap-1">
|
||||
</dd></div>
|
||||
<div class="detail-row sm:col-span-2"><dt><%= t(".flags") %></dt>
|
||||
<dd class="flex flex-wrap gap-1">
|
||||
<% { tbo_critical: t(".tbo_critical"), replacement_critical: t(".replacement_critical"), on_condition: t(".on_condition") }.each do |flag, label| %>
|
||||
<% if @component.public_send("#{flag}?") %><span class="badge-blue"><%= label %></span><% end %>
|
||||
<% end %>
|
||||
</dd>
|
||||
</dd></div>
|
||||
</dl>
|
||||
<% if @component.notes.present? %><div class="border-t border-slate-100 px-4 py-3 text-sm"><%= simple_format @component.notes %></div><% end %>
|
||||
</section>
|
||||
|
||||
@@ -13,7 +13,14 @@
|
||||
<% if current.image? %>
|
||||
<%= image_tag rails_blob_path(current, disposition: :inline), alt: current.filename.to_s, class: "max-h-[80vh] max-w-full" %>
|
||||
<% elsif current.content_type == "application/pdf" %>
|
||||
<iframe src="<%= rails_blob_path(current, disposition: :inline) %>" class="h-[80vh] w-full"></iframe>
|
||||
<% pdf_url = rails_blob_path(current, disposition: :inline) %>
|
||||
<%# Phones get the pages drawn by PDF.js; browsers with a PDF viewer of their own get it in the frame. %>
|
||||
<div class="w-full space-y-2" data-controller="pdf-viewer" data-pdf-viewer-url-value="<%= pdf_url %>" data-pdf-viewer-pdfjs-value="<%= Rails.application.config.x.pdfjs_path %>">
|
||||
<template data-pdf-viewer-target="frame"><iframe src="<%= pdf_url %>" title="<%= current.filename %>" class="h-[80vh] w-full"></iframe></template>
|
||||
<p class="p-6 text-center text-sm text-slate-500" role="status" data-pdf-viewer-target="status"><%= t("js.pdf.loading") %></p>
|
||||
<div class="space-y-2" data-pdf-viewer-target="pages"></div>
|
||||
<noscript><iframe src="<%= pdf_url %>" title="<%= current.filename %>" class="h-[80vh] w-full"></iframe></noscript>
|
||||
</div>
|
||||
<% else %>
|
||||
<p class="p-6 text-sm"><%= link_to t(".download", filename: current.filename), rails_blob_path(current, disposition: :attachment), class: "link" %></p>
|
||||
<% end %>
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<div class="card-body space-y-4">
|
||||
<p class="text-sm text-slate-600"><%= t(".review_the_entry_your_signature_html", link: (link_to t(".how_signing_works"), records_help_path, class: "link", target: "_blank")) %></p>
|
||||
<%= render "logbook_entries/content", entry: entry %>
|
||||
<%= render "logbook_entries/draft_batch", entry: entry %>
|
||||
<% if @signing_error %>
|
||||
<div class="rounded-md bg-red-50 p-3 text-sm text-red-700 ring-1 ring-red-200" role="alert"><%= @signing_error %></div>
|
||||
<% end %>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<%# One page of the activity log, in its own frame; a lazy frame after it
|
||||
loads the next page when it scrolls into view. Links open in the whole page. %>
|
||||
<%= turbo_frame_tag "events-#{page}", target: "_top", class: ["block", ("border-t border-slate-100" if page > 1)] do %>
|
||||
<%= render "events/list", events: events, full: true %>
|
||||
<% if more %>
|
||||
<% next_page = aircraft_events_path(@aircraft, category: category, page: page + 1) %>
|
||||
<%= turbo_frame_tag "events-#{page + 1}", src: next_page, loading: :lazy, target: "_top", class: "block border-t border-slate-100" do %>
|
||||
<p class="px-4 py-4 text-center text-sm text-slate-500">
|
||||
<%= t(".loading_earlier_activity_html", link: (link_to t(".load_more"), next_page, class: "link", data: { turbo_frame: "events-#{page + 1}" })) %>
|
||||
</p>
|
||||
<% end %>
|
||||
<% end %>
|
||||
<% end %>
|
||||
@@ -10,5 +10,5 @@
|
||||
<% end %>
|
||||
</div>
|
||||
</div>
|
||||
<%= render "events/list", events: @events, full: true %>
|
||||
<%= render "events/page", events: @events, page: @page, more: @more, category: @category %>
|
||||
</section>
|
||||
@@ -17,15 +17,15 @@
|
||||
<% if tail.present? && tail.upcase != @aircraft.tail_number.to_s.upcase %>
|
||||
<p class="border-b border-slate-100 bg-amber-50 px-4 py-2 text-xs text-amber-800"><%= t(".this_recording_is_from_not_html", tail: tail, tail_number: @aircraft.tail_number) %></p>
|
||||
<% end %>
|
||||
<dl class="card-body grid grid-cols-2 gap-x-4 gap-y-2 text-sm sm:grid-cols-4">
|
||||
<dt class="text-slate-500"><%= t(".recorded") %></dt>
|
||||
<dd class="col-span-3"><%= t(".monitor_time_html", start: (recording.local(recording.started_at).strftime("%Y-%m-%d %H:%M")), end: (recording.local(recording.ended_at).strftime("%H:%M"))) %>
|
||||
<span class="text-xs text-slate-500"><%= t(".samples_html", file_format: recording.format, flight_number: (" flight ##{recording.metadata[:flight_number]}" if recording.metadata[:flight_number]), samples: (number_with_delimiter(recording.samples))) %></span></dd>
|
||||
<dt class="text-slate-500"><%= t(".engine_run") %></dt><dd><%= recording.engine_start ? run_duration(recording.run_time) : t(".engine_not_run") %></dd>
|
||||
<dt class="text-slate-500"><%= t(".fuel_burned") %></dt><dd><%= engine_value(recording.fuel_burned, "gal", precision: 1) %></dd>
|
||||
<dt class="text-slate-500"><%= t(".tach") %></dt><dd class="tabular-nums"><%= hours_line.(:tach, 2) %></dd>
|
||||
<dt class="text-slate-500"><%= t(".engine_hrs") %></dt><dd class="tabular-nums"><%= hours_line.(:engine_hours, 2) %></dd>
|
||||
<% if (flt = recording.last(:flight_hours)) %><dt class="text-slate-500"><%= t(".airborne") %></dt><dd><%= flt.zero? ? t(".no_ground_run") : "#{number_with_precision(flt, precision: 2)} hrs" %></dd><% end %>
|
||||
<dl class="card-body grid gap-x-8 gap-y-3 text-sm sm:grid-cols-2">
|
||||
<div class="detail-row sm:col-span-2"><dt><%= t(".recorded") %></dt>
|
||||
<dd><%= t(".monitor_time_html", start: (recording.local(recording.started_at).strftime("%Y-%m-%d %H:%M")), end: (recording.local(recording.ended_at).strftime("%H:%M"))) %>
|
||||
<span class="text-xs text-slate-500"><%= t(".samples_html", file_format: recording.format, flight_number: (" flight ##{recording.metadata[:flight_number]}" if recording.metadata[:flight_number]), samples: (number_with_delimiter(recording.samples))) %></span></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".engine_run") %></dt><dd><%= recording.engine_start ? run_duration(recording.run_time) : t(".engine_not_run") %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".fuel_burned") %></dt><dd><%= engine_value(recording.fuel_burned, "gal", precision: 1) %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".tach") %></dt><dd class="tabular-nums"><%= hours_line.(:tach, 2) %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".engine_hrs") %></dt><dd class="tabular-nums"><%= hours_line.(:engine_hours, 2) %></dd></div>
|
||||
<% if (flt = recording.last(:flight_hours)) %><div class="detail-row"><dt><%= t(".airborne") %></dt><dd><%= flt.zero? ? t(".no_ground_run") : "#{number_with_precision(flt, precision: 2)} hrs" %></dd></div><% end %>
|
||||
</dl>
|
||||
|
||||
<div class="overflow-x-auto border-t border-slate-100">
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<%= render "shared/aircraft_header", aircraft: @aircraft %>
|
||||
<%= form_with model: [@aircraft, @flight_log], class: "card card-body space-y-5 max-w-3xl",
|
||||
data: { controller: "offline-form", offline_form_kind_value: "flight", offline_form_tail_value: @aircraft.tail_number,
|
||||
action: "submit->offline-form#submit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } do |f| %>
|
||||
action: "submit->offline-form#submit turbo:before-fetch-request->offline-form#limit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } do |f| %>
|
||||
<%= f.hidden_field :client_key, data: { offline_form_target: "key" } %>
|
||||
<div class="hidden rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200" data-offline-form-target="notice" role="status"></div>
|
||||
<%= f.errors_summary %>
|
||||
@@ -40,8 +40,8 @@
|
||||
</div>
|
||||
<p class="hint"><%= t(".saving_adds_the_tach_time") %></p>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<%= f.submit t(".log_flight") %>
|
||||
<%= f.submit t(".log_and_next_leg"), name: "next_leg", class: "btn-secondary", title: t(".log_and_next_leg_title") %>
|
||||
<%= f.submit t(".log_flight"), data: { turbo_submits_with: t(".sending") } %>
|
||||
<%= f.submit t(".log_and_next_leg"), name: "next_leg", class: "btn-secondary", title: t(".log_and_next_leg_title"), data: { turbo_submits_with: t(".sending") } %>
|
||||
<%= link_to t(".cancel"), aircraft_flight_logs_path(@aircraft), class: "btn-secondary" %>
|
||||
</div>
|
||||
<% end %>
|
||||
@@ -3,23 +3,24 @@
|
||||
<section class="card max-w-3xl">
|
||||
<div class="card-header"><h2 class="card-title"><%= t(".flight_on_html", date: (fmt_date(@flight_log.date))) %></h2>
|
||||
<% if owner? %><%= delete_button t(".delete"), aircraft_flight_log_path(@aircraft, @flight_log), confirm: t(".delete_this_flight_log_aircraft") %><% end %></div>
|
||||
<dl class="card-body grid grid-cols-2 gap-x-4 gap-y-2 text-sm sm:grid-cols-4">
|
||||
<dt class="text-slate-500"><%= t(".tach") %></dt><dd><%= hours(@flight_log.tach_time) %> <span class="text-xs text-slate-500"><%= "(#{@flight_log.tach_out} → #{@flight_log.tach_in})" if @flight_log.tach_out && @flight_log.tach_in %></span></dd>
|
||||
<dt class="text-slate-500"><%= t(".hobbs") %></dt><dd><%= hours(@flight_log.hobbs_time) %> <span class="text-xs text-slate-500"><%= "(#{@flight_log.hobbs_out} → #{@flight_log.hobbs_in})" if @flight_log.hobbs_out && @flight_log.hobbs_in %></span></dd>
|
||||
<dt class="text-slate-500"><%= t(".route") %></dt><dd class="col-span-3"><%= @flight_log.route_summary.presence || "—" %> <%= @flight_log.route %></dd>
|
||||
<dt class="text-slate-500"><%= t(".oil_added") %></dt><dd><%= @flight_log.oil_added ? "#{@flight_log.oil_added} qt #{@flight_log.oil_added_type}" : "—" %></dd>
|
||||
<dt class="text-slate-500"><%= t(".fuel_added") %></dt><dd><%= @flight_log.fuel_added ? "#{@flight_log.fuel_added} gal #{@flight_log.fuel_added_type}" : "—" %></dd>
|
||||
<dt class="text-slate-500"><%= t(".pilot") %></dt><dd><%= @flight_log.user&.display_name || "—" %></dd>
|
||||
<dt class="text-slate-500"><%= t(".track_log") %></dt><dd class="col-span-3"><%= @flight_log.track_log.attached? ? link_to(@flight_log.track_log.filename, rails_blob_path(@flight_log.track_log, disposition: :attachment), class: "link") : "—" %>
|
||||
<%# One item per row on a phone (label, then value); two columns on wider screens. %>
|
||||
<dl class="card-body grid gap-x-8 gap-y-3 text-sm sm:grid-cols-2">
|
||||
<div class="detail-row"><dt><%= t(".tach") %></dt><dd><%= hours(@flight_log.tach_time) %> <span class="text-xs text-slate-500"><%= "(#{@flight_log.tach_out} → #{@flight_log.tach_in})" if @flight_log.tach_out && @flight_log.tach_in %></span></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".hobbs") %></dt><dd><%= hours(@flight_log.hobbs_time) %> <span class="text-xs text-slate-500"><%= "(#{@flight_log.hobbs_out} → #{@flight_log.hobbs_in})" if @flight_log.hobbs_out && @flight_log.hobbs_in %></span></dd></div>
|
||||
<div class="detail-row sm:col-span-2"><dt><%= t(".route") %></dt><dd><%= @flight_log.route_summary.presence || "—" %> <%= @flight_log.route %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".oil_added") %></dt><dd><%= @flight_log.oil_added ? "#{@flight_log.oil_added} qt #{@flight_log.oil_added_type}" : "—" %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".fuel_added") %></dt><dd><%= @flight_log.fuel_added ? "#{@flight_log.fuel_added} gal #{@flight_log.fuel_added_type}" : "—" %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".pilot") %></dt><dd><%= @flight_log.user&.display_name || "—" %></dd></div>
|
||||
<div class="detail-row sm:col-span-2"><dt><%= t(".track_log") %></dt><dd class="min-w-0 break-words"><%= @flight_log.track_log.attached? ? link_to(@flight_log.track_log.filename, rails_blob_path(@flight_log.track_log, disposition: :attachment), class: "link") : "—" %>
|
||||
<% if @track %><span class="text-xs text-slate-500"> <%= t(".gps_points_html", points: (number_with_delimiter(@track.points)), max_altitude_ft: (t(".max_ft", max_altitude_ft: (number_with_delimiter(@track.max_altitude_ft))) if @track.max_altitude_ft)) %></span>
|
||||
<% elsif @track_error %><span class="text-xs text-amber-700"> · <%= @track_error %></span><% end %></dd>
|
||||
<% elsif @track_error %><span class="text-xs text-amber-700"> · <%= @track_error %></span><% end %></dd></div>
|
||||
<% if @air_trail_sync || @air_trail_connection %>
|
||||
<dt class="text-slate-500"><%= t(".airtrail") %></dt>
|
||||
<dd class="col-span-3 text-xs">
|
||||
<div class="detail-row sm:col-span-2"><dt><%= t(".airtrail") %></dt>
|
||||
<dd class="text-xs">
|
||||
<% if @air_trail_sync&.status == "synced" %><span class="badge-green"><%= t(".synced") %></span> <%= t(".ago_html", synced_at: (time_ago_in_words(@air_trail_sync.synced_at))) %>
|
||||
<% elsif @air_trail_sync&.status == "error" %><span class="badge-red"><%= t(".not_synced") %></span> <%= @air_trail_sync.last_error %>
|
||||
<% else %><span class="badge-gray"><%= t(".pending") %></span><% end %>
|
||||
</dd>
|
||||
</dd></div>
|
||||
<% end %>
|
||||
</dl>
|
||||
<% if @flight_log.notes.present? %><div class="border-t border-slate-100 px-4 py-3 text-sm"><%= simple_format @flight_log.notes %></div><% end %>
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<%# The release notes (CHANGELOG.md, see Changelog): the running version and
|
||||
any newer open, older releases folded to one line each, by month. %>
|
||||
<h1 class="mb-3 text-2xl font-bold"><%= changelog.title %></h1>
|
||||
<%= guide_markdown(changelog.intro, class: "mb-2") if changelog.intro.present? %>
|
||||
<% changelog.releases.group_by(&:month_start).each do |month, releases| %>
|
||||
<h2 class="mt-6 mb-2 text-xs font-semibold uppercase tracking-wide text-slate-500"><%= l(month, format: "%B %Y") %></h2>
|
||||
<div class="divide-y divide-slate-200 rounded-md ring-1 ring-slate-200">
|
||||
<% releases.each do |release| %>
|
||||
<details id="<%= release.anchor %>" class="group release" <%= "open" if changelog.open?(release, running: running) %>>
|
||||
<summary class="flex cursor-pointer list-none flex-wrap items-baseline gap-x-3 gap-y-1 px-4 py-3 hover:bg-slate-50 [&::-webkit-details-marker]:hidden">
|
||||
<span aria-hidden="true" class="inline-block text-xs text-slate-400 transition-transform group-open:rotate-90">▶</span>
|
||||
<h3 class="font-mono text-base font-semibold"><%= release.version %></h3>
|
||||
<% if release.version == running %><span class="badge-blue"><%= t(".this_version") %></span><% end %>
|
||||
<span class="text-sm text-slate-500"><%= release_summary(release) %></span>
|
||||
</summary>
|
||||
<%= guide_markdown(release.markdown, class: "px-4 pb-4") %>
|
||||
</details>
|
||||
<% end %>
|
||||
</div>
|
||||
<% end %>
|
||||
@@ -10,5 +10,7 @@
|
||||
aria: { current: (p == @page ? "page" : nil) } %></li><% end %>
|
||||
</ul>
|
||||
</nav>
|
||||
<article class="card card-body min-w-0 max-w-3xl"><%= guide_html(@page) %></article>
|
||||
<article class="card card-body min-w-0 max-w-3xl">
|
||||
<%= @page.slug == "changelog" ? render("help/changelog", changelog: Changelog.load, running: SystemInfo.new.version) : guide_html(@page) %>
|
||||
</article>
|
||||
</div>
|
||||
@@ -14,7 +14,8 @@
|
||||
<meta name="theme-color" content="#0f172a">
|
||||
<meta name="apple-mobile-web-app-title" content="SAM">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black">
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
|
||||
<link rel="icon" href="/favicon.ico" sizes="32x32">
|
||||
<link rel="icon" href="/favicon.svg?v=2" type="image/svg+xml">
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||
<%= stylesheet_link_tag :app, "data-turbo-track": "reload" %>
|
||||
<%= javascript_importmap_tags %>
|
||||
@@ -26,11 +27,15 @@
|
||||
<body class="min-h-full text-slate-800" data-controller="offline-sync page-age app-update<%= " offline-prep" if current_user %>"<% if current_user %> data-offline-prep-aircraft-value="<%= offline_pages.to_json %>"<% end %>>
|
||||
<%= t(".skip_to_content_html") %>
|
||||
<%# Solid and stuck to the top: iOS 26 home-screen apps then extend its color under the status bar instead of blurring it. %>
|
||||
<header class="sticky top-0 z-40 bg-header text-white">
|
||||
<%# Red when the server can't be reached; the ring shows saving for offline and sending (connection_controller.js). %>
|
||||
<header class="sticky top-0 z-40 bg-header text-white" data-controller="connection">
|
||||
<div class="mx-auto flex max-w-7xl items-center justify-between gap-4 px-4 py-3">
|
||||
<%= link_to root_path, class: "flex items-center gap-2 font-semibold tracking-tight whitespace-nowrap" do %>
|
||||
<span class="text-xl">✈</span> <span class="hidden sm:inline"><%= t(".simple_aircraft_manager") %></span><span class="sm:hidden" aria-label="<%= t(".simple_aircraft_manager") %>"><%= t(".sam") %></span>
|
||||
<% end %>
|
||||
<div class="flex items-center gap-2 sm:gap-4">
|
||||
<span class="sync-ring" role="img" hidden data-connection-target="ring"><span data-connection-target="label"></span></span>
|
||||
<span class="sr-only" role="status" data-connection-target="announce"></span>
|
||||
<% if current_user %>
|
||||
<%# Phones: Fleet, theme and one menu for the rest. %>
|
||||
<nav class="flex items-center gap-1 text-sm sm:hidden" aria-label="<%= t(".main") %>">
|
||||
@@ -45,7 +50,7 @@
|
||||
<%= link_to t(".help"), help_path, class: "block px-4 py-2.5 hover:bg-slate-100" %>
|
||||
<% if current_user.admin? %>
|
||||
<p class="border-t border-slate-100 px-4 pt-2 pb-1 text-xs font-semibold text-slate-500"><%= t(".admin") %></p>
|
||||
<% [ [ t(".users"), admin_users_path ], [ t(".component_types"), admin_component_types_path ], [ t(".airports"), admin_airports_path ], [ t(".logbook_templates"), admin_logbook_templates_path ], [ t(".settings"), edit_admin_settings_path ], [ t(".off_site_backup"), admin_offsite_backup_path ], [ t(".recordkeeping_procedures"), admin_procedures_path ], [ t(".records_audits"), admin_audits_path ], [ t(".about"), admin_about_path ] ].each do |label, path| %>
|
||||
<% [ [ t(".users"), admin_users_path ], [ t(".integrations"), admin_integrations_path ], [ t(".component_types"), admin_component_types_path ], [ t(".airports"), admin_airports_path ], [ t(".logbook_templates"), admin_logbook_templates_path ], [ t(".settings"), edit_admin_settings_path ], [ t(".off_site_backup"), admin_offsite_backup_path ], [ t(".recordkeeping_procedures"), admin_procedures_path ], [ t(".records_audits"), admin_audits_path ], [ t(".about"), admin_about_path ] ].each do |label, path| %>
|
||||
<%= link_to label, path, class: "block px-4 py-2.5 hover:bg-slate-100" %>
|
||||
<% end %>
|
||||
<% end %>
|
||||
@@ -66,7 +71,7 @@
|
||||
<%= t(".admin") %> <span aria-hidden="true" class="text-xs">▾</span>
|
||||
</summary>
|
||||
<div class="absolute right-0 z-30 mt-2 w-48 rounded-md bg-surface py-1 text-slate-700 shadow-lg ring-1 ring-slate-200">
|
||||
<% [ [ t(".users"), admin_users_path ], [ t(".component_types"), admin_component_types_path ], [ t(".airports"), admin_airports_path ], [ t(".logbook_templates"), admin_logbook_templates_path ], [ t(".settings"), edit_admin_settings_path ], [ t(".off_site_backup"), admin_offsite_backup_path ], [ t(".recordkeeping_procedures"), admin_procedures_path ], [ t(".records_audits"), admin_audits_path ], [ t(".about"), admin_about_path ] ].each do |label, path| %>
|
||||
<% [ [ t(".users"), admin_users_path ], [ t(".integrations"), admin_integrations_path ], [ t(".component_types"), admin_component_types_path ], [ t(".airports"), admin_airports_path ], [ t(".logbook_templates"), admin_logbook_templates_path ], [ t(".settings"), edit_admin_settings_path ], [ t(".off_site_backup"), admin_offsite_backup_path ], [ t(".recordkeeping_procedures"), admin_procedures_path ], [ t(".records_audits"), admin_audits_path ], [ t(".about"), admin_about_path ] ].each do |label, path| %>
|
||||
<%= link_to label, path, class: [ "block px-4 py-2 text-sm hover:bg-slate-100", ("font-semibold text-sky-700" if current_page?(path)) ] %>
|
||||
<% end %>
|
||||
</div>
|
||||
@@ -79,6 +84,7 @@
|
||||
</nav>
|
||||
<% end %>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div class="hidden bg-sky-50 px-4 py-2 text-center text-sm text-sky-900 ring-1 ring-sky-200" data-page-age-target="banner" role="status"></div>
|
||||
<div class="hidden bg-sky-50 px-4 py-2 text-center text-sm text-sky-900 ring-1 ring-sky-200" data-app-update-target="banner" role="status">
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
<meta name="theme-color" content="#0f172a">
|
||||
<meta name="apple-mobile-web-app-title" content="SAM">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black">
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
|
||||
<link rel="icon" href="/favicon.ico" sizes="32x32">
|
||||
<link rel="icon" href="/favicon.svg?v=2" type="image/svg+xml">
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||
<%= stylesheet_link_tag :app, "data-turbo-track": "reload" %>
|
||||
<%= javascript_importmap_tags %>
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<%# Always a full page load: a Turbo visit would keep the app's dark theme
|
||||
on this white page, and leave this page's styles behind on Back. %>
|
||||
<meta name="turbo-visit-control" content="reload">
|
||||
<% unless @standalone %><link rel="icon" href="/favicon.svg" type="image/svg+xml"><% end %>
|
||||
<% unless @standalone %><link rel="icon" href="/favicon.ico" sizes="32x32"><link rel="icon" href="/favicon.svg?v=2" type="image/svg+xml"><% end %>
|
||||
<%= stylesheet_link_tag :app, "data-turbo-track": "reload" %>
|
||||
<%# No Turbo here (Back is then an ordinary page load); just the Print button. %>
|
||||
<script nonce="<%= content_security_policy_nonce %>">
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
<%# An entry sent through the API as a draft: where it came from and what
|
||||
signing will do (held until every entry of the draft is signed). Locals: entry. %>
|
||||
<% batch = entry.draft_batch %>
|
||||
<% if batch %>
|
||||
<% effects = batch.awaiting? ? batch.held_effects_for(entry) : { squawks: [], inspections: [] } %>
|
||||
<div class="rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200">
|
||||
<p><%= t(".from", name: batch.api_token&.name || t(".the_api"), person: batch.created_by&.display_name || "—", ref: batch.external_ref.presence || "—") %></p>
|
||||
<% if effects[:squawks].any? || effects[:inspections].any? %>
|
||||
<p class="mt-1 font-medium"><%= t(batch.entries.size > 1 ? ".when_all_signed" : ".when_signed", count: batch.entries.size) %></p>
|
||||
<ul class="mt-1 list-disc pl-5">
|
||||
<% effects[:squawks].each do |s| %><li><%= t(".resolves", issue: s.issue_reported.truncate(120)) %></li><% end %>
|
||||
<% effects[:inspections].each do |type| %><li><%= t(".completes", name: type.name) %></li><% end %>
|
||||
</ul>
|
||||
<% end %>
|
||||
</div>
|
||||
<% end %>
|
||||
@@ -19,6 +19,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body space-y-3">
|
||||
<%= render "logbook_entries/draft_batch", entry: @entry %>
|
||||
<% if @entry.signed? %><%= render "logbook_entries/signature", entry: @entry %>
|
||||
<% elsif LogbookEntry::RECORD_TYPES.include?(@entry.entry_type) %>
|
||||
<p class="rounded-md bg-slate-50 px-3 py-2 text-sm text-slate-600 ring-1 ring-slate-200"><%= t(".not_signed_electronically_sign_it_html", supersedes: (t(".pending_correction_of_the_entry", date: (fmt_date(@entry.supersedes.date))) if @entry.supersedes)) %></p>
|
||||
|
||||
@@ -2,24 +2,24 @@
|
||||
<section class="card max-w-4xl">
|
||||
<div class="card-header"><h2 class="card-title"><%= @record.type_label %>: <%= @record.title %></h2>
|
||||
<% if owner? %><%= link_to t(".edit"), edit_aircraft_major_record_path(@aircraft, @record), class: "btn-secondary btn-sm" %><% end %></div>
|
||||
<dl class="card-body grid grid-cols-2 gap-x-4 gap-y-2 text-sm sm:grid-cols-4">
|
||||
<dt class="text-slate-500"><%= t(".date") %></dt><dd><%= fmt_date(@record.date_performed) %></dd>
|
||||
<dt class="text-slate-500"><%= t(".aircraft_hours") %></dt><dd><%= hours(@record.aircraft_hours) %></dd>
|
||||
<dt class="text-slate-500"><%= t(".performed_by") %></dt><dd><%= @record.performed_by.presence || "—" %></dd>
|
||||
<dt class="text-slate-500"><%= t(".component") %></dt><dd><%= @record.component || "—" %></dd>
|
||||
<dt class="text-slate-500"><%= t(".form_337") %></dt><dd><%= @record.form_337_document ? link_to(@record.form_337_document.name, aircraft_document_path(@aircraft, @record.form_337_document), class: "link") : "—" %></dd>
|
||||
<dt class="text-slate-500"><%= t(".stc") %></dt><dd><%= [@record.stc_number, @record.stc_holder].compact_blank.join(" · ").presence || "—" %>
|
||||
<%= link_to(t(".docs"), aircraft_document_path(@aircraft, @record.stc_document), class: "link") if @record.stc_document %></dd>
|
||||
<dt class="text-slate-500"><%= t(".logbook") %></dt><dd><%= @record.logbook_entry ? link_to(@record.logbook_entry.date, aircraft_logbook_entry_path(@aircraft, @record.logbook_entry), class: "link") : "—" %></dd>
|
||||
<dt class="text-slate-500"><%= t(".weight_balance") %></dt>
|
||||
<dl class="card-body grid gap-x-8 gap-y-3 text-sm sm:grid-cols-2">
|
||||
<div class="detail-row"><dt><%= t(".date") %></dt><dd><%= fmt_date(@record.date_performed) %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".aircraft_hours") %></dt><dd><%= hours(@record.aircraft_hours) %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".performed_by") %></dt><dd><%= @record.performed_by.presence || "—" %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".component") %></dt><dd><%= @record.component || "—" %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".form_337") %></dt><dd><%= @record.form_337_document ? link_to(@record.form_337_document.name, aircraft_document_path(@aircraft, @record.form_337_document), class: "link") : "—" %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".stc") %></dt><dd><%= [@record.stc_number, @record.stc_holder].compact_blank.join(" · ").presence || "—" %>
|
||||
<%= link_to(t(".docs"), aircraft_document_path(@aircraft, @record.stc_document), class: "link") if @record.stc_document %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".logbook") %></dt><dd><%= @record.logbook_entry ? link_to(@record.logbook_entry.date, aircraft_logbook_entry_path(@aircraft, @record.logbook_entry), class: "link") : "—" %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".weight_balance") %></dt>
|
||||
<dd>
|
||||
<% if (wb = @aircraft.weight_balance_records.where(major_record: @record).recent_first.first) %>
|
||||
<%= link_to t(".lb_in", date: fmt_date(wb.date), weight: number_with_precision(wb.empty_weight, precision: 1), arm: number_with_precision(wb.empty_arm, precision: 2)), aircraft_weight_balance_records_path(@aircraft), class: "link" %>
|
||||
<% elsif owner? %>
|
||||
<%= link_to t(".record_the_new_w_b"), new_aircraft_weight_balance_record_path(@aircraft, major_record_id: @record.id), class: "link" %>
|
||||
<% else %>—<% end %>
|
||||
</dd>
|
||||
<dt class="text-slate-500"><%= t(".icas") %></dt>
|
||||
</dd></div>
|
||||
<div class="detail-row"><dt><%= t(".icas") %></dt>
|
||||
<dd>
|
||||
<%= @record.has_ica? ? t(".yes") : t(".no") %>
|
||||
<% if (ica = @record.ica_inspection_type) %>
|
||||
@@ -28,7 +28,7 @@
|
||||
<% elsif @record.has_ica? && owner? %>
|
||||
· <%= link_to t(".add_the_ica_s_recurring"), new_aircraft_inspection_type_path(@aircraft, major_record_id: @record.id), class: "link" %>
|
||||
<% end %>
|
||||
</dd>
|
||||
</dd></div>
|
||||
</dl>
|
||||
<% [[t(".description"), @record.description], [t(".ica_notes"), @record.ica_notes], [t(".notes"), @record.notes]].each do |title, text| %>
|
||||
<% if text.present? %><div class="border-t border-slate-100 px-4 py-3 text-sm"><h3 class="mb-1 font-medium"><%= title %></h3><%= simple_format text %></div><% end %>
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<meta name="theme-color" content="#0f172a">
|
||||
<title><%= t(".title") %></title>
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
|
||||
<link rel="icon" href="/favicon.ico" sizes="32x32">
|
||||
<link rel="icon" href="/favicon.svg?v=2" type="image/svg+xml">
|
||||
<style>
|
||||
:root { --page: #f1f5f9; --surface: #fff; --text: #1e293b; --muted: #64748b; --accent: #0369a1; }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
<h1 class="mb-4 text-2xl font-bold"><%= t(".your_profile") %></h1>
|
||||
<%= form_with model: @user, url: profile_path, method: :patch, class: "card card-body space-y-4 max-w-md" do |f| %>
|
||||
<%# One column on a phone; on a wide screen, the account and its security on
|
||||
the left and everything else on the right. %>
|
||||
<div class="grid max-w-5xl items-start gap-5 lg:grid-cols-2">
|
||||
<div class="space-y-5">
|
||||
<%= form_with model: @user, url: profile_path, method: :patch, class: "card card-body space-y-4" do |f| %>
|
||||
<h2 class="card-title"><%= t(".account") %></h2>
|
||||
<%= f.errors_summary %>
|
||||
<%= f.field :name %>
|
||||
<%= f.field :email_address, as: :email, label: t(".email") %>
|
||||
@@ -23,7 +28,7 @@
|
||||
<% end %>
|
||||
|
||||
<% if Sso.enabled? %>
|
||||
<section class="card card-body mt-5 max-w-md">
|
||||
<section class="card card-body">
|
||||
<h2 class="card-title"><%= t(".single_sign_on") %></h2>
|
||||
<% if @user.sso_uid? %>
|
||||
<p class="mt-1 text-sm text-slate-600"><%= t(".your_account_is_linked_to_html", so: Sso.label) %></p>
|
||||
@@ -38,7 +43,7 @@
|
||||
</section>
|
||||
<% end %>
|
||||
|
||||
<section class="card card-body mt-5 max-w-md" id="two-factor">
|
||||
<section class="card card-body" id="two-factor">
|
||||
<h2 class="card-title"><%= t(".two_factor_sign_in") %></h2>
|
||||
<% if @user.otp_enabled? %>
|
||||
<p class="mt-1 text-sm text-slate-600"><span class="badge-green"><%= t(".on") %></span> <%= t(".since_signing_in_with_your_html", to_date: (fmt_date(@user.otp_enabled_at.to_date)), recovery_codes_left: @user.recovery_codes_left) %></p>
|
||||
@@ -53,7 +58,21 @@
|
||||
<% end %>
|
||||
</section>
|
||||
|
||||
<section class="card card-body mt-5 max-w-md" id="calendar">
|
||||
<section class="card card-body">
|
||||
<h2 class="card-title"><%= t(".sessions") %></h2>
|
||||
<% others = @user.sessions.where.not(id: Current.session.id).count %>
|
||||
<p class="mt-1 text-sm text-slate-600">
|
||||
<%= t(".you_re_signed_in_on", count: others) %>
|
||||
<%= t(".sessions_unused_for_sign_out_html", days: (Authentication::SESSION_IDLE_TIMEOUT.in_days.to_i)) %>
|
||||
</p>
|
||||
<% if others.positive? %>
|
||||
<div class="mt-3"><%= button_to t(".sign_out_everywhere_else"), other_sessions_path, method: :delete, class: "btn-secondary btn-sm" %></div>
|
||||
<% end %>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="space-y-5">
|
||||
<section class="card card-body" id="calendar">
|
||||
<h2 class="card-title"><%= t(".calendar_feed") %></h2>
|
||||
<p class="mt-1 text-sm text-slate-600"><%= t(".what_s_coming_due_on") %></p>
|
||||
<% if @user.calendar_token.present? %>
|
||||
@@ -70,7 +89,7 @@
|
||||
<% end %>
|
||||
</section>
|
||||
|
||||
<section class="card card-body mt-5 max-w-md" id="certificates">
|
||||
<section class="card card-body" id="certificates">
|
||||
<h2 class="card-title"><%= t(".certificates") %></h2>
|
||||
<p class="mt-1 text-sm text-slate-600"><%= t(".your_faa_certificates_for_signing") %></p>
|
||||
<% if @user.certificates.any? %>
|
||||
@@ -95,7 +114,7 @@
|
||||
<% end %>
|
||||
</section>
|
||||
|
||||
<section class="card card-body mt-5 max-w-md space-y-4" id="device">
|
||||
<section class="card card-body space-y-4" id="device">
|
||||
<h2 class="card-title"><%= t(".this_device") %></h2>
|
||||
<div data-controller="install">
|
||||
<h3 class="text-sm font-semibold"><%= t(".install_heading") %></h3>
|
||||
@@ -108,7 +127,7 @@
|
||||
<div data-controller="push" data-push-key-value="<%= PushKeys.public_key %>" data-push-url-value="<%= push_subscription_path %>" data-push-test-url-value="<%= test_push_subscription_path %>">
|
||||
<h3 class="text-sm font-semibold"><%= t(".notifications_heading") %></h3>
|
||||
<p class="hint"><%= t(".notifications_what") %></p>
|
||||
<p class="mt-2 text-sm text-slate-600" data-push-target="status" role="status"></p>
|
||||
<p class="mt-2 whitespace-pre-line text-sm text-slate-600" data-push-target="status" role="status"></p>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
<button type="button" class="btn-secondary btn-sm" data-push-target="on" data-action="push#turnOn" hidden><%= t(".notifications_on") %></button>
|
||||
<button type="button" class="btn-secondary btn-sm" data-push-target="off" data-action="push#turnOff" hidden><%= t(".notifications_off") %></button>
|
||||
@@ -117,22 +136,40 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card card-body mt-5 max-w-md">
|
||||
<h2 class="card-title"><%= t(".sessions") %></h2>
|
||||
<% others = @user.sessions.where.not(id: Current.session.id).count %>
|
||||
<p class="mt-1 text-sm text-slate-600">
|
||||
<%= t(".you_re_signed_in_on", count: others) %>
|
||||
<%= t(".sessions_unused_for_sign_out_html", days: (Authentication::SESSION_IDLE_TIMEOUT.in_days.to_i)) %>
|
||||
</p>
|
||||
<% if others.positive? %>
|
||||
<div class="mt-3"><%= button_to t(".sign_out_everywhere_else"), other_sessions_path, method: :delete, class: "btn-secondary btn-sm" %></div>
|
||||
<section class="card card-body" id="api">
|
||||
<h2 class="card-title"><%= t(".api_tokens") %></h2>
|
||||
<p class="mt-1 text-sm text-slate-600"><%= t(".api_tokens_what_html", docs: link_to(t(".api_docs"), help_page_path("api"), class: "link")) %></p>
|
||||
<% tokens = @user.api_tokens.personal.active.order(:created_at) %>
|
||||
<% if tokens.any? %>
|
||||
<ul class="mt-3 divide-y divide-slate-100 rounded-md ring-1 ring-slate-200">
|
||||
<% tokens.each do |token| %>
|
||||
<li class="flex flex-wrap items-center justify-between gap-2 px-3 py-2 text-sm">
|
||||
<span><span class="font-medium"><%= token.name %></span> <code class="text-xs text-slate-500"><%= token.token_hint %>…</code>
|
||||
<span class="block text-xs text-slate-500"><%= token.scopes.map { ApiToken::SCOPES[_1] }.to_sentence %> ·
|
||||
<%= token.last_used_at ? t(".api_token_used", ago: time_ago_in_words(token.last_used_at)) : t(".api_token_unused") %></span></span>
|
||||
<%= button_to t(".revoke"), api_token_path(token), method: :delete, class: "btn-secondary btn-sm",
|
||||
form: { data: { turbo_confirm: t(".revoke_token", name: token.name) } } %>
|
||||
</li>
|
||||
<% end %>
|
||||
</ul>
|
||||
<% end %>
|
||||
<%= form_with model: ApiToken.new, url: api_tokens_path, class: "mt-3 space-y-2", data: { turbo: false } do |f| %>
|
||||
<%= f.text_field :name, class: "input", placeholder: t(".api_token_name"), required: true, maxlength: 80, "aria-label": t(".api_token_name") %>
|
||||
<fieldset class="space-y-1 text-sm">
|
||||
<% ApiToken::SCOPES.each do |key, label| %>
|
||||
<label class="flex items-start gap-2"><%= check_box_tag "api_token[scopes][]", key, key == "read", id: "api_token_scope_#{key.parameterize}", class: "mt-1" %> <span><%= label %></span></label>
|
||||
<% end %>
|
||||
</fieldset>
|
||||
<%= f.submit t(".create_api_token"), class: "btn-secondary" %>
|
||||
<% end %>
|
||||
</section>
|
||||
|
||||
<section class="card card-body mt-5 max-w-md">
|
||||
<section class="card card-body">
|
||||
<h2 class="card-title"><%= t(".integrations") %></h2>
|
||||
<p class="mt-1 text-sm text-slate-600">
|
||||
<%= link_to t(".airtrail_sync"), air_trail_connection_path, class: "link" %>:
|
||||
<%= t(".push_the_flights_you_log_html", off: (current_user.air_trail_connection&.enabled? ? "on" : "off")) %>
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
@@ -9,6 +9,8 @@
|
||||
// - each aircraft's photo (put in sam-images ahead of time), shown when offline.
|
||||
// The forms and pages are saved ahead of time for all your aircraft
|
||||
// (offline_prep_controller.js), not only the ones you've opened.
|
||||
// Any other page, when the server can't be reached (no signal, or one so
|
||||
// weak nothing comes back within NETWORK_TIMEOUT), gets the offline page.
|
||||
// Nothing else is cached; signing out clears the forms and pages.
|
||||
// The version changes with every build, so a release refreshes the cached shell.
|
||||
const VERSION = "<%= j "#{SystemInfo.new.revision}-#{I18n.locale}" %>"
|
||||
@@ -24,7 +26,20 @@ const SHORTCUTS = { "/go/log-flight": "flight_logs", "/go/report-squawk": "squaw
|
||||
// A proxy in front of the app (Traefik, Authentik) answers these when the app
|
||||
// itself can't be reached: treat them like no connection.
|
||||
const UNREACHABLE = [ 502, 503, 504 ]
|
||||
const SHELL = [ "/offline", "/offline.js", "/icon.svg", "/icon-192.png" ]
|
||||
// A weak signal can leave a request hanging for minutes: give up after this.
|
||||
const NETWORK_TIMEOUT = 10 * 1000
|
||||
// Downloads made while you wait (the .sam.zip, the records package, PDFs)
|
||||
// can take longer than that to start, so they get no time limit.
|
||||
const DOWNLOADS = /\.\w+$|^\/aircraft\/\d+\/(export|records)$/
|
||||
// After a request fails, pages go straight to the kept copy or the offline
|
||||
// page for a moment instead of trying again (Turbo follows a failed visit
|
||||
// with a full page load, which would otherwise wait all over again), then
|
||||
// for a while longer wait only briefly, so moving around offline is quick.
|
||||
const RECENTLY = 5 * 1000
|
||||
const STILL_OFFLINE = 60 * 1000
|
||||
const OFFLINE_TIMEOUT = 3 * 1000
|
||||
let failedAt = 0
|
||||
const SHELL = [ "/offline", "/offline.js", "/icon.svg", "/icon-192.png", "/favicon.svg" ]
|
||||
|
||||
self.addEventListener("install", (event) => {
|
||||
event.waitUntil(caches.open(SHELL_CACHE).then((cache) => cache.addAll(SHELL)).then(() => self.skipWaiting()))
|
||||
@@ -53,18 +68,16 @@ self.addEventListener("fetch", (event) => {
|
||||
event.respondWith(keptPage(request, PAGE_CACHE))
|
||||
} else if (request.mode === "navigate" && SHORTCUTS[url.pathname]) {
|
||||
event.respondWith(shortcut(request, SHORTCUTS[url.pathname]))
|
||||
} else if (request.mode === "navigate") {
|
||||
// Always go to the network for pages; show the offline page if it's unreachable.
|
||||
event.respondWith(fetch(request)
|
||||
.then((response) => UNREACHABLE.includes(response.status) ? offlinePage() : response)
|
||||
.catch(() => offlinePage()))
|
||||
} else if (wantsHtml) {
|
||||
// Any other page comes from the network; the offline page when it's unreachable.
|
||||
event.respondWith(page(request))
|
||||
} else if (SHELL.includes(url.pathname)) {
|
||||
// The offline page's own script and icon: fresh when online, kept copy when not.
|
||||
event.respondWith(fetch(request).then((r) => r.ok ? r : caches.match(url.pathname).then((hit) => hit || r))
|
||||
.catch(() => caches.match(url.pathname)))
|
||||
} else if (url.pathname.startsWith("/assets/")) {
|
||||
event.respondWith(cachedAsset(request))
|
||||
} else if (url.pathname.startsWith("/rails/active_storage/blobs/redirect/")) {
|
||||
} else if (/^\/rails\/active_storage\/(blobs|representations)\/redirect\//.test(url.pathname)) {
|
||||
// Uploaded files come from the network; an aircraft photo saved for
|
||||
// offline use stands in when there's none.
|
||||
event.respondWith(fetch(request)
|
||||
@@ -74,17 +87,51 @@ self.addEventListener("fetch", (event) => {
|
||||
})
|
||||
|
||||
const offlinePage = () => caches.match("/offline")
|
||||
|
||||
// The network, within NETWORK_TIMEOUT. A proxy's "can't reach the app" counts
|
||||
// as no connection. Rejects when there isn't one (and remembers that).
|
||||
async function network(request) {
|
||||
const since = Date.now() - failedAt
|
||||
if (since < RECENTLY) throw new Error("offline")
|
||||
const wait = since < STILL_OFFLINE ? OFFLINE_TIMEOUT : NETWORK_TIMEOUT
|
||||
let timer
|
||||
try {
|
||||
const limit = DOWNLOADS.test(new URL(request.url).pathname) ? [] :
|
||||
[ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("timed out")), wait) }) ]
|
||||
const response = await Promise.race([ fetch(request), ...limit ])
|
||||
if (UNREACHABLE.includes(response.status)) throw new Error("unreachable")
|
||||
failedAt = 0
|
||||
return response
|
||||
} catch (error) {
|
||||
failedAt = Date.now()
|
||||
throw error
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
// A page with no kept copy. A Turbo fetch gets the error instead, so Turbo
|
||||
// falls back to a full page load, which then gets the offline page.
|
||||
async function page(request) {
|
||||
try {
|
||||
return await network(request)
|
||||
} catch (error) {
|
||||
if (request.mode !== "navigate") throw error
|
||||
return offlinePage()
|
||||
}
|
||||
}
|
||||
const savedImage = async (request, response) => {
|
||||
const key = imageKey(request.url)
|
||||
return (key && await caches.open(IMAGE_CACHE).then((c) => c.match(key))) || response || Response.error()
|
||||
}
|
||||
|
||||
// Photo links carry an expiry, so they change with every page; the saved copy
|
||||
// is filed under the upload's id instead (same rule in offline_prep_controller.js).
|
||||
// is filed under the upload's id (and size) instead (same rule in offline_prep_controller.js).
|
||||
function imageKey(url) {
|
||||
try {
|
||||
const signed = new URL(url, self.location.origin).pathname.match(/\/blobs\/redirect\/([^/]+?)--/)[1]
|
||||
return `${self.location.origin}/offline-image/${JSON.parse(atob(decodeURIComponent(signed)))._rails.data}`
|
||||
const [ , signed, size ] = new URL(url, self.location.origin).pathname.match(/\/(?:blobs|representations)\/redirect\/([^/]+?)--[^/]+\/(?:([^/]+)\/)?/)
|
||||
const id = JSON.parse(atob(decodeURIComponent(signed)))._rails.data
|
||||
return `${self.location.origin}/offline-image/${id}${size ? `/${size}` : ""}`
|
||||
} catch (_) { return null }
|
||||
}
|
||||
|
||||
@@ -113,12 +160,7 @@ async function keptPage(request, cacheName) {
|
||||
const cache = await caches.open(cacheName)
|
||||
const key = request.url.split("?")[0]
|
||||
try {
|
||||
const response = await fetch(request)
|
||||
if (UNREACHABLE.includes(response.status)) {
|
||||
const kept = await cache.match(key)
|
||||
if (kept) return kept
|
||||
return request.mode === "navigate" ? offlinePage() : response
|
||||
}
|
||||
const response = await network(request)
|
||||
const html = (response.headers.get("Content-Type") || "").includes("text/html")
|
||||
if (response.ok && !response.redirected && html) await cache.put(key, response.clone())
|
||||
return response
|
||||
@@ -135,8 +177,7 @@ async function keptPage(request, cacheName) {
|
||||
// of that kind (one aircraft), otherwise the offline page, which lists them.
|
||||
async function shortcut(request, kind) {
|
||||
try {
|
||||
const response = await fetch(request)
|
||||
if (!UNREACHABLE.includes(response.status)) return response
|
||||
return await network(request)
|
||||
} catch (_) { /* offline */ }
|
||||
const cache = await caches.open(FORM_CACHE)
|
||||
const forms = (await cache.keys()).filter((r) => new URL(r.url).pathname.includes(`/${kind}/new`))
|
||||
|
||||
@@ -3,6 +3,12 @@
|
||||
<p class="mb-4 text-sm text-slate-600"><%= t(".create_the_administrator_account_to") %></p>
|
||||
<%= form_with model: @user, url: setup_path, class: "card card-body space-y-4" do |f| %>
|
||||
<%= f.errors_summary %>
|
||||
<div>
|
||||
<%= label_tag :setup_code, t(".setup_code"), class: "label" %>
|
||||
<%= text_field_tag :setup_code, params[:setup_code], required: true, autocomplete: "off", autocapitalize: "characters", spellcheck: false,
|
||||
class: "input font-mono tracking-widest", placeholder: "XXXX-XXXX" %>
|
||||
<p class="hint"><%= t(".setup_code_hint_html") %></p>
|
||||
</div>
|
||||
<%= f.field :name %>
|
||||
<%= f.field :email_address, as: :email, label: t(".email"), required: true %>
|
||||
<%= f.field :password, as: :password, required: true, hint: t(".at_least_characters_not_one", min: User::PASSWORD_MIN) %>
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
<% aw = aircraft.airworthiness %>
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-3">
|
||||
<% if aircraft.picture.attached? %>
|
||||
<%= image_tag aircraft.picture, class: "h-12 w-12 rounded-md object-cover", alt: "" %>
|
||||
<% if aircraft.picture_shown? %>
|
||||
<%= image_tag aircraft.picture_for(:thumb), width: 48, height: 48, class: "h-12 w-12 rounded-md object-cover", alt: "" %>
|
||||
<% end %>
|
||||
<div>
|
||||
<h1 class="text-2xl font-bold tracking-tight">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<% content_for :title, @aircraft.tail_number %>
|
||||
<div class="mb-5 flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-3">
|
||||
<% if @aircraft.picture.attached? %><%= image_tag rails_blob_path(@aircraft.picture, disposition: :inline), class: "h-16 w-16 rounded-md object-cover", alt: t(".photo_of", tail_number: @aircraft.tail_number) %><% end %>
|
||||
<% if @aircraft.picture_shown? %><%= image_tag @aircraft.picture_for(:thumb), width: 64, height: 64, class: "h-16 w-16 rounded-md object-cover", alt: t(".photo_of", tail_number: @aircraft.tail_number) %><% end %>
|
||||
<div>
|
||||
<h1 class="text-2xl font-bold"><%= @aircraft.tail_number %> <span class="text-base font-normal text-slate-500"><%= [@aircraft.make, @aircraft.model].compact_blank.join(" ") %></span></h1>
|
||||
<div class="mt-1 flex flex-wrap items-center gap-2 text-sm">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<%= form_with model: [aircraft, squawk], multipart: true, class: "card card-body space-y-4 max-w-2xl",
|
||||
data: (squawk.new_record? ? { controller: "offline-form show-when", offline_form_kind_value: "squawk", offline_form_tail_value: aircraft.tail_number,
|
||||
action: "submit->offline-form#submit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } : { controller: "show-when" }) do |f| %>
|
||||
action: "submit->offline-form#submit turbo:before-fetch-request->offline-form#limit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } : { controller: "show-when" }) do |f| %>
|
||||
<% if squawk.new_record? %>
|
||||
<%= f.hidden_field :client_key, data: { offline_form_target: "key" } %>
|
||||
<div class="hidden rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200" data-offline-form-target="notice" role="status"></div>
|
||||
@@ -25,7 +25,7 @@
|
||||
<% end %>
|
||||
<% if squawk.persisted? %><%= f.field :notes, as: :textarea, rows: 3 %><% end %>
|
||||
<div class="flex gap-2">
|
||||
<%= f.submit squawk.new_record? ? t(".report_squawk") : t(".save") %>
|
||||
<%= f.submit squawk.new_record? ? t(".report_squawk") : t(".save"), data: { turbo_submits_with: t(".sending") } %>
|
||||
<%= link_to t(".cancel"), aircraft_squawks_path(aircraft), class: "btn-secondary" %>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
@@ -100,12 +100,26 @@ Rails.application.configure do
|
||||
# Only use :id for inspections in production.
|
||||
config.active_record.attributes_for_inspect = [ :id ]
|
||||
|
||||
# Enable DNS rebinding protection and other `Host` header attacks.
|
||||
# config.hosts = [
|
||||
# "example.com", # Allow requests from example.com
|
||||
# /.*\.example\.com/ # Allow requests from subdomains like `www.example.com`
|
||||
# ]
|
||||
#
|
||||
# Skip DNS rebinding protection for the default health check endpoint.
|
||||
# config.host_authorization = { exclude: ->(request) { request.path == "/up" } }
|
||||
# Answer only for the app's own names (stops DNS rebinding and forged Host
|
||||
# headers): APP_HOST, the APP_URL host, ALLOWED_HOSTS, localhost and IP
|
||||
# addresses (a rebinding attack needs a name). Off when APP_HOST isn't set.
|
||||
if ENV["APP_HOST"].present?
|
||||
config.hosts = [
|
||||
ENV["APP_HOST"].sub(/:\d+\z/, ""),
|
||||
(URI.parse(ENV["APP_URL"]).host if ENV["APP_URL"].present?),
|
||||
*ENV.fetch("ALLOWED_HOSTS", "").split(",").map(&:strip),
|
||||
"localhost",
|
||||
IPAddr.new("0.0.0.0/0"),
|
||||
IPAddr.new("::/0")
|
||||
].compact_blank
|
||||
config.host_authorization = {
|
||||
exclude: ->(request) { request.path == "/up" },
|
||||
# Say why, rather than a blank page: usually a name that's simply missing.
|
||||
response_app: ->(env) {
|
||||
host = ActionDispatch::Request.new(env).host.to_s.gsub(/[^a-z0-9.\-:\[\]]/i, "").first(253)
|
||||
[ 403, { "content-type" => "text/plain; charset=utf-8" },
|
||||
[ "This server doesn't answer for \"#{host}\". If that's a name for this app, add it to ALLOWED_HOSTS (comma-separated) and restart.\n" ] ]
|
||||
}
|
||||
}
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,8 @@
|
||||
# Uploads that claim to be images but can't be read as one (empty, corrupt,
|
||||
# or another kind of file with an image name): if resizing fails, send the
|
||||
# original rather than an error.
|
||||
Rails.application.config.to_prepare do
|
||||
ActiveStorage::Representations::BaseController.rescue_from(Vips::Error, ActiveStorage::InvariableError) do
|
||||
redirect_to Rails.application.routes.url_helpers.rails_blob_path(@blob, disposition: params[:disposition], only_path: true)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,8 @@
|
||||
# Uploaded files already answer Range requests (206), but don't say so. The
|
||||
# PDF viewer on phones (PDF.js) needs "Accept-Ranges: bytes" to fetch only
|
||||
# the parts of a PDF for the pages being looked at, instead of all of it.
|
||||
Rails.application.config.to_prepare do
|
||||
ActiveStorage::DiskController.after_action(only: :show) do
|
||||
response.headers["Accept-Ranges"] = "bytes" if response.successful?
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,7 @@
|
||||
# PDF.js (pdfjs-dist from npm, Apache-2.0) draws PDFs in the document viewer
|
||||
# on phones, which can't show them in a frame. Its files live in
|
||||
# public/pdfjs/<version>/ undigested, because it loads its decoders and fonts
|
||||
# by name; the version in the path keeps the year-long cache safe.
|
||||
# To update: copy build/pdf.min.mjs, build/pdf.worker.min.mjs, LICENSE, iccs/,
|
||||
# standard_fonts/ and wasm/ (minus quickjs) into a new folder and change this.
|
||||
Rails.application.config.x.pdfjs_path = "/pdfjs/6.5.438/"
|
||||
@@ -0,0 +1,5 @@
|
||||
# Refuse to run in production with a guessable secret key (see SecretKeyCheck).
|
||||
# Skipped for the image build's asset step, which uses a throwaway key.
|
||||
if Rails.env.production? && ENV["SECRET_KEY_BASE"].present? && ENV["SECRET_KEY_BASE_DUMMY"].blank?
|
||||
Rails.application.config.after_initialize { SecretKeyCheck.verify! }
|
||||
end
|
||||
+174
-2
@@ -4,7 +4,34 @@
|
||||
# a controller name are its views (t(".key") in the view).
|
||||
|
||||
en:
|
||||
api:
|
||||
draft_batches:
|
||||
sent:
|
||||
one: "Draft logbook entry sent by %{name} for signing"
|
||||
other: "%{count} draft logbook entries sent by %{name} for signing"
|
||||
api_tokens:
|
||||
created:
|
||||
title: Your new API token
|
||||
copy_now: "Copy the token for %{name} now: it isn't shown again (only its first characters are kept, to tell tokens apart)."
|
||||
token: API token
|
||||
how_to_use_html: 'Send it with each request: <code>Authorization: Bearer <token></code>. See the API reference in Help.'
|
||||
done: Done
|
||||
labels:
|
||||
api_token:
|
||||
scopes:
|
||||
read: Read aircraft, parts, due items, squawks and logbook entries
|
||||
'squawks:write': Report and update squawks
|
||||
'drafts:write': Send draft logbook entries for signing (acting for an owner of the aircraft)
|
||||
webhook_endpoint:
|
||||
events:
|
||||
squawk:
|
||||
created: A squawk is reported
|
||||
updated: A squawk is changed
|
||||
resolved: A squawk is resolved
|
||||
entry:
|
||||
signed: A logbook entry is signed
|
||||
draft_batch:
|
||||
completed: All the entries of a draft are signed (and what it resolves is done)
|
||||
aircraft:
|
||||
statuses:
|
||||
AVAILABLE: Available
|
||||
@@ -286,6 +313,10 @@ en:
|
||||
signed_locked: This entry is signed, so it can't be changed. Make a correction entry instead
|
||||
squawk:
|
||||
confirm: 'Confirm: %{check}'
|
||||
api_token:
|
||||
attributes:
|
||||
kind:
|
||||
admins_only: "integration tokens can only be made by an administrator"
|
||||
ad_compliance:
|
||||
needs_owner: Must belong to an aircraft or component
|
||||
attributes:
|
||||
@@ -301,6 +332,7 @@ en:
|
||||
attributes:
|
||||
parent_component:
|
||||
itself: can't be itself
|
||||
own_part: can't be one of its own parts
|
||||
other_aircraft: must be on the same aircraft
|
||||
user:
|
||||
attributes:
|
||||
@@ -704,6 +736,14 @@ en:
|
||||
envelope_weights: Envelope weights must be more than 0
|
||||
fuel_weight: Fuel weight per gallon must be between 4 and 9 lb
|
||||
flash:
|
||||
admin_integrations:
|
||||
saved: Integration saved.
|
||||
revoked: "%{name} revoked: its token no longer works and its webhook is stopped."
|
||||
api_tokens:
|
||||
revoked: Token revoked. Programs using it can no longer connect.
|
||||
push_subscriptions:
|
||||
not_saved: "This browser's push service (%{host}) isn't one the app sends to."
|
||||
unknown_device: Unknown browser
|
||||
sign_in_links:
|
||||
try_again_later: Try again later.
|
||||
try_again_later_2: Try again later.
|
||||
@@ -826,6 +866,8 @@ en:
|
||||
unreachable: couldn't reach or verify %{provider}; see the server log
|
||||
setup:
|
||||
welcome_you_re_the: Welcome! You're the administrator. Add your first aircraft.
|
||||
wrong_code: That setup code isn't right. It's in the server's log, on the line starting "Setup code".
|
||||
try_again_later: Too many tries. Wait a few minutes and try again.
|
||||
invited_signings:
|
||||
try_again_later: Try again later.
|
||||
sign_in_to_continue: Sign in to continue.
|
||||
@@ -914,6 +956,7 @@ en:
|
||||
certificate_removed: Certificate removed.
|
||||
application:
|
||||
admins_only: Admins only.
|
||||
invalid_input: Something in that form couldn't be saved. Check what you entered and try again.
|
||||
oil_analyses:
|
||||
oil_analysis_saved: Oil analysis saved.
|
||||
choose_a_lab_report: Choose a lab report PDF.
|
||||
@@ -1173,6 +1216,69 @@ en:
|
||||
matches: Matches
|
||||
update: Update
|
||||
admin:
|
||||
integrations:
|
||||
show:
|
||||
revoked: Revoked
|
||||
edit: Edit
|
||||
revoke: Revoke
|
||||
revoke_confirm: "Revoke %{name}? Its token stops working at once and its webhook stops. This can't be undone; make a new integration to reconnect."
|
||||
token: Token
|
||||
hint: Starts with
|
||||
scopes: May
|
||||
aircraft: Aircraft
|
||||
created: Created
|
||||
last_used: Last used
|
||||
never: never
|
||||
webhook: Webhook
|
||||
url: Address
|
||||
paused: Paused
|
||||
events: Events
|
||||
new_secret: New secret
|
||||
new_secret_confirm: "Make a new webhook secret? The other system needs the new one; webhooks signed with the old one will fail its check."
|
||||
no_webhook: "None: the system only calls the API."
|
||||
recent_deliveries: Recent webhooks
|
||||
when: When
|
||||
event: Event
|
||||
result: Result
|
||||
attempts:
|
||||
one: "%{count} attempt"
|
||||
other: "%{count} attempts"
|
||||
status:
|
||||
pending: Pending
|
||||
delivered: Delivered
|
||||
failed: Failed
|
||||
created:
|
||||
copy_now: "Copy these now: they aren't shown again."
|
||||
token: API token
|
||||
webhook_secret: Webhook secret
|
||||
secret_hint: The other system checks each webhook with it (see the API reference).
|
||||
done: Done
|
||||
new:
|
||||
new_integration: New integration
|
||||
form:
|
||||
name_hint: The system it's for, e.g. Redmine.
|
||||
scopes: What it may do
|
||||
aircraft: Aircraft it may reach
|
||||
aircraft_hint: When it acts for a person, only those of these aircraft that person can see.
|
||||
webhook: Webhook (optional)
|
||||
webhook_hint: "Where to post changes. Each post is signed with a secret shown once after saving (header SAM-Signature)."
|
||||
webhook_url: Webhook address
|
||||
webhook_enabled: Send webhooks
|
||||
save: Save
|
||||
create: Create integration
|
||||
index:
|
||||
integrations: Integrations
|
||||
new_integration: New integration
|
||||
what_html: "Let another system, such as Redmine, work with the aircraft through the REST API (%{docs}). Each integration has its own token, limited to the aircraft and actions you choose; its changes name the person they're for, so the record history shows who. It can be told about changes by webhook."
|
||||
api_docs: API reference
|
||||
name: Name
|
||||
aircraft: Aircraft
|
||||
webhook: Webhook
|
||||
last_used: Last used
|
||||
revoked: Revoked
|
||||
ago: "%{ago} ago"
|
||||
never: never
|
||||
none_yet: No integrations yet.
|
||||
about:
|
||||
show:
|
||||
about: About
|
||||
@@ -1181,6 +1287,8 @@ en:
|
||||
this_commit_on_github: This commit on GitHub
|
||||
build_html: Build %{build}
|
||||
what_s_new: What's new
|
||||
whats_new_in: What's new in %{version}
|
||||
all_releases: All releases
|
||||
disclaimer: Disclaimer
|
||||
source_code: Source code
|
||||
built: Built
|
||||
@@ -2165,6 +2273,9 @@ en:
|
||||
ago_html: "%{who} · %{created_at} ago"
|
||||
no_activity_yet: No activity yet.
|
||||
system: System
|
||||
page:
|
||||
load_more: Load more
|
||||
loading_earlier_activity_html: Loading earlier activity… %{link}
|
||||
flight_imports:
|
||||
new:
|
||||
import_flights: Import Flights
|
||||
@@ -2292,6 +2403,7 @@ en:
|
||||
oil_qt: Oil (qt)
|
||||
no_flights_logged_yet: No flights logged yet.
|
||||
new:
|
||||
sending: Sending…
|
||||
log_flight: Log Flight
|
||||
from: From
|
||||
koqu: KOQU
|
||||
@@ -2375,6 +2487,21 @@ en:
|
||||
past_30_days: Past 30 days
|
||||
this_year: This year
|
||||
help:
|
||||
changelog:
|
||||
this_version: This version
|
||||
counts:
|
||||
changes:
|
||||
one: 1 change
|
||||
other: "%{count} changes"
|
||||
fixes:
|
||||
one: 1 fix
|
||||
other: "%{count} fixes"
|
||||
administrators:
|
||||
one: 1 for administrators
|
||||
other: "%{count} for administrators"
|
||||
notes:
|
||||
one: 1 note
|
||||
other: "%{count} notes"
|
||||
show:
|
||||
help: 'Help: %{title}'
|
||||
help_pages: Help pages
|
||||
@@ -2464,6 +2591,7 @@ en:
|
||||
sign_out: Sign out
|
||||
layouts:
|
||||
application:
|
||||
integrations: Integrations
|
||||
skip_to_content_html: <a href="#main" class="skip-link">Skip to content</a>
|
||||
simple_aircraft_manager: Simple Aircraft Manager
|
||||
sam: SAM
|
||||
@@ -2524,6 +2652,13 @@ en:
|
||||
cg_in: "= CG (in)"
|
||||
cg_in_2: CG (in)
|
||||
logbook_entries:
|
||||
draft_batch:
|
||||
from: "Draft sent through %{name} for %{person} (their reference: %{ref})."
|
||||
the_api: the API
|
||||
when_signed: "When you sign it, this also:"
|
||||
when_all_signed: "When all %{count} entries of this draft are signed, this also:"
|
||||
resolves: "Resolves the squawk: %{issue}"
|
||||
completes: "Records the %{name} as completed"
|
||||
component_fields:
|
||||
component: Component
|
||||
for_engine_and_propeller_logs: 'For engine and propeller logs: printed with its serial number and times.'
|
||||
@@ -2939,7 +3074,17 @@ en:
|
||||
subject: Reset your password
|
||||
profiles:
|
||||
edit:
|
||||
revoke: Revoke
|
||||
api_tokens: API tokens
|
||||
api_tokens_what_html: "Keys for scripts and other programs to read your aircraft and report squawks through the REST API, acting as you (%{docs}). Treat a token like a password: anyone who has it can do what it allows."
|
||||
api_docs: API reference
|
||||
api_token_used: used %{ago} ago
|
||||
api_token_unused: never used
|
||||
revoke_token: "Revoke %{name}? Programs using it stop working."
|
||||
api_token_name: Name (what it's for)
|
||||
create_api_token: Create token
|
||||
your_profile: Your Profile
|
||||
account: Account
|
||||
email: Email
|
||||
weekly_maintenance_reminders: Weekly maintenance reminders
|
||||
a_monday_email_about_overdue: A Monday email about overdue and upcoming inspections, ADs, parts and documents on aircraft you own, and certificates of yours about to expire. Only sent when something needs attention.
|
||||
@@ -3105,6 +3250,8 @@ en:
|
||||
new:
|
||||
welcome: Welcome
|
||||
create_the_administrator_account_to: Create the administrator account to get started.
|
||||
setup_code: Setup code
|
||||
setup_code_hint_html: 'Shown in the server''s log, so only whoever runs the server can finish setup. With Docker: <code>docker compose logs web | grep "Setup code"</code>'
|
||||
email: Email
|
||||
at_least_characters_not_one: At least %{min} characters; not one known from a data breach.
|
||||
simple_aircraft_manager_is_provided: Simple Aircraft Manager is provided as is, without warranty, and is not approved by the FAA or any other aviation authority. It is up to you to verify that using it for your aircraft and operation is legal and suitable. The full disclaimer is under Help once you're signed in.
|
||||
@@ -3253,6 +3400,7 @@ en:
|
||||
edit:
|
||||
edit_squawk: Edit Squawk
|
||||
form:
|
||||
sending: Sending…
|
||||
ground_aircraft_makes_the_aircraft: "“Ground Aircraft” makes the aircraft not airworthy until resolved."
|
||||
issue: Issue
|
||||
component_optional: Component (optional)
|
||||
@@ -3496,6 +3644,9 @@ en:
|
||||
aircraft_grounded_error:
|
||||
message: Aircraft is grounded and airworthiness enforcement is enabled
|
||||
procedures_templates:
|
||||
api: "**Programs that use the records (API).** %{integrations} Each has its own key, limited to chosen aircraft and actions, which the administrator can revoke at any time; the system records when each key was last used and from where, and every change made through it is in the record history with the key and the person it was for. Through the API, another program can read records, report squawks and send draft logbook entries; it cannot sign an entry, change or delete a signed one, or change users, roles or the record history. Draft entries are reviewed and signed in the system by the person certifying the work, and the squawks or inspections they resolve take effect only once signed. [Describe what each program is used for and who looks after it.]"
|
||||
api_integrations: "The following programs are connected: %{names}."
|
||||
api_no_integrations: "No other systems are connected; users may make personal keys for their own scripts, which act with their own access."
|
||||
server: "**Server.** The system runs %{location} at [location, e.g. the owner's home or a hosting provider]. Its data (the database, the uploaded files and the nightly verified database copies) is on that server's storage volume. Only [the owner] has administrative access to the server."
|
||||
server_docker: as a Docker container on a server
|
||||
server_plain: on a server
|
||||
@@ -3667,6 +3818,8 @@ en:
|
||||
signed_event: Logbook entry signed electronically (%{date})
|
||||
air_trail:
|
||||
can_t_reach_airtrail_at: 'Can''t reach AirTrail at %{host}: %{message}'
|
||||
blocked_never: "%{host} is this server or a link-local address, which AirTrail can't be."
|
||||
blocked_private: "%{host} is on the private network. Ask an administrator to connect it, or to list it in AIRTRAIL_ALLOWED_HOSTS."
|
||||
airtrail_username_must_be_3: AirTrail username must be 3–20 letters, numbers, “.”, “_” or “-”
|
||||
aircraft_type_must_be_an: Aircraft type must be an ICAO type designator like C150 (up to 4 letters/numbers)
|
||||
no_flights_to_export: No flights to export
|
||||
@@ -3790,6 +3943,20 @@ en:
|
||||
not_entries: 'Not logbook entries (forms, tags…), so nothing was transcribed from: %{pages}.'
|
||||
unreadable: 'Too hard to read: %{pages}.'
|
||||
js:
|
||||
connection:
|
||||
offline: "Offline: can't reach the server. Pages saved for offline use still work."
|
||||
back_online: Back online.
|
||||
saving: "Saving for offline use: %{percent}%"
|
||||
sending: "Sending what was logged offline: %{percent}%"
|
||||
waiting:
|
||||
one: "%{count} logged offline, waiting to send"
|
||||
other: "%{count} logged offline, waiting to send"
|
||||
pdf:
|
||||
loading: Loading the PDF…
|
||||
page: Page %{page} of %{pages}
|
||||
page_failed: This page couldn't be shown.
|
||||
failed: This PDF can't be shown here.
|
||||
open: Open it
|
||||
airports:
|
||||
not_found: Not in the airport database
|
||||
wb:
|
||||
@@ -3876,8 +4043,13 @@ en:
|
||||
blocked: Notifications are blocked for this site in the browser's settings.
|
||||
unsupported: This browser can't show notifications from the app.
|
||||
ios_install_first: On iPhone and iPad, install the app first (above); notifications can then be turned on in it.
|
||||
failed: Couldn't turn notifications on. Try again.
|
||||
test_sent: Test notification sent; it should arrive in a few seconds.
|
||||
failed: "Couldn't turn notifications on: %{reason}"
|
||||
not_saved: "Notifications are on in this browser, but the app couldn't record it: %{reason}"
|
||||
test_sending: Sending…
|
||||
test_none: No device has notifications on. Turn them on again here.
|
||||
test_ok: "%{device}: sent"
|
||||
test_failed: "%{device}: not sent (%{reason})"
|
||||
test_hint: Sent ones should arrive within a few seconds. If this device's doesn't, check that notifications are allowed for the app in the phone's settings.
|
||||
hours:
|
||||
tach: Tach %{from} → %{to} (%{delta})
|
||||
hobbs: Hobbs %{from} → %{to} (%{delta})
|
||||
|
||||
@@ -18,6 +18,9 @@ production:
|
||||
purge_abandoned_uploads:
|
||||
command: "ActiveStorage::Blob.unattached.where(created_at: ..2.days.ago).find_each(&:purge_later)"
|
||||
schedule: every day at 4am <%= zone %>
|
||||
purge_api_records:
|
||||
command: "ApiIdempotencyKey.purge_old; WebhookDelivery.purge_old"
|
||||
schedule: every day at 4:15am <%= zone %>
|
||||
dedupe_storage:
|
||||
command: "ActiveStorage::Blob.service.try(:sweep)"
|
||||
schedule: every day at 4:30am <%= zone %>
|
||||
|
||||
@@ -27,6 +27,7 @@ Rails.application.routes.draw do
|
||||
# Home-screen shortcuts: the form for your aircraft, or a choice of aircraft.
|
||||
get "go/log-flight", to: "shortcuts#log_flight", as: :log_flight_shortcut
|
||||
get "go/report-squawk", to: "shortcuts#report_squawk", as: :report_squawk_shortcut
|
||||
resources :api_tokens, path: "profile/api_tokens", only: %i[create destroy]
|
||||
resources :certificates, path: "profile/certificates", controller: "user_certificates", only: %i[create update destroy]
|
||||
resource :air_trail_connection, path: "profile/airtrail", only: %i[show create update destroy] do
|
||||
post :test
|
||||
@@ -171,12 +172,37 @@ Rails.application.routes.draw do
|
||||
post "about/test_reminder", to: "about#test_reminder", as: :test_reminder
|
||||
post "about/check_records", to: "about#check_records", as: :check_records
|
||||
resources :users, except: :show
|
||||
resources :integrations do
|
||||
post :new_secret, on: :member
|
||||
end
|
||||
resources :component_types, except: :show
|
||||
resources :airports, except: :show do
|
||||
collection { post :refresh }
|
||||
end
|
||||
end
|
||||
|
||||
# REST API (docs/api.md): bearer tokens, JSON.
|
||||
namespace :api, defaults: { format: :json } do
|
||||
namespace :v1 do
|
||||
get "me", to: "me#show"
|
||||
resources :aircraft, only: %i[index show] do
|
||||
member do
|
||||
get :components
|
||||
get :due
|
||||
get :inspections
|
||||
get :ads
|
||||
get :logbook_entries
|
||||
end
|
||||
resources :squawks, only: %i[index create]
|
||||
resources :draft_batches, only: %i[index create]
|
||||
end
|
||||
get "squawks", to: "squawks#lookup"
|
||||
resources :squawks, only: %i[show update]
|
||||
get "draft_batches", to: "draft_batches#lookup"
|
||||
resources :draft_batches, only: %i[show destroy]
|
||||
end
|
||||
end
|
||||
|
||||
get "up" => "rails/health#show", as: :rails_health_check
|
||||
get "manifest" => "rails/pwa#manifest", as: :pwa_manifest
|
||||
get "offline" => "offline#show", as: :offline
|
||||
|
||||
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user