phpvms/app/Filament/Resources/Ranks/Schemas/RankForm.php
Nabeel S. de34422008
Updating styling and looks of the installer/admin/system filament pages (#2211)
* fix(installer): handle missing DB and fix CSRF middleware class

- InstalledCheck: wrap Schema::hasTable in try-catch to handle when
database is unreachable or does not exist, preventing crash before
installer can redirect
- SystemPanelProvider, AdminPanelProvider: fix non-existent
PreventRequestForgery class to ValidateCsrfToken (Laravel 12)
- .env.example: change default SESSION_DRIVER from database to file
so fresh installs don't require sessions table before migrations run

* Filament installer/system styles and changes

* Don't include frontend js in system/admin

* Don't include frontend js in system/admin

* fix(translations): normalize 'informations' and snake_case keys

- Fix ungrammatical plural 'informations' → 'Information' across all locales
- Rename joined-word translation keys to snake_case convention:
  auth: create_account, forgot_password, full_name, email_address, etc.
  pireps: new_flight_report, flight_time, flight_level, fields_readonly, etc.
  common: newest_pilots, live_map, rights_reserved, toggle_colors
  flights: flight_time, profile: transfer_hours, widgets: live_map
  dashboard: total_hours, your_balance, your_last_report, no_reports_yet
- Update all PHP/Blade references to renamed keys
- Add missing translation keys to non-English locales (send_reset_link,
  comment, error_changing_state, fields, field_value, landing_rate, etc.)
- Fix fr/filament.php: two keys on single line
- Fix en/aircraft.php: double space in 'Dry Weight'
- Run Pint on all modified files

* Design and other small changes

* feat(admin): add News Filament resource and seed PIREP sample data

Replace the dashboard News widget with a full Filament resource that
opens Create/Edit in modals (no separate pages routed). Adds the
matching policy so filament-shield can wire permissions.

Add a dev seed script (scripts/seed_sample_pireps.php) that inserts
sample airports, subfleets, aircraft, and 10 admin-owned PIREPs (last
two PENDING) to populate an empty database for UI testing.

Fix lazy-load exception on the PIREPs admin table by eager-loading
airline, aircraft and user via modifyQueryUsing; the table only worked
before because the database had no PIREPs.

* chore(admin): pending Filament panel refactor in working tree

Pre-existing uncommitted work from earlier sessions. Not authored or
reviewed in this commit's session; batched here only to clear the
working tree.

Includes:
- Airports resource simplified to modal-via-no-route pattern
  (CreateAirport, EditAirport page stubs deleted; getPages trimmed
  to index only)
- Modules page renamed to Addons
- New plugins: ClearCachesPlugin, SidebarCollapseTogglePlugin
- ClearCaches Livewire component
- Filament admin theme.css restyle
- NavigationGroup enum + lang/common, lang/filament tweaks
- system/brand.blade.php moved to shared/brand.blade.php
- Override attribute normalization across Filament resources

* fix(review): address CodeRabbit PR #2211 review feedback

Critical
- Restore CSRF middleware (PreventRequestForgery) in Admin + System panels
- Fix Addons page redirectRoute (modules -> addons) in 3 actions
- SeederService: fix SplFileInfo TypeError, guard missing seed dir, arrow fn
- YamlSeeder: propagate $ignore_errors, fix SplFileInfo bug, guard file read,
  proper File facade import
- Installer: gate install via withoutGlobalScopes()->exists() not count(),
  drop duplicated stream() of full buffer after chunked streaming
- .env.example: APP_DEBUG/DEBUGBAR_ENABLED default to false

Bugs
- seed_sample_pireps.php: swap KSAN/KLAX lat/lon
- theme.css: drop phantom mobile ::before rule (no matching selector)
- module-links-topbar.blade: localize hardcoded Admin label
- seven/app.blade: drop @vite call referencing removed bundles

i18n
- de/auth: fix Adresse typo + translate send_reset_link
- de/installer.title: brand wordmark phpvms
- fr/auth.toc_accept: fix acceptez typo
- es-es/it/tr/jp/pt-br: translate 10 PIREP keys + send_reset_link/fill_captcha
- de/es-es/it/jp/tr/common: add toggle_colors

Cleanup
- Remove dead commented blocks (Installer headerActions, InstallSeeder,
  YamlSeeder, seed_sample_pireps section dividers)
- NewsResource label uses common.news namespace
- login-hero alt uses lowercase brand

Rector + Pint auto-fixes
- Add declare(strict_types=1) where missing
- Add arrow-fn return types for brandLogo + News table schema
- Standardize catch-block exception names

* wip: pre-plan baseline (pirep map work + admin/frontend JS split)

* feat(pireps): add PerformanceChartService for ACARS chart datasets

* feat(pireps): load fares/field_values + build performance chart payload

* refactor(pireps): drop relation manager tabs (will embed inline)

* feat(pireps): register Chart.js wrapper for performance charts

* feat(pireps): add detail page header + stat strip partial

* feat(pireps): add unified Route & Performance card partial

* feat(pireps): add notes + filed route partial

* feat(pireps): add detail sidebar partial

* feat(pireps): wire new detail blade composition + embedded RMs

* feat(pireps): style v2 detail page (Stripe-flavored, theme tokens, dark mode)

* chore(pireps): drop legacy .fi-pirep-modal-* styles

* fix(pireps): inline Acars query to satisfy PHPStan level 5

larastan does not forward #[Scope] attribute methods through
HasMany relation builders, so calling `->ofType()->orderedByCreatedAt()`
on the relation tripped method.notFound at PHPStan level 5.

Replace with explicit where() + orderBy() — same runtime behavior,
no scope-forwarding surface for the analyzer to miss.

* fix(pireps): prune wasted eager loads + preserve zero-fuel samples

- Eager-load `user.rank` (sidebar reads $pilot->rank->name and would N+1
  on every detail page view).
- Drop `comments.user`, `transactions`, `fares.fare` from loadMissing —
  the embedded relation managers issue their own queries, so preloading
  at the page level only adds round-trips for data the page itself never
  uses.
- Fix fuel series to treat a fuel value of `0` as a real sample rather
  than null. Previously `$s->fuel ? ... : null` collapsed legitimate
  empty-tanks readings into gaps.

* fix(pireps): restore eager loads for embedded relation managers

Filament relation managers ARE separate Livewire queries, but their
blade columns still reach into nested relations on each row
(e.g. PirepFare->fare in FaresRelationManager). With lazy loading
disabled globally via Model::preventLazyLoading, those accesses
hard-fail with LazyLoadingViolationException.

Restore comments.user / transactions / fares.fare to the parent
loadMissing(). Keep user.rank from the earlier fix.

Reverts the wasted-load optimization in d6a8a3b5 — the optimization
was based on speculation, not measurement, and broke real
runtime behavior. Net effect: one extra preload per detail page,
versus a 500 error.

Refs: detail.blade.php:46 @livewire(FaresRelationManager)

* fix(pireps): address review findings (eager loads, ts null guard, downsample tail)

Tier A fixes from post-merge review of the redesign branch.

ViewPirep::mount
- Add fares.pirep + field_values.pirep to loadMissing. The FaresRelationManager
  and FieldValuesRelationManager column `disabled` closures call
  `$record->pirep->read_only` per row. Under Model::preventLazyLoading
  (active in dev/test) that triggered a lazy-load violation when editing
  any fare/field value. Production silently lazy-loaded on every edit.
- Drop airline from loadMissing. No partial or relation manager touches the
  airline relation; the preload was dead weight.

PerformanceChartService::ts
- Guard against null Acars$created_at (documented Carbon|null; partial imports
  leave it unset). Use \DateTimeInterface instanceof check rather than ?->,
  because larastan narrows the model property to non-null Carbon and reports
  nullsafe.neverNull at level 5 even when the runtime type is genuinely null.

PerformanceChartService::downsample
- Always include the final sample. Previously `$i % $step === 0` could drop
  the last point when total count was not a multiple of step, hiding the
  touchdown / arrival sample from the chart. Index 0 stays included via
  the existing modulo, so first + last are both preserved.

* refactor(pireps): drop route text card, restore route bar under map

Removes the raw waypoint route card from the PIREP view (notes partial),
restores the route bar (departure/arrival ICAO + name + block times + line)
that sits below the map in route-performance partial, and re-adds its
matching CSS in the admin theme.

- resources/views/filament/pireps/detail/notes.blade.php: remove route text card
- resources/views/filament/pireps/detail/route-performance.blade.php: restore route bar block + php helpers (blockOff/blockOn/duration/unitDistance)
- resources/css/filament/admin/theme.css: restore .fi-pirep-detail-v2-route-bar styles

* wip(pireps): landing analysis card, perf chart split, comment policy + tooling

Bundles in-progress PIREP detail work plus build tooling that landed in the
working tree:

PIREP detail
- Landing analysis card: runway plan-views, scorecard polar, attitude
  indicators (route-performance partial owns the markup; see prior commit).
- PerformanceChartService: build landing payload + extra chart series.
- Sidebar + modal/detail partials: stacked custom-fields card, layout tweaks.
- PirepCommentPolicy + RelationManager wiring for per-row authorization.

Assets
- Split AlpineComponents into resources/js/components/{pirep-landing-analysis,pirep-performance-chart}.js.
- bin/build.js esbuild driver; package.json/vite.config.js/.gitignore updates.
- Drop legacy resources/js/admin/pirep-performance-chart.js (moved to components/).

Misc
- AdminPanelProvider, base_map.js, config/services.php small adjustments.
- justfile task runner.
- composer/package lock updates.

* feat(admin): improve PIREP detail page layout and theming

- Split fares/transactions into separate cards (was single Finance card)
- Fares: plain text columns, no pagination, currency formatting
- Transactions: JetBrains Mono money amounts, no pagination
- Net total row in its own card
- Sidebar facts (Pilot/Flight) use stacked layout matching PIREP fields
- JetBrains Mono font for all money values (fi-pirep-money-mono)
- Map switches CartoDB.Voyager/DarkMatter on theme change
- Admin sidebar width 14.5rem
- PIREP detail sidebar sticky positioning accounts for topbar

* View pirep page updates

* fix: admin pirep page UX improvements and chart stability

- View PIREP button: transparent background, no fill
- Flight number links to view PIREP page
- PIREP detail heading shows flight number + route (VMS7620 C.PF MMMX→MMAA)
- Hero section: pilot name + aircraft on top line, filed time + source on secondary
- Sidebar: remove sticky scroll, let entire page scroll naturally
- Performance chart: fix canvas detachment on tab switch by wrapping in wire:ignore parent and using .canvas

* Shape up finances table

* feat: add flight log timeline tab with phase-colored badges

Two-column flight strip on Flight Log tab rendering ACARS LOG entries
(type=2) with timestamp/altitude/speed badges and phase assignment
from PerformanceChartService phase detection. Sort toggle flips
between earliest-first and latest-first order.

* fix(review): address code review blockers

- phpunit.xml: restore DB_CONNECTION=sqlite (suite was hitting MySQL
  with :memory: database name, all tests 500ing on first query)
- ViewPirep::getHeading: use typed $this->record over getRecord()
  to fix 4 phpstan property.notFound errors at level 5
- NewsResource: drop user_id overwrite on EditAction; preserved the
  original author. user_id only set on create now.
- PerformanceChartService: remove discarded toFloat call on landing
  speed (no consumer anywhere in codebase)

Pre-PR checks: pint v, phpstan v, rector v, pest v (368 passed).

* chore(review): tidy review minors

- finance widgets: refresh /livewire/update comment to v4 hashed path
  format; widget visibility logic is path-agnostic so behavior unchanged
- seed_sample_pireps: make bulk PIREP loop idempotent. lookup by
  source_name + flight_number + airport pair so re-running the script
  no longer duplicates the 10 routes on each invocation

* fix(pireps): flight-log rows respect dark mode

Inline style="background: #..." on each row + badge was overriding
the dark-mode CSS rules, leaving alternating rows white in dark mode.

- blade: drop the phaseColor/phaseBg/phaseTextColor/rowBg PHP closures.
  collapse to a single $phaseBucket helper that maps a phase code to a
  bucket name (ground/climb/cruise/descent/land/neutral). row + badge
  pick up CSS modifier classes instead of inline styles.
- theme.css: add zebra + phase tint rules for the row (.--zebra,
  .--phase-climb, .--phase-land) plus six badge variants. each has a
  light + dark pair using translucent tints with brighter text so the
  badge stays readable against the gray-900 row background.

* fix(ci): guard Vite::asset() against missing build manifest

composer install runs `package:discover` which boots service providers.
AdminPanelProvider::register() called Vite::asset() eagerly, throwing
ViteManifestNotFoundException on CI / fresh clones where composer runs
before npm has built the frontend.

Move the admin maps Js asset behind an `is_file(public_path(...))`
guard so the provider registers the rest of the assets unconditionally
and skips the Vite-resolved entry until the manifest exists. The map
blade has its own @vite() at render time so end-user behavior is
unchanged once `npm run build` has run.

Verified locally by removing public/build/manifest.json and running
composer dump-autoload — package:discover now completes cleanly.

* fix(ci): guard AlpineComponent assets against missing dist files

filament:upgrade (post-autoload-dump) was throwing on CI when copying
resources/js/dist/components/pirep-performance-chart.js to the public
assets folder. The esbuild'd Alpine components are produced by
bin/build.js and not committed, so a fresh clone has no dist directory
when composer post-autoload hooks run.

Loop the components through an `is_file()` guard like the Vite manifest
check added in the previous commit. Provider registration completes
when the frontend hasn't been built; the components register the
moment `npm run build` (or `node bin/build.js`) creates the files.

Verified by removing resources/js/dist and re-running
`php artisan filament:upgrade` — clean.

* chore(ci): build frontend before composer + commit dist artifacts

Two coordinated fixes for CI ordering + asset shipping:

(A) Reorder CI so Node + frontend build run BEFORE composer install.
The Laravel post-autoload-dump hook chain (package:discover ->
filament:upgrade) boots service providers which read the Vite manifest
and copy AlpineComponent files at register time. Running composer first
threw ViteManifestNotFoundException and copy() ENOENT on a fresh clone.

Affects all three jobs in build.yml:
- `build` (matrix x3 PHP versions): Node setup moved above composer
- `artifacts` (release packager): same swap
- `docker` (image builder): Node setup added (was composer-only)

(C) Commit `resources/js/dist/components/*.js` esbuild output. Removes
the runtime dependency on `node bin/build.js` for downstream consumers
(shared hosting installs, fresh composer-create-project flows). Matches
the existing convention for `public/js/filament/*` and
`public/assets/frontend/js/*` which are already committed pre-built.

A "Verify committed dist files match a fresh build" CI step diffs the
post-build tree against HEAD so contributors who edit the AlpineComponent
sources without re-running `npm run build:components` fail the build with
a clear error rather than shipping stale dist files.

The defensive `is_file()` guards in AdminPanelProvider stay (committed
in 7fdf2b2b + 97618bb8) — belt and suspenders against partial checkouts.

Refs PR #2211 review.

* chore(js): reorganize Filament components under admin/ + lint cleanup

CI lint failures surfaced two issues that local lint had buried under
1318 warnings from the committed esbuild output (Chart.js internals):

- resources/js/app.js was an empty stub (`//`), never imported anywhere.
  Removed.
- RW_RUNWAY_TOP in pirep-landing-analysis.js was declared but never
  used. Removed.

Folded in a directory reorg while touching the same files:

- Sources move to resources/js/admin/components/. Mirrors the existing
  resources/js/admin/ tree (request.js, storage.js, maps/, etc.) which
  was created in this branch for the admin-only JS split.
- Esbuild output mirrors the source layout — moves to
  resources/js/dist/admin/components/.
- bin/build.js entry + outfile paths updated.
- AdminPanelProvider resource_path() updated to match.

Tooling guards added so dist noise stops drowning real warnings:

- .oxlintrc.json: ignore resources/js/dist/** (bundled output)
- .oxfmtrc.json: ignore resources/js/dist/** (minified output)
- bin/build.js itself was new in this branch and not yet oxfmt-clean;
  reformatted (quotes/semis/indent).

Verified locally: oxlint 0 warnings 0 errors, fmt:check clean for all
tracked files, pint v, phpstan v, rector v.

* fix(ci): three-step bootstrap to break composer<->vite chicken-and-egg

The previous "npm before composer" reorder broke the build:
resources/css/filament/admin/theme.css imports
vendor/filament/filament/resources/css/theme.css, which doesn't exist
until composer install has run. Vite resolve failed at CI line 1.

Reverting to "composer before npm" re-triggers the original failure
(ViteManifestNotFoundException during package:discover; ENOENT during
filament:upgrade) because composer post-autoload-dump boots service
providers that need the Vite manifest + dist files.

Fix: three-step bootstrap, applied to all three jobs in build.yml.

  1. composer install --no-scripts
       Pulls vendor/ (Vite needs it for theme.css @imports) WITHOUT
       firing post-autoload-dump (which would boot the providers
       prematurely).
  2. npm install + npm run build
       Now resolves the vendor CSS @import. Produces
       public/build/manifest.json and rebuilds
       resources/js/dist/admin/components/*.js.
  3. composer dump-autoload
       Re-fires post-autoload-dump. package:discover and
       filament:upgrade boot providers cleanly — the Vite manifest
       and dist files are both present.

Verified locally inside the dev container: removed vendor/,
public/build/, resources/js/dist/, ran the three steps, all clean.

The freshness check (git diff --exit-code resources/js/dist) and the
build matrix's lint/fmt/pint/pest/phpstan stages run unchanged — only
the bootstrap order in front of them changes.

* fix(installer): address CodeRabbit review feedback

- Add Response return type to InstalledCheck::handle()
- Translate hero_title for es-es, fr, pt-br locales
- Standardize brand alt text to 'phpvms'
- Null-safe source label in PIREP row blade to avoid error
  when source_name is set but source enum is null
- Render landing_rate stat box for 0 values (use !== null check)

* chore(build): stop committing compiled JS/CSS assets

Untrack frontend build artifacts and rely on CI to (re)build them:

- resources/js/dist/ AlpineComponents (output of bin/build.js)
- public/js/filament/, public/css/filament/, public/fonts/filament/
- public/css/filament-spatie-backup/

The Filament assets are re-published by 'php artisan filament:upgrade'
during composer post-autoload-dump. The AlpineComponents are produced by
'npm run build'. Both already run in build.yml and release.yml.

Also drop the now-obsolete 'verify committed dist files match a fresh
build' step in CI \u2014 dist files are no longer tracked.

* refactor(filament): remove is_file guards around admin assets

The guards were added when composer post-autoload-dump could fire before
`npm run build` produced the frontend artifacts. CI now does a three-step
bootstrap (composer install --no-scripts -> npm build -> composer
dump-autoload) so dist files and the Vite manifest always exist by the
time AdminPanelProvider::register() runs. Release tarballs ship them
pre-built.

If assets are missing at runtime we want to know immediately, not
silently degrade the admin panel.

* refactor(filament): mirror Pireps namespace under views/filament/pireps

Co-locate page views and partials under resources/views/filament/pireps/
to mirror App\Filament\Resources\Pireps namespace.

- pages/{list-pireps,view-pirep}.blade.php (was filament/resources/pireps/pages/)
- partials/row.blade.php + partials/detail/* (was filament/pireps/{row,detail}/)
- Update $view in ListPireps and ViewPirep
- Rewrite 6 @include paths

* chore(build): add npm clean script to remove built assets

Removes public/build (Vite output) and resources/js/dist (esbuild
components output) in one command.

* Add the fillament public assets back in

* Move the vite js into the page render hook, lazily load map on first use
2026-05-20 11:05:32 -05:00

83 lines
3.6 KiB
PHP

<?php
namespace App\Filament\Resources\Ranks\Schemas;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
class RankForm
{
public static function configure(Schema $schema): Schema
{
return $schema
->components([
Section::make(__('filament.rank_information'))
->schema([
Grid::make()
->schema([
TextInput::make('name')
->label(__('common.name'))
->required()
->string(),
TextInput::make('image_url')
->label(__('common.image_url'))
->string(),
])
->columnSpanFull()
->columns(),
Grid::make()
->schema([
TextInput::make('hours')
->label(trans_choice('common.hour', 2))
->required()
->numeric()
->minValue(0),
TextInput::make('acars_base_pay_rate')
->label(__('filament.rank_acars_base_pay_rate'))
->numeric()
->minValue(0)
->helperText(__('filament.rank_acars_base_pay_rate_hint')),
TextInput::make('manual_base_pay_rate')
->label(__('filament.rank_manual_base_pay_rate'))
->numeric()
->minValue(0)
->helperText(__('filament.rank_manual_base_pay_rate_hint')),
Toggle::make('auto_approve_acars')
->label(__('filament.rank_auto_approve_acars'))
->offIcon(Heroicon::XCircle)
->offColor('danger')
->onIcon(Heroicon::CheckCircle)
->onColor('success'),
Toggle::make('auto_approve_manual')
->label(__('filament.rank_auto_approve_manual'))
->offIcon(Heroicon::XCircle)
->offColor('danger')
->onIcon(Heroicon::CheckCircle)
->onColor('success'),
Toggle::make('auto_promote')
->label(__('filament.rank_auto_promote'))
->helperText(__('filament.rank_auto_promote_hint'))
->offIcon(Heroicon::XCircle)
->offColor('danger')
->onIcon(Heroicon::CheckCircle)
->onColor('success'),
])
->columnSpanFull()
->columns(3),
])
->columnSpanFull(),
]);
}
}