Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions resources/boost/skills/saucebase-filament-development/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
46 changes: 41 additions & 5 deletions src/Capabilities.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -19,7 +20,12 @@
*/
class Capabilities
{
/** @var array<string, list<array<string, array<string, mixed>>|Closure(): array<string, array<string, mixed>>>> */
/**
* By group, then by where `add()` was called (`file:line`), so a declaration that runs
* again replaces itself.
*
* @var array<string, array<string, array<string, array<string, mixed>>|Closure(): array<string, array<string, mixed>>>>

Check warning on line 27 in src/Capabilities.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 124 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_core&issues=AaGyjU4a4ipd6Ru01yQN&open=AaGyjU4a4ipd6Ru01yQN&pullRequest=38
*/
private array $entries = [];

private bool $loaded = false;
Expand All @@ -29,22 +35,52 @@
/** @param array<string, array<string, mixed>>|Closure(): array<string, array<string, mixed>> $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<string, array<string, mixed>>
*/
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),
Expand Down
9 changes: 9 additions & 0 deletions src/Console/Commands/InstallCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -83,6 +84,14 @@

$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]) !== 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');

Check warning on line 92 in src/Console/Commands/InstallCommand.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 140 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_core&issues=AaGymma9LjZQeDKj2EC5&open=AaGymma9LjZQeDKj2EC5&pullRequest=38
}

$this->components->info("Saucebase is installed with {$framework}.");
$this->components->bulletList([
'npm install && npm run build',
Expand Down
35 changes: 35 additions & 0 deletions src/Console/Commands/SyncModuleTaskfileCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace Saucebase\Core\Console\Commands;

use Illuminate\Console\Command;
use InterNACHI\Modular\Support\ModuleRegistry;
use Saucebase\Core\ModuleTaskfile;

/** Lists exactly the installed modules that have a Taskfile in the app's Taskfile. */
class SyncModuleTaskfileCommand extends Command
{
protected $signature = 'saucebase:taskfile-sync';

protected $description = 'List the installed modules in the app\'s Taskfile';

public function handle(ModuleRegistry $registry): int
{
$modules = $registry->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;
}
}
2 changes: 2 additions & 0 deletions src/CoreServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -105,6 +106,7 @@ public function boot(): void
ModuleSetupCommand::class,
RecipeToModuleCommand::class,
SeedModulesCommand::class,
SyncModuleTaskfileCommand::class,
SyncModuleBoostCommand::class,
]);

Expand Down
17 changes: 17 additions & 0 deletions src/Filament/Concerns/ReadsPeriod.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Saucebase\Core\Filament\Concerns;

use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Saucebase\Core\Filament\Period;

/** For a widget on a `Saucebase\Core\Filament\Pages\Dashboard`: the period its picker is set to. */
trait ReadsPeriod /** @phpstan-ignore trait.unused */
{
use InteractsWithPageFilters;

protected function period(): Period
{
return Period::fromFilters($this->pageFilters);
}
}
87 changes: 87 additions & 0 deletions src/Filament/Pages/Dashboard.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

namespace Saucebase\Core\Filament\Pages;

use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Pages\Dashboard\Actions\FilterAction;
use Filament\Pages\Dashboard as BaseDashboard;
use Filament\Pages\Dashboard\Concerns\HasFiltersAction;
use Filament\Schemas\Components\Utilities\Set;
use Saucebase\Core\Filament\Period;

/**
* Filament's dashboard with a period filter: the header's filter button, top
* right, opens a slide-over with presets and dates. Widgets read it with
* `Concerns\ReadsPeriod`. Other dashboards extend this one.
*/
class Dashboard extends BaseDashboard
{
use HasFiltersAction;

protected function getHeaderActions(): array
{
return [
FilterAction::make()
->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))) {

Check warning on line 64 in src/Filament/Pages/Dashboard.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 125 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_core&issues=AaGyjU0N4ipd6Ru01yQK&open=AaGyjU0N4ipd6Ru01yQK&pullRequest=38
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<string, mixed>|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(),
];
}
}
Loading
Loading