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 :components, dependent: :destroy
|
||||||
has_many :squawks, dependent: :destroy
|
has_many :squawks, dependent: :destroy
|
||||||
has_many :logbook_entries, dependent: :destroy
|
has_many :logbook_entries, dependent: :destroy
|
||||||
|
has_many :draft_batches, dependent: :destroy
|
||||||
has_many :logbook_imports, dependent: :destroy
|
has_many :logbook_imports, dependent: :destroy
|
||||||
has_many :document_collections, dependent: :destroy
|
has_many :document_collections, dependent: :destroy
|
||||||
has_many :documents, dependent: :destroy
|
has_many :documents, dependent: :destroy
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
# for (SAM-On-Behalf-Of), so the record history always shows who.
|
# for (SAM-On-Behalf-Of), so the record history always shows who.
|
||||||
class ApiToken < ApplicationRecord
|
class ApiToken < ApplicationRecord
|
||||||
KINDS = %w[personal integration].freeze
|
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_"
|
PREFIX = "sam_"
|
||||||
|
|
||||||
belongs_to :user
|
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?
|
next if imported?
|
||||||
entry = logbook_entry
|
entry = logbook_entry
|
||||||
Webhooks.publish("entry.signed", aircraft: entry.aircraft, data: ApiPresenter.logbook_entry(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
|
end
|
||||||
before_update { throw :abort } # signatures are permanent (2.1.2.7)
|
before_update { throw :abort } # signatures are permanent (2.1.2.7)
|
||||||
before_destroy { throw :abort unless destroyed_by_association }
|
before_destroy { throw :abort unless destroyed_by_association }
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ class LogbookEntry < ApplicationRecord
|
|||||||
belongs_to :document, optional: true
|
belongs_to :document, optional: true
|
||||||
# For engine / propeller logs: which one, and its times at this entry.
|
# For engine / propeller logs: which one, and its times at this entry.
|
||||||
belongs_to :component, optional: true
|
belongs_to :component, optional: true
|
||||||
|
belongs_to :draft_batch, optional: true # made through the API, see DraftBatch
|
||||||
# Sub-components it also covers (the oil filter on the engine…).
|
# Sub-components it also covers (the oil filter on the engine…).
|
||||||
has_many :parts, -> { includes(component: :component_type).order(:id) }, class_name: "LogbookEntryPart",
|
has_many :parts, -> { includes(component: :component_type).order(:id) }, class_name: "LogbookEntryPart",
|
||||||
dependent: :destroy, autosave: true
|
dependent: :destroy, autosave: true
|
||||||
@@ -33,6 +34,7 @@ class LogbookEntry < ApplicationRecord
|
|||||||
validates :signoff_certificate_type, inclusion: { in: CERTIFICATE_TYPES.keys }, allow_blank: true
|
validates :signoff_certificate_type, inclusion: { in: CERTIFICATE_TYPES.keys }, allow_blank: true
|
||||||
validates :inspection_result, inclusion: { in: INSPECTION_RESULTS.keys }, allow_blank: true
|
validates :inspection_result, inclusion: { in: INSPECTION_RESULTS.keys }, allow_blank: true
|
||||||
validates :component_hours_at_entry, :component_since_overhaul_at_entry, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
|
validates :component_hours_at_entry, :component_since_overhaul_at_entry, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
|
||||||
|
normalizes :external_ref, with: ->(r) { r.to_s.strip.first(200).presence }
|
||||||
normalizes :signoff_certificate_type, :inspection_result, :signoff_certificate_number, with: ->(v) { v.strip.presence }
|
normalizes :signoff_certificate_type, :inspection_result, :signoff_certificate_number, with: ->(v) { v.strip.presence }
|
||||||
|
|
||||||
# Fields that may still change on a signed entry: its link to a scanned
|
# Fields that may still change on a signed entry: its link to a scanned
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Where an integration wants to hear about changes (squawks, signed entries):
|
# Where an integration wants to hear about changes (squawks, signed entries):
|
||||||
# SAM posts JSON there, signed with the shared secret (see WebhookDeliveryJob).
|
# SAM posts JSON there, signed with the shared secret (see WebhookDeliveryJob).
|
||||||
class WebhookEndpoint < ApplicationRecord
|
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
|
belongs_to :api_token
|
||||||
has_many :deliveries, class_name: "WebhookDelivery", dependent: :delete_all
|
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,
|
{ 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),
|
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?,
|
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,
|
signoff: sig ? nil : { person: e.signoff_person.presence, certificate_type: e.signoff_certificate_type.presence,
|
||||||
certificate_number: e.signoff_certificate_number.presence }.compact.presence,
|
certificate_number: e.signoff_certificate_number.presence }.compact.presence,
|
||||||
created_at: time(e.created_at), updated_at: time(e.updated_at) }
|
created_at: time(e.created_at), updated_at: time(e.updated_at) }
|
||||||
end
|
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)
|
def signature(sig)
|
||||||
{ signer_name: sig.signer_name, certificate_kind: sig.certificate_kind, certificate_number: sig.certificate_number,
|
{ signer_name: sig.signer_name, certificate_kind: sig.certificate_kind, certificate_number: sig.certificate_number,
|
||||||
signed_at: time(sig.signed_at) }
|
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,
|
t(:sign_in, sentence: sign_in_sentence, min: User::PASSWORD_MIN, minutes: User::LOCK_FOR.in_minutes.to_i,
|
||||||
tries: User::LOCK_AFTER, days: Authentication::SESSION_IDLE_TIMEOUT.in_days.to_i),
|
tries: User::LOCK_AFTER, days: Authentication::SESSION_IDLE_TIMEOUT.in_days.to_i),
|
||||||
t(Sso.enabled? ? :signing_sso : :signing),
|
t(Sso.enabled? ? :signing_sso : :signing),
|
||||||
|
api_sentence,
|
||||||
t(:updates),
|
t(:updates),
|
||||||
t(:secret_key)
|
t(:secret_key)
|
||||||
].join("\n\n")
|
].compact.join("\n\n")
|
||||||
end
|
end
|
||||||
|
|
||||||
def additional
|
def additional
|
||||||
@@ -37,6 +38,13 @@ module ProceduresTemplates
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Only when the API is in use: who can reach the records through it, and that signing stays in the app.
|
||||||
|
def api_sentence
|
||||||
|
integrations = ApiToken.integration.active.order(:name).pluck(:name)
|
||||||
|
return if integrations.empty? && !ApiToken.personal.active.exists?
|
||||||
|
t(:api, integrations: integrations.any? ? t(:api_integrations, names: integrations.to_sentence) : t(:api_no_integrations))
|
||||||
|
end
|
||||||
|
|
||||||
def docker? = File.exist?("/.dockerenv")
|
def docker? = File.exist?("/.dockerenv")
|
||||||
|
|
||||||
def t(key, **opts) = I18n.t(key, scope: "services.procedures_templates", **opts)
|
def t(key, **opts) = I18n.t(key, scope: "services.procedures_templates", **opts)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
<div class="card-body space-y-4">
|
<div class="card-body space-y-4">
|
||||||
<p class="text-sm text-slate-600"><%= t(".review_the_entry_your_signature_html", link: (link_to t(".how_signing_works"), records_help_path, class: "link", target: "_blank")) %></p>
|
<p class="text-sm text-slate-600"><%= t(".review_the_entry_your_signature_html", link: (link_to t(".how_signing_works"), records_help_path, class: "link", target: "_blank")) %></p>
|
||||||
<%= render "logbook_entries/content", entry: entry %>
|
<%= render "logbook_entries/content", entry: entry %>
|
||||||
|
<%= render "logbook_entries/draft_batch", entry: entry %>
|
||||||
<% if @signing_error %>
|
<% if @signing_error %>
|
||||||
<div class="rounded-md bg-red-50 p-3 text-sm text-red-700 ring-1 ring-red-200" role="alert"><%= @signing_error %></div>
|
<div class="rounded-md bg-red-50 p-3 text-sm text-red-700 ring-1 ring-red-200" role="alert"><%= @signing_error %></div>
|
||||||
<% end %>
|
<% end %>
|
||||||
|
|||||||
@@ -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>
|
</div>
|
||||||
<div class="card-body space-y-3">
|
<div class="card-body space-y-3">
|
||||||
|
<%= render "logbook_entries/draft_batch", entry: @entry %>
|
||||||
<% if @entry.signed? %><%= render "logbook_entries/signature", entry: @entry %>
|
<% if @entry.signed? %><%= render "logbook_entries/signature", entry: @entry %>
|
||||||
<% elsif LogbookEntry::RECORD_TYPES.include?(@entry.entry_type) %>
|
<% 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>
|
<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>
|
||||||
|
|||||||
@@ -4,6 +4,11 @@
|
|||||||
# a controller name are its views (t(".key") in the view).
|
# a controller name are its views (t(".key") in the view).
|
||||||
|
|
||||||
en:
|
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:
|
api_tokens:
|
||||||
created:
|
created:
|
||||||
title: Your new API token
|
title: Your new API token
|
||||||
@@ -16,6 +21,7 @@ en:
|
|||||||
scopes:
|
scopes:
|
||||||
read: Read aircraft, parts, due items, squawks and logbook entries
|
read: Read aircraft, parts, due items, squawks and logbook entries
|
||||||
'squawks:write': Report and update squawks
|
'squawks:write': Report and update squawks
|
||||||
|
'drafts:write': Send draft logbook entries for signing (acting for an owner of the aircraft)
|
||||||
webhook_endpoint:
|
webhook_endpoint:
|
||||||
events:
|
events:
|
||||||
squawk:
|
squawk:
|
||||||
@@ -24,6 +30,8 @@ en:
|
|||||||
resolved: A squawk is resolved
|
resolved: A squawk is resolved
|
||||||
entry:
|
entry:
|
||||||
signed: A logbook entry is signed
|
signed: A logbook entry is signed
|
||||||
|
draft_batch:
|
||||||
|
completed: All the entries of a draft are signed (and what it resolves is done)
|
||||||
aircraft:
|
aircraft:
|
||||||
statuses:
|
statuses:
|
||||||
AVAILABLE: Available
|
AVAILABLE: Available
|
||||||
@@ -2623,6 +2631,13 @@ en:
|
|||||||
cg_in: "= CG (in)"
|
cg_in: "= CG (in)"
|
||||||
cg_in_2: CG (in)
|
cg_in_2: CG (in)
|
||||||
logbook_entries:
|
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_fields:
|
||||||
component: Component
|
component: Component
|
||||||
for_engine_and_propeller_logs: 'For engine and propeller logs: printed with its serial number and times.'
|
for_engine_and_propeller_logs: 'For engine and propeller logs: printed with its serial number and times.'
|
||||||
@@ -3607,6 +3622,9 @@ en:
|
|||||||
aircraft_grounded_error:
|
aircraft_grounded_error:
|
||||||
message: Aircraft is grounded and airworthiness enforcement is enabled
|
message: Aircraft is grounded and airworthiness enforcement is enabled
|
||||||
procedures_templates:
|
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: "**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_docker: as a Docker container on a server
|
||||||
server_plain: on a server
|
server_plain: on a server
|
||||||
|
|||||||
@@ -194,9 +194,12 @@ Rails.application.routes.draw do
|
|||||||
get :logbook_entries
|
get :logbook_entries
|
||||||
end
|
end
|
||||||
resources :squawks, only: %i[index create]
|
resources :squawks, only: %i[index create]
|
||||||
|
resources :draft_batches, only: %i[index create]
|
||||||
end
|
end
|
||||||
get "squawks", to: "squawks#lookup"
|
get "squawks", to: "squawks#lookup"
|
||||||
resources :squawks, only: %i[show update]
|
resources :squawks, only: %i[show update]
|
||||||
|
get "draft_batches", to: "draft_batches#lookup"
|
||||||
|
resources :draft_batches, only: %i[show destroy]
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Draft logbook entries from the API (docs/api.md, "Draft entries"): one
|
||||||
|
# batch per visit, one unsigned entry per logbook; what the work resolves
|
||||||
|
# (squawks, inspections) is held until every entry is signed.
|
||||||
|
class CreateDraftBatches < ActiveRecord::Migration[8.1]
|
||||||
|
def change
|
||||||
|
create_table :draft_batches do |t|
|
||||||
|
t.references :aircraft, null: false, foreign_key: true
|
||||||
|
t.references :api_token, foreign_key: true
|
||||||
|
t.references :created_by, foreign_key: { to_table: :users }
|
||||||
|
t.string :external_ref
|
||||||
|
t.string :status, null: false, default: "awaiting_signature" # awaiting_signature | completed | withdrawn
|
||||||
|
t.string :signer_email
|
||||||
|
t.json :held, null: false, default: {} # { "squawks" => [{ "id", "log" }], "inspections" => [{ "id", "log" }] }
|
||||||
|
t.datetime :completed_at
|
||||||
|
t.timestamps
|
||||||
|
t.index :external_ref
|
||||||
|
end
|
||||||
|
add_reference :logbook_entries, :draft_batch, foreign_key: true
|
||||||
|
add_column :logbook_entries, :external_ref, :string
|
||||||
|
end
|
||||||
|
end
|
||||||
Generated
+25
-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_15_010000) do
|
ActiveRecord::Schema[8.1].define(version: 2026_11_15_020000) 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
|
||||||
@@ -441,6 +441,23 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_15_010000) do
|
|||||||
t.index ["document_collection_id"], name: "index_documents_on_document_collection_id"
|
t.index ["document_collection_id"], name: "index_documents_on_document_collection_id"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
create_table "draft_batches", force: :cascade do |t|
|
||||||
|
t.integer "aircraft_id", null: false
|
||||||
|
t.integer "api_token_id"
|
||||||
|
t.integer "created_by_id"
|
||||||
|
t.string "external_ref"
|
||||||
|
t.string "status", default: "awaiting_signature", null: false
|
||||||
|
t.string "signer_email"
|
||||||
|
t.json "held", default: {}, null: false
|
||||||
|
t.datetime "completed_at"
|
||||||
|
t.datetime "created_at", null: false
|
||||||
|
t.datetime "updated_at", null: false
|
||||||
|
t.index ["aircraft_id"], name: "index_draft_batches_on_aircraft_id"
|
||||||
|
t.index ["api_token_id"], name: "index_draft_batches_on_api_token_id"
|
||||||
|
t.index ["created_by_id"], name: "index_draft_batches_on_created_by_id"
|
||||||
|
t.index ["external_ref"], name: "index_draft_batches_on_external_ref"
|
||||||
|
end
|
||||||
|
|
||||||
create_table "drs_imports", force: :cascade do |t|
|
create_table "drs_imports", force: :cascade do |t|
|
||||||
t.integer "aircraft_id", null: false
|
t.integer "aircraft_id", null: false
|
||||||
t.integer "user_id"
|
t.integer "user_id"
|
||||||
@@ -569,9 +586,12 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_15_010000) do
|
|||||||
t.decimal "component_since_overhaul_at_entry", precision: 8, scale: 1
|
t.decimal "component_since_overhaul_at_entry", precision: 8, scale: 1
|
||||||
t.integer "supersedes_id"
|
t.integer "supersedes_id"
|
||||||
t.datetime "superseded_at"
|
t.datetime "superseded_at"
|
||||||
|
t.integer "draft_batch_id"
|
||||||
|
t.string "external_ref"
|
||||||
t.index ["aircraft_id"], name: "index_logbook_entries_on_aircraft_id"
|
t.index ["aircraft_id"], name: "index_logbook_entries_on_aircraft_id"
|
||||||
t.index ["component_id"], name: "index_logbook_entries_on_component_id"
|
t.index ["component_id"], name: "index_logbook_entries_on_component_id"
|
||||||
t.index ["document_id"], name: "index_logbook_entries_on_document_id"
|
t.index ["document_id"], name: "index_logbook_entries_on_document_id"
|
||||||
|
t.index ["draft_batch_id"], name: "index_logbook_entries_on_draft_batch_id"
|
||||||
t.index ["supersedes_id"], name: "index_logbook_entries_on_supersedes_id"
|
t.index ["supersedes_id"], name: "index_logbook_entries_on_supersedes_id"
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -952,6 +972,9 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_15_010000) do
|
|||||||
add_foreign_key "document_collections", "aircraft"
|
add_foreign_key "document_collections", "aircraft"
|
||||||
add_foreign_key "documents", "aircraft"
|
add_foreign_key "documents", "aircraft"
|
||||||
add_foreign_key "documents", "document_collections"
|
add_foreign_key "documents", "document_collections"
|
||||||
|
add_foreign_key "draft_batches", "aircraft"
|
||||||
|
add_foreign_key "draft_batches", "api_tokens"
|
||||||
|
add_foreign_key "draft_batches", "users", column: "created_by_id"
|
||||||
add_foreign_key "drs_imports", "aircraft", on_delete: :cascade
|
add_foreign_key "drs_imports", "aircraft", on_delete: :cascade
|
||||||
add_foreign_key "drs_imports", "users", on_delete: :nullify
|
add_foreign_key "drs_imports", "users", on_delete: :nullify
|
||||||
add_foreign_key "entry_signatures", "logbook_entries"
|
add_foreign_key "entry_signatures", "logbook_entries"
|
||||||
@@ -966,6 +989,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_15_010000) do
|
|||||||
add_foreign_key "logbook_entries", "aircraft"
|
add_foreign_key "logbook_entries", "aircraft"
|
||||||
add_foreign_key "logbook_entries", "components", on_delete: :nullify
|
add_foreign_key "logbook_entries", "components", on_delete: :nullify
|
||||||
add_foreign_key "logbook_entries", "documents", on_delete: :nullify
|
add_foreign_key "logbook_entries", "documents", on_delete: :nullify
|
||||||
|
add_foreign_key "logbook_entries", "draft_batches"
|
||||||
add_foreign_key "logbook_entries", "logbook_entries", column: "supersedes_id", on_delete: :nullify
|
add_foreign_key "logbook_entries", "logbook_entries", column: "supersedes_id", on_delete: :nullify
|
||||||
add_foreign_key "logbook_entry_parts", "components", on_delete: :cascade
|
add_foreign_key "logbook_entry_parts", "components", on_delete: :cascade
|
||||||
add_foreign_key "logbook_entry_parts", "logbook_entries", on_delete: :cascade
|
add_foreign_key "logbook_entry_parts", "logbook_entries", on_delete: :cascade
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ Reading works without it (limited to the integration's aircraft). Every write ne
|
|||||||
|---|---|
|
|---|---|
|
||||||
| `read` | Aircraft, parts, due items, inspections, ADs, squawks and logbook entries |
|
| `read` | Aircraft, parts, due items, inspections, ADs, squawks and logbook entries |
|
||||||
| `squawks:write` | Reporting squawks and updating them |
|
| `squawks:write` | Reporting squawks and updating them |
|
||||||
|
| `drafts:write` | Sending draft logbook entries for signing, and withdrawing them (acting for an owner of the aircraft) |
|
||||||
|
|
||||||
## Requests and answers
|
## Requests and answers
|
||||||
|
|
||||||
@@ -68,6 +69,11 @@ Squawks have an `external_ref`: your own id for them, such as `redmine:issue:451
|
|||||||
| `GET /squawks?external_ref=…` | Find squawks by your id for them |
|
| `GET /squawks?external_ref=…` | Find squawks by your id for them |
|
||||||
| `GET /squawks/:id` | One squawk |
|
| `GET /squawks/:id` | One squawk |
|
||||||
| `PATCH /squawks/:id` | Update a squawk |
|
| `PATCH /squawks/:id` | Update a squawk |
|
||||||
|
| `POST /aircraft/:id/draft_batches` | Send a visit's work as draft logbook entries for signing |
|
||||||
|
| `GET /aircraft/:id/draft_batches` | Its drafts (`?status=awaiting_signature`, `completed` or `withdrawn`) |
|
||||||
|
| `GET /draft_batches?external_ref=…` | Find drafts by your id for them |
|
||||||
|
| `GET /draft_batches/:id` | One draft, with its entries and whether they're signed |
|
||||||
|
| `DELETE /draft_batches/:id` | Withdraw a draft nothing in which is signed yet |
|
||||||
|
|
||||||
### Reporting a squawk
|
### Reporting a squawk
|
||||||
|
|
||||||
@@ -94,6 +100,46 @@ The answer is `201` with the squawk:
|
|||||||
|
|
||||||
`PATCH /squawks/:id` with `{ "squawk": { … } }`. Anyone who may write can set `external_ref`; changing `issue_reported`, `priority`, `component_id` or `notes` needs an owner of the aircraft, as in the app. A resolved squawk can't be changed. Squawks are resolved by a signed logbook entry, in the app.
|
`PATCH /squawks/:id` with `{ "squawk": { … } }`. Anyone who may write can set `external_ref`; changing `issue_reported`, `priority`, `component_id` or `notes` needs an owner of the aircraft, as in the app. A resolved squawk can't be changed. Squawks are resolved by a signed logbook entry, in the app.
|
||||||
|
|
||||||
|
## Draft entries
|
||||||
|
|
||||||
|
Another system that tracks the work, such as Redmine's issues, can send a finished visit to SAM as **draft logbook entries**: the person certifying the work then reviews and signs them in the app. Like writing entries in the app, sending drafts is for the aircraft's owners: an integration acts for an owner (`SAM-On-Behalf-Of`), such as the director of maintenance.
|
||||||
|
|
||||||
|
```
|
||||||
|
POST /api/v1/aircraft/12/draft_batches
|
||||||
|
{ "draft_batch": {
|
||||||
|
"date": "2026-11-20",
|
||||||
|
"aircraft_hours": 4321.4,
|
||||||
|
"external_ref": "redmine:visit:77",
|
||||||
|
"items": [
|
||||||
|
{ "log": "ENG", "text": "Changed oil and filter, 7 qt Aeroshell W100.", "external_ref": "redmine:issue:4512" },
|
||||||
|
{ "log": "AC", "text": "Replaced left brake linings.", "resolves_squawks": [88], "external_ref": "redmine:issue:4513" },
|
||||||
|
{ "log": "AC", "text": "Annual inspection completed IAW Part 43 Appendix D.", "external_ref": "redmine:issue:4519" }
|
||||||
|
],
|
||||||
|
"completes_inspections": [ { "inspection_type_id": 3, "result": "approved" } ],
|
||||||
|
"signer": { "email": "mechanic@example.com", "send_email": false }
|
||||||
|
} }
|
||||||
|
```
|
||||||
|
|
||||||
|
- **One entry per logbook.** Items are grouped by `log` (`AC`, `ENG`, `PROP` or `OTHER`) into one unsigned entry each, their texts in order, so a visit that touched the engine and the airframe makes two entries, signed one after the other.
|
||||||
|
- **Inspections** (`completes_inspections`): each needs its `result`, `approved` (airworthy) or `discrepancies` (a list was given to the owner), and the draft needs `aircraft_hours`. The entry recording it is an inspection entry, in the logbook named by `log`, else the airframe log if an item is for it.
|
||||||
|
- **Nothing is resolved until it's signed.** The squawks the items resolve and the inspections they complete are held until **every** entry of the draft is signed; then they're resolved and recorded, attributed to the person who signed last, and linked to the entry that described the work. A draft never clears a squawk on its own. The signer sees what signing will do before they sign.
|
||||||
|
- **The signer.** Anyone with access to the aircraft and a certificate in their profile can sign, from each entry's `sign_url`. Give `signer.email` for someone else (a mechanic without an account): each entry then gets an `invitation_url`, a link that lets that person create an account for that address and sign that entry, for 14 days. Pass the link on yourself (for example inside Redmine), or set `send_email: true` to have SAM email it.
|
||||||
|
|
||||||
|
The answer (`201`):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "data": { "id": 301, "status": "awaiting_signature", "external_ref": "redmine:visit:77",
|
||||||
|
"held": { "resolves_squawks": [88], "completes_inspections": [3] },
|
||||||
|
"entries": [
|
||||||
|
{ "id": 9001, "log": "AC", "entry_type": "INSPECTION", "text": "Replaced left brake linings.\n\nAnnual inspection…", "signed": false,
|
||||||
|
"sign_url": "https://sam.example.com/aircraft/12/logbook_entries/9001/signature/new", "invitation_url": "https://sam.example.com/sign/…" },
|
||||||
|
{ "id": 9002, "log": "ENG", "entry_type": "MAINTENANCE", "text": "Changed oil and filter…", "signed": false, … } ] } }
|
||||||
|
```
|
||||||
|
|
||||||
|
When every entry is signed, the draft's `status` becomes `completed` and the `draft_batch.completed` webhook is sent: the moment to close the work order.
|
||||||
|
|
||||||
|
A draft can be withdrawn (`DELETE /draft_batches/:id`) while nothing in it is signed; its entries are removed, and the record history keeps them. Once an entry is signed it's a record: mistakes are fixed with a correction entry in the app, never through the API.
|
||||||
|
|
||||||
## Webhooks
|
## Webhooks
|
||||||
|
|
||||||
An integration can be told about changes. In Admin → Integrations, give it a webhook address and choose the events. SAM then posts JSON there after each change:
|
An integration can be told about changes. In Admin → Integrations, give it a webhook address and choose the events. SAM then posts JSON there after each change:
|
||||||
@@ -104,6 +150,7 @@ An integration can be told about changes. In Admin → Integrations, give it a w
|
|||||||
| `squawk.updated` | A squawk is changed |
|
| `squawk.updated` | A squawk is changed |
|
||||||
| `squawk.resolved` | A squawk is resolved |
|
| `squawk.resolved` | A squawk is resolved |
|
||||||
| `entry.signed` | A logbook entry is signed |
|
| `entry.signed` | A logbook entry is signed |
|
||||||
|
| `draft_batch.completed` | Every entry of a draft is signed, and what it resolves is done |
|
||||||
|
|
||||||
Only events on the integration's aircraft are sent. The body:
|
Only events on the integration's aircraft are sent. The body:
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
require "test_helper"
|
||||||
|
|
||||||
|
# Draft logbook entries through the API: one unsigned entry per logbook,
|
||||||
|
# signed in the app; the squawks and inspections they resolve wait for the
|
||||||
|
# signatures.
|
||||||
|
class ApiDraftsTest < ActionDispatch::IntegrationTest
|
||||||
|
include ActionMailer::TestHelper
|
||||||
|
|
||||||
|
setup do
|
||||||
|
@admin = create_user("admin@example.com", admin: true)
|
||||||
|
@owner = create_user("owner@example.com")
|
||||||
|
@mech = create_user("mech@example.com").tap { _1.update!(name: "Sam Mechanic") }
|
||||||
|
@a = create_aircraft(owner: @owner, pilot: @mech, tail_number: "N12345")
|
||||||
|
@ap = @mech.certificates.create!(kind: "AP", number: "7654321")
|
||||||
|
@ia = @mech.certificates.create!(kind: "IA", number: "7654321", expires_on: Date.current + 200)
|
||||||
|
@brake = @a.squawks.create!(issue_reported: "Left brake soft", priority: 0, reported_by: @mech)
|
||||||
|
@annual = InspectionType.create!(name: "Annual", recurring: true, recurring_months: 12).tap { _1.aircraft << @a }
|
||||||
|
@token = ApiToken.create!(name: "Redmine", kind: "integration", user: @admin, scopes: %w[read drafts:write], aircraft_ids: [ @a.id ])
|
||||||
|
end
|
||||||
|
|
||||||
|
test "a visit's work becomes one draft entry per logbook; nothing is resolved until all are signed" do
|
||||||
|
post "/api/v1/aircraft/#{@a.id}/draft_batches", params: batch_params, headers: headers(as: @owner), as: :json
|
||||||
|
assert_response :created
|
||||||
|
data = JSON.parse(response.body)["data"]
|
||||||
|
batch = DraftBatch.find(data["id"])
|
||||||
|
assert_equal [ "AC", "ENG" ], data["entries"].map { _1["log"] }
|
||||||
|
ac, eng = batch.entries.order(:log_type).to_a
|
||||||
|
assert_equal "Replaced left brake linings.\n\nAnnual inspection.", ac.text
|
||||||
|
assert_equal [ "INSPECTION", "MAINTENANCE", "1234.5" ], [ ac.entry_type, eng.entry_type, eng.aircraft_hours_at_entry.to_s ]
|
||||||
|
assert_equal "redmine:issue:2,redmine:issue:3", ac.external_ref
|
||||||
|
assert data["entries"].all? { _1["sign_url"] && _1["invitation_url"].nil? }
|
||||||
|
assert @a.events.exists?(category: "logbook")
|
||||||
|
|
||||||
|
sign_in @mech
|
||||||
|
get new_aircraft_logbook_entry_signature_path(@a, ac)
|
||||||
|
assert_includes response.body, "When all 2 entries of this draft are signed, this also:"
|
||||||
|
assert_includes response.body, "Resolves the squawk: Left brake soft"
|
||||||
|
assert_includes response.body, "Records the Annual as completed"
|
||||||
|
|
||||||
|
sign(ac, @ia)
|
||||||
|
assert ac.reload.signed?
|
||||||
|
assert_equal "approved", ac.inspection_result
|
||||||
|
assert_not @brake.reload.resolved?, "held until every entry is signed"
|
||||||
|
assert_empty @a.inspection_records
|
||||||
|
|
||||||
|
webhook = @token.webhook_endpoints.create!(url: "https://redmine.example.com/sam", secret: "s" * 32, events: %w[draft_batch.completed])
|
||||||
|
stub_request(:post, "https://redmine.example.com/sam").to_return(status: 200)
|
||||||
|
perform_enqueued_jobs { sign(eng) }
|
||||||
|
assert @brake.reload.resolved?
|
||||||
|
assert_equal ac, @brake.logbook_entry, "resolved by the airframe entry that described the work"
|
||||||
|
assert_equal [ [ @annual, ac ] ], @a.inspection_records.map { [ _1.inspection_type, _1.logbook_entry ] }
|
||||||
|
assert_equal "completed", batch.reload.status
|
||||||
|
assert_equal @mech.id, @brake.versions.last.user_id, "the change is attributed to the person who signed"
|
||||||
|
assert_equal "completed", JSON.parse(webhook.deliveries.last.payload).dig("data", "status")
|
||||||
|
end
|
||||||
|
|
||||||
|
test "a signer without an account gets a link, returned to the caller (and emailed only when asked)" do
|
||||||
|
params = batch_params
|
||||||
|
params[:draft_batch][:signer] = { email: "Outside.Mech@Example.com" }
|
||||||
|
assert_no_emails do
|
||||||
|
perform_enqueued_jobs { post "/api/v1/aircraft/#{@a.id}/draft_batches", params: params, headers: headers(as: @owner), as: :json }
|
||||||
|
end
|
||||||
|
entries = JSON.parse(response.body).dig("data", "entries")
|
||||||
|
assert entries.all? { _1["invitation_url"].to_s.include?("/sign/") }
|
||||||
|
token = entries.first["invitation_url"][%r{/sign/(.+)\z}, 1]
|
||||||
|
invitation = SigningInvitation.find_usable(token)
|
||||||
|
assert_equal "outside.mech@example.com", invitation.email
|
||||||
|
end
|
||||||
|
|
||||||
|
test "drafts are for owners: an integration must act for one, with the drafts scope" do
|
||||||
|
post "/api/v1/aircraft/#{@a.id}/draft_batches", params: batch_params, headers: headers(as: @mech), as: :json
|
||||||
|
assert_response :forbidden
|
||||||
|
assert_equal "owners_only", JSON.parse(response.body).dig("error", "code")
|
||||||
|
@token.update!(scopes: %w[read])
|
||||||
|
post "/api/v1/aircraft/#{@a.id}/draft_batches", params: batch_params, headers: headers(as: @owner), as: :json
|
||||||
|
assert_equal "missing_scope", JSON.parse(response.body).dig("error", "code")
|
||||||
|
assert_equal 0, DraftBatch.count
|
||||||
|
end
|
||||||
|
|
||||||
|
test "bad drafts are refused with the fields at fault, and nothing is made" do
|
||||||
|
params = { draft_batch: { date: "not a date", items: [ { log: "WING", text: "" } ], completes_inspections: [ { inspection_type_id: 999 } ],
|
||||||
|
signer: { email: "nope" } } }
|
||||||
|
params[:draft_batch][:items].first[:resolves_squawks] = [ @brake.id + 1000 ]
|
||||||
|
post "/api/v1/aircraft/#{@a.id}/draft_batches", params: params, headers: headers(as: @owner), as: :json
|
||||||
|
assert_response :unprocessable_entity
|
||||||
|
fields = JSON.parse(response.body).dig("error", "fields")
|
||||||
|
assert_equal %w[aircraft_hours completes_inspections.0 completes_inspections.0.result date items.0.log items.0.text resolves_squawks signer.email].sort, fields.keys.sort
|
||||||
|
assert_equal 0, LogbookEntry.count
|
||||||
|
end
|
||||||
|
|
||||||
|
test "an unsigned draft can be withdrawn; once part is signed it can't" do
|
||||||
|
post "/api/v1/aircraft/#{@a.id}/draft_batches", params: batch_params, headers: headers(as: @owner), as: :json
|
||||||
|
batch = DraftBatch.find(JSON.parse(response.body).dig("data", "id"))
|
||||||
|
delete "/api/v1/draft_batches/#{batch.id}", headers: headers(as: @owner)
|
||||||
|
assert_response :success
|
||||||
|
assert_equal [ "withdrawn", 0 ], [ batch.reload.status, batch.entries.count ]
|
||||||
|
assert_not @brake.reload.resolved?
|
||||||
|
|
||||||
|
post "/api/v1/aircraft/#{@a.id}/draft_batches", params: batch_params, headers: headers(as: @owner).merge("Idempotency-Key" => "second"), as: :json
|
||||||
|
second = DraftBatch.find(JSON.parse(response.body).dig("data", "id"))
|
||||||
|
sign_in @mech
|
||||||
|
sign(second.entries.find_by(log_type: "ENG"))
|
||||||
|
delete "/api/v1/draft_batches/#{second.id}", headers: headers(as: @owner)
|
||||||
|
assert_response :conflict
|
||||||
|
end
|
||||||
|
|
||||||
|
test "drafts can be found by the other system's reference" do
|
||||||
|
post "/api/v1/aircraft/#{@a.id}/draft_batches", params: batch_params, headers: headers(as: @owner), as: :json
|
||||||
|
get "/api/v1/draft_batches", params: { external_ref: "redmine:visit:77" }, headers: headers
|
||||||
|
assert_equal 1, JSON.parse(response.body)["data"].size
|
||||||
|
get "/api/v1/aircraft/#{@a.id}/draft_batches", params: { status: "awaiting_signature" }, headers: headers
|
||||||
|
assert_equal 1, JSON.parse(response.body)["data"].size
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def batch_params
|
||||||
|
{ draft_batch: {
|
||||||
|
date: Date.current.iso8601, aircraft_hours: "1234.5", external_ref: "redmine:visit:77",
|
||||||
|
items: [
|
||||||
|
{ log: "ENG", text: "Changed oil and filter.", external_ref: "redmine:issue:1" },
|
||||||
|
{ log: "AC", text: "Replaced left brake linings.", resolves_squawks: [ @brake.id ], external_ref: "redmine:issue:2" },
|
||||||
|
{ log: "AC", text: "Annual inspection.", external_ref: "redmine:issue:3" }
|
||||||
|
],
|
||||||
|
completes_inspections: [ { inspection_type_id: @annual.id, result: "approved" } ]
|
||||||
|
} }
|
||||||
|
end
|
||||||
|
|
||||||
|
def headers(as: nil)
|
||||||
|
{ "Authorization" => "Bearer #{@token.token}" }.tap { |h| h["SAM-On-Behalf-Of"] = as.email_address if as }
|
||||||
|
end
|
||||||
|
|
||||||
|
def sign(entry, certificate = @ap)
|
||||||
|
post aircraft_logbook_entry_signature_path(@a, entry), params: { certificate_id: certificate.id, password: "test-password-123", confirm: "1" }
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -100,4 +100,12 @@ class ApiManagementTest < ActionDispatch::IntegrationTest
|
|||||||
assert_response :success
|
assert_response :success
|
||||||
assert_select "h1", "REST API"
|
assert_select "h1", "REST API"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
test "the suggested procedures describe the API once it's in use" do
|
||||||
|
assert_no_match "API", ProceduresTemplates.hosting
|
||||||
|
ApiToken.create!(name: "Redmine", kind: "integration", user: @admin, scopes: %w[read], aircraft_ids: [ @a.id ])
|
||||||
|
text = ProceduresTemplates.hosting
|
||||||
|
assert_match "The following programs are connected: Redmine.", text
|
||||||
|
assert_match "cannot sign an entry", text
|
||||||
|
end
|
||||||
end
|
end
|
||||||
Reference in new issue
Block a user