From 38df19c331aa9dfc51e9c4b606249d266fb490b0 Mon Sep 17 00:00:00 2001 From: Rick Barrette Date: Wed, 4 Nov 2026 17:59:08 -0500 Subject: [PATCH] Initial commit: Rails port of Simple Aircraft Manager Rails 8.1 + SQLite rewrite of marbindrakon/simple-aircraft-manager, designed to self-host as a single container (Solid Queue/Cache/Cable, Active Storage on disk, Hotwire + importmap, Tailwind). - Airworthiness engine ported from health/services.py (ADs, grounding squawks, inspection recurrency, component replacement) - Hours updates and flight logs cascading to in-service components, optional airworthiness enforcement - Components, squawks, ADs, inspections, logbook, documents, major records, oil/fuel consumption stats and charts, activity log - Admin/owner/pilot RBAC and public share links (status/maintenance) - Docker Compose and Kamal deployment, env-driven production config - Service and integration tests Co-Authored-By: Claude Opus 5.5 --- .dockerignore | 51 ++ .env.example | 12 + .gitattributes | 9 + .github/dependabot.yml | 12 + .github/workflows/ci.yml | 90 +++ .gitignore | 41 ++ .kamal/hooks/docker-setup.sample | 3 + .kamal/hooks/post-app-boot.sample | 3 + .kamal/hooks/post-deploy.sample | 14 + .kamal/hooks/post-proxy-reboot.sample | 3 + .kamal/hooks/pre-app-boot.sample | 3 + .kamal/hooks/pre-build.sample | 51 ++ .kamal/hooks/pre-connect.sample | 47 ++ .kamal/hooks/pre-deploy.sample | 122 ++++ .kamal/hooks/pre-proxy-reboot.sample | 3 + .kamal/secrets | 17 + .rubocop.yml | 8 + .ruby-version | 1 + Dockerfile | 73 +++ Gemfile | 67 +++ Gemfile.lock | 566 ++++++++++++++++++ Procfile.dev | 2 + README.md | 129 ++++ Rakefile | 6 + app/assets/builds/.keep | 0 app/assets/images/.keep | 0 app/assets/stylesheets/application.css | 10 + app/assets/tailwind/application.css | 36 ++ app/channels/application_cable/connection.rb | 16 + app/controllers/ad_compliances_controller.rb | 57 ++ .../admin/component_types_controller.rb | 44 ++ app/controllers/admin/users_controller.rb | 50 ++ app/controllers/aircraft_controller.rb | 74 +++ app/controllers/aircraft_roles_controller.rb | 54 ++ .../airworthiness_directives_controller.rb | 74 +++ app/controllers/application_controller.rb | 28 + app/controllers/components_controller.rb | 90 +++ app/controllers/concerns/.keep | 0 app/controllers/concerns/aircraft_scoped.rb | 46 ++ app/controllers/concerns/applicability.rb | 38 ++ app/controllers/concerns/authentication.rb | 52 ++ .../consumable_records_controller.rb | 53 ++ .../document_collections_controller.rb | 41 ++ app/controllers/documents_controller.rb | 62 ++ app/controllers/events_controller.rb | 10 + app/controllers/flight_logs_controller.rb | 47 ++ .../inspection_records_controller.rb | 51 ++ .../inspection_types_controller.rb | 56 ++ app/controllers/inspections_controller.rb | 8 + app/controllers/logbook_entries_controller.rb | 57 ++ app/controllers/major_records_controller.rb | 59 ++ app/controllers/notes_controller.rb | 45 ++ app/controllers/passwords_controller.rb | 33 + app/controllers/profiles_controller.rb | 16 + app/controllers/sessions_controller.rb | 21 + app/controllers/setup_controller.rb | 20 + app/controllers/share_tokens_controller.rb | 22 + app/controllers/shared_controller.rb | 30 + app/controllers/squawks_controller.rb | 62 ++ app/form_builders/app_form_builder.rb | 54 ++ app/helpers/aircraft_helper.rb | 33 + app/helpers/application_helper.rb | 64 ++ app/javascript/application.js | 5 + app/javascript/controllers/application.js | 9 + .../controllers/hello_controller.js | 7 + app/javascript/controllers/index.js | 4 + app/jobs/application_job.rb | 7 + app/mailers/application_mailer.rb | 4 + app/mailers/passwords_mailer.rb | 6 + app/models/ad_compliance.rb | 16 + app/models/aircraft.rb | 73 +++ app/models/aircraft_event.rb | 15 + app/models/aircraft_note.rb | 8 + app/models/aircraft_role.rb | 11 + app/models/airworthiness_directive.rb | 33 + app/models/application_record.rb | 3 + app/models/component.rb | 73 +++ app/models/component_type.rb | 6 + app/models/concerns/.keep | 0 app/models/concerns/upload_validation.rb | 27 + app/models/consumable_record.rb | 17 + app/models/current.rb | 4 + app/models/document.rb | 38 ++ app/models/document_collection.rb | 12 + app/models/flight_log.rb | 28 + app/models/inspection_record.rb | 22 + app/models/inspection_type.rb | 27 + app/models/logbook_entry.rb | 26 + app/models/major_record.rb | 16 + app/models/session.rb | 3 + app/models/share_token.rb | 28 + app/models/squawk.rb | 27 + app/models/user.rb | 27 + app/services/aircraft_grounded_error.rb | 11 + app/services/airworthiness.rb | 120 ++++ app/services/compliance.rb | 119 ++++ app/services/consumption_stats.rb | 58 ++ app/services/hours_service.rb | 75 +++ app/views/ad_compliances/_form.html.erb | 15 + app/views/ad_compliances/edit.html.erb | 2 + app/views/ad_compliances/new.html.erb | 2 + .../admin/component_types/_form.html.erb | 7 + app/views/admin/component_types/edit.html.erb | 2 + .../admin/component_types/index.html.erb | 7 + app/views/admin/component_types/new.html.erb | 2 + app/views/admin/users/_form.html.erb | 10 + app/views/admin/users/edit.html.erb | 2 + app/views/admin/users/index.html.erb | 12 + app/views/admin/users/new.html.erb | 2 + app/views/aircraft/_form.html.erb | 30 + app/views/aircraft/edit.html.erb | 9 + app/views/aircraft/index.html.erb | 48 ++ app/views/aircraft/new.html.erb | 3 + app/views/aircraft/show.html.erb | 109 ++++ app/views/aircraft_roles/index.html.erb | 61 ++ .../airworthiness_directives/_form.html.erb | 27 + .../airworthiness_directives/edit.html.erb | 2 + .../airworthiness_directives/index.html.erb | 70 +++ .../airworthiness_directives/new.html.erb | 2 + app/views/components/_form.html.erb | 50 ++ app/views/components/edit.html.erb | 3 + app/views/components/index.html.erb | 52 ++ app/views/components/new.html.erb | 3 + app/views/components/show.html.erb | 61 ++ app/views/consumable_records/_form.html.erb | 15 + app/views/consumable_records/edit.html.erb | 2 + app/views/consumable_records/index.html.erb | 51 ++ app/views/consumable_records/new.html.erb | 2 + app/views/document_collections/_form.html.erb | 9 + app/views/document_collections/edit.html.erb | 2 + app/views/document_collections/new.html.erb | 2 + app/views/documents/_doc_row.html.erb | 11 + app/views/documents/_form.html.erb | 24 + app/views/documents/_viewer.html.erb | 21 + app/views/documents/edit.html.erb | 2 + app/views/documents/index.html.erb | 39 ++ app/views/documents/new.html.erb | 2 + app/views/documents/show.html.erb | 18 + app/views/errors/not_found.html.erb | 5 + app/views/events/_list.html.erb | 16 + app/views/events/index.html.erb | 11 + app/views/flight_logs/index.html.erb | 28 + app/views/flight_logs/new.html.erb | 36 ++ app/views/flight_logs/show.html.erb | 15 + app/views/inspection_records/_form.html.erb | 13 + app/views/inspection_records/edit.html.erb | 2 + app/views/inspection_records/new.html.erb | 2 + app/views/inspection_types/_form.html.erb | 19 + app/views/inspection_types/edit.html.erb | 2 + app/views/inspection_types/new.html.erb | 2 + app/views/inspections/index.html.erb | 54 ++ app/views/layouts/application.html.erb | 43 ++ app/views/layouts/mailer.html.erb | 13 + app/views/layouts/mailer.text.erb | 1 + app/views/layouts/public.html.erb | 22 + app/views/logbook_entries/_form.html.erb | 18 + app/views/logbook_entries/edit.html.erb | 2 + app/views/logbook_entries/index.html.erb | 36 ++ app/views/logbook_entries/new.html.erb | 2 + app/views/logbook_entries/show.html.erb | 18 + app/views/major_records/_form.html.erb | 24 + app/views/major_records/edit.html.erb | 2 + app/views/major_records/index.html.erb | 27 + app/views/major_records/new.html.erb | 2 + app/views/major_records/show.html.erb | 19 + app/views/notes/_form.html.erb | 7 + app/views/notes/edit.html.erb | 2 + app/views/notes/index.html.erb | 24 + app/views/notes/new.html.erb | 2 + app/views/passwords/edit.html.erb | 21 + app/views/passwords/new.html.erb | 17 + app/views/passwords_mailer/reset.html.erb | 4 + app/views/passwords_mailer/reset.text.erb | 2 + app/views/profiles/edit.html.erb | 9 + app/views/pwa/manifest.json.erb | 22 + app/views/pwa/service-worker.js | 26 + app/views/sessions/new.html.erb | 12 + app/views/setup/new.html.erb | 12 + app/views/shared/_aircraft_header.html.erb | 30 + .../shared/_applicability_fields.html.erb | 14 + app/views/shared/_flash.html.erb | 6 + app/views/shared/show.html.erb | 101 ++++ app/views/squawks/_form.html.erb | 15 + app/views/squawks/_table.html.erb | 25 + app/views/squawks/edit.html.erb | 3 + app/views/squawks/index.html.erb | 31 + app/views/squawks/new.html.erb | 3 + bin/brakeman | 7 + bin/dev | 16 + bin/docker-entrypoint | 14 + bin/importmap | 4 + bin/jobs | 6 + bin/kamal | 16 + bin/rails | 4 + bin/rake | 4 + bin/rubocop | 8 + bin/setup | 34 ++ bin/thrust | 5 + config.ru | 6 + config/application.rb | 30 + config/boot.rb | 4 + config/cable.yml | 17 + config/cache.yml | 16 + config/credentials.yml.enc | 1 + config/database.yml | 41 ++ config/deploy.yml | 116 ++++ config/environment.rb | 5 + config/environments/development.rb | 72 +++ config/environments/production.rb | 106 ++++ config/environments/test.rb | 53 ++ config/importmap.rb | 9 + config/initializers/assets.rb | 7 + .../initializers/content_security_policy.rb | 25 + .../initializers/filter_parameter_logging.rb | 8 + config/initializers/inflections.rb | 4 + config/locales/en.yml | 31 + config/puma.rb | 41 ++ config/queue.yml | 18 + config/recurring.yml | 15 + config/routes.rb | 50 ++ config/storage.yml | 34 ++ db/cable_schema.rb | 11 + db/cache_schema.rb | 12 + db/migrate/20261104222307_create_users.rb | 11 + db/migrate/20261104222308_create_sessions.rb | 11 + ...te_active_storage_tables.active_storage.rb | 57 ++ .../20261104222400_create_aircraft_domain.rb | 261 ++++++++ db/queue_schema.rb | 160 +++++ db/schema.rb | 423 +++++++++++++ db/seeds.rb | 91 +++ docker-compose.yml | 18 + lib/tasks/.keep | 0 log/.keep | 0 public/400.html | 114 ++++ public/404.html | 114 ++++ public/406-unsupported-browser.html | 114 ++++ public/422.html | 114 ++++ public/500.html | 114 ++++ public/icon.png | Bin 0 -> 4166 bytes public/icon.svg | 3 + public/robots.txt | 1 + script/.keep | 0 storage/.keep | 0 test/application_system_test_case.rb | 5 + test/controllers/.keep | 0 test/fixtures/files/.keep | 0 test/helpers/.keep | 0 test/integration/.keep | 0 test/integration/pages_test.rb | 104 ++++ test/integration/permissions_test.rb | 126 ++++ test/integration/setup_test.rb | 22 + test/mailers/.keep | 0 .../previews/passwords_mailer_preview.rb | 7 + test/models/.keep | 0 test/services/airworthiness_test.rb | 92 +++ test/services/consumption_stats_test.rb | 33 + test/services/hours_service_test.rb | 58 ++ test/system/.keep | 0 test/test_helper.rb | 36 ++ tmp/.keep | 0 tmp/pids/.keep | 0 tmp/storage/.keep | 0 vendor/.keep | 0 vendor/javascript/.keep | 0 264 files changed, 8365 insertions(+) create mode 100644 .dockerignore create mode 100644 .env.example create mode 100644 .gitattributes create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100755 .kamal/hooks/docker-setup.sample create mode 100755 .kamal/hooks/post-app-boot.sample create mode 100755 .kamal/hooks/post-deploy.sample create mode 100755 .kamal/hooks/post-proxy-reboot.sample create mode 100755 .kamal/hooks/pre-app-boot.sample create mode 100755 .kamal/hooks/pre-build.sample create mode 100755 .kamal/hooks/pre-connect.sample create mode 100755 .kamal/hooks/pre-deploy.sample create mode 100755 .kamal/hooks/pre-proxy-reboot.sample create mode 100644 .kamal/secrets create mode 100644 .rubocop.yml create mode 100644 .ruby-version create mode 100644 Dockerfile create mode 100644 Gemfile create mode 100644 Gemfile.lock create mode 100644 Procfile.dev create mode 100644 README.md create mode 100644 Rakefile create mode 100644 app/assets/builds/.keep create mode 100644 app/assets/images/.keep create mode 100644 app/assets/stylesheets/application.css create mode 100644 app/assets/tailwind/application.css create mode 100644 app/channels/application_cable/connection.rb create mode 100644 app/controllers/ad_compliances_controller.rb create mode 100644 app/controllers/admin/component_types_controller.rb create mode 100644 app/controllers/admin/users_controller.rb create mode 100644 app/controllers/aircraft_controller.rb create mode 100644 app/controllers/aircraft_roles_controller.rb create mode 100644 app/controllers/airworthiness_directives_controller.rb create mode 100644 app/controllers/application_controller.rb create mode 100644 app/controllers/components_controller.rb create mode 100644 app/controllers/concerns/.keep create mode 100644 app/controllers/concerns/aircraft_scoped.rb create mode 100644 app/controllers/concerns/applicability.rb create mode 100644 app/controllers/concerns/authentication.rb create mode 100644 app/controllers/consumable_records_controller.rb create mode 100644 app/controllers/document_collections_controller.rb create mode 100644 app/controllers/documents_controller.rb create mode 100644 app/controllers/events_controller.rb create mode 100644 app/controllers/flight_logs_controller.rb create mode 100644 app/controllers/inspection_records_controller.rb create mode 100644 app/controllers/inspection_types_controller.rb create mode 100644 app/controllers/inspections_controller.rb create mode 100644 app/controllers/logbook_entries_controller.rb create mode 100644 app/controllers/major_records_controller.rb create mode 100644 app/controllers/notes_controller.rb create mode 100644 app/controllers/passwords_controller.rb create mode 100644 app/controllers/profiles_controller.rb create mode 100644 app/controllers/sessions_controller.rb create mode 100644 app/controllers/setup_controller.rb create mode 100644 app/controllers/share_tokens_controller.rb create mode 100644 app/controllers/shared_controller.rb create mode 100644 app/controllers/squawks_controller.rb create mode 100644 app/form_builders/app_form_builder.rb create mode 100644 app/helpers/aircraft_helper.rb create mode 100644 app/helpers/application_helper.rb create mode 100644 app/javascript/application.js create mode 100644 app/javascript/controllers/application.js create mode 100644 app/javascript/controllers/hello_controller.js create mode 100644 app/javascript/controllers/index.js create mode 100644 app/jobs/application_job.rb create mode 100644 app/mailers/application_mailer.rb create mode 100644 app/mailers/passwords_mailer.rb create mode 100644 app/models/ad_compliance.rb create mode 100644 app/models/aircraft.rb create mode 100644 app/models/aircraft_event.rb create mode 100644 app/models/aircraft_note.rb create mode 100644 app/models/aircraft_role.rb create mode 100644 app/models/airworthiness_directive.rb create mode 100644 app/models/application_record.rb create mode 100644 app/models/component.rb create mode 100644 app/models/component_type.rb create mode 100644 app/models/concerns/.keep create mode 100644 app/models/concerns/upload_validation.rb create mode 100644 app/models/consumable_record.rb create mode 100644 app/models/current.rb create mode 100644 app/models/document.rb create mode 100644 app/models/document_collection.rb create mode 100644 app/models/flight_log.rb create mode 100644 app/models/inspection_record.rb create mode 100644 app/models/inspection_type.rb create mode 100644 app/models/logbook_entry.rb create mode 100644 app/models/major_record.rb create mode 100644 app/models/session.rb create mode 100644 app/models/share_token.rb create mode 100644 app/models/squawk.rb create mode 100644 app/models/user.rb create mode 100644 app/services/aircraft_grounded_error.rb create mode 100644 app/services/airworthiness.rb create mode 100644 app/services/compliance.rb create mode 100644 app/services/consumption_stats.rb create mode 100644 app/services/hours_service.rb create mode 100644 app/views/ad_compliances/_form.html.erb create mode 100644 app/views/ad_compliances/edit.html.erb create mode 100644 app/views/ad_compliances/new.html.erb create mode 100644 app/views/admin/component_types/_form.html.erb create mode 100644 app/views/admin/component_types/edit.html.erb create mode 100644 app/views/admin/component_types/index.html.erb create mode 100644 app/views/admin/component_types/new.html.erb create mode 100644 app/views/admin/users/_form.html.erb create mode 100644 app/views/admin/users/edit.html.erb create mode 100644 app/views/admin/users/index.html.erb create mode 100644 app/views/admin/users/new.html.erb create mode 100644 app/views/aircraft/_form.html.erb create mode 100644 app/views/aircraft/edit.html.erb create mode 100644 app/views/aircraft/index.html.erb create mode 100644 app/views/aircraft/new.html.erb create mode 100644 app/views/aircraft/show.html.erb create mode 100644 app/views/aircraft_roles/index.html.erb create mode 100644 app/views/airworthiness_directives/_form.html.erb create mode 100644 app/views/airworthiness_directives/edit.html.erb create mode 100644 app/views/airworthiness_directives/index.html.erb create mode 100644 app/views/airworthiness_directives/new.html.erb create mode 100644 app/views/components/_form.html.erb create mode 100644 app/views/components/edit.html.erb create mode 100644 app/views/components/index.html.erb create mode 100644 app/views/components/new.html.erb create mode 100644 app/views/components/show.html.erb create mode 100644 app/views/consumable_records/_form.html.erb create mode 100644 app/views/consumable_records/edit.html.erb create mode 100644 app/views/consumable_records/index.html.erb create mode 100644 app/views/consumable_records/new.html.erb create mode 100644 app/views/document_collections/_form.html.erb create mode 100644 app/views/document_collections/edit.html.erb create mode 100644 app/views/document_collections/new.html.erb create mode 100644 app/views/documents/_doc_row.html.erb create mode 100644 app/views/documents/_form.html.erb create mode 100644 app/views/documents/_viewer.html.erb create mode 100644 app/views/documents/edit.html.erb create mode 100644 app/views/documents/index.html.erb create mode 100644 app/views/documents/new.html.erb create mode 100644 app/views/documents/show.html.erb create mode 100644 app/views/errors/not_found.html.erb create mode 100644 app/views/events/_list.html.erb create mode 100644 app/views/events/index.html.erb create mode 100644 app/views/flight_logs/index.html.erb create mode 100644 app/views/flight_logs/new.html.erb create mode 100644 app/views/flight_logs/show.html.erb create mode 100644 app/views/inspection_records/_form.html.erb create mode 100644 app/views/inspection_records/edit.html.erb create mode 100644 app/views/inspection_records/new.html.erb create mode 100644 app/views/inspection_types/_form.html.erb create mode 100644 app/views/inspection_types/edit.html.erb create mode 100644 app/views/inspection_types/new.html.erb create mode 100644 app/views/inspections/index.html.erb create mode 100644 app/views/layouts/application.html.erb create mode 100644 app/views/layouts/mailer.html.erb create mode 100644 app/views/layouts/mailer.text.erb create mode 100644 app/views/layouts/public.html.erb create mode 100644 app/views/logbook_entries/_form.html.erb create mode 100644 app/views/logbook_entries/edit.html.erb create mode 100644 app/views/logbook_entries/index.html.erb create mode 100644 app/views/logbook_entries/new.html.erb create mode 100644 app/views/logbook_entries/show.html.erb create mode 100644 app/views/major_records/_form.html.erb create mode 100644 app/views/major_records/edit.html.erb create mode 100644 app/views/major_records/index.html.erb create mode 100644 app/views/major_records/new.html.erb create mode 100644 app/views/major_records/show.html.erb create mode 100644 app/views/notes/_form.html.erb create mode 100644 app/views/notes/edit.html.erb create mode 100644 app/views/notes/index.html.erb create mode 100644 app/views/notes/new.html.erb create mode 100644 app/views/passwords/edit.html.erb create mode 100644 app/views/passwords/new.html.erb create mode 100644 app/views/passwords_mailer/reset.html.erb create mode 100644 app/views/passwords_mailer/reset.text.erb create mode 100644 app/views/profiles/edit.html.erb create mode 100644 app/views/pwa/manifest.json.erb create mode 100644 app/views/pwa/service-worker.js create mode 100644 app/views/sessions/new.html.erb create mode 100644 app/views/setup/new.html.erb create mode 100644 app/views/shared/_aircraft_header.html.erb create mode 100644 app/views/shared/_applicability_fields.html.erb create mode 100644 app/views/shared/_flash.html.erb create mode 100644 app/views/shared/show.html.erb create mode 100644 app/views/squawks/_form.html.erb create mode 100644 app/views/squawks/_table.html.erb create mode 100644 app/views/squawks/edit.html.erb create mode 100644 app/views/squawks/index.html.erb create mode 100644 app/views/squawks/new.html.erb create mode 100755 bin/brakeman create mode 100755 bin/dev create mode 100755 bin/docker-entrypoint create mode 100755 bin/importmap create mode 100755 bin/jobs create mode 100755 bin/kamal create mode 100755 bin/rails create mode 100755 bin/rake create mode 100755 bin/rubocop create mode 100755 bin/setup create mode 100755 bin/thrust create mode 100644 config.ru create mode 100644 config/application.rb create mode 100644 config/boot.rb create mode 100644 config/cable.yml create mode 100644 config/cache.yml create mode 100644 config/credentials.yml.enc create mode 100644 config/database.yml create mode 100644 config/deploy.yml create mode 100644 config/environment.rb create mode 100644 config/environments/development.rb create mode 100644 config/environments/production.rb create mode 100644 config/environments/test.rb create mode 100644 config/importmap.rb create mode 100644 config/initializers/assets.rb create mode 100644 config/initializers/content_security_policy.rb create mode 100644 config/initializers/filter_parameter_logging.rb create mode 100644 config/initializers/inflections.rb create mode 100644 config/locales/en.yml create mode 100644 config/puma.rb create mode 100644 config/queue.yml create mode 100644 config/recurring.yml create mode 100644 config/routes.rb create mode 100644 config/storage.yml create mode 100644 db/cable_schema.rb create mode 100644 db/cache_schema.rb create mode 100644 db/migrate/20261104222307_create_users.rb create mode 100644 db/migrate/20261104222308_create_sessions.rb create mode 100644 db/migrate/20261104222309_create_active_storage_tables.active_storage.rb create mode 100644 db/migrate/20261104222400_create_aircraft_domain.rb create mode 100644 db/queue_schema.rb create mode 100644 db/schema.rb create mode 100644 db/seeds.rb create mode 100644 docker-compose.yml create mode 100644 lib/tasks/.keep create mode 100644 log/.keep create mode 100644 public/400.html create mode 100644 public/404.html create mode 100644 public/406-unsupported-browser.html create mode 100644 public/422.html create mode 100644 public/500.html create mode 100644 public/icon.png create mode 100644 public/icon.svg create mode 100644 public/robots.txt create mode 100644 script/.keep create mode 100644 storage/.keep create mode 100644 test/application_system_test_case.rb create mode 100644 test/controllers/.keep create mode 100644 test/fixtures/files/.keep create mode 100644 test/helpers/.keep create mode 100644 test/integration/.keep create mode 100644 test/integration/pages_test.rb create mode 100644 test/integration/permissions_test.rb create mode 100644 test/integration/setup_test.rb create mode 100644 test/mailers/.keep create mode 100644 test/mailers/previews/passwords_mailer_preview.rb create mode 100644 test/models/.keep create mode 100644 test/services/airworthiness_test.rb create mode 100644 test/services/consumption_stats_test.rb create mode 100644 test/services/hours_service_test.rb create mode 100644 test/system/.keep create mode 100644 test/test_helper.rb create mode 100644 tmp/.keep create mode 100644 tmp/pids/.keep create mode 100644 tmp/storage/.keep create mode 100644 vendor/.keep create mode 100644 vendor/javascript/.keep diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..325bfc0 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,51 @@ +# See https://docs.docker.com/engine/reference/builder/#dockerignore-file for more about ignoring files. + +# Ignore git directory. +/.git/ +/.gitignore + +# Ignore bundler config. +/.bundle + +# Ignore all environment files. +/.env* + +# Ignore all default key files. +/config/master.key +/config/credentials/*.key + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/.keep + +# Ignore storage (uploaded files in development and any SQLite databases). +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/.keep + +# Ignore assets. +/node_modules/ +/app/assets/builds/* +!/app/assets/builds/.keep +/public/assets + +# Ignore CI service files. +/.github + +# Ignore Kamal files. +/config/deploy*.yml +/.kamal + +# Ignore development files +/.devcontainer + +# Ignore Docker-related files +/.dockerignore +/Dockerfile* diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..d81426a --- /dev/null +++ b/.env.example @@ -0,0 +1,12 @@ +# Generate with: bin/rails secret +SECRET_KEY_BASE=change-me +# Public hostname, used in password-reset email links +APP_HOST=localhost:3000 +# "true" when behind HTTPS (reverse proxy / Kamal). "false" for plain HTTP on a LAN. +FORCE_SSL=false +# Optional: enable password-reset emails +# SMTP_ADDRESS=smtp.example.com +# SMTP_PORT=587 +# SMTP_USERNAME= +# SMTP_PASSWORD= +# MAIL_FROM=aircraft@example.com diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8dc4323 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# See https://git-scm.com/docs/gitattributes for more about git attribute files. + +# Mark the database schema as having been generated. +db/schema.rb linguist-generated + +# Mark any vendored files as having been vendored. +vendor/* linguist-vendored +config/credentials/*.yml.enc diff=rails_credentials +config/credentials.yml.enc diff=rails_credentials diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..f0527e6 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +version: 2 +updates: +- package-ecosystem: bundler + directory: "/" + schedule: + interval: daily + open-pull-requests-limit: 10 +- package-ecosystem: github-actions + directory: "/" + schedule: + interval: daily + open-pull-requests-limit: 10 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..6185486 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,90 @@ +name: CI + +on: + pull_request: + push: + branches: [ main ] + +jobs: + scan_ruby: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: .ruby-version + bundler-cache: true + + - name: Scan for common Rails security vulnerabilities using static analysis + run: bin/brakeman --no-pager + + scan_js: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: .ruby-version + bundler-cache: true + + - name: Scan for security vulnerabilities in JavaScript dependencies + run: bin/importmap audit + + lint: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: .ruby-version + bundler-cache: true + + - name: Lint code for consistent style + run: bin/rubocop -f github + + test: + runs-on: ubuntu-latest + + # services: + # redis: + # image: redis + # ports: + # - 6379:6379 + # options: --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 + steps: + - name: Install packages + run: sudo apt-get update && sudo apt-get install --no-install-recommends -y build-essential git libyaml-dev pkg-config google-chrome-stable + + - name: Checkout code + uses: actions/checkout@v6 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: .ruby-version + bundler-cache: true + + - name: Run tests + env: + RAILS_ENV: test + # REDIS_URL: redis://localhost:6379/0 + run: bin/rails db:test:prepare test test:system + + - name: Keep screenshots from failed system tests + uses: actions/upload-artifact@v4 + if: failure() + with: + name: screenshots + path: ${{ github.workspace }}/tmp/screenshots + if-no-files-found: ignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d22da89 --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# Temporary files generated by your text editor or operating system +# belong in git's global ignore instead: +# `$XDG_CONFIG_HOME/git/ignore` or `~/.config/git/ignore` + +# Ignore bundler config. +/.bundle + +# Ignore all environment files. +/.env* + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/ +!/tmp/pids/.keep + +# Ignore storage (uploaded files in development and any SQLite databases). +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/ +!/tmp/storage/.keep + +/public/assets + +# Ignore master key for decrypting credentials and more. +/config/master.key + +/app/assets/builds/* +!/app/assets/builds/.keep + +# Local env for docker compose +.env +!/.env.example diff --git a/.kamal/hooks/docker-setup.sample b/.kamal/hooks/docker-setup.sample new file mode 100755 index 0000000..a0b0537 --- /dev/null +++ b/.kamal/hooks/docker-setup.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Docker set up on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/post-app-boot.sample b/.kamal/hooks/post-app-boot.sample new file mode 100755 index 0000000..7d2a13d --- /dev/null +++ b/.kamal/hooks/post-app-boot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Booted app version $KAMAL_VERSION on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/post-deploy.sample b/.kamal/hooks/post-deploy.sample new file mode 100755 index 0000000..17b0567 --- /dev/null +++ b/.kamal/hooks/post-deploy.sample @@ -0,0 +1,14 @@ +#!/usr/bin/env sh + +# A sample post-deploy hook +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) +# KAMAL_RUNTIME + +echo "$KAMAL_PERFORMER deployed $KAMAL_VERSION to $KAMAL_DESTINATION in $KAMAL_RUNTIME seconds" diff --git a/.kamal/hooks/post-proxy-reboot.sample b/.kamal/hooks/post-proxy-reboot.sample new file mode 100755 index 0000000..84548ed --- /dev/null +++ b/.kamal/hooks/post-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Rebooted kamal-proxy on $KAMAL_HOSTS" diff --git a/.kamal/hooks/pre-app-boot.sample b/.kamal/hooks/pre-app-boot.sample new file mode 100755 index 0000000..1f9fe84 --- /dev/null +++ b/.kamal/hooks/pre-app-boot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Booting app version $KAMAL_VERSION on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/pre-build.sample b/.kamal/hooks/pre-build.sample new file mode 100755 index 0000000..d53d28c --- /dev/null +++ b/.kamal/hooks/pre-build.sample @@ -0,0 +1,51 @@ +#!/usr/bin/env sh + +# A sample pre-build hook +# +# Checks: +# 1. We have a clean checkout +# 2. A remote is configured +# 3. The branch has been pushed to the remote +# 4. The version we are deploying matches the remote +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) + +if [ -n "$(git status --porcelain)" ]; then + echo "Git checkout is not clean, aborting..." >&2 + git status --porcelain >&2 + exit 1 +fi + +first_remote=$(git remote) + +if [ -z "$first_remote" ]; then + echo "No git remote set, aborting..." >&2 + exit 1 +fi + +current_branch=$(git branch --show-current) + +if [ -z "$current_branch" ]; then + echo "Not on a git branch, aborting..." >&2 + exit 1 +fi + +remote_head=$(git ls-remote $first_remote --tags $current_branch | cut -f1) + +if [ -z "$remote_head" ]; then + echo "Branch not pushed to remote, aborting..." >&2 + exit 1 +fi + +if [ "$KAMAL_VERSION" != "$remote_head" ]; then + echo "Version ($KAMAL_VERSION) does not match remote HEAD ($remote_head), aborting..." >&2 + exit 1 +fi + +exit 0 diff --git a/.kamal/hooks/pre-connect.sample b/.kamal/hooks/pre-connect.sample new file mode 100755 index 0000000..77744bd --- /dev/null +++ b/.kamal/hooks/pre-connect.sample @@ -0,0 +1,47 @@ +#!/usr/bin/env ruby + +# A sample pre-connect check +# +# Warms DNS before connecting to hosts in parallel +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) +# KAMAL_RUNTIME + +hosts = ENV["KAMAL_HOSTS"].split(",") +results = nil +max = 3 + +elapsed = Benchmark.realtime do + results = hosts.map do |host| + Thread.new do + tries = 1 + + begin + Socket.getaddrinfo(host, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME) + rescue SocketError + if tries < max + puts "Retrying DNS warmup: #{host}" + tries += 1 + sleep rand + retry + else + puts "DNS warmup failed: #{host}" + host + end + end + + tries + end + end.map(&:value) +end + +retries = results.sum - hosts.size +nopes = results.count { |r| r == max } + +puts "Prewarmed %d DNS lookups in %.2f sec: %d retries, %d failures" % [ hosts.size, elapsed, retries, nopes ] diff --git a/.kamal/hooks/pre-deploy.sample b/.kamal/hooks/pre-deploy.sample new file mode 100755 index 0000000..05b3055 --- /dev/null +++ b/.kamal/hooks/pre-deploy.sample @@ -0,0 +1,122 @@ +#!/usr/bin/env ruby + +# A sample pre-deploy hook +# +# Checks the Github status of the build, waiting for a pending build to complete for up to 720 seconds. +# +# Fails unless the combined status is "success" +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_COMMAND +# KAMAL_SUBCOMMAND +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) + +# Only check the build status for production deployments +if ENV["KAMAL_COMMAND"] == "rollback" || ENV["KAMAL_DESTINATION"] != "production" + exit 0 +end + +require "bundler/inline" + +# true = install gems so this is fast on repeat invocations +gemfile(true, quiet: true) do + source "https://rubygems.org" + + gem "octokit" + gem "faraday-retry" +end + +MAX_ATTEMPTS = 72 +ATTEMPTS_GAP = 10 + +def exit_with_error(message) + $stderr.puts message + exit 1 +end + +class GithubStatusChecks + attr_reader :remote_url, :git_sha, :github_client, :combined_status + + def initialize + @remote_url = github_repo_from_remote_url + @git_sha = `git rev-parse HEAD`.strip + @github_client = Octokit::Client.new(access_token: ENV["GITHUB_TOKEN"]) + refresh! + end + + def refresh! + @combined_status = github_client.combined_status(remote_url, git_sha) + end + + def state + combined_status[:state] + end + + def first_status_url + first_status = combined_status[:statuses].find { |status| status[:state] == state } + first_status && first_status[:target_url] + end + + def complete_count + combined_status[:statuses].count { |status| status[:state] != "pending"} + end + + def total_count + combined_status[:statuses].count + end + + def current_status + if total_count > 0 + "Completed #{complete_count}/#{total_count} checks, see #{first_status_url} ..." + else + "Build not started..." + end + end + + private + def github_repo_from_remote_url + url = `git config --get remote.origin.url`.strip.delete_suffix(".git") + if url.start_with?("https://github.com/") + url.delete_prefix("https://github.com/") + elsif url.start_with?("git@github.com:") + url.delete_prefix("git@github.com:") + else + url + end + end +end + + +$stdout.sync = true + +begin + puts "Checking build status..." + + attempts = 0 + checks = GithubStatusChecks.new + + loop do + case checks.state + when "success" + puts "Checks passed, see #{checks.first_status_url}" + exit 0 + when "failure" + exit_with_error "Checks failed, see #{checks.first_status_url}" + when "pending" + attempts += 1 + end + + exit_with_error "Checks are still pending, gave up after #{MAX_ATTEMPTS * ATTEMPTS_GAP} seconds" if attempts == MAX_ATTEMPTS + + puts checks.current_status + sleep(ATTEMPTS_GAP) + checks.refresh! + end +rescue Octokit::NotFound + exit_with_error "Build status could not be found" +end diff --git a/.kamal/hooks/pre-proxy-reboot.sample b/.kamal/hooks/pre-proxy-reboot.sample new file mode 100755 index 0000000..93e1199 --- /dev/null +++ b/.kamal/hooks/pre-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Rebooting kamal-proxy on $KAMAL_HOSTS..." diff --git a/.kamal/secrets b/.kamal/secrets new file mode 100644 index 0000000..9a771a3 --- /dev/null +++ b/.kamal/secrets @@ -0,0 +1,17 @@ +# Secrets defined here are available for reference under registry/password, env/secret, builder/secrets, +# and accessories/*/env/secret in config/deploy.yml. All secrets should be pulled from either +# password manager, ENV, or a file. DO NOT ENTER RAW CREDENTIALS HERE! This file needs to be safe for git. + +# Example of extracting secrets from 1password (or another compatible pw manager) +# SECRETS=$(kamal secrets fetch --adapter 1password --account your-account --from Vault/Item KAMAL_REGISTRY_PASSWORD RAILS_MASTER_KEY) +# KAMAL_REGISTRY_PASSWORD=$(kamal secrets extract KAMAL_REGISTRY_PASSWORD ${SECRETS}) +# RAILS_MASTER_KEY=$(kamal secrets extract RAILS_MASTER_KEY ${SECRETS}) + +# Use a GITHUB_TOKEN if private repositories are needed for the image +# GITHUB_TOKEN=$(gh config get -h github.com oauth_token) + +# Grab the registry password from ENV +KAMAL_REGISTRY_PASSWORD=$KAMAL_REGISTRY_PASSWORD + +# Improve security by using a password manager. Never check config/master.key into git! +RAILS_MASTER_KEY=$(cat config/master.key) diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..f9d86d4 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,8 @@ +# Omakase Ruby styling for Rails +inherit_gem: { rubocop-rails-omakase: rubocop.yml } + +# Overwrite or add rules to create your own house style +# +# # Use `[a, [b, c]]` not `[ a, [ b, c ] ]` +# Layout/SpaceInsideArrayLiteralBrackets: +# Enabled: false diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000..ab96aa9 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +ruby-3.2.3 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e38463d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,73 @@ +# syntax=docker/dockerfile:1 +# check=error=true + +# This Dockerfile is designed for production, not development. Use with Kamal or build'n'run by hand: +# docker build -t simple_aircraft_manager . +# docker run -d -p 80:80 -e RAILS_MASTER_KEY= --name simple_aircraft_manager simple_aircraft_manager + +# For a containerized dev environment, see Dev Containers: https://guides.rubyonrails.org/getting_started_with_devcontainer.html + +# Make sure RUBY_VERSION matches the Ruby version in .ruby-version +ARG RUBY_VERSION=3.2.3 +FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base + +# Rails app lives here +WORKDIR /rails + +# Install base packages +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y curl libjemalloc2 libvips sqlite3 && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Set production environment +ENV RAILS_ENV="production" \ + BUNDLE_DEPLOYMENT="1" \ + BUNDLE_PATH="/usr/local/bundle" \ + BUNDLE_WITHOUT="development" + +# Throw-away build stage to reduce size of final image +FROM base AS build + +# Install packages needed to build gems +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y build-essential git libyaml-dev pkg-config && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Install application gems +COPY vendor/* ./vendor/ +COPY Gemfile Gemfile.lock ./ +RUN bundle install && \ + rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ + bundle exec bootsnap precompile --gemfile + +# Copy application code +COPY . . + +# Precompile bootsnap code for faster boot times +RUN bundle exec bootsnap precompile app/ lib/ + +# Precompiling assets for production without requiring secret RAILS_MASTER_KEY +RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile + + + + +# Final stage for app image +FROM base + +# Copy built artifacts: gems, application +COPY --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}" +COPY --from=build /rails /rails + +# Run and own only the runtime files as a non-root user for security +RUN groupadd --system --gid 1000 rails && \ + useradd rails --uid 1000 --gid 1000 --create-home --shell /bin/bash && \ + chown -R rails:rails db log storage tmp +USER 1000:1000 + +# Entrypoint prepares the database. +ENTRYPOINT ["/rails/bin/docker-entrypoint"] + +# Start server via Thruster by default, this can be overwritten at runtime +EXPOSE 80 +CMD ["./bin/thrust", "./bin/rails", "server"] diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..6817edd --- /dev/null +++ b/Gemfile @@ -0,0 +1,67 @@ +source "https://rubygems.org" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 8.1.0" +# The modern asset pipeline for Rails [https://github.com/rails/propshaft] +gem "propshaft" +# Use sqlite3 as the database for Active Record +gem "sqlite3", ">= 2.1" +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", ">= 5.0" +# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails] +gem "importmap-rails" +# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev] +gem "turbo-rails" +# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev] +gem "stimulus-rails" +# Use Tailwind CSS [https://github.com/rails/tailwindcss-rails] +gem "tailwindcss-rails" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +gem "bcrypt", "~> 3.1.7" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem "tzinfo-data", platforms: %i[ windows jruby ] + +# Use the database-backed adapters for Rails.cache, Active Job, and Action Cable +gem "solid_cache" +gem "solid_queue" +gem "solid_cable" + +# Reduces boot times through caching; required in config/boot.rb +gem "bootsnap", require: false + +# Deploy this application anywhere as a Docker container [https://kamal-deploy.org] +gem "kamal", require: false + +# Add HTTP asset caching/compression and X-Sendfile acceleration to Puma [https://github.com/basecamp/thruster/] +gem "thruster", require: false + +# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] +# gem "image_processing", "~> 1.2" + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem "debug", platforms: %i[ mri windows ], require: "debug/prelude" + + # Static analysis for security vulnerabilities [https://brakemanscanner.org/] + gem "brakeman", require: false + + # Omakase Ruby styling [https://github.com/rails/rubocop-rails-omakase/] + gem "rubocop-rails-omakase", require: false +end + +group :development do + # Use console on exceptions pages [https://github.com/rails/web-console] + gem "web-console" +end + +group :test do + # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] + gem "capybara" + gem "selenium-webdriver" +end + +gem "chartkick", "~> 5.2" + +gem "json", "~> 2.10" diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..a3c4fb4 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,566 @@ +GEM + remote: https://rubygems.org/ + specs: + action_text-trix (2.1.19) + railties + actioncable (8.1.4.1) + actionpack (= 8.1.4.1) + activesupport (= 8.1.4.1) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (8.1.4.1) + actionpack (= 8.1.4.1) + activejob (= 8.1.4.1) + activerecord (= 8.1.4.1) + activestorage (= 8.1.4.1) + activesupport (= 8.1.4.1) + mail (>= 2.8.0) + actionmailer (8.1.4.1) + actionpack (= 8.1.4.1) + actionview (= 8.1.4.1) + activejob (= 8.1.4.1) + activesupport (= 8.1.4.1) + mail (>= 2.8.0) + rails-dom-testing (~> 2.2) + actionpack (8.1.4.1) + actionview (= 8.1.4.1) + activesupport (= 8.1.4.1) + nokogiri (>= 1.8.5) + rack (>= 2.2.4) + rack-session (>= 1.0.1) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + useragent (~> 0.16) + actiontext (8.1.4.1) + action_text-trix (~> 2.1.15) + actionpack (= 8.1.4.1) + activerecord (= 8.1.4.1) + activestorage (= 8.1.4.1) + activesupport (= 8.1.4.1) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (8.1.4.1) + activesupport (= 8.1.4.1) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6, >= 1.7.2) + activejob (8.1.4.1) + activesupport (= 8.1.4.1) + globalid (>= 0.3.6) + activemodel (8.1.4.1) + activesupport (= 8.1.4.1) + activerecord (8.1.4.1) + activemodel (= 8.1.4.1) + activesupport (= 8.1.4.1) + timeout (>= 0.4.0) + activestorage (8.1.4.1) + actionpack (= 8.1.4.1) + activejob (= 8.1.4.1) + activerecord (= 8.1.4.1) + activesupport (= 8.1.4.1) + marcel (~> 1.0) + activesupport (8.1.4.1) + base64 + bigdecimal + concurrent-ruby (~> 1.0, >= 1.3.1) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + json + logger (>= 1.4.2) + minitest (>= 5.1) + securerandom (>= 0.3) + tzinfo (~> 2.0, >= 2.0.5) + uri (>= 0.13.1) + addressable (2.9.2) + public_suffix (>= 2.0.2, < 8.0) + ast (2.4.3) + base64 (0.3.0) + bcrypt (3.1.22) + bcrypt_pbkdf (1.1.2) + bcrypt_pbkdf (1.1.2-arm64-darwin) + bcrypt_pbkdf (1.1.2-x86_64-darwin) + bigdecimal (4.1.3) + bindex (0.8.1) + bootsnap (1.26.1) + msgpack (~> 1.5) + brakeman (8.1.0) + racc + builder (3.3.0) + capybara (3.40.0) + addressable + matrix + mini_mime (>= 0.1.3) + nokogiri (~> 1.11) + rack (>= 1.6.0) + rack-test (>= 0.6.3) + regexp_parser (>= 1.5, < 3.0) + xpath (~> 3.2) + chartkick (5.2.1) + concurrent-ruby (1.3.8) + connection_pool (3.0.2) + crass (1.0.8) + date (3.6.0) + debug (1.11.1) + irb (~> 1.10) + reline (>= 0.3.8) + dotenv (3.2.0) + drb (2.2.3) + ed25519 (1.4.0) + erb (6.0.7) + erubi (1.13.1) + et-orbi (1.4.2) + tzinfo + fugit (1.14.0) + et-orbi (~> 1.4) + raabro (~> 1.4) + globalid (1.4.0) + activesupport (>= 6.1) + i18n (1.15.2) + concurrent-ruby (~> 1.0) + importmap-rails (2.2.3) + actionpack (>= 6.0.0) + activesupport (>= 6.0.0) + railties (>= 6.0.0) + io-console (0.9.5) + irb (1.18.0) + pp (>= 0.6.0) + prism (>= 1.3.0) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + json (2.21.2) + kamal (2.12.0) + activesupport (>= 7.0) + base64 (~> 0.2) + bcrypt_pbkdf (~> 1.0) + concurrent-ruby (~> 1.2) + dotenv (~> 3.1) + ed25519 (~> 1.4) + net-ssh (~> 7.3) + sshkit (>= 1.23.0, < 2.0) + thor (~> 1.3) + zeitwerk (>= 2.6.18, < 3.0) + language_server-protocol (3.17.0.6) + lint_roller (1.1.0) + logger (1.7.0) + loofah (2.25.3) + crass (~> 1.0.2) + nokogiri (>= 1.19.5) + mail (2.9.1) + logger + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.2.1) + matrix (0.4.3) + mini_mime (1.1.5) + minitest (6.0.6) + drb (~> 2.0) + prism (~> 1.5) + msgpack (1.8.7) + net-imap (0.6.8) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.4.0) + timeout + net-scp (4.2.1) + net-ssh (>= 2.6.5, < 9.0.0) + net-sftp (4.1.1) + net-ssh (>= 5.0.0, < 9.0.0) + net-smtp (0.5.2) + net-protocol + net-ssh (7.3.8) + logger + nio4r (2.7.5) + nokogiri (1.19.7-aarch64-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.7-aarch64-linux-musl) + racc (~> 1.4) + nokogiri (1.19.7-arm-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.7-arm-linux-musl) + racc (~> 1.4) + nokogiri (1.19.7-arm64-darwin) + racc (~> 1.4) + nokogiri (1.19.7-x86_64-darwin) + racc (~> 1.4) + nokogiri (1.19.7-x86_64-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.7-x86_64-linux-musl) + racc (~> 1.4) + ostruct (0.6.3) + parallel (1.28.0) + parser (3.3.13.0) + ast (~> 2.4.1) + racc + pp (0.6.4) + prettyprint + prettyprint (0.2.1) + prism (1.9.0) + propshaft (1.3.2) + actionpack (>= 7.0.0) + activesupport (>= 7.0.0) + rack + public_suffix (7.0.5) + puma (8.0.2) + nio4r (~> 2.0) + raabro (1.5.0) + racc (1.8.1) + rack (3.2.8) + rack-session (2.1.2) + base64 (>= 0.1.0) + rack (>= 3.0.0) + rack-test (2.3.0) + rack (>= 1.3) + rackup (2.3.1) + rack (>= 3) + rails (8.1.4.1) + actioncable (= 8.1.4.1) + actionmailbox (= 8.1.4.1) + actionmailer (= 8.1.4.1) + actionpack (= 8.1.4.1) + actiontext (= 8.1.4.1) + actionview (= 8.1.4.1) + activejob (= 8.1.4.1) + activemodel (= 8.1.4.1) + activerecord (= 8.1.4.1) + activestorage (= 8.1.4.1) + activesupport (= 8.1.4.1) + bundler (>= 1.15.0) + railties (= 8.1.4.1) + rails-dom-testing (2.3.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.7.2) + loofah (~> 2.25, >= 2.25.3) + nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) + railties (8.1.4.1) + actionpack (= 8.1.4.1) + activesupport (= 8.1.4.1) + irb (~> 1.13) + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + tsort (>= 0.2) + zeitwerk (~> 2.6) + rainbow (3.1.1) + rake (13.4.2) + rbs (4.1.3) + logger + prism (>= 1.6.0) + tsort + rdoc (8.1.0) + erb + prism (>= 1.6.0) + rbs (>= 4.0.0) + tsort + regexp_parser (2.13.1) + reline (0.7.0) + io-console (~> 0.5) + rexml (3.4.4) + rubocop (1.92.2) + json (>= 2.3) + language_server-protocol (~> 3.17.0.2) + lint_roller (~> 1.1.0) + parallel (>= 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 2.11.3, < 3.0) + rubocop-ast (>= 1.49.0, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.50.0) + parser (>= 3.3.7.2) + prism (~> 1.7) + rubocop-performance (1.27.0) + lint_roller (~> 1.1) + rubocop (>= 1.89.0, < 2.0) + rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rails (2.38.0) + activesupport (>= 4.2.0) + lint_roller (~> 1.1) + rack (>= 1.1) + rubocop (>= 1.89.0, < 2.0) + rubocop-ast (>= 1.44.0, < 2.0) + rubocop-rails-omakase (1.1.0) + rubocop (>= 1.72) + rubocop-performance (>= 1.24) + rubocop-rails (>= 2.30) + ruby-progressbar (1.13.0) + rubyzip (3.7.0) + securerandom (0.4.1) + selenium-webdriver (4.44.0) + base64 (~> 0.2) + logger (~> 1.4) + rexml (~> 3.2, >= 3.2.5) + rubyzip (>= 1.2.2, < 4.0) + websocket (~> 1.0) + solid_cable (3.0.12) + actioncable (>= 7.2) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_cache (1.0.10) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_queue (1.7.2) + activejob (>= 7.1) + activerecord (>= 7.1) + concurrent-ruby (>= 1.3.1) + fugit (~> 1.11) + railties (>= 7.1) + thor (>= 1.3.1) + sqlite3 (2.10.2-aarch64-linux-gnu) + sqlite3 (2.10.2-aarch64-linux-musl) + sqlite3 (2.10.2-arm-linux-gnu) + sqlite3 (2.10.2-arm-linux-musl) + sqlite3 (2.10.2-arm64-darwin) + sqlite3 (2.10.2-x86_64-darwin) + sqlite3 (2.10.2-x86_64-linux-gnu) + sqlite3 (2.10.2-x86_64-linux-musl) + sshkit (1.25.1) + base64 + logger + net-scp (>= 1.1.2) + net-sftp (>= 2.1.2) + net-ssh (>= 2.8.0) + ostruct + stimulus-rails (1.3.4) + railties (>= 6.0.0) + tailwindcss-rails (4.7.0) + railties (>= 7.0.0) + tailwindcss-ruby (~> 4.0) + tailwindcss-ruby (4.3.3) + tailwindcss-ruby (4.3.3-aarch64-linux-gnu) + tailwindcss-ruby (4.3.3-aarch64-linux-musl) + tailwindcss-ruby (4.3.3-arm64-darwin) + tailwindcss-ruby (4.3.3-x86_64-darwin) + tailwindcss-ruby (4.3.3-x86_64-linux-gnu) + tailwindcss-ruby (4.3.3-x86_64-linux-musl) + thor (1.5.0) + thruster (0.1.27) + thruster (0.1.27-aarch64-linux) + thruster (0.1.27-arm64-darwin) + thruster (0.1.27-x86_64-darwin) + thruster (0.1.27-x86_64-linux) + timeout (0.6.1) + tsort (0.2.0) + turbo-rails (2.0.23) + actionpack (>= 7.1.0) + railties (>= 7.1.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (3.3.0) + unicode-emoji (~> 4.3) + unicode-emoji (4.3.0) + uri (1.1.2) + useragent (0.16.11) + web-console (4.3.0) + actionview (>= 8.0.0) + bindex (>= 0.4.0) + railties (>= 8.0.0) + websocket (1.2.11) + websocket-driver (0.8.2) + base64 + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + xpath (3.2.0) + nokogiri (~> 1.8) + zeitwerk (2.8.3) + +PLATFORMS + aarch64-linux + aarch64-linux-gnu + aarch64-linux-musl + arm-linux-gnu + arm-linux-musl + arm64-darwin + x86_64-darwin + x86_64-linux + x86_64-linux-musl + +DEPENDENCIES + bcrypt (~> 3.1.7) + bootsnap + brakeman + capybara + chartkick (~> 5.2) + debug + importmap-rails + json (~> 2.10) + kamal + propshaft + puma (>= 5.0) + rails (~> 8.1.0) + rubocop-rails-omakase + selenium-webdriver + solid_cable + solid_cache + solid_queue + sqlite3 (>= 2.1) + stimulus-rails + tailwindcss-rails + thruster + turbo-rails + tzinfo-data + web-console + +CHECKSUMS + action_text-trix (2.1.19) sha256=7012f59421009cf284aa651294896414d653a61a2417c9b8714c8476d2f74009 + actioncable (8.1.4.1) sha256=007670f7297973e94809e9f32a56624a7aa60b6e9d6696cd078064ce86d1c7fc + actionmailbox (8.1.4.1) sha256=18b43dd842bf3a3e31b8e38b7917c21e48c128fc8b263c893481cc66ee1a8f78 + actionmailer (8.1.4.1) sha256=a7b71dedf744e48dd6751e97350634edce9a2f7beeceac332dcccb91729ad066 + actionpack (8.1.4.1) sha256=8c6f2e7cbd2653ef0539bde1ff20eb3e2e264e366affe56f0ba7f06d3670cb4b + actiontext (8.1.4.1) sha256=fb59611dc16e2b6bbfcec66793acfae6cdd64b1e35ef3f9175424f31e62c38da + actionview (8.1.4.1) sha256=d25b4d9cf8d0c0195ffcfe8b2cf3fcbe6fea54fd7c17f1a9cb8182881463f12b + activejob (8.1.4.1) sha256=82c4c9311ea1016d5f7f134a0c5f9b6527cad5a6237f5f3f60aa17984ef36229 + activemodel (8.1.4.1) sha256=063caf105372fbc98b2d789e4be23de63ac5c043f7d9330f04e2caddb7012805 + activerecord (8.1.4.1) sha256=bd65599ca0b5d210937f835d42c7aff69d271741c75aab022730be6cbce67e87 + activestorage (8.1.4.1) sha256=0f4e2f114f3584723a80a2c089aacc6170e765a0b2c385c9782e26ed78f05c66 + activesupport (8.1.4.1) sha256=16ac4f341ca65c85a1fcdb8ac73f68891aae9e3c4a6f9c3a27daed8b00017ed7 + addressable (2.9.2) sha256=9117c7e7d6ee07230e75ce41fb9401ae55354dc654fcd0e862ba41d539e9a610 + ast (2.4.3) sha256=954615157c1d6a382bc27d690d973195e79db7f55e9765ac7c481c60bdb4d383 + base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b + bcrypt (3.1.22) sha256=1f0072e88c2d705d94aff7f2c5cb02eb3f1ec4b8368671e19112527489f29032 + bcrypt_pbkdf (1.1.2) sha256=c2414c23ce66869b3eb9f643d6a3374d8322dfb5078125c82792304c10b94cf6 + bcrypt_pbkdf (1.1.2-arm64-darwin) sha256=afdd6feb6ed5a97b8e44caacb3f2d641b98af78e6a516d4a3520b69af5cf9fea + bcrypt_pbkdf (1.1.2-x86_64-darwin) sha256=35f5639d0058e6c2cc2f856f9c0b14080543268d3047abe6bc81c513093caa0e + bigdecimal (4.1.3) sha256=61ebe1e5e559bdc3cc6f2c0ee7f427321fc838f59611c294356eb04d6e21cf66 + bindex (0.8.1) sha256=7b1ecc9dc539ed8bccfc8cb4d2732046227b09d6f37582ff12e50a5047ceb17e + bootsnap (1.26.1) sha256=5b5bd90f8f13ea338627c1d56ffbe2ea25e743ac48c2afec1a9bea3a06a264e2 + brakeman (8.1.0) sha256=cfa9e5214e4925842f4bc849a64f8a7e6c5d0425fe98eac8d7b7bc60fdc17e07 + builder (3.3.0) sha256=497918d2f9dca528fdca4b88d84e4ef4387256d984b8154e9d5d3fe5a9c8835f + capybara (3.40.0) sha256=42dba720578ea1ca65fd7a41d163dd368502c191804558f6e0f71b391054aeef + chartkick (5.2.1) sha256=2848d7de87189f30f28d077eb0bbdebc8a1f0f6f81de1ded95008fe564369949 + concurrent-ruby (1.3.8) sha256=b2f1be836e968ccc78ccfce277ea79c72a88633f22306782c16ff23fb415d1e1 + connection_pool (3.0.2) sha256=33fff5ba71a12d2aa26cb72b1db8bba2a1a01823559fb01d29eb74c286e62e0a + crass (1.0.8) sha256=7a0145c7a2c59f8e7923b3a69ce819c444823a00a5127d805298fea13be24efe + date (3.6.0) sha256=18ac945c4e24ebd93534f8eab8c2fd8c5604b3e977105b3798d62a1e8d27b580 + debug (1.11.1) sha256=2e0b0ac6119f2207a6f8ac7d4a73ca8eb4e440f64da0a3136c30343146e952b6 + dotenv (3.2.0) sha256=e375b83121ea7ca4ce20f214740076129ab8514cd81378161f11c03853fe619d + drb (2.2.3) sha256=0b00d6fdb50995fe4a45dea13663493c841112e4068656854646f418fda13373 + ed25519 (1.4.0) sha256=16e97f5198689a154247169f3453ef4cfd3f7a47481fde0ae33206cdfdcac506 + erb (6.0.7) sha256=c5ca6dc25b0ef974a44dc8f59fe847577122483b1968a38dec305c60bf91ee92 + erubi (1.13.1) sha256=a082103b0885dbc5ecf1172fede897f9ebdb745a4b97a5e8dc63953db1ee4ad9 + et-orbi (1.4.2) sha256=bb555dae668419cb24caa2a293a170e58be6d4df1e017c51f5030bdc133cd20c + fugit (1.14.0) sha256=e311a9cc85a54bb67649df45060e721282a1e2c8ebad40e41874a3a7d576f37e + globalid (1.4.0) sha256=037f12fbf1d9d7a014d501c2d5c77356fd4ddd96d7a7991d6700bba96706f427 + i18n (1.15.2) sha256=00f9eb62412fe593b2a65a97daa75300d37abb8f7202ec748e94b6d46a9dd1b5 + importmap-rails (2.2.3) sha256=7101be2a4dc97cf1558fb8f573a718404c5f6bcfe94f304bf1f39e444feeb16a + io-console (0.9.5) sha256=83dd9bbf4c4680416629245b39cd4212eb5f4d9a4ea91804870c1f6b846414d5 + irb (1.18.0) sha256=de9454a0703a54704b9811a5ef31a60c86949fbf4013fcf244fabc7c775248e3 + json (2.21.2) sha256=1f1d3b7cf2b3ba1a69beca0bb6db13d5438b80bff3cd54cdaaa620b9b07c1c6a + kamal (2.12.0) sha256=c51d1ab085e515470f98d0c0f043637122b5ebf76e8b610cb1fbbed0b7f9b8fa + language_server-protocol (3.17.0.6) sha256=5ef2c0c138f8267e1bc631d3328347d354f96724b0af22f2c79516120443b7f0 + lint_roller (1.1.0) sha256=2c0c845b632a7d172cb849cc90c1bce937a28c5c8ccccb50dfd46a485003cc87 + logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203 + loofah (2.25.3) sha256=545f14eef0cc2a7de80df560530d593232b7c07e515c5c4e37532d9cb5b0185c + mail (2.9.1) sha256=06574eca475253d6c18145dd70af80d0eb970182d55053497c5f4d797ea160e8 + marcel (1.2.1) sha256=1678e9360e32f9eafa917c80029e2f6d10b2715c66a4b87b6d0da9b9cd1f859f + matrix (0.4.3) sha256=a0d5ab7ddcc1973ff690ab361b67f359acbb16958d1dc072b8b956a286564c5b + mini_mime (1.1.5) sha256=8681b7e2e4215f2a159f9400b5816d85e9d8c6c6b491e96a12797e798f8bccef + minitest (6.0.6) sha256=153ea36d1d987a62942382b61075745042a2b3123b1cd48f4c3675af9cc7d6f1 + msgpack (1.8.7) sha256=dfefec761b5f9047e6e8d95d2c7f8af4b3725d984a01942adc533aa819a2df33 + net-imap (0.6.8) sha256=eb30bb62227b64a3af6b518b04b2375113d69f68f15de59b0193b07d98acf6d9 + net-pop (0.1.2) sha256=848b4e982013c15b2f0382792268763b748cce91c9e91e36b0f27ed26420dff3 + net-protocol (0.4.0) sha256=f9f90c8c6f64794a45160bf422177a336db12809de3beeeaa26b88fcd2e8c853 + net-scp (4.2.1) sha256=5c9ff6743da37eef6746f248043d97d2bbf3910a4694ec8e372326ec588c2394 + net-sftp (4.1.1) sha256=dc2019e59e3e3552943b576f14cb0201ec55823935b967e10dcda169b04e4573 + net-smtp (0.5.2) sha256=35103cc04d6b2d94632f9928ede07483c24b70b9c0db1f231fea43909b678f3c + net-ssh (7.3.8) sha256=16bb1fccc4d9a580decdeea8ddb98e8544df29b7e6ac8cb94d4b379cfe4bee9f + nio4r (2.7.5) sha256=6c90168e48fb5f8e768419c93abb94ba2b892a1d0602cb06eef16d8b7df1dca1 + nokogiri (1.19.7-aarch64-linux-gnu) sha256=8f5e15d299602456406e1f03a9f3456cceb33a0722811e818d2ee2214eb4c84a + nokogiri (1.19.7-aarch64-linux-musl) sha256=efe0c3602e6e54521bc21c681930ce5568e2d11203de17400710b2b3ca2e4cb4 + nokogiri (1.19.7-arm-linux-gnu) sha256=7fd1907125691aa89e838cc91161761c758b4e17bb32f0dd9b5515a82cc759af + nokogiri (1.19.7-arm-linux-musl) sha256=28d0ff0c87b6bb2e56580323a6fb049d5d4a02b94f0958fdd47e9ac146991c77 + nokogiri (1.19.7-arm64-darwin) sha256=f27d7f25f4873fbc3aa35a2cc2fb680c98555fec1925348da439d0869d541142 + nokogiri (1.19.7-x86_64-darwin) sha256=508e81e8c5f84aaa240dce981bf1c43faae60808726f0ce7024ee92effc5cafe + nokogiri (1.19.7-x86_64-linux-gnu) sha256=25865ccb462f714e712fdf8906fde07849cb6704a808e3d629d75baa5af5dd3b + nokogiri (1.19.7-x86_64-linux-musl) sha256=464d1f3dfb0d53cf54c0c6a7e23e8e91cf68ec3cafc2b27dc4a7682f2d9bf546 + ostruct (0.6.3) sha256=95a2ed4a4bd1d190784e666b47b2d3f078e4a9efda2fccf18f84ddc6538ed912 + parallel (1.28.0) sha256=33e6de1484baf2524792d178b0913fc8eb94c628d6cfe45599ad4458c638c970 + parser (3.3.13.0) sha256=e02f9b63c2fe05b0c68f692ba4df89b3cb113b663964f75d988fbebfd6c3deca + pp (0.6.4) sha256=dfcb0fce700c41456265922884f9fe195d7fbb0674a3578e6c0f69588e82b570 + prettyprint (0.2.1) sha256=d555d57ea6d7cf001d4774b693546a6bd88bec1e778ddffb5c60b68ceec4b7d4 + prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85 + propshaft (1.3.2) sha256=1d56a3e56a92c21bfc29caf07406b5386b00d4c47ddf357cf989a5a234b1389e + public_suffix (7.0.5) sha256=1a8bb08f1bbea19228d3bed6e5ed908d1cb4f7c2726d18bd9cadf60bc676f623 + puma (8.0.2) sha256=c8ed871dfbbe66448ea9ffd46692342d9804d4071522b52b5331b7b6e7b686fb + raabro (1.5.0) sha256=3f998a7bc84f9c84df3ab580634d2e0a5bda4f0841168d56035f529c9877440a + racc (1.8.1) sha256=4a7f6929691dbec8b5209a0b373bc2614882b55fc5d2e447a21aaa691303d62f + rack (3.2.8) sha256=1fecc85e463ebc7a2a945fff829ffcd549babeb1556384796fad946c28dc4ec7 + rack-session (2.1.2) sha256=595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8 + rack-test (2.3.0) sha256=b118d177cc002c572fc1b6fd8d19c9ed5881a36e8d6f689f9e618f9f861241e8 + rackup (2.3.1) sha256=6c79c26753778e90983761d677a48937ee3192b3ffef6bc963c0950f94688868 + rails (8.1.4.1) sha256=365c3a0ad2713bd6e60628e5e826622d4ca8dee60b5a7e560e9b20844e9650bc + rails-dom-testing (2.3.0) sha256=8acc7953a7b911ca44588bf08737bc16719f431a1cc3091a292bca7317925c1d + rails-html-sanitizer (1.7.2) sha256=a21ef45b7a6639fc8e2282473c547514cb86ae271616162a946bf89148fa2424 + railties (8.1.4.1) sha256=ff2ef4b5a62cbc89811f88be11c776e2ed71b14dd012eae6a494d37994aa9782 + rainbow (3.1.1) sha256=039491aa3a89f42efa1d6dec2fc4e62ede96eb6acd95e52f1ad581182b79bc6a + rake (13.4.2) sha256=cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701 + rbs (4.1.3) sha256=0c4474a9751cdc14364bfad0b3e53678323bbdc2c31683b0445932867dbab8c4 + rdoc (8.1.0) sha256=befc37880a5cfd36dcb176c748b5fd5ee39dd3536a75e81824e4972ce230f60a + regexp_parser (2.13.1) sha256=5aedb6b7c35688f51e86eef17a15374dfd287c83f4ca644b2c5f3ec50a33b44b + reline (0.7.0) sha256=5b012d8e55dbf9d450f12bde2cf7d15ff546ae80b3f8f3b30e570d431815583d + rexml (3.4.4) sha256=19e0a2c3425dfbf2d4fc1189747bdb2f849b6c5e74180401b15734bc97b5d142 + rubocop (1.92.2) sha256=14fb31eed143a0dc6f78186c550c1715e81cd38f59d05d1165050e445c1f5382 + rubocop-ast (1.50.0) sha256=b9ca88300da0803ee222ad20cdb30494c0a784eed06fdc35d254b06d662788db + rubocop-performance (1.27.0) sha256=eeeb1374d062a368ee1c787b70eb0b0cc4b184cb1f8565f424760946146d61ce + rubocop-rails (2.38.0) sha256=6e2b7c532efa95e3050371bec20b8f5b025662acead8bc70ee31f0e3e6fa2f06 + rubocop-rails-omakase (1.1.0) sha256=2af73ac8ee5852de2919abbd2618af9c15c19b512c4cfc1f9a5d3b6ef009109d + ruby-progressbar (1.13.0) sha256=80fc9c47a9b640d6834e0dc7b3c94c9df37f08cb072b7761e4a71e22cff29b33 + rubyzip (3.7.0) sha256=65c19294da75297a939006f3516deacc33185fbd721ff1954f7a231db6d3e121 + securerandom (0.4.1) sha256=cc5193d414a4341b6e225f0cb4446aceca8e50d5e1888743fac16987638ea0b1 + selenium-webdriver (4.44.0) sha256=6f1df072529af369589c46f0e01132952aabb250cfd683c274d74dc1eb5d8477 + solid_cable (3.0.12) sha256=a168a54731a455d5627af48d8441ea3b554b8c1f6e6cd6074109de493e6b0460 + solid_cache (1.0.10) sha256=bc05a2fb3ac78a6f43cbb5946679cf9db67dd30d22939ededc385cb93e120d41 + solid_queue (1.7.2) sha256=a22685e1d2ee14ce7b4e5d4592c9d8e837951884c51555609dee58679ed03325 + sqlite3 (2.10.2-aarch64-linux-gnu) sha256=e9aea2c2b3476fc875dd8a89313a9a2862818519c0186bfb5b56d6f57bb08d98 + sqlite3 (2.10.2-aarch64-linux-musl) sha256=4986fc40cdf21342362b72a941df28e95cfe0e644f3ad2532d948b157c39dbee + sqlite3 (2.10.2-arm-linux-gnu) sha256=762f609ef891463226b472d3df66aea84d5466ff4376d3ccf4a059718c4ce9c9 + sqlite3 (2.10.2-arm-linux-musl) sha256=833623eaf1157b1b85d1c0830e3e8f9beb3bb95a9bec3d252f20557a50e9803a + sqlite3 (2.10.2-arm64-darwin) sha256=5b0d235ea037e6dcd1b8387a19d73be571917db9f93044d35741cf933a21a37d + sqlite3 (2.10.2-x86_64-darwin) sha256=fd2c67b49d313031af112e172c83ab321681a2b4996bf882eefac50be7bea08f + sqlite3 (2.10.2-x86_64-linux-gnu) sha256=ca92731ab464df9cae503fa1a439a549e2724f6953c8c05a7769b59366e38f15 + sqlite3 (2.10.2-x86_64-linux-musl) sha256=b9f8fc62f3e0eb8966b41de251b492b4c8e9d1b23559beb6e150ad7f8d590941 + sshkit (1.25.1) sha256=be3f10b9d6eb0b44d5eaba3f7cbe41bc6bb894bce4339688ac20124391455b78 + stimulus-rails (1.3.4) sha256=765676ffa1f33af64ce026d26b48e8ffb2e0b94e0f50e9119e11d6107d67cb06 + tailwindcss-rails (4.7.0) sha256=9b09bd677d7cd226fc8ff3f7d2d91c6dc6c3da75dd74dc4cab5f94711f69ba41 + tailwindcss-ruby (4.3.3) sha256=ee0a64030749862deb501acab4c4aaf5adbee13865746a33299d46d7b5d0952a + tailwindcss-ruby (4.3.3-aarch64-linux-gnu) sha256=c86d6dd3eccc85fe0d792a832b06f2bf3c0a7a83b399308aeb9d8f5725f42a6a + tailwindcss-ruby (4.3.3-aarch64-linux-musl) sha256=72b77ca9edea82383dd09510ab520a122e3cb9f9864ca5b38e27698098d2b899 + tailwindcss-ruby (4.3.3-arm64-darwin) sha256=776c51fc734aac64bde0c253eadd2ed2e610b2ba0d8e760501fe7cbec55fd6cf + tailwindcss-ruby (4.3.3-x86_64-darwin) sha256=483011e5d3792cf5ef4afdfb04c1d95daccf42c30cdb6fe53b77520954e7b922 + tailwindcss-ruby (4.3.3-x86_64-linux-gnu) sha256=2337017ff8b02698480eae1e9637cf01faa0e4824db89d067a13c5a5ee38c9b2 + tailwindcss-ruby (4.3.3-x86_64-linux-musl) sha256=27d478c417bcf73828e5b544744c5bdfd5b5cb54f1a266fc4f185281c32efe6c + thor (1.5.0) sha256=e3a9e55fe857e44859ce104a84675ab6e8cd59c650a49106a05f55f136425e73 + thruster (0.1.27) sha256=5fd3855192bb4e8d13db69ae5f70d39f2dfd88fe0394fa372104996edf0bb599 + thruster (0.1.27-aarch64-linux) sha256=c50789f2dcd4dfa072c4719f99c38dea5d47ebb60ad0cc1fd1996b2266ecfd22 + thruster (0.1.27-arm64-darwin) sha256=ece0ff0f2ec195008030fbca97067e5e867f4e1f66501fa8b8a3ec3f829bf2bf + thruster (0.1.27-x86_64-darwin) sha256=f389bdfccf332dabff8053194e64cd65d4ae247f1afd386624233a1dfaa41485 + thruster (0.1.27-x86_64-linux) sha256=7e0e6381011401810b047ff25506e0e38755b2430499ff5586f1a110086981c6 + timeout (0.6.1) sha256=78f57368a7e7bbadec56971f78a3f5ecbcfb59b7fcbb0a3ed6ddc08a5094accb + tsort (0.2.0) sha256=9650a793f6859a43b6641671278f79cfead60ac714148aabe4e3f0060480089f + turbo-rails (2.0.23) sha256=ee0d90733aafff056cf51ff11e803d65e43cae258cc55f6492020ec1f9f9315f + tzinfo (2.0.6) sha256=8daf828cc77bcf7d63b0e3bdb6caa47e2272dcfaf4fbfe46f8c3a9df087a829b + unicode-display_width (3.3.0) sha256=4b7aa66a4b11db50f6f7e98411215cd0dd10eaecb665d36eec5bcacb3fa0b613 + unicode-emoji (4.3.0) sha256=11c02fa73290378c066bb0562cd4c87d8e1b706fbbe0059ca12746a4244de8ce + uri (1.1.2) sha256=89292e98eabbef6248b0a0ed5e7e398e152f83f17560023a6d94a7f492b169fb + useragent (0.16.11) sha256=700e6413ad4bb954bb63547fa098dddf7b0ebe75b40cc6f93b8d54255b173844 + web-console (4.3.0) sha256=e13b71301cdfc2093f155b5aa3a622db80b4672d1f2f713119cc7ec7ac6a6da4 + websocket (1.2.11) sha256=b7e7a74e2410b5e85c25858b26b3322f29161e300935f70a0e0d3c35e0462737 + websocket-driver (0.8.2) sha256=97c556b019bf3410b4961002ac501621e9322d3f8a7bc02161a09301cc4c4146 + websocket-extensions (0.1.5) sha256=1c6ba63092cda343eb53fc657110c71c754c56484aad42578495227d717a8241 + xpath (3.2.0) sha256=6dfda79d91bb3b949b947ecc5919f042ef2f399b904013eb3ef6d20dd3a4082e + zeitwerk (2.8.3) sha256=2c85125a8467ce069e20123d1e709a08955c9d29c118c25b46b7b7fafdbb92e5 + +BUNDLED WITH + 4.0.8 diff --git a/Procfile.dev b/Procfile.dev new file mode 100644 index 0000000..da151fe --- /dev/null +++ b/Procfile.dev @@ -0,0 +1,2 @@ +web: bin/rails server +css: bin/rails tailwindcss:watch diff --git a/README.md b/README.md new file mode 100644 index 0000000..19f6946 --- /dev/null +++ b/README.md @@ -0,0 +1,129 @@ +# Simple Aircraft Manager (Rails) + +A Ruby on Rails port of [Simple Aircraft Manager](https://github.com/marbindrakon/simple-aircraft-manager), a self-hosted app for tracking records and status for small fleets of aircraft: components and TBO, squawks, ADs, inspections, logbook, documents, oil and fuel trends, and read-only share links for mechanics and buyers. + +The port aims to be **easy to host**. It runs as one process with one SQLite database directory. It needs no Postgres, no Redis, no nginx, and no Kubernetes. + +## Stack + +- Rails 8.1, SQLite. Solid Queue, Solid Cache, and Solid Cable all use SQLite, so there are no extra services. +- Hotwire (Turbo and Stimulus) with importmap, so there is no Node build step. Tailwind CSS 4 runs through `tailwindcss-rails`. +- Active Storage on local disk handles pictures, document pages, squawk attachments, and track logs. +- Chartkick and Chart.js draw the oil and fuel charts. +- Authentication uses the Rails 8 built-in generator (sessions plus password reset). + +## Quick start (development) + +```bash +bundle install +bin/rails db:prepare +DEMO=1 bin/rails db:seed # optional: demo aircraft N12345 +bin/dev # http://localhost:3000 +``` + +With demo data, sign in as `admin@example.com` / `password123` (owner) or `pilot@example.com` / `password123` (pilot). +Without demo data, the first visit asks you to create the admin account. + +Run the tests: `bin/rails test` + +## Hosting + +Everything persistent lives in `storage/`: the SQLite databases and the uploaded files. Back up that one directory. + +### Option A: Docker Compose (simplest) + +```bash +cp .env.example .env # set SECRET_KEY_BASE (bin/rails secret), APP_HOST, FORCE_SSL +docker compose up -d --build # http://:3000 +``` + +Data lives in the `sam_storage` volume. Set `FORCE_SSL=false` if you serve plain HTTP on a LAN. Set it to `true` when a TLS reverse proxy such as Caddy, Traefik, or Cloudflare Tunnel sits in front. + +### Option B: Kamal (any VPS, automatic TLS) + +Edit `config/deploy.yml` with your server IP, registry, and domain, then run `bin/kamal setup`. Kamal Proxy handles Let's Encrypt certificates. Background jobs run inside Puma (`SOLID_QUEUE_IN_PUMA`). + +### Option C: Plain server / PaaS + +The app is a standard Rails app. Run `bin/rails db:prepare && bin/thrust bin/rails server` with `RAILS_ENV=production`, `SECRET_KEY_BASE`, and `SOLID_QUEUE_IN_PUMA=true`. Mount `storage/` on persistent disk. + +### Environment variables + +| Variable | Purpose | +|---|---| +| `SECRET_KEY_BASE` | Required in production (`bin/rails secret`). Alternatively provide `RAILS_MASTER_KEY`. | +| `FORCE_SSL` | `true` (default) redirects to HTTPS and sets secure cookies. Use `false` for plain HTTP. | +| `APP_HOST` | Host used in password-reset email links. | +| `SMTP_ADDRESS`, `SMTP_PORT`, `SMTP_USERNAME`, `SMTP_PASSWORD`, `MAIL_FROM` | Optional. They enable password-reset emails. Without them an admin resets passwords from **Users**. | + +### Backups + +SQLite runs in WAL mode, so a plain file copy taken while the app is running can be inconsistent. Use the SQLite backup command instead: + +```bash +mkdir -p backup +for db in storage/production*.sqlite3; do sqlite3 "$db" ".backup 'backup/$(basename "$db")'"; done +rsync -a --exclude '*.sqlite3*' storage/ backup/ # uploaded files +``` + +Alternatively, stop the container and copy the volume. + +## Features + +| Area | Notes | +|---|---| +| Fleet dashboard | Every aircraft you can access, with airworthiness status and its top issues. | +| Airworthiness | RED/ORANGE/GREEN from AD compliance, grounding squawks, inspection recurrency, and replacement-critical components. Warnings start 10 hours or 30 days ahead. Logic: `app/services/airworthiness.rb`, `app/services/compliance.rb`. | +| Hours | Absolute tach/hobbs updates or per-flight logs. Both apply the delta to every in-service component. Downward corrections are clamped at 0. | +| Airworthiness enforcement | Optional per aircraft. It blocks flight logs and hours updates while the aircraft is RED. | +| Components | Tree of parent and child parts, TBO and replacement limits, and service/replace reset. Owners can create new component types inline. | +| Squawks | Four priorities. "Ground Aircraft" makes the aircraft RED. Supports attachments, resolve, and reopen. | +| ADs and bulletins | Shared across aircraft and applicable to the airframe or to specific components. Hour- and month-based recurrence (due at end of month), conditional and non-mandatory types, and compliance history. | +| Inspections | Shared inspection types with hour, month, and day recurrence, plus history. | +| Logbook | Maintenance entries with search and a link to a scanned document page. | +| Documents | Collections, multi-file documents with a page viewer, and per-document share visibility. | +| Major repairs and alterations | Form 337, STC, and ICA tracking. | +| Oil and fuel | Records, trend charts, and averages (last 20 intervals, IQR outlier filtering, manual exclusion). | +| Activity log | Every write is recorded as an `AircraftEvent`. | +| Access | Admin, owner, and pilot roles, plus share links (Status or Maintenance privilege, optional expiry, at most 10 per aircraft). | + +### Roles + +| Action | Admin | Owner | Pilot | +|---|:-:|:-:|:-:| +| View everything on the aircraft | ✓ | ✓ | ✓ | +| Update hours, log flights, add squawks/notes/oil/fuel | ✓ | ✓ | ✓ | +| Edit or delete squawks and notes, resolve squawks | ✓ | ✓ | | +| Components, logbook, ADs, inspections, documents, major records | ✓ | ✓ | | +| Edit or delete aircraft, manage people and share links | ✓ | ✓ | | +| Create aircraft (creator becomes owner) | ✓ | ✓ | ✓ | +| Manage users and component types | ✓ | | | + +Users who aren't on an aircraft get a 404 for it, identical to a missing record. + +## Mapping from the Django original + +| Django | Rails | +|---|---| +| `health/services.py` | `app/services/airworthiness.rb`, `compliance.rb`, `hours_service.rb`, `consumption_stats.rb` | +| `AircraftScopedMixin` / `core/permissions.py` | `app/controllers/concerns/aircraft_scoped.rb` | +| `EventLoggingMixin` / `log_event` | `Aircraft#log_event!`, called from controllers | +| DRF viewsets + Alpine.js mixins | Server-rendered controllers and ERB views with Turbo | +| `AD` | `AirworthinessDirective` | +| `MajorRepairAlteration` | `MajorRecord` | +| `DocumentImage` | `Document has_many_attached :pages` | +| `AircraftShareToken` | `ShareToken` (`has_secure_token`) | +| `views_public.py` | `SharedController` → `/shared/:token` | + +Differences from the original: +- Integer primary keys instead of UUIDs. Share tokens are 32-character random strings. +- Logbook entries and inspection records don't keep many-to-many links to components. An inspection record or AD compliance can reference one component. +- Accounts are created by an admin, or by the first-run setup. The original's invitation codes aren't implemented yet. + +### Not yet ported + +AI logbook transcription, oil-analysis PDF import, the MCP server for AI agents, OIDC single sign-on, invitation codes, aircraft import/export, the plugin system, and the desktop builds. + +## License + +The original project is released under [The Unlicense](https://unlicense.org). This port follows the same spirit. diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..9a5ea73 --- /dev/null +++ b/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative "config/application" + +Rails.application.load_tasks diff --git a/app/assets/builds/.keep b/app/assets/builds/.keep new file mode 100644 index 0000000..e69de29 diff --git a/app/assets/images/.keep b/app/assets/images/.keep new file mode 100644 index 0000000..e69de29 diff --git a/app/assets/stylesheets/application.css b/app/assets/stylesheets/application.css new file mode 100644 index 0000000..fe93333 --- /dev/null +++ b/app/assets/stylesheets/application.css @@ -0,0 +1,10 @@ +/* + * This is a manifest file that'll be compiled into application.css. + * + * With Propshaft, assets are served efficiently without preprocessing steps. You can still include + * application-wide styles in this file, but keep in mind that CSS precedence will follow the standard + * cascading order, meaning styles declared later in the document or manifest will override earlier ones, + * depending on specificity. + * + * Consider organizing styles into separate files for maintainability. + */ diff --git a/app/assets/tailwind/application.css b/app/assets/tailwind/application.css new file mode 100644 index 0000000..0c4f970 --- /dev/null +++ b/app/assets/tailwind/application.css @@ -0,0 +1,36 @@ +@import "tailwindcss"; + +@utility btn { @apply inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium shadow-sm transition cursor-pointer disabled:opacity-50; } +@utility btn-primary { @apply btn bg-sky-700 text-white hover:bg-sky-800; } +@utility btn-secondary { @apply btn bg-white text-slate-700 ring-1 ring-slate-300 ring-inset hover:bg-slate-50; } +@utility btn-danger { @apply btn bg-white text-red-700 ring-1 ring-red-300 ring-inset hover:bg-red-50; } +@utility btn-sm { @apply px-2 py-1 text-xs; } +@utility link { @apply text-sky-700 hover:underline; } + +@utility card { @apply rounded-lg bg-white shadow-sm ring-1 ring-slate-200; } +@utility card-header { @apply flex flex-wrap items-center justify-between gap-3 border-b border-slate-200 px-4 py-3; } +@utility card-title { @apply text-base font-semibold text-slate-900; } +@utility card-body { @apply p-4; } + +@utility label { @apply block text-sm font-medium text-slate-700 mb-1; } +@utility input { @apply block w-full rounded-md border-0 px-2.5 py-1.5 text-sm text-slate-900 shadow-sm ring-1 ring-slate-300 ring-inset placeholder:text-slate-400 focus:ring-2 focus:ring-sky-600 focus:outline-none bg-white; } +@utility hint { @apply mt-1 text-xs text-slate-500; } +@utility field-error { @apply mt-1 text-xs text-red-600; } + +@utility table { + @apply min-w-full text-sm; + & th { @apply px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-500 bg-slate-50; } + & td { @apply px-3 py-2 align-top text-slate-700; } + & tbody tr { @apply border-t border-slate-100; } + & tbody tr:hover { @apply bg-slate-50; } +} + +@utility badge { @apply inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ring-1 ring-inset whitespace-nowrap; } +@utility badge-red { @apply badge bg-red-50 text-red-700 ring-red-600/20; } +@utility badge-orange { @apply badge bg-amber-50 text-amber-800 ring-amber-600/30; } +@utility badge-green { @apply badge bg-emerald-50 text-emerald-700 ring-emerald-600/20; } +@utility badge-blue { @apply badge bg-sky-50 text-sky-700 ring-sky-600/20; } +@utility badge-gray { @apply badge bg-slate-100 text-slate-600 ring-slate-500/20; } + +@utility tab { @apply whitespace-nowrap border-b-2 border-transparent px-3 py-2 text-sm font-medium text-slate-500 hover:border-slate-300 hover:text-slate-700; } +@utility tab-active { @apply border-sky-700 text-sky-700; } diff --git a/app/channels/application_cable/connection.rb b/app/channels/application_cable/connection.rb new file mode 100644 index 0000000..4264c74 --- /dev/null +++ b/app/channels/application_cable/connection.rb @@ -0,0 +1,16 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + identified_by :current_user + + def connect + set_current_user || reject_unauthorized_connection + end + + private + def set_current_user + if session = Session.find_by(id: cookies.signed[:session_id]) + self.current_user = session.user + end + end + end +end diff --git a/app/controllers/ad_compliances_controller.rb b/app/controllers/ad_compliances_controller.rb new file mode 100644 index 0000000..54a92a7 --- /dev/null +++ b/app/controllers/ad_compliances_controller.rb @@ -0,0 +1,57 @@ +class AdCompliancesController < ApplicationController + include AircraftScoped + before_action :require_owner! + before_action :set_compliance, only: %i[edit update destroy] + + def new + ad = @aircraft.applicable_ads.find_by(id: params[:ad_id]) + @compliance = AdCompliance.new(aircraft: @aircraft, airworthiness_directive: ad, date_complied: Date.current, + aircraft_hours_at_compliance: @aircraft.tach_time) + if ad&.recurring? && ad.recurring_hours.to_d > 0 + @compliance.next_due_at_time = @aircraft.current_hours + ad.recurring_hours + end + end + + def create + @compliance = AdCompliance.new(compliance_params.merge(aircraft: @aircraft)) + if @compliance.save + log_event("ad", "Compliance recorded: #{@compliance.airworthiness_directive.name}") + redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "Compliance recorded." + else + render :new, status: :unprocessable_entity + end + end + + def edit; end + + def update + if @compliance.update(compliance_params) + log_event("ad", "Compliance updated: #{@compliance.airworthiness_directive.name}") + redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "Compliance updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @compliance.destroy! + log_event("ad", "Compliance deleted: #{@compliance.airworthiness_directive.name}") + redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "Compliance record deleted." + end + + private + + def set_compliance = @compliance = AdCompliance.for_aircraft(@aircraft).find(params[:id]) + + def compliance_params + p = params.require(:ad_compliance).permit( + :airworthiness_directive_id, :date_complied, :compliance_notes, :permanent, :next_due_at_time, + :aircraft_hours_at_compliance, :logbook_entry_id, :inspection_record_id, :component_id + ) + p[:airworthiness_directive_id] = scoped_id(@aircraft.applicable_ads, p[:airworthiness_directive_id]) + p[:logbook_entry_id] = scoped_id(@aircraft.logbook_entries, p[:logbook_entry_id]) + p[:inspection_record_id] = scoped_id(InspectionRecord.for_aircraft(@aircraft), p[:inspection_record_id]) + p[:component_id] = scoped_id(@aircraft.components, p[:component_id]) + p + end +end diff --git a/app/controllers/admin/component_types_controller.rb b/app/controllers/admin/component_types_controller.rb new file mode 100644 index 0000000..8d9cfc7 --- /dev/null +++ b/app/controllers/admin/component_types_controller.rb @@ -0,0 +1,44 @@ +class Admin::ComponentTypesController < ApplicationController + before_action :require_admin! + before_action :set_type, only: %i[edit update destroy] + + def index + @component_types = ComponentType.ordered + end + + def new + @component_type = ComponentType.new + end + + def create + @component_type = ComponentType.new(type_params) + if @component_type.save + redirect_to admin_component_types_path, notice: "Component type created." + else + render :new, status: :unprocessable_entity + end + end + + def edit; end + + def update + if @component_type.update(type_params) + redirect_to admin_component_types_path, notice: "Component type updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + if @component_type.destroy + redirect_to admin_component_types_path, notice: "Component type deleted." + else + redirect_to admin_component_types_path, alert: @component_type.errors.full_messages.to_sentence + end + end + + private + + def set_type = @component_type = ComponentType.find(params[:id]) + def type_params = params.require(:component_type).permit(:name, :consumable) +end diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb new file mode 100644 index 0000000..8813fe2 --- /dev/null +++ b/app/controllers/admin/users_controller.rb @@ -0,0 +1,50 @@ +class Admin::UsersController < ApplicationController + before_action :require_admin! + before_action :set_user, only: %i[edit update destroy] + + def index + @users = User.order(:email_address).includes(aircraft_roles: :aircraft) + end + + def new + @user = User.new + end + + def create + @user = User.new(user_params) + @user.admin = admin_flag + if @user.save + redirect_to admin_users_path, notice: "User #{@user.email_address} created." + else + render :new, status: :unprocessable_entity + end + end + + def edit; end + + def update + attrs = user_params + attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank? + if @user == current_user && !admin_flag + return redirect_to admin_users_path, alert: "You can't remove your own admin rights." + end + @user.admin = admin_flag + if @user.update(attrs) + redirect_to admin_users_path, notice: "User updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + return redirect_to admin_users_path, alert: "You can't delete yourself." if @user == current_user + @user.destroy! + redirect_to admin_users_path, notice: "User deleted." + end + + private + + def set_user = @user = User.find(params[:id]) + def user_params = params.require(:user).permit(:name, :email_address, :password, :password_confirmation) + def admin_flag = params.dig(:user, :admin) == "1" +end diff --git a/app/controllers/aircraft_controller.rb b/app/controllers/aircraft_controller.rb new file mode 100644 index 0000000..a1dd8fb --- /dev/null +++ b/app/controllers/aircraft_controller.rb @@ -0,0 +1,74 @@ +class AircraftController < ApplicationController + include AircraftScoped + skip_before_action :set_aircraft, only: %i[index new create] + before_action :require_owner!, only: %i[edit update destroy] + + def index + @aircraft_list = current_user.accessible_aircraft.ordered.with_attached_picture + end + + def show + @airworthiness = @aircraft.airworthiness + @active_squawks = @aircraft.squawks.active.by_priority.includes(:component, :reported_by) + @recent_events = @aircraft.events.includes(:user).limit(8) + @notes = @aircraft.notes.recent_first.includes(:user).limit(5) + @oil = ConsumptionStats.new(@aircraft, "oil") + @fuel = ConsumptionStats.new(@aircraft, "fuel") + end + + def new + @aircraft = Aircraft.new + end + + def create + @aircraft = Aircraft.new(aircraft_params) + Aircraft.transaction do + @aircraft.save! + @aircraft.roles.create!(user: current_user, role: "owner") + @aircraft.log_event!("aircraft", "Aircraft created") + end + redirect_to @aircraft, notice: "#{@aircraft.tail_number} added." + rescue ActiveRecord::RecordInvalid + render :new, status: :unprocessable_entity + end + + def edit; end + + def update + if @aircraft.update(aircraft_params) + log_event("aircraft", "Aircraft details updated") + redirect_to @aircraft, notice: "Aircraft updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @aircraft.destroy! + redirect_to root_path, notice: "#{@aircraft.tail_number} deleted." + end + + # Pilots and above: set absolute tach/hobbs readings. + def update_hours + delta = HoursService.new(@aircraft).update_hours!( + tach_time: params.require(:tach_time), hobbs_time: params[:hobbs_time] + ) + redirect_to @aircraft, notice: "Hours updated (#{delta >= 0 ? '+' : ''}#{delta})." + rescue AircraftGroundedError => e + redirect_to @aircraft, alert: e.message + rescue ArgumentError + redirect_to @aircraft, alert: "Enter a valid tach reading." + end + + private + + def aircraft_param = params[:id] + + def aircraft_params + params.require(:aircraft).permit( + :tail_number, :make, :model, :serial_number, :description, :purchased, :status, + :tach_time, :tach_time_offset, :hobbs_time, :hobbs_time_offset, + :airworthiness_enforcement, :picture + ) + end +end diff --git a/app/controllers/aircraft_roles_controller.rb b/app/controllers/aircraft_roles_controller.rb new file mode 100644 index 0000000..24d5913 --- /dev/null +++ b/app/controllers/aircraft_roles_controller.rb @@ -0,0 +1,54 @@ +# Owner-only: manage who can access the aircraft, and its public share links. +class AircraftRolesController < ApplicationController + include AircraftScoped + before_action :require_owner! + + def index + @roles = @aircraft.roles.includes(:user).order(:role, :created_at) + @share_tokens = @aircraft.share_tokens.order(created_at: :desc).includes(:created_by) + end + + def create + user = User.find_by(email_address: params[:email_address].to_s.strip.downcase) + unless user + return redirect_to aircraft_aircraft_roles_path(@aircraft), + alert: "No user with that email. Ask an administrator to create their account first." + end + role = @aircraft.roles.new(user: user, role: params[:role]) + if role.save + log_event("role", "#{user.display_name} added as #{role.role}") + redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "#{user.display_name} added." + else + redirect_to aircraft_aircraft_roles_path(@aircraft), alert: role.errors.full_messages.to_sentence + end + end + + def update + role = @aircraft.roles.find(params[:id]) + if demoting_last_owner?(role, params[:role]) + return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: "An aircraft must keep at least one owner." + end + role.update!(role: params[:role]) + log_event("role", "#{role.user.display_name} changed to #{role.role}") + redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Role updated." + end + + def destroy + role = @aircraft.roles.find(params[:id]) + if role.user == current_user + return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: "You can't remove yourself." + end + if demoting_last_owner?(role, nil) + return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: "An aircraft must keep at least one owner." + end + role.destroy! + log_event("role", "#{role.user.display_name} removed") + redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Access removed." + end + + private + + def demoting_last_owner?(role, new_role) + role.role == "owner" && new_role != "owner" && @aircraft.roles.owners.count <= 1 + end +end diff --git a/app/controllers/airworthiness_directives_controller.rb b/app/controllers/airworthiness_directives_controller.rb new file mode 100644 index 0000000..8ad1d91 --- /dev/null +++ b/app/controllers/airworthiness_directives_controller.rb @@ -0,0 +1,74 @@ +class AirworthinessDirectivesController < ApplicationController + include AircraftScoped + include Applicability + before_action :require_owner!, except: :index + before_action :set_ad, only: %i[edit update destroy] + + def index + @rows = Compliance.ad_rows(@aircraft) + @history = AdCompliance.for_aircraft(@aircraft).recent_first.includes(:airworthiness_directive, :component) + @attachable = AirworthinessDirective.where.not(id: @aircraft.applicable_ads.select(:id)).ordered if owner? + end + + def new + @ad = AirworthinessDirective.new + @applies_to_airframe = true + end + + def create + @ad = AirworthinessDirective.new(ad_params) + AirworthinessDirective.transaction do + @ad.save! + apply_applicability(@ad, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids) + end + log_event("ad", "#{@ad.bulletin_label} added: #{@ad.name}") + redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{@ad.bulletin_label} added." + rescue ActiveRecord::RecordInvalid + @applies_to_airframe = applies_to_airframe? + render :new, status: :unprocessable_entity + end + + # Link an AD that already exists (e.g. tracked on another aircraft). + def attach + ad = AirworthinessDirective.find(params[:airworthiness_directive_id]) + ad.aircraft << @aircraft unless ad.aircraft.include?(@aircraft) + log_event("ad", "#{ad.bulletin_label} linked: #{ad.name}") + redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{ad.name} linked." + end + + def edit + @applies_to_airframe = @ad.aircraft.include?(@aircraft) + end + + def update + AirworthinessDirective.transaction do + @ad.update!(ad_params) + apply_applicability(@ad, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids) + end + log_event("ad", "#{@ad.bulletin_label} updated: #{@ad.name}") + redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{@ad.bulletin_label} updated." + rescue ActiveRecord::RecordInvalid + @applies_to_airframe = applies_to_airframe? + render :edit, status: :unprocessable_entity + end + + # Removes the AD from this aircraft (the shared AD record survives if other aircraft use it). + def destroy + detach_from_aircraft(@ad) + log_event("ad", "#{@ad.bulletin_label} removed: #{@ad.name}") + redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{@ad.name} removed from #{@aircraft.tail_number}." + end + + private + + def set_ad = @ad = @aircraft.applicable_ads.find(params[:id]) + + def ad_params + p = params.require(:airworthiness_directive).permit( + :name, :short_description, :required_action, :compliance_type, :trigger_condition, :recurring, + :recurring_hours, :recurring_months, :recurring_days, :bulletin_type, :mandatory, :document_id + ) + p[:document_id] = scoped_id(@aircraft.documents, p[:document_id]) + p + end +end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 0000000..b5eca1a --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,28 @@ +class ApplicationController < ActionController::Base + default_form_builder AppFormBuilder + include Authentication + allow_browser versions: :modern + + prepend_before_action :redirect_to_setup + helper_method :current_user + + rescue_from ActiveRecord::RecordNotFound do + respond_to do |format| + format.html { render "errors/not_found", status: :not_found, layout: (authenticated? ? "application" : "public") } + format.any { head :not_found } + end + end + + private + + def current_user = Current.user + + # First run: no users yet → create the initial admin. + def redirect_to_setup + redirect_to new_setup_path if !User.exists? && !is_a?(SetupController) + end + + def require_admin! + redirect_to root_path, alert: "Admins only." unless current_user&.admin? + end +end diff --git a/app/controllers/components_controller.rb b/app/controllers/components_controller.rb new file mode 100644 index 0000000..501da25 --- /dev/null +++ b/app/controllers/components_controller.rb @@ -0,0 +1,90 @@ +class ComponentsController < ApplicationController + include AircraftScoped + before_action :require_owner!, except: %i[index show] + before_action :set_component, only: %i[show edit update destroy reset_service] + + def index + all = @aircraft.components.includes(:component_type, :parent_component).order(:install_location) + @show_disposed = params[:disposed].present? + all = all.where.not(status: "DISPOSED") unless @show_disposed + # Depth-first tree order: parents followed by their children. + by_parent = all.group_by(&:parent_component_id) + @rows = [] + walk = ->(parent_id, depth) do + (by_parent[parent_id] || []).sort_by { [ _1.component_type.name, _1.install_location.to_s ] }.each do |c| + @rows << [ c, depth ] + walk.(c.id, depth + 1) + end + end + walk.(nil, 0) + orphans = all.to_a - @rows.map(&:first) # children whose parent is filtered out + orphans.each { @rows << [ _1, 0 ] } + end + + def show + @squawks = @component.squawks.by_priority + end + + def new + @component = @aircraft.components.new(date_in_service: Date.current, status: "IN-USE", + parent_component_id: params[:parent_id]) + end + + def create + @component = @aircraft.components.new(component_params) + if @component.save + log_event("component", "Component added: #{@component}") + redirect_to aircraft_components_path(@aircraft), notice: "Component added." + else + render :new, status: :unprocessable_entity + end + end + + def edit; end + + def update + if @component.update(component_params) + log_event("component", "Component updated: #{@component}") + redirect_to aircraft_components_path(@aircraft), notice: "Component updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @component.destroy! + log_event("component", "Component deleted: #{@component}") + redirect_to aircraft_components_path(@aircraft), notice: "Component deleted." + end + + # Always zeroes hours since overhaul; reset_in_service=1 also zeroes the + # in-service clock (use when the part was physically replaced). + def reset_service + replaced = params[:reset_in_service] == "1" + @component.reset_service!(reset_in_service: replaced) + log_event("component", "#{replaced ? 'Replaced' : 'Serviced'}: #{@component}") + redirect_to aircraft_components_path(@aircraft), notice: "#{@component} #{replaced ? 'replaced' : 'serviced'}." + end + + private + + def set_component + @component = @aircraft.components.find(params[:id]) + end + + def component_params + params.require(:component).permit( + :component_type_id, :parent_component_id, :manufacturer, :model, :serial_number, + :install_location, :notes, :status, :date_in_service, :hours_in_service, + :hours_since_overhaul, :overhaul_date, :tbo_hours, :tbo_days, :inspection_hours, + :inspection_days, :replacement_hours, :replacement_days, :tbo_critical, :on_condition, + :inspection_critical, :replacement_critical + ).tap do |p| + # Owners can create a component type inline instead of asking an admin. + if (name = params[:new_component_type].to_s.strip).present? + type = ComponentType.where("lower(name) = ?", name.downcase).first || ComponentType.create!(name: name) + p[:component_type_id] = type.id + end + end + end +end diff --git a/app/controllers/concerns/.keep b/app/controllers/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/app/controllers/concerns/aircraft_scoped.rb b/app/controllers/concerns/aircraft_scoped.rb new file mode 100644 index 0000000..6d17851 --- /dev/null +++ b/app/controllers/concerns/aircraft_scoped.rb @@ -0,0 +1,46 @@ +# Scopes a controller to one aircraft the current user can access and exposes +# role helpers. Unknown and inaccessible aircraft both 404 (enumeration-safe). +# +# Access matrix (mirrors the original): +# admin – everything +# owner – everything on their aircraft +# pilot – view all; update hours; create squawks, notes, oil/fuel, flight logs +module AircraftScoped + extend ActiveSupport::Concern + + included do + before_action :set_aircraft + helper_method :current_role, :owner?, :can_write? + end + + private + + def aircraft_param = params[:aircraft_id] + + def set_aircraft + @aircraft = current_user.accessible_aircraft.find(aircraft_param) + end + + def current_role + @current_role ||= current_user.role_for(@aircraft) + end + + # Owner-level write access (admins included). + def owner? = current_role.in?(%w[admin owner]) + alias_method :can_write?, :owner? + + def require_owner! + return if owner? + redirect_back fallback_location: aircraft_path(@aircraft), + alert: "Only owners can do that." + end + + # Returns id only if it belongs to the given (aircraft-scoped) relation; else nil. + def scoped_id(scope, id) + id.present? && scope.where(id: id).exists? ? id : nil + end + + def log_event(category, name, notes: nil) + @aircraft.log_event!(category, name, notes: notes) + end +end diff --git a/app/controllers/concerns/applicability.rb b/app/controllers/concerns/applicability.rb new file mode 100644 index 0000000..b4ec8fc --- /dev/null +++ b/app/controllers/concerns/applicability.rb @@ -0,0 +1,38 @@ +# ADs and inspection types are shared reference data that can apply to many +# aircraft. From an aircraft's page we only ever touch *this* aircraft's links: +# the airframe itself and/or some of its components. +module Applicability + extend ActiveSupport::Concern + + private + + def apply_applicability(record, to_airframe:, component_ids:) + mine = @aircraft.components.where(id: Array(component_ids).compact_blank).to_a + others = record.components.where.not(aircraft_id: @aircraft.id).to_a + record.components = others + mine + if to_airframe + record.aircraft << @aircraft unless record.aircraft.include?(@aircraft) + else + record.aircraft.delete(@aircraft) + end + # Never let a record silently drop off this aircraft entirely. + record.aircraft << @aircraft if mine.empty? && !to_airframe + end + + def detach_from_aircraft(record) + record.aircraft.delete(@aircraft) + record.components.delete(*record.components.where(aircraft_id: @aircraft.id)) + record.destroy if record.aircraft.empty? && record.components.empty? && orphan_deletable?(record) + end + + def orphan_deletable?(record) + case record + when AirworthinessDirective then record.ad_compliances.none? + when InspectionType then record.inspection_records.none? + else false + end + end + + def applies_to_airframe? = params[:applies_to_airframe] == "1" + def applicable_component_ids = params[:component_ids] +end diff --git a/app/controllers/concerns/authentication.rb b/app/controllers/concerns/authentication.rb new file mode 100644 index 0000000..3538f48 --- /dev/null +++ b/app/controllers/concerns/authentication.rb @@ -0,0 +1,52 @@ +module Authentication + extend ActiveSupport::Concern + + included do + before_action :require_authentication + helper_method :authenticated? + end + + class_methods do + def allow_unauthenticated_access(**options) + skip_before_action :require_authentication, **options + end + end + + private + def authenticated? + resume_session + end + + def require_authentication + resume_session || request_authentication + end + + def resume_session + Current.session ||= find_session_by_cookie + end + + def find_session_by_cookie + Session.find_by(id: cookies.signed[:session_id]) if cookies.signed[:session_id] + end + + def request_authentication + session[:return_to_after_authenticating] = request.url + redirect_to new_session_path + end + + def after_authentication_url + session.delete(:return_to_after_authenticating) || root_url + end + + def start_new_session_for(user) + user.sessions.create!(user_agent: request.user_agent, ip_address: request.remote_ip).tap do |session| + Current.session = session + cookies.signed.permanent[:session_id] = { value: session.id, httponly: true, same_site: :lax } + end + end + + def terminate_session + Current.session.destroy + cookies.delete(:session_id) + end +end diff --git a/app/controllers/consumable_records_controller.rb b/app/controllers/consumable_records_controller.rb new file mode 100644 index 0000000..94f1e1d --- /dev/null +++ b/app/controllers/consumable_records_controller.rb @@ -0,0 +1,53 @@ +class ConsumableRecordsController < ApplicationController + include AircraftScoped + before_action :require_owner!, only: %i[edit update destroy] + before_action :set_record, only: %i[edit update destroy] + + def index + @oil = ConsumptionStats.new(@aircraft, "oil") + @fuel = ConsumptionStats.new(@aircraft, "fuel") + @records = @aircraft.consumable_records.recent_first.limit(200) + end + + def new + type = params[:type].in?(ConsumableRecord::TYPES.keys) ? params[:type] : "oil" + @record = @aircraft.consumable_records.new(record_type: type, date: Date.current, + flight_hours: @aircraft.tach_time) + end + + def create + @record = @aircraft.consumable_records.new(record_params) + if @record.save + log_event(@record.record_type, "#{@record.record_type.capitalize} added: #{@record.quantity_added} #{@record.unit}") + redirect_to aircraft_consumable_records_path(@aircraft), notice: "Record added." + else + render :new, status: :unprocessable_entity + end + end + + def edit; end + + def update + if @record.update(record_params) + log_event(@record.record_type, "#{@record.record_type.capitalize} record updated") + redirect_to aircraft_consumable_records_path(@aircraft), notice: "Record updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @record.destroy! + log_event(@record.record_type, "#{@record.record_type.capitalize} record deleted") + redirect_to aircraft_consumable_records_path(@aircraft), notice: "Record deleted." + end + + private + + def set_record = @record = @aircraft.consumable_records.find(params[:id]) + + def record_params + params.require(:consumable_record).permit(:record_type, :date, :quantity_added, :level_after, + :consumable_type, :flight_hours, :notes, :excluded_from_averages) + end +end diff --git a/app/controllers/document_collections_controller.rb b/app/controllers/document_collections_controller.rb new file mode 100644 index 0000000..fd58e5f --- /dev/null +++ b/app/controllers/document_collections_controller.rb @@ -0,0 +1,41 @@ +class DocumentCollectionsController < ApplicationController + include AircraftScoped + before_action :require_owner! + before_action :set_collection, only: %i[edit update destroy] + + def new + @collection = @aircraft.document_collections.new + end + + def create + @collection = @aircraft.document_collections.new(collection_params) + if @collection.save + log_event("document", "Collection created: #{@collection.name}") + redirect_to aircraft_documents_path(@aircraft), notice: "Collection created." + else + render :new, status: :unprocessable_entity + end + end + + def edit; end + + def update + if @collection.update(collection_params) + log_event("document", "Collection updated: #{@collection.name}") + redirect_to aircraft_documents_path(@aircraft), notice: "Collection updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @collection.destroy! + log_event("document", "Collection deleted: #{@collection.name}") + redirect_to aircraft_documents_path(@aircraft), notice: "Collection and its documents deleted." + end + + private + + def set_collection = @collection = @aircraft.document_collections.find(params[:id]) + def collection_params = params.require(:document_collection).permit(:name, :description, :visibility, :starred) +end diff --git a/app/controllers/documents_controller.rb b/app/controllers/documents_controller.rb new file mode 100644 index 0000000..29d4f86 --- /dev/null +++ b/app/controllers/documents_controller.rb @@ -0,0 +1,62 @@ +class DocumentsController < ApplicationController + include AircraftScoped + before_action :require_owner!, except: %i[index show] + before_action :set_document, only: %i[show edit update destroy] + + def index + @collections = @aircraft.document_collections.ordered.includes(documents: { pages_attachments: :blob }) + @uncollected = @aircraft.documents.where(document_collection_id: nil).ordered.includes(pages_attachments: :blob) + end + + def show + @page = (params[:page] || 1).to_i.clamp(1, [ @document.pages.size, 1 ].max) + end + + def new + @document = @aircraft.documents.new(document_collection_id: params[:collection_id]) + end + + def create + @document = @aircraft.documents.new(document_params) + if @document.save + log_event("document", "Document added: #{@document.name}") + redirect_to aircraft_document_path(@aircraft, @document), notice: "Document added." + else + render :new, status: :unprocessable_entity + end + end + + def edit; end + + def update + attrs = document_params + new_pages = attrs.delete(:pages) + @document.assign_attributes(attrs) + @document.pages.attach(new_pages) if new_pages.present? + Array(params[:remove_page_ids]).each { |id| @document.pages.find_by(id: id)&.purge_later } + if @document.save + log_event("document", "Document updated: #{@document.name}") + redirect_to aircraft_document_path(@aircraft, @document), notice: "Document updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @document.destroy! + log_event("document", "Document deleted: #{@document.name}") + redirect_to aircraft_documents_path(@aircraft), notice: "Document deleted." + end + + private + + def set_document = @document = @aircraft.documents.find(params[:id]) + + def document_params + p = params.require(:document).permit(:name, :description, :doc_type, :visibility, :document_collection_id, pages: []) + p[:pages]&.compact_blank! + p.delete(:pages) if p[:pages].blank? + p[:document_collection_id] = scoped_id(@aircraft.document_collections, p[:document_collection_id]) + p + end +end diff --git a/app/controllers/events_controller.rb b/app/controllers/events_controller.rb new file mode 100644 index 0000000..119e83b --- /dev/null +++ b/app/controllers/events_controller.rb @@ -0,0 +1,10 @@ +class EventsController < ApplicationController + include AircraftScoped + + def index + @category = params[:category].presence_in(AircraftEvent::CATEGORIES.keys) + scope = @aircraft.events.includes(:user) + scope = scope.where(category: @category) if @category + @events = scope.limit(200) + end +end diff --git a/app/controllers/flight_logs_controller.rb b/app/controllers/flight_logs_controller.rb new file mode 100644 index 0000000..efdab3e --- /dev/null +++ b/app/controllers/flight_logs_controller.rb @@ -0,0 +1,47 @@ +class FlightLogsController < ApplicationController + include AircraftScoped + before_action :require_owner!, only: :destroy + + def index + @flight_logs = @aircraft.flight_logs.recent_first.includes(:user) + end + + def show + @flight_log = @aircraft.flight_logs.find(params[:id]) + end + + def new + @flight_log = @aircraft.flight_logs.new(date: Date.current, tach_out: @aircraft.tach_time, + hobbs_out: @aircraft.hobbs_time) + end + + def create + @flight_log = @aircraft.flight_logs.new(flight_log_params) + if @flight_log.valid? + HoursService.new(@aircraft).log_flight!(@flight_log) + redirect_to aircraft_flight_logs_path(@aircraft), notice: "Flight logged (#{@flight_log.tach_time} hrs)." + else + render :new, status: :unprocessable_entity + end + rescue AircraftGroundedError => e + flash.now[:alert] = e.message + render :new, status: :conflict + end + + # Deleting a flight does not roll back hours; correct those with an hours update. + def destroy + @aircraft.flight_logs.find(params[:id]).destroy! + log_event("flight", "Flight log deleted") + redirect_to aircraft_flight_logs_path(@aircraft), notice: "Flight log deleted. Aircraft hours were not changed." + end + + private + + def flight_log_params + params.require(:flight_log).permit( + :date, :tach_time, :tach_out, :tach_in, :hobbs_time, :hobbs_out, :hobbs_in, + :departure_location, :destination_location, :route, :oil_added, :oil_added_type, + :oil_level_after, :fuel_added, :fuel_added_type, :fuel_level_after, :notes, :track_log + ) + end +end diff --git a/app/controllers/inspection_records_controller.rb b/app/controllers/inspection_records_controller.rb new file mode 100644 index 0000000..0ee26fc --- /dev/null +++ b/app/controllers/inspection_records_controller.rb @@ -0,0 +1,51 @@ +class InspectionRecordsController < ApplicationController + include AircraftScoped + before_action :require_owner! + before_action :set_record, only: %i[edit update destroy] + + def new + @record = InspectionRecord.new(aircraft: @aircraft, date: Date.current, + aircraft_hours: @aircraft.tach_time, + inspection_type_id: params[:inspection_type_id]) + end + + def create + @record = InspectionRecord.new(record_params.merge(aircraft: @aircraft)) + if @record.save + log_event("inspection", "Inspection completed: #{@record.inspection_type.name}") + redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection recorded." + else + render :new, status: :unprocessable_entity + end + end + + def edit; end + + def update + if @record.update(record_params) + log_event("inspection", "Inspection record updated: #{@record.inspection_type.name}") + redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection record updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @record.destroy! + log_event("inspection", "Inspection record deleted: #{@record.inspection_type.name}") + redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection record deleted." + end + + private + + def set_record = @record = InspectionRecord.for_aircraft(@aircraft).find(params[:id]) + + def record_params + p = params.require(:inspection_record).permit(:inspection_type_id, :date, :aircraft_hours, :notes, + :logbook_entry_id, :component_id) + p[:inspection_type_id] = scoped_id(@aircraft.applicable_inspection_types, p[:inspection_type_id]) + p[:logbook_entry_id] = scoped_id(@aircraft.logbook_entries, p[:logbook_entry_id]) + p[:component_id] = scoped_id(@aircraft.components, p[:component_id]) + p + end +end diff --git a/app/controllers/inspection_types_controller.rb b/app/controllers/inspection_types_controller.rb new file mode 100644 index 0000000..c7cc9c0 --- /dev/null +++ b/app/controllers/inspection_types_controller.rb @@ -0,0 +1,56 @@ +class InspectionTypesController < ApplicationController + include AircraftScoped + include Applicability + before_action :require_owner! + before_action :set_type, only: %i[edit update destroy] + + def new + @inspection_type = InspectionType.new(required: true, recurring: true) + @applies_to_airframe = true + end + + def create + @inspection_type = InspectionType.new(type_params) + InspectionType.transaction do + @inspection_type.save! + apply_applicability(@inspection_type, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids) + end + log_event("inspection", "Inspection type added: #{@inspection_type.name}") + redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection type added." + rescue ActiveRecord::RecordInvalid + @applies_to_airframe = applies_to_airframe? + render :new, status: :unprocessable_entity + end + + def edit + @applies_to_airframe = @inspection_type.aircraft.include?(@aircraft) + end + + def update + InspectionType.transaction do + @inspection_type.update!(type_params) + apply_applicability(@inspection_type, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids) + end + log_event("inspection", "Inspection type updated: #{@inspection_type.name}") + redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection type updated." + rescue ActiveRecord::RecordInvalid + @applies_to_airframe = applies_to_airframe? + render :edit, status: :unprocessable_entity + end + + def destroy + detach_from_aircraft(@inspection_type) + log_event("inspection", "Inspection type removed: #{@inspection_type.name}") + redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection removed from #{@aircraft.tail_number}." + end + + private + + def set_type + @inspection_type = @aircraft.applicable_inspection_types.find(params[:id]) + end + + def type_params + params.require(:inspection_type).permit(:name, :recurring, :required, :recurring_hours, :recurring_days, :recurring_months) + end +end diff --git a/app/controllers/inspections_controller.rb b/app/controllers/inspections_controller.rb new file mode 100644 index 0000000..9622d8a --- /dev/null +++ b/app/controllers/inspections_controller.rb @@ -0,0 +1,8 @@ +class InspectionsController < ApplicationController + include AircraftScoped + + def index + @rows = Compliance.inspection_rows(@aircraft) + @history = InspectionRecord.for_aircraft(@aircraft).recent_first.includes(:inspection_type, :component, :logbook_entry) + end +end diff --git a/app/controllers/logbook_entries_controller.rb b/app/controllers/logbook_entries_controller.rb new file mode 100644 index 0000000..2c5c46d --- /dev/null +++ b/app/controllers/logbook_entries_controller.rb @@ -0,0 +1,57 @@ +class LogbookEntriesController < ApplicationController + include AircraftScoped + before_action :require_owner!, except: %i[index show] + before_action :set_entry, only: %i[show edit update destroy] + + def index + @query = params[:q] + @log_type = params[:log_type].presence + scope = @aircraft.logbook_entries.search(@query).recent_first.includes(:document) + scope = scope.where(log_type: @log_type) if @log_type + @entries = scope.limit(500) + end + + def show; end + + def new + @entry = @aircraft.logbook_entries.new(date: Date.current, aircraft_hours_at_entry: @aircraft.tach_time) + end + + def create + @entry = @aircraft.logbook_entries.new(entry_params) + if @entry.save + log_event("logbook", "Logbook entry added (#{@entry.date})") + redirect_to aircraft_logbook_entries_path(@aircraft), notice: "Logbook entry added." + else + render :new, status: :unprocessable_entity + end + end + + def edit; end + + def update + if @entry.update(entry_params) + log_event("logbook", "Logbook entry updated (#{@entry.date})") + redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: "Logbook entry updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @entry.destroy! + log_event("logbook", "Logbook entry deleted (#{@entry.date})") + redirect_to aircraft_logbook_entries_path(@aircraft), notice: "Logbook entry deleted." + end + + private + + def set_entry = @entry = @aircraft.logbook_entries.find(params[:id]) + + def entry_params + p = params.require(:logbook_entry).permit(:log_type, :entry_type, :date, :text, :signoff_person, + :signoff_location, :aircraft_hours_at_entry, :document_id, :page_number) + p[:document_id] = scoped_id(@aircraft.documents, p[:document_id]) + p + end +end diff --git a/app/controllers/major_records_controller.rb b/app/controllers/major_records_controller.rb new file mode 100644 index 0000000..687e8ac --- /dev/null +++ b/app/controllers/major_records_controller.rb @@ -0,0 +1,59 @@ +class MajorRecordsController < ApplicationController + include AircraftScoped + before_action :require_owner!, except: %i[index show] + before_action :set_record, only: %i[show edit update destroy] + + def index + @records = @aircraft.major_records.recent_first.includes(:component) + end + + def show; end + + def new + @record = @aircraft.major_records.new(record_type: params[:type] || "repair", date_performed: Date.current, + aircraft_hours: @aircraft.tach_time) + end + + def create + @record = @aircraft.major_records.new(record_params) + if @record.save + log_event("major_record", "#{@record.type_label} added: #{@record.title}") + redirect_to aircraft_major_records_path(@aircraft), notice: "Record added." + else + render :new, status: :unprocessable_entity + end + end + + def edit; end + + def update + if @record.update(record_params) + log_event("major_record", "#{@record.type_label} updated: #{@record.title}") + redirect_to aircraft_major_record_path(@aircraft, @record), notice: "Record updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @record.destroy! + log_event("major_record", "#{@record.type_label} deleted: #{@record.title}") + redirect_to aircraft_major_records_path(@aircraft), notice: "Record deleted." + end + + private + + def set_record = @record = @aircraft.major_records.find(params[:id]) + + def record_params + p = params.require(:major_record).permit( + :record_type, :title, :description, :date_performed, :performed_by, :component_id, + :form_337_document_id, :stc_number, :stc_holder, :stc_document_id, :logbook_entry_id, + :aircraft_hours, :has_ica, :ica_notes, :notes + ) + p[:component_id] = scoped_id(@aircraft.components, p[:component_id]) + p[:logbook_entry_id] = scoped_id(@aircraft.logbook_entries, p[:logbook_entry_id]) + %i[form_337_document_id stc_document_id].each { |k| p[k] = scoped_id(@aircraft.documents, p[k]) } + p + end +end diff --git a/app/controllers/notes_controller.rb b/app/controllers/notes_controller.rb new file mode 100644 index 0000000..07e37d0 --- /dev/null +++ b/app/controllers/notes_controller.rb @@ -0,0 +1,45 @@ +class NotesController < ApplicationController + include AircraftScoped + before_action :require_owner!, only: %i[edit update destroy] + before_action :set_note, only: %i[edit update destroy] + + def index + @notes = @aircraft.notes.recent_first.includes(:user) + end + + def new + @note = @aircraft.notes.new + end + + def create + @note = @aircraft.notes.new(note_params.merge(user: current_user)) + if @note.save + log_event("note", "Note added") + redirect_to aircraft_notes_path(@aircraft), notice: "Note added." + else + render :new, status: :unprocessable_entity + end + end + + def edit; end + + def update + if @note.update(note_params.merge(edited_at: Time.current)) + log_event("note", "Note updated") + redirect_to aircraft_notes_path(@aircraft), notice: "Note updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @note.destroy! + log_event("note", "Note deleted") + redirect_to aircraft_notes_path(@aircraft), notice: "Note deleted." + end + + private + + def set_note = @note = @aircraft.notes.find(params[:id]) + def note_params = params.require(:aircraft_note).permit(:text, :public) +end diff --git a/app/controllers/passwords_controller.rb b/app/controllers/passwords_controller.rb new file mode 100644 index 0000000..0c4b4a8 --- /dev/null +++ b/app/controllers/passwords_controller.rb @@ -0,0 +1,33 @@ +class PasswordsController < ApplicationController + allow_unauthenticated_access + before_action :set_user_by_token, only: %i[ edit update ] + + def new + end + + def create + if user = User.find_by(email_address: params[:email_address]) + PasswordsMailer.reset(user).deliver_later + end + + redirect_to new_session_path, notice: "Password reset instructions sent (if user with that email address exists)." + end + + def edit + end + + def update + if @user.update(params.permit(:password, :password_confirmation)) + redirect_to new_session_path, notice: "Password has been reset." + else + redirect_to edit_password_path(params[:token]), alert: "Passwords did not match." + end + end + + private + def set_user_by_token + @user = User.find_by_password_reset_token!(params[:token]) + rescue ActiveSupport::MessageVerifier::InvalidSignature + redirect_to new_password_path, alert: "Password reset link is invalid or has expired." + end +end diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb new file mode 100644 index 0000000..8ee40e9 --- /dev/null +++ b/app/controllers/profiles_controller.rb @@ -0,0 +1,16 @@ +class ProfilesController < ApplicationController + def edit + @user = current_user + end + + def update + @user = current_user + attrs = params.require(:user).permit(:name, :email_address, :password, :password_confirmation) + attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank? + if @user.update(attrs) + redirect_to root_path, notice: "Profile updated." + else + render :edit, status: :unprocessable_entity + end + end +end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb new file mode 100644 index 0000000..9785c92 --- /dev/null +++ b/app/controllers/sessions_controller.rb @@ -0,0 +1,21 @@ +class SessionsController < ApplicationController + allow_unauthenticated_access only: %i[ new create ] + rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_session_url, alert: "Try again later." } + + def new + end + + def create + if user = User.authenticate_by(params.permit(:email_address, :password)) + start_new_session_for user + redirect_to after_authentication_url + else + redirect_to new_session_path, alert: "Try another email address or password." + end + end + + def destroy + terminate_session + redirect_to new_session_path + end +end diff --git a/app/controllers/setup_controller.rb b/app/controllers/setup_controller.rb new file mode 100644 index 0000000..fa474dd --- /dev/null +++ b/app/controllers/setup_controller.rb @@ -0,0 +1,20 @@ +class SetupController < ApplicationController + allow_unauthenticated_access + before_action { redirect_to root_path if User.exists? } + layout "public" + + def new + @user = User.new + end + + def create + @user = User.new(params.require(:user).permit(:name, :email_address, :password, :password_confirmation)) + @user.admin = true + if @user.save + start_new_session_for @user + redirect_to root_path, notice: "Welcome! You're the administrator. Add your first aircraft." + else + render :new, status: :unprocessable_entity + end + end +end diff --git a/app/controllers/share_tokens_controller.rb b/app/controllers/share_tokens_controller.rb new file mode 100644 index 0000000..7a29e25 --- /dev/null +++ b/app/controllers/share_tokens_controller.rb @@ -0,0 +1,22 @@ +class ShareTokensController < ApplicationController + include AircraftScoped + before_action :require_owner! + + def create + token = @aircraft.share_tokens.new(params.require(:share_token).permit(:label, :privilege, :expires_at)) + token.created_by = current_user + if token.save + log_event("aircraft", "Share link created (#{token.privilege})", notes: token.label) + redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Share link created." + else + redirect_to aircraft_aircraft_roles_path(@aircraft), alert: token.errors.full_messages.to_sentence + end + end + + def destroy + token = @aircraft.share_tokens.find(params[:id]) + token.destroy! + log_event("aircraft", "Share link revoked", notes: token.label) + redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Share link revoked." + end +end diff --git a/app/controllers/shared_controller.rb b/app/controllers/shared_controller.rb new file mode 100644 index 0000000..d7608d0 --- /dev/null +++ b/app/controllers/shared_controller.rb @@ -0,0 +1,30 @@ +# Read-only public view of an aircraft via a share link — no login required. +# 'status' links see current state; 'maintenance' links also see full history. +class SharedController < ApplicationController + allow_unauthenticated_access + skip_before_action :redirect_to_setup + layout "public" + + def show + @share = ShareToken.find_active(params[:token]) or raise ActiveRecord::RecordNotFound + @aircraft = @share.aircraft + @airworthiness = @aircraft.airworthiness + @components = @aircraft.components.where.not(status: "DISPOSED").includes(:component_type).order(:install_location) + @active_squawks = @aircraft.squawks.active.by_priority + @notes = @aircraft.notes.visible_publicly.recent_first + @ad_rows = Compliance.ad_rows(@aircraft) + @inspection_rows = Compliance.inspection_rows(@aircraft) + @oil = ConsumptionStats.new(@aircraft, "oil") + @fuel = ConsumptionStats.new(@aircraft, "fuel") + @documents = @aircraft.documents.includes(:document_collection, pages_attachments: :blob) + .select { |d| d.visible_to_share?(@share) } + + if @share.maintenance? + @logbook = @aircraft.logbook_entries.recent_first + @resolved_squawks = @aircraft.squawks.resolved.order(resolved_at: :desc) + @major_records = @aircraft.major_records.recent_first + @inspection_history = InspectionRecord.for_aircraft(@aircraft).recent_first.includes(:inspection_type) + @ad_history = AdCompliance.for_aircraft(@aircraft).recent_first.includes(:airworthiness_directive) + end + end +end diff --git a/app/controllers/squawks_controller.rb b/app/controllers/squawks_controller.rb new file mode 100644 index 0000000..619cfea --- /dev/null +++ b/app/controllers/squawks_controller.rb @@ -0,0 +1,62 @@ +class SquawksController < ApplicationController + include AircraftScoped + # Pilots may create squawks; editing/resolving needs an owner. + before_action :require_owner!, except: %i[index new create] + 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) + end + + def new + @squawk = @aircraft.squawks.new(priority: 1) + end + + def create + @squawk = @aircraft.squawks.new(squawk_params.merge(reported_by: current_user)) + if @squawk.save + log_event("squawk", "Squawk reported: #{@squawk.priority_label}", notes: @squawk.issue_reported.truncate(200)) + redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk reported." + else + render :new, status: :unprocessable_entity + end + end + + def edit; end + + def update + if @squawk.update(squawk_params) + log_event("squawk", "Squawk updated") + redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk updated." + else + render :edit, status: :unprocessable_entity + end + end + + def resolve + @squawk.resolve!(notes: params[:resolution_notes]) + log_event("squawk", "Squawk resolved", notes: @squawk.issue_reported.truncate(200)) + redirect_back fallback_location: aircraft_squawks_path(@aircraft), notice: "Squawk resolved." + end + + def reopen + @squawk.update!(resolved: false, resolved_at: nil) + log_event("squawk", "Squawk reopened") + redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk reopened." + end + + def destroy + @squawk.destroy! + log_event("squawk", "Squawk deleted") + redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk deleted." + end + + private + + def set_squawk = @squawk = @aircraft.squawks.find(params[:id]) + + def squawk_params + params.require(:squawk).permit(:priority, :issue_reported, :component_id, :notes, :attachment) + end +end diff --git a/app/form_builders/app_form_builder.rb b/app/form_builders/app_form_builder.rb new file mode 100644 index 0000000..1a01bef --- /dev/null +++ b/app/form_builders/app_form_builder.rb @@ -0,0 +1,54 @@ +# Wraps fields with a label, hint, and inline errors using the app's Tailwind classes. +# <%= f.field :tail_number %> +# <%= f.field :tach_time, as: :number, step: 0.1 %> +# <%= f.field :status, as: :select, collection: Aircraft::STATUSES.invert %> +# <%= f.field :public, as: :checkbox, label: "Show on share links" %> +class AppFormBuilder < ActionView::Helpers::FormBuilder + def field(method, as: :text, label: nil, hint: nil, collection: nil, include_blank: false, wrapper: {}, **opts) + label_text = label || method.to_s.humanize + errors = object.respond_to?(:errors) ? object.errors[method] : [] + + if as == :checkbox + return @template.content_tag(:div, class: [ "flex items-start gap-2", wrapper[:class] ]) do + check_box(method, { class: "mt-0.5 h-4 w-4 rounded border-slate-300 text-sky-700" }.merge(opts)) + + @template.content_tag(:div) do + label(method, label_text, class: "text-sm text-slate-700") + + (hint ? @template.content_tag(:p, hint, class: "hint") : "".html_safe) + end + end + end + + input_opts = { class: "input" }.merge(opts) + input = + case as + when :textarea then text_area(method, { rows: 4 }.merge(input_opts)) + when :number then number_field(method, input_opts) + when :date then date_field(method, input_opts) + when :datetime then datetime_field(method, input_opts) + when :email then email_field(method, input_opts) + when :password then password_field(method, input_opts) + when :file then file_field(method, opts.merge(class: "block text-sm text-slate-600 file:mr-3 file:rounded-md file:border-0 file:bg-slate-100 file:px-3 file:py-1.5 file:text-sm file:font-medium hover:file:bg-slate-200")) + when :select then select(method, collection, { include_blank: include_blank }, input_opts) + else text_field(method, input_opts) + end + + @template.content_tag(:div, class: wrapper[:class]) do + label(method, label_text, class: "label") + input + + (hint ? @template.content_tag(:p, hint, class: "hint") : "".html_safe) + + errors.map { |e| @template.content_tag(:p, "#{label_text} #{e}", class: "field-error") }.join.html_safe + end + end + + def errors_summary + return "".html_safe unless object&.errors&.any? + @template.content_tag(:div, class: "rounded-md bg-red-50 p-3 text-sm text-red-700 ring-1 ring-red-200") do + @template.content_tag(:ul, class: "list-disc pl-5") do + object.errors.full_messages.map { |m| @template.content_tag(:li, m) }.join.html_safe + end + end + end + + def submit(value = nil, **opts) + super(value, { class: "btn-primary" }.merge(opts)) + end +end diff --git a/app/helpers/aircraft_helper.rb b/app/helpers/aircraft_helper.rb new file mode 100644 index 0000000..c5ba2e2 --- /dev/null +++ b/app/helpers/aircraft_helper.rb @@ -0,0 +1,33 @@ +module AircraftHelper + # Tabs on the aircraft pages: [label, path, controller names that highlight it, owner_only] + def aircraft_tabs(aircraft) + [ + [ "Overview", aircraft_path(aircraft), %w[aircraft] ], + [ "Components", aircraft_components_path(aircraft), %w[components] ], + [ "Squawks", aircraft_squawks_path(aircraft), %w[squawks] ], + [ "Flights", aircraft_flight_logs_path(aircraft), %w[flight_logs] ], + [ "Oil & Fuel", aircraft_consumable_records_path(aircraft), %w[consumable_records] ], + [ "Logbook", aircraft_logbook_entries_path(aircraft), %w[logbook_entries] ], + [ "Inspections", aircraft_inspections_path(aircraft), %w[inspections inspection_types inspection_records] ], + [ "ADs", aircraft_airworthiness_directives_path(aircraft), %w[airworthiness_directives ad_compliances] ], + [ "Documents", aircraft_documents_path(aircraft), %w[documents document_collections] ], + [ "Major Records", aircraft_major_records_path(aircraft), %w[major_records] ], + [ "Notes", aircraft_notes_path(aircraft), %w[notes] ], + [ "Activity", aircraft_events_path(aircraft), %w[events] ], + ([ "Access & Sharing", aircraft_aircraft_roles_path(aircraft), %w[aircraft_roles share_tokens] ] if owner?) + ].compact + end + + def component_options(aircraft, include_blank: true) + opts = aircraft.components.where.not(status: "DISPOSED").includes(:component_type).map { [ _1.to_s, _1.id ] } + include_blank ? [ [ "— None —", nil ] ] + opts : opts + end + + def document_options(aircraft) + [ [ "— None —", nil ] ] + aircraft.documents.ordered.map { [ _1.name, _1.id ] } + end + + def logbook_options(aircraft) + [ [ "— None —", nil ] ] + aircraft.logbook_entries.recent_first.limit(300).map { [ "#{_1.date} – #{_1.text.truncate(60)}", _1.id ] } + end +end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb new file mode 100644 index 0000000..5ef17df --- /dev/null +++ b/app/helpers/application_helper.rb @@ -0,0 +1,64 @@ +module ApplicationHelper + def hours(value) + return "—" if value.nil? + number_with_precision(value, precision: 1, delimiter: ",") + end + + def fmt_date(value) + value ? l(value.to_date, format: :long) : "—" + end + + def airworthiness_badge(status, large: false) + color = { "RED" => "red", "ORANGE" => "orange", "GREEN" => "green" }[status.status] + tag.span(status.label, class: [ "badge-#{color}", ("text-sm px-3 py-1" if large) ]) + end + + def airworthiness_dot(status) + color = { "RED" => "bg-red-500", "ORANGE" => "bg-amber-400", "GREEN" => "bg-emerald-500" }[status.status] + tag.span(class: "inline-block h-3 w-3 rounded-full #{color}", title: status.label) + end + + COMPLIANCE_BADGES = { + "compliant" => [ "green", "Compliant" ], "due_soon" => [ "orange", "Due Soon" ], + "overdue" => [ "red", "Overdue" ], "no_compliance" => [ "red", "No Record" ], + "never_completed" => [ "red", "Never Completed" ], "conditional" => [ "gray", "Conditional" ] + }.freeze + + def compliance_badge(status) + color, text = COMPLIANCE_BADGES.fetch(status, [ "gray", status.to_s.humanize ]) + tag.span(text, class: "badge-#{color}") + end + + def life_badge(status) + return "" unless status + color, text = { overdue: [ "red", "Overdue" ], due_soon: [ "orange", "Due Soon" ], ok: [ "green", "OK" ] }[status] + tag.span(text, class: "badge-#{color}") + end + + def squawk_priority_badge(squawk) + tag.span(squawk.priority_label, class: "badge-#{squawk.priority_color}") + end + + def aircraft_status_badge(aircraft) + color = { "AVAILABLE" => "green", "MX" => "orange", "GROUND" => "red", "UNAVAILABLE" => "gray" }[aircraft.status] + tag.span(aircraft.status_label, class: "badge-#{color}") + end + + def visibility_badge(visibility) + color = { "private" => "gray", "status" => "green", "maintenance" => "blue" }[visibility] + tag.span(DocumentCollection::VISIBILITIES[visibility], class: "badge-#{color}") + end + + def delete_button(label, path, confirm: "Are you sure?", **opts) + button_to label, path, method: :delete, form: { data: { turbo_confirm: confirm }, class: "inline" }, + class: opts[:class] || "btn-danger btn-sm" + end + + def empty_state(text) + tag.p(text, class: "py-6 text-center text-sm text-slate-500") + end + + def nav_tab(label, path, active) + link_to label, path, class: [ "tab", ("tab-active" if active) ] + end +end diff --git a/app/javascript/application.js b/app/javascript/application.js new file mode 100644 index 0000000..9495c27 --- /dev/null +++ b/app/javascript/application.js @@ -0,0 +1,5 @@ +// Configure your import map in config/importmap.rb. +import "@hotwired/turbo-rails" +import "controllers" +import "chartkick" +import "Chart.bundle" diff --git a/app/javascript/controllers/application.js b/app/javascript/controllers/application.js new file mode 100644 index 0000000..1213e85 --- /dev/null +++ b/app/javascript/controllers/application.js @@ -0,0 +1,9 @@ +import { Application } from "@hotwired/stimulus" + +const application = Application.start() + +// Configure Stimulus development experience +application.debug = false +window.Stimulus = application + +export { application } diff --git a/app/javascript/controllers/hello_controller.js b/app/javascript/controllers/hello_controller.js new file mode 100644 index 0000000..5975c07 --- /dev/null +++ b/app/javascript/controllers/hello_controller.js @@ -0,0 +1,7 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + connect() { + this.element.textContent = "Hello World!" + } +} diff --git a/app/javascript/controllers/index.js b/app/javascript/controllers/index.js new file mode 100644 index 0000000..1156bf8 --- /dev/null +++ b/app/javascript/controllers/index.js @@ -0,0 +1,4 @@ +// Import and register all your controllers from the importmap via controllers/**/*_controller +import { application } from "controllers/application" +import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" +eagerLoadControllersFrom("controllers", application) diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb new file mode 100644 index 0000000..d394c3d --- /dev/null +++ b/app/jobs/application_job.rb @@ -0,0 +1,7 @@ +class ApplicationJob < ActiveJob::Base + # Automatically retry jobs that encountered a deadlock + # retry_on ActiveRecord::Deadlocked + + # Most jobs are safe to ignore if the underlying records are no longer available + # discard_on ActiveJob::DeserializationError +end diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb new file mode 100644 index 0000000..d3efeb5 --- /dev/null +++ b/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: ENV.fetch("MAIL_FROM", "aircraft-manager@localhost") + layout "mailer" +end diff --git a/app/mailers/passwords_mailer.rb b/app/mailers/passwords_mailer.rb new file mode 100644 index 0000000..4f0ac7f --- /dev/null +++ b/app/mailers/passwords_mailer.rb @@ -0,0 +1,6 @@ +class PasswordsMailer < ApplicationMailer + def reset(user) + @user = user + mail subject: "Reset your password", to: user.email_address + end +end diff --git a/app/models/ad_compliance.rb b/app/models/ad_compliance.rb new file mode 100644 index 0000000..c6a9c49 --- /dev/null +++ b/app/models/ad_compliance.rb @@ -0,0 +1,16 @@ +class AdCompliance < ApplicationRecord + belongs_to :airworthiness_directive + belongs_to :aircraft, optional: true + belongs_to :component, optional: true + belongs_to :logbook_entry, optional: true + belongs_to :inspection_record, optional: true + + validates :date_complied, :compliance_notes, presence: true + validate { errors.add(:base, "Must belong to an aircraft or component") unless aircraft_id || component_id } + + scope :recent_first, -> { order(date_complied: :desc, created_at: :desc) } + + def self.for_aircraft(aircraft) + where(aircraft_id: aircraft.id).or(where(component_id: aircraft.components.select(:id))) + end +end diff --git a/app/models/aircraft.rb b/app/models/aircraft.rb new file mode 100644 index 0000000..f973053 --- /dev/null +++ b/app/models/aircraft.rb @@ -0,0 +1,73 @@ +class Aircraft < ApplicationRecord + STATUSES = { + "AVAILABLE" => "Available", + "MX" => "In Maintenance", + "GROUND" => "Grounded", + "UNAVAILABLE" => "Unavailable" + }.freeze + + has_one_attached :picture + + has_many :roles, class_name: "AircraftRole", dependent: :destroy + has_many :users, through: :roles + has_many :notes, class_name: "AircraftNote", dependent: :destroy + has_many :events, class_name: "AircraftEvent", dependent: :delete_all + has_many :share_tokens, dependent: :destroy + has_many :components, dependent: :destroy + has_many :squawks, dependent: :destroy + has_many :logbook_entries, dependent: :destroy + has_many :document_collections, dependent: :destroy + has_many :documents, dependent: :destroy + has_many :inspection_records, dependent: :destroy + has_many :ad_compliances, dependent: :destroy + has_many :major_records, dependent: :destroy + has_many :flight_logs, dependent: :destroy + has_many :consumable_records, dependent: :destroy + has_and_belongs_to_many :inspection_types + has_and_belongs_to_many :airworthiness_directives + + validates :tail_number, presence: true + validates :status, inclusion: { in: STATUSES.keys } + validate :picture_is_image + + scope :ordered, -> { order(:tail_number) } + + def to_s = tail_number + + def status_label = STATUSES[status] + + # Hours used for compliance calculations (tach minus offset, as in the original). + def current_hours + tach_time - tach_time_offset + end + + def airworthiness + @airworthiness ||= Airworthiness.new(self).call + end + + def reload(*) + @airworthiness = nil + super + end + + # ADs that apply directly or via any installed component. + def applicable_ads + AirworthinessDirective.applicable_to(self) + end + + def applicable_inspection_types + InspectionType.applicable_to(self) + end + + def log_event!(category, event_name, user: Current.user, notes: nil) + events.create!(category: category, event_name: event_name, user: user, notes: notes) + end + + private + + def picture_is_image + if picture.attached? && !picture.content_type.to_s.start_with?("image/") + errors.add(:picture, "must be an image") + end + end +end diff --git a/app/models/aircraft_event.rb b/app/models/aircraft_event.rb new file mode 100644 index 0000000..c546f5e --- /dev/null +++ b/app/models/aircraft_event.rb @@ -0,0 +1,15 @@ +class AircraftEvent < ApplicationRecord + CATEGORIES = { + "hours" => "Hours Update", "flight" => "Flight", "component" => "Component", + "squawk" => "Squawk", "note" => "Note", "oil" => "Oil", "fuel" => "Fuel", + "logbook" => "Logbook", "ad" => "Airworthiness Directive", "inspection" => "Inspection", + "document" => "Document", "aircraft" => "Aircraft", "role" => "Role", + "major_record" => "Major Repair/Alteration" + }.freeze + + belongs_to :aircraft + belongs_to :user, optional: true + + validates :category, inclusion: { in: CATEGORIES.keys } + default_scope { order(created_at: :desc) } +end diff --git a/app/models/aircraft_note.rb b/app/models/aircraft_note.rb new file mode 100644 index 0000000..9cf22ee --- /dev/null +++ b/app/models/aircraft_note.rb @@ -0,0 +1,8 @@ +class AircraftNote < ApplicationRecord + belongs_to :aircraft + belongs_to :user, optional: true + + validates :text, presence: true + scope :visible_publicly, -> { where(public: true) } + scope :recent_first, -> { order(created_at: :desc) } +end diff --git a/app/models/aircraft_role.rb b/app/models/aircraft_role.rb new file mode 100644 index 0000000..1f16f1d --- /dev/null +++ b/app/models/aircraft_role.rb @@ -0,0 +1,11 @@ +class AircraftRole < ApplicationRecord + ROLES = { "owner" => "Owner", "pilot" => "Pilot" }.freeze + + belongs_to :aircraft + belongs_to :user + + validates :role, inclusion: { in: ROLES.keys } + validates :user_id, uniqueness: { scope: :aircraft_id, message: "already has a role on this aircraft" } + + scope :owners, -> { where(role: "owner") } +end diff --git a/app/models/airworthiness_directive.rb b/app/models/airworthiness_directive.rb new file mode 100644 index 0000000..37c549f --- /dev/null +++ b/app/models/airworthiness_directive.rb @@ -0,0 +1,33 @@ +class AirworthinessDirective < ApplicationRecord + COMPLIANCE_TYPES = { "standard" => "Standard", "conditional" => "Conditional" }.freeze + BULLETIN_TYPES = { + "ad" => "Airworthiness Directive", "saib" => "Special Airworthiness Information Bulletin", + "sb" => "Service Bulletin", "alert" => "Airworthiness Alert", "other" => "Other" + }.freeze + BULLETIN_LABELS = { "ad" => "AD", "saib" => "SAIB", "sb" => "SB", "alert" => "Alert", "other" => "Bulletin" }.freeze + + belongs_to :document, optional: true + has_and_belongs_to_many :aircraft + has_and_belongs_to_many :components + has_many :ad_compliances, dependent: :destroy + + validates :name, :short_description, presence: true + validates :compliance_type, inclusion: { in: COMPLIANCE_TYPES.keys } + validates :bulletin_type, inclusion: { in: BULLETIN_TYPES.keys } + + scope :ordered, -> { order(:name) } + + def self.applicable_to(aircraft) + direct = joins(:aircraft).where(aircraft: { id: aircraft.id }).select(:id) + via_component = joins(:components).where(components: { aircraft_id: aircraft.id }).select(:id) + where(id: direct).or(where(id: via_component)) + end + + def to_s = name + def conditional? = compliance_type == "conditional" + def bulletin_label = BULLETIN_LABELS[bulletin_type] + + def latest_compliance_for(aircraft) + ad_compliances.for_aircraft(aircraft).order(date_complied: :desc, created_at: :desc).first + end +end diff --git a/app/models/application_record.rb b/app/models/application_record.rb new file mode 100644 index 0000000..b63caeb --- /dev/null +++ b/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/app/models/component.rb b/app/models/component.rb new file mode 100644 index 0000000..deb792a --- /dev/null +++ b/app/models/component.rb @@ -0,0 +1,73 @@ +class Component < ApplicationRecord + STATUSES = { "SPARE" => "Spare Part", "IN-USE" => "In Service", "DISPOSED" => "Disposed" }.freeze + + belongs_to :aircraft, optional: true + belongs_to :parent_component, class_name: "Component", optional: true + belongs_to :component_type + has_many :child_components, class_name: "Component", foreign_key: :parent_component_id, dependent: :destroy + has_many :squawks, dependent: :nullify + has_and_belongs_to_many :inspection_types + has_and_belongs_to_many :airworthiness_directives + + validates :manufacturer, :model, :date_in_service, presence: true + validates :status, inclusion: { in: STATUSES.keys } + validate :parent_on_same_aircraft + + scope :in_use, -> { where(status: "IN-USE") } + + def to_s + [ component_type&.name, install_location.presence && "(#{install_location})" ].compact.join(" ") + end + + def status_label = STATUSES[status] + + def hours_to_tbo + tbo_hours - hours_since_overhaul if tbo_hours + end + + def hours_to_replacement + replacement_hours - hours_since_overhaul if replacement_hours + end + + def next_replacement_date + overhaul_date + replacement_days.days if replacement_days && overhaul_date + end + + # :overdue / :due_soon / :ok / nil (not tracked) for display on the components tab. + def life_status + statuses = [] + if replacement_critical? + if replacement_hours + statuses << rank(hours_to_replacement <= 0, hours_to_replacement <= Airworthiness::HOURS_WARNING) + end + if (d = next_replacement_date) + statuses << rank(Date.current >= d, Date.current + Airworthiness::DAYS_WARNING >= d) + end + end + if tbo_critical? && tbo_hours && !on_condition? + statuses << rank(hours_to_tbo <= 0, hours_to_tbo <= Airworthiness::HOURS_WARNING * 5) + end + return nil if statuses.empty? + %i[overdue due_soon ok].find { |s| statuses.include?(s) } + end + + # Service reset: always zeroes time since overhaul; optionally the whole + # in-service clock when the part was physically replaced. + def reset_service!(reset_in_service: false) + attrs = { hours_since_overhaul: 0, overhaul_date: Date.current } + attrs.merge!(hours_in_service: 0, date_in_service: Date.current) if reset_in_service + update!(attrs) + end + + private + + def rank(overdue, soon) + overdue ? :overdue : (soon ? :due_soon : :ok) + end + + def parent_on_same_aircraft + return unless parent_component + errors.add(:parent_component, "can't be itself") if parent_component_id == id && id + errors.add(:parent_component, "must be on the same aircraft") if parent_component.aircraft_id != aircraft_id + end +end diff --git a/app/models/component_type.rb b/app/models/component_type.rb new file mode 100644 index 0000000..04b6b4c --- /dev/null +++ b/app/models/component_type.rb @@ -0,0 +1,6 @@ +class ComponentType < ApplicationRecord + has_many :components, dependent: :restrict_with_error + validates :name, presence: true, uniqueness: { case_sensitive: false } + scope :ordered, -> { order(:name) } + def to_s = name +end diff --git a/app/models/concerns/.keep b/app/models/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/app/models/concerns/upload_validation.rb b/app/models/concerns/upload_validation.rb new file mode 100644 index 0000000..765f323 --- /dev/null +++ b/app/models/concerns/upload_validation.rb @@ -0,0 +1,27 @@ +# Mirrors the original's ALLOWED_UPLOAD_EXTENSIONS / content-type checks. +module UploadValidation + extend ActiveSupport::Concern + + ALLOWED_CONTENT_TYPES = %w[ + image/jpeg image/png image/gif image/webp image/bmp image/tiff + application/pdf text/plain application/gpx+xml application/xml text/xml + text/csv application/vnd.google-earth.kml+xml application/octet-stream + ].freeze + MAX_SIZE = 50.megabytes + + class_methods do + def validates_uploads(*names) + validate do + names.each do |name| + Array(public_send(name).attachments).each do |att| + next unless att.blob + unless ALLOWED_CONTENT_TYPES.include?(att.blob.content_type) + errors.add(name, "#{att.filename} is not an allowed file type") + end + errors.add(name, "#{att.filename} is too large") if att.blob.byte_size > MAX_SIZE + end + end + end + end + end +end diff --git a/app/models/consumable_record.rb b/app/models/consumable_record.rb new file mode 100644 index 0000000..e0640fa --- /dev/null +++ b/app/models/consumable_record.rb @@ -0,0 +1,17 @@ +class ConsumableRecord < ApplicationRecord + TYPES = { "oil" => "Oil", "fuel" => "Fuel" }.freeze + UNITS = { "oil" => "qt", "fuel" => "gal" }.freeze + + belongs_to :aircraft + belongs_to :flight_log, optional: true + + validates :record_type, inclusion: { in: TYPES.keys } + validates :date, :flight_hours, presence: true + validates :quantity_added, presence: true, numericality: { greater_than_or_equal_to: 0 } + + scope :oil, -> { where(record_type: "oil") } + scope :fuel, -> { where(record_type: "fuel") } + scope :recent_first, -> { order(date: :desc, created_at: :desc) } + + def unit = UNITS[record_type] +end diff --git a/app/models/current.rb b/app/models/current.rb new file mode 100644 index 0000000..2bef56d --- /dev/null +++ b/app/models/current.rb @@ -0,0 +1,4 @@ +class Current < ActiveSupport::CurrentAttributes + attribute :session + delegate :user, to: :session, allow_nil: true +end diff --git a/app/models/document.rb b/app/models/document.rb new file mode 100644 index 0000000..92f5bba --- /dev/null +++ b/app/models/document.rb @@ -0,0 +1,38 @@ +class Document < ApplicationRecord + include UploadValidation + + TYPES = { + "LOG" => "Logbook", "ALTER" => "Alteration Record", "REPORT" => "Report", + "ESTIMATE" => "Estimate", "DISC" => "Discrepancy List", "INVOICE" => "Receipt / Invoice", + "AIRCRAFT" => "Aircraft Record", "OTHER" => "Other" + }.freeze + + belongs_to :aircraft + belongs_to :document_collection, optional: true + has_many_attached :pages + has_many :logbook_entries, dependent: :nullify + + validates :name, presence: true + validates :doc_type, inclusion: { in: TYPES.keys } + validates :visibility, inclusion: { in: DocumentCollection::VISIBILITIES.keys }, allow_nil: true + validates_uploads :pages + normalizes :visibility, with: ->(v) { v.presence } + + scope :ordered, -> { order(:name) } + + def to_s = name + def type_label = TYPES[doc_type] + + # nil visibility inherits from the collection; uncollected docs default to private. + def effective_visibility + visibility || document_collection&.visibility || "private" + end + + def visible_to_share?(share) + case effective_visibility + when "status" then true + when "maintenance" then share.maintenance? + else false + end + end +end diff --git a/app/models/document_collection.rb b/app/models/document_collection.rb new file mode 100644 index 0000000..ceb240c --- /dev/null +++ b/app/models/document_collection.rb @@ -0,0 +1,12 @@ +class DocumentCollection < ApplicationRecord + VISIBILITIES = { "private" => "Private", "status" => "All share links", "maintenance" => "Maintenance only" }.freeze + + belongs_to :aircraft + has_many :documents, dependent: :destroy + + validates :name, presence: true + validates :visibility, inclusion: { in: VISIBILITIES.keys } + + scope :ordered, -> { order(starred: :desc, name: :asc) } + def to_s = name +end diff --git a/app/models/flight_log.rb b/app/models/flight_log.rb new file mode 100644 index 0000000..7459872 --- /dev/null +++ b/app/models/flight_log.rb @@ -0,0 +1,28 @@ +class FlightLog < ApplicationRecord + include UploadValidation + + belongs_to :aircraft + belongs_to :user, optional: true + has_many :consumable_records, dependent: :nullify + has_one_attached :track_log + + validates :date, presence: true + validates :tach_time, presence: true, numericality: { greater_than: 0 } + validates :hobbs_time, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true + validates_uploads :track_log + before_validation :derive_times + + scope :recent_first, -> { order(date: :desc, created_at: :desc) } + + def route_summary + [ departure_location, destination_location ].compact_blank.join(" → ") + end + + private + + # Let the pilot enter out/in readings instead of the delta. + def derive_times + self.tach_time = tach_in - tach_out if tach_time.blank? && tach_in && tach_out + self.hobbs_time = hobbs_in - hobbs_out if hobbs_time.blank? && hobbs_in && hobbs_out + end +end diff --git a/app/models/inspection_record.rb b/app/models/inspection_record.rb new file mode 100644 index 0000000..3fcc0ca --- /dev/null +++ b/app/models/inspection_record.rb @@ -0,0 +1,22 @@ +class InspectionRecord < ApplicationRecord + belongs_to :inspection_type + belongs_to :aircraft, optional: true + belongs_to :component, optional: true + belongs_to :logbook_entry, optional: true + has_many :ad_compliances, dependent: :nullify + + validates :date, presence: true + validate { errors.add(:base, "Must belong to an aircraft or component") unless aircraft_id || component_id } + + scope :recent_first, -> { order(date: :desc, created_at: :desc) } + + # Records belonging to the aircraft, or to any of its components. + def self.for_aircraft(aircraft) + where(aircraft_id: aircraft.id).or(where(component_id: aircraft.components.select(:id))) + end + + # Hours at inspection, falling back to the linked logbook entry. + def hours_at_inspection + aircraft_hours || logbook_entry&.aircraft_hours_at_entry + end +end diff --git a/app/models/inspection_type.rb b/app/models/inspection_type.rb new file mode 100644 index 0000000..d78f7bb --- /dev/null +++ b/app/models/inspection_type.rb @@ -0,0 +1,27 @@ +class InspectionType < ApplicationRecord + has_and_belongs_to_many :aircraft + has_and_belongs_to_many :components + has_many :inspection_records, dependent: :destroy + + validates :name, presence: true + + scope :ordered, -> { order(:name) } + + # Applies to the aircraft directly, or to one of its components. + def self.applicable_to(aircraft) + direct = joins(:aircraft).where(aircraft: { id: aircraft.id }).select(:id) + via_component = joins(:components).where(components: { aircraft_id: aircraft.id }).select(:id) + where(id: direct).or(where(id: via_component)) + end + + def to_s = name + + def interval_description + return "One-time" unless recurring? + parts = [] + parts << "#{recurring_hours.to_s.sub(/\.0\z/, '')} hrs" if recurring_hours.to_f > 0 + parts << "#{recurring_months} months" if recurring_months > 0 + parts << "#{recurring_days} days" if recurring_days > 0 + parts.any? ? "Every #{parts.join(' / ')}" : "Recurring" + end +end diff --git a/app/models/logbook_entry.rb b/app/models/logbook_entry.rb new file mode 100644 index 0000000..1aa494c --- /dev/null +++ b/app/models/logbook_entry.rb @@ -0,0 +1,26 @@ +class LogbookEntry < ApplicationRecord + LOG_TYPES = { "AC" => "Aircraft", "ENG" => "Engine", "PROP" => "Propeller", "OTHER" => "Other" }.freeze + ENTRY_TYPES = { + "MAINTENANCE" => "Maintenance", "INSPECTION" => "Inspection", "FLIGHT" => "Flight", + "HOURS_UPDATE" => "Hours Update", "OTHER" => "Other" + }.freeze + + belongs_to :aircraft + belongs_to :document, optional: true + has_many :inspection_records, dependent: :nullify + has_many :ad_compliances, dependent: :nullify + + validates :date, :text, presence: true + validates :log_type, inclusion: { in: LOG_TYPES.keys } + validates :entry_type, inclusion: { in: ENTRY_TYPES.keys } + + scope :recent_first, -> { order(date: :desc, created_at: :desc) } + + def self.search(q) + return all if q.blank? + term = "%#{sanitize_sql_like(q)}%" + where("text LIKE :t OR signoff_person LIKE :t OR signoff_location LIKE :t", t: term) + end + + def to_s = "#{date} — #{LOG_TYPES[log_type]}" +end diff --git a/app/models/major_record.rb b/app/models/major_record.rb new file mode 100644 index 0000000..2702281 --- /dev/null +++ b/app/models/major_record.rb @@ -0,0 +1,16 @@ +class MajorRecord < ApplicationRecord + RECORD_TYPES = { "repair" => "Major Repair", "alteration" => "Major Alteration" }.freeze + + belongs_to :aircraft + belongs_to :component, optional: true + belongs_to :form_337_document, class_name: "Document", optional: true + belongs_to :stc_document, class_name: "Document", optional: true + belongs_to :logbook_entry, optional: true + + validates :title, :date_performed, presence: true + validates :record_type, inclusion: { in: RECORD_TYPES.keys } + + scope :recent_first, -> { order(date_performed: :desc, created_at: :desc) } + + def type_label = RECORD_TYPES[record_type] +end diff --git a/app/models/session.rb b/app/models/session.rb new file mode 100644 index 0000000..cf376fb --- /dev/null +++ b/app/models/session.rb @@ -0,0 +1,3 @@ +class Session < ApplicationRecord + belongs_to :user +end diff --git a/app/models/share_token.rb b/app/models/share_token.rb new file mode 100644 index 0000000..991966e --- /dev/null +++ b/app/models/share_token.rb @@ -0,0 +1,28 @@ +class ShareToken < ApplicationRecord + PRIVILEGES = { "status" => "Current Status", "maintenance" => "Maintenance Detail" }.freeze + MAX_PER_AIRCRAFT = 10 + + belongs_to :aircraft + belongs_to :created_by, class_name: "User", optional: true + has_secure_token :token, length: 32 + + validates :privilege, inclusion: { in: PRIVILEGES.keys } + validate :within_limit, on: :create + + scope :active, -> { where(expires_at: nil).or(where(expires_at: Time.current..)) } + + def self.find_active(token) + active.find_by(token: token.to_s) + end + + def maintenance? = privilege == "maintenance" + def expired? = expires_at.present? && expires_at < Time.current + + private + + def within_limit + if aircraft && aircraft.share_tokens.count >= MAX_PER_AIRCRAFT + errors.add(:base, "An aircraft can have at most #{MAX_PER_AIRCRAFT} share links") + end + end +end diff --git a/app/models/squawk.rb b/app/models/squawk.rb new file mode 100644 index 0000000..638adff --- /dev/null +++ b/app/models/squawk.rb @@ -0,0 +1,27 @@ +class Squawk < ApplicationRecord + include UploadValidation + + PRIORITIES = { 0 => "Ground Aircraft", 1 => "Fix Soon", 2 => "Fix at Next Inspection", 3 => "Fix Eventually" }.freeze + PRIORITY_COLORS = { 0 => "red", 1 => "orange", 2 => "blue", 3 => "gray" }.freeze + + belongs_to :aircraft + belongs_to :component, optional: true + belongs_to :reported_by, class_name: "User", optional: true + has_one_attached :attachment + + validates :priority, inclusion: { in: PRIORITIES.keys } + validates :issue_reported, presence: true + validates_uploads :attachment + + scope :active, -> { where(resolved: false) } + scope :resolved, -> { where(resolved: true) } + scope :by_priority, -> { order(:priority, created_at: :desc) } + + def priority_label = PRIORITIES[priority] + def priority_color = PRIORITY_COLORS[priority] + def grounding? = priority.zero? && !resolved? + + def resolve!(notes: nil) + update!(resolved: true, resolved_at: Time.current, notes: [ self.notes, notes ].compact_blank.join("\n\n")) + end +end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 0000000..f9ede5c --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,27 @@ +class User < ApplicationRecord + has_secure_password + has_many :sessions, dependent: :destroy + has_many :aircraft_roles, dependent: :destroy + has_many :aircraft, through: :aircraft_roles + + normalizes :email_address, with: ->(e) { e.strip.downcase } + + validates :email_address, presence: true, uniqueness: true, + format: { with: URI::MailTo::EMAIL_REGEXP } + validates :password, length: { minimum: 8 }, allow_nil: true + + # Aircraft visible to this user: admins see the whole fleet. + def accessible_aircraft + admin? ? Aircraft.all : aircraft + end + + # 'admin' | 'owner' | 'pilot' | nil + def role_for(aircraft) + return "admin" if admin? + aircraft_roles.find_by(aircraft: aircraft)&.role + end + + def display_name + name.presence || email_address + end +end diff --git a/app/services/aircraft_grounded_error.rb b/app/services/aircraft_grounded_error.rb new file mode 100644 index 0000000..b092452 --- /dev/null +++ b/app/services/aircraft_grounded_error.rb @@ -0,0 +1,11 @@ +# Raised when a flight-activity write is attempted on a RED aircraft whose +# airworthiness enforcement is enabled. +class AircraftGroundedError < StandardError + attr_reader :airworthiness + + def initialize(airworthiness) + @airworthiness = airworthiness + reasons = airworthiness.red_issues.map(&:title).join("; ") + super([ "Aircraft is grounded and airworthiness enforcement is enabled", reasons.presence ].compact.join(": ")) + end +end diff --git a/app/services/airworthiness.rb b/app/services/airworthiness.rb new file mode 100644 index 0000000..f30c343 --- /dev/null +++ b/app/services/airworthiness.rb @@ -0,0 +1,120 @@ +# Computes RED / ORANGE / GREEN airworthiness for an aircraft. Checks (in order): +# AD compliance, grounding squawks, inspection recurrency, component replacement. +class Airworthiness + HOURS_WARNING = BigDecimal("10") + DAYS_WARNING = 30 + + RED = "RED" + ORANGE = "ORANGE" + GREEN = "GREEN" + + Issue = Struct.new(:category, :severity, :title, :description, :item, keyword_init: true) + + Status = Struct.new(:status, :issues, keyword_init: true) do + def red? = status == RED + def orange? = status == ORANGE + def green? = status == GREEN + def can_fly? = green? + def red_issues = issues.select { |i| i.severity == RED } + def label = { RED => "Not Airworthy", ORANGE => "Attention Needed", GREEN => "Airworthy" }[status] + end + + def initialize(aircraft, today: Date.current) + @aircraft = aircraft + @today = today + @hours = aircraft.current_hours + @issues = [] + end + + def call + check_ads + check_grounding_squawks + check_inspections + check_components + + status = + if @issues.any? { _1.severity == RED } then RED + elsif @issues.any? { _1.severity == ORANGE } then ORANGE + else GREEN + end + Status.new(status: status, issues: @issues) + end + + private + + def add(category, severity, title, description, item) + @issues << Issue.new(category:, severity:, title:, description:, item:) + end + + def check_ads + @aircraft.applicable_ads.where(mandatory: true, compliance_type: "standard").find_each do |ad| + compliance = ad.latest_compliance_for(@aircraft) + res = Compliance.ad_status(ad, compliance, @hours, @today) + label = ad.bulletin_label + case res.rank + when Compliance::OVERDUE + desc = compliance ? "#{ad.short_description}. Compliance overdue." : "#{ad.short_description}. No compliance record found." + add("AD", RED, "#{label} #{ad.name} - Overdue", desc, ad) + when Compliance::DUE_SOON + add("AD", ORANGE, "#{label} #{ad.name} - Due Soon", "#{ad.short_description}. Compliance due soon.", ad) + end + end + end + + def check_grounding_squawks + @aircraft.squawks.active.where(priority: 0).find_each do |squawk| + add("SQUAWK", RED, "Grounding Squawk", squawk.issue_reported.to_s.truncate(100).presence || "No description", squawk) + end + end + + def check_inspections + @aircraft.applicable_inspection_types.where(required: true).find_each do |type| + last = type.inspection_records.for_aircraft(@aircraft).recent_first.first + res = Compliance.inspection_status(type, last, @hours, @today) + case res.rank + when Compliance::OVERDUE + if last + add("INSPECTION", RED, "#{type.name} - Overdue", "Inspection overdue.", type) + else + add("INSPECTION", RED, "#{type.name} - Never Completed", "Required inspection has no completion record.", type) + end + when Compliance::DUE_SOON + add("INSPECTION", ORANGE, "#{type.name} - Due Soon", "Inspection due soon.", type) + end + end + end + + def check_components + @aircraft.components.in_use.where(replacement_critical: true).includes(:component_type).find_each do |c| + overdue = false + approaching = false + desc = "" + + if c.replacement_hours + if c.hours_since_overhaul >= c.replacement_hours + overdue = true + desc = "Replace every #{c.replacement_hours} hrs. Current: #{c.hours_since_overhaul} hrs." + elsif c.hours_since_overhaul + HOURS_WARNING >= c.replacement_hours + approaching = true + desc = "Replace in #{c.replacement_hours - c.hours_since_overhaul} hrs." + end + end + + if (due = c.next_replacement_date) + if @today >= due + overdue = true + desc = "Replace every #{c.replacement_days} days. Last serviced #{c.overhaul_date}." + elsif @today + DAYS_WARNING >= due + approaching = true + desc = "Replace in #{(due - @today).to_i} days." + end + end + + if overdue + add("COMPONENT", RED, "#{c} - Replacement Overdue", desc, c) + elsif approaching + add("COMPONENT", ORANGE, "#{c} - Replacement Due Soon", desc, c) + end + end + end +end diff --git a/app/services/compliance.rb b/app/services/compliance.rb new file mode 100644 index 0000000..c771d2b --- /dev/null +++ b/app/services/compliance.rb @@ -0,0 +1,119 @@ +# Shared AD / inspection due-status math (port of ad_compliance_status / +# inspection_compliance_status from the original health/services.py). +module Compliance + COMPLIANT = 0 + DUE_SOON = 1 + OVERDUE = 2 + LABELS = %w[compliant due_soon overdue].freeze + + Result = Struct.new(:rank, :next_due_date, :next_due_hours, keyword_init: true) do + def label = LABELS[rank] + end + + module_function + + # Last day of the month `months` after `date` (FAA "end of month" convention). + def end_of_month_after(date, months) + (date >> months).end_of_month + end + + def ad_status(ad, compliance, current_hours, today = Date.current) + return Result.new(rank: COMPLIANT) if ad.conditional? + return Result.new(rank: OVERDUE) unless compliance + return Result.new(rank: COMPLIANT) if compliance.permanent? + + rank = COMPLIANT + result = Result.new + + due_hours = compliance.next_due_at_time.to_d + if due_hours > 0 + result.next_due_hours = due_hours + if current_hours >= due_hours + rank = OVERDUE + elsif current_hours + Airworthiness::HOURS_WARNING >= due_hours + rank = [ rank, DUE_SOON ].max + end + end + + if ad.recurring? && ad.recurring_months.positive? + due = end_of_month_after(compliance.date_complied, ad.recurring_months) + result.next_due_date = due + if today > due + rank = OVERDUE + elsif today + Airworthiness::DAYS_WARNING >= due + rank = [ rank, DUE_SOON ].max + end + end + + result.rank = rank + result + end + + def inspection_status(type, last_record, current_hours, today = Date.current) + return Result.new(rank: OVERDUE) unless last_record + return Result.new(rank: COMPLIANT) unless type.recurring? + + rank = COMPLIANT + result = Result.new + + if type.recurring_months.positive? || type.recurring_days.positive? + due = last_record.date + due = end_of_month_after(due, type.recurring_months) if type.recurring_months.positive? + due += type.recurring_days.days if type.recurring_days.positive? + result.next_due_date = due + if today > due + rank = OVERDUE + elsif today + Airworthiness::DAYS_WARNING >= due + rank = [ rank, DUE_SOON ].max + end + end + + interval = type.recurring_hours.to_d + if interval > 0 && (hours_at = last_record.hours_at_inspection) + since = current_hours - hours_at + result.next_due_hours = hours_at + interval + if since >= interval + rank = OVERDUE + elsif since + Airworthiness::HOURS_WARNING >= interval + rank = [ rank, DUE_SOON ].max + end + end + + result.rank = rank + result + end + + # Rows for the ADs tab: every applicable AD with its latest compliance and status. + AdRow = Struct.new(:ad, :latest, :status, :next_due_date, :next_due_hours, keyword_init: true) + + def ad_rows(aircraft) + hours = aircraft.current_hours + aircraft.applicable_ads.ordered.map do |ad| + latest = ad.latest_compliance_for(aircraft) + status = + if ad.conditional? then latest ? "compliant" : "conditional" + elsif latest.nil? then "no_compliance" + elsif latest.permanent? then "compliant" + end + res = ad_status(ad, latest, hours) unless status + AdRow.new(ad: ad, latest: latest, status: status || res.label, + next_due_date: res&.next_due_date, next_due_hours: res&.next_due_hours) + end + end + + InspectionRow = Struct.new(:type, :latest, :status, :next_due_date, :next_due_hours, keyword_init: true) + + def inspection_rows(aircraft) + hours = aircraft.current_hours + aircraft.applicable_inspection_types.ordered.map do |type| + latest = type.inspection_records.for_aircraft(aircraft).recent_first.first + if latest.nil? + InspectionRow.new(type: type, latest: nil, status: "never_completed") + else + res = inspection_status(type, latest, hours) + InspectionRow.new(type: type, latest: latest, status: res.label, + next_due_date: res.next_due_date, next_due_hours: res.next_due_hours) + end + end + end +end diff --git a/app/services/consumption_stats.rb b/app/services/consumption_stats.rb new file mode 100644 index 0000000..ba71009 --- /dev/null +++ b/app/services/consumption_stats.rb @@ -0,0 +1,58 @@ +# Oil/fuel consumption: per-interval datapoints between consecutive records +# (sorted by flight hours), averaged over the last 20 with IQR outliers and +# excluded records left out. Oil → hours per quart; fuel → gallons per hour. +class ConsumptionStats + WINDOW = 20 + Point = Struct.new(:record, :hours, :value, :excluded, :outlier, keyword_init: true) + + attr_reader :record_type, :records + + def initialize(aircraft, record_type) + @record_type = record_type + @records = aircraft.consumable_records.where(record_type: record_type).order(:flight_hours, :date).to_a + end + + def oil? = record_type == "oil" + def metric_label = oil? ? "hrs/qt" : "gal/hr" + + def points + @points ||= begin + pts = @records.each_cons(2).filter_map do |prev, cur| + dh = (cur.flight_hours - prev.flight_hours).to_f + qty = cur.quantity_added.to_f + next unless qty > 0 && dh > 0 + Point.new(record: cur, hours: cur.flight_hours.to_f, value: oil? ? dh / qty : qty / dh, + excluded: cur.excluded_from_averages?) + end + bounds = iqr_bounds(pts.map(&:value)) + pts.each { |p| p.outlier = bounds && !(bounds[0]..bounds[1]).cover?(p.value) } + end + end + + def average + window = points.last(WINDOW) + return nil if window.empty? + included = window.reject { |p| p.excluded || p.outlier } + source = included.presence || window + (source.sum(&:value) / source.size).round(1) + end + + def latest = points.last&.value&.round(1) + + def chart_data + points.map { |p| [ p.hours.round(1), p.value.round(2) ] } + end + + private + + def iqr_bounds(values) + return nil if values.size < 5 + nums = values.sort + n = nums.size + q1 = nums[n / 4] + q3 = nums[(3 * n) / 4] + iqr = q3 - q1 + return nil if iqr.zero? + [ q1 - 1.5 * iqr, q3 + 1.5 * iqr ] + end +end diff --git a/app/services/hours_service.rb b/app/services/hours_service.rb new file mode 100644 index 0000000..188c1c8 --- /dev/null +++ b/app/services/hours_service.rb @@ -0,0 +1,75 @@ +# Flight-activity writes: absolute hours updates and flight logs. Both cascade +# the tach delta to every IN-USE component. +class HoursService + def initialize(aircraft, user: Current.user) + @aircraft = aircraft + @user = user + end + + def enforce_airworthiness! + return unless @aircraft.airworthiness_enforcement? + status = Airworthiness.new(@aircraft).call + raise AircraftGroundedError, status if status.red? + end + + # Set absolute tach (and optional hobbs); component hours are clamped at 0 + # so downward corrections can't go negative. + def update_hours!(tach_time:, hobbs_time: nil) + enforce_airworthiness! + tach = BigDecimal(tach_time.to_s) + delta = tach - @aircraft.tach_time + old = @aircraft.tach_time + + Aircraft.transaction do + @aircraft.tach_time = tach + @aircraft.hobbs_time = BigDecimal(hobbs_time.to_s) if hobbs_time.present? + @aircraft.save! + cascade_to_components(delta, clamp: true) + @aircraft.log_event!("hours", + "Hours #{delta >= 0 ? 'updated' : 'corrected'} to #{tach}", + user: @user, notes: "Previous: #{old}, delta: #{delta >= 0 ? '+' : ''}#{delta}") + end + delta + end + + # Persist a flight log and apply its side effects atomically. + def log_flight!(flight) + enforce_airworthiness! + Aircraft.transaction do + flight.aircraft = @aircraft + flight.user ||= @user + flight.save! + + @aircraft.tach_time += flight.tach_time + @aircraft.hobbs_time += flight.hobbs_time if flight.hobbs_time + @aircraft.save! + cascade_to_components(flight.tach_time) + + { "oil" => [ flight.oil_added, flight.oil_level_after, flight.oil_added_type ], + "fuel" => [ flight.fuel_added, flight.fuel_level_after, flight.fuel_added_type ] }.each do |type, (qty, level, kind)| + next unless qty.to_f > 0 + @aircraft.consumable_records.create!( + record_type: type, flight_log: flight, date: flight.date, quantity_added: qty, + level_after: level, consumable_type: kind, flight_hours: @aircraft.tach_time, + notes: "Auto-created from flight log") + @aircraft.log_event!(type, "#{type.capitalize} added: #{qty} #{ConsumableRecord::UNITS[type]}", + user: @user, notes: "From flight log") + end + + route = flight.route_summary.presence + @aircraft.log_event!("flight", "Flight logged: #{flight.tach_time} hrs#{" (#{route})" if route}", user: @user) + end + flight + end + + private + + def cascade_to_components(delta, clamp: false) + @aircraft.components.in_use.find_each do |c| + his = c.hours_in_service + delta + hso = c.hours_since_overhaul + delta + his, hso = [ his, 0 ].max, [ hso, 0 ].max if clamp + c.update_columns(hours_in_service: his, hours_since_overhaul: hso, updated_at: Time.current) + end + end +end diff --git a/app/views/ad_compliances/_form.html.erb b/app/views/ad_compliances/_form.html.erb new file mode 100644 index 0000000..d9e462b --- /dev/null +++ b/app/views/ad_compliances/_form.html.erb @@ -0,0 +1,15 @@ +<%= form_with model: compliance, url: compliance.new_record? ? aircraft_ad_compliances_path(aircraft) : aircraft_ad_compliance_path(aircraft, compliance), class: "card card-body space-y-4 max-w-2xl" do |f| %> + <%= f.errors_summary %> + <%= f.field :airworthiness_directive_id, as: :select, label: "AD", collection: aircraft.applicable_ads.ordered.map { ["#{_1.name} – #{_1.short_description.truncate(50)}", _1.id] } %> +
+ <%= f.field :date_complied, as: :date %> + <%= f.field :aircraft_hours_at_compliance, as: :number, step: 0.1, label: "Aircraft hours (tach)" %> + <%= f.field :next_due_at_time, as: :number, step: 0.1, label: "Next due at (tach hours)", hint: "0 = no hour-based recurrence." %> + <%= f.field :component_id, as: :select, label: "Component", collection: component_options(aircraft) %> + <%= f.field :logbook_entry_id, as: :select, label: "Logbook entry", collection: logbook_options(aircraft) %> +
+ <%= f.field :permanent, as: :checkbox, label: "Permanently complied (terminating action)" %> + <%= f.field :compliance_notes, as: :textarea, label: "Method of compliance", rows: 3, required: true %> +
<%= f.submit "Save" %><%= link_to "Cancel", aircraft_airworthiness_directives_path(aircraft), class: "btn-secondary" %>
+<% end %> +<% if compliance.persisted? %>
<%= delete_button "Delete record", aircraft_ad_compliance_path(aircraft, compliance) %>
<% end %> diff --git a/app/views/ad_compliances/edit.html.erb b/app/views/ad_compliances/edit.html.erb new file mode 100644 index 0000000..a5a02f1 --- /dev/null +++ b/app/views/ad_compliances/edit.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, compliance: @compliance %> diff --git a/app/views/ad_compliances/new.html.erb b/app/views/ad_compliances/new.html.erb new file mode 100644 index 0000000..a5a02f1 --- /dev/null +++ b/app/views/ad_compliances/new.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, compliance: @compliance %> diff --git a/app/views/admin/component_types/_form.html.erb b/app/views/admin/component_types/_form.html.erb new file mode 100644 index 0000000..f7e2281 --- /dev/null +++ b/app/views/admin/component_types/_form.html.erb @@ -0,0 +1,7 @@ +<%= form_with model: [:admin, component_type], class: "card card-body space-y-4 max-w-md" do |f| %> + <%= f.errors_summary %> + <%= f.field :name, required: true %> + <%= f.field :consumable, as: :checkbox, label: "Consumable (oil filter, spark plugs…)" %> +
<%= f.submit "Save" %><%= link_to "Cancel", admin_component_types_path, class: "btn-secondary" %>
+<% end %> +<% if component_type.persisted? %>
<%= delete_button "Delete type", admin_component_type_path(component_type) %>
<% end %> diff --git a/app/views/admin/component_types/edit.html.erb b/app/views/admin/component_types/edit.html.erb new file mode 100644 index 0000000..ad83fe9 --- /dev/null +++ b/app/views/admin/component_types/edit.html.erb @@ -0,0 +1,2 @@ +

Edit Component Type

+<%= render "form", component_type: @component_type %> diff --git a/app/views/admin/component_types/index.html.erb b/app/views/admin/component_types/index.html.erb new file mode 100644 index 0000000..8c25540 --- /dev/null +++ b/app/views/admin/component_types/index.html.erb @@ -0,0 +1,7 @@ +<% content_for :title, "Component Types" %> +

Component Types

<%= link_to "+ New Type", new_admin_component_type_path, class: "btn-primary" %>
+
+ + <% @component_types.each do |t| %> + <% end %> +
NameConsumable
<%= t.name %><%= "Yes" if t.consumable? %><%= link_to "Edit", edit_admin_component_type_path(t), class: "btn-secondary btn-sm" %>
diff --git a/app/views/admin/component_types/new.html.erb b/app/views/admin/component_types/new.html.erb new file mode 100644 index 0000000..4a09a8e --- /dev/null +++ b/app/views/admin/component_types/new.html.erb @@ -0,0 +1,2 @@ +

New Component Type

+<%= render "form", component_type: @component_type %> diff --git a/app/views/admin/users/_form.html.erb b/app/views/admin/users/_form.html.erb new file mode 100644 index 0000000..833ecef --- /dev/null +++ b/app/views/admin/users/_form.html.erb @@ -0,0 +1,10 @@ +<%= form_with model: [:admin, user], class: "card card-body space-y-4 max-w-md" do |f| %> + <%= f.errors_summary %> + <%= f.field :name %> + <%= f.field :email_address, as: :email, label: "Email", required: true %> + <%= f.field :password, as: :password, hint: (user.persisted? ? "Leave blank to keep current password." : "At least 8 characters."), autocomplete: "new-password" %> + <%= f.field :password_confirmation, as: :password %> + <%= f.field :admin, as: :checkbox, label: "Administrator", hint: "Admins can see and edit every aircraft and manage users." %> +
<%= f.submit "Save" %><%= link_to "Cancel", admin_users_path, class: "btn-secondary" %>
+<% end %> +<% if user.persisted? && user != current_user %>
<%= delete_button "Delete user", admin_user_path(user) %>
<% end %> diff --git a/app/views/admin/users/edit.html.erb b/app/views/admin/users/edit.html.erb new file mode 100644 index 0000000..701280d --- /dev/null +++ b/app/views/admin/users/edit.html.erb @@ -0,0 +1,2 @@ +

Edit User

+<%= render "form", user: @user %> diff --git a/app/views/admin/users/index.html.erb b/app/views/admin/users/index.html.erb new file mode 100644 index 0000000..b02b858 --- /dev/null +++ b/app/views/admin/users/index.html.erb @@ -0,0 +1,12 @@ +<% content_for :title, "Users" %> +

Users

<%= link_to "+ New User", new_admin_user_path, class: "btn-primary" %>
+
+ + <% @users.each do |u| %> + + + + + <% end %> +
NameEmailAircraft
<%= u.name %> <% if u.admin? %>Admin<% end %><%= u.email_address %><%= u.aircraft_roles.map { "#{_1.aircraft.tail_number} (#{_1.role})" }.join(", ").presence || "—" %><%= link_to "Edit", edit_admin_user_path(u), class: "btn-secondary btn-sm" %>
+

After creating an account, an aircraft owner can grant access from the aircraft's “Access & Sharing” tab.

diff --git a/app/views/admin/users/new.html.erb b/app/views/admin/users/new.html.erb new file mode 100644 index 0000000..a059316 --- /dev/null +++ b/app/views/admin/users/new.html.erb @@ -0,0 +1,2 @@ +

New User

+<%= render "form", user: @user %> diff --git a/app/views/aircraft/_form.html.erb b/app/views/aircraft/_form.html.erb new file mode 100644 index 0000000..46f7a27 --- /dev/null +++ b/app/views/aircraft/_form.html.erb @@ -0,0 +1,30 @@ +<%= form_with model: aircraft, class: "card card-body space-y-4 max-w-3xl" do |f| %> + <%= f.errors_summary %> +
+ <%= f.field :tail_number, required: true, autofocus: true %> + <%= f.field :make %> + <%= f.field :model %> + <%= f.field :serial_number %> + <%= f.field :purchased, as: :date %> + <%= f.field :status, as: :select, collection: Aircraft::STATUSES.invert %> +
+ <%= f.field :description, as: :textarea, rows: 3 %> +
+ <% if aircraft.new_record? %> + <%= f.field :tach_time, as: :number, step: 0.1, label: "Current tach" %> + <%= f.field :hobbs_time, as: :number, step: 0.1, label: "Current hobbs" %> + <% end %> + <%= f.field :tach_time_offset, as: :number, step: 0.1, hint: "Subtracted from tach for compliance math (e.g. after a tach replacement)." %> + <%= f.field :hobbs_time_offset, as: :number, step: 0.1 %> +
+ <% unless aircraft.new_record? %> +

To change hours use “Update Hours” on the overview, so component times stay in sync.

+ <% end %> + <%= f.field :picture, as: :file, accept: "image/*" %> + <%= f.field :airworthiness_enforcement, as: :checkbox, label: "Enforce airworthiness", + hint: "Block flight logs and hours updates while the aircraft is red." %> +
+ <%= f.submit aircraft.new_record? ? "Add Aircraft" : "Save" %> + <%= link_to "Cancel", aircraft.new_record? ? root_path : aircraft_path(aircraft), class: "btn-secondary" %> +
+<% end %> diff --git a/app/views/aircraft/edit.html.erb b/app/views/aircraft/edit.html.erb new file mode 100644 index 0000000..a22dc15 --- /dev/null +++ b/app/views/aircraft/edit.html.erb @@ -0,0 +1,9 @@ +<% content_for :title, "Edit #{@aircraft.tail_number}" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft %> +
+

Danger zone

+

Deleting an aircraft removes all of its records, documents and history.

+ <%= delete_button "Delete #{@aircraft.tail_number}", aircraft_path(@aircraft), + confirm: "Delete #{@aircraft.tail_number} and ALL its records? This cannot be undone.", class: "btn-danger" %> +
diff --git a/app/views/aircraft/index.html.erb b/app/views/aircraft/index.html.erb new file mode 100644 index 0000000..f911652 --- /dev/null +++ b/app/views/aircraft/index.html.erb @@ -0,0 +1,48 @@ +<% content_for :title, "Fleet" %> +
+

Fleet

+ <%= link_to "+ Add Aircraft", new_aircraft_path, class: "btn-primary" %> +
+ +<% if @aircraft_list.empty? %> +
+

No aircraft yet.

+

<%= link_to "Add your first aircraft", new_aircraft_path, class: "btn-primary" %>

+
+<% else %> +
+ <% @aircraft_list.each do |aircraft| %> + <% aw = aircraft.airworthiness %> + <%= link_to aircraft_path(aircraft), class: "card block overflow-hidden transition hover:shadow-md" do %> +
+ <% if aircraft.picture.attached? %> + <%= image_tag aircraft.picture, class: "h-full w-full object-cover" %> + <% else %> + ✈ + <% end %> +
+
+
+
+
<%= aircraft.tail_number %>
+
<%= [aircraft.make, aircraft.model].compact_blank.join(" ").presence || "—" %>
+
+ <%= airworthiness_badge(aw) %> +
+
+ Tach <%= hours(aircraft.tach_time) %> + <%= aircraft_status_badge(aircraft) %> +
+ <% if aw.issues.any? %> +
    + <% aw.issues.first(3).each do |issue| %> +
  • • <%= issue.title %>
  • + <% end %> + <% if aw.issues.size > 3 %>
  • + <%= aw.issues.size - 3 %> more
  • <% end %> +
+ <% end %> +
+ <% end %> + <% end %> +
+<% end %> diff --git a/app/views/aircraft/new.html.erb b/app/views/aircraft/new.html.erb new file mode 100644 index 0000000..1019148 --- /dev/null +++ b/app/views/aircraft/new.html.erb @@ -0,0 +1,3 @@ +<% content_for :title, "Add Aircraft" %> +

Add Aircraft

+<%= render "form", aircraft: @aircraft %> diff --git a/app/views/aircraft/show.html.erb b/app/views/aircraft/show.html.erb new file mode 100644 index 0000000..9004e60 --- /dev/null +++ b/app/views/aircraft/show.html.erb @@ -0,0 +1,109 @@ +<% content_for :title, @aircraft.tail_number %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> + +
+
+
+
+

Airworthiness

+ <%= airworthiness_badge(@airworthiness, large: true) %> +
+
+ <% if @airworthiness.issues.empty? %> +

No open issues. All tracked ADs, inspections, components and squawks are current.

+ <% else %> +
    + <% @airworthiness.issues.each do |issue| %> +
  • + <%= issue.category %> +
    +
    <%= issue.title %>
    +
    <%= issue.description %>
    +
    +
  • + <% end %> +
+ <% end %> + <% if @aircraft.airworthiness_enforcement? %> +

Airworthiness enforcement is on: flights and hours updates are blocked while the status is red.

+ <% end %> +
+
+ +
+
+

Active Squawks

+ <%= link_to "All squawks →", aircraft_squawks_path(@aircraft), class: "link text-sm" %> +
+ <% if @active_squawks.any? %> + <%= render "squawks/table", squawks: @active_squawks, aircraft: @aircraft %> + <% else %> + <%= empty_state "No open squawks." %> + <% end %> +
+ +
+

Consumption

+ <%= link_to "Oil & fuel →", aircraft_consumable_records_path(@aircraft), class: "link text-sm" %>
+
+
<%= @oil.average || "—" %>
Avg oil, hrs/qt
+
<%= @fuel.average || "—" %>
Avg fuel burn, gal/hr
+
+
+
+ +
+
+

Update Hours

+ <%= form_with url: hours_aircraft_path(@aircraft), method: :patch, class: "card-body space-y-3" do |f| %> +
+
<%= f.label :tach_time, "Tach", class: "label" %> + <%= f.number_field :tach_time, value: @aircraft.tach_time, step: 0.1, class: "input", required: true %>
+
<%= f.label :hobbs_time, "Hobbs", class: "label" %> + <%= f.number_field :hobbs_time, value: @aircraft.hobbs_time, step: 0.1, class: "input" %>
+
+

Enter the current meter readings. The difference is applied to every in-service component. For a single flight, use <%= link_to "Log Flight", new_aircraft_flight_log_path(@aircraft), class: "link" %>.

+ <%= f.submit "Update Hours", class: "btn-primary" %> + <% end %> +
+ +
+
+

Details

+ <% if owner? %><%= link_to "Edit", edit_aircraft_path(@aircraft), class: "btn-secondary btn-sm" %><% end %> +
+
+
Serial
<%= @aircraft.serial_number.presence || "—" %>
+
Purchased
<%= fmt_date(@aircraft.purchased) %>
+
Tach offset
<%= hours(@aircraft.tach_time_offset) %>
+
Hobbs offset
<%= hours(@aircraft.hobbs_time_offset) %>
+
+ <% if @aircraft.description.present? %> +

<%= simple_format @aircraft.description %>

+ <% end %> +
+ +
+

Notes

+ <%= link_to "+ Add", new_aircraft_note_path(@aircraft), class: "btn-secondary btn-sm" %>
+ <% if @notes.any? %> +
    + <% @notes.each do |note| %> +
  • +
    <%= note.text.truncate(200) %>
    +
    <%= note.user&.display_name %> · <%= time_ago_in_words(note.created_at) %> ago <%= "· public" if note.public? %>
    +
  • + <% end %> +
+ <% else %> + <%= empty_state "No notes." %> + <% end %> +
+ +
+

Recent Activity

+ <%= link_to "All →", aircraft_events_path(@aircraft), class: "link text-sm" %>
+ <%= render "events/list", events: @recent_events %> +
+
+
diff --git a/app/views/aircraft_roles/index.html.erb b/app/views/aircraft_roles/index.html.erb new file mode 100644 index 0000000..376e501 --- /dev/null +++ b/app/views/aircraft_roles/index.html.erb @@ -0,0 +1,61 @@ +<% content_for :title, "#{@aircraft.tail_number} Access" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
+
+

People

+ + + <% @roles.each do |r| %> + + + + + + <% end %> + +
<%= r.user.display_name %>
<%= r.user.email_address %>
+ <%= form_with url: aircraft_aircraft_role_path(@aircraft, r), method: :patch do |f| %> + <%= f.select :role, AircraftRole::ROLES.invert, { selected: r.role }, class: "input w-28", onchange: "this.form.requestSubmit()" %> + <% end %> + <% unless r.user == current_user %><%= delete_button "Remove", aircraft_aircraft_role_path(@aircraft, r), confirm: "Remove #{r.user.display_name}'s access?" %><% end %>
+ <%= form_with url: aircraft_aircraft_roles_path(@aircraft), class: "flex flex-wrap items-end gap-2 border-t border-slate-100 p-4" do |f| %> +
<%= f.label :email_address, "Add by email", class: "label" %><%= f.email_field :email_address, class: "input", required: true %>
+ <%= f.select :role, AircraftRole::ROLES.invert, { selected: "pilot" }, class: "input w-28" %> + <%= f.submit "Add", class: "btn-primary" %> + <% end %> +

Owners can edit everything. Pilots can view all records, log flights, update hours, and add squawks, notes and oil/fuel.

+
+ +
+

Share Links

+ <% if @share_tokens.any? %> +
    + <% @share_tokens.each do |t| %> +
  • +
    +
    + <%= t.label.presence || "Untitled link" %> + <%= tag.span ShareToken::PRIVILEGES[t.privilege], class: t.maintenance? ? "badge-blue" : "badge-green" %> + <% if t.expired? %>Expired<% end %> +
    + <%= delete_button "Revoke", aircraft_share_token_path(@aircraft, t), confirm: "Revoke this link? Anyone using it will lose access." %> +
    + +
    Created <%= t.created_at.to_date %><%= " by #{t.created_by.display_name}" if t.created_by %> · <%= t.expires_at ? "expires #{l t.expires_at, format: :short}" : "never expires" %>
    +
  • + <% end %> +
+ <% else %> + <%= empty_state "No share links." %> + <% end %> + <%= form_with model: ShareToken.new, url: aircraft_share_tokens_path(@aircraft), class: "space-y-3 border-t border-slate-100 p-4" do |f| %> +
+ <%= f.field :label, placeholder: "Mechanic, buyer…" %> + <%= f.field :privilege, as: :select, label: "Shows", collection: ShareToken::PRIVILEGES.invert %> + <%= f.field :expires_at, as: :datetime, label: "Expires (optional)" %> +
+

Current Status: overview, airworthiness, components, open squawks, AD/inspection status, oil & fuel, public notes and documents shared with all links. Maintenance Detail adds the full logbook, history, resolved squawks and major records.

+ <%= f.submit "Create Share Link" %> + <% end %> +
+
diff --git a/app/views/airworthiness_directives/_form.html.erb b/app/views/airworthiness_directives/_form.html.erb new file mode 100644 index 0000000..649382f --- /dev/null +++ b/app/views/airworthiness_directives/_form.html.erb @@ -0,0 +1,27 @@ +<%= form_with model: ad, url: ad.new_record? ? aircraft_airworthiness_directives_path(aircraft) : aircraft_airworthiness_directive_path(aircraft, ad), class: "card card-body space-y-4 max-w-3xl" do |f| %> + <%= f.errors_summary %> +
+ <%= f.field :name, label: "Number", required: true, placeholder: "2011-10-09" %> + <%= f.field :bulletin_type, as: :select, label: "Type", collection: AirworthinessDirective::BULLETIN_TYPES.invert %> + <%= f.field :compliance_type, as: :select, label: "Compliance", collection: AirworthinessDirective::COMPLIANCE_TYPES.invert, + hint: "Conditional ADs only apply when a trigger occurs and don't affect airworthiness." %> +
+ <%= f.field :short_description, required: true %> + <%= f.field :required_action, as: :textarea, rows: 3 %> + <%= f.field :trigger_condition, as: :textarea, rows: 2, hint: "For conditional ADs (e.g. “on prop strike”)." %> +
+ <%= f.field :mandatory, as: :checkbox, label: "Mandatory" %> + <%= f.field :recurring, as: :checkbox, label: "Recurring" %> +
+
+ <%= f.field :recurring_hours, as: :number, step: 0.1, label: "Every (hours)" %> + <%= f.field :recurring_months, as: :number, label: "Every (months)" %> + <%= f.field :document_id, as: :select, label: "Reference document", collection: document_options(aircraft) %> +
+ <%= render "shared/applicability_fields", aircraft: aircraft, record: ad, applies_to_airframe: @applies_to_airframe %> + <% if ad.persisted? && (ad.aircraft.count + ad.components.where.not(aircraft_id: aircraft.id).count) > 1 %> +

This AD is shared with other aircraft; edits affect them too.

+ <% end %> +
<%= f.submit "Save" %><%= link_to "Cancel", aircraft_airworthiness_directives_path(aircraft), class: "btn-secondary" %>
+<% end %> +<% if ad.persisted? %>
<%= delete_button "Remove from #{aircraft.tail_number}", aircraft_airworthiness_directive_path(aircraft, ad) %>
<% end %> diff --git a/app/views/airworthiness_directives/edit.html.erb b/app/views/airworthiness_directives/edit.html.erb new file mode 100644 index 0000000..bca24ad --- /dev/null +++ b/app/views/airworthiness_directives/edit.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, ad: @ad %> diff --git a/app/views/airworthiness_directives/index.html.erb b/app/views/airworthiness_directives/index.html.erb new file mode 100644 index 0000000..661bb40 --- /dev/null +++ b/app/views/airworthiness_directives/index.html.erb @@ -0,0 +1,70 @@ +<% content_for :title, "#{@aircraft.tail_number} ADs" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
+
+

Airworthiness Directives & Bulletins

+ <% if owner? %> +
+ <% if @attachable.any? %> + <%= form_with url: attach_aircraft_airworthiness_directives_path(@aircraft), class: "flex gap-2" do |f| %> + <%= f.select :airworthiness_directive_id, @attachable.map { ["#{_1.name} – #{_1.short_description.truncate(40)}", _1.id] }, {}, class: "input w-64" %> + <%= f.submit "Link existing", class: "btn-secondary" %> + <% end %> + <% end %> + <%= link_to "+ New AD", new_aircraft_airworthiness_directive_path(@aircraft), class: "btn-primary" %> +
+ <% end %> +
+ <% if @rows.any? %> +
+ + + + <% @rows.each do |row| ad = row.ad %> + + + + + + + + + + <% end %> + +
AD / BulletinDescriptionRecurrenceLast compliedNext dueStatus
<%= ad.bulletin_label %><%= ad.name %> + <% unless ad.mandatory? %>
not mandatory
<% end %>
<%= ad.short_description %> + <% if ad.conditional? && ad.trigger_condition.present? %>
Trigger: <%= ad.trigger_condition %>
<% end %>
<%= ad.recurring? ? [ad.recurring_hours.to_f > 0 && "#{hours(ad.recurring_hours)} h", ad.recurring_months > 0 && "#{ad.recurring_months} mo"].select(&:itself).join(" / ") : "One-time" %><%= row.latest ? "#{row.latest.date_complied}#{' (permanent)' if row.latest.permanent?}" : "—" %><%= [row.next_due_date&.strftime("%b %Y"), row.next_due_hours && "#{hours(row.next_due_hours)} h"].compact.join(" / ").presence || "—" %><%= compliance_badge(row.status) %> + <% if owner? %> + <%= link_to "Comply", new_aircraft_ad_compliance_path(@aircraft, ad_id: ad.id), class: "btn-secondary btn-sm" %> + <%= link_to "Edit", edit_aircraft_airworthiness_directive_path(@aircraft, ad), class: "btn-secondary btn-sm" %> + <% end %> +
+
+ <% else %> + <%= empty_state "No ADs tracked for this aircraft." %> + <% end %> +
+ +
+

Compliance History

+ <% if @history.any? %> + + + + <% @history.each do |c| %> + + + + + + + + + <% end %> + +
DateADHoursNext due (hrs)Notes
<%= c.date_complied %><%= c.airworthiness_directive.name %><%= " (#{c.component})" if c.component %><%= hours(c.aircraft_hours_at_compliance) %><%= c.permanent? ? "Permanent" : (c.next_due_at_time.to_f > 0 ? hours(c.next_due_at_time) : "—") %><%= c.compliance_notes %><% if owner? %><%= link_to "Edit", edit_aircraft_ad_compliance_path(@aircraft, c), class: "btn-secondary btn-sm" %><% end %>
+ <% else %> + <%= empty_state "No compliance records." %> + <% end %> +
diff --git a/app/views/airworthiness_directives/new.html.erb b/app/views/airworthiness_directives/new.html.erb new file mode 100644 index 0000000..bca24ad --- /dev/null +++ b/app/views/airworthiness_directives/new.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, ad: @ad %> diff --git a/app/views/components/_form.html.erb b/app/views/components/_form.html.erb new file mode 100644 index 0000000..54e04d5 --- /dev/null +++ b/app/views/components/_form.html.erb @@ -0,0 +1,50 @@ +<%= form_with model: [aircraft, component], class: "card card-body space-y-5 max-w-4xl" do |f| %> + <%= f.errors_summary %> +
+
+ <%= f.field :component_type_id, as: :select, label: "Type", + collection: ComponentType.ordered.map { [_1.name, _1.id] }, include_blank: "— Select —" %> + <%= text_field_tag :new_component_type, params[:new_component_type], class: "input mt-2", placeholder: "…or type a new one" %> +
+ <%= f.field :manufacturer, required: true %> + <%= f.field :model, required: true %> + <%= f.field :serial_number %> + <%= f.field :install_location, hint: "e.g. Left mag, #3 cylinder" %> + <%= f.field :status, as: :select, collection: Component::STATUSES.invert %> + <%= f.field :parent_component_id, as: :select, label: "Parent component", + collection: [["— None —", nil]] + aircraft.components.where.not(id: component.id).includes(:component_type).map { [_1.to_s, _1.id] } %> +
+ +
+ Time + <%= f.field :date_in_service, as: :date, required: true %> + <%= f.field :hours_in_service, as: :number, step: 0.1 %> + <%= f.field :overhaul_date, as: :date, label: "Last overhaul / service" %> + <%= f.field :hours_since_overhaul, as: :number, step: 0.1, label: "Hours since OH / service" %> +
+ +
+ Limits + <%= f.field :replacement_hours, as: :number, label: "Replace every (hrs)" %> + <%= f.field :replacement_days, as: :number, label: "Replace every (days)" %> + <%= f.field :replacement_critical, as: :checkbox, label: "Replacement critical", hint: "Overdue replacement grounds the aircraft (oil, filters, ELT battery…)." %> + <%= f.field :tbo_hours, as: :number, label: "TBO (hrs)" %> + <%= f.field :tbo_days, as: :number, label: "TBO (days)" %> +
+ <%= f.field :tbo_critical, as: :checkbox, label: "TBO critical" %> + <%= f.field :on_condition, as: :checkbox, label: "On condition (Part 91)" %> +
+ <%= f.field :inspection_hours, as: :number, label: "Inspect every (hrs)" %> + <%= f.field :inspection_days, as: :number, label: "Inspect every (days)" %> + <%= f.field :inspection_critical, as: :checkbox, label: "Inspection critical" %> +
+ + <%= f.field :notes, as: :textarea, rows: 3 %> +
+ <%= f.submit component.new_record? ? "Add Component" : "Save" %> + <%= link_to "Cancel", aircraft_components_path(aircraft), class: "btn-secondary" %> +
+<% end %> +<% if component.persisted? %> +
<%= delete_button "Delete component", aircraft_component_path(aircraft, component), confirm: "Delete #{component} and its sub-components?" %>
+<% end %> diff --git a/app/views/components/edit.html.erb b/app/views/components/edit.html.erb new file mode 100644 index 0000000..e9ce0ce --- /dev/null +++ b/app/views/components/edit.html.erb @@ -0,0 +1,3 @@ +<% content_for :title, "Edit Component" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, component: @component %> diff --git a/app/views/components/index.html.erb b/app/views/components/index.html.erb new file mode 100644 index 0000000..48dd016 --- /dev/null +++ b/app/views/components/index.html.erb @@ -0,0 +1,52 @@ +<% content_for :title, "#{@aircraft.tail_number} Components" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
+
+

Components

+
+ <%= link_to (@show_disposed ? "Hide disposed" : "Show disposed"), + aircraft_components_path(@aircraft, disposed: (@show_disposed ? nil : 1)), class: "link text-sm" %> + <% if owner? %><%= link_to "+ Add Component", new_aircraft_component_path(@aircraft), class: "btn-primary" %><% end %> +
+
+ <% if @rows.empty? %> + <%= empty_state "No components yet. Add the engine, propeller, oil filter, ELT battery, etc." %> + <% else %> +
+ + + + + + + + <% @rows.each do |c, depth| %> + + + + + + + + + + + <% end %> + +
ComponentMake / ModelStatusIn serviceSince OH/svcLimitLife
+ <%= "↳ " if depth > 0 %><%= link_to c.component_type.name, aircraft_component_path(@aircraft, c), class: "link font-medium" %> + <% if c.install_location.present? %>
<%= c.install_location %>
<% end %> +
<%= c.manufacturer %> <%= c.model %><% if c.serial_number.present? %>
S/N <%= c.serial_number %>
<% end %>
<%= tag.span c.status_label, class: { "IN-USE" => "badge-green", "SPARE" => "badge-gray", "DISPOSED" => "badge-gray" }[c.status] %><%= hours(c.hours_in_service) %><%= hours(c.hours_since_overhaul) %> + <% if c.replacement_critical? && (c.replacement_hours || c.replacement_days) %> + Replace: <%= [c.replacement_hours && "#{c.replacement_hours} h", c.replacement_days && "#{c.replacement_days} d"].compact.join(" / ") %>
+ <% end %> + <% if c.tbo_critical? && c.tbo_hours %>TBO: <%= c.tbo_hours %> h<%= " (on condition)" if c.on_condition? %><% end %> +
<%= life_badge(c.life_status) %> + <% if owner? %> + <%= link_to "Edit", edit_aircraft_component_path(@aircraft, c), class: "btn-secondary btn-sm" %> + <%= link_to "Service", aircraft_component_path(@aircraft, c, anchor: "service"), class: "btn-secondary btn-sm" %> + <% end %> +
+
+ <% end %> +
diff --git a/app/views/components/new.html.erb b/app/views/components/new.html.erb new file mode 100644 index 0000000..c2b37c9 --- /dev/null +++ b/app/views/components/new.html.erb @@ -0,0 +1,3 @@ +<% content_for :title, "Add Component" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, component: @component %> diff --git a/app/views/components/show.html.erb b/app/views/components/show.html.erb new file mode 100644 index 0000000..c169a15 --- /dev/null +++ b/app/views/components/show.html.erb @@ -0,0 +1,61 @@ +<% content_for :title, @component.to_s %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
+
+
+

<%= @component %> <%= life_badge(@component.life_status) %>

+ <% if owner? %> +
+ <%= link_to "+ Sub-component", new_aircraft_component_path(@aircraft, parent_id: @component.id), class: "btn-secondary btn-sm" %> + <%= link_to "Edit", edit_aircraft_component_path(@aircraft, @component), class: "btn-secondary btn-sm" %> +
+ <% end %> +
+
+
Manufacturer
<%= @component.manufacturer %>
+
Model
<%= @component.model %>
+
Serial
<%= @component.serial_number.presence || "—" %>
+
Status
<%= @component.status_label %>
+
Parent
<%= @component.parent_component ? link_to(@component.parent_component, aircraft_component_path(@aircraft, @component.parent_component), class: "link") : "—" %>
+
Location
<%= @component.install_location.presence || "—" %>
+
In service since
<%= fmt_date(@component.date_in_service) %>
+
Last OH / service
<%= fmt_date(@component.overhaul_date) %>
+
Hours in service
<%= hours(@component.hours_in_service) %>
+
Since OH / service
<%= hours(@component.hours_since_overhaul) %>
+
TBO
<%= @component.tbo_hours ? "#{@component.tbo_hours} h (#{hours(@component.hours_to_tbo)} remaining)" : "—" %>
+
Replacement
+ <%= [@component.replacement_hours && "#{@component.replacement_hours} h", @component.replacement_days && "#{@component.replacement_days} d"].compact.join(" / ").presence || "—" %> + <% if (d = @component.next_replacement_date) %>
Next by <%= fmt_date(d) %>
<% end %> +
+
Flags
+
+ <% { tbo_critical: "TBO critical", replacement_critical: "Replacement critical", inspection_critical: "Inspection critical", on_condition: "On condition" }.each do |flag, label| %> + <% if @component.public_send("#{flag}?") %><%= label %><% end %> + <% end %> +
+
+ <% if @component.notes.present? %>
<%= simple_format @component.notes %>
<% end %> +
+ + <% if owner? %> +
+

Service / Replace

+ <%= form_with url: reset_service_aircraft_component_path(@aircraft, @component), method: :post, class: "card-body space-y-3", + data: { turbo_confirm: "Reset hours for #{@component}?" } do |f| %> +

Resets hours since overhaul to 0 and sets the service date to today.

+ + <%= f.submit "Record Service", class: "btn-primary" %> + <% end %> +
+ <% end %> +
+ +<% if @squawks.any? %> +
+

Squawks on this component

+ <%= render "squawks/table", squawks: @squawks, aircraft: @aircraft %> +
+<% end %> diff --git a/app/views/consumable_records/_form.html.erb b/app/views/consumable_records/_form.html.erb new file mode 100644 index 0000000..4bf8846 --- /dev/null +++ b/app/views/consumable_records/_form.html.erb @@ -0,0 +1,15 @@ +<%= form_with model: [aircraft, record], class: "card card-body space-y-4 max-w-2xl" do |f| %> + <%= f.errors_summary %> +
+ <%= f.field :record_type, as: :select, label: "Type", collection: ConsumableRecord::TYPES.invert %> + <%= f.field :date, as: :date %> + <%= f.field :quantity_added, as: :number, step: 0.01, label: "Quantity added (qt / gal)" %> + <%= f.field :level_after, as: :number, step: 0.01, label: "Level after" %> + <%= f.field :consumable_type, label: "Product", placeholder: "Aeroshell W100 / 100LL" %> + <%= f.field :flight_hours, as: :number, step: 0.1, label: "Tach at time of record" %> +
+ <%= f.field :notes, as: :textarea, rows: 2 %> + <%= f.field :excluded_from_averages, as: :checkbox, label: "Exclude from averages", hint: "Use for oil changes or partial fills that would skew the trend." %> +
<%= f.submit "Save" %><%= link_to "Cancel", aircraft_consumable_records_path(aircraft), class: "btn-secondary" %>
+<% end %> +<% if record.persisted? %>
<%= delete_button "Delete record", aircraft_consumable_record_path(aircraft, record) %>
<% end %> diff --git a/app/views/consumable_records/edit.html.erb b/app/views/consumable_records/edit.html.erb new file mode 100644 index 0000000..badc243 --- /dev/null +++ b/app/views/consumable_records/edit.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, record: @record %> diff --git a/app/views/consumable_records/index.html.erb b/app/views/consumable_records/index.html.erb new file mode 100644 index 0000000..8f20702 --- /dev/null +++ b/app/views/consumable_records/index.html.erb @@ -0,0 +1,51 @@ +<% content_for :title, "#{@aircraft.tail_number} Oil & Fuel" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
+ <% [@oil, @fuel].each do |stats| %> +
+
+

<%= stats.oil? ? "Oil Consumption" : "Fuel Burn" %>

+ <%= link_to "+ Add #{stats.oil? ? 'Oil' : 'Fuel'}", new_aircraft_consumable_record_path(@aircraft, type: stats.record_type), class: "btn-secondary btn-sm" %> +
+
+
+
<%= stats.average || "—" %> <%= stats.metric_label %> avg (last 20)
+
<%= stats.latest || "—" %> latest
+
+ <% if stats.points.size >= 2 %> + <%= line_chart stats.chart_data, xtitle: "Tach hours", ytitle: stats.metric_label, height: "220px", + library: { scales: { x: { type: "linear" } } }, colors: [stats.oil? ? "#b45309" : "#0369a1"] %> + <% else %> + <%= empty_state "Add at least three records to see a trend." %> + <% end %> +
+
+ <% end %> +
+ +
+

Records

+ <% if @records.any? %> +
+ + + + <% @records.each do |r| %> + + + + + + + + + + + <% end %> + +
DateTypeAddedLevel afterProductTachNotes
<%= r.date %><%= tag.span ConsumableRecord::TYPES[r.record_type], class: r.record_type == "oil" ? "badge-orange" : "badge-blue" %><%= r.quantity_added %> <%= r.unit %><%= r.level_after ? "#{r.level_after} #{r.unit}" : "" %><%= r.consumable_type %><%= hours(r.flight_hours) %><%= r.notes %><%= " (excluded from average)" if r.excluded_from_averages? %><% if owner? %><%= link_to "Edit", edit_aircraft_consumable_record_path(@aircraft, r), class: "btn-secondary btn-sm" %><% end %>
+
+ <% else %> + <%= empty_state "No oil or fuel records yet." %> + <% end %> +
diff --git a/app/views/consumable_records/new.html.erb b/app/views/consumable_records/new.html.erb new file mode 100644 index 0000000..badc243 --- /dev/null +++ b/app/views/consumable_records/new.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, record: @record %> diff --git a/app/views/document_collections/_form.html.erb b/app/views/document_collections/_form.html.erb new file mode 100644 index 0000000..150530a --- /dev/null +++ b/app/views/document_collections/_form.html.erb @@ -0,0 +1,9 @@ +<%= form_with model: [aircraft, collection], class: "card card-body space-y-4 max-w-2xl" do |f| %> + <%= f.errors_summary %> + <%= f.field :name, required: true %> + <%= f.field :description, as: :textarea, rows: 2 %> + <%= f.field :visibility, as: :select, label: "Share-link visibility", collection: DocumentCollection::VISIBILITIES.invert %> + <%= f.field :starred, as: :checkbox, label: "Starred (shown first)" %> +
<%= f.submit "Save Collection" %><%= link_to "Cancel", aircraft_documents_path(aircraft), class: "btn-secondary" %>
+<% end %> +<% if collection.persisted? %>
<%= delete_button "Delete collection and its documents", aircraft_document_collection_path(aircraft, collection) %>
<% end %> diff --git a/app/views/document_collections/edit.html.erb b/app/views/document_collections/edit.html.erb new file mode 100644 index 0000000..ac0cd8e --- /dev/null +++ b/app/views/document_collections/edit.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, collection: @collection %> diff --git a/app/views/document_collections/new.html.erb b/app/views/document_collections/new.html.erb new file mode 100644 index 0000000..ac0cd8e --- /dev/null +++ b/app/views/document_collections/new.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, collection: @collection %> diff --git a/app/views/documents/_doc_row.html.erb b/app/views/documents/_doc_row.html.erb new file mode 100644 index 0000000..6a5c1af --- /dev/null +++ b/app/views/documents/_doc_row.html.erb @@ -0,0 +1,11 @@ +
  • +
    + <%= link_to doc.name, aircraft_document_path(aircraft, doc), class: "link font-medium" %> + <%= doc.type_label %> · <%= pluralize(doc.pages.size, "file") %> + <% if doc.description.present? %>
    <%= doc.description.truncate(120) %>
    <% end %> +
    +
    + <%= visibility_badge(doc.effective_visibility) %> + <% if owner? %><%= link_to "Edit", edit_aircraft_document_path(aircraft, doc), class: "btn-secondary btn-sm" %><% end %> +
    +
  • diff --git a/app/views/documents/_form.html.erb b/app/views/documents/_form.html.erb new file mode 100644 index 0000000..bab13d7 --- /dev/null +++ b/app/views/documents/_form.html.erb @@ -0,0 +1,24 @@ +<%= form_with model: [aircraft, document], class: "card card-body space-y-4 max-w-3xl", multipart: true do |f| %> + <%= f.errors_summary %> +
    + <%= f.field :name, required: true %> + <%= f.field :doc_type, as: :select, label: "Type", collection: Document::TYPES.invert %> + <%= f.field :document_collection_id, as: :select, label: "Collection", + collection: [["— None —", nil]] + aircraft.document_collections.ordered.map { [_1.name, _1.id] } %> + <%= f.field :visibility, as: :select, label: "Share-link visibility", + collection: [["Inherit from collection", nil]] + DocumentCollection::VISIBILITIES.invert.to_a %> +
    + <%= f.field :description, as: :textarea, rows: 2 %> + <%= f.field :pages, as: :file, multiple: true, label: document.persisted? ? "Add files" : "Files", + hint: "Images, PDFs or text. Each file is a page in the viewer, in upload order." %> + <% if document.persisted? && document.pages.any? %> +
    +

    Remove existing files

    + <% document.pages.each do |p| %> + + <% end %> +
    + <% end %> +
    <%= f.submit "Save Document" %><%= link_to "Cancel", aircraft_documents_path(aircraft), class: "btn-secondary" %>
    +<% end %> +<% if document.persisted? %>
    <%= delete_button "Delete document", aircraft_document_path(aircraft, document) %>
    <% end %> diff --git a/app/views/documents/_viewer.html.erb b/app/views/documents/_viewer.html.erb new file mode 100644 index 0000000..25f7ad1 --- /dev/null +++ b/app/views/documents/_viewer.html.erb @@ -0,0 +1,21 @@ +<%# Multi-page viewer: one attachment per "page", with prev/next. %> +<% pages = document.pages.to_a %> +<% if pages.empty? %> + <%= empty_state "No files uploaded." %> +<% else %> + <% current = pages[page - 1] %> +
    + <%= link_to "← Prev", url_for(page: page - 1), class: ["btn-secondary btn-sm", ("pointer-events-none opacity-40" if page <= 1)] %> + Page <%= page %> of <%= pages.size %> · <%= link_to current.filename, rails_blob_path(current, disposition: :attachment), class: "link" %> + <%= link_to "Next →", url_for(page: page + 1), class: ["btn-secondary btn-sm", ("pointer-events-none opacity-40" if page >= pages.size)] %> +
    +
    + <% if current.image? %> + <%= image_tag rails_blob_path(current, disposition: :inline), class: "max-h-[80vh] max-w-full" %> + <% elsif current.content_type == "application/pdf" %> + + <% else %> +

    <%= link_to "Download #{current.filename}", rails_blob_path(current, disposition: :attachment), class: "link" %>

    + <% end %> +
    +<% end %> diff --git a/app/views/documents/edit.html.erb b/app/views/documents/edit.html.erb new file mode 100644 index 0000000..d00942f --- /dev/null +++ b/app/views/documents/edit.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, document: @document %> diff --git a/app/views/documents/index.html.erb b/app/views/documents/index.html.erb new file mode 100644 index 0000000..9d9c5bd --- /dev/null +++ b/app/views/documents/index.html.erb @@ -0,0 +1,39 @@ +<% content_for :title, "#{@aircraft.tail_number} Documents" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
    + <% if owner? %> + <%= link_to "+ Collection", new_aircraft_document_collection_path(@aircraft), class: "btn-secondary" %> + <%= link_to "+ Upload Document", new_aircraft_document_path(@aircraft), class: "btn-primary" %> + <% end %> +
    +<% if @collections.empty? && @uncollected.empty? %> +
    <%= empty_state "No documents yet. Upload logbook scans, 337s, weight & balance, receipts…" %>
    +<% end %> +
    + <% @collections.each do |col| %> +
    +
    +
    +

    <%= "★ " if col.starred? %><%= col.name %>

    + <% if col.description.present? %>

    <%= col.description %>

    <% end %> +
    +
    + <%= visibility_badge(col.visibility) %> + <% if owner? %> + <%= link_to "+ Document", new_aircraft_document_path(@aircraft, collection_id: col.id), class: "btn-secondary btn-sm" %> + <%= link_to "Edit", edit_aircraft_document_collection_path(@aircraft, col), class: "btn-secondary btn-sm" %> + <% end %> +
    +
    + <% if col.documents.any? %> +
      <% col.documents.sort_by(&:name).each do |doc| %><%= render "documents/doc_row", doc: doc, aircraft: @aircraft %><% end %>
    + <% else %><%= empty_state "Empty collection." %><% end %> +
    + <% end %> + <% if @uncollected.any? %> +
    +

    Uncollected

    +
      <% @uncollected.each do |doc| %><%= render "documents/doc_row", doc: doc, aircraft: @aircraft %><% end %>
    +
    + <% end %> +
    diff --git a/app/views/documents/new.html.erb b/app/views/documents/new.html.erb new file mode 100644 index 0000000..d00942f --- /dev/null +++ b/app/views/documents/new.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, document: @document %> diff --git a/app/views/documents/show.html.erb b/app/views/documents/show.html.erb new file mode 100644 index 0000000..36b0edc --- /dev/null +++ b/app/views/documents/show.html.erb @@ -0,0 +1,18 @@ +<% content_for :title, @document.name %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
    +
    +
    +

    <%= @document.name %>

    +

    <%= @document.type_label %><%= " · #{@document.document_collection.name}" if @document.document_collection %>

    +
    +
    + <%= visibility_badge(@document.effective_visibility) %> + <% if owner? %><%= link_to "Edit", edit_aircraft_document_path(@aircraft, @document), class: "btn-secondary btn-sm" %><% end %> +
    +
    +
    + <% if @document.description.present? %>

    <%= @document.description %>

    <% end %> + <%= render "documents/viewer", document: @document, page: @page %> +
    +
    diff --git a/app/views/errors/not_found.html.erb b/app/views/errors/not_found.html.erb new file mode 100644 index 0000000..44e6f58 --- /dev/null +++ b/app/views/errors/not_found.html.erb @@ -0,0 +1,5 @@ +
    +

    Not found

    +

    That page doesn't exist, or you don't have access to it.

    + <% if current_user %>

    <%= link_to "Back to fleet", root_path, class: "btn-secondary" %>

    <% end %> +
    diff --git a/app/views/events/_list.html.erb b/app/views/events/_list.html.erb new file mode 100644 index 0000000..0a8b0c4 --- /dev/null +++ b/app/views/events/_list.html.erb @@ -0,0 +1,16 @@ +<% if events.any? %> +
      + <% events.each do |e| %> +
    • +
      + <%= e.event_name %> + <%= AircraftEvent::CATEGORIES[e.category] %> +
      +
      <%= e.user&.display_name || "System" %> · <%= time_ago_in_words(e.created_at) %> ago
      + <% if e.notes.present? && local_assigns[:full] %>
      <%= e.notes %>
      <% end %> +
    • + <% end %> +
    +<% else %> + <%= empty_state "No activity yet." %> +<% end %> diff --git a/app/views/events/index.html.erb b/app/views/events/index.html.erb new file mode 100644 index 0000000..d399191 --- /dev/null +++ b/app/views/events/index.html.erb @@ -0,0 +1,11 @@ +<% content_for :title, "#{@aircraft.tail_number} Activity" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
    +
    +

    Activity Log

    + <%= form_with url: aircraft_events_path(@aircraft), method: :get, class: "flex gap-2" do |f| %> + <%= f.select :category, AircraftEvent::CATEGORIES.invert, { include_blank: "All categories", selected: @category }, class: "input", onchange: "this.form.requestSubmit()" %> + <% end %> +
    + <%= render "events/list", events: @events, full: true %> +
    diff --git a/app/views/flight_logs/index.html.erb b/app/views/flight_logs/index.html.erb new file mode 100644 index 0000000..a562b66 --- /dev/null +++ b/app/views/flight_logs/index.html.erb @@ -0,0 +1,28 @@ +<% content_for :title, "#{@aircraft.tail_number} Flights" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
    +

    Flight Log

    <%= link_to "+ Log Flight", new_aircraft_flight_log_path(@aircraft), class: "btn-primary" %>
    + <% if @flight_logs.any? %> +
    + + + + <% @flight_logs.each do |fl| %> + + + + + + + + + + + <% end %> + +
    DateRouteTachHobbsOilFuelPilot
    <%= link_to fl.date, aircraft_flight_log_path(@aircraft, fl), class: "link" %><%= fl.route_summary.presence || "—" %><%= hours(fl.tach_time) %><%= hours(fl.hobbs_time) %><%= fl.oil_added ? "#{fl.oil_added} qt" : "" %><%= fl.fuel_added ? "#{fl.fuel_added} gal" : "" %><%= fl.user&.display_name %><%= "📍" if fl.track_log.attached? %>
    +
    + <% else %> + <%= empty_state "No flights logged yet." %> + <% end %> +
    diff --git a/app/views/flight_logs/new.html.erb b/app/views/flight_logs/new.html.erb new file mode 100644 index 0000000..08b4d24 --- /dev/null +++ b/app/views/flight_logs/new.html.erb @@ -0,0 +1,36 @@ +<% content_for :title, "Log Flight" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= form_with model: [@aircraft, @flight_log], class: "card card-body space-y-5 max-w-3xl" do |f| %> + <%= f.errors_summary %> +
    + <%= f.field :date, as: :date, required: true %> + <%= f.field :departure_location, label: "From", placeholder: "KPVD" %> + <%= f.field :destination_location, label: "To", placeholder: "KBID" %> +
    +
    + Tach (required) + <%= f.field :tach_out, as: :number, step: 0.1, label: "Tach out" %> + <%= f.field :tach_in, as: :number, step: 0.1, label: "Tach in" %> + <%= f.field :tach_time, as: :number, step: 0.1, label: "…or duration", hint: "Calculated from out/in if blank." %> +
    +
    + Hobbs (optional) + <%= f.field :hobbs_out, as: :number, step: 0.1, label: "Hobbs out" %> + <%= f.field :hobbs_in, as: :number, step: 0.1, label: "Hobbs in" %> + <%= f.field :hobbs_time, as: :number, step: 0.1, label: "…or duration" %> +
    +
    + Oil & fuel added + <%= f.field :oil_added, as: :number, step: 0.25, label: "Oil added (qt)" %> + <%= f.field :oil_level_after, as: :number, step: 0.25, label: "Oil level after (qt)" %> + <%= f.field :oil_added_type, label: "Oil type", placeholder: "Aeroshell W100" %> + <%= f.field :fuel_added, as: :number, step: 0.1, label: "Fuel added (gal)" %> + <%= f.field :fuel_level_after, as: :number, step: 0.1, label: "Fuel level after (gal)" %> + <%= f.field :fuel_added_type, label: "Fuel type", placeholder: "100LL" %> +
    + <%= f.field :route, as: :textarea, rows: 2 %> + <%= f.field :notes, as: :textarea, rows: 2 %> + <%= f.field :track_log, as: :file, label: "Track log (GPX/KML/CSV)" %> +

    Saving adds the tach time to the aircraft and all in-service components, and records any oil/fuel added.

    +
    <%= f.submit "Log Flight" %><%= link_to "Cancel", aircraft_flight_logs_path(@aircraft), class: "btn-secondary" %>
    +<% end %> diff --git a/app/views/flight_logs/show.html.erb b/app/views/flight_logs/show.html.erb new file mode 100644 index 0000000..f631509 --- /dev/null +++ b/app/views/flight_logs/show.html.erb @@ -0,0 +1,15 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
    +

    Flight on <%= fmt_date(@flight_log.date) %>

    + <% if owner? %><%= delete_button "Delete", aircraft_flight_log_path(@aircraft, @flight_log), confirm: "Delete this flight log? Aircraft and component hours will NOT be rolled back." %><% end %>
    +
    +
    Tach
    <%= hours(@flight_log.tach_time) %> <%= "(#{@flight_log.tach_out} → #{@flight_log.tach_in})" if @flight_log.tach_out && @flight_log.tach_in %>
    +
    Hobbs
    <%= hours(@flight_log.hobbs_time) %> <%= "(#{@flight_log.hobbs_out} → #{@flight_log.hobbs_in})" if @flight_log.hobbs_out && @flight_log.hobbs_in %>
    +
    Route
    <%= @flight_log.route_summary.presence || "—" %> <%= @flight_log.route %>
    +
    Oil added
    <%= @flight_log.oil_added ? "#{@flight_log.oil_added} qt #{@flight_log.oil_added_type}" : "—" %>
    +
    Fuel added
    <%= @flight_log.fuel_added ? "#{@flight_log.fuel_added} gal #{@flight_log.fuel_added_type}" : "—" %>
    +
    Pilot
    <%= @flight_log.user&.display_name || "—" %>
    +
    Track log
    <%= @flight_log.track_log.attached? ? link_to(@flight_log.track_log.filename, rails_blob_path(@flight_log.track_log, disposition: :attachment), class: "link") : "—" %>
    +
    + <% if @flight_log.notes.present? %>
    <%= simple_format @flight_log.notes %>
    <% end %> +
    diff --git a/app/views/inspection_records/_form.html.erb b/app/views/inspection_records/_form.html.erb new file mode 100644 index 0000000..7b26e23 --- /dev/null +++ b/app/views/inspection_records/_form.html.erb @@ -0,0 +1,13 @@ +<%= form_with model: record, url: record.new_record? ? aircraft_inspection_records_path(aircraft) : aircraft_inspection_record_path(aircraft, record), class: "card card-body space-y-4 max-w-2xl" do |f| %> + <%= f.errors_summary %> + <%= f.field :inspection_type_id, as: :select, label: "Inspection", collection: aircraft.applicable_inspection_types.ordered.map { [_1.name, _1.id] } %> +
    + <%= f.field :date, as: :date %> + <%= f.field :aircraft_hours, as: :number, step: 0.1, label: "Aircraft hours (tach)" %> + <%= f.field :component_id, as: :select, label: "Component (if component-level)", collection: component_options(aircraft) %> + <%= f.field :logbook_entry_id, as: :select, label: "Logbook entry", collection: logbook_options(aircraft) %> +
    + <%= f.field :notes, as: :textarea, rows: 2 %> +
    <%= f.submit "Save" %><%= link_to "Cancel", aircraft_inspections_path(aircraft), class: "btn-secondary" %>
    +<% end %> +<% if record.persisted? %>
    <%= delete_button "Delete record", aircraft_inspection_record_path(aircraft, record) %>
    <% end %> diff --git a/app/views/inspection_records/edit.html.erb b/app/views/inspection_records/edit.html.erb new file mode 100644 index 0000000..badc243 --- /dev/null +++ b/app/views/inspection_records/edit.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, record: @record %> diff --git a/app/views/inspection_records/new.html.erb b/app/views/inspection_records/new.html.erb new file mode 100644 index 0000000..badc243 --- /dev/null +++ b/app/views/inspection_records/new.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, record: @record %> diff --git a/app/views/inspection_types/_form.html.erb b/app/views/inspection_types/_form.html.erb new file mode 100644 index 0000000..f7bebe8 --- /dev/null +++ b/app/views/inspection_types/_form.html.erb @@ -0,0 +1,19 @@ +<%= form_with model: inspection_type, url: inspection_type.new_record? ? aircraft_inspection_types_path(aircraft) : aircraft_inspection_type_path(aircraft, inspection_type), class: "card card-body space-y-4 max-w-2xl" do |f| %> + <%= f.errors_summary %> + <%= f.field :name, required: true, placeholder: "Annual Inspection" %> +
    + <%= f.field :required, as: :checkbox, label: "Required for airworthiness" %> + <%= f.field :recurring, as: :checkbox, label: "Recurring" %> +
    +
    + <%= f.field :recurring_hours, as: :number, step: 0.1, label: "Every (hours)" %> + <%= f.field :recurring_months, as: :number, label: "Every (calendar months)", hint: "Due end of month." %> + <%= f.field :recurring_days, as: :number, label: "Every (days)" %> +
    + <%= render "shared/applicability_fields", aircraft: aircraft, record: inspection_type, applies_to_airframe: @applies_to_airframe %> + <% if inspection_type.persisted? && inspection_type.aircraft.count > 1 %> +

    This inspection type is shared with other aircraft; interval changes affect them too.

    + <% end %> +
    <%= f.submit "Save" %><%= link_to "Cancel", aircraft_inspections_path(aircraft), class: "btn-secondary" %>
    +<% end %> +<% if inspection_type.persisted? %>
    <%= delete_button "Remove from #{aircraft.tail_number}", aircraft_inspection_type_path(aircraft, inspection_type) %>
    <% end %> diff --git a/app/views/inspection_types/edit.html.erb b/app/views/inspection_types/edit.html.erb new file mode 100644 index 0000000..2ac5bdc --- /dev/null +++ b/app/views/inspection_types/edit.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, inspection_type: @inspection_type %> diff --git a/app/views/inspection_types/new.html.erb b/app/views/inspection_types/new.html.erb new file mode 100644 index 0000000..2ac5bdc --- /dev/null +++ b/app/views/inspection_types/new.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, inspection_type: @inspection_type %> diff --git a/app/views/inspections/index.html.erb b/app/views/inspections/index.html.erb new file mode 100644 index 0000000..f7de6cd --- /dev/null +++ b/app/views/inspections/index.html.erb @@ -0,0 +1,54 @@ +<% content_for :title, "#{@aircraft.tail_number} Inspections" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
    +

    Inspection Status

    + <% if owner? %><%= link_to "+ Inspection Type", new_aircraft_inspection_type_path(@aircraft), class: "btn-primary" %><% end %>
    + <% if @rows.any? %> +
    + + + + <% @rows.each do |row| %> + + + + + + + + + <% end %> + +
    InspectionIntervalLast doneNext dueStatus
    <%= row.type.name %><%= tag.span(" optional", class: "text-xs text-slate-400") unless row.type.required? %><%= row.type.interval_description %><%= row.latest ? "#{row.latest.date} @ #{hours(row.latest.hours_at_inspection)} h" : "—" %><%= [row.next_due_date&.to_s, row.next_due_hours && "#{hours(row.next_due_hours)} h"].compact.join(" / ").presence || "—" %><%= compliance_badge(row.status) %> + <% if owner? %> + <%= link_to "Record", new_aircraft_inspection_record_path(@aircraft, inspection_type_id: row.type.id), class: "btn-secondary btn-sm" %> + <%= link_to "Edit", edit_aircraft_inspection_type_path(@aircraft, row.type), class: "btn-secondary btn-sm" %> + <% end %> +
    +
    + <% else %> + <%= empty_state "No inspections tracked. Add Annual, 100-hour, transponder (91.413), pitot-static (91.411), ELT (91.207)…" %> + <% end %> +
    + +
    +

    History

    + <% if @history.any? %> + + + + <% @history.each do |r| %> + + + + + + + + <% end %> + +
    DateInspectionHoursNotes
    <%= r.date %><%= r.inspection_type.name %><%= " (#{r.component})" if r.component %><%= hours(r.hours_at_inspection) %><%= r.notes %><% if r.logbook_entry %> <%= link_to "logbook", aircraft_logbook_entry_path(@aircraft, r.logbook_entry), class: "link" %><% end %><% if owner? %><%= link_to "Edit", edit_aircraft_inspection_record_path(@aircraft, r), class: "btn-secondary btn-sm" %><% end %>
    + <% else %> + <%= empty_state "No inspections recorded." %> + <% end %> +
    diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb new file mode 100644 index 0000000..57b6300 --- /dev/null +++ b/app/views/layouts/application.html.erb @@ -0,0 +1,43 @@ + + + + <%= [content_for(:title), "Simple Aircraft Manager"].compact.join(" · ") %> + + + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + <%= yield :head %> + + + + <%= stylesheet_link_tag :app, "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + + +
    +
    + <%= link_to root_path, class: "flex items-center gap-2 font-semibold tracking-tight" do %> + ✈ Simple Aircraft Manager + <% end %> + <% if current_user %> + + <% end %> +
    +
    + +
    + <%= render "shared/flash" %> + <%= yield %> +
    + + diff --git a/app/views/layouts/mailer.html.erb b/app/views/layouts/mailer.html.erb new file mode 100644 index 0000000..3aac900 --- /dev/null +++ b/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/app/views/layouts/mailer.text.erb b/app/views/layouts/mailer.text.erb new file mode 100644 index 0000000..37f0bdd --- /dev/null +++ b/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/app/views/layouts/public.html.erb b/app/views/layouts/public.html.erb new file mode 100644 index 0000000..1235d42 --- /dev/null +++ b/app/views/layouts/public.html.erb @@ -0,0 +1,22 @@ + + + + <%= [content_for(:title), "Simple Aircraft Manager"].compact.join(" · ") %> + + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag :app, "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + +
    +
    ✈ Simple Aircraft Manager
    +
    +
    + <%= render "shared/flash" %> + <%= yield %> +
    + + diff --git a/app/views/logbook_entries/_form.html.erb b/app/views/logbook_entries/_form.html.erb new file mode 100644 index 0000000..9f06073 --- /dev/null +++ b/app/views/logbook_entries/_form.html.erb @@ -0,0 +1,18 @@ +<%= form_with model: [aircraft, entry], class: "card card-body space-y-4 max-w-3xl" do |f| %> + <%= f.errors_summary %> +
    + <%= f.field :date, as: :date %> + <%= f.field :log_type, as: :select, label: "Logbook", collection: LogbookEntry::LOG_TYPES.invert %> + <%= f.field :entry_type, as: :select, label: "Entry type", collection: LogbookEntry::ENTRY_TYPES.invert %> + <%= f.field :aircraft_hours_at_entry, as: :number, step: 0.1, label: "Aircraft hours" %> +
    + <%= f.field :text, as: :textarea, label: "Entry text", rows: 8 %> +
    + <%= f.field :signoff_person, label: "Signed off by", placeholder: "Name, A&P/IA #" %> + <%= f.field :signoff_location, label: "Location / shop" %> + <%= f.field :document_id, as: :select, label: "Scanned page document", collection: document_options(aircraft) %> + <%= f.field :page_number, as: :number, label: "Page # in document" %> +
    +
    <%= f.submit "Save Entry" %><%= link_to "Cancel", aircraft_logbook_entries_path(aircraft), class: "btn-secondary" %>
    +<% end %> +<% if entry.persisted? %>
    <%= delete_button "Delete entry", aircraft_logbook_entry_path(aircraft, entry) %>
    <% end %> diff --git a/app/views/logbook_entries/edit.html.erb b/app/views/logbook_entries/edit.html.erb new file mode 100644 index 0000000..2a14097 --- /dev/null +++ b/app/views/logbook_entries/edit.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, entry: @entry %> diff --git a/app/views/logbook_entries/index.html.erb b/app/views/logbook_entries/index.html.erb new file mode 100644 index 0000000..92967a5 --- /dev/null +++ b/app/views/logbook_entries/index.html.erb @@ -0,0 +1,36 @@ +<% content_for :title, "#{@aircraft.tail_number} Logbook" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
    +
    +

    Maintenance Logbook

    +
    + <%= form_with url: aircraft_logbook_entries_path(@aircraft), method: :get, class: "flex gap-2" do |f| %> + <%= f.search_field :q, value: @query, placeholder: "Search entries…", class: "input w-48" %> + <%= f.select :log_type, LogbookEntry::LOG_TYPES.invert, { include_blank: "All logs", selected: @log_type }, class: "input w-32" %> + <%= f.submit "Filter", class: "btn-secondary" %> + <% end %> + <% if owner? %><%= link_to "+ New Entry", new_aircraft_logbook_entry_path(@aircraft), class: "btn-primary" %><% end %> +
    +
    + <% if @entries.any? %> +
    + + + + <% @entries.each do |e| %> + + + + + + + + + <% end %> + +
    DateLogTypeHoursEntrySigned off
    <%= link_to e.date, aircraft_logbook_entry_path(@aircraft, e), class: "link" %><%= LogbookEntry::LOG_TYPES[e.log_type] %><%= LogbookEntry::ENTRY_TYPES[e.entry_type] %><%= hours(e.aircraft_hours_at_entry) %><%= e.text.truncate(220) %> <%= "📄" if e.document %><%= e.signoff_person %><% if e.signoff_location.present? %>
    <%= e.signoff_location %><% end %>
    +
    + <% else %> + <%= empty_state(@query.present? ? "No entries match “#{@query}”." : "No logbook entries yet.") %> + <% end %> +
    diff --git a/app/views/logbook_entries/new.html.erb b/app/views/logbook_entries/new.html.erb new file mode 100644 index 0000000..2a14097 --- /dev/null +++ b/app/views/logbook_entries/new.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, entry: @entry %> diff --git a/app/views/logbook_entries/show.html.erb b/app/views/logbook_entries/show.html.erb new file mode 100644 index 0000000..f613fd8 --- /dev/null +++ b/app/views/logbook_entries/show.html.erb @@ -0,0 +1,18 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
    +
    +

    <%= LogbookEntry::LOG_TYPES[@entry.log_type] %> log — <%= fmt_date(@entry.date) %>

    + <% if owner? %><%= link_to "Edit", edit_aircraft_logbook_entry_path(@aircraft, @entry), class: "btn-secondary btn-sm" %><% end %> +
    +
    +
    + Type: <%= LogbookEntry::ENTRY_TYPES[@entry.entry_type] %> + Aircraft hours: <%= hours(@entry.aircraft_hours_at_entry) %> +
    +
    <%= @entry.text %>
    +
    Signed off: <%= @entry.signoff_person.presence || "—" %> <%= "(#{@entry.signoff_location})" if @entry.signoff_location.present? %>
    + <% if @entry.document %> +

    Scan: <%= link_to @entry.document.name, aircraft_document_path(@aircraft, @entry.document, page: @entry.page_number), class: "link" %><%= " (page #{@entry.page_number})" if @entry.page_number %>

    + <% end %> +
    +
    diff --git a/app/views/major_records/_form.html.erb b/app/views/major_records/_form.html.erb new file mode 100644 index 0000000..7fd2f13 --- /dev/null +++ b/app/views/major_records/_form.html.erb @@ -0,0 +1,24 @@ +<%= form_with model: [aircraft, record], class: "card card-body space-y-4 max-w-3xl" do |f| %> + <%= f.errors_summary %> +
    + <%= f.field :record_type, as: :select, label: "Type", collection: MajorRecord::RECORD_TYPES.invert %> + <%= f.field :date_performed, as: :date %> + <%= f.field :aircraft_hours, as: :number, step: 0.1 %> +
    + <%= f.field :title, required: true %> + <%= f.field :description, as: :textarea, rows: 4 %> +
    + <%= f.field :performed_by %> + <%= f.field :component_id, as: :select, label: "Component", collection: component_options(aircraft) %> + <%= f.field :form_337_document_id, as: :select, label: "Form 337 document", collection: document_options(aircraft) %> + <%= f.field :logbook_entry_id, as: :select, label: "Logbook entry", collection: logbook_options(aircraft) %> + <%= f.field :stc_number, label: "STC number" %> + <%= f.field :stc_holder, label: "STC holder" %> + <%= f.field :stc_document_id, as: :select, label: "STC document", collection: document_options(aircraft) %> +
    + <%= f.field :has_ica, as: :checkbox, label: "Includes Instructions for Continued Airworthiness" %> + <%= f.field :ica_notes, as: :textarea, rows: 2, label: "ICA notes" %> + <%= f.field :notes, as: :textarea, rows: 2 %> +
    <%= f.submit "Save" %><%= link_to "Cancel", aircraft_major_records_path(aircraft), class: "btn-secondary" %>
    +<% end %> +<% if record.persisted? %>
    <%= delete_button "Delete record", aircraft_major_record_path(aircraft, record) %>
    <% end %> diff --git a/app/views/major_records/edit.html.erb b/app/views/major_records/edit.html.erb new file mode 100644 index 0000000..badc243 --- /dev/null +++ b/app/views/major_records/edit.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, record: @record %> diff --git a/app/views/major_records/index.html.erb b/app/views/major_records/index.html.erb new file mode 100644 index 0000000..9981c74 --- /dev/null +++ b/app/views/major_records/index.html.erb @@ -0,0 +1,27 @@ +<% content_for :title, "#{@aircraft.tail_number} Major Records" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
    +

    Major Repairs & Alterations

    + <% if owner? %>
    + <%= link_to "+ Repair", new_aircraft_major_record_path(@aircraft, type: "repair"), class: "btn-secondary" %> + <%= link_to "+ Alteration", new_aircraft_major_record_path(@aircraft, type: "alteration"), class: "btn-primary" %>
    <% end %>
    + <% if @records.any? %> + + + + <% @records.each do |r| %> + + + + + + + + + <% end %> + +
    DateTypeTitlePerformed bySTCICA
    <%= r.date_performed %><%= tag.span r.type_label, class: r.record_type == "repair" ? "badge-orange" : "badge-blue" %><%= link_to r.title, aircraft_major_record_path(@aircraft, r), class: "link" %><%= tag.div(r.component, class: "text-xs text-slate-500") if r.component %><%= r.performed_by %><%= r.stc_number %><%= "✓" if r.has_ica? %>
    + <% else %> + <%= empty_state "No major repairs or alterations recorded." %> + <% end %> +
    diff --git a/app/views/major_records/new.html.erb b/app/views/major_records/new.html.erb new file mode 100644 index 0000000..badc243 --- /dev/null +++ b/app/views/major_records/new.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, record: @record %> diff --git a/app/views/major_records/show.html.erb b/app/views/major_records/show.html.erb new file mode 100644 index 0000000..a2b0c2c --- /dev/null +++ b/app/views/major_records/show.html.erb @@ -0,0 +1,19 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
    +

    <%= @record.type_label %>: <%= @record.title %>

    + <% if owner? %><%= link_to "Edit", edit_aircraft_major_record_path(@aircraft, @record), class: "btn-secondary btn-sm" %><% end %>
    +
    +
    Date
    <%= fmt_date(@record.date_performed) %>
    +
    Aircraft hours
    <%= hours(@record.aircraft_hours) %>
    +
    Performed by
    <%= @record.performed_by.presence || "—" %>
    +
    Component
    <%= @record.component || "—" %>
    +
    Form 337
    <%= @record.form_337_document ? link_to(@record.form_337_document.name, aircraft_document_path(@aircraft, @record.form_337_document), class: "link") : "—" %>
    +
    STC
    <%= [@record.stc_number, @record.stc_holder].compact_blank.join(" · ").presence || "—" %> + <%= link_to("(docs)", aircraft_document_path(@aircraft, @record.stc_document), class: "link") if @record.stc_document %>
    +
    Logbook
    <%= @record.logbook_entry ? link_to(@record.logbook_entry.date, aircraft_logbook_entry_path(@aircraft, @record.logbook_entry), class: "link") : "—" %>
    +
    ICAs
    <%= @record.has_ica? ? "Yes" : "No" %>
    +
    + <% [["Description", @record.description], ["ICA notes", @record.ica_notes], ["Notes", @record.notes]].each do |title, text| %> + <% if text.present? %>

    <%= title %>

    <%= simple_format text %>
    <% end %> + <% end %> +
    diff --git a/app/views/notes/_form.html.erb b/app/views/notes/_form.html.erb new file mode 100644 index 0000000..d92abc9 --- /dev/null +++ b/app/views/notes/_form.html.erb @@ -0,0 +1,7 @@ +<%= form_with model: note, url: note.new_record? ? aircraft_notes_path(aircraft) : aircraft_note_path(aircraft, note), class: "card card-body space-y-4 max-w-2xl" do |f| %> + <%= f.errors_summary %> + <%= f.field :text, as: :textarea, label: "Note", rows: 5, autofocus: true %> + <%= f.field :public, as: :checkbox, label: "Show on share links" %> +
    <%= f.submit "Save Note" %><%= link_to "Cancel", aircraft_notes_path(aircraft), class: "btn-secondary" %>
    +<% end %> +<% if note.persisted? %>
    <%= delete_button "Delete note", aircraft_note_path(aircraft, note) %>
    <% end %> diff --git a/app/views/notes/edit.html.erb b/app/views/notes/edit.html.erb new file mode 100644 index 0000000..01961d8 --- /dev/null +++ b/app/views/notes/edit.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, note: @note %> diff --git a/app/views/notes/index.html.erb b/app/views/notes/index.html.erb new file mode 100644 index 0000000..5521533 --- /dev/null +++ b/app/views/notes/index.html.erb @@ -0,0 +1,24 @@ +<% content_for :title, "#{@aircraft.tail_number} Notes" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
    +

    Notes

    <%= link_to "+ Add Note", new_aircraft_note_path(@aircraft), class: "btn-primary" %>
    + <% if @notes.any? %> +
      + <% @notes.each do |note| %> +
    • +
      +
      <%= simple_format note.text %>
      +
      + <%= note.user&.display_name || "Unknown" %> · <%= l note.created_at, format: :short %> + <%= "· edited" if note.edited_at %> + <% if note.public? %>Visible on share links<% end %> +
      +
      + <% if owner? %><%= link_to "Edit", edit_aircraft_note_path(@aircraft, note), class: "btn-secondary btn-sm" %><% end %> +
    • + <% end %> +
    + <% else %> + <%= empty_state "No notes yet." %> + <% end %> +
    diff --git a/app/views/notes/new.html.erb b/app/views/notes/new.html.erb new file mode 100644 index 0000000..01961d8 --- /dev/null +++ b/app/views/notes/new.html.erb @@ -0,0 +1,2 @@ +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, note: @note %> diff --git a/app/views/passwords/edit.html.erb b/app/views/passwords/edit.html.erb new file mode 100644 index 0000000..65798f8 --- /dev/null +++ b/app/views/passwords/edit.html.erb @@ -0,0 +1,21 @@ +
    + <% if alert = flash[:alert] %> +

    <%= alert %>

    + <% end %> + +

    Update your password

    + + <%= form_with url: password_path(params[:token]), method: :put, class: "contents" do |form| %> +
    + <%= form.password_field :password, required: true, autocomplete: "new-password", placeholder: "Enter new password", maxlength: 72, class: "block shadow-sm rounded-md border border-gray-400 focus:outline-solid focus:outline-blue-600 px-3 py-2 mt-2 w-full" %> +
    + +
    + <%= form.password_field :password_confirmation, required: true, autocomplete: "new-password", placeholder: "Repeat new password", maxlength: 72, class: "block shadow-sm rounded-md border border-gray-400 focus:outline-solid focus:outline-blue-600 px-3 py-2 mt-2 w-full" %> +
    + +
    + <%= form.submit "Save", class: "w-full sm:w-auto text-center rounded-md px-3.5 py-2.5 bg-blue-600 hover:bg-blue-500 text-white inline-block font-medium cursor-pointer" %> +
    + <% end %> +
    diff --git a/app/views/passwords/new.html.erb b/app/views/passwords/new.html.erb new file mode 100644 index 0000000..8360e02 --- /dev/null +++ b/app/views/passwords/new.html.erb @@ -0,0 +1,17 @@ +
    + <% if alert = flash[:alert] %> +

    <%= alert %>

    + <% end %> + +

    Forgot your password?

    + + <%= form_with url: passwords_path, class: "contents" do |form| %> +
    + <%= form.email_field :email_address, required: true, autofocus: true, autocomplete: "username", placeholder: "Enter your email address", value: params[:email_address], class: "block shadow-sm rounded-md border border-gray-400 focus:outline-solid focus:outline-blue-600 px-3 py-2 mt-2 w-full" %> +
    + +
    + <%= form.submit "Email reset instructions", class: "w-full sm:w-auto text-center rounded-lg px-3.5 py-2.5 bg-blue-600 hover:bg-blue-500 text-white inline-block font-medium cursor-pointer" %> +
    + <% end %> +
    diff --git a/app/views/passwords_mailer/reset.html.erb b/app/views/passwords_mailer/reset.html.erb new file mode 100644 index 0000000..4a06619 --- /dev/null +++ b/app/views/passwords_mailer/reset.html.erb @@ -0,0 +1,4 @@ +

    + You can reset your password within the next 15 minutes on + <%= link_to "this password reset page", edit_password_url(@user.password_reset_token) %>. +

    diff --git a/app/views/passwords_mailer/reset.text.erb b/app/views/passwords_mailer/reset.text.erb new file mode 100644 index 0000000..2cf03fc --- /dev/null +++ b/app/views/passwords_mailer/reset.text.erb @@ -0,0 +1,2 @@ +You can reset your password within the next 15 minutes on this password reset page: +<%= edit_password_url(@user.password_reset_token) %> diff --git a/app/views/profiles/edit.html.erb b/app/views/profiles/edit.html.erb new file mode 100644 index 0000000..eb38cdf --- /dev/null +++ b/app/views/profiles/edit.html.erb @@ -0,0 +1,9 @@ +

    Your Profile

    +<%= form_with model: @user, url: profile_path, method: :patch, class: "card card-body space-y-4 max-w-md" do |f| %> + <%= f.errors_summary %> + <%= f.field :name %> + <%= f.field :email_address, as: :email, label: "Email" %> + <%= f.field :password, as: :password, label: "New password", hint: "Leave blank to keep your current password.", autocomplete: "new-password" %> + <%= f.field :password_confirmation, as: :password, label: "Confirm new password" %> + <%= f.submit "Save" %> +<% end %> diff --git a/app/views/pwa/manifest.json.erb b/app/views/pwa/manifest.json.erb new file mode 100644 index 0000000..2d8f973 --- /dev/null +++ b/app/views/pwa/manifest.json.erb @@ -0,0 +1,22 @@ +{ + "name": "SimpleAircraftManager", + "icons": [ + { + "src": "/icon.png", + "type": "image/png", + "sizes": "512x512" + }, + { + "src": "/icon.png", + "type": "image/png", + "sizes": "512x512", + "purpose": "maskable" + } + ], + "start_url": "/", + "display": "standalone", + "scope": "/", + "description": "SimpleAircraftManager.", + "theme_color": "red", + "background_color": "red" +} diff --git a/app/views/pwa/service-worker.js b/app/views/pwa/service-worker.js new file mode 100644 index 0000000..b3a13fb --- /dev/null +++ b/app/views/pwa/service-worker.js @@ -0,0 +1,26 @@ +// Add a service worker for processing Web Push notifications: +// +// self.addEventListener("push", async (event) => { +// const { title, options } = await event.data.json() +// event.waitUntil(self.registration.showNotification(title, options)) +// }) +// +// self.addEventListener("notificationclick", function(event) { +// event.notification.close() +// event.waitUntil( +// clients.matchAll({ type: "window" }).then((clientList) => { +// for (let i = 0; i < clientList.length; i++) { +// let client = clientList[i] +// let clientPath = (new URL(client.url)).pathname +// +// if (clientPath == event.notification.data.path && "focus" in client) { +// return client.focus() +// } +// } +// +// if (clients.openWindow) { +// return clients.openWindow(event.notification.data.path) +// } +// }) +// ) +// }) diff --git a/app/views/sessions/new.html.erb b/app/views/sessions/new.html.erb new file mode 100644 index 0000000..ef430d9 --- /dev/null +++ b/app/views/sessions/new.html.erb @@ -0,0 +1,12 @@ +<% content_for :title, "Sign in" %> +
    +

    Sign in

    + <%= form_with url: session_path, class: "card card-body space-y-4" do |form| %> +
    <%= form.label :email_address, "Email", class: "label" %> + <%= form.email_field :email_address, required: true, autofocus: true, autocomplete: "username", value: params[:email_address], class: "input" %>
    +
    <%= form.label :password, class: "label" %> + <%= form.password_field :password, required: true, autocomplete: "current-password", maxlength: 72, class: "input" %>
    + <%= form.submit "Sign in", class: "btn-primary w-full justify-center" %> +

    <%= link_to "Forgot password?", new_password_path, class: "link" %>

    + <% end %> +
    diff --git a/app/views/setup/new.html.erb b/app/views/setup/new.html.erb new file mode 100644 index 0000000..f445796 --- /dev/null +++ b/app/views/setup/new.html.erb @@ -0,0 +1,12 @@ +
    +

    Welcome

    +

    Create the administrator account to get started.

    + <%= form_with model: @user, url: setup_path, class: "card card-body space-y-4" do |f| %> + <%= f.errors_summary %> + <%= f.field :name %> + <%= f.field :email_address, as: :email, label: "Email", required: true %> + <%= f.field :password, as: :password, required: true, hint: "At least 8 characters." %> + <%= f.field :password_confirmation, as: :password, required: true %> + <%= f.submit "Create Admin Account", class: "btn-primary w-full justify-center" %> + <% end %> +
    diff --git a/app/views/shared/_aircraft_header.html.erb b/app/views/shared/_aircraft_header.html.erb new file mode 100644 index 0000000..e838e26 --- /dev/null +++ b/app/views/shared/_aircraft_header.html.erb @@ -0,0 +1,30 @@ +<%# Header + tab bar shown on every aircraft page. %> +<% aw = aircraft.airworthiness %> +
    +
    + <% if aircraft.picture.attached? %> + <%= image_tag aircraft.picture, class: "h-12 w-12 rounded-md object-cover" %> + <% end %> +
    +

    + <%= link_to aircraft.tail_number, aircraft_path(aircraft) %> + <%= [aircraft.make, aircraft.model].compact_blank.join(" ") %> +

    +
    + <%= airworthiness_badge(aw) %> + <%= aircraft_status_badge(aircraft) %> + Tach <%= hours(aircraft.tach_time) %> · Hobbs <%= hours(aircraft.hobbs_time) %> + <%= current_role.capitalize %> +
    +
    +
    +
    + <%= link_to "Log Flight", new_aircraft_flight_log_path(aircraft), class: "btn-primary" %> + <%= link_to "Report Squawk", new_aircraft_squawk_path(aircraft), class: "btn-secondary" %> +
    +
    + diff --git a/app/views/shared/_applicability_fields.html.erb b/app/views/shared/_applicability_fields.html.erb new file mode 100644 index 0000000..f765131 --- /dev/null +++ b/app/views/shared/_applicability_fields.html.erb @@ -0,0 +1,14 @@ +<%# ADs and inspection types: which parts of THIS aircraft they apply to. %> +
    + Applies to on <%= aircraft.tail_number %> + + <% comps = aircraft.components.where.not(status: "DISPOSED").includes(:component_type) %> + <% if comps.any? %> +
    + <% comps.each do |c| %> + + <% end %> +
    + <% end %> +

    Component-level items follow the component if it moves to another aircraft.

    +
    diff --git a/app/views/shared/_flash.html.erb b/app/views/shared/_flash.html.erb new file mode 100644 index 0000000..4257f11 --- /dev/null +++ b/app/views/shared/_flash.html.erb @@ -0,0 +1,6 @@ +<% if notice.present? %> +
    <%= notice %>
    +<% end %> +<% if alert.present? %> +
    <%= alert %>
    +<% end %> diff --git a/app/views/shared/show.html.erb b/app/views/shared/show.html.erb new file mode 100644 index 0000000..856ae6b --- /dev/null +++ b/app/views/shared/show.html.erb @@ -0,0 +1,101 @@ +<% content_for :title, @aircraft.tail_number %> +
    +
    + <% if @aircraft.picture.attached? %><%= image_tag rails_blob_path(@aircraft.picture, disposition: :inline), class: "h-16 w-16 rounded-md object-cover" %><% end %> +
    +

    <%= @aircraft.tail_number %> <%= [@aircraft.make, @aircraft.model].compact_blank.join(" ") %>

    +
    + <%= airworthiness_badge(@airworthiness) %> <%= aircraft_status_badge(@aircraft) %> + Tach <%= hours(@aircraft.tach_time) %> · Hobbs <%= hours(@aircraft.hobbs_time) %> +
    +
    +
    + Shared view · <%= ShareToken::PRIVILEGES[@share.privilege] %> +
    + +
    +
    +

    Airworthiness

    <%= airworthiness_badge(@airworthiness, large: true) %>
    +
    + <% if @airworthiness.issues.empty? %>

    No open issues.

    <% else %> +
      <% @airworthiness.issues.each do |i| %>
    • <%= i.category %> <%= i.title %> <%= i.description %>
    • <% end %>
    + <% end %> +
    +
    + +
    +
    +

    Open Squawks

    + <% if @active_squawks.any? %> +
      <% @active_squawks.each do |s| %>
    • <%= squawk_priority_badge(s) %> <%= s.issue_reported %>
    • <% end %>
    + <% else %><%= empty_state "None." %><% end %> +
    +
    +

    Consumption

    +
    +
    <%= @oil.average || "—" %>
    Oil hrs/qt
    +
    <%= @fuel.average || "—" %>
    Fuel gal/hr
    +
    +
    +
    + +
    +

    Components

    +
    + + <% @components.each do |c| %> + + + <% end %> +
    ComponentMake / ModelIn serviceSince OH/svcTBOLife
    <%= c %><%= c.manufacturer %> <%= c.model %><%= hours(c.hours_in_service) %><%= hours(c.hours_since_overhaul) %><%= c.tbo_hours %><%= life_badge(c.life_status) %>
    +
    + +
    +
    +

    Inspections

    + <% @inspection_rows.each do |r| %> + <% end %>
    <%= r.type.name %><%= r.latest&.date || "—" %><%= compliance_badge(r.status) %>
    +
    +
    +

    ADs

    + <% @ad_rows.each do |r| %> + <% end %>
    <%= r.ad.name %>
    <%= r.ad.short_description %>
    <%= r.latest&.date_complied || "—" %><%= compliance_badge(r.status) %>
    +
    +
    + + <% if @notes.any? %> +

    Notes

    +
      <% @notes.each do |n| %>
    • <%= simple_format n.text %>
      <%= n.created_at.to_date %>
    • <% end %>
    + <% end %> + + <% if @documents.any? %> +

    Documents

    +
      <% @documents.each do |d| %>
    • + <%= d.name %> <%= d.type_label %> +
      <% d.pages.each_with_index do |p, i| %><%= link_to "#{i + 1}. #{p.filename}", rails_blob_path(p, disposition: :inline), class: "link text-xs", target: "_blank" %><% end %>
      +
    • <% end %>
    + <% end %> + + <% if @share.maintenance? %> +

    Logbook

    + <% if @logbook.any? %><% @logbook.each do |e| %> + + <% end %>
    <%= e.date %><%= LogbookEntry::LOG_TYPES[e.log_type] %><%= hours(e.aircraft_hours_at_entry) %><%= e.text %><%= e.signoff_person %>
    + <% else %><%= empty_state "No entries." %><% end %>
    + +
    +

    Inspection History

    + <% @inspection_history.each do |r| %><% end %>
    <%= r.date %><%= r.inspection_type.name %><%= hours(r.hours_at_inspection) %>
    +

    AD Compliance History

    + <% @ad_history.each do |c| %><% end %>
    <%= c.date_complied %><%= c.airworthiness_directive.name %><%= c.compliance_notes %>
    +
    + +

    Major Repairs & Alterations

    + <% if @major_records.any? %><% @major_records.each do |r| %><% end %>
    <%= r.date_performed %><%= r.type_label %><%= r.title %>
    <%= r.description %>
    <%= r.stc_number %>
    + <% else %><%= empty_state "None recorded." %><% end %>
    + +

    Resolved Squawks

    + <% if @resolved_squawks.any? %>
      <% @resolved_squawks.each do |s| %>
    • <%= squawk_priority_badge(s) %> <%= s.issue_reported %> resolved <%= s.resolved_at&.to_date %>
    • <% end %>
    + <% else %><%= empty_state "None." %><% end %>
    + <% end %> +
    diff --git a/app/views/squawks/_form.html.erb b/app/views/squawks/_form.html.erb new file mode 100644 index 0000000..7fe8edb --- /dev/null +++ b/app/views/squawks/_form.html.erb @@ -0,0 +1,15 @@ +<%= form_with model: [aircraft, squawk], 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" %> + <% if squawk.persisted? %><%= f.field :notes, as: :textarea, rows: 3 %><% end %> +
    + <%= f.submit squawk.new_record? ? "Report Squawk" : "Save" %> + <%= link_to "Cancel", aircraft_squawks_path(aircraft), class: "btn-secondary" %> +
    +<% end %> +<% if squawk.persisted? && owner? %> +
    <%= delete_button "Delete squawk", aircraft_squawk_path(aircraft, squawk) %>
    +<% end %> diff --git a/app/views/squawks/_table.html.erb b/app/views/squawks/_table.html.erb new file mode 100644 index 0000000..7b4eef6 --- /dev/null +++ b/app/views/squawks/_table.html.erb @@ -0,0 +1,25 @@ +
    + + + + <% squawks.each do |s| %> + + + + + + + + <% end %> + +
    PriorityIssueComponentReported
    <%= 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 %> + <% if s.notes.present? %>
    <%= s.notes %>
    <% end %> +
    <%= s.component&.to_s || "—" %><%= s.created_at.to_date %>
    <%= s.reported_by&.display_name %>
    + <% if owner? %> + <%= button_to "Resolve", resolve_aircraft_squawk_path(aircraft, s), method: :patch, class: "btn-secondary btn-sm", form: { class: "inline" } %> + <%= link_to "Edit", edit_aircraft_squawk_path(aircraft, s), class: "btn-secondary btn-sm" %> + <% end %> +
    +
    diff --git a/app/views/squawks/edit.html.erb b/app/views/squawks/edit.html.erb new file mode 100644 index 0000000..c391eeb --- /dev/null +++ b/app/views/squawks/edit.html.erb @@ -0,0 +1,3 @@ +<% content_for :title, "Edit Squawk" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, squawk: @squawk %> diff --git a/app/views/squawks/index.html.erb b/app/views/squawks/index.html.erb new file mode 100644 index 0000000..95a4110 --- /dev/null +++ b/app/views/squawks/index.html.erb @@ -0,0 +1,31 @@ +<% content_for :title, "#{@aircraft.tail_number} Squawks" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
    +
    +

    Open Squawks

    + <%= link_to "+ Report Squawk", new_aircraft_squawk_path(@aircraft), class: "btn-primary" %> +
    + <% if @active.any? %><%= render "squawks/table", squawks: @active, aircraft: @aircraft %><% else %><%= empty_state "No open squawks." %><% end %> +
    + +
    +

    Resolved

    + <% if @resolved.any? %> + + + + <% @resolved.each do |s| %> + + + + + + + + <% end %> + +
    PriorityIssueResolutionResolved
    <%= squawk_priority_badge(s) %><%= s.issue_reported %><%= 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 %>
    + <% else %> + <%= empty_state "No resolved squawks." %> + <% end %> +
    diff --git a/app/views/squawks/new.html.erb b/app/views/squawks/new.html.erb new file mode 100644 index 0000000..58c3e0a --- /dev/null +++ b/app/views/squawks/new.html.erb @@ -0,0 +1,3 @@ +<% content_for :title, "Report Squawk" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, squawk: @squawk %> diff --git a/bin/brakeman b/bin/brakeman new file mode 100755 index 0000000..ace1c9b --- /dev/null +++ b/bin/brakeman @@ -0,0 +1,7 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +ARGV.unshift("--ensure-latest") + +load Gem.bin_path("brakeman", "brakeman") diff --git a/bin/dev b/bin/dev new file mode 100755 index 0000000..ad72c7d --- /dev/null +++ b/bin/dev @@ -0,0 +1,16 @@ +#!/usr/bin/env sh + +if ! gem list foreman -i --silent; then + echo "Installing foreman..." + gem install foreman +fi + +# Default to port 3000 if not specified +export PORT="${PORT:-3000}" + +# Let the debug gem allow remote connections, +# but avoid loading until `debugger` is called +export RUBY_DEBUG_OPEN="true" +export RUBY_DEBUG_LAZY="true" + +exec foreman start -f Procfile.dev "$@" diff --git a/bin/docker-entrypoint b/bin/docker-entrypoint new file mode 100755 index 0000000..57567d6 --- /dev/null +++ b/bin/docker-entrypoint @@ -0,0 +1,14 @@ +#!/bin/bash -e + +# Enable jemalloc for reduced memory usage and latency. +if [ -z "${LD_PRELOAD+x}" ]; then + LD_PRELOAD=$(find /usr/lib -name libjemalloc.so.2 -print -quit) + export LD_PRELOAD +fi + +# If running the rails server then create or migrate existing database +if [ "${@: -2:1}" == "./bin/rails" ] && [ "${@: -1:1}" == "server" ]; then + ./bin/rails db:prepare +fi + +exec "${@}" diff --git a/bin/importmap b/bin/importmap new file mode 100755 index 0000000..36502ab --- /dev/null +++ b/bin/importmap @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby + +require_relative "../config/application" +require "importmap/commands" diff --git a/bin/jobs b/bin/jobs new file mode 100755 index 0000000..dcf59f3 --- /dev/null +++ b/bin/jobs @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby + +require_relative "../config/environment" +require "solid_queue/cli" + +SolidQueue::Cli.start(ARGV) diff --git a/bin/kamal b/bin/kamal new file mode 100755 index 0000000..77f72b4 --- /dev/null +++ b/bin/kamal @@ -0,0 +1,16 @@ +#!/usr/bin/env ruby3.2 +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'kamal' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("kamal", "kamal") diff --git a/bin/rails b/bin/rails new file mode 100755 index 0000000..efc0377 --- /dev/null +++ b/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/bin/rake b/bin/rake new file mode 100755 index 0000000..4fbf10b --- /dev/null +++ b/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/bin/rubocop b/bin/rubocop new file mode 100755 index 0000000..40330c0 --- /dev/null +++ b/bin/rubocop @@ -0,0 +1,8 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +# explicit rubocop config increases performance slightly while avoiding config confusion. +ARGV.unshift("--config", File.expand_path("../.rubocop.yml", __dir__)) + +load Gem.bin_path("rubocop", "rubocop") diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..be3db3c --- /dev/null +++ b/bin/setup @@ -0,0 +1,34 @@ +#!/usr/bin/env ruby +require "fileutils" + +APP_ROOT = File.expand_path("..", __dir__) + +def system!(*args) + system(*args, exception: true) +end + +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. + # Add necessary setup steps to this file. + + puts "== Installing dependencies ==" + system("bundle check") || system!("bundle install") + + # puts "\n== Copying sample files ==" + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" + # end + + puts "\n== Preparing database ==" + system! "bin/rails db:prepare" + + puts "\n== Removing old logs and tempfiles ==" + system! "bin/rails log:clear tmp:clear" + + unless ARGV.include?("--skip-server") + puts "\n== Starting development server ==" + STDOUT.flush # flush the output before exec(2) so that it displays + exec "bin/dev" + end +end diff --git a/bin/thrust b/bin/thrust new file mode 100755 index 0000000..36bde2d --- /dev/null +++ b/bin/thrust @@ -0,0 +1,5 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("thruster", "thrust") diff --git a/config.ru b/config.ru new file mode 100644 index 0000000..4a3c09a --- /dev/null +++ b/config.ru @@ -0,0 +1,6 @@ +# This file is used by Rack-based servers to start the application. + +require_relative "config/environment" + +run Rails.application +Rails.application.load_server diff --git a/config/application.rb b/config/application.rb new file mode 100644 index 0000000..f679f01 --- /dev/null +++ b/config/application.rb @@ -0,0 +1,30 @@ +require_relative "boot" + +require "rails/all" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module SimpleAircraftManager + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 8.0 + + # Please, add to the `ignore` list any other `lib` subdirectories that do + # not contain `.rb` files, or that should not be reloaded or eager loaded. + # Common ones are `templates`, `generators`, or `middleware`, for example. + config.autoload_lib(ignore: %w[assets tasks]) + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + + # Uploads are served as-is (no image variants), so libvips/image_processing is not needed. + config.active_storage.variant_processor = :disabled + end +end diff --git a/config/boot.rb b/config/boot.rb new file mode 100644 index 0000000..988a5dd --- /dev/null +++ b/config/boot.rb @@ -0,0 +1,4 @@ +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +require "bundler/setup" # Set up gems listed in the Gemfile. +require "bootsnap/setup" # Speed up boot time by caching expensive operations. diff --git a/config/cable.yml b/config/cable.yml new file mode 100644 index 0000000..b9adc5a --- /dev/null +++ b/config/cable.yml @@ -0,0 +1,17 @@ +# Async adapter only works within the same process, so for manually triggering cable updates from a console, +# and seeing results in the browser, you must do so from the web console (running inside the dev process), +# not a terminal started via bin/rails console! Add "console" to any action or any ERB template view +# to make the web console appear. +development: + adapter: async + +test: + adapter: test + +production: + adapter: solid_cable + connects_to: + database: + writing: cable + polling_interval: 0.1.seconds + message_retention: 1.day diff --git a/config/cache.yml b/config/cache.yml new file mode 100644 index 0000000..19d4908 --- /dev/null +++ b/config/cache.yml @@ -0,0 +1,16 @@ +default: &default + store_options: + # Cap age of oldest cache entry to fulfill retention policies + # max_age: <%= 60.days.to_i %> + max_size: <%= 256.megabytes %> + namespace: <%= Rails.env %> + +development: + <<: *default + +test: + <<: *default + +production: + database: cache + <<: *default diff --git a/config/credentials.yml.enc b/config/credentials.yml.enc new file mode 100644 index 0000000..c625c97 --- /dev/null +++ b/config/credentials.yml.enc @@ -0,0 +1 @@ +7Mikb0spSSLzAF+jRrFycGwXntTOF7neXVGHr65dhlxtBDsx9GGiwlZlW/Zg16A1jdbk/ZXY/7NUR7Q2vHmDs3qwPlEpBFxMHmJKDp9sjmc9RDZMoUZrHrhZCNYFa/RiMo7e4DxoArCL0hALwF/udtMLCnoO3RCALqAx5dt/DGUku7TKC8yKs2lS4j/aU93p3Xqw7sMcYP50QFRKEEp6vje2PYaHBzO8fsRUkRBflVfTeDOFe3P445B7IzomZx4NPI7aC4IqP5Rh1WGjifPtZEoB63/gMZx9otWyPRPz1nXdVwhIjBh/xndRKHp6l0sHNJxRGQA8tg0QW96yfZFHFWQhv62xhMPeqgEloNz8hgFbmHsXUHdzSAxEoa3rl4S88an0jyj8ApS4BYOdGa01wU69r6LolxZE801iKX+XGc0QN4Mhg+yST3UjfSWSmviYF81UhrAhhzaPjtDyvrVx8J3AGI56JdsNANerf59Hu0ez4snkcihgRS4F--zJOOzTZv/zd5rXwk--nQeOe7rhofL05Ldg+nc+UA== \ No newline at end of file diff --git a/config/database.yml b/config/database.yml new file mode 100644 index 0000000..2640cb5 --- /dev/null +++ b/config/database.yml @@ -0,0 +1,41 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem "sqlite3" +# +default: &default + adapter: sqlite3 + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + database: storage/development.sqlite3 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: storage/test.sqlite3 + + +# Store production database in the storage/ directory, which by default +# is mounted as a persistent Docker volume in config/deploy.yml. +production: + primary: + <<: *default + database: storage/production.sqlite3 + cache: + <<: *default + database: storage/production_cache.sqlite3 + migrations_paths: db/cache_migrate + queue: + <<: *default + database: storage/production_queue.sqlite3 + migrations_paths: db/queue_migrate + cable: + <<: *default + database: storage/production_cable.sqlite3 + migrations_paths: db/cable_migrate diff --git a/config/deploy.yml b/config/deploy.yml new file mode 100644 index 0000000..05449ff --- /dev/null +++ b/config/deploy.yml @@ -0,0 +1,116 @@ +# Name of your application. Used to uniquely configure containers. +service: simple_aircraft_manager + +# Name of the container image. +image: your-user/simple_aircraft_manager + +# Deploy to these servers. +servers: + web: + - 192.168.0.1 + # job: + # hosts: + # - 192.168.0.1 + # cmd: bin/jobs + +# Enable SSL auto certification via Let's Encrypt and allow for multiple apps on a single web server. +# Remove this section when using multiple web servers and ensure you terminate SSL at your load balancer. +# +# Note: If using Cloudflare, set encryption mode in SSL/TLS setting to "Full" to enable CF-to-app encryption. +proxy: + ssl: true + host: app.example.com + +# Credentials for your image host. +registry: + # Specify the registry server, if you're not using Docker Hub + # server: registry.digitalocean.com / ghcr.io / ... + username: your-user + + # Always use an access token rather than real password when possible. + password: + - KAMAL_REGISTRY_PASSWORD + +# Inject ENV variables into containers (secrets come from .kamal/secrets). +env: + secret: + - RAILS_MASTER_KEY + clear: + # Run the Solid Queue Supervisor inside the web server's Puma process to do jobs. + # When you start using multiple servers, you should split out job processing to a dedicated machine. + SOLID_QUEUE_IN_PUMA: true + + # Set number of processes dedicated to Solid Queue (default: 1) + # JOB_CONCURRENCY: 3 + + # Set number of cores available to the application on each server (default: 1). + # WEB_CONCURRENCY: 2 + + # Match this to any external database server to configure Active Record correctly + # Use simple_aircraft_manager-db for a db accessory server on same machine via local kamal docker network. + # DB_HOST: 192.168.0.2 + + # Log everything from Rails + # RAILS_LOG_LEVEL: debug + +# Aliases are triggered with "bin/kamal ". You can overwrite arguments on invocation: +# "bin/kamal logs -r job" will tail logs from the first server in the job section. +aliases: + console: app exec --interactive --reuse "bin/rails console" + shell: app exec --interactive --reuse "bash" + logs: app logs -f + dbc: app exec --interactive --reuse "bin/rails dbconsole" + + +# Use a persistent storage volume for sqlite database files and local Active Storage files. +# Recommended to change this to a mounted volume path that is backed up off server. +volumes: + - "simple_aircraft_manager_storage:/rails/storage" + + +# Bridge fingerprinted assets, like JS and CSS, between versions to avoid +# hitting 404 on in-flight requests. Combines all files from new and old +# version inside the asset_path. +asset_path: /rails/public/assets + +# Configure the image builder. +builder: + arch: amd64 + + # # Build image via remote server (useful for faster amd64 builds on arm64 computers) + # remote: ssh://docker@docker-builder-server + # + # # Pass arguments and secrets to the Docker build process + # args: + # RUBY_VERSION: ruby-3.2.3 + # secrets: + # - GITHUB_TOKEN + # - RAILS_MASTER_KEY + +# Use a different ssh user than root +# ssh: +# user: app + +# Use accessory services (secrets come from .kamal/secrets). +# accessories: +# db: +# image: mysql:8.0 +# host: 192.168.0.2 +# # Change to 3306 to expose port to the world instead of just local network. +# port: "127.0.0.1:3306:3306" +# env: +# clear: +# MYSQL_ROOT_HOST: '%' +# secret: +# - MYSQL_ROOT_PASSWORD +# files: +# - config/mysql/production.cnf:/etc/mysql/my.cnf +# - db/production.sql:/docker-entrypoint-initdb.d/setup.sql +# directories: +# - data:/var/lib/mysql +# redis: +# image: redis:7.0 +# host: 192.168.0.2 +# port: 6379 +# directories: +# - data:/data diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 0000000..cac5315 --- /dev/null +++ b/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/config/environments/development.rb b/config/environments/development.rb new file mode 100644 index 0000000..4cc21c4 --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,72 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Make code changes take effect immediately without server restart. + config.enable_reloading = true + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable server timing. + config.server_timing = true + + # Enable/disable Action Controller caching. By default Action Controller caching is disabled. + # Run rails dev:cache to toggle Action Controller caching. + if Rails.root.join("tmp/caching-dev.txt").exist? + config.action_controller.perform_caching = true + config.action_controller.enable_fragment_cache_logging = true + config.public_file_server.headers = { "cache-control" => "public, max-age=#{2.days.to_i}" } + else + config.action_controller.perform_caching = false + end + + # Change to :null_store to avoid any caching. + config.cache_store = :memory_store + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + # Make template changes take effect immediately. + config.action_mailer.perform_caching = false + + # Set localhost to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "localhost", port: 3000 } + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Append comments with runtime information tags to SQL queries in logs. + config.active_record.query_log_tags_enabled = true + + # Highlight code that enqueued background job in logs. + config.active_job.verbose_enqueue_logs = true + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + config.action_view.annotate_rendered_view_with_filenames = true + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true + + # Raise error when a before_action's only/except options reference missing actions. + config.action_controller.raise_on_missing_callback_actions = true + + # Apply autocorrection by RuboCop to files generated by `bin/rails generate`. + # config.generators.apply_rubocop_autocorrect_after_generate! +end diff --git a/config/environments/production.rb b/config/environments/production.rb new file mode 100644 index 0000000..500b382 --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,106 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.enable_reloading = false + + # Eager load code on boot for better performance and memory savings (ignored by Rake tasks). + config.eager_load = true + + # Full error reports are disabled. + config.consider_all_requests_local = false + + # Turn on fragment caching in view templates. + config.action_controller.perform_caching = true + + # Cache assets for far-future expiry since they are all digest stamped. + config.public_file_server.headers = { "cache-control" => "public, max-age=#{1.year.to_i}" } + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Assume all access to the app is happening through a SSL-terminating reverse proxy. + # Set FORCE_SSL=false when serving plain HTTP (e.g. on a home LAN without a TLS proxy). + config.assume_ssl = ENV.fetch("FORCE_SSL", "true") == "true" + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + config.force_ssl = ENV.fetch("FORCE_SSL", "true") == "true" + + # Skip http-to-https redirect for the default health check endpoint. + config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } + + # Log to STDOUT with the current request id as a default log tag. + config.log_tags = [ :request_id ] + config.logger = ActiveSupport::TaggedLogging.logger(STDOUT) + + # Change to "debug" to log everything (including potentially personally-identifiable information!) + config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") + + # Prevent health checks from clogging up the logs. + config.silence_healthcheck_path = "/up" + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Replace the default in-process memory cache store with a durable alternative. + config.cache_store = :solid_cache_store + + # Replace the default in-process and non-durable queuing backend for Active Job. + config.active_job.queue_adapter = :solid_queue + config.solid_queue.connects_to = { database: { writing: :queue } } + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Set host to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { + host: ENV.fetch("APP_HOST", "localhost"), + protocol: ENV.fetch("FORCE_SSL", "true") == "true" ? "https" : "http" + } + # Password-reset emails. Configure SMTP_ADDRESS (and friends) to enable. + if ENV["SMTP_ADDRESS"].present? + config.action_mailer.delivery_method = :smtp + config.action_mailer.smtp_settings = { + address: ENV["SMTP_ADDRESS"], + port: ENV.fetch("SMTP_PORT", 587).to_i, + user_name: ENV["SMTP_USERNAME"], + password: ENV["SMTP_PASSWORD"], + authentication: :plain, + enable_starttls_auto: true + }.compact + end + + # Specify outgoing SMTP server. Remember to add smtp/* credentials via rails credentials:edit. + # config.action_mailer.smtp_settings = { + # user_name: Rails.application.credentials.dig(:smtp, :user_name), + # password: Rails.application.credentials.dig(:smtp, :password), + # address: "smtp.example.com", + # port: 587, + # authentication: :plain + # } + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false + + # Only use :id for inspections in production. + config.active_record.attributes_for_inspect = [ :id ] + + # Enable DNS rebinding protection and other `Host` header attacks. + # config.hosts = [ + # "example.com", # Allow requests from example.com + # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` + # ] + # + # Skip DNS rebinding protection for the default health check endpoint. + # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } +end diff --git a/config/environments/test.rb b/config/environments/test.rb new file mode 100644 index 0000000..c2095b1 --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,53 @@ +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # While tests run files are not watched, reloading is not necessary. + config.enable_reloading = false + + # Eager loading loads your entire application. When running a single test locally, + # this is usually not necessary, and can slow down your test suite. However, it's + # recommended that you enable it in continuous integration systems to ensure eager + # loading is working properly before deploying your code. + config.eager_load = ENV["CI"].present? + + # Configure public file server for tests with cache-control for performance. + config.public_file_server.headers = { "cache-control" => "public, max-age=3600" } + + # Show full error reports. + config.consider_all_requests_local = true + config.cache_store = :null_store + + # Render exception templates for rescuable exceptions and raise for other exceptions. + config.action_dispatch.show_exceptions = :rescuable + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + config.active_storage.service = :test + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Set host to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "example.com" } + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Raise error when a before_action's only/except options reference missing actions. + config.action_controller.raise_on_missing_callback_actions = true +end diff --git a/config/importmap.rb b/config/importmap.rb new file mode 100644 index 0000000..6fa0453 --- /dev/null +++ b/config/importmap.rb @@ -0,0 +1,9 @@ +# Pin npm packages by running ./bin/importmap + +pin "application" +pin "@hotwired/turbo-rails", to: "turbo.min.js" +pin "@hotwired/stimulus", to: "stimulus.min.js" +pin "@hotwired/stimulus-loading", to: "stimulus-loading.js" +pin_all_from "app/javascript/controllers", under: "controllers" +pin "chartkick", to: "chartkick.js" +pin "Chart.bundle", to: "Chart.bundle.js" diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb new file mode 100644 index 0000000..4873244 --- /dev/null +++ b/config/initializers/assets.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = "1.0" + +# Add additional assets to the asset load path. +# Rails.application.config.assets.paths << Emoji.images_path diff --git a/config/initializers/content_security_policy.rb b/config/initializers/content_security_policy.rb new file mode 100644 index 0000000..b3076b3 --- /dev/null +++ b/config/initializers/content_security_policy.rb @@ -0,0 +1,25 @@ +# Be sure to restart your server when you modify this file. + +# Define an application-wide content security policy. +# See the Securing Rails Applications Guide for more information: +# https://guides.rubyonrails.org/security.html#content-security-policy-header + +# Rails.application.configure do +# config.content_security_policy do |policy| +# policy.default_src :self, :https +# policy.font_src :self, :https, :data +# policy.img_src :self, :https, :data +# policy.object_src :none +# policy.script_src :self, :https +# policy.style_src :self, :https +# # Specify URI for violation reports +# # policy.report_uri "/csp-violation-report-endpoint" +# end +# +# # Generate session nonces for permitted importmap, inline scripts, and inline styles. +# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } +# config.content_security_policy_nonce_directives = %w(script-src style-src) +# +# # Report violations without enforcing the policy. +# # config.content_security_policy_report_only = true +# end diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000..c0b717f --- /dev/null +++ b/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. +# Use this to limit dissemination of sensitive information. +# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc +] diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb new file mode 100644 index 0000000..c49a61c --- /dev/null +++ b/config/initializers/inflections.rb @@ -0,0 +1,4 @@ +# "aircraft" is both singular and plural. +ActiveSupport::Inflector.inflections(:en) do |inflect| + inflect.uncountable %w[aircraft] +end diff --git a/config/locales/en.yml b/config/locales/en.yml new file mode 100644 index 0000000..6c349ae --- /dev/null +++ b/config/locales/en.yml @@ -0,0 +1,31 @@ +# Files in the config/locales directory are used for internationalization and +# are automatically loaded by Rails. If you want to use locales other than +# English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t "hello" +# +# In views, this is aliased to just `t`: +# +# <%= t("hello") %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more about the API, please read the Rails Internationalization guide +# at https://guides.rubyonrails.org/i18n.html. +# +# Be aware that YAML interprets the following case-insensitive strings as +# booleans: `true`, `false`, `on`, `off`, `yes`, `no`. Therefore, these strings +# must be quoted to be interpreted as strings. For example: +# +# en: +# "yes": yup +# enabled: "ON" + +en: + hello: "Hello world" diff --git a/config/puma.rb b/config/puma.rb new file mode 100644 index 0000000..a248513 --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,41 @@ +# This configuration file will be evaluated by Puma. The top-level methods that +# are invoked here are part of Puma's configuration DSL. For more information +# about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. +# +# Puma starts a configurable number of processes (workers) and each process +# serves each request in a thread from an internal thread pool. +# +# You can control the number of workers using ENV["WEB_CONCURRENCY"]. You +# should only set this value when you want to run 2 or more workers. The +# default is already 1. +# +# The ideal number of threads per worker depends both on how much time the +# application spends waiting for IO operations and on how much you wish to +# prioritize throughput over latency. +# +# As a rule of thumb, increasing the number of threads will increase how much +# traffic a given process can handle (throughput), but due to CRuby's +# Global VM Lock (GVL) it has diminishing returns and will degrade the +# response time (latency) of the application. +# +# The default is set to 3 threads as it's deemed a decent compromise between +# throughput and latency for the average Rails application. +# +# Any libraries that use a connection pool or another resource pool should +# be configured to provide at least as many connections as the number of +# threads. This includes Active Record's `pool` parameter in `database.yml`. +threads_count = ENV.fetch("RAILS_MAX_THREADS", 3) +threads threads_count, threads_count + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +port ENV.fetch("PORT", 3000) + +# Allow puma to be restarted by `bin/rails restart` command. +plugin :tmp_restart + +# Run the Solid Queue supervisor inside of Puma for single-server deployments +plugin :solid_queue if ENV["SOLID_QUEUE_IN_PUMA"] + +# Specify the PID file. Defaults to tmp/pids/server.pid in development. +# In other environments, only set the PID file if requested. +pidfile ENV["PIDFILE"] if ENV["PIDFILE"] diff --git a/config/queue.yml b/config/queue.yml new file mode 100644 index 0000000..6b14360 --- /dev/null +++ b/config/queue.yml @@ -0,0 +1,18 @@ +default: &default + dispatchers: + - polling_interval: 1 + batch_size: 500 + workers: + - queues: "*" + threads: 3 + processes: <%= ENV.fetch("JOB_CONCURRENCY", 1) %> + polling_interval: 1 + +development: + <<: *default + +test: + <<: *default + +production: + <<: *default diff --git a/config/recurring.yml b/config/recurring.yml new file mode 100644 index 0000000..b4207f9 --- /dev/null +++ b/config/recurring.yml @@ -0,0 +1,15 @@ +# examples: +# periodic_cleanup: +# class: CleanSoftDeletedRecordsJob +# queue: background +# args: [ 1000, { batch_size: 500 } ] +# schedule: every hour +# periodic_cleanup_with_command: +# command: "SoftDeletedRecord.due.delete_all" +# priority: 2 +# schedule: at 5am every day + +production: + clear_solid_queue_finished_jobs: + command: "SolidQueue::Job.clear_finished_in_batches(sleep_between_batches: 0.3)" + schedule: every hour at minute 12 diff --git a/config/routes.rb b/config/routes.rb new file mode 100644 index 0000000..706c183 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,50 @@ +Rails.application.routes.draw do + resource :session + resources :passwords, param: :token + resource :setup, only: %i[new create], controller: "setup" + resource :profile, only: %i[edit update] + + resources :aircraft do + member do + patch :hours, action: :update_hours + end + + resources :components do + member { post :reset_service } + end + resources :squawks, except: :show do + member do + patch :resolve + patch :reopen + end + end + resources :notes, except: :show + resources :flight_logs, only: %i[index new create show destroy] + resources :consumable_records, path: "consumables", except: :show + resources :logbook_entries + resources :documents + resources :document_collections, except: %i[index show] + resources :inspections, only: :index + resources :inspection_types, except: %i[index show] + resources :inspection_records, except: %i[index show] + resources :airworthiness_directives, path: "ads", except: :show do + collection { post :attach } + end + resources :ad_compliances, except: %i[index show] + resources :major_records + resources :aircraft_roles, path: "access", only: %i[index create update destroy] + resources :share_tokens, only: %i[create destroy] + resources :events, only: :index + end + + # Public read-only share links (no login). + get "shared/:token", to: "shared#show", as: :shared + + namespace :admin do + resources :users, except: :show + resources :component_types, except: :show + end + + get "up" => "rails/health#show", as: :rails_health_check + root "aircraft#index" +end diff --git a/config/storage.yml b/config/storage.yml new file mode 100644 index 0000000..4942ab6 --- /dev/null +++ b/config/storage.yml @@ -0,0 +1,34 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket-<%= Rails.env %> + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket-<%= Rails.env %> + +# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/db/cable_schema.rb b/db/cable_schema.rb new file mode 100644 index 0000000..2366660 --- /dev/null +++ b/db/cable_schema.rb @@ -0,0 +1,11 @@ +ActiveRecord::Schema[7.1].define(version: 1) do + create_table "solid_cable_messages", force: :cascade do |t| + t.binary "channel", limit: 1024, null: false + t.binary "payload", limit: 536870912, null: false + t.datetime "created_at", null: false + t.integer "channel_hash", limit: 8, null: false + t.index ["channel"], name: "index_solid_cable_messages_on_channel" + t.index ["channel_hash"], name: "index_solid_cable_messages_on_channel_hash" + t.index ["created_at"], name: "index_solid_cable_messages_on_created_at" + end +end diff --git a/db/cache_schema.rb b/db/cache_schema.rb new file mode 100644 index 0000000..81a410d --- /dev/null +++ b/db/cache_schema.rb @@ -0,0 +1,12 @@ +ActiveRecord::Schema[7.2].define(version: 1) do + create_table "solid_cache_entries", force: :cascade do |t| + t.binary "key", limit: 1024, null: false + t.binary "value", limit: 536870912, null: false + t.datetime "created_at", null: false + t.integer "key_hash", limit: 8, null: false + t.integer "byte_size", limit: 4, null: false + t.index ["byte_size"], name: "index_solid_cache_entries_on_byte_size" + t.index ["key_hash", "byte_size"], name: "index_solid_cache_entries_on_key_hash_and_byte_size" + t.index ["key_hash"], name: "index_solid_cache_entries_on_key_hash", unique: true + end +end diff --git a/db/migrate/20261104222307_create_users.rb b/db/migrate/20261104222307_create_users.rb new file mode 100644 index 0000000..2075edf --- /dev/null +++ b/db/migrate/20261104222307_create_users.rb @@ -0,0 +1,11 @@ +class CreateUsers < ActiveRecord::Migration[8.0] + def change + create_table :users do |t| + t.string :email_address, null: false + t.string :password_digest, null: false + + t.timestamps + end + add_index :users, :email_address, unique: true + end +end diff --git a/db/migrate/20261104222308_create_sessions.rb b/db/migrate/20261104222308_create_sessions.rb new file mode 100644 index 0000000..8102f13 --- /dev/null +++ b/db/migrate/20261104222308_create_sessions.rb @@ -0,0 +1,11 @@ +class CreateSessions < ActiveRecord::Migration[8.0] + def change + create_table :sessions do |t| + t.references :user, null: false, foreign_key: true + t.string :ip_address + t.string :user_agent + + t.timestamps + end + end +end diff --git a/db/migrate/20261104222309_create_active_storage_tables.active_storage.rb b/db/migrate/20261104222309_create_active_storage_tables.active_storage.rb new file mode 100644 index 0000000..6bd8bd0 --- /dev/null +++ b/db/migrate/20261104222309_create_active_storage_tables.active_storage.rb @@ -0,0 +1,57 @@ +# This migration comes from active_storage (originally 20170806125915) +class CreateActiveStorageTables < ActiveRecord::Migration[7.0] + def change + # Use Active Record's configured type for primary and foreign keys + primary_key_type, foreign_key_type = primary_and_foreign_key_types + + create_table :active_storage_blobs, id: primary_key_type do |t| + t.string :key, null: false + t.string :filename, null: false + t.string :content_type + t.text :metadata + t.string :service_name, null: false + t.bigint :byte_size, null: false + t.string :checksum + + if connection.supports_datetime_with_precision? + t.datetime :created_at, precision: 6, null: false + else + t.datetime :created_at, null: false + end + + t.index [ :key ], unique: true + end + + create_table :active_storage_attachments, id: primary_key_type do |t| + t.string :name, null: false + t.references :record, null: false, polymorphic: true, index: false, type: foreign_key_type + t.references :blob, null: false, type: foreign_key_type + + if connection.supports_datetime_with_precision? + t.datetime :created_at, precision: 6, null: false + else + t.datetime :created_at, null: false + end + + t.index [ :record_type, :record_id, :name, :blob_id ], name: :index_active_storage_attachments_uniqueness, unique: true + t.foreign_key :active_storage_blobs, column: :blob_id + end + + create_table :active_storage_variant_records, id: primary_key_type do |t| + t.belongs_to :blob, null: false, index: false, type: foreign_key_type + t.string :variation_digest, null: false + + t.index [ :blob_id, :variation_digest ], name: :index_active_storage_variant_records_uniqueness, unique: true + t.foreign_key :active_storage_blobs, column: :blob_id + end + end + + private + def primary_and_foreign_key_types + config = Rails.configuration.generators + setting = config.options[config.orm][:primary_key_type] + primary_key_type = setting || :primary_key + foreign_key_type = setting || :bigint + [ primary_key_type, foreign_key_type ] + end +end diff --git a/db/migrate/20261104222400_create_aircraft_domain.rb b/db/migrate/20261104222400_create_aircraft_domain.rb new file mode 100644 index 0000000..d13bd79 --- /dev/null +++ b/db/migrate/20261104222400_create_aircraft_domain.rb @@ -0,0 +1,261 @@ +class CreateAircraftDomain < ActiveRecord::Migration[8.0] + def change + add_column :users, :name, :string + add_column :users, :admin, :boolean, null: false, default: false + + create_table :aircraft do |t| + t.string :tail_number, null: false + t.string :make + t.string :model + t.string :serial_number + t.text :description + t.date :purchased + t.string :status, null: false, default: "AVAILABLE" + t.decimal :tach_time, precision: 8, scale: 1, null: false, default: 0 + t.decimal :tach_time_offset, precision: 8, scale: 1, null: false, default: 0 + t.decimal :hobbs_time, precision: 8, scale: 1, null: false, default: 0 + t.decimal :hobbs_time_offset, precision: 8, scale: 1, null: false, default: 0 + t.boolean :airworthiness_enforcement, null: false, default: false + t.timestamps + end + + create_table :aircraft_roles do |t| + t.references :aircraft, null: false, foreign_key: true + t.references :user, null: false, foreign_key: true + t.string :role, null: false + t.timestamps + end + add_index :aircraft_roles, [ :aircraft_id, :user_id ], unique: true + + create_table :aircraft_notes do |t| + t.references :aircraft, null: false, foreign_key: true + t.references :user, foreign_key: { on_delete: :nullify } + t.text :text, null: false + t.boolean :public, null: false, default: false + t.datetime :edited_at + t.timestamps + end + + create_table :aircraft_events do |t| + t.references :aircraft, null: false, foreign_key: true + t.references :user, foreign_key: { on_delete: :nullify } + t.string :category, null: false + t.string :event_name, null: false + t.text :notes + t.datetime :created_at, null: false + end + add_index :aircraft_events, [ :aircraft_id, :created_at ] + + create_table :share_tokens do |t| + t.references :aircraft, null: false, foreign_key: true + t.references :created_by, foreign_key: { to_table: :users, on_delete: :nullify } + t.string :token, null: false + t.string :label + t.string :privilege, null: false, default: "status" + t.datetime :expires_at + t.timestamps + end + add_index :share_tokens, :token, unique: true + + create_table :component_types do |t| + t.string :name, null: false + t.boolean :consumable, null: false, default: false + t.timestamps + end + add_index :component_types, :name, unique: true + + create_table :components do |t| + t.references :aircraft, foreign_key: true + t.references :parent_component, foreign_key: { to_table: :components } + t.references :component_type, null: false, foreign_key: true + t.string :manufacturer, null: false + t.string :model, null: false + t.string :serial_number + t.string :install_location + t.text :notes + t.string :status, null: false, default: "SPARE" + t.date :date_in_service, null: false + t.decimal :hours_in_service, precision: 8, scale: 1, null: false, default: 0 + t.decimal :hours_since_overhaul, precision: 8, scale: 1, null: false, default: 0 + t.date :overhaul_date + t.integer :tbo_hours + t.integer :tbo_days + t.integer :inspection_hours + t.integer :inspection_days + t.integer :replacement_hours + t.integer :replacement_days + t.boolean :tbo_critical, null: false, default: true + t.boolean :on_condition, null: false, default: false + t.boolean :inspection_critical, null: false, default: true + t.boolean :replacement_critical, null: false, default: false + t.timestamps + end + + create_table :document_collections do |t| + t.references :aircraft, null: false, foreign_key: true + t.string :name, null: false + t.text :description + t.string :visibility, null: false, default: "private" + t.boolean :starred, null: false, default: false + t.timestamps + end + + create_table :documents do |t| + t.references :aircraft, null: false, foreign_key: true + t.references :document_collection, foreign_key: true + t.string :doc_type, null: false, default: "OTHER" + t.string :name, null: false + t.text :description + # nil = inherit from collection (or private when uncollected) + t.string :visibility + t.timestamps + end + + create_table :logbook_entries do |t| + t.references :aircraft, null: false, foreign_key: true + t.references :document, foreign_key: { on_delete: :nullify } # scanned page(s) + t.string :log_type, null: false, default: "AC" + t.string :entry_type, null: false, default: "MAINTENANCE" + t.date :date, null: false + t.text :text, null: false + t.text :signoff_person + t.string :signoff_location + t.decimal :aircraft_hours_at_entry, precision: 8, scale: 1 + t.integer :page_number + t.timestamps + end + + create_table :squawks do |t| + t.references :aircraft, null: false, foreign_key: true + t.references :component, foreign_key: { on_delete: :nullify } + t.references :reported_by, foreign_key: { to_table: :users, on_delete: :nullify } + t.integer :priority, null: false, default: 0 + t.text :issue_reported + t.text :notes + t.boolean :resolved, null: false, default: false + t.datetime :resolved_at + t.timestamps + end + + create_table :inspection_types do |t| + t.string :name, null: false + t.boolean :recurring, null: false, default: false + t.boolean :required, null: false, default: true + t.decimal :recurring_hours, precision: 8, scale: 1, null: false, default: 0 + t.integer :recurring_days, null: false, default: 0 + t.integer :recurring_months, null: false, default: 0 + t.timestamps + end + create_join_table :aircraft, :inspection_types do |t| + t.index [ :aircraft_id, :inspection_type_id ], unique: true, name: "idx_aircraft_inspection_types" + end + create_join_table :components, :inspection_types do |t| + t.index [ :component_id, :inspection_type_id ], unique: true, name: "idx_component_inspection_types" + end + + create_table :inspection_records do |t| + t.references :inspection_type, null: false, foreign_key: true + t.references :aircraft, foreign_key: true + t.references :component, foreign_key: true + t.references :logbook_entry, foreign_key: { on_delete: :nullify } + t.date :date, null: false + t.decimal :aircraft_hours, precision: 8, scale: 1 + t.text :notes + t.timestamps + end + + create_table :airworthiness_directives do |t| + t.string :name, null: false + t.string :short_description, null: false + t.text :required_action + t.string :compliance_type, null: false, default: "standard" + t.text :trigger_condition + t.boolean :recurring, null: false, default: false + t.decimal :recurring_hours, precision: 8, scale: 1, null: false, default: 0 + t.integer :recurring_months, null: false, default: 0 + t.integer :recurring_days, null: false, default: 0 + t.string :bulletin_type, null: false, default: "ad" + t.boolean :mandatory, null: false, default: true + t.references :document, foreign_key: { on_delete: :nullify } + t.timestamps + end + create_join_table :aircraft, :airworthiness_directives do |t| + t.index [ :aircraft_id, :airworthiness_directive_id ], unique: true, name: "idx_aircraft_ads" + end + create_join_table :components, :airworthiness_directives do |t| + t.index [ :component_id, :airworthiness_directive_id ], unique: true, name: "idx_component_ads" + end + + create_table :ad_compliances do |t| + t.references :airworthiness_directive, null: false, foreign_key: true + t.references :aircraft, foreign_key: true + t.references :component, foreign_key: true + t.references :logbook_entry, foreign_key: { on_delete: :nullify } + t.references :inspection_record, foreign_key: { on_delete: :nullify } + t.date :date_complied, null: false + t.text :compliance_notes, null: false + t.boolean :permanent, null: false, default: false + t.decimal :next_due_at_time, precision: 8, scale: 1, null: false, default: 0 + t.decimal :aircraft_hours_at_compliance, precision: 8, scale: 1 + t.timestamps + end + + create_table :major_records do |t| + t.references :aircraft, null: false, foreign_key: true + t.references :component, foreign_key: { on_delete: :nullify } + t.references :form_337_document, foreign_key: { to_table: :documents, on_delete: :nullify } + t.references :stc_document, foreign_key: { to_table: :documents, on_delete: :nullify } + t.references :logbook_entry, foreign_key: { on_delete: :nullify } + t.string :record_type, null: false + t.string :title, null: false + t.text :description + t.date :date_performed, null: false + t.string :performed_by + t.string :stc_number + t.string :stc_holder + t.decimal :aircraft_hours, precision: 8, scale: 1 + t.boolean :has_ica, null: false, default: false + t.text :ica_notes + t.text :notes + t.timestamps + end + + create_table :flight_logs do |t| + t.references :aircraft, null: false, foreign_key: true + t.references :user, foreign_key: { on_delete: :nullify } + t.date :date, null: false + t.decimal :tach_time, precision: 6, scale: 1, null: false + t.decimal :tach_out, precision: 8, scale: 1 + t.decimal :tach_in, precision: 8, scale: 1 + t.decimal :hobbs_time, precision: 6, scale: 1 + t.decimal :hobbs_out, precision: 8, scale: 1 + t.decimal :hobbs_in, precision: 8, scale: 1 + t.string :departure_location + t.string :destination_location + t.text :route + t.decimal :oil_added, precision: 6, scale: 2 + t.string :oil_added_type + t.decimal :oil_level_after, precision: 6, scale: 2 + t.decimal :fuel_added, precision: 8, scale: 2 + t.string :fuel_added_type + t.decimal :fuel_level_after, precision: 8, scale: 2 + t.text :notes + t.timestamps + end + + create_table :consumable_records do |t| + t.references :aircraft, null: false, foreign_key: true + t.references :flight_log, foreign_key: { on_delete: :nullify } + t.string :record_type, null: false + t.date :date, null: false + t.decimal :quantity_added, precision: 6, scale: 2, null: false + t.decimal :level_after, precision: 6, scale: 2 + t.string :consumable_type + t.decimal :flight_hours, precision: 8, scale: 1, null: false + t.text :notes + t.boolean :excluded_from_averages, null: false, default: false + t.timestamps + end + add_index :consumable_records, [ :aircraft_id, :record_type, :flight_hours ] + end +end diff --git a/db/queue_schema.rb b/db/queue_schema.rb new file mode 100644 index 0000000..f9a71da --- /dev/null +++ b/db/queue_schema.rb @@ -0,0 +1,160 @@ +ActiveRecord::Schema[7.1].define(version: 1) do + create_table "solid_queue_blocked_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.string "concurrency_key", null: false + t.datetime "expires_at", null: false + t.datetime "created_at", null: false + t.index [ "concurrency_key", "priority", "job_id" ], name: "index_solid_queue_blocked_executions_for_release" + t.index [ "expires_at", "concurrency_key" ], name: "index_solid_queue_blocked_executions_for_maintenance" + t.index [ "job_id" ], name: "index_solid_queue_blocked_executions_on_job_id", unique: true + end + + create_table "solid_queue_claimed_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.bigint "process_id" + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_claimed_executions_on_job_id", unique: true + t.index [ "process_id", "job_id" ], name: "index_solid_queue_claimed_executions_on_process_id_and_job_id" + end + + create_table "solid_queue_failed_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.text "error" + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_failed_executions_on_job_id", unique: true + end + + create_table "solid_queue_jobs", force: :cascade do |t| + t.string "queue_name", null: false + t.string "class_name", null: false + t.text "arguments" + t.integer "priority", default: 0, null: false + t.string "active_job_id" + t.datetime "scheduled_at" + t.datetime "finished_at" + t.string "concurrency_key" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.bigint "batch_id" + t.index [ "active_job_id" ], name: "index_solid_queue_jobs_on_active_job_id" + t.index [ "batch_id" ], name: "index_solid_queue_jobs_on_batch_id" + t.index [ "class_name" ], name: "index_solid_queue_jobs_on_class_name" + t.index [ "finished_at" ], name: "index_solid_queue_jobs_on_finished_at" + t.index [ "queue_name", "finished_at" ], name: "index_solid_queue_jobs_for_filtering" + t.index [ "scheduled_at", "finished_at" ], name: "index_solid_queue_jobs_for_alerting" + end + + create_table "solid_queue_pauses", force: :cascade do |t| + t.string "queue_name", null: false + t.datetime "created_at", null: false + t.index [ "queue_name" ], name: "index_solid_queue_pauses_on_queue_name", unique: true + end + + create_table "solid_queue_processes", force: :cascade do |t| + t.string "kind", null: false + t.datetime "last_heartbeat_at", null: false + t.bigint "supervisor_id" + t.integer "pid", null: false + t.string "hostname" + t.text "metadata" + t.datetime "created_at", null: false + t.string "name", null: false + t.index [ "last_heartbeat_at" ], name: "index_solid_queue_processes_on_last_heartbeat_at" + t.index [ "name", "supervisor_id" ], name: "index_solid_queue_processes_on_name_and_supervisor_id", unique: true + t.index [ "supervisor_id" ], name: "index_solid_queue_processes_on_supervisor_id" + end + + create_table "solid_queue_ready_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_ready_executions_on_job_id", unique: true + t.index [ "priority", "job_id" ], name: "index_solid_queue_poll_all" + t.index [ "queue_name", "priority", "job_id" ], name: "index_solid_queue_poll_by_queue" + end + + create_table "solid_queue_recurring_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "task_key", null: false + t.datetime "run_at", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_recurring_executions_on_job_id", unique: true + t.index [ "task_key", "run_at" ], name: "index_solid_queue_recurring_executions_on_task_key_and_run_at", unique: true + end + + create_table "solid_queue_recurring_tasks", force: :cascade do |t| + t.string "key", null: false + t.string "schedule", null: false + t.string "command", limit: 2048 + t.string "class_name" + t.text "arguments" + t.string "queue_name" + t.integer "priority", default: 0 + t.boolean "static", default: true, null: false + t.text "description" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "key" ], name: "index_solid_queue_recurring_tasks_on_key", unique: true + t.index [ "static" ], name: "index_solid_queue_recurring_tasks_on_static" + end + + create_table "solid_queue_scheduled_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.datetime "scheduled_at", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_scheduled_executions_on_job_id", unique: true + t.index [ "scheduled_at", "priority", "job_id" ], name: "index_solid_queue_dispatch_all" + end + + create_table "solid_queue_semaphores", force: :cascade do |t| + t.string "key", null: false + t.integer "value", default: 1, null: false + t.datetime "expires_at", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "expires_at" ], name: "index_solid_queue_semaphores_on_expires_at" + t.index [ "key", "value" ], name: "index_solid_queue_semaphores_on_key_and_value" + t.index [ "key" ], name: "index_solid_queue_semaphores_on_key", unique: true + end + + create_table "solid_queue_batches", force: :cascade do |t| + t.string "active_job_batch_id" + t.string "description" + t.text "on_finish" + t.text "on_success" + t.text "on_failure" + t.text "metadata" + t.integer "total_jobs", default: 0, null: false + t.integer "completed_jobs", default: 0, null: false + t.integer "failed_jobs", default: 0, null: false + t.datetime "enqueued_at" + t.datetime "finished_at" + t.datetime "failed_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "active_job_batch_id" ], name: "index_solid_queue_batches_on_active_job_batch_id", unique: true + t.index [ "finished_at" ], name: "index_solid_queue_batches_on_finished_at" + end + + create_table "solid_queue_batch_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.bigint "batch_id", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_batch_executions_on_job_id", unique: true + t.index [ "batch_id" ], name: "index_solid_queue_batch_executions_on_batch_id" + end + + add_foreign_key "solid_queue_batch_executions", "solid_queue_batches", column: "batch_id", on_delete: :cascade + add_foreign_key "solid_queue_batch_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_blocked_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_claimed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_failed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_ready_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_recurring_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_scheduled_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 0000000..a5ff998 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,423 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# This file is the source Rails uses to define your schema when running `bin/rails +# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to +# be faster and is potentially less error prone than running all of your +# migrations from scratch. Old migrations may fail to apply correctly if those +# migrations use external dependencies or application code. +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema[8.0].define(version: 2026_11_04_222400) do + create_table "active_storage_attachments", force: :cascade do |t| + t.string "name", null: false + t.string "record_type", null: false + t.bigint "record_id", null: false + t.bigint "blob_id", null: false + t.datetime "created_at", null: false + t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id" + t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true + end + + create_table "active_storage_blobs", force: :cascade do |t| + t.string "key", null: false + t.string "filename", null: false + t.string "content_type" + t.text "metadata" + t.string "service_name", null: false + t.bigint "byte_size", null: false + t.string "checksum" + t.datetime "created_at", null: false + t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true + end + + create_table "active_storage_variant_records", force: :cascade do |t| + t.bigint "blob_id", null: false + t.string "variation_digest", null: false + t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true + end + + create_table "ad_compliances", force: :cascade do |t| + t.integer "airworthiness_directive_id", null: false + t.integer "aircraft_id" + t.integer "component_id" + t.integer "logbook_entry_id" + t.integer "inspection_record_id" + t.date "date_complied", null: false + t.text "compliance_notes", null: false + t.boolean "permanent", default: false, null: false + t.decimal "next_due_at_time", precision: 8, scale: 1, default: "0.0", null: false + t.decimal "aircraft_hours_at_compliance", precision: 8, scale: 1 + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id"], name: "index_ad_compliances_on_aircraft_id" + t.index ["airworthiness_directive_id"], name: "index_ad_compliances_on_airworthiness_directive_id" + t.index ["component_id"], name: "index_ad_compliances_on_component_id" + t.index ["inspection_record_id"], name: "index_ad_compliances_on_inspection_record_id" + t.index ["logbook_entry_id"], name: "index_ad_compliances_on_logbook_entry_id" + end + + create_table "aircraft", force: :cascade do |t| + t.string "tail_number", null: false + t.string "make" + t.string "model" + t.string "serial_number" + t.text "description" + t.date "purchased" + t.string "status", default: "AVAILABLE", null: false + t.decimal "tach_time", precision: 8, scale: 1, default: "0.0", null: false + t.decimal "tach_time_offset", precision: 8, scale: 1, default: "0.0", null: false + t.decimal "hobbs_time", precision: 8, scale: 1, default: "0.0", null: false + t.decimal "hobbs_time_offset", precision: 8, scale: 1, default: "0.0", null: false + t.boolean "airworthiness_enforcement", default: false, null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + create_table "aircraft_airworthiness_directives", id: false, force: :cascade do |t| + t.integer "aircraft_id", null: false + t.integer "airworthiness_directive_id", null: false + t.index ["aircraft_id", "airworthiness_directive_id"], name: "idx_aircraft_ads", unique: true + end + + create_table "aircraft_events", force: :cascade do |t| + t.integer "aircraft_id", null: false + t.integer "user_id" + t.string "category", null: false + t.string "event_name", null: false + t.text "notes" + t.datetime "created_at", null: false + t.index ["aircraft_id", "created_at"], name: "index_aircraft_events_on_aircraft_id_and_created_at" + t.index ["aircraft_id"], name: "index_aircraft_events_on_aircraft_id" + t.index ["user_id"], name: "index_aircraft_events_on_user_id" + end + + create_table "aircraft_inspection_types", id: false, force: :cascade do |t| + t.integer "aircraft_id", null: false + t.integer "inspection_type_id", null: false + t.index ["aircraft_id", "inspection_type_id"], name: "idx_aircraft_inspection_types", unique: true + end + + create_table "aircraft_notes", force: :cascade do |t| + t.integer "aircraft_id", null: false + t.integer "user_id" + t.text "text", null: false + t.boolean "public", default: false, null: false + t.datetime "edited_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id"], name: "index_aircraft_notes_on_aircraft_id" + t.index ["user_id"], name: "index_aircraft_notes_on_user_id" + end + + create_table "aircraft_roles", force: :cascade do |t| + t.integer "aircraft_id", null: false + t.integer "user_id", null: false + t.string "role", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id", "user_id"], name: "index_aircraft_roles_on_aircraft_id_and_user_id", unique: true + t.index ["aircraft_id"], name: "index_aircraft_roles_on_aircraft_id" + t.index ["user_id"], name: "index_aircraft_roles_on_user_id" + end + + create_table "airworthiness_directives", force: :cascade do |t| + t.string "name", null: false + t.string "short_description", null: false + t.text "required_action" + t.string "compliance_type", default: "standard", null: false + t.text "trigger_condition" + t.boolean "recurring", default: false, null: false + t.decimal "recurring_hours", precision: 8, scale: 1, default: "0.0", null: false + t.integer "recurring_months", default: 0, null: false + t.integer "recurring_days", default: 0, null: false + t.string "bulletin_type", default: "ad", null: false + t.boolean "mandatory", default: true, null: false + t.integer "document_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["document_id"], name: "index_airworthiness_directives_on_document_id" + end + + create_table "airworthiness_directives_components", id: false, force: :cascade do |t| + t.integer "component_id", null: false + t.integer "airworthiness_directive_id", null: false + t.index ["component_id", "airworthiness_directive_id"], name: "idx_component_ads", unique: true + end + + create_table "component_types", force: :cascade do |t| + t.string "name", null: false + t.boolean "consumable", default: false, null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["name"], name: "index_component_types_on_name", unique: true + end + + create_table "components", force: :cascade do |t| + t.integer "aircraft_id" + t.integer "parent_component_id" + t.integer "component_type_id", null: false + t.string "manufacturer", null: false + t.string "model", null: false + t.string "serial_number" + t.string "install_location" + t.text "notes" + t.string "status", default: "SPARE", null: false + t.date "date_in_service", null: false + t.decimal "hours_in_service", precision: 8, scale: 1, default: "0.0", null: false + t.decimal "hours_since_overhaul", precision: 8, scale: 1, default: "0.0", null: false + t.date "overhaul_date" + t.integer "tbo_hours" + t.integer "tbo_days" + t.integer "inspection_hours" + t.integer "inspection_days" + t.integer "replacement_hours" + t.integer "replacement_days" + t.boolean "tbo_critical", default: true, null: false + t.boolean "on_condition", default: false, null: false + t.boolean "inspection_critical", default: true, null: false + t.boolean "replacement_critical", default: false, null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id"], name: "index_components_on_aircraft_id" + t.index ["component_type_id"], name: "index_components_on_component_type_id" + t.index ["parent_component_id"], name: "index_components_on_parent_component_id" + end + + create_table "components_inspection_types", id: false, force: :cascade do |t| + t.integer "component_id", null: false + t.integer "inspection_type_id", null: false + t.index ["component_id", "inspection_type_id"], name: "idx_component_inspection_types", unique: true + end + + create_table "consumable_records", force: :cascade do |t| + t.integer "aircraft_id", null: false + t.integer "flight_log_id" + t.string "record_type", null: false + t.date "date", null: false + t.decimal "quantity_added", precision: 6, scale: 2, null: false + t.decimal "level_after", precision: 6, scale: 2 + t.string "consumable_type" + t.decimal "flight_hours", precision: 8, scale: 1, null: false + t.text "notes" + t.boolean "excluded_from_averages", default: false, null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id", "record_type", "flight_hours"], name: "idx_on_aircraft_id_record_type_flight_hours_2c5ed6828c" + t.index ["aircraft_id"], name: "index_consumable_records_on_aircraft_id" + t.index ["flight_log_id"], name: "index_consumable_records_on_flight_log_id" + end + + create_table "document_collections", force: :cascade do |t| + t.integer "aircraft_id", null: false + t.string "name", null: false + t.text "description" + t.string "visibility", default: "private", null: false + t.boolean "starred", default: false, null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id"], name: "index_document_collections_on_aircraft_id" + end + + create_table "documents", force: :cascade do |t| + t.integer "aircraft_id", null: false + t.integer "document_collection_id" + t.string "doc_type", default: "OTHER", null: false + t.string "name", null: false + t.text "description" + t.string "visibility" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id"], name: "index_documents_on_aircraft_id" + t.index ["document_collection_id"], name: "index_documents_on_document_collection_id" + end + + create_table "flight_logs", force: :cascade do |t| + t.integer "aircraft_id", null: false + t.integer "user_id" + t.date "date", null: false + t.decimal "tach_time", precision: 6, scale: 1, null: false + t.decimal "tach_out", precision: 8, scale: 1 + t.decimal "tach_in", precision: 8, scale: 1 + t.decimal "hobbs_time", precision: 6, scale: 1 + t.decimal "hobbs_out", precision: 8, scale: 1 + t.decimal "hobbs_in", precision: 8, scale: 1 + t.string "departure_location" + t.string "destination_location" + t.text "route" + t.decimal "oil_added", precision: 6, scale: 2 + t.string "oil_added_type" + t.decimal "oil_level_after", precision: 6, scale: 2 + t.decimal "fuel_added", precision: 8, scale: 2 + t.string "fuel_added_type" + t.decimal "fuel_level_after", precision: 8, scale: 2 + t.text "notes" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id"], name: "index_flight_logs_on_aircraft_id" + t.index ["user_id"], name: "index_flight_logs_on_user_id" + end + + create_table "inspection_records", force: :cascade do |t| + t.integer "inspection_type_id", null: false + t.integer "aircraft_id" + t.integer "component_id" + t.integer "logbook_entry_id" + t.date "date", null: false + t.decimal "aircraft_hours", precision: 8, scale: 1 + t.text "notes" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id"], name: "index_inspection_records_on_aircraft_id" + t.index ["component_id"], name: "index_inspection_records_on_component_id" + t.index ["inspection_type_id"], name: "index_inspection_records_on_inspection_type_id" + t.index ["logbook_entry_id"], name: "index_inspection_records_on_logbook_entry_id" + end + + create_table "inspection_types", force: :cascade do |t| + t.string "name", null: false + t.boolean "recurring", default: false, null: false + t.boolean "required", default: true, null: false + t.decimal "recurring_hours", precision: 8, scale: 1, default: "0.0", null: false + t.integer "recurring_days", default: 0, null: false + t.integer "recurring_months", default: 0, null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + + create_table "logbook_entries", force: :cascade do |t| + t.integer "aircraft_id", null: false + t.integer "document_id" + t.string "log_type", default: "AC", null: false + t.string "entry_type", default: "MAINTENANCE", null: false + t.date "date", null: false + t.text "text", null: false + t.text "signoff_person" + t.string "signoff_location" + t.decimal "aircraft_hours_at_entry", precision: 8, scale: 1 + t.integer "page_number" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id"], name: "index_logbook_entries_on_aircraft_id" + t.index ["document_id"], name: "index_logbook_entries_on_document_id" + end + + create_table "major_records", force: :cascade do |t| + t.integer "aircraft_id", null: false + t.integer "component_id" + t.integer "form_337_document_id" + t.integer "stc_document_id" + t.integer "logbook_entry_id" + t.string "record_type", null: false + t.string "title", null: false + t.text "description" + t.date "date_performed", null: false + t.string "performed_by" + t.string "stc_number" + t.string "stc_holder" + t.decimal "aircraft_hours", precision: 8, scale: 1 + t.boolean "has_ica", default: false, null: false + t.text "ica_notes" + t.text "notes" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id"], name: "index_major_records_on_aircraft_id" + t.index ["component_id"], name: "index_major_records_on_component_id" + t.index ["form_337_document_id"], name: "index_major_records_on_form_337_document_id" + t.index ["logbook_entry_id"], name: "index_major_records_on_logbook_entry_id" + t.index ["stc_document_id"], name: "index_major_records_on_stc_document_id" + end + + create_table "sessions", force: :cascade do |t| + t.integer "user_id", null: false + t.string "ip_address" + t.string "user_agent" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["user_id"], name: "index_sessions_on_user_id" + end + + create_table "share_tokens", force: :cascade do |t| + t.integer "aircraft_id", null: false + t.integer "created_by_id" + t.string "token", null: false + t.string "label" + t.string "privilege", default: "status", null: false + t.datetime "expires_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id"], name: "index_share_tokens_on_aircraft_id" + t.index ["created_by_id"], name: "index_share_tokens_on_created_by_id" + t.index ["token"], name: "index_share_tokens_on_token", unique: true + end + + create_table "squawks", force: :cascade do |t| + t.integer "aircraft_id", null: false + t.integer "component_id" + t.integer "reported_by_id" + t.integer "priority", default: 0, null: false + t.text "issue_reported" + t.text "notes" + t.boolean "resolved", default: false, null: false + t.datetime "resolved_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id"], name: "index_squawks_on_aircraft_id" + t.index ["component_id"], name: "index_squawks_on_component_id" + t.index ["reported_by_id"], name: "index_squawks_on_reported_by_id" + end + + create_table "users", force: :cascade do |t| + t.string "email_address", null: false + t.string "password_digest", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.string "name" + t.boolean "admin", default: false, null: false + t.index ["email_address"], name: "index_users_on_email_address", unique: true + end + + add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id" + add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id" + add_foreign_key "ad_compliances", "aircraft" + add_foreign_key "ad_compliances", "airworthiness_directives" + add_foreign_key "ad_compliances", "components" + add_foreign_key "ad_compliances", "inspection_records", on_delete: :nullify + add_foreign_key "ad_compliances", "logbook_entries", on_delete: :nullify + add_foreign_key "aircraft_events", "aircraft" + add_foreign_key "aircraft_events", "users", on_delete: :nullify + add_foreign_key "aircraft_notes", "aircraft" + add_foreign_key "aircraft_notes", "users", on_delete: :nullify + add_foreign_key "aircraft_roles", "aircraft" + add_foreign_key "aircraft_roles", "users" + add_foreign_key "airworthiness_directives", "documents", on_delete: :nullify + add_foreign_key "components", "aircraft" + add_foreign_key "components", "component_types" + add_foreign_key "components", "components", column: "parent_component_id" + add_foreign_key "consumable_records", "aircraft" + add_foreign_key "consumable_records", "flight_logs", on_delete: :nullify + add_foreign_key "document_collections", "aircraft" + add_foreign_key "documents", "aircraft" + add_foreign_key "documents", "document_collections" + add_foreign_key "flight_logs", "aircraft" + add_foreign_key "flight_logs", "users", on_delete: :nullify + add_foreign_key "inspection_records", "aircraft" + add_foreign_key "inspection_records", "components" + add_foreign_key "inspection_records", "inspection_types" + add_foreign_key "inspection_records", "logbook_entries", on_delete: :nullify + add_foreign_key "logbook_entries", "aircraft" + add_foreign_key "logbook_entries", "documents", on_delete: :nullify + add_foreign_key "major_records", "aircraft" + add_foreign_key "major_records", "components", on_delete: :nullify + add_foreign_key "major_records", "documents", column: "form_337_document_id", on_delete: :nullify + add_foreign_key "major_records", "documents", column: "stc_document_id", on_delete: :nullify + add_foreign_key "major_records", "logbook_entries", on_delete: :nullify + add_foreign_key "sessions", "users" + add_foreign_key "share_tokens", "aircraft" + add_foreign_key "share_tokens", "users", column: "created_by_id", on_delete: :nullify + add_foreign_key "squawks", "aircraft" + add_foreign_key "squawks", "components", on_delete: :nullify + add_foreign_key "squawks", "users", column: "reported_by_id", on_delete: :nullify +end diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 0000000..712980d --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,91 @@ +# Standard component types (idempotent). +[ + [ "Engine", false ], [ "Propeller", false ], [ "Magneto", false ], [ "Vacuum Pump", false ], + [ "Alternator", false ], [ "Starter", false ], [ "ELT", false ], [ "ELT Battery", true ], + [ "Oil", true ], [ "Oil Filter", true ], [ "Spark Plugs", true ], [ "Air Filter", true ], + [ "Battery", true ], [ "Transponder", false ], [ "Tires", true ], [ "Brakes", true ] +].each do |name, consumable| + ComponentType.find_or_create_by!(name: name) { _1.consumable = consumable } +end + +# Demo data: `DEMO=1 bin/rails db:seed` +if ENV["DEMO"].present? + admin = User.find_or_create_by!(email_address: "admin@example.com") do |u| + u.name = "Demo Admin" + u.password = "password123" + u.admin = true + end + pilot = User.find_or_create_by!(email_address: "pilot@example.com") do |u| + u.name = "Demo Pilot" + u.password = "password123" + end + + Current.session = admin.sessions.first_or_create!(user_agent: "seed", ip_address: "127.0.0.1") + + ac = Aircraft.find_or_create_by!(tail_number: "N12345") do |a| + a.make = "Cessna" + a.model = "172N" + a.serial_number = "17270001" + a.tach_time = 4210.3 + a.hobbs_time = 5102.8 + a.purchased = Date.new(2019, 6, 1) + end + ac.roles.find_or_create_by!(user: admin) { _1.role = "owner" } + ac.roles.find_or_create_by!(user: pilot) { _1.role = "pilot" } + + type = ->(n) { ComponentType.find_by!(name: n) } + if ac.components.none? + engine = ac.components.create!(component_type: type.("Engine"), manufacturer: "Lycoming", model: "O-320-H2AD", + serial_number: "L-1234-76", status: "IN-USE", date_in_service: Date.new(2012, 3, 1), + hours_in_service: 1650, hours_since_overhaul: 1650, tbo_hours: 2000, overhaul_date: Date.new(2012, 3, 1)) + ac.components.create!(component_type: type.("Propeller"), manufacturer: "McCauley", model: "1C160/DTM7553", + status: "IN-USE", date_in_service: Date.new(2015, 1, 1), hours_in_service: 900, hours_since_overhaul: 900, + tbo_hours: 2000, tbo_critical: true) + ac.components.create!(component_type: type.("Oil"), parent_component: engine, manufacturer: "Aeroshell", + model: "W100", status: "IN-USE", date_in_service: 40.days.ago, overhaul_date: 40.days.ago, + hours_since_overhaul: 44, replacement_hours: 50, replacement_days: 120, replacement_critical: true, + tbo_critical: false) + ac.components.create!(component_type: type.("ELT Battery"), manufacturer: "ACK", model: "E-04", + install_location: "Tailcone", status: "IN-USE", date_in_service: 2.years.ago, overhaul_date: 2.years.ago, + replacement_days: 730, replacement_critical: true, tbo_critical: false) + end + + annual = InspectionType.find_or_create_by!(name: "Annual Inspection") { _1.recurring = true; _1.recurring_months = 12 } + xpdr = InspectionType.find_or_create_by!(name: "Transponder (91.413)") { _1.recurring = true; _1.recurring_months = 24 } + [ annual, xpdr ].each { |t| t.aircraft << ac unless t.aircraft.include?(ac) } + ac.inspection_records.find_or_create_by!(inspection_type: annual) { _1.date = 11.months.ago.to_date; _1.aircraft_hours = 4150 } + ac.inspection_records.find_or_create_by!(inspection_type: xpdr) { _1.date = 10.months.ago.to_date; _1.aircraft_hours = 4160 } + + ad = AirworthinessDirective.find_or_create_by!(name: "2011-10-09") do |a| + a.short_description = "Seat rail inspection" + a.recurring = true + a.recurring_hours = 100 + end + ad.aircraft << ac unless ad.aircraft.include?(ac) + ad.ad_compliances.find_or_create_by!(aircraft: ac) do |c| + c.date_complied = 11.months.ago.to_date + c.compliance_notes = "Inspected seat rails and stops IAW AD. No defects." + c.aircraft_hours_at_compliance = 4150 + c.next_due_at_time = 4250 + end + + ac.squawks.find_or_create_by!(issue_reported: "Left landing light inop") { _1.priority = 2; _1.reported_by = pilot } + + if ac.consumable_records.none? + hrs = 4150.0 + [ 1, 1, 0.5, 1, 1, 0.5, 1 ].each_with_index do |qt, i| + hrs += [ 9, 11, 6, 10, 12, 5, 10 ][i] + ac.consumable_records.create!(record_type: "oil", date: (60 - i * 8).days.ago, quantity_added: qt, flight_hours: hrs) + ac.consumable_records.create!(record_type: "fuel", date: (60 - i * 8).days.ago, + quantity_added: (8.5 * [ 9, 11, 6, 10, 12, 5, 10 ][i]).round(1), flight_hours: hrs) + end + end + + ac.logbook_entries.find_or_create_by!(date: 11.months.ago.to_date, text: "Annual inspection completed IAW 14 CFR 43 App. D. Aircraft found airworthy.") do |e| + e.entry_type = "INSPECTION" + e.aircraft_hours_at_entry = 4150 + e.signoff_person = "J. Mechanic A&P/IA 1234567" + end + + puts "Demo data loaded. Sign in as admin@example.com / password123 (or pilot@example.com)." +end diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..90b42bd --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,18 @@ +# Simplest self-hosting: one container, SQLite + uploads in a named volume. +# +# cp .env.example .env # set SECRET_KEY_BASE (bin/rails secret) and APP_HOST +# docker compose up -d --build +# open http://localhost:3000 → create the admin account +services: + web: + build: . + restart: unless-stopped + ports: + - "3000:80" + env_file: .env + environment: + SOLID_QUEUE_IN_PUMA: "true" # background jobs run inside the web process + volumes: + - sam_storage:/rails/storage # databases + uploaded files: back this up +volumes: + sam_storage: diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 0000000..e69de29 diff --git a/log/.keep b/log/.keep new file mode 100644 index 0000000..e69de29 diff --git a/public/400.html b/public/400.html new file mode 100644 index 0000000..282dbc8 --- /dev/null +++ b/public/400.html @@ -0,0 +1,114 @@ + + + + + + + The server cannot process the request due to a client error (400 Bad Request) + + + + + + + + + + + + + +
    +
    + +
    +
    +

    The server cannot process the request due to a client error. Please check the request and try again. If you’re the application owner check the logs for more information.

    +
    +
    + + + + diff --git a/public/404.html b/public/404.html new file mode 100644 index 0000000..c0670bc --- /dev/null +++ b/public/404.html @@ -0,0 +1,114 @@ + + + + + + + The page you were looking for doesn’t exist (404 Not found) + + + + + + + + + + + + + +
    +
    + +
    +
    +

    The page you were looking for doesn’t exist. You may have mistyped the address or the page may have moved. If you’re the application owner check the logs for more information.

    +
    +
    + + + + diff --git a/public/406-unsupported-browser.html b/public/406-unsupported-browser.html new file mode 100644 index 0000000..9532a9c --- /dev/null +++ b/public/406-unsupported-browser.html @@ -0,0 +1,114 @@ + + + + + + + Your browser is not supported (406 Not Acceptable) + + + + + + + + + + + + + +
    +
    + +
    +
    +

    Your browser is not supported.
    Please upgrade your browser to continue.

    +
    +
    + + + + diff --git a/public/422.html b/public/422.html new file mode 100644 index 0000000..8bcf060 --- /dev/null +++ b/public/422.html @@ -0,0 +1,114 @@ + + + + + + + The change you wanted was rejected (422 Unprocessable Entity) + + + + + + + + + + + + + +
    +
    + +
    +
    +

    The change you wanted was rejected. Maybe you tried to change something you didn’t have access to. If you’re the application owner check the logs for more information.

    +
    +
    + + + + diff --git a/public/500.html b/public/500.html new file mode 100644 index 0000000..d77718c --- /dev/null +++ b/public/500.html @@ -0,0 +1,114 @@ + + + + + + + We’re sorry, but something went wrong (500 Internal Server Error) + + + + + + + + + + + + + +
    +
    + +
    +
    +

    We’re sorry, but something went wrong.
    If you’re the application owner check the logs for more information.

    +
    +
    + + + + diff --git a/public/icon.png b/public/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..c4c9dbfbbd2f7c1421ffd5727188146213abbcef GIT binary patch literal 4166 zcmd6qU;WFw?|v@m)Sk^&NvB8tcujdV-r1b=i(NJxn&7{KTb zX$3(M+3TP2o^#KAo{#tIjl&t~(8D-k004kqPglzn0HFG(Q~(I*AKsD#M*g7!XK0T7 zN6P7j>HcT8rZgKl$v!xr806dyN19Bd4C0x_R*I-a?#zsTvb_89cyhuC&T**i|Rc zq5b8M;+{8KvoJ~uj9`u~d_f6`V&3+&ZX9x5pc8s)d175;@pjm(?dapmBcm0&vl9+W zx1ZD2o^nuyUHWj|^A8r>lUorO`wFF;>9XL-Jy!P}UXC{(z!FO%SH~8k`#|9;Q|eue zqWL0^Bp(fg_+Pkm!fDKRSY;+^@BF?AJE zCUWpXPst~hi_~u)SzYBDZroR+Z4xeHIlm_3Yc_9nZ(o_gg!jDgVa=E}Y8uDgem9`b zf=mfJ_@(BXSkW53B)F2s!&?_R4ptb1fYXlF++@vPhd=marQgEGRZS@B4g1Mu?euknL= z67P~tZ?*>-Hmi7GwlisNHHJDku-dSm7g@!=a}9cSL6Pa^w^2?&?$Oi8ibrr>w)xqx zOH_EMU@m05)9kuNR>>4@H%|){U$^yvVQ(YgOlh;5oU_-vivG-p4=LrN-k7D?*?u1u zsWly%tfAzKd6Fb=`eU2un_uaTXmcT#tlOL+aRS=kZZf}A7qT8lvcTx~7j` z*b>=z)mwg7%B2_!D0!1IZ?Nq{^Y$uI4Qx*6T!E2Col&2{k?ImCO=dD~A&9f9diXy^$x{6CwkBimn|1E09 zAMSezYtiL?O6hS37KpvDM?22&d{l)7h-!F)C-d3j8Z`c@($?mfd{R82)H>Qe`h{~G z!I}(2j(|49{LR?w4Jspl_i!(4T{31|dqCOpI52r5NhxYV+cDAu(xp*4iqZ2e-$YP= zoFOPmm|u*7C?S{Fp43y+V;>~@FFR76bCl@pTtyB93vNWy5yf;HKr8^0d7&GVIslYm zo3Tgt@M!`8B6IW&lK{Xk>%zp41G%`(DR&^u z5^pwD4>E6-w<8Kl2DzJ%a@~QDE$(e87lNhy?-Qgep!$b?5f7+&EM7$e>|WrX+=zCb z=!f5P>MxFyy;mIRxjc(H*}mceXw5a*IpC0PEYJ8Y3{JdoIW)@t97{wcUB@u+$FCCO z;s2Qe(d~oJC^`m$7DE-dsha`glrtu&v&93IZadvl_yjp!c89>zo;Krk+d&DEG4?x$ zufC1n+c1XD7dolX1q|7}uelR$`pT0Z)1jun<39$Sn2V5g&|(j~Z!wOddfYiZo7)A< z!dK`aBHOOk+-E_xbWCA3VR-+o$i5eO9`rMI#p_0xQ}rjEpGW;U!&&PKnivOcG(|m9 z!C8?WC6nCXw25WVa*eew)zQ=h45k8jSIPbq&?VE{oG%?4>9rwEeB4&qe#?-y_es4c|7ufw%+H5EY#oCgv!Lzv291#-oNlX~X+Jl5(riC~r z=0M|wMOP)Tt8@hNg&%V@Z9@J|Q#K*hE>sr6@oguas9&6^-=~$*2Gs%h#GF@h)i=Im z^iKk~ipWJg1VrvKS;_2lgs3n1zvNvxb27nGM=NXE!D4C!U`f*K2B@^^&ij9y}DTLB*FI zEnBL6y{jc?JqXWbkIZd7I16hA>(f9T!iwbIxJj~bKPfrO;>%*5nk&Lf?G@c2wvGrY&41$W{7HM9+b@&XY@>NZM5s|EK_Dp zQX60CBuantx>|d#DsaZ*8MW(we|#KTYZ=vNa#d*DJQe6hr~J6{_rI#?wi@s|&O}FR zG$kfPxheXh1?IZ{bDT-CWB4FTvO-k5scW^mi8?iY5Q`f8JcnnCxiy@m@D-%lO;y0pTLhh6i6l@x52j=#^$5_U^os}OFg zzdHbo(QI`%9#o*r8GCW~T3UdV`szO#~)^&X_(VW>o~umY9-ns9-V4lf~j z`QBD~pJ4a#b`*6bJ^3RS5y?RAgF7K5$ll97Y8#WZduZ`j?IEY~H(s^doZg>7-tk*t z4_QE1%%bb^p~4F5SB$t2i1>DBG1cIo;2(xTaj*Y~hlM{tSDHojL-QPg%Mo%6^7FrpB*{ z4G0@T{-77Por4DCMF zB_5Y~Phv%EQ64W8^GS6h?x6xh;w2{z3$rhC;m+;uD&pR74j+i22P5DS-tE8ABvH(U~indEbBUTAAAXfHZg5QpB@TgV9eI<)JrAkOI z8!TSOgfAJiWAXeM&vR4Glh;VxH}WG&V$bVb`a`g}GSpwggti*&)taV1@Ak|{WrV|5 zmNYx)Ans=S{c52qv@+jmGQ&vd6>6yX6IKq9O$3r&0xUTdZ!m1!irzn`SY+F23Rl6# zFRxws&gV-kM1NX(3(gnKpGi0Q)Dxi~#?nyzOR9!en;Ij>YJZVFAL*=R%7y%Mz9hU% zs>+ZB?qRmZ)nISx7wxY)y#cd$iaC~{k0avD>BjyF1q^mNQ1QcwsxiTySe<6C&cC6P zE`vwO9^k-d`9hZ!+r@Jnr+MF*2;2l8WjZ}DrwDUHzSF{WoG zucbSWguA!3KgB3MU%HH`R;XqVv0CcaGq?+;v_A5A2kpmk5V%qZE3yzQ7R5XWhq=eR zyUezH=@V)y>L9T-M-?tW(PQYTRBKZSVb_!$^H-Pn%ea;!vS_?M<~Tm>_rWIW43sPW z=!lY&fWc1g7+r?R)0p8(%zp&vl+FK4HRkns%BW+Up&wK8!lQ2~bja|9bD12WrKn#M zK)Yl9*8$SI7MAwSK$%)dMd>o+1UD<2&aQMhyjS5R{-vV+M;Q4bzl~Z~=4HFj_#2V9 zB)Gfzx3ncy@uzx?yzi}6>d%-?WE}h7v*w)Jr_gBl!2P&F3DX>j_1#--yjpL%<;JMR z*b70Gr)MMIBWDo~#<5F^Q0$VKI;SBIRneuR7)yVsN~A9I@gZTXe)E?iVII+X5h0~H zx^c(fP&4>!*q>fb6dAOC?MI>Cz3kld#J*;uik+Ps49cwm1B4 zZc1|ZxYyTv;{Z!?qS=D)sgRKx^1AYf%;y_V&VgZglfU>d+Ufk5&LV$sKv}Hoj+s; xK3FZRYdhbXT_@RW*ff3@`D1#ps#~H)p+y&j#(J|vk^lW{fF9OJt5(B-_&*Xgn9~3N literal 0 HcmV?d00001 diff --git a/public/icon.svg b/public/icon.svg new file mode 100644 index 0000000..04b34bf --- /dev/null +++ b/public/icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 0000000..c19f78a --- /dev/null +++ b/public/robots.txt @@ -0,0 +1 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/script/.keep b/script/.keep new file mode 100644 index 0000000..e69de29 diff --git a/storage/.keep b/storage/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rb new file mode 100644 index 0000000..cee29fd --- /dev/null +++ b/test/application_system_test_case.rb @@ -0,0 +1,5 @@ +require "test_helper" + +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :headless_chrome, screen_size: [ 1400, 1400 ] +end diff --git a/test/controllers/.keep b/test/controllers/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/fixtures/files/.keep b/test/fixtures/files/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/helpers/.keep b/test/helpers/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/integration/.keep b/test/integration/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/integration/pages_test.rb b/test/integration/pages_test.rb new file mode 100644 index 0000000..8b7ff7e --- /dev/null +++ b/test/integration/pages_test.rb @@ -0,0 +1,104 @@ +require "test_helper" + +# Renders every page with realistic data to catch view/route errors. +class PagesTest < ActionDispatch::IntegrationTest + setup do + @owner = create_user("owner@example.com", admin: false) + @a = create_aircraft(owner: @owner, tail_number: "N100AB") + @engine = create_component(@a) + @oil = create_component(@a, component_type: component_type("Oil"), parent_component: @engine, + replacement_critical: true, replacement_hours: 50, hours_since_overhaul: 45, overhaul_date: Date.current) + @squawk = @a.squawks.create!(priority: 1, issue_reported: "Nav light out", reported_by: @owner) + @a.squawks.create!(priority: 3, issue_reported: "Old one", resolved: true, resolved_at: Time.current) + @note = @a.notes.create!(text: "Hangar 4", user: @owner, public: true) + @entry = @a.logbook_entries.create!(date: Date.current, text: "Oil changed", aircraft_hours_at_entry: 1000) + @collection = @a.document_collections.create!(name: "Logbooks", visibility: "status") + @doc = @a.documents.create!(name: "W&B", document_collection: @collection) + @doc.pages.attach(io: StringIO.new("hello"), filename: "wb.txt", content_type: "text/plain") + @itype = InspectionType.create!(name: "Annual", recurring: true, recurring_months: 12) + @itype.aircraft << @a + @irec = @a.inspection_records.create!(inspection_type: @itype, date: Date.current, aircraft_hours: 1000) + @ad = AirworthinessDirective.create!(name: "2020-01-01", short_description: "Check", recurring: true, recurring_hours: 100) + @ad.aircraft << @a + @adc = @ad.ad_compliances.create!(aircraft: @a, date_complied: Date.current, compliance_notes: "Done", next_due_at_time: 1100) + @major = @a.major_records.create!(record_type: "alteration", title: "LED lights", date_performed: Date.current) + @flight = @a.flight_logs.create!(date: Date.current, tach_time: 1.2) + @cr = @a.consumable_records.create!(record_type: "oil", date: Date.current, quantity_added: 1, flight_hours: 1000) + @token = @a.share_tokens.create!(privilege: "maintenance", label: "Mechanic") + @a.log_event!("aircraft", "Created", user: @owner) + sign_in @owner + end + + test "owner can render every page" do + a = @a + paths = [ + root_path, aircraft_path(a), new_aircraft_path, edit_aircraft_path(a), + aircraft_components_path(a), aircraft_components_path(a, disposed: 1), new_aircraft_component_path(a), + aircraft_component_path(a, @engine), edit_aircraft_component_path(a, @oil), + aircraft_squawks_path(a), new_aircraft_squawk_path(a), edit_aircraft_squawk_path(a, @squawk), + aircraft_notes_path(a), new_aircraft_note_path(a), edit_aircraft_note_path(a, @note), + aircraft_flight_logs_path(a), new_aircraft_flight_log_path(a), aircraft_flight_log_path(a, @flight), + aircraft_consumable_records_path(a), new_aircraft_consumable_record_path(a, type: "fuel"), edit_aircraft_consumable_record_path(a, @cr), + aircraft_logbook_entries_path(a), aircraft_logbook_entries_path(a, q: "oil", log_type: "AC"), + new_aircraft_logbook_entry_path(a), aircraft_logbook_entry_path(a, @entry), edit_aircraft_logbook_entry_path(a, @entry), + aircraft_documents_path(a), new_aircraft_document_path(a), aircraft_document_path(a, @doc), edit_aircraft_document_path(a, @doc), + new_aircraft_document_collection_path(a), edit_aircraft_document_collection_path(a, @collection), + aircraft_inspections_path(a), new_aircraft_inspection_type_path(a), edit_aircraft_inspection_type_path(a, @itype), + new_aircraft_inspection_record_path(a, inspection_type_id: @itype.id), edit_aircraft_inspection_record_path(a, @irec), + aircraft_airworthiness_directives_path(a), new_aircraft_airworthiness_directive_path(a), + edit_aircraft_airworthiness_directive_path(a, @ad), new_aircraft_ad_compliance_path(a, ad_id: @ad.id), + edit_aircraft_ad_compliance_path(a, @adc), + aircraft_major_records_path(a), new_aircraft_major_record_path(a), aircraft_major_record_path(a, @major), + edit_aircraft_major_record_path(a, @major), + aircraft_aircraft_roles_path(a), aircraft_events_path(a), aircraft_events_path(a, category: "aircraft"), + edit_profile_path + ] + paths.each do |path| + get path + assert_response :success, "GET #{path} → #{response.status}" + end + end + + test "maintenance share link renders without login and shows history" do + delete session_path + get shared_path(@token.token) + assert_response :success + assert_includes response.body, "N100AB" + assert_includes response.body, "Oil changed" # logbook + assert_includes response.body, "LED lights" # major records + assert_includes response.body, "Hangar 4" # public note + assert_includes response.body, "W&B" # status-visible doc + end + + test "status share link hides maintenance history" do + t = @a.share_tokens.create!(privilege: "status") + @a.notes.create!(text: "Secret combo", public: false) + delete session_path + get shared_path(t.token) + assert_response :success + assert_not_includes response.body, "Oil changed" + assert_not_includes response.body, "LED lights" + assert_not_includes response.body, "Secret combo" + assert_includes response.body, "Nav light out" + end + + test "expired or unknown share link is 404" do + t = @a.share_tokens.create!(privilege: "status", expires_at: 1.minute.ago) + get shared_path(t.token) + assert_response :not_found + get shared_path("nope") + assert_response :not_found + end + + test "admin pages" do + admin = create_user("boss@example.com", admin: true) + sign_in admin + [ admin_users_path, new_admin_user_path, edit_admin_user_path(@owner), + admin_component_types_path, new_admin_component_type_path ].each do |path| + get path + assert_response :success, path + end + get aircraft_path(@a) # admins see every aircraft + assert_response :success + end +end diff --git a/test/integration/permissions_test.rb b/test/integration/permissions_test.rb new file mode 100644 index 0000000..9169097 --- /dev/null +++ b/test/integration/permissions_test.rb @@ -0,0 +1,126 @@ +require "test_helper" + +class PermissionsTest < ActionDispatch::IntegrationTest + setup do + @owner = create_user + @pilot = create_user + @outsider = create_user + @a = create_aircraft(owner: @owner, pilot: @pilot, tach_time: 1000) + @engine = create_component(@a, hours_in_service: 100, hours_since_overhaul: 100) + end + + test "outsider gets 404 for aircraft and nested resources" do + sign_in @outsider + get aircraft_path(@a) + assert_response :not_found + get aircraft_components_path(@a) + assert_response :not_found + patch hours_aircraft_path(@a), params: { tach_time: 2000 } + assert_response :not_found + assert_equal 1000, @a.reload.tach_time + end + + test "fleet only lists accessible aircraft" do + other = create_aircraft(owner: @outsider, tail_number: "N999ZZ") + sign_in @pilot + get root_path + assert_includes response.body, @a.tail_number + assert_not_includes response.body, other.tail_number + end + + test "pilot can update hours, log flights, report squawks, add notes and oil" do + sign_in @pilot + patch hours_aircraft_path(@a), params: { tach_time: "1010" } + assert_equal 1010, @a.reload.tach_time + assert_equal 110, @engine.reload.hours_in_service + + post aircraft_flight_logs_path(@a), params: { flight_log: { date: Date.current, tach_out: 1010, tach_in: 1011.5, oil_added: 1 } } + assert_redirected_to aircraft_flight_logs_path(@a) + assert_equal 1011.5, @a.reload.tach_time + assert_equal 1, @a.consumable_records.oil.count + + post aircraft_squawks_path(@a), params: { squawk: { priority: 0, issue_reported: "Mag drop" } } + assert_equal @pilot, @a.squawks.last.reported_by + assert_equal "RED", @a.reload.airworthiness.status + + post aircraft_notes_path(@a), params: { aircraft_note: { text: "Low on fuel" } } + assert_equal 1, @a.notes.count + + post aircraft_consumable_records_path(@a), params: { consumable_record: { record_type: "fuel", date: Date.current, quantity_added: 20, flight_hours: 1011.5 } } + assert_equal 1, @a.consumable_records.fuel.count + end + + test "pilot cannot edit owner-level data" do + squawk = @a.squawks.create!(priority: 1, issue_reported: "x") + sign_in @pilot + + patch resolve_aircraft_squawk_path(@a, squawk) + assert_not squawk.reload.resolved? + + post aircraft_components_path(@a), params: { component: { component_type_id: component_type.id, manufacturer: "x", model: "y", date_in_service: Date.current } } + assert_equal 1, @a.components.count + + delete aircraft_component_path(@a, @engine) + assert Component.exists?(@engine.id) + + patch aircraft_path(@a), params: { aircraft: { tail_number: "HACKED" } } + assert_not_equal "HACKED", @a.reload.tail_number + + post aircraft_share_tokens_path(@a), params: { share_token: { privilege: "maintenance" } } + assert_equal 0, @a.share_tokens.count + + get aircraft_aircraft_roles_path(@a) + assert_response :redirect + + post aircraft_logbook_entries_path(@a), params: { logbook_entry: { date: Date.current, text: "x" } } + assert_equal 0, @a.logbook_entries.count + end + + test "owner manages roles with last-owner protection" do + sign_in @owner + owner_role = @a.roles.find_by(user: @owner) + patch aircraft_aircraft_role_path(@a, owner_role), params: { role: "pilot" } + assert_equal "owner", owner_role.reload.role + + newbie = create_user("newbie@example.com") + post aircraft_aircraft_roles_path(@a), params: { email_address: "NewBie@example.com ", role: "owner" } + assert_equal "owner", @a.roles.find_by(user: newbie).role + + delete aircraft_aircraft_role_path(@a, owner_role) + assert AircraftRole.exists?(owner_role.id), "can't remove self" + end + + test "owner full workflow: component service, AD compliance, inspection" do + sign_in @owner + post reset_service_aircraft_component_path(@a, @engine), params: { reset_in_service: "1" } + assert_equal 0, @engine.reload.hours_in_service + + post aircraft_airworthiness_directives_path(@a), params: { + airworthiness_directive: { name: "2024-05-05", short_description: "Muffler", recurring: "1", recurring_hours: 100 }, + applies_to_airframe: "0", component_ids: [ @engine.id ] + } + ad = AirworthinessDirective.find_by!(name: "2024-05-05") + assert_equal [ @engine ], ad.components.to_a + assert_equal "RED", @a.reload.airworthiness.status + + post aircraft_ad_compliances_path(@a), params: { ad_compliance: { airworthiness_directive_id: ad.id, date_complied: Date.current, compliance_notes: "Inspected", next_due_at_time: 1100 } } + assert_equal "GREEN", @a.reload.airworthiness.status + + post aircraft_inspection_types_path(@a), params: { inspection_type: { name: "Annual", recurring: "1", recurring_months: 12, required: "1" }, applies_to_airframe: "1" } + assert_equal "RED", @a.reload.airworthiness.status + it = InspectionType.find_by!(name: "Annual") + post aircraft_inspection_records_path(@a), params: { inspection_record: { inspection_type_id: it.id, date: Date.current, aircraft_hours: 1000 } } + assert_equal "GREEN", @a.reload.airworthiness.status + + delete aircraft_airworthiness_directive_path(@a, ad) + assert_not @a.reload.applicable_ads.exists?(ad.id) + end + + test "owner cannot reach another aircraft's records through their own aircraft" do + other = create_aircraft(owner: @outsider) + other_engine = create_component(other) + sign_in @owner + get aircraft_component_path(@a, other_engine) + assert_response :not_found + end +end diff --git a/test/integration/setup_test.rb b/test/integration/setup_test.rb new file mode 100644 index 0000000..2b6a178 --- /dev/null +++ b/test/integration/setup_test.rb @@ -0,0 +1,22 @@ +require "test_helper" + +class SetupTest < ActionDispatch::IntegrationTest + test "first run creates admin, then setup is closed" do + get root_path + assert_redirected_to new_setup_path + post setup_path, params: { user: { name: "Ricky", email_address: "a@b.com", password: "password123", password_confirmation: "password123" } } + assert_redirected_to root_path + assert User.last.admin? + get new_setup_path + assert_redirected_to root_path + end + + test "create aircraft makes creator the owner" do + user = create_user + sign_in user + post aircraft_index_path, params: { aircraft: { tail_number: "N1", tach_time: 50 } } + a = Aircraft.find_by!(tail_number: "N1") + assert_redirected_to aircraft_path(a) + assert_equal "owner", user.role_for(a) + end +end diff --git a/test/mailers/.keep b/test/mailers/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/mailers/previews/passwords_mailer_preview.rb b/test/mailers/previews/passwords_mailer_preview.rb new file mode 100644 index 0000000..01d07ec --- /dev/null +++ b/test/mailers/previews/passwords_mailer_preview.rb @@ -0,0 +1,7 @@ +# Preview all emails at http://localhost:3000/rails/mailers/passwords_mailer +class PasswordsMailerPreview < ActionMailer::Preview + # Preview this email at http://localhost:3000/rails/mailers/passwords_mailer/reset + def reset + PasswordsMailer.reset(User.take) + end +end diff --git a/test/models/.keep b/test/models/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/services/airworthiness_test.rb b/test/services/airworthiness_test.rb new file mode 100644 index 0000000..0f293a5 --- /dev/null +++ b/test/services/airworthiness_test.rb @@ -0,0 +1,92 @@ +require "test_helper" + +class AirworthinessTest < ActiveSupport::TestCase + setup do + @aircraft = create_aircraft(tach_time: 1000) + end + + test "clean aircraft is green" do + assert_equal "GREEN", @aircraft.airworthiness.status + end + + test "unresolved priority-0 squawk grounds aircraft" do + @aircraft.squawks.create!(priority: 0, issue_reported: "Flat tire") + assert_equal "RED", Airworthiness.new(@aircraft).call.status + end + + test "lower-priority squawk does not affect status" do + @aircraft.squawks.create!(priority: 1, issue_reported: "Light out") + assert_equal "GREEN", Airworthiness.new(@aircraft).call.status + end + + test "required inspection never completed is red" do + InspectionType.create!(name: "Annual", recurring: true, recurring_months: 12).aircraft << @aircraft + result = Airworthiness.new(@aircraft).call + assert_equal "RED", result.status + assert_match "Never Completed", result.issues.first.title + end + + test "annual due at end of month, orange within 30 days" do + type = InspectionType.create!(name: "Annual", recurring: true, recurring_months: 12) + type.aircraft << @aircraft + @aircraft.inspection_records.create!(inspection_type: type, date: Date.new(2025, 6, 10), aircraft_hours: 900) + + assert_equal "GREEN", Airworthiness.new(@aircraft, today: Date.new(2026, 5, 30)).call.status + assert_equal "ORANGE", Airworthiness.new(@aircraft, today: Date.new(2026, 6, 15)).call.status + assert_equal "ORANGE", Airworthiness.new(@aircraft, today: Date.new(2026, 6, 30)).call.status + assert_equal "RED", Airworthiness.new(@aircraft, today: Date.new(2026, 7, 1)).call.status + end + + test "hour-based inspection uses current hours minus offset" do + type = InspectionType.create!(name: "100 hr", recurring: true, recurring_hours: 100) + type.aircraft << @aircraft + @aircraft.inspection_records.create!(inspection_type: type, date: Date.current, aircraft_hours: 950) + + assert_equal "GREEN", Airworthiness.new(@aircraft).call.status # 50 hrs since + @aircraft.update!(tach_time: 1045) + assert_equal "ORANGE", Airworthiness.new(@aircraft).call.status # 95 since, within 10 + @aircraft.update!(tach_time: 1050) + assert_equal "RED", Airworthiness.new(@aircraft).call.status # 100 since + @aircraft.update!(tach_time_offset: 10) + assert_equal "ORANGE", Airworthiness.new(@aircraft).call.status # offset → 90 since + end + + test "AD without compliance is red; hour-based due soon is orange; permanent is green" do + ad = AirworthinessDirective.create!(name: "2020-01-01", short_description: "Check thing") + ad.aircraft << @aircraft + assert_equal "RED", Airworthiness.new(@aircraft).call.status + + c = ad.ad_compliances.create!(aircraft: @aircraft, date_complied: Date.current, compliance_notes: "Done", + next_due_at_time: 1005) + assert_equal "ORANGE", Airworthiness.new(@aircraft).call.status + c.update!(permanent: true) + assert_equal "GREEN", Airworthiness.new(@aircraft).call.status + end + + test "conditional and non-mandatory ADs never affect status" do + AirworthinessDirective.create!(name: "C", short_description: "x", compliance_type: "conditional").aircraft << @aircraft + AirworthinessDirective.create!(name: "S", short_description: "x", bulletin_type: "sb", mandatory: false).aircraft << @aircraft + assert_equal "GREEN", Airworthiness.new(@aircraft).call.status + end + + test "AD applied via component counts for the aircraft" do + engine = create_component(@aircraft) + AirworthinessDirective.create!(name: "ENG", short_description: "x").components << engine + assert_equal "RED", Airworthiness.new(@aircraft).call.status + end + + test "replacement-critical component overdue by hours or days" do + oil = create_component(@aircraft, component_type: component_type("Oil"), replacement_critical: true, + replacement_hours: 50, hours_since_overhaul: 45, overhaul_date: Date.current) + assert_equal "ORANGE", Airworthiness.new(@aircraft).call.status + oil.update!(hours_since_overhaul: 50) + assert_equal "RED", Airworthiness.new(@aircraft).call.status + oil.update!(hours_since_overhaul: 0, replacement_days: 120, overhaul_date: 121.days.ago.to_date) + assert_equal "RED", Airworthiness.new(@aircraft).call.status + end + + test "spare components are ignored" do + create_component(@aircraft, status: "SPARE", replacement_critical: true, replacement_hours: 10, hours_since_overhaul: 50) + assert_equal "GREEN", Airworthiness.new(@aircraft).call.status + end +end diff --git a/test/services/consumption_stats_test.rb b/test/services/consumption_stats_test.rb new file mode 100644 index 0000000..c1c2bbc --- /dev/null +++ b/test/services/consumption_stats_test.rb @@ -0,0 +1,33 @@ +require "test_helper" + +class ConsumptionStatsTest < ActiveSupport::TestCase + test "oil hrs/qt average excludes IQR outliers and excluded records" do + a = create_aircraft + a.consumable_records.create!(record_type: "oil", date: Date.current, quantity_added: 1, flight_hours: 100) + hours = 100.0 + # interval values (hrs/qt): 10, 11, 9, 10, 1 (outlier), 12, 10 (manually excluded) + [ [ 10, false ], [ 11, false ], [ 9, false ], [ 10, false ], [ 1, false ], [ 12, false ], [ 10, true ] ].each do |dh, excl| + hours += dh + a.consumable_records.create!(record_type: "oil", date: Date.current, quantity_added: 1, flight_hours: hours, + excluded_from_averages: excl) + end + stats = ConsumptionStats.new(a, "oil") + assert_equal 7, stats.points.size + assert_equal 10.4, stats.average # (10+11+9+10+12)/5 + end + + test "zero spread disables outlier filtering (matches original)" do + a = create_aircraft + [ 100, 110, 120, 130, 131, 141 ].each do |h| + a.consumable_records.create!(record_type: "oil", date: Date.current, quantity_added: 1, flight_hours: h) + end + assert_equal 8.2, ConsumptionStats.new(a, "oil").average + end + + test "fuel gal/hr" do + a = create_aircraft + a.consumable_records.create!(record_type: "fuel", date: Date.current, quantity_added: 40, flight_hours: 100) + a.consumable_records.create!(record_type: "fuel", date: Date.current, quantity_added: 17, flight_hours: 102) + assert_equal 8.5, ConsumptionStats.new(a, "fuel").average + end +end diff --git a/test/services/hours_service_test.rb b/test/services/hours_service_test.rb new file mode 100644 index 0000000..6f346a8 --- /dev/null +++ b/test/services/hours_service_test.rb @@ -0,0 +1,58 @@ +require "test_helper" + +class HoursServiceTest < ActiveSupport::TestCase + setup do + @user = create_user + @aircraft = create_aircraft(owner: @user, tach_time: 1000, hobbs_time: 1200) + @engine = create_component(@aircraft, hours_in_service: 500, hours_since_overhaul: 300) + @spare = create_component(@aircraft, status: "SPARE", hours_in_service: 10, hours_since_overhaul: 10) + end + + test "hours update cascades delta to in-use components only and logs event" do + HoursService.new(@aircraft, user: @user).update_hours!(tach_time: "1012.5", hobbs_time: "1214") + assert_equal 1012.5, @aircraft.reload.tach_time + assert_equal 1214, @aircraft.hobbs_time + assert_equal 512.5, @engine.reload.hours_in_service + assert_equal 312.5, @engine.hours_since_overhaul + assert_equal 10, @spare.reload.hours_in_service + assert_equal "hours", @aircraft.events.first.category + end + + test "downward correction clamps component hours at zero" do + @engine.update!(hours_since_overhaul: 2) + HoursService.new(@aircraft, user: @user).update_hours!(tach_time: "995") + assert_equal 0, @engine.reload.hours_since_overhaul + assert_equal 495, @engine.hours_in_service + end + + test "flight log increments hours and creates consumable records" do + flight = @aircraft.flight_logs.new(date: Date.current, tach_out: 1000, tach_in: 1001.8, hobbs_time: 2.1, + oil_added: 1, fuel_added: 20, departure_location: "KPVD", destination_location: "KBID") + HoursService.new(@aircraft, user: @user).log_flight!(flight) + assert_equal 1.8, flight.tach_time + assert_equal 1001.8, @aircraft.reload.tach_time + assert_equal 1202.1, @aircraft.hobbs_time + assert_equal 501.8, @engine.reload.hours_in_service + assert_equal %w[fuel oil], @aircraft.consumable_records.pluck(:record_type).sort + assert_equal 1001.8, @aircraft.consumable_records.first.flight_hours + assert_includes @aircraft.events.pluck(:event_name), "Flight logged: 1.8 hrs (KPVD → KBID)" + end + + test "enforcement blocks flights on red aircraft only when enabled" do + @aircraft.squawks.create!(priority: 0, issue_reported: "Engine rough") + HoursService.new(@aircraft).update_hours!(tach_time: 1001) # allowed: enforcement off + + @aircraft.update!(airworthiness_enforcement: true) + assert_raises(AircraftGroundedError) { HoursService.new(@aircraft).update_hours!(tach_time: 1002) } + assert_equal 1001, @aircraft.reload.tach_time + end + + test "component service reset" do + @engine.reset_service! + assert_equal 0, @engine.hours_since_overhaul + assert_equal 500, @engine.hours_in_service + @engine.reset_service!(reset_in_service: true) + assert_equal 0, @engine.hours_in_service + assert_equal Date.current, @engine.date_in_service + end +end diff --git a/test/system/.keep b/test/system/.keep new file mode 100644 index 0000000..e69de29 diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..ccd6dde --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,36 @@ +ENV["RAILS_ENV"] ||= "test" +require_relative "../config/environment" +require "rails/test_help" + +module ActiveSupport + class TestCase + parallelize(workers: :number_of_processors) + + def create_user(email = "user#{SecureRandom.hex(3)}@example.com", admin: false) + User.create!(email_address: email, password: "password123", name: email.split("@").first, admin: admin) + end + + def create_aircraft(owner: nil, pilot: nil, **attrs) + Aircraft.create!({ tail_number: "N#{rand(10000..99999)}", tach_time: 1000 }.merge(attrs)).tap do |a| + a.roles.create!(user: owner, role: "owner") if owner + a.roles.create!(user: pilot, role: "pilot") if pilot + end + end + + def component_type(name = "Engine") + ComponentType.find_or_create_by!(name: name) + end + + def create_component(aircraft, **attrs) + aircraft.components.create!({ component_type: component_type, manufacturer: "Lycoming", model: "O-320", + status: "IN-USE", date_in_service: 1.year.ago.to_date }.merge(attrs)) + end + end +end + +class ActionDispatch::IntegrationTest + def sign_in(user) + post session_path, params: { email_address: user.email_address, password: "password123" } + follow_redirect! + end +end diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 0000000..e69de29 diff --git a/tmp/pids/.keep b/tmp/pids/.keep new file mode 100644 index 0000000..e69de29 diff --git a/tmp/storage/.keep b/tmp/storage/.keep new file mode 100644 index 0000000..e69de29 diff --git a/vendor/.keep b/vendor/.keep new file mode 100644 index 0000000..e69de29 diff --git a/vendor/javascript/.keep b/vendor/javascript/.keep new file mode 100644 index 0000000..e69de29