mirror of
https://github.com/rickbarrette/simple-aircraft-manager-rails.git
synced 2026-11-17 23:50:36 -05:00
Log flights offline: the form is kept by the service worker, flights queue on the device (IndexedDB) and send when back online; one-time keys prevent duplicates
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
08ba017c7e
commit
191eb030e8
14 files changed
+314
-14
No files matched your search
@@ -55,6 +55,10 @@ class FlightLogsController < ApplicationController
|
|||||||
end
|
end
|
||||||
|
|
||||||
def create
|
def create
|
||||||
|
# Already received (sent again from the offline queue): don't log it twice.
|
||||||
|
if (key = params.dig(:flight_log, :client_key).to_s.presence) && @aircraft.flight_logs.exists?(client_key: key.first(64))
|
||||||
|
return redirect_to(aircraft_flight_logs_path(@aircraft), notice: "Flight already logged.")
|
||||||
|
end
|
||||||
@flight_log = @aircraft.flight_logs.new(flight_log_params)
|
@flight_log = @aircraft.flight_logs.new(flight_log_params)
|
||||||
if @flight_log.valid?
|
if @flight_log.valid?
|
||||||
HoursService.new(@aircraft).log_flight!(@flight_log)
|
HoursService.new(@aircraft).log_flight!(@flight_log)
|
||||||
@@ -111,7 +115,7 @@ class FlightLogsController < ApplicationController
|
|||||||
params.require(:flight_log).permit(
|
params.require(:flight_log).permit(
|
||||||
:date, :tach_time, :tach_out, :tach_in, :hobbs_time, :hobbs_out, :hobbs_in,
|
:date, :tach_time, :tach_out, :tach_in, :hobbs_time, :hobbs_out, :hobbs_in,
|
||||||
:departure_location, :destination_location, :route, :oil_added, :oil_added_type,
|
:departure_location, :destination_location, :route, :oil_added, :oil_added_type,
|
||||||
:oil_level_after, :fuel_added, :fuel_added_type, :fuel_level_after, :notes, :track_log, :engine_data
|
:oil_level_after, :fuel_added, :fuel_added_type, :fuel_level_after, :notes, :track_log, :engine_data, :client_key
|
||||||
)
|
).tap { _1[:client_key] = _1[:client_key].to_s.first(64).presence if _1.key?(:client_key) }
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { Controller } from "@hotwired/stimulus"
|
||||||
|
import { queue, formFields, newKey } from "controllers/offline_queue"
|
||||||
|
|
||||||
|
// The Log Flight form: with no connection, the flight is kept on this device
|
||||||
|
// and sent later (see offline_sync_controller). The next leg starts where the
|
||||||
|
// last saved one ended.
|
||||||
|
export default class extends Controller {
|
||||||
|
static targets = [ "key", "notice" ]
|
||||||
|
static values = { tail: String }
|
||||||
|
|
||||||
|
async connect() {
|
||||||
|
if (!this.keyTarget.value) this.keyTarget.value = newKey()
|
||||||
|
try {
|
||||||
|
const mine = (await queue.all()).filter((i) => i.url === this.element.action)
|
||||||
|
if (mine.length) {
|
||||||
|
this.prefillFrom(mine[mine.length - 1])
|
||||||
|
this.say(`${mine.length} flight${mine.length > 1 ? "s" : ""} logged offline on this device, waiting to send. This one starts where the last ended.`)
|
||||||
|
}
|
||||||
|
} catch (_) { /* no IndexedDB: nothing queued */ }
|
||||||
|
this.rememberForm()
|
||||||
|
}
|
||||||
|
|
||||||
|
// No connection: keep it here instead of submitting.
|
||||||
|
async submit(event) {
|
||||||
|
if (navigator.onLine) return
|
||||||
|
event.preventDefault()
|
||||||
|
event.stopImmediatePropagation()
|
||||||
|
await this.save(formFields(this.element))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kept in case the request fails on the way (no signal but the browser thinks it's online).
|
||||||
|
remember() { this.pending = formFields(this.element) }
|
||||||
|
|
||||||
|
async networkFailed() {
|
||||||
|
if (this.pending) await this.save(this.pending)
|
||||||
|
}
|
||||||
|
|
||||||
|
async save(fields) {
|
||||||
|
const item = { id: this.keyTarget.value, url: this.element.action, tail: this.tailValue, savedAt: new Date().toISOString(), fields }
|
||||||
|
try {
|
||||||
|
await queue.add(item)
|
||||||
|
} catch (_) {
|
||||||
|
this.say("No connection, and this browser can't store the flight. Write it down and log it when you're back online.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.prefillFrom(item)
|
||||||
|
this.clearLegFields()
|
||||||
|
this.keyTarget.value = newKey()
|
||||||
|
this.pending = null
|
||||||
|
window.scrollTo({ top: 0 })
|
||||||
|
this.say("No connection: flight saved on this device. It's sent automatically when you're back online. Log the next leg below, or close the app.")
|
||||||
|
document.dispatchEvent(new CustomEvent("offline-queue:changed"))
|
||||||
|
}
|
||||||
|
|
||||||
|
prefillFrom(item) {
|
||||||
|
const value = (name) => (item.fields.find(([ n ]) => n === `flight_log[${name}]`) || [])[1]
|
||||||
|
const set = (name, v) => { const el = this.element.querySelector(`[name="flight_log[${name}]"]`); if (el && v) el.value = v }
|
||||||
|
set("tach_out", value("tach_in"))
|
||||||
|
set("hobbs_out", value("hobbs_in"))
|
||||||
|
set("departure_location", value("destination_location"))
|
||||||
|
}
|
||||||
|
|
||||||
|
clearLegFields() {
|
||||||
|
for (const name of [ "tach_in", "tach_time", "hobbs_in", "hobbs_time", "destination_location", "route", "notes",
|
||||||
|
"oil_added", "oil_level_after", "fuel_added", "fuel_level_after", "track_log", "engine_data" ]) {
|
||||||
|
const el = this.element.querySelector(`[name="flight_log[${name}]"]`)
|
||||||
|
if (el) el.value = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lets the offline page offer this form for this aircraft.
|
||||||
|
rememberForm() {
|
||||||
|
try {
|
||||||
|
const forms = JSON.parse(localStorage.getItem("sam-offline-forms") || "{}")
|
||||||
|
forms[location.pathname] = this.tailValue
|
||||||
|
localStorage.setItem("sam-offline-forms", JSON.stringify(forms))
|
||||||
|
} catch (_) { /* storage off */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
say(text) {
|
||||||
|
this.noticeTarget.textContent = text
|
||||||
|
this.noticeTarget.classList.remove("hidden")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// Flights logged without a connection, kept in this browser (IndexedDB, so
|
||||||
|
// attached track and engine files are kept too) until they can be sent.
|
||||||
|
const DB = "sam-offline"
|
||||||
|
const STORE = "flights"
|
||||||
|
|
||||||
|
function open() {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const req = indexedDB.open(DB, 1)
|
||||||
|
req.onupgradeneeded = () => req.result.createObjectStore(STORE, { keyPath: "id" })
|
||||||
|
req.onsuccess = () => resolve(req.result)
|
||||||
|
req.onerror = () => reject(req.error)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function run(mode, fn) {
|
||||||
|
const db = await open()
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const tx = db.transaction(STORE, mode)
|
||||||
|
const result = fn(tx.objectStore(STORE))
|
||||||
|
tx.oncomplete = () => resolve(result && "result" in result ? result.result : undefined)
|
||||||
|
tx.onerror = () => reject(tx.error)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// item: { id, url, tail, savedAt, fields: [[name, value]], error }
|
||||||
|
export const queue = {
|
||||||
|
add: (item) => run("readwrite", (s) => s.put(item)),
|
||||||
|
put: (item) => run("readwrite", (s) => s.put(item)),
|
||||||
|
remove: (id) => run("readwrite", (s) => s.delete(id)),
|
||||||
|
all: async () => ((await run("readonly", (s) => s.getAll())) || []).sort((a, b) => a.savedAt.localeCompare(b.savedAt)),
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formFields(form) {
|
||||||
|
return [ ...new FormData(form).entries() ].filter(([ name, value ]) => !(value instanceof File && value.size === 0) && name !== "authenticity_token")
|
||||||
|
}
|
||||||
|
|
||||||
|
export function newKey() {
|
||||||
|
return (crypto.randomUUID && crypto.randomUUID()) || `${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import { Controller } from "@hotwired/stimulus"
|
||||||
|
import { queue } from "controllers/offline_queue"
|
||||||
|
|
||||||
|
// On every page: sends flights logged offline once there's a connection, and
|
||||||
|
// says what happened. A rejected flight stays until it's discarded.
|
||||||
|
export default class extends Controller {
|
||||||
|
static targets = [ "banner" ]
|
||||||
|
|
||||||
|
connect() {
|
||||||
|
this.sync = this.sync.bind(this)
|
||||||
|
window.addEventListener("online", this.sync)
|
||||||
|
document.addEventListener("offline-queue:changed", this.sync)
|
||||||
|
this.sync()
|
||||||
|
}
|
||||||
|
|
||||||
|
disconnect() {
|
||||||
|
window.removeEventListener("online", this.sync)
|
||||||
|
document.removeEventListener("offline-queue:changed", this.sync)
|
||||||
|
}
|
||||||
|
|
||||||
|
async sync() {
|
||||||
|
let items
|
||||||
|
try { items = await queue.all() } catch (_) { return }
|
||||||
|
if (!items.length) return this.show("")
|
||||||
|
if (!navigator.onLine || this.running) return this.status(items)
|
||||||
|
this.running = true
|
||||||
|
let sent = 0
|
||||||
|
try {
|
||||||
|
for (const item of items.filter((i) => !i.error)) {
|
||||||
|
const result = await this.send(item)
|
||||||
|
if (result === "sent") { await queue.remove(item.id); sent++ }
|
||||||
|
else if (result === "signin") { this.show("Sign in to send the flights logged offline."); return }
|
||||||
|
else if (result === "offline") break
|
||||||
|
else { item.error = result; await queue.put(item) }
|
||||||
|
}
|
||||||
|
} finally { this.running = false }
|
||||||
|
this.status(await queue.all(), sent)
|
||||||
|
}
|
||||||
|
|
||||||
|
async send(item) {
|
||||||
|
const body = new FormData()
|
||||||
|
for (const [ name, value ] of item.fields) body.append(name, value)
|
||||||
|
const token = document.querySelector("meta[name=csrf-token]")?.content
|
||||||
|
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" } })
|
||||||
|
} catch (_) { return "offline" }
|
||||||
|
if (response.url.includes("/session/new")) return "signin"
|
||||||
|
if (response.ok) return "sent"
|
||||||
|
const html = await response.text()
|
||||||
|
const doc = new DOMParser().parseFromString(html, "text/html")
|
||||||
|
const message = [ ...doc.querySelectorAll("[role=alert], .field-error") ].map((e) => e.textContent.trim()).filter(Boolean).join(" ")
|
||||||
|
return message || `Not accepted (${response.status}).`
|
||||||
|
}
|
||||||
|
|
||||||
|
status(items, sent = 0) {
|
||||||
|
const failed = items.filter((i) => i.error)
|
||||||
|
const waiting = items.length - failed.length
|
||||||
|
const parts = []
|
||||||
|
if (sent) parts.push(`Sent ${sent} flight${sent > 1 ? "s" : ""} logged offline.`)
|
||||||
|
if (waiting) parts.push(`${waiting} flight${waiting > 1 ? "s" : ""} logged offline waiting for a connection.`)
|
||||||
|
this.show(parts.join(" "), failed)
|
||||||
|
}
|
||||||
|
|
||||||
|
show(text, failed = []) {
|
||||||
|
const banner = this.bannerTarget
|
||||||
|
banner.replaceChildren()
|
||||||
|
if (text) banner.append(Object.assign(document.createElement("p"), { textContent: text }))
|
||||||
|
for (const item of failed) {
|
||||||
|
const date = (item.fields.find(([ n ]) => n === "flight_log[date]") || [])[1] || ""
|
||||||
|
const row = document.createElement("p")
|
||||||
|
row.textContent = `${item.tail} flight ${date} logged offline wasn't accepted: ${item.error} `
|
||||||
|
const discard = Object.assign(document.createElement("button"), { type: "button", textContent: "Discard", className: "btn-secondary btn-sm ml-1" })
|
||||||
|
discard.addEventListener("click", async () => { await queue.remove(item.id); this.sync() })
|
||||||
|
row.append(discard)
|
||||||
|
banner.append(row)
|
||||||
|
}
|
||||||
|
banner.classList.toggle("hidden", !text && !failed.length)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
<% content_for :title, "Log Flight" %>
|
<% content_for :title, "Log Flight" %>
|
||||||
<%= render "shared/aircraft_header", aircraft: @aircraft %>
|
<%= render "shared/aircraft_header", aircraft: @aircraft %>
|
||||||
<%= form_with model: [@aircraft, @flight_log], class: "card card-body space-y-5 max-w-3xl" do |f| %>
|
<%= form_with model: [@aircraft, @flight_log], class: "card card-body space-y-5 max-w-3xl",
|
||||||
|
data: { controller: "offline-flight", offline_flight_tail_value: @aircraft.tail_number,
|
||||||
|
action: "submit->offline-flight#submit turbo:submit-start->offline-flight#remember turbo:fetch-request-error->offline-flight#networkFailed" } do |f| %>
|
||||||
|
<%= f.hidden_field :client_key, data: { offline_flight_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-flight-target="notice" role="status"></div>
|
||||||
<%= f.errors_summary %>
|
<%= f.errors_summary %>
|
||||||
<div class="grid gap-4 sm:grid-cols-3">
|
<div class="grid gap-4 sm:grid-cols-3">
|
||||||
<%= f.field :date, as: :date, required: true %>
|
<%= f.field :date, as: :date, required: true %>
|
||||||
|
|||||||
@@ -20,7 +20,8 @@
|
|||||||
<%= javascript_importmap_tags %>
|
<%= javascript_importmap_tags %>
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body class="min-h-full text-slate-800">
|
<body class="min-h-full text-slate-800" data-controller="offline-sync">
|
||||||
|
<div class="hidden space-y-1 bg-amber-50 px-4 py-2 text-center text-sm text-amber-900 ring-1 ring-amber-200" data-offline-sync-target="banner" role="status"></div>
|
||||||
<header class="bg-header text-white">
|
<header class="bg-header text-white">
|
||||||
<div class="mx-auto flex max-w-7xl items-center justify-between gap-4 px-4 py-3">
|
<div class="mx-auto flex max-w-7xl items-center justify-between gap-4 px-4 py-3">
|
||||||
<%= link_to root_path, class: "flex items-center gap-2 font-semibold tracking-tight whitespace-nowrap" do %>
|
<%= link_to root_path, class: "flex items-center gap-2 font-semibold tracking-tight whitespace-nowrap" do %>
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
// Makes the app installable and gives it an offline page. Only public, static
|
// Makes the app installable and gives it an offline page. Cached: public,
|
||||||
// files are cached (the offline page, icons and fingerprinted /assets/), never
|
// static files (the offline page, icons, fingerprinted /assets/) and, so a
|
||||||
// aircraft pages, so no private data is stored on the device.
|
// flight can be logged without signal, the Log Flight forms you've opened
|
||||||
const VERSION = "v1"
|
// (tail number and meter readings only). Other aircraft pages are never cached.
|
||||||
|
const VERSION = "v2"
|
||||||
|
const FORM_CACHE = "sam-flight-forms"
|
||||||
|
const FLIGHT_FORM = /^\/aircraft\/\d+\/flight_logs\/new$/
|
||||||
const SHELL_CACHE = `sam-shell-${VERSION}`
|
const SHELL_CACHE = `sam-shell-${VERSION}`
|
||||||
const ASSET_CACHE = "sam-assets"
|
const ASSET_CACHE = "sam-assets"
|
||||||
const MAX_ASSETS = 80
|
const MAX_ASSETS = 80
|
||||||
const SHELL = [ "/offline.html", "/icon.svg", "/icon-192.png" ]
|
const SHELL = [ "/offline.html", "/offline.js", "/icon.svg", "/icon-192.png" ]
|
||||||
|
|
||||||
self.addEventListener("install", (event) => {
|
self.addEventListener("install", (event) => {
|
||||||
event.waitUntil(caches.open(SHELL_CACHE).then((cache) => cache.addAll(SHELL)).then(() => self.skipWaiting()))
|
event.waitUntil(caches.open(SHELL_CACHE).then((cache) => cache.addAll(SHELL)).then(() => self.skipWaiting()))
|
||||||
@@ -25,7 +28,9 @@ self.addEventListener("fetch", (event) => {
|
|||||||
const url = new URL(request.url)
|
const url = new URL(request.url)
|
||||||
if (url.origin !== self.location.origin) return
|
if (url.origin !== self.location.origin) return
|
||||||
|
|
||||||
if (request.mode === "navigate") {
|
if (request.mode === "navigate" && FLIGHT_FORM.test(url.pathname)) {
|
||||||
|
event.respondWith(flightForm(request))
|
||||||
|
} else if (request.mode === "navigate") {
|
||||||
// Always go to the network for pages; show the offline page if it's unreachable.
|
// Always go to the network for pages; show the offline page if it's unreachable.
|
||||||
event.respondWith(fetch(request).catch(() => caches.match("/offline.html")))
|
event.respondWith(fetch(request).catch(() => caches.match("/offline.html")))
|
||||||
} else if (url.pathname.startsWith("/assets/")) {
|
} else if (url.pathname.startsWith("/assets/")) {
|
||||||
@@ -51,3 +56,16 @@ async function trim(cache) {
|
|||||||
const keys = await cache.keys()
|
const keys = await cache.keys()
|
||||||
await Promise.all(keys.slice(0, Math.max(0, keys.length - MAX_ASSETS)).map((k) => cache.delete(k)))
|
await Promise.all(keys.slice(0, Math.max(0, keys.length - MAX_ASSETS)).map((k) => cache.delete(k)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The Log Flight form: fresh from the network when there is one (and kept),
|
||||||
|
// the kept copy when there isn't.
|
||||||
|
async function flightForm(request) {
|
||||||
|
const cache = await caches.open(FORM_CACHE)
|
||||||
|
try {
|
||||||
|
const response = await fetch(request)
|
||||||
|
if (response.ok && !response.redirected) await cache.put(request.url.split("?")[0], response.clone())
|
||||||
|
return response
|
||||||
|
} catch (_) {
|
||||||
|
return (await cache.match(request.url.split("?")[0])) || caches.match("/offline.html")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
class AddClientKeyToFlightLogs < ActiveRecord::Migration[8.1]
|
||||||
|
def change
|
||||||
|
# A random key from the form, so a flight logged offline and sent again
|
||||||
|
# (after a dropped connection) isn't saved twice.
|
||||||
|
add_column :flight_logs, :client_key, :string
|
||||||
|
add_index :flight_logs, [ :aircraft_id, :client_key ], unique: true
|
||||||
|
end
|
||||||
|
end
|
||||||
Generated
+3
-1
@@ -10,7 +10,7 @@
|
|||||||
#
|
#
|
||||||
# It's strongly recommended that you check this file into your version control system.
|
# It's strongly recommended that you check this file into your version control system.
|
||||||
|
|
||||||
ActiveRecord::Schema[8.1].define(version: 2026_11_11_040000) do
|
ActiveRecord::Schema[8.1].define(version: 2026_11_11_050000) do
|
||||||
create_table "active_storage_attachments", force: :cascade do |t|
|
create_table "active_storage_attachments", force: :cascade do |t|
|
||||||
t.string "name", null: false
|
t.string "name", null: false
|
||||||
t.string "record_type", null: false
|
t.string "record_type", null: false
|
||||||
@@ -471,6 +471,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_11_040000) do
|
|||||||
t.text "notes"
|
t.text "notes"
|
||||||
t.datetime "created_at", null: false
|
t.datetime "created_at", null: false
|
||||||
t.datetime "updated_at", null: false
|
t.datetime "updated_at", null: false
|
||||||
|
t.string "client_key"
|
||||||
|
t.index ["aircraft_id", "client_key"], name: "index_flight_logs_on_aircraft_id_and_client_key", unique: true
|
||||||
t.index ["aircraft_id"], name: "index_flight_logs_on_aircraft_id"
|
t.index ["aircraft_id"], name: "index_flight_logs_on_aircraft_id"
|
||||||
t.index ["user_id"], name: "index_flight_logs_on_user_id"
|
t.index ["user_id"], name: "index_flight_logs_on_user_id"
|
||||||
end
|
end
|
||||||
|
|||||||
+2
-2
@@ -70,7 +70,7 @@ For domain-level forward auth, Authentik matches each line as a regular expressi
|
|||||||
```
|
```
|
||||||
^https://aircraft\.example\.com/manifest\.json$
|
^https://aircraft\.example\.com/manifest\.json$
|
||||||
^https://aircraft\.example\.com/service-worker\.js$
|
^https://aircraft\.example\.com/service-worker\.js$
|
||||||
^https://aircraft\.example\.com/offline\.html$
|
^https://aircraft\.example\.com/offline\.(html|js)$
|
||||||
^https://aircraft\.example\.com/favicon\.svg$
|
^https://aircraft\.example\.com/favicon\.svg$
|
||||||
^https://aircraft\.example\.com/icon(-192|-maskable)?\.(png|svg)$
|
^https://aircraft\.example\.com/icon(-192|-maskable)?\.(png|svg)$
|
||||||
^https://aircraft\.example\.com/apple-touch-icon\.png$
|
^https://aircraft\.example\.com/apple-touch-icon\.png$
|
||||||
@@ -89,7 +89,7 @@ What each group is for:
|
|||||||
|
|
||||||
| Lines | Needed for | What's exposed |
|
| Lines | Needed for | What's exposed |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `manifest.json`, `service-worker.js`, `offline.html`, icons | Installing the app on a phone (the browser fetches these without cookies), and share pages | Static files with no data |
|
| `manifest.json`, `service-worker.js`, `offline.html`, `offline.js`, icons | Installing the app on a phone (the browser fetches these without cookies), and share pages | Static files with no data |
|
||||||
| `/assets/…` | Styles and scripts for share pages and the signing pages | Static files with no data |
|
| `/assets/…` | Styles and scripts for share pages and the signing pages | Static files with no data |
|
||||||
| `/shared/<token>`, `/shared/<token>/report` | Read-only share links (Access & Sharing) | Only with a valid, unexpired, unrevoked 32-character token, and only what that link's level shows |
|
| `/shared/<token>`, `/shared/<token>/report` | Read-only share links (Access & Sharing) | Only with a valid, unexpired, unrevoked 32-character token, and only what that link's level shows |
|
||||||
| `/rails/active_storage/blobs/redirect/…`, `/rails/active_storage/disk/…` | The aircraft picture and shared documents on share pages | A file only to someone holding its signed link (from a page they could see). Disk links expire after a few minutes; redirect links don't, so a forwarded link keeps working |
|
| `/rails/active_storage/blobs/redirect/…`, `/rails/active_storage/disk/…` | The aircraft picture and shared documents on share pages | A file only to someone holding its signed link (from a page they could see). Disk links expire after a few minutes; redirect links don't, so a forwarded link keeps working |
|
||||||
|
|||||||
@@ -11,6 +11,12 @@ Every hour flown is added to the aircraft and to each installed component, which
|
|||||||
- The route (From/To airports autocomplete) and notes.
|
- The route (From/To airports autocomplete) and notes.
|
||||||
- Optionally a **track log** (GPX, KML or CSV) and **engine monitor data** (CGR-30P / CGR-30C `.csv`), which you can chart on the flight's page.
|
- Optionally a **track log** (GPX, KML or CSV) and **engine monitor data** (CGR-30P / CGR-30C `.csv`), which you can chart on the flight's page.
|
||||||
|
|
||||||
|
### With no signal
|
||||||
|
|
||||||
|
On a phone or tablet with the app installed (see [Getting started](getting-started.md)), you can log a flight without a connection, as long as you've opened **Log Flight** for that aircraft on that device before. Without signal, the form opens from the copy the device kept, and **Log Flight** saves the flight on the device instead of sending it. The next leg starts where the last one ended. When the connection is back, the app sends the saved flights by itself and says so at the top of the page. A flight that's rejected (for example a typo in the tach) stays there with the reason, to log again by hand or discard. Sending twice never logs a flight twice.
|
||||||
|
|
||||||
|
Track and engine data files attached offline are kept and sent too.
|
||||||
|
|
||||||
## Update hours
|
## Update hours
|
||||||
|
|
||||||
When you don't log each flight, use **Update Hours** on the overview: enter the current meter readings and the difference is applied to every installed component. A reading lower than the current one is treated as a correction.
|
When you don't log each flight, use **Update Hours** on the overview: enter the current meter readings and the difference is applied to every installed component. A reading lower than the current one is treated as a correction.
|
||||||
|
|||||||
+5
-1
@@ -19,6 +19,7 @@
|
|||||||
img { width: 72px; height: 72px; }
|
img { width: 72px; height: 72px; }
|
||||||
h1 { font-size: 1.25rem; margin: 16px 0 8px; }
|
h1 { font-size: 1.25rem; margin: 16px 0 8px; }
|
||||||
p { margin: 0 0 24px; color: var(--muted); }
|
p { margin: 0 0 24px; color: var(--muted); }
|
||||||
|
#forms a { display: block; margin-top: 8px; color: var(--accent); font-weight: 600; }
|
||||||
button { font: inherit; font-weight: 600; color: #fff; background: var(--accent); border: 0; border-radius: 6px; padding: 10px 20px; cursor: pointer; }
|
button { font: inherit; font-weight: 600; color: #fff; background: var(--accent); border: 0; border-radius: 6px; padding: 10px 20px; cursor: pointer; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
@@ -28,7 +29,10 @@
|
|||||||
<h1>You're offline</h1>
|
<h1>You're offline</h1>
|
||||||
<p>Simple Aircraft Manager needs a connection to load your aircraft. Check your signal and try again.</p>
|
<p>Simple Aircraft Manager needs a connection to load your aircraft. Check your signal and try again.</p>
|
||||||
<button type="button" onclick="location.reload()">Try again</button>
|
<button type="button" onclick="location.reload()">Try again</button>
|
||||||
|
<div id="forms" hidden>
|
||||||
|
<p style="margin:24px 0 8px">You can still log a flight; it's sent when you're back online:</p>
|
||||||
|
</div>
|
||||||
</main>
|
</main>
|
||||||
<script>window.addEventListener("online", function () { location.reload() })</script>
|
<script src="/offline.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
// The offline page: reload when the connection is back, and link to the Log
|
||||||
|
// Flight forms this device has kept (so a flight can be logged offline).
|
||||||
|
window.addEventListener("online", function () { location.reload() })
|
||||||
|
try {
|
||||||
|
var forms = JSON.parse(localStorage.getItem("sam-offline-forms") || "{}")
|
||||||
|
var box = document.getElementById("forms")
|
||||||
|
Object.keys(forms).forEach(function (path) {
|
||||||
|
if (!/^\/aircraft\/\d+\/flight_logs\/new$/.test(path)) return
|
||||||
|
var a = document.createElement("a")
|
||||||
|
a.href = path
|
||||||
|
a.textContent = "Log a flight: " + forms[path]
|
||||||
|
box.appendChild(a)
|
||||||
|
box.hidden = false
|
||||||
|
})
|
||||||
|
} catch (e) { /* storage off */ }
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
require "test_helper"
|
||||||
|
|
||||||
|
# Logging a flight with no signal: the form works offline (kept by the service
|
||||||
|
# worker), queues on the device, and is sent once; sending it twice doesn't
|
||||||
|
# log it twice.
|
||||||
|
class OfflineFlightsTest < ActionDispatch::IntegrationTest
|
||||||
|
setup do
|
||||||
|
@owner = create_user("owner@example.com")
|
||||||
|
@a = create_aircraft(owner: @owner, tail_number: "N12345", tach_time: 1000)
|
||||||
|
sign_in @owner
|
||||||
|
end
|
||||||
|
|
||||||
|
test "the form carries a one-time key and the offline controller; the same key is logged once" do
|
||||||
|
get new_aircraft_flight_log_path(@a)
|
||||||
|
assert_select "form[data-controller=offline-flight][data-offline-flight-tail-value=N12345]"
|
||||||
|
assert_select "input[type=hidden][name='flight_log[client_key]']"
|
||||||
|
assert_select "body[data-controller=offline-sync] [data-offline-sync-target=banner]"
|
||||||
|
|
||||||
|
params = { flight_log: { date: "2026-11-08", tach_out: 1000, tach_in: 1001.2, departure_location: "KOQU", destination_location: "KBID", client_key: "key-1" } }
|
||||||
|
post aircraft_flight_logs_path(@a), params: params
|
||||||
|
assert_redirected_to aircraft_flight_logs_path(@a)
|
||||||
|
post aircraft_flight_logs_path(@a), params: params # resent after a dropped connection
|
||||||
|
assert_redirected_to aircraft_flight_logs_path(@a)
|
||||||
|
assert_equal 1, @a.flight_logs.where(client_key: "key-1").count
|
||||||
|
assert_in_delta 1001.2, @a.reload.tach_time, 0.001 # hours applied once
|
||||||
|
end
|
||||||
|
|
||||||
|
test "the service worker keeps Log Flight forms and the offline page links them" do
|
||||||
|
get pwa_service_worker_path(format: :js)
|
||||||
|
assert_includes response.body, "FLIGHT_FORM"
|
||||||
|
assert_includes response.body, %q(const FLIGHT_FORM = /^\/aircraft\/\d+\/flight_logs\/new$/)
|
||||||
|
assert Rails.public_path.join("offline.js").read.include?("sam-offline-forms")
|
||||||
|
end
|
||||||
|
end
|
||||||
Reference in new issue
Block a user