From f15bf836a729b781d21cffd196f54a8f979a7c79 Mon Sep 17 00:00:00 2001 From: roble Date: Thu, 5 Nov 2026 15:09:31 +0000 Subject: [PATCH 1/6] feat: add queue, schedule and workers tasks and a Taskfile sync command (sc-1110) Co-Authored-By: Claude Opus 5.5 --- .../Commands/SyncModuleTaskfileCommand.php | 35 +++++++++++ src/CoreServiceProvider.php | 2 + src/ModuleTaskfile.php | 36 ++++++++++- stubs/app/Taskfile.yml | 12 ++++ tests/Feature/InstallCommandTest.php | 12 ++++ .../Feature/SyncModuleTaskfileCommandTest.php | 59 +++++++++++++++++++ 6 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 src/Console/Commands/SyncModuleTaskfileCommand.php create mode 100644 tests/Feature/SyncModuleTaskfileCommandTest.php diff --git a/src/Console/Commands/SyncModuleTaskfileCommand.php b/src/Console/Commands/SyncModuleTaskfileCommand.php new file mode 100644 index 0000000..ecea57e --- /dev/null +++ b/src/Console/Commands/SyncModuleTaskfileCommand.php @@ -0,0 +1,35 @@ +modules() + ->filter(fn ($module): bool => file_exists($module->path('Taskfile.yml'))) + ->map(fn ($module): string => $module->name) + ->sort() + ->values() + ->all(); + + if (! ModuleTaskfile::sync($modules)) { + $this->components->error('Taskfile.yml needs the BEGIN MODULES and END MODULES markers.'); + + return self::FAILURE; + } + + $this->components->info(count($modules).' module(s) listed in Taskfile.yml.'); + + return self::SUCCESS; + } +} diff --git a/src/CoreServiceProvider.php b/src/CoreServiceProvider.php index 1856c7f..e73dd80 100644 --- a/src/CoreServiceProvider.php +++ b/src/CoreServiceProvider.php @@ -21,6 +21,7 @@ use Saucebase\Core\Console\Commands\RecipeToModuleCommand; use Saucebase\Core\Console\Commands\SeedModulesCommand; use Saucebase\Core\Console\Commands\SyncModuleBoostCommand; +use Saucebase\Core\Console\Commands\SyncModuleTaskfileCommand; use Saucebase\Core\Http\Middleware\HandleAppearance; use Saucebase\Core\Http\Middleware\HandleInertiaRequests; use Saucebase\Core\Http\Middleware\HandleLocalization; @@ -105,6 +106,7 @@ public function boot(): void ModuleSetupCommand::class, RecipeToModuleCommand::class, SeedModulesCommand::class, + SyncModuleTaskfileCommand::class, SyncModuleBoostCommand::class, ]); diff --git a/src/ModuleTaskfile.php b/src/ModuleTaskfile.php index 0c32ccf..8775114 100644 --- a/src/ModuleTaskfile.php +++ b/src/ModuleTaskfile.php @@ -25,7 +25,7 @@ public static function add(string $module): void throw new RuntimeException("Unable to read Taskfile at [{$taskfile}]."); } - $entry = " {$module}:\n taskfile: ./modules/{$module}/Taskfile.yml\n optional: true\n"; + $entry = self::entry($module); $marker = ' # ── END MODULES'; if (str_contains($content, "taskfile: ./modules/{$module}/Taskfile.yml")) { @@ -40,4 +40,38 @@ public static function add(string $module): void file_put_contents($taskfile, substr($content, 0, $markerPosition).$entry.substr($content, $markerPosition)); } + + /** + * Replaces everything between the markers with these modules. + * + * @param string[] $modules + * @return bool False when the app has no Taskfile or no markers: nothing is changed. + */ + public static function sync(array $modules): bool + { + $taskfile = base_path('Taskfile.yml'); + $content = file_exists($taskfile) ? file_get_contents($taskfile) : false; + + if ($content === false || ! preg_match('/^ *# ── BEGIN MODULES.*\n/m', $content, $begin, PREG_OFFSET_CAPTURE)) { + return false; + } + + $start = $begin[0][1] + strlen($begin[0][0]); + $end = strpos($content, ' # ── END MODULES', $start); + + if ($end === false) { + return false; + } + + $entries = implode('', array_map(self::entry(...), $modules)); + + file_put_contents($taskfile, substr($content, 0, $start).$entries.substr($content, $end)); + + return true; + } + + private static function entry(string $module): string + { + return " {$module}:\n taskfile: ./modules/{$module}/Taskfile.yml\n optional: true\n"; + } } diff --git a/stubs/app/Taskfile.yml b/stubs/app/Taskfile.yml index 4cc93e8..f89fc2c 100644 --- a/stubs/app/Taskfile.yml +++ b/stubs/app/Taskfile.yml @@ -21,6 +21,18 @@ tasks: desc: Start dev server (app, queue, logs, vite) cmd: composer dev + queue: + desc: Run the queue worker (restarts when code changes) + cmd: '{{.APP}} php artisan queue:listen --tries=1 --timeout=0' + + schedule: + desc: Run the scheduler (runs due tasks every minute) + cmd: '{{.APP}} php artisan schedule:work' + + workers: + desc: Run the queue worker and scheduler together + deps: [queue, schedule] + build: desc: Production build (includes SSR) cmd: npm run build diff --git a/tests/Feature/InstallCommandTest.php b/tests/Feature/InstallCommandTest.php index c403947..da779c9 100644 --- a/tests/Feature/InstallCommandTest.php +++ b/tests/Feature/InstallCommandTest.php @@ -6,6 +6,7 @@ use Illuminate\Filesystem\Filesystem; use PHPUnit\Framework\Attributes\DataProvider; use Saucebase\Core\Tests\TestCase; +use Symfony\Component\Yaml\Yaml; class InstallCommandTest extends TestCase { @@ -85,6 +86,17 @@ public function test_it_publishes_a_taskfile_with_an_empty_app_prefix(): void $this->assertStringContainsString("APP: ''", $this->read('Taskfile.yml')); } + public function test_the_taskfile_runs_the_queue_and_scheduler_without_a_web_server(): void + { + $this->artisan('saucebase:install', ['framework' => 'vue', '--force' => true])->assertSuccessful(); + + $tasks = Yaml::parse($this->read('Taskfile.yml'))['tasks']; + + $this->assertStringContainsString('{{.APP}} php artisan queue:listen', $tasks['queue']['cmd']); + $this->assertStringContainsString('{{.APP}} php artisan schedule:work', $tasks['schedule']['cmd']); + $this->assertSame(['queue', 'schedule'], $tasks['workers']['deps']); + } + public function test_the_published_example_test_migrates_the_database(): void { $this->artisan('saucebase:install', ['framework' => 'vue', '--force' => true])->assertSuccessful(); diff --git a/tests/Feature/SyncModuleTaskfileCommandTest.php b/tests/Feature/SyncModuleTaskfileCommandTest.php new file mode 100644 index 0000000..9039f94 --- /dev/null +++ b/tests/Feature/SyncModuleTaskfileCommandTest.php @@ -0,0 +1,59 @@ +taskfile( + "includes:\n # ── BEGIN MODULES\n gone:\n taskfile: ./modules/gone/Taskfile.yml\n optional: true\n # ── END MODULES\n\ntasks:\n # kept\n" + ); + + $this->artisan('saucebase:taskfile-sync')->assertSuccessful(); + + $content = file_get_contents($taskfile); + $this->assertStringContainsString(" module-test-fixture:\n taskfile: ./modules/module-test-fixture/Taskfile.yml\n optional: true\n # ── END MODULES", $content); + $this->assertStringNotContainsString('gone', $content); + $this->assertStringNotContainsString('module-order-fixture', $content); + $this->assertStringContainsString("tasks:\n # kept\n", $content); + } + + public function test_running_it_again_changes_nothing(): void + { + $taskfile = $this->taskfile("includes:\n # ── BEGIN MODULES\n # ── END MODULES\n"); + + $this->artisan('saucebase:taskfile-sync')->assertSuccessful(); + $first = file_get_contents($taskfile); + $this->artisan('saucebase:taskfile-sync')->assertSuccessful(); + + $this->assertSame($first, file_get_contents($taskfile)); + } + + public function test_a_taskfile_without_the_markers_is_left_alone(): void + { + $taskfile = $this->taskfile($content = "tasks:\n dev:\n cmd: npm run dev\n"); + + $this->artisan('saucebase:taskfile-sync')->assertFailed(); + + $this->assertSame($content, file_get_contents($taskfile)); + } + + private function taskfile(string $content): string + { + $appPath = sys_get_temp_dir().'/saucebase-taskfile-sync-'.uniqid(); + mkdir($appPath); + file_put_contents($appPath.'/Taskfile.yml', $content); + $this->app->setBasePath($appPath); + $this->beforeApplicationDestroyed(fn () => (new Filesystem)->deleteDirectory($appPath)); + + return $appPath.'/Taskfile.yml'; + } +} From 76d55af6f94dae849b8e93178b55a25221725ee1 Mon Sep 17 00:00:00 2001 From: roble Date: Thu, 5 Nov 2026 16:37:56 +0000 Subject: [PATCH 2/6] feat: create the E2E env file on install (sc-1108) Co-Authored-By: Claude Opus 5.5 --- src/Console/Commands/InstallCommand.php | 6 ++++++ stubs/app/README.md | 2 +- tests/Feature/InstallCommandTest.php | 20 ++++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/Console/Commands/InstallCommand.php b/src/Console/Commands/InstallCommand.php index 640f6a8..6295af8 100644 --- a/src/Console/Commands/InstallCommand.php +++ b/src/Console/Commands/InstallCommand.php @@ -4,6 +4,7 @@ use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; +use Illuminate\Support\Facades\Artisan; use Illuminate\Support\ServiceProvider; use Saucebase\Core\Console\Traits\DisplaysBanner; use Saucebase\Core\ProjectConfig; @@ -83,6 +84,11 @@ public function handle(Filesystem $files, ProjectConfig $config): int $this->publishStack($files, $stubs.'/stack', $framework); + // A package's require-dev never reaches the app, so a manual install may not have it. + if (array_key_exists('playwright:env', Artisan::all())) { + $this->call('playwright:env', ['--no-interaction' => true]); + } + $this->components->info("Saucebase is installed with {$framework}."); $this->components->bulletList([ 'npm install && npm run build', diff --git a/stubs/app/README.md b/stubs/app/README.md index d0d0318..dd65708 100644 --- a/stubs/app/README.md +++ b/stubs/app/README.md @@ -40,7 +40,7 @@ php artisan test # PHPUnit npm run test:e2e # Playwright ``` -**`npm run test:e2e` runs on its own server and database**, from `.env.e2e`, so your app's data stays untouched. Create the file once with `php artisan playwright:env` (a copy of `.env` with its own SQLite database and port). +**`npm run test:e2e` runs on its own server and database**, from `.env.e2e`, so your app's data stays untouched. `saucebase:install` creates it, a copy of `.env` with its own SQLite database and port. Run `php artisan playwright:env` to create it again. ## Learn more diff --git a/tests/Feature/InstallCommandTest.php b/tests/Feature/InstallCommandTest.php index da779c9..4364185 100644 --- a/tests/Feature/InstallCommandTest.php +++ b/tests/Feature/InstallCommandTest.php @@ -4,6 +4,7 @@ use Database\Factories\UserFactory; use Illuminate\Filesystem\Filesystem; +use Illuminate\Support\Facades\Artisan; use PHPUnit\Framework\Attributes\DataProvider; use Saucebase\Core\Tests\TestCase; use Symfony\Component\Yaml\Yaml; @@ -97,6 +98,25 @@ public function test_the_taskfile_runs_the_queue_and_scheduler_without_a_web_ser $this->assertSame(['queue', 'schedule'], $tasks['workers']['deps']); } + public function test_it_writes_the_e2e_env_when_the_playwright_package_is_installed(): void + { + $ran = false; + Artisan::command('playwright:env', function () use (&$ran) { + $ran = ! $this->input->isInteractive(); + }); + + $this->artisan('saucebase:install', ['framework' => 'vue', '--force' => true])->assertSuccessful(); + + $this->assertTrue($ran, 'playwright:env should run, unattended, so it can never replace a file.'); + } + + public function test_it_installs_without_the_playwright_package(): void + { + $this->assertArrayNotHasKey('playwright:env', Artisan::all()); + + $this->artisan('saucebase:install', ['framework' => 'vue', '--force' => true])->assertSuccessful(); + } + public function test_the_published_example_test_migrates_the_database(): void { $this->artisan('saucebase:install', ['framework' => 'vue', '--force' => true])->assertSuccessful(); From 5b9a1ccb6feb23010df49002d9d284e42ab91454 Mon Sep 17 00:00:00 2001 From: roble Date: Fri, 6 Nov 2026 10:15:35 +0000 Subject: [PATCH 3/6] chore: forbid nested ternaries in both stacks' ESLint config Co-Authored-By: Claude Opus 5.5 --- stubs/stack/react/config/eslint.config.js | 2 ++ stubs/stack/vue/config/eslint.config.js | 2 ++ 2 files changed, 4 insertions(+) diff --git a/stubs/stack/react/config/eslint.config.js b/stubs/stack/react/config/eslint.config.js index d92f906..ff6e5f6 100644 --- a/stubs/stack/react/config/eslint.config.js +++ b/stubs/stack/react/config/eslint.config.js @@ -17,6 +17,8 @@ export default tseslint.config( { rules: { '@typescript-eslint/no-explicit-any': 'off', + // Nested conditionals read as a puzzle: an if/else, a lookup or a computed instead. + 'no-nested-ternary': 'error', // v7 rules designed for the React compiler — disable until the project adopts it 'react-hooks/refs': 'off', 'react-hooks/static-components': 'off', diff --git a/stubs/stack/vue/config/eslint.config.js b/stubs/stack/vue/config/eslint.config.js index 89b1aa1..b884211 100644 --- a/stubs/stack/vue/config/eslint.config.js +++ b/stubs/stack/vue/config/eslint.config.js @@ -61,6 +61,8 @@ export default defineConfigWithVueTs( rules: { 'vue/multi-word-component-names': 'off', '@typescript-eslint/no-explicit-any': 'off', + // Nested conditionals read as a puzzle: an if/else, a lookup or a computed instead. + 'no-nested-ternary': 'error', }, }, prettier, From 64f463b64eb95980a26ee67579462c4317d36b77 Mon Sep 17 00:00:00 2001 From: roble Date: Fri, 6 Nov 2026 14:00:01 +0000 Subject: [PATCH 4/6] feat: throw when two sources declare the same capability in a group (sc-1114) Co-Authored-By: Claude Opus 5.5 --- src/Capabilities.php | 46 ++++++++++++++++++++++++--- tests/Feature/CapabilitiesTest.php | 50 ++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 5 deletions(-) diff --git a/src/Capabilities.php b/src/Capabilities.php index c8046c9..8aa622c 100644 --- a/src/Capabilities.php +++ b/src/Capabilities.php @@ -5,6 +5,7 @@ use Closure; use InterNACHI\Modular\Support\ModuleConfig; use InterNACHI\Modular\Support\ModuleRegistry; +use LogicException; /** * One catalog of what can be granted, grouped by who reads it: `api` for what a @@ -19,7 +20,12 @@ */ class Capabilities { - /** @var array>|Closure(): array>>> */ + /** + * By group, then by where `add()` was called (`file:line`), so a declaration that runs + * again replaces itself. + * + * @var array>|Closure(): array>>> + */ private array $entries = []; private bool $loaded = false; @@ -29,13 +35,31 @@ public function __construct(private readonly ModuleRegistry $modules) {} /** @param array>|Closure(): array> $entries key => ['label' => …, 'description' => …] */ public function add(string $group, array|Closure $entries): void { - $this->entries[$group][] = $entries; + $this->entries[$group][self::caller()] = $entries; + } + + /** + * Where `add()` was called from, past the facade. Modular also requires a module's + * `routes/*.php` at boot, so without a route cache a capabilities file runs twice: + * keyed by its call site, the repeat is the same declaration, not a second one. + */ + private static function caller(): string + { + foreach (debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6) as $frame) { + $file = $frame['file'] ?? null; + + if ($file !== null && $file !== __FILE__ && ! str_ends_with($file, 'Facades/Facade.php')) { + return $file.':'.($frame['line'] ?? 0); + } + } + + return 'unknown'; } /** * Every entry in the group, labels translated (the key when there is none). * Keys besides label and description (`read_only`) pass through for the - * group's reader. + * group's reader. A key declared by two sources in one group throws; across groups it is fine. * * @return array> */ @@ -43,8 +67,20 @@ public function group(string $group): array { $this->load(); - return collect($this->entries[$group] ?? []) - ->flatMap(fn (array|Closure $entries): array => $entries instanceof Closure ? $entries() : $entries) + $all = []; + + foreach ($this->entries[$group] ?? [] as $entries) { + foreach ($entries instanceof Closure ? $entries() : $entries as $key => $entry) { + // Two sources would leave one silently replacing the other, even when they agree. + if (array_key_exists($key, $all)) { + throw new LogicException("The capability [{$key}] is declared twice in the [{$group}] group."); + } + + $all[$key] = $entry; + } + } + + return collect($all) ->map(fn (array $entry, string $key): array => [ ...$entry, 'label' => __($entry['label'] ?? $key), diff --git a/tests/Feature/CapabilitiesTest.php b/tests/Feature/CapabilitiesTest.php index ebe6c99..2c3c555 100644 --- a/tests/Feature/CapabilitiesTest.php +++ b/tests/Feature/CapabilitiesTest.php @@ -2,6 +2,7 @@ namespace Saucebase\Core\Tests\Feature; +use LogicException; use Saucebase\Core\Capabilities; use Saucebase\Core\Facades\Capabilities as CapabilitiesFacade; use Saucebase\Core\Tests\Concerns\InteractsWithFixtureModules; @@ -62,4 +63,53 @@ public function test_files_load_once_per_application(): void $this->assertCount(1, $capabilities->group('api')); $this->assertSame($capabilities, $this->app->make(Capabilities::class)); } + + /** + * Two sources claiming one key with different meanings would let the second silently + * win: say which key. + */ + public function test_a_key_declared_twice_in_a_group_throws(): void + { + CapabilitiesFacade::add('billing', ['webhooks' => []]); + CapabilitiesFacade::add('billing', fn (): array => ['webhooks' => ['label' => 'Again']]); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('[webhooks]'); + + CapabilitiesFacade::group('billing'); + } + + /** + * Modular also requires a module's `routes/*.php` at boot, so without a route cache its + * capabilities file runs twice. One declaration running again replaces itself. + */ + public function test_the_same_declaration_running_again_is_not_a_conflict(): void + { + $declare = fn () => CapabilitiesFacade::add('billing', ['webhooks' => ['label' => 'Webhooks']]); + $declare(); + $declare(); + + $this->assertSame(['webhooks' => ['label' => 'Webhooks', 'description' => '']], CapabilitiesFacade::group('billing')); + } + + /** Two sources are a conflict even when they agree: one of them should not be declaring it. */ + public function test_two_sources_declaring_an_identical_key_throw(): void + { + CapabilitiesFacade::add('billing', ['webhooks' => ['label' => 'Webhooks']]); + CapabilitiesFacade::add('billing', ['webhooks' => ['label' => 'Webhooks']]); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('[webhooks]'); + + CapabilitiesFacade::group('billing'); + } + + /** Groups are read by different readers, so one key may mean something in each. */ + public function test_the_same_key_may_appear_in_different_groups(): void + { + CapabilitiesFacade::add('billing', ['posts' => []]); + + $this->assertArrayHasKey('posts', CapabilitiesFacade::group('api')); + $this->assertArrayHasKey('posts', CapabilitiesFacade::group('billing')); + } } From 3a32e7cd3cb40c439607c10ee6758f3fab504c73 Mon Sep 17 00:00:00 2001 From: roble Date: Fri, 6 Nov 2026 19:57:10 +0000 Subject: [PATCH 5/6] feat: dashboard period filter, Period and TrendStat for widgets, and the app stub's dashboard (sc-1113) Co-Authored-By: Claude Opus 5.5 --- .../saucebase-filament-development/SKILL.md | 11 ++ src/Filament/Concerns/ReadsPeriod.php | 17 ++ src/Filament/Pages/Dashboard.php | 87 +++++++++ src/Filament/Period.php | 168 ++++++++++++++++++ src/Filament/TrendStat.php | 44 +++++ .../Filament/Admin/Widgets/UsersWidget.php | 47 +++++ .../Providers/Filament/AdminPanelProvider.php | 15 +- .../app/tests/Feature/AdminDashboardTest.php | 79 ++++++++ tests/Feature/DashboardPeriodTest.php | 87 +++++++++ tests/Feature/PeriodTest.php | 151 ++++++++++++++++ tests/Fixtures/Filament/PeriodWidget.php | 17 ++ tests/Fixtures/Filament/TestPanelProvider.php | 2 +- tests/Unit/Filament/TrendStatTest.php | 47 +++++ tests/Unit/Stubs/AdminPanelStubTest.php | 30 ++++ 14 files changed, 790 insertions(+), 12 deletions(-) create mode 100644 src/Filament/Concerns/ReadsPeriod.php create mode 100644 src/Filament/Pages/Dashboard.php create mode 100644 src/Filament/Period.php create mode 100644 src/Filament/TrendStat.php create mode 100644 stubs/app/app/Filament/Admin/Widgets/UsersWidget.php create mode 100644 stubs/app/tests/Feature/AdminDashboardTest.php create mode 100644 tests/Feature/DashboardPeriodTest.php create mode 100644 tests/Feature/PeriodTest.php create mode 100644 tests/Fixtures/Filament/PeriodWidget.php create mode 100644 tests/Unit/Filament/TrendStatTest.php create mode 100644 tests/Unit/Stubs/AdminPanelStubTest.php diff --git a/resources/boost/skills/saucebase-filament-development/SKILL.md b/resources/boost/skills/saucebase-filament-development/SKILL.md index f5309a4..a12d00b 100644 --- a/resources/boost/skills/saucebase-filament-development/SKILL.md +++ b/resources/boost/skills/saucebase-filament-development/SKILL.md @@ -69,6 +69,17 @@ class FeaturePlugin implements Plugin The `ModulePlugin` trait discovers Pages, Resources and Widgets under `src/Filament/`, and Livewire components under `src/Livewire/`. +### Dashboard widgets + +The panel's dashboard is core's `Filament\Pages\Dashboard`: Filament's, with its `FilterAction` (`HasFiltersAction`) as the period filter. The header button, top right, shows the active period and opens a slide-over: a preset (Today, 7 days, 30 days default, 3 months, 12 months, custom) plus From and To. A preset fills the dates; editing a date makes it custom. Presets include today. Filters are `period`, `start`, `end`, kept in the URL and session. Other dashboards extend it and list their own `getWidgets()` (billing's does). + +- **Period:** `use Concerns\ReadsPeriod;` then `$this->period()` gives a `Filament\Period` (`start`, `end`, `previous()`, `labels()`). `$period->series($query, 'sum(amount)')` returns one value per bucket: days up to 31 days, weeks up to 92, then months. The database groups by `date()`, the same in SQLite, MySQL and PostgreSQL. +- **Stats:** `TrendStat::make($label, $now, $before, $chart, lowerIsBetter:, format:)` shows the value, the change against the previous period (green when good), and a trend line. With no baseline it says so instead of a percentage. +- **Order bands (`$sort`):** 10–19 stats, 20–29 needs attention, 30+ charts. Taken: 10 users (app), 11 workspaces (tenancy), 12 billing, 13 packages, 14 newsletter, 20 billing attention, 21 roadmap attention. Pick a free slot; `AdminDashboardTest` fails on a tie. +- **Size:** the dashboard has 2 columns. A widget with one or two stats sets `$columnSpan = 1` and `$columns` to its stat count, so it pairs with its neighbour; three or more stats take `'full'`. +- **Cost:** each lazy widget is its own request. Cache what's expensive (billing's `BillingMetrics` uses `Cache::flexible`, keyed by the dates), never what a person must act on now (attention counts). `tests/Load/DashboardLoadTest.php` times every widget: `LOAD_TEST=1 php -d memory_limit=4G artisan test tests/Load`. +- **Empty states:** no misleading zeros. Hide a widget in `canView()` until there's something to show (no packages, newsletter not configured, nothing needing attention), or show one stat linking to setup (billing without plans). Keep the permission check in `canView()` too. + Optional plugin hooks, read by core's `ModulesPlugin`: - `public static function getNavigationGroupSort(): int` orders plugin registration, and so the module's diff --git a/src/Filament/Concerns/ReadsPeriod.php b/src/Filament/Concerns/ReadsPeriod.php new file mode 100644 index 0000000..2372501 --- /dev/null +++ b/src/Filament/Concerns/ReadsPeriod.php @@ -0,0 +1,17 @@ +pageFilters); + } +} diff --git a/src/Filament/Pages/Dashboard.php b/src/Filament/Pages/Dashboard.php new file mode 100644 index 0000000..f4e838e --- /dev/null +++ b/src/Filament/Pages/Dashboard.php @@ -0,0 +1,87 @@ +label(fn (): string => $this->periodLabel()) + ->icon('heroicon-m-calendar') + ->fillForm(fn (): array => $this->filtersWithDates($this->filters)) + ->schema([ + Select::make('period') + ->label(__('Period')) + ->options(Period::options()) + ->selectablePlaceholder(false) + ->live() + ->afterStateUpdated(function (?string $state, Set $set): void { + if ($state !== 'custom') { + $dates = $this->filtersWithDates(['period' => $state]); + $set('start', $dates['start']); + $set('end', $dates['end']); + } + }), + DatePicker::make('start') + ->label(__('From')) + ->required() + ->live() + ->afterStateUpdated(fn (Set $set) => $set('period', 'custom')), + DatePicker::make('end') + ->label(__('To')) + ->required() + ->afterOrEqual('start') + ->live() + ->afterStateUpdated(fn (Set $set) => $set('period', 'custom')), + ]), + ]; + } + + /** The preset's name, or the custom range's dates. */ + private function periodLabel(): string + { + $preset = Period::preset($this->filters); + $period = Period::fromFilters($this->filters); + + // A custom range without valid dates has fallen back to the default: say so. + if ($preset !== 'custom' || ($period->end->isToday() && $period->start->equalTo(Period::fromFilters(null)->start))) { + return Period::options()[$preset === 'custom' ? Period::DEFAULT : $preset]; + } + + return $period->start->translatedFormat('M j, Y').' – '.$period->end->translatedFormat('M j, Y'); + } + + /** + * The saved filters with both dates filled in, so the form shows what a preset covers. + * + * @param array|null $filters + * @return array{period: string, start: string, end: string} + */ + private function filtersWithDates(?array $filters): array + { + $period = Period::fromFilters($filters); + + return [ + 'period' => Period::preset($filters), + 'start' => $period->start->toDateString(), + 'end' => $period->end->toDateString(), + ]; + } +} diff --git a/src/Filament/Period.php b/src/Filament/Period.php new file mode 100644 index 0000000..396dd41 --- /dev/null +++ b/src/Filament/Period.php @@ -0,0 +1,168 @@ + */ + public static function options(): array + { + return [ + 'today' => __('Today'), + '7d' => __('Last 7 days'), + '30d' => __('Last 30 days'), + '90d' => __('Last 3 months'), + '12m' => __('Last 12 months'), + 'custom' => __('Custom range'), + ]; + } + + /** The longest custom range, counted back from its end: every bucket is a chart point and a query row. */ + public const MAX_YEARS = 5; + + /** + * Filters come from the URL and the session, so anything that isn't a known preset or + * a real `Y-m-d` date falls back to the default rather than failing the page. + * + * @param array|null $filters + */ + public static function fromFilters(?array $filters): self + { + $preset = self::preset($filters); + $today = CarbonImmutable::today(); + + if ($preset === 'custom' && ($start = self::date($filters['start'] ?? null)) && ($end = self::date($filters['end'] ?? null))) { + [$start, $end] = $start <= $end ? [$start, $end] : [$end, $start]; + + return new self(max($start, $end->subYears(self::MAX_YEARS)->addDay()), $end->endOfDay()); + } + + $start = match ($preset) { + 'today' => $today, + '7d' => $today->subDays(6), + '90d' => $today->subDays(89), + '12m' => $today->subMonths(11)->startOfMonth(), + default => $today->subDays(29), + }; + + return new self($start, $today->endOfDay()); + } + + /** + * The preset the filters name, if it is one; else the default. + * + * @param array|null $filters + */ + public static function preset(?array $filters): string + { + $preset = $filters['period'] ?? null; + + return is_string($preset) && isset(self::options()[$preset]) ? $preset : self::DEFAULT; + } + + private static function date(mixed $value): ?CarbonImmutable + { + if (! is_string($value) || ! preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) { + return null; + } + + $date = CarbonImmutable::createFromFormat('!Y-m-d', $value); + + return $date && $date->format('Y-m-d') === $value ? $date : null; // 2026-02-30 rolls over: refuse it + } + + /** The same number of days, ending the day before this one starts. */ + public function previous(): self + { + $days = $this->days(); + + return new self($this->start->subDays($days), $this->start->subDay()->endOfDay()); + } + + /** @return 'day'|'week'|'month' */ + public function unit(): string + { + return match (true) { + $this->days() <= 31 => 'day', + $this->days() <= 92 => 'week', + default => 'month', + }; + } + + /** Percentage change from `$before` to `$now`; null when there is nothing to compare with. */ + public static function change(int|float $now, int|float $before): ?float + { + return $before == 0 ? null : round(($now - $before) / $before * 100, 1); + } + + /** + * One value per bucket, oldest first, empty buckets as 0. The database + * groups by day (`date()` is the same in SQLite, MySQL and PostgreSQL); + * days are added up into weeks or months here. + * + * @return list + */ + public function series(Builder $query, string $aggregate = 'count(*)', string $column = 'created_at'): array + { + $buckets = array_fill_keys(array_keys($this->labels()), 0); + + $rows = $query->whereBetween($column, [$this->start, $this->end]) + ->selectRaw("date({$column}) as bucket_day, {$aggregate} as bucket_value") + ->groupBy('bucket_day') + ->pluck('bucket_value', 'bucket_day'); + + foreach ($rows as $day => $value) { + $buckets[$this->bucketOf(CarbonImmutable::parse($day))] += 0 + $value; + } + + return array_values($buckets); + } + + /** @return array bucket key => label */ + public function labels(): array + { + $labels = []; + $cursor = $this->bucketStart($this->start); + + while ($cursor <= $this->end) { + $labels[$this->bucketOf($cursor)] = $cursor->translatedFormat($this->unit() === 'month' ? 'M Y' : 'M j'); + $cursor = $cursor->add(1, $this->unit()); + } + + return $labels; + } + + private function bucketOf(CarbonImmutable $day): string + { + return $this->bucketStart($day)->format('Y-m-d'); + } + + private function bucketStart(CarbonImmutable $day): CarbonImmutable + { + return match ($this->unit()) { + 'day' => $day->startOfDay(), + 'week' => $day->startOfWeek(), + 'month' => $day->startOfMonth(), + }; + } + + private function days(): int + { + return (int) $this->start->diffInDays($this->end->addSecond()); + } +} diff --git a/src/Filament/TrendStat.php b/src/Filament/TrendStat.php new file mode 100644 index 0000000..1528106 --- /dev/null +++ b/src/Filament/TrendStat.php @@ -0,0 +1,44 @@ + $chart + * @param (Closure(int|float): string)|null $format + */ + public static function make(string $label, int|float $now, int|float $before, array $chart = [], bool $lowerIsBetter = false, ?Closure $format = null): Stat + { + $stat = Stat::make($label, $format ? $format($now) : number_format($now)); + + if (array_filter($chart)) { + $stat->chart($chart); + } + + $change = Period::change($now, $before); + + if ($change === null) { + return $stat->description(__('No data for the previous period'))->color('gray'); + } + + $good = $change == 0 ? null : ($change > 0) !== $lowerIsBetter; + $color = match ($good) { + true => 'success', + false => 'danger', + null => 'gray', + }; + + return $stat + ->description(__(':change% vs previous period', ['change' => ($change > 0 ? '+' : '').$change])) + ->descriptionIcon($change < 0 ? 'heroicon-m-arrow-trending-down' : 'heroicon-m-arrow-trending-up') + ->color($color); + } +} diff --git a/stubs/app/app/Filament/Admin/Widgets/UsersWidget.php b/stubs/app/app/Filament/Admin/Widgets/UsersWidget.php new file mode 100644 index 0000000..135c1a6 --- /dev/null +++ b/stubs/app/app/Filament/Admin/Widgets/UsersWidget.php @@ -0,0 +1,47 @@ +user()?->can('manage users') ?? false; + } + + protected function getStats(): array + { + $period = $this->period(); + $previous = $period->previous(); + + return [ + TrendStat::make( + __('New users'), + User::whereBetween('created_at', [$period->start, $period->end])->count(), + User::whereBetween('created_at', [$previous->start, $previous->end])->count(), + $period->series(User::query()), + ), + Stat::make(__('Total users'), number_format(User::count())) + ->descriptionIcon('heroicon-m-users'), + ]; + } +} diff --git a/stubs/app/app/Providers/Filament/AdminPanelProvider.php b/stubs/app/app/Providers/Filament/AdminPanelProvider.php index b73aa97..7e1d009 100644 --- a/stubs/app/app/Providers/Filament/AdminPanelProvider.php +++ b/stubs/app/app/Providers/Filament/AdminPanelProvider.php @@ -7,12 +7,9 @@ use Filament\Http\Middleware\AuthenticateSession; use Filament\Http\Middleware\DisableBladeIconComponents; use Filament\Http\Middleware\DispatchServingFilamentEvent; -use Filament\Pages\Dashboard; use Filament\Panel; use Filament\PanelProvider; use Filament\Support\Colors\Color; -use Filament\Widgets\AccountWidget; -use Filament\Widgets\FilamentInfoWidget; use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse; use Illuminate\Cookie\Middleware\EncryptCookies; use Illuminate\Foundation\Http\Middleware\PreventRequestForgery; @@ -20,6 +17,7 @@ use Illuminate\Session\Middleware\StartSession; use Illuminate\View\Middleware\ShareErrorsFromSession; use Saucebase\Core\Filament\ModulesPlugin; +use Saucebase\Core\Filament\Pages\Dashboard; use Saucebase\Core\Filament\Pages\GeneralSettings; use Saucebase\Core\Filament\Pages\LocalizationSettings; use Saucebase\Core\Filament\Pages\SeoSettings; @@ -53,10 +51,9 @@ public function panel(Panel $panel): Panel ]) ->discoverResources(in: app_path('Filament/Admin/Resources'), for: 'App\Filament\Admin\Resources') ->discoverPages(in: app_path('Filament/Admin/Pages'), for: 'App\Filament\Admin\Pages') - // Core's own settings pages are named rather than discovered: they live in - // vendor/, where Filament's directory scan does not reach. Removing one is a - // deleted line here, which is the escape hatch for anybody rebranding. - // TODO: Consider adding a mechanism to allow discovery of core settings pages if needed. + // Core's own pages are named rather than discovered: scanning vendor/ would tie + // the app to where Composer puts core. Removing one is a deleted line here, + // which is the escape hatch for anybody rebranding. ->pages([ Dashboard::class, GeneralSettings::class, @@ -64,10 +61,6 @@ public function panel(Panel $panel): Panel SeoSettings::class, ]) ->discoverWidgets(in: app_path('Filament/Admin/Widgets'), for: 'App\Filament\Admin\Widgets') - ->widgets([ - AccountWidget::class, - FilamentInfoWidget::class, - ]) ->middleware([ EncryptCookies::class, AddQueuedCookiesToResponse::class, diff --git a/stubs/app/tests/Feature/AdminDashboardTest.php b/stubs/app/tests/Feature/AdminDashboardTest.php new file mode 100644 index 0000000..ddad0a6 --- /dev/null +++ b/stubs/app/tests/Feature/AdminDashboardTest.php @@ -0,0 +1,79 @@ +create(['created_at' => '2025-01-01']); + $admin->assignRole('admin'); + $this->actingAs($admin); + } + + public function test_the_dashboard_has_the_period_picker_and_no_filament_branding(): void + { + $this->get(Dashboard::getUrl())->assertOk()->assertDontSee('filamentphp.com'); + + $widgets = Filament::getPanel('admin')->getWidgets(); + $this->assertNotContains(FilamentInfoWidget::class, $widgets); + $this->assertNotContains(AccountWidget::class, $widgets); + $this->assertContains(UsersWidget::class, $widgets); + } + + public function test_the_period_starts_at_30_days(): void + { + Livewire::test(Dashboard::class)->assertActionExists('filter', fn ($action): bool => $action->getLabel() === 'Last 30 days'); + } + + /** Widgets are ordered by band (10 stats, 20 attention, 30 charts); users open the stats. */ + public function test_users_come_first(): void + { + $sorts = collect(Filament::getPanel('admin')->getWidgets()) + ->mapWithKeys(fn (string $widget) => [$widget => $widget::getSort()]); + + $this->assertSame(10, $sorts[UsersWidget::class]); + $this->assertSame($sorts->count(), $sorts->unique()->count(), 'Two widgets share a sort: '.$sorts->duplicates()->keys()->implode(', ')); + } + + /** Like every other widget, it asks for the permission behind its own admin page. */ + public function test_users_show_only_to_user_managers(): void + { + Permission::findOrCreate('access admin panel'); + Permission::findOrCreate('manage users'); + + $this->actingAs(User::factory()->create()->givePermissionTo('access admin panel')); + $this->assertFalse(UsersWidget::canView()); + + $this->actingAs(User::factory()->create()->givePermissionTo('access admin panel', 'manage users')); + $this->assertTrue(UsersWidget::canView()); + } + + public function test_users_show_signups_against_the_previous_period(): void + { + User::factory()->count(3)->create(['created_at' => '2026-11-05']); + User::factory()->create(['created_at' => '2026-10-28']); // previous 7 days + + Livewire::test(UsersWidget::class, ['pageFilters' => ['period' => '7d']]) + ->assertSee('New users') + ->assertSee('+200% vs previous period') + ->assertSee('Total users'); + } +} diff --git a/tests/Feature/DashboardPeriodTest.php b/tests/Feature/DashboardPeriodTest.php new file mode 100644 index 0000000..eefa1ca --- /dev/null +++ b/tests/Feature/DashboardPeriodTest.php @@ -0,0 +1,87 @@ +actingAs(User::factory()->create()); + } + + /** Filament's filter action: a header button, top right, opening a slide-over. */ + public function test_the_period_is_picked_from_the_header(): void + { + Livewire::test(Dashboard::class) + ->assertActionExists('filter', fn ($action): bool => $action->isModalSlideOver() && $action->getLabel() === 'Last 30 days') + ->mountAction('filter') + ->assertSchemaStateSet(['period' => Period::DEFAULT, 'start' => '2026-10-08', 'end' => '2026-11-06']); + } + + public function test_a_preset_fills_the_dates(): void + { + Livewire::test(Dashboard::class) + ->mountAction('filter') + ->fillForm(['period' => '7d']) + ->assertSchemaStateSet(['start' => '2026-10-31', 'end' => '2026-11-06']) + ->callMountedAction() + ->assertSet('filters.period', '7d') + ->assertActionExists('filter', fn ($action): bool => $action->getLabel() === 'Last 7 days'); + } + + public function test_changing_a_date_makes_the_range_custom(): void + { + Livewire::test(Dashboard::class) + ->mountAction('filter') + ->fillForm(['start' => '2026-01-01', 'end' => '2026-01-31']) + ->assertSchemaStateSet(['period' => 'custom']) + ->callMountedAction() + ->assertSet('filters', ['period' => 'custom', 'start' => '2026-01-01', 'end' => '2026-01-31']) + ->assertActionExists('filter', fn ($action): bool => $action->getLabel() === 'Jan 1, 2026 – Jan 31, 2026'); + } + + public function test_the_end_cannot_come_before_the_start(): void + { + Livewire::test(Dashboard::class) + ->mountAction('filter') + ->fillForm(['period' => 'custom', 'start' => '2026-02-01', 'end' => '2026-01-01']) + ->callMountedAction() + ->assertHasFormErrors(['end']); + } + + /** A crafted link must not break the page, nor the session it is saved in. */ + public function test_malformed_filters_in_the_url_fall_back(): void + { + foreach ([['period' => ['x']], ['period' => 'custom', 'start' => 'garbage', 'end' => '2026-01-01']] as $filters) { + Livewire::withQueryParams(['filters' => $filters]) + ->test(Dashboard::class) + ->assertOk() + ->assertActionExists('filter', fn ($action): bool => $action->getLabel() === 'Last 30 days'); + } + } + + public function test_a_widget_reads_the_period_from_the_page(): void + { + $widget = new PeriodWidget; + + $widget->pageFilters = ['period' => '7d']; + $this->assertSame('2026-10-31', $widget->start()); + + $widget->pageFilters = null; + $this->assertSame('2026-10-08', $widget->start()); + } +} diff --git a/tests/Feature/PeriodTest.php b/tests/Feature/PeriodTest.php new file mode 100644 index 0000000..2b6be9f --- /dev/null +++ b/tests/Feature/PeriodTest.php @@ -0,0 +1,151 @@ +assertSame('2026-10-08 00:00:00', $period->start->toDateTimeString()); + $this->assertSame('2026-11-06 23:59:59', $period->end->toDateTimeString()); + } + + public function test_reads_a_preset(): void + { + $period = Period::fromFilters(['period' => '7d']); + + $this->assertSame('2026-10-31 00:00:00', $period->start->toDateTimeString()); + } + + public function test_reads_a_custom_range(): void + { + $period = Period::fromFilters(['period' => 'custom', 'start' => '2026-01-01', 'end' => '2026-01-31']); + + $this->assertSame('2026-01-01 00:00:00', $period->start->toDateTimeString()); + $this->assertSame('2026-01-31 23:59:59', $period->end->toDateTimeString()); + } + + public function test_an_incomplete_custom_range_falls_back_to_the_default(): void + { + $period = Period::fromFilters(['period' => 'custom', 'start' => '2026-01-01']); + + $this->assertSame('2026-10-08 00:00:00', $period->start->toDateTimeString()); + } + + public function test_an_unknown_preset_falls_back_to_the_default(): void + { + $this->assertSame('2026-10-08 00:00:00', Period::fromFilters(['period' => 'nope'])->start->toDateTimeString()); + } + + /** Filters come from the URL and the session: anything that isn't a preset or a date falls back. */ + public function test_malformed_filters_fall_back_to_the_default(): void + { + foreach ([ + ['period' => ['x']], + ['period' => 'custom', 'start' => 'garbage', 'end' => '2026-01-31'], + ['period' => 'custom', 'start' => ['2026-01-01'], 'end' => '2026-01-31'], + ['period' => 'custom', 'start' => '2026-01-01 00:00:00; drop', 'end' => '2026-01-31'], + ['period' => 'custom', 'start' => '2026-02-30', 'end' => '2026-03-01'], + ] as $filters) { + $this->assertSame('2026-10-08 00:00:00', Period::fromFilters($filters)->start->toDateTimeString(), json_encode($filters)); + } + } + + public function test_a_reversed_range_is_put_the_right_way_round(): void + { + $period = Period::fromFilters(['period' => 'custom', 'start' => '2026-01-31', 'end' => '2026-01-01']); + + $this->assertSame('2026-01-01 00:00:00', $period->start->toDateTimeString()); + $this->assertSame('2026-01-31 23:59:59', $period->end->toDateTimeString()); + } + + /** At most five years, counted back from the end: every bucket is a chart point and a query row. */ + public function test_a_custom_range_is_capped(): void + { + $period = Period::fromFilters(['period' => 'custom', 'start' => '0001-01-01', 'end' => '2026-01-31']); + + $this->assertSame('2021-02-01 00:00:00', $period->start->toDateTimeString()); + $this->assertLessThanOrEqual(61, count($period->labels())); + } + + /** The previous period is the same length, ending just before this one starts. */ + public function test_the_previous_period_has_the_same_length(): void + { + $previous = Period::fromFilters(['period' => '7d'])->previous(); + + $this->assertSame('2026-10-24 00:00:00', $previous->start->toDateTimeString()); + $this->assertSame('2026-10-30 23:59:59', $previous->end->toDateTimeString()); + } + + public function test_the_bucket_size_follows_the_length(): void + { + $this->assertSame('day', Period::fromFilters(['period' => '30d'])->unit()); + $this->assertSame('week', Period::fromFilters(['period' => '90d'])->unit()); + $this->assertSame('month', Period::fromFilters(['period' => '12m'])->unit()); + } + + public function test_change_is_a_percentage_or_null_without_a_baseline(): void + { + $this->assertSame(50.0, Period::change(150, 100)); + $this->assertSame(-25.0, Period::change(75, 100)); + $this->assertNull(Period::change(10, 0)); + } + + public function test_series_fills_every_bucket_in_order(): void + { + Schema::create('events', function (Blueprint $table): void { + $table->id(); + $table->unsignedInteger('amount'); + $table->timestamp('created_at'); + }); + DB::table('events')->insert([ + ['amount' => 5, 'created_at' => '2026-11-04 10:00:00'], + ['amount' => 7, 'created_at' => '2026-11-04 22:00:00'], + ['amount' => 1, 'created_at' => '2026-11-06 01:00:00'], + ['amount' => 9, 'created_at' => '2026-10-01 01:00:00'], // before the period + ]); + + $period = Period::fromFilters(['period' => '7d']); + + $this->assertSame([0, 0, 0, 0, 2, 0, 1], $period->series(DB::table('events'))); + $this->assertSame([0, 0, 0, 0, 12, 0, 1], $period->series(DB::table('events'), 'sum(amount)')); + $this->assertCount(7, $period->labels()); + } + + public function test_weekly_and_monthly_series_add_up_the_days(): void + { + Schema::create('events', function (Blueprint $table): void { + $table->id(); + $table->timestamp('created_at'); + }); + DB::table('events')->insert([ + ['created_at' => '2026-10-01 10:00:00'], + ['created_at' => '2026-10-02 10:00:00'], + ['created_at' => '2026-11-05 10:00:00'], + ]); + + $monthly = Period::fromFilters(['period' => '12m'])->series(DB::table('events')); + $weekly = Period::fromFilters(['period' => '90d'])->series(DB::table('events')); + + $this->assertSame(3, array_sum($monthly)); + $this->assertSame([2, 1], array_slice($monthly, -2)); + $this->assertSame(3, array_sum($weekly)); + $this->assertSame(1, end($weekly)); + } +} diff --git a/tests/Fixtures/Filament/PeriodWidget.php b/tests/Fixtures/Filament/PeriodWidget.php new file mode 100644 index 0000000..3db1494 --- /dev/null +++ b/tests/Fixtures/Filament/PeriodWidget.php @@ -0,0 +1,17 @@ +period()->start->toDateString(); + } +} diff --git a/tests/Fixtures/Filament/TestPanelProvider.php b/tests/Fixtures/Filament/TestPanelProvider.php index 173f7c2..9ffb2b3 100644 --- a/tests/Fixtures/Filament/TestPanelProvider.php +++ b/tests/Fixtures/Filament/TestPanelProvider.php @@ -5,7 +5,6 @@ use Filament\Http\Middleware\Authenticate; use Filament\Http\Middleware\DisableBladeIconComponents; use Filament\Http\Middleware\DispatchServingFilamentEvent; -use Filament\Pages\Dashboard; use Filament\Panel; use Filament\PanelProvider; use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse; @@ -15,6 +14,7 @@ use Illuminate\Session\Middleware\StartSession; use Illuminate\View\Middleware\ShareErrorsFromSession; use Saucebase\Core\Filament\ModulesPlugin; +use Saucebase\Core\Filament\Pages\Dashboard; use Saucebase\Core\Filament\Pages\GeneralSettings; use Saucebase\Core\Filament\Pages\LocalizationSettings; diff --git a/tests/Unit/Filament/TrendStatTest.php b/tests/Unit/Filament/TrendStatTest.php new file mode 100644 index 0000000..7bc56e0 --- /dev/null +++ b/tests/Unit/Filament/TrendStatTest.php @@ -0,0 +1,47 @@ +assertSame('150', (string) $stat->getValue()); + $this->assertSame('+50% vs previous period', (string) $stat->getDescription()); + $this->assertSame('heroicon-m-arrow-trending-up', $stat->getDescriptionIcon()); + $this->assertSame('success', $stat->getColor()); + $this->assertSame([1, 2, 3], $stat->getChart()); + } + + public function test_a_fall_is_red_unless_lower_is_better(): void + { + $this->assertSame('danger', TrendStat::make('Users', 50, 100)->getColor()); + $this->assertSame('-50% vs previous period', (string) TrendStat::make('Users', 50, 100)->getDescription()); + $this->assertSame('success', TrendStat::make('Churn', 50, 100, lowerIsBetter: true)->getColor()); + $this->assertSame('heroicon-m-arrow-trending-down', TrendStat::make('Churn', 50, 100)->getDescriptionIcon()); + } + + public function test_no_baseline_says_so_instead_of_a_misleading_percentage(): void + { + $stat = TrendStat::make('Users', 3, 0); + + $this->assertSame('No data for the previous period', (string) $stat->getDescription()); + $this->assertSame('gray', $stat->getColor()); + } + + public function test_the_value_is_formatted(): void + { + $this->assertSame('1,234', (string) TrendStat::make('Users', 1234, 1000)->getValue()); + $this->assertSame('$12.34', (string) TrendStat::make('Revenue', 1234, 1000, format: fn ($v) => '$'.number_format($v / 100, 2))->getValue()); + } + + public function test_a_chart_with_no_movement_is_left_out(): void + { + $this->assertNull(TrendStat::make('Users', 0, 0, [0, 0, 0])->getChart()); + } +} diff --git a/tests/Unit/Stubs/AdminPanelStubTest.php b/tests/Unit/Stubs/AdminPanelStubTest.php new file mode 100644 index 0000000..d12e3dc --- /dev/null +++ b/tests/Unit/Stubs/AdminPanelStubTest.php @@ -0,0 +1,30 @@ +assertStringContainsString('use Saucebase\Core\Filament\Pages\Dashboard;', $provider); + $this->assertStringNotContainsString('use Filament\Pages\Dashboard;', $provider); + $this->assertStringNotContainsString('FilamentInfoWidget', $provider); + $this->assertStringNotContainsString('AccountWidget', $provider); + } + + public function test_the_app_ships_the_users_widget_and_its_test(): void + { + $this->assertFileExists(self::APP.'app/Filament/Admin/Widgets/UsersWidget.php'); + $this->assertFileExists(self::APP.'tests/Feature/AdminDashboardTest.php'); + } +} From 6ed4b00fc29d72458ef39e0f5b9ea487dbeec981 Mon Sep 17 00:00:00 2001 From: roble Date: Fri, 6 Nov 2026 20:43:07 +0000 Subject: [PATCH 6/6] fix: keep every month in the 12-month period, warn when the E2E env isn't created, stop workers together From review on #38: the 12-month preset and the five-year cap no longer roll past a short month or a leap day; the installer says how to create .env.e2e when playwright:env fails; task workers fails fast. Co-Authored-By: Claude Opus 5.5 --- src/Console/Commands/InstallCommand.php | 7 +++++-- src/Filament/Period.php | 4 ++-- stubs/app/Taskfile.yml | 1 + tests/Feature/InstallCommandTest.php | 22 ++++++++++++++++++++++ tests/Feature/PeriodTest.php | 18 ++++++++++++++++++ 5 files changed, 48 insertions(+), 4 deletions(-) diff --git a/src/Console/Commands/InstallCommand.php b/src/Console/Commands/InstallCommand.php index 6295af8..c3cdafa 100644 --- a/src/Console/Commands/InstallCommand.php +++ b/src/Console/Commands/InstallCommand.php @@ -85,8 +85,11 @@ public function handle(Filesystem $files, ProjectConfig $config): int $this->publishStack($files, $stubs.'/stack', $framework); // A package's require-dev never reaches the app, so a manual install may not have it. - if (array_key_exists('playwright:env', Artisan::all())) { - $this->call('playwright:env', ['--no-interaction' => true]); + if (array_key_exists('playwright:env', Artisan::all()) + && $this->call('playwright:env', ['--no-interaction' => true]) !== self::SUCCESS + && ! $files->exists($this->laravel->basePath('.env.e2e'))) { + // Everything else is in place, so finish and say how to complete it. + $this->components->warn('The E2E environment file (.env.e2e) could not be created. Create it with: php artisan playwright:env'); } $this->components->info("Saucebase is installed with {$framework}."); diff --git a/src/Filament/Period.php b/src/Filament/Period.php index 396dd41..7752814 100644 --- a/src/Filament/Period.php +++ b/src/Filament/Period.php @@ -49,14 +49,14 @@ public static function fromFilters(?array $filters): self if ($preset === 'custom' && ($start = self::date($filters['start'] ?? null)) && ($end = self::date($filters['end'] ?? null))) { [$start, $end] = $start <= $end ? [$start, $end] : [$end, $start]; - return new self(max($start, $end->subYears(self::MAX_YEARS)->addDay()), $end->endOfDay()); + return new self(max($start, $end->subYearsNoOverflow(self::MAX_YEARS)->addDay()), $end->endOfDay()); } $start = match ($preset) { 'today' => $today, '7d' => $today->subDays(6), '90d' => $today->subDays(89), - '12m' => $today->subMonths(11)->startOfMonth(), + '12m' => $today->startOfMonth()->subMonths(11), // from the 1st: the 31st minus months can roll forward default => $today->subDays(29), }; diff --git a/stubs/app/Taskfile.yml b/stubs/app/Taskfile.yml index f89fc2c..5533df7 100644 --- a/stubs/app/Taskfile.yml +++ b/stubs/app/Taskfile.yml @@ -32,6 +32,7 @@ tasks: workers: desc: Run the queue worker and scheduler together deps: [queue, schedule] + failfast: true # one stopping stops both (Task 3.46.1+), so jobs never pile up unprocessed build: desc: Production build (includes SSR) diff --git a/tests/Feature/InstallCommandTest.php b/tests/Feature/InstallCommandTest.php index 4364185..7149bdf 100644 --- a/tests/Feature/InstallCommandTest.php +++ b/tests/Feature/InstallCommandTest.php @@ -96,6 +96,7 @@ public function test_the_taskfile_runs_the_queue_and_scheduler_without_a_web_ser $this->assertStringContainsString('{{.APP}} php artisan queue:listen', $tasks['queue']['cmd']); $this->assertStringContainsString('{{.APP}} php artisan schedule:work', $tasks['schedule']['cmd']); $this->assertSame(['queue', 'schedule'], $tasks['workers']['deps']); + $this->assertTrue($tasks['workers']['failfast'], 'one worker stopping must stop both'); } public function test_it_writes_the_e2e_env_when_the_playwright_package_is_installed(): void @@ -110,6 +111,27 @@ public function test_it_writes_the_e2e_env_when_the_playwright_package_is_instal $this->assertTrue($ran, 'playwright:env should run, unattended, so it can never replace a file.'); } + /** The rest is installed and `saucebase.json` written, so say how to finish instead of failing. */ + public function test_a_failed_e2e_env_says_how_to_create_it(): void + { + Artisan::command('playwright:env', fn () => 1); + + $this->artisan('saucebase:install', ['framework' => 'vue', '--force' => true]) + ->expectsOutputToContain('php artisan playwright:env') + ->assertSuccessful(); + } + + /** It also fails when it refuses to replace an existing `.env.e2e`: nothing to say then. */ + public function test_an_existing_e2e_env_is_not_reported(): void + { + file_put_contents($this->appPath.'/.env.e2e', "APP_ENV=e2e\n"); + Artisan::command('playwright:env', fn () => 1); + + $this->artisan('saucebase:install', ['framework' => 'vue', '--force' => true]) + ->doesntExpectOutputToContain('could not be created') + ->assertSuccessful(); + } + public function test_it_installs_without_the_playwright_package(): void { $this->assertArrayNotHasKey('playwright:env', Artisan::all()); diff --git a/tests/Feature/PeriodTest.php b/tests/Feature/PeriodTest.php index 2b6be9f..426fd32 100644 --- a/tests/Feature/PeriodTest.php +++ b/tests/Feature/PeriodTest.php @@ -84,6 +84,13 @@ public function test_a_custom_range_is_capped(): void $this->assertLessThanOrEqual(61, count($period->labels())); } + public function test_the_cap_does_not_roll_past_a_leap_day(): void + { + $period = Period::fromFilters(['period' => 'custom', 'start' => '2000-01-01', 'end' => '2028-02-29']); + + $this->assertSame('2023-03-01 00:00:00', $period->start->toDateTimeString()); + } + /** The previous period is the same length, ending just before this one starts. */ public function test_the_previous_period_has_the_same_length(): void { @@ -100,6 +107,17 @@ public function test_the_bucket_size_follows_the_length(): void $this->assertSame('month', Period::fromFilters(['period' => '12m'])->unit()); } + /** On the 31st, eleven months back can land in a month with no 31st and roll forward. */ + public function test_12_months_keeps_every_month_at_a_month_end(): void + { + Carbon::setTestNow('2027-03-31 12:00:00'); + + $period = Period::fromFilters(['period' => '12m']); + + $this->assertSame('2026-04-01 00:00:00', $period->start->toDateTimeString()); + $this->assertCount(12, $period->labels()); + } + public function test_change_is_a_percentage_or_null_without_a_baseline(): void { $this->assertSame(50.0, Period::change(150, 100));