diff --git a/app/controllers/aircraft_controller.rb b/app/controllers/aircraft_controller.rb index 0a94489..01c0cfc 100644 --- a/app/controllers/aircraft_controller.rb +++ b/app/controllers/aircraft_controller.rb @@ -9,7 +9,7 @@ class AircraftController < ApplicationController def show @airworthiness = @aircraft.airworthiness - @active_squawks = @aircraft.squawks.active.by_priority.includes(:component, :reported_by) + @active_squawks = @aircraft.squawks.active.by_priority.includes(:component, :reported_by).with_attached_attachments @recent_events = @aircraft.events.includes(:user).limit(8) @notes = @aircraft.notes.recent_first.includes(:user).limit(5) @oil = ConsumptionStats.new(@aircraft, "oil") diff --git a/app/controllers/components_controller.rb b/app/controllers/components_controller.rb index 501da25..cc9489a 100644 --- a/app/controllers/components_controller.rb +++ b/app/controllers/components_controller.rb @@ -22,7 +22,7 @@ class ComponentsController < ApplicationController end def show - @squawks = @component.squawks.by_priority + @squawks = @component.squawks.by_priority.with_attached_attachments end def new diff --git a/app/controllers/squawks_controller.rb b/app/controllers/squawks_controller.rb index 619cfea..c53b5b9 100644 --- a/app/controllers/squawks_controller.rb +++ b/app/controllers/squawks_controller.rb @@ -5,8 +5,8 @@ class SquawksController < ApplicationController before_action :set_squawk, only: %i[edit update destroy resolve reopen] def index - @active = @aircraft.squawks.active.by_priority.includes(:component, :reported_by) - @resolved = @aircraft.squawks.resolved.order(resolved_at: :desc).includes(:component).limit(100) + @active = @aircraft.squawks.active.by_priority.includes(:component, :reported_by).with_attached_attachments + @resolved = @aircraft.squawks.resolved.order(resolved_at: :desc).includes(:component).with_attached_attachments.limit(100) end def new @@ -26,7 +26,9 @@ class SquawksController < ApplicationController def edit; end def update - if @squawk.update(squawk_params) + @squawk.assign_attributes(squawk_params.except(:attachments)) + change_attachments + if @squawk.save log_event("squawk", "Squawk updated") redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk updated." else @@ -56,7 +58,17 @@ class SquawksController < ApplicationController def set_squawk = @squawk = @aircraft.squawks.find(params[:id]) + # Adds uploads and drops ticked files in one change, so nothing is saved + # (or purged) unless the whole update validates. + def change_attachments + added = Array(squawk_params[:attachments]).compact_blank + removed = Array(params[:remove_attachment_ids]).map(&:to_s) + return if added.empty? && removed.empty? + kept = @squawk.attachments.reject { removed.include?(_1.id.to_s) }.map(&:blob) + @squawk.attachments = kept + added + end + def squawk_params - params.require(:squawk).permit(:priority, :issue_reported, :component_id, :notes, :attachment) + params.require(:squawk).permit(:priority, :issue_reported, :component_id, :notes, attachments: []) end end diff --git a/app/javascript/controllers/gallery_controller.js b/app/javascript/controllers/gallery_controller.js new file mode 100644 index 0000000..2618ce0 --- /dev/null +++ b/app/javascript/controllers/gallery_controller.js @@ -0,0 +1,69 @@ +import { Controller } from "@hotwired/stimulus" + +// In-app photo viewer for a set of image links. Click a photo to open it +// full-screen; ←/→, swipe or the arrow buttons move between photos, Esc or a +// click on the backdrop closes. Ctrl/⌘-click still opens the image in a tab. +export default class extends Controller { + static targets = [ "item", "dialog", "image", "caption", "counter", "download", "original", "nav" ] + + connect() { + this.index = 0 + } + + disconnect() { + if (this.hasDialogTarget && this.dialogTarget.open) this.dialogTarget.close() + } + + open(event) { + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button > 0) return + event.preventDefault() + this.show(this.itemTargets.indexOf(event.currentTarget)) + this.dialogTarget.showModal() + } + + close() { + this.dialogTarget.close() + } + + next() { this.show(this.index + 1) } + previous() { this.show(this.index - 1) } + + keydown(event) { + if (event.key === "ArrowRight") { event.preventDefault(); this.next() } + if (event.key === "ArrowLeft") { event.preventDefault(); this.previous() } + } + + // The backdrop is the dialog element itself; clicks on the photo or controls aren't. + backdrop(event) { + if (event.target === this.dialogTarget || event.target.dataset.galleryClose !== undefined) this.close() + } + + touchstart(event) { + this.touchX = event.changedTouches[0].clientX + } + + touchend(event) { + if (this.touchX == null) return + const dx = event.changedTouches[0].clientX - this.touchX + this.touchX = null + if (Math.abs(dx) > 50) dx < 0 ? this.next() : this.previous() + } + + show(index) { + const items = this.itemTargets + this.index = (index + items.length) % items.length + const item = items[this.index] + const name = item.dataset.galleryName + + this.imageTarget.src = item.href + this.imageTarget.alt = name + this.captionTarget.textContent = name + this.downloadTarget.href = item.dataset.galleryDownload + this.originalTarget.href = item.href + this.counterTarget.textContent = items.length > 1 ? `${this.index + 1} / ${items.length}` : "" + this.navTargets.forEach((el) => { el.hidden = items.length < 2 }) + + // Preload the neighbours so swiping feels instant. + if (items.length > 1) [ this.index + 1, this.index - 1 ].forEach((i) => { new Image().src = items[(i + items.length) % items.length].href }) + } +} diff --git a/app/models/squawk.rb b/app/models/squawk.rb index 638adff..4a02a71 100644 --- a/app/models/squawk.rb +++ b/app/models/squawk.rb @@ -7,11 +7,11 @@ class Squawk < ApplicationRecord belongs_to :aircraft belongs_to :component, optional: true belongs_to :reported_by, class_name: "User", optional: true - has_one_attached :attachment + has_many_attached :attachments validates :priority, inclusion: { in: PRIORITIES.keys } validates :issue_reported, presence: true - validates_uploads :attachment + validates_uploads :attachments scope :active, -> { where(resolved: false) } scope :resolved, -> { where(resolved: true) } diff --git a/app/views/squawks/_attachments.html.erb b/app/views/squawks/_attachments.html.erb new file mode 100644 index 0000000..d1eb51c --- /dev/null +++ b/app/views/squawks/_attachments.html.erb @@ -0,0 +1,55 @@ +<%# A squawk's files: photos open in the in-app viewer, everything else opens in + a new tab. Every file has a download link. %> +<% files = squawk.attachments.to_a %> +<% if files.any? %> + <% photos, others = files.partition(&:image?) %> +
+ + + <% if photos.any? %> + +
+
+ + + Open + ⬇ Download + +
+
+ + + +
+
+
+ <% end %> +
+<% end %> diff --git a/app/views/squawks/_form.html.erb b/app/views/squawks/_form.html.erb index 7fe8edb..2cc3f88 100644 --- a/app/views/squawks/_form.html.erb +++ b/app/views/squawks/_form.html.erb @@ -1,9 +1,18 @@ -<%= form_with model: [aircraft, squawk], class: "card card-body space-y-4 max-w-2xl" do |f| %> +<%= form_with model: [aircraft, squawk], multipart: true, class: "card card-body space-y-4 max-w-2xl" do |f| %> <%= f.errors_summary %> <%= f.field :priority, as: :select, collection: Squawk::PRIORITIES.invert, hint: "“Ground Aircraft” makes the aircraft not airworthy until resolved." %> <%= f.field :issue_reported, as: :textarea, label: "Issue", required: true, autofocus: true %> <%= f.field :component_id, as: :select, label: "Component (optional)", collection: component_options(aircraft) %> - <%= f.field :attachment, as: :file, label: "Photo / attachment" %> + <%= f.field :attachments, as: :file, multiple: true, label: squawk.attachments.attached? ? "Add photos / files" : "Photos / files", + hint: "Select several at once. Images, PDFs or text, up to 50 MB each." %> + <% if squawk.persisted? && squawk.attachments.attached? %> +
+

Remove attached files

+ <% squawk.attachments.each do |file| %> + + <% end %> +
+ <% end %> <% if squawk.persisted? %><%= f.field :notes, as: :textarea, rows: 3 %><% end %>
<%= f.submit squawk.new_record? ? "Report Squawk" : "Save" %> diff --git a/app/views/squawks/_table.html.erb b/app/views/squawks/_table.html.erb index 7b4eef6..30c2bc2 100644 --- a/app/views/squawks/_table.html.erb +++ b/app/views/squawks/_table.html.erb @@ -7,7 +7,7 @@ <%= squawk_priority_badge(s) %> <%= s.issue_reported %> - <% if s.attachment.attached? %>
<%= link_to "📎 #{s.attachment.filename}", rails_blob_path(s.attachment, disposition: :inline), class: "link text-xs", target: "_blank" %>
<% end %> + <%= render "squawks/attachments", squawk: s %> <% if s.notes.present? %>
<%= s.notes %>
<% end %> <%= s.component&.to_s || "—" %> diff --git a/app/views/squawks/index.html.erb b/app/views/squawks/index.html.erb index 95a4110..84208f5 100644 --- a/app/views/squawks/index.html.erb +++ b/app/views/squawks/index.html.erb @@ -17,7 +17,7 @@ <% @resolved.each do |s| %> <%= squawk_priority_badge(s) %> - <%= s.issue_reported %> + <%= s.issue_reported %><%= render "squawks/attachments", squawk: s %> <%= s.notes %> <%= s.resolved_at&.to_date %> <% if owner? %><%= button_to "Reopen", reopen_aircraft_squawk_path(@aircraft, s), method: :patch, class: "btn-secondary btn-sm" %><% end %> diff --git a/db/migrate/20261106170000_rename_squawk_attachment_to_attachments.rb b/db/migrate/20261106170000_rename_squawk_attachment_to_attachments.rb new file mode 100644 index 0000000..4059726 --- /dev/null +++ b/db/migrate/20261106170000_rename_squawk_attachment_to_attachments.rb @@ -0,0 +1,16 @@ +# Squawks go from one attachment to many; keep the files already uploaded. +class RenameSquawkAttachmentToAttachments < ActiveRecord::Migration[8.1] + def up + execute "UPDATE active_storage_attachments SET name = 'attachments' WHERE record_type = 'Squawk' AND name = 'attachment'" + end + + def down + # Only the first file per squawk fits back into a single attachment. + execute <<~SQL + DELETE FROM active_storage_attachments + WHERE record_type = 'Squawk' AND name = 'attachments' + AND id NOT IN (SELECT MIN(id) FROM active_storage_attachments WHERE record_type = 'Squawk' AND name = 'attachments' GROUP BY record_id) + SQL + execute "UPDATE active_storage_attachments SET name = 'attachment' WHERE record_type = 'Squawk' AND name = 'attachments'" + end +end diff --git a/db/schema.rb b/db/schema.rb index f85b209..4e0654a 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.1].define(version: 2026_11_06_160000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_06_170000) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false diff --git a/test/integration/squawk_attachments_test.rb b/test/integration/squawk_attachments_test.rb new file mode 100644 index 0000000..96539b1 --- /dev/null +++ b/test/integration/squawk_attachments_test.rb @@ -0,0 +1,93 @@ +require "test_helper" + +class SquawkAttachmentsTest < ActionDispatch::IntegrationTest + setup do + @owner = create_user("owner@example.com") + @pilot = create_user("pilot@example.com") + @a = create_aircraft(owner: @owner, pilot: @pilot) + end + + def upload(name, type = "text/plain", body = "file #{name}") + Rack::Test::UploadedFile.new(StringIO.new(body), type, original_filename: name) + end + + test "a pilot can report a squawk with several files" do + sign_in @pilot + post aircraft_squawks_path(@a), params: { squawk: { priority: 1, issue_reported: "Cracked fairing", + attachments: [ "", upload("front.jpg", "image/jpeg"), upload("notes.txt") ] } } + squawk = @a.squawks.last + assert_equal %w[front.jpg notes.txt], squawk.attachments.map { _1.filename.to_s }.sort + + get aircraft_squawks_path(@a) + assert_select "[data-controller=gallery]" do + assert_select "a[data-gallery-target=item][data-action='gallery#open'][href*='front.jpg']", text: /🖼/ + assert_select "a[data-gallery-target=item]", 1 # only photos open in the viewer + assert_select "a[target=_blank][href*='notes.txt']", text: /📎/ + assert_select "dialog[data-gallery-target=dialog] a[data-gallery-target=download]" + end + end + + test "every file has a download link that forces a download" do + @a.squawks.create!(priority: 1, issue_reported: "x", attachments: [ upload("pic.png", "image/png"), upload("log.pdf", "application/pdf") ]) + sign_in @pilot + get aircraft_squawks_path(@a) + downloads = css_select("a[download]").reject { _1["data-gallery-target"] } + assert_equal %w[log.pdf pic.png], downloads.map { _1["download"] }.sort + downloads.each do |link| + get link["href"] + follow_redirect! while response.redirect? + assert_match(/\Aattachment;/, response.headers["Content-Disposition"]) + end + end + + test "squawks with no photos get no viewer" do + @a.squawks.create!(priority: 1, issue_reported: "x", attachments: [ upload("notes.txt") ]) + sign_in @pilot + get aircraft_squawks_path(@a) + assert_select "dialog", 0 + assert_select "a[download='notes.txt']" + end + + test "an owner can add files and remove some in one edit" do + squawk = @a.squawks.create!(priority: 1, issue_reported: "Oil leak", attachments: [ upload("a.txt"), upload("b.txt") ]) + a_file = squawk.attachments.find { _1.filename.to_s == "a.txt" } + sign_in @owner + + get edit_aircraft_squawk_path(@a, squawk) + assert_select "input[type=file][multiple][name='squawk[attachments][]']" + assert_select "input[type=checkbox][name='remove_attachment_ids[]']", 2 + + patch aircraft_squawk_path(@a, squawk), params: { squawk: { issue_reported: "Oil leak at sump", attachments: [ "", upload("c.txt") ] }, + remove_attachment_ids: [ a_file.id ] } + assert_redirected_to aircraft_squawks_path(@a) + squawk.reload + assert_equal "Oil leak at sump", squawk.issue_reported + assert_equal %w[b.txt c.txt], squawk.attachments.map { _1.filename.to_s }.sort + end + + test "editing without touching files keeps them" do + squawk = @a.squawks.create!(priority: 1, issue_reported: "x", attachments: [ upload("a.txt") ]) + sign_in @owner + patch aircraft_squawk_path(@a, squawk), params: { squawk: { notes: "Ordered part", attachments: [ "" ] } } + assert_equal %w[a.txt], squawk.reload.attachments.map { _1.filename.to_s } + end + + test "a bad file rejects the whole edit and removes nothing" do + squawk = @a.squawks.create!(priority: 1, issue_reported: "Oil leak", attachments: [ upload("a.txt") ]) + sign_in @owner + patch aircraft_squawk_path(@a, squawk), params: { squawk: { issue_reported: "Changed", attachments: [ upload("run.exe", "application/x-msdownload") ] }, + remove_attachment_ids: [ squawk.attachments.first.id ] } + assert_response :unprocessable_entity + assert_match "run.exe is not an allowed file type", response.body + squawk.reload + assert_equal "Oil leak", squawk.issue_reported + assert_equal %w[a.txt], squawk.attachments.map { _1.filename.to_s } + end + + test "pilots can't edit a squawk's files" do + squawk = @a.squawks.create!(priority: 1, issue_reported: "x", attachments: [ upload("a.txt") ]) + sign_in @pilot + patch aircraft_squawk_path(@a, squawk), params: { remove_attachment_ids: [ squawk.attachments.first.id ], squawk: { notes: "y" } } + assert_equal 1, squawk.reload.attachments.count + end +end