mirror of
https://github.com/rickbarrette/simple-aircraft-manager-rails.git
synced 2026-11-17 23:50:36 -05:00
API: draft logbook entries for signing
- POST /aircraft/:id/draft_batches turns a visit's work items into one unsigned entry per logbook, signed in the app (by a user with a certificate, or a mechanic through a returned or emailed invitation link). - The squawks they resolve and inspections they complete (with their result) are held until every entry is signed, then applied, attributed to the last signer; draft_batch.completed webhook. A draft never clears a squawk alone. - Drafts are for owners (integrations act for one, drafts:write scope); unsigned drafts can be withdrawn; lookup by external_ref. - The signing and entry pages show where a draft came from and what signing will do. - The suggested recordkeeping procedures describe the API once it's in use. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bffdea937c
commit
e4c27c6ff7
19 files changed
+495
-5
No files matched your search
@@ -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
|
||||
@@ -16,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
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
# 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])
|
||||
SCOPES = LabelSet.new("api_token.scopes", %w[read squawks:write drafts:write])
|
||||
PREFIX = "sam_"
|
||||
|
||||
belongs_to :user
|
||||
|
||||
@@ -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
|
||||
@@ -23,6 +23,7 @@ class EntrySignature < ApplicationRecord
|
||||
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 }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# 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])
|
||||
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
|
||||
|
||||
@@ -42,12 +42,23 @@ module ApiPresenter
|
||||
{ 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),
|
||||
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) }
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,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>
|
||||
|
||||
Reference in new issue
Block a user