Compare commits
1 Commits
dev
...
fix/tenant
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63195af1eb |
@ -1,167 +0,0 @@
|
||||
---
|
||||
name: pest-testing
|
||||
description: "Tests applications using the Pest 4 PHP framework. Activates when writing tests, creating unit or feature tests, adding assertions, testing Livewire components, browser testing, debugging test failures, working with datasets or mocking; or when the user mentions test, spec, TDD, expects, assertion, coverage, or needs to verify functionality works."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Pest Testing 4
|
||||
|
||||
## When to Apply
|
||||
|
||||
Activate this skill when:
|
||||
|
||||
- Creating new tests (unit, feature, or browser)
|
||||
- Modifying existing tests
|
||||
- Debugging test failures
|
||||
- Working with browser testing or smoke testing
|
||||
- Writing architecture tests or visual regression tests
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Pest 4 patterns and documentation.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Creating Tests
|
||||
|
||||
All tests must be written using Pest. Use `php artisan make:test --pest {name}`.
|
||||
|
||||
### Test Organization
|
||||
|
||||
- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories.
|
||||
- Browser tests: `tests/Browser/` directory.
|
||||
- Do NOT remove tests without approval - these are core application code.
|
||||
|
||||
### Basic Test Structure
|
||||
|
||||
<!-- Basic Pest Test Example -->
|
||||
```php
|
||||
it('is true', function () {
|
||||
expect(true)->toBeTrue();
|
||||
});
|
||||
```
|
||||
|
||||
### Running Tests
|
||||
|
||||
- Run minimal tests with filter before finalizing: `php artisan test --compact --filter=testName`.
|
||||
- Run all tests: `php artisan test --compact`.
|
||||
- Run file: `php artisan test --compact tests/Feature/ExampleTest.php`.
|
||||
|
||||
## Assertions
|
||||
|
||||
Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`:
|
||||
|
||||
<!-- Pest Response Assertion -->
|
||||
```php
|
||||
it('returns all', function () {
|
||||
$this->postJson('/api/docs', [])->assertSuccessful();
|
||||
});
|
||||
```
|
||||
|
||||
| Use | Instead of |
|
||||
|-----|------------|
|
||||
| `assertSuccessful()` | `assertStatus(200)` |
|
||||
| `assertNotFound()` | `assertStatus(404)` |
|
||||
| `assertForbidden()` | `assertStatus(403)` |
|
||||
|
||||
## Mocking
|
||||
|
||||
Import mock function before use: `use function Pest\Laravel\mock;`
|
||||
|
||||
## Datasets
|
||||
|
||||
Use datasets for repetitive tests (validation rules, etc.):
|
||||
|
||||
<!-- Pest Dataset Example -->
|
||||
```php
|
||||
it('has emails', function (string $email) {
|
||||
expect($email)->not->toBeEmpty();
|
||||
})->with([
|
||||
'james' => 'james@laravel.com',
|
||||
'taylor' => 'taylor@laravel.com',
|
||||
]);
|
||||
```
|
||||
|
||||
## Pest 4 Features
|
||||
|
||||
| Feature | Purpose |
|
||||
|---------|---------|
|
||||
| Browser Testing | Full integration tests in real browsers |
|
||||
| Smoke Testing | Validate multiple pages quickly |
|
||||
| Visual Regression | Compare screenshots for visual changes |
|
||||
| Test Sharding | Parallel CI runs |
|
||||
| Architecture Testing | Enforce code conventions |
|
||||
|
||||
### Browser Test Example
|
||||
|
||||
Browser tests run in real browsers for full integration testing:
|
||||
|
||||
- Browser tests live in `tests/Browser/`.
|
||||
- Use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories.
|
||||
- Use `RefreshDatabase` for clean state per test.
|
||||
- Interact with page: click, type, scroll, select, submit, drag-and-drop, touch gestures.
|
||||
- Test on multiple browsers (Chrome, Firefox, Safari) if requested.
|
||||
- Test on different devices/viewports (iPhone 14 Pro, tablets) if requested.
|
||||
- Switch color schemes (light/dark mode) when appropriate.
|
||||
- Take screenshots or pause tests for debugging.
|
||||
|
||||
<!-- Pest Browser Test Example -->
|
||||
```php
|
||||
it('may reset the password', function () {
|
||||
Notification::fake();
|
||||
|
||||
$this->actingAs(User::factory()->create());
|
||||
|
||||
$page = visit('/sign-in');
|
||||
|
||||
$page->assertSee('Sign In')
|
||||
->assertNoJavaScriptErrors()
|
||||
->click('Forgot Password?')
|
||||
->fill('email', 'nuno@laravel.com')
|
||||
->click('Send Reset Link')
|
||||
->assertSee('We have emailed your password reset link!');
|
||||
|
||||
Notification::assertSent(ResetPassword::class);
|
||||
});
|
||||
```
|
||||
|
||||
### Smoke Testing
|
||||
|
||||
Quickly validate multiple pages have no JavaScript errors:
|
||||
|
||||
<!-- Pest Smoke Testing Example -->
|
||||
```php
|
||||
$pages = visit(['/', '/about', '/contact']);
|
||||
|
||||
$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs();
|
||||
```
|
||||
|
||||
### Visual Regression Testing
|
||||
|
||||
Capture and compare screenshots to detect visual changes.
|
||||
|
||||
### Test Sharding
|
||||
|
||||
Split tests across parallel processes for faster CI runs.
|
||||
|
||||
### Architecture Testing
|
||||
|
||||
Pest 4 includes architecture testing (from Pest 3):
|
||||
|
||||
<!-- Architecture Test Example -->
|
||||
```php
|
||||
arch('controllers')
|
||||
->expect('App\Http\Controllers')
|
||||
->toExtendNothing()
|
||||
->toHaveSuffix('Controller');
|
||||
```
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Not importing `use function Pest\Laravel\mock;` before using mock
|
||||
- Using `assertStatus(200)` instead of `assertSuccessful()`
|
||||
- Forgetting datasets for repetitive validation tests
|
||||
- Deleting tests without approval
|
||||
- Forgetting `assertNoJavaScriptErrors()` in browser tests
|
||||
@ -1,129 +0,0 @@
|
||||
---
|
||||
name: tailwindcss-development
|
||||
description: "Styles applications using Tailwind CSS v4 utilities. Activates when adding styles, restyling components, working with gradients, spacing, layout, flex, grid, responsive design, dark mode, colors, typography, or borders; or when the user mentions CSS, styling, classes, Tailwind, restyle, hero section, cards, buttons, or any visual/UI changes."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Tailwind CSS Development
|
||||
|
||||
## When to Apply
|
||||
|
||||
Activate this skill when:
|
||||
|
||||
- Adding styles to components or pages
|
||||
- Working with responsive design
|
||||
- Implementing dark mode
|
||||
- Extracting repeated patterns into components
|
||||
- Debugging spacing or layout issues
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Tailwind CSS v4 patterns and documentation.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
- Use Tailwind CSS classes to style HTML. Check and follow existing Tailwind conventions in the project before introducing new patterns.
|
||||
- Offer to extract repeated patterns into components that match the project's conventions (e.g., Blade, JSX, Vue).
|
||||
- Consider class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child elements carefully to reduce repetition, and group elements logically.
|
||||
|
||||
## Tailwind CSS v4 Specifics
|
||||
|
||||
- Always use Tailwind CSS v4 and avoid deprecated utilities.
|
||||
- `corePlugins` is not supported in Tailwind v4.
|
||||
|
||||
### CSS-First Configuration
|
||||
|
||||
In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed:
|
||||
|
||||
<!-- CSS-First Config -->
|
||||
```css
|
||||
@theme {
|
||||
--color-brand: oklch(0.72 0.11 178);
|
||||
}
|
||||
```
|
||||
|
||||
### Import Syntax
|
||||
|
||||
In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead of the `@tailwind` directives used in v3:
|
||||
|
||||
<!-- v4 Import Syntax -->
|
||||
```diff
|
||||
- @tailwind base;
|
||||
- @tailwind components;
|
||||
- @tailwind utilities;
|
||||
+ @import "tailwindcss";
|
||||
```
|
||||
|
||||
### Replaced Utilities
|
||||
|
||||
Tailwind v4 removed deprecated utilities. Use the replacements shown below. Opacity values remain numeric.
|
||||
|
||||
| Deprecated | Replacement |
|
||||
|------------|-------------|
|
||||
| bg-opacity-* | bg-black/* |
|
||||
| text-opacity-* | text-black/* |
|
||||
| border-opacity-* | border-black/* |
|
||||
| divide-opacity-* | divide-black/* |
|
||||
| ring-opacity-* | ring-black/* |
|
||||
| placeholder-opacity-* | placeholder-black/* |
|
||||
| flex-shrink-* | shrink-* |
|
||||
| flex-grow-* | grow-* |
|
||||
| overflow-ellipsis | text-ellipsis |
|
||||
| decoration-slice | box-decoration-slice |
|
||||
| decoration-clone | box-decoration-clone |
|
||||
|
||||
## Spacing
|
||||
|
||||
Use `gap` utilities instead of margins for spacing between siblings:
|
||||
|
||||
<!-- Gap Utilities -->
|
||||
```html
|
||||
<div class="flex gap-8">
|
||||
<div>Item 1</div>
|
||||
<div>Item 2</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Dark Mode
|
||||
|
||||
If existing pages and components support dark mode, new pages and components must support it the same way, typically using the `dark:` variant:
|
||||
|
||||
<!-- Dark Mode -->
|
||||
```html
|
||||
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
|
||||
Content adapts to color scheme
|
||||
</div>
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Flexbox Layout
|
||||
|
||||
<!-- Flexbox Layout -->
|
||||
```html
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div>Left content</div>
|
||||
<div>Right content</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Grid Layout
|
||||
|
||||
<!-- Grid Layout -->
|
||||
```html
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<div>Card 1</div>
|
||||
<div>Card 2</div>
|
||||
<div>Card 3</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Using deprecated v3 utilities (bg-opacity-*, flex-shrink-*, etc.)
|
||||
- Using `@tailwind` directives instead of `@import "tailwindcss"`
|
||||
- Trying to use `tailwind.config.js` instead of CSS `@theme` directive
|
||||
- Using margins for spacing between siblings instead of gap utilities
|
||||
- Forgetting to add dark mode variants when the project uses dark mode
|
||||
@ -1,4 +0,0 @@
|
||||
[mcp_servers.laravel-boost]
|
||||
command = "vendor/bin/sail"
|
||||
args = ["artisan", "boost:mcp"]
|
||||
cwd = "/Users/ahmeddarrazi/Documents/projects/TenantAtlas"
|
||||
16
.github/agents/copilot-instructions.md
vendored
16
.github/agents/copilot-instructions.md
vendored
@ -29,16 +29,6 @@ ## Active Technologies
|
||||
- PHP 8.4 (Laravel 12) + Filament v5, Livewire v4, Laravel Sail, Tailwind CSS v4 (085-tenant-operate-hub)
|
||||
- PostgreSQL (Sail), SQLite in tests (087-legacy-runs-removal)
|
||||
- PHP 8.4.x + Laravel 12, Filament v5, Livewire v4, Microsoft Graph integration via `GraphClientInterface` (095-graph-contracts-registry-completeness)
|
||||
- PHP 8.4.15 (Laravel 12) + Filament v5, Livewire v4, Laravel Queue, Laravel Notifications (100-alert-target-test-actions)
|
||||
- PostgreSQL (Sail locally); SQLite is used in some tests (101-golden-master-baseline-governance-v1)
|
||||
- PHP 8.4 (Laravel 12) + Filament v5, Livewire v4, `OperateHubShell` support class (103-ia-scope-filter-semantics)
|
||||
- PostgreSQL — no schema changes (103-ia-scope-filter-semantics)
|
||||
- PHP 8.4 (Laravel 12) + Filament v5, Livewire v4, Pest v4 (104-provider-permission-posture)
|
||||
- PostgreSQL (via Sail), JSONB for stored report payloads and finding evidence (104-provider-permission-posture)
|
||||
- PHP 8.4 / Laravel 12 + Filament v5, Livewire v4, Tailwind CSS v4 (107-workspace-chooser)
|
||||
- PostgreSQL (existing tables: `workspaces`, `workspace_memberships`, `users`, `audit_logs`) (107-workspace-chooser)
|
||||
- PHP 8.4 (Laravel 12) + Filament v5, Livewire v4, Laravel Framework v12 (109-review-pack-export)
|
||||
- PostgreSQL (jsonb columns for summary/options), local filesystem (`exports` disk) for ZIP artifacts (109-review-pack-export)
|
||||
|
||||
- PHP 8.4.15 (feat/005-bulk-operations)
|
||||
|
||||
@ -58,8 +48,8 @@ ## Code Style
|
||||
PHP 8.4.15: Follow standard conventions
|
||||
|
||||
## Recent Changes
|
||||
- 110-ops-ux-enforcement: Added PHP 8.4.x + Laravel 12, Filament v5, Livewire v4
|
||||
- 109-review-pack-export: Added PHP 8.4 (Laravel 12) + Filament v5, Livewire v4, Laravel Framework v12
|
||||
- 109-review-pack-export: Added [if applicable, e.g., PostgreSQL, CoreData, files or N/A]
|
||||
- 095-graph-contracts-registry-completeness: Added PHP 8.4.x + Laravel 12, Filament v5, Livewire v4, Microsoft Graph integration via `GraphClientInterface`
|
||||
- 090-action-surface-contract-compliance: Added PHP 8.4.15
|
||||
- 087-legacy-runs-removal: Added PHP 8.4.15 + Laravel 12, Filament v5, Livewire v4
|
||||
<!-- MANUAL ADDITIONS START -->
|
||||
<!-- MANUAL ADDITIONS END -->
|
||||
|
||||
167
.github/skills/pest-testing/SKILL.md
vendored
167
.github/skills/pest-testing/SKILL.md
vendored
@ -1,167 +0,0 @@
|
||||
---
|
||||
name: pest-testing
|
||||
description: "Tests applications using the Pest 4 PHP framework. Activates when writing tests, creating unit or feature tests, adding assertions, testing Livewire components, browser testing, debugging test failures, working with datasets or mocking; or when the user mentions test, spec, TDD, expects, assertion, coverage, or needs to verify functionality works."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Pest Testing 4
|
||||
|
||||
## When to Apply
|
||||
|
||||
Activate this skill when:
|
||||
|
||||
- Creating new tests (unit, feature, or browser)
|
||||
- Modifying existing tests
|
||||
- Debugging test failures
|
||||
- Working with browser testing or smoke testing
|
||||
- Writing architecture tests or visual regression tests
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Pest 4 patterns and documentation.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Creating Tests
|
||||
|
||||
All tests must be written using Pest. Use `php artisan make:test --pest {name}`.
|
||||
|
||||
### Test Organization
|
||||
|
||||
- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories.
|
||||
- Browser tests: `tests/Browser/` directory.
|
||||
- Do NOT remove tests without approval - these are core application code.
|
||||
|
||||
### Basic Test Structure
|
||||
|
||||
<!-- Basic Pest Test Example -->
|
||||
```php
|
||||
it('is true', function () {
|
||||
expect(true)->toBeTrue();
|
||||
});
|
||||
```
|
||||
|
||||
### Running Tests
|
||||
|
||||
- Run minimal tests with filter before finalizing: `php artisan test --compact --filter=testName`.
|
||||
- Run all tests: `php artisan test --compact`.
|
||||
- Run file: `php artisan test --compact tests/Feature/ExampleTest.php`.
|
||||
|
||||
## Assertions
|
||||
|
||||
Use specific assertions (`assertSuccessful()`, `assertNotFound()`) instead of `assertStatus()`:
|
||||
|
||||
<!-- Pest Response Assertion -->
|
||||
```php
|
||||
it('returns all', function () {
|
||||
$this->postJson('/api/docs', [])->assertSuccessful();
|
||||
});
|
||||
```
|
||||
|
||||
| Use | Instead of |
|
||||
|-----|------------|
|
||||
| `assertSuccessful()` | `assertStatus(200)` |
|
||||
| `assertNotFound()` | `assertStatus(404)` |
|
||||
| `assertForbidden()` | `assertStatus(403)` |
|
||||
|
||||
## Mocking
|
||||
|
||||
Import mock function before use: `use function Pest\Laravel\mock;`
|
||||
|
||||
## Datasets
|
||||
|
||||
Use datasets for repetitive tests (validation rules, etc.):
|
||||
|
||||
<!-- Pest Dataset Example -->
|
||||
```php
|
||||
it('has emails', function (string $email) {
|
||||
expect($email)->not->toBeEmpty();
|
||||
})->with([
|
||||
'james' => 'james@laravel.com',
|
||||
'taylor' => 'taylor@laravel.com',
|
||||
]);
|
||||
```
|
||||
|
||||
## Pest 4 Features
|
||||
|
||||
| Feature | Purpose |
|
||||
|---------|---------|
|
||||
| Browser Testing | Full integration tests in real browsers |
|
||||
| Smoke Testing | Validate multiple pages quickly |
|
||||
| Visual Regression | Compare screenshots for visual changes |
|
||||
| Test Sharding | Parallel CI runs |
|
||||
| Architecture Testing | Enforce code conventions |
|
||||
|
||||
### Browser Test Example
|
||||
|
||||
Browser tests run in real browsers for full integration testing:
|
||||
|
||||
- Browser tests live in `tests/Browser/`.
|
||||
- Use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories.
|
||||
- Use `RefreshDatabase` for clean state per test.
|
||||
- Interact with page: click, type, scroll, select, submit, drag-and-drop, touch gestures.
|
||||
- Test on multiple browsers (Chrome, Firefox, Safari) if requested.
|
||||
- Test on different devices/viewports (iPhone 14 Pro, tablets) if requested.
|
||||
- Switch color schemes (light/dark mode) when appropriate.
|
||||
- Take screenshots or pause tests for debugging.
|
||||
|
||||
<!-- Pest Browser Test Example -->
|
||||
```php
|
||||
it('may reset the password', function () {
|
||||
Notification::fake();
|
||||
|
||||
$this->actingAs(User::factory()->create());
|
||||
|
||||
$page = visit('/sign-in');
|
||||
|
||||
$page->assertSee('Sign In')
|
||||
->assertNoJavaScriptErrors()
|
||||
->click('Forgot Password?')
|
||||
->fill('email', 'nuno@laravel.com')
|
||||
->click('Send Reset Link')
|
||||
->assertSee('We have emailed your password reset link!');
|
||||
|
||||
Notification::assertSent(ResetPassword::class);
|
||||
});
|
||||
```
|
||||
|
||||
### Smoke Testing
|
||||
|
||||
Quickly validate multiple pages have no JavaScript errors:
|
||||
|
||||
<!-- Pest Smoke Testing Example -->
|
||||
```php
|
||||
$pages = visit(['/', '/about', '/contact']);
|
||||
|
||||
$pages->assertNoJavaScriptErrors()->assertNoConsoleLogs();
|
||||
```
|
||||
|
||||
### Visual Regression Testing
|
||||
|
||||
Capture and compare screenshots to detect visual changes.
|
||||
|
||||
### Test Sharding
|
||||
|
||||
Split tests across parallel processes for faster CI runs.
|
||||
|
||||
### Architecture Testing
|
||||
|
||||
Pest 4 includes architecture testing (from Pest 3):
|
||||
|
||||
<!-- Architecture Test Example -->
|
||||
```php
|
||||
arch('controllers')
|
||||
->expect('App\Http\Controllers')
|
||||
->toExtendNothing()
|
||||
->toHaveSuffix('Controller');
|
||||
```
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Not importing `use function Pest\Laravel\mock;` before using mock
|
||||
- Using `assertStatus(200)` instead of `assertSuccessful()`
|
||||
- Forgetting datasets for repetitive validation tests
|
||||
- Deleting tests without approval
|
||||
- Forgetting `assertNoJavaScriptErrors()` in browser tests
|
||||
129
.github/skills/tailwindcss-development/SKILL.md
vendored
129
.github/skills/tailwindcss-development/SKILL.md
vendored
@ -1,129 +0,0 @@
|
||||
---
|
||||
name: tailwindcss-development
|
||||
description: "Styles applications using Tailwind CSS v4 utilities. Activates when adding styles, restyling components, working with gradients, spacing, layout, flex, grid, responsive design, dark mode, colors, typography, or borders; or when the user mentions CSS, styling, classes, Tailwind, restyle, hero section, cards, buttons, or any visual/UI changes."
|
||||
license: MIT
|
||||
metadata:
|
||||
author: laravel
|
||||
---
|
||||
|
||||
# Tailwind CSS Development
|
||||
|
||||
## When to Apply
|
||||
|
||||
Activate this skill when:
|
||||
|
||||
- Adding styles to components or pages
|
||||
- Working with responsive design
|
||||
- Implementing dark mode
|
||||
- Extracting repeated patterns into components
|
||||
- Debugging spacing or layout issues
|
||||
|
||||
## Documentation
|
||||
|
||||
Use `search-docs` for detailed Tailwind CSS v4 patterns and documentation.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
- Use Tailwind CSS classes to style HTML. Check and follow existing Tailwind conventions in the project before introducing new patterns.
|
||||
- Offer to extract repeated patterns into components that match the project's conventions (e.g., Blade, JSX, Vue).
|
||||
- Consider class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child elements carefully to reduce repetition, and group elements logically.
|
||||
|
||||
## Tailwind CSS v4 Specifics
|
||||
|
||||
- Always use Tailwind CSS v4 and avoid deprecated utilities.
|
||||
- `corePlugins` is not supported in Tailwind v4.
|
||||
|
||||
### CSS-First Configuration
|
||||
|
||||
In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed:
|
||||
|
||||
<!-- CSS-First Config -->
|
||||
```css
|
||||
@theme {
|
||||
--color-brand: oklch(0.72 0.11 178);
|
||||
}
|
||||
```
|
||||
|
||||
### Import Syntax
|
||||
|
||||
In Tailwind v4, import Tailwind with a regular CSS `@import` statement instead of the `@tailwind` directives used in v3:
|
||||
|
||||
<!-- v4 Import Syntax -->
|
||||
```diff
|
||||
- @tailwind base;
|
||||
- @tailwind components;
|
||||
- @tailwind utilities;
|
||||
+ @import "tailwindcss";
|
||||
```
|
||||
|
||||
### Replaced Utilities
|
||||
|
||||
Tailwind v4 removed deprecated utilities. Use the replacements shown below. Opacity values remain numeric.
|
||||
|
||||
| Deprecated | Replacement |
|
||||
|------------|-------------|
|
||||
| bg-opacity-* | bg-black/* |
|
||||
| text-opacity-* | text-black/* |
|
||||
| border-opacity-* | border-black/* |
|
||||
| divide-opacity-* | divide-black/* |
|
||||
| ring-opacity-* | ring-black/* |
|
||||
| placeholder-opacity-* | placeholder-black/* |
|
||||
| flex-shrink-* | shrink-* |
|
||||
| flex-grow-* | grow-* |
|
||||
| overflow-ellipsis | text-ellipsis |
|
||||
| decoration-slice | box-decoration-slice |
|
||||
| decoration-clone | box-decoration-clone |
|
||||
|
||||
## Spacing
|
||||
|
||||
Use `gap` utilities instead of margins for spacing between siblings:
|
||||
|
||||
<!-- Gap Utilities -->
|
||||
```html
|
||||
<div class="flex gap-8">
|
||||
<div>Item 1</div>
|
||||
<div>Item 2</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Dark Mode
|
||||
|
||||
If existing pages and components support dark mode, new pages and components must support it the same way, typically using the `dark:` variant:
|
||||
|
||||
<!-- Dark Mode -->
|
||||
```html
|
||||
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
|
||||
Content adapts to color scheme
|
||||
</div>
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Flexbox Layout
|
||||
|
||||
<!-- Flexbox Layout -->
|
||||
```html
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div>Left content</div>
|
||||
<div>Right content</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Grid Layout
|
||||
|
||||
<!-- Grid Layout -->
|
||||
```html
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<div>Card 1</div>
|
||||
<div>Card 2</div>
|
||||
<div>Card 3</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Using deprecated v3 utilities (bg-opacity-*, flex-shrink-*, etc.)
|
||||
- Using `@tailwind` directives instead of `@import "tailwindcss"`
|
||||
- Trying to use `tailwind.config.js` instead of CSS `@theme` directive
|
||||
- Using margins for spacing between siblings instead of gap utilities
|
||||
- Forgetting to add dark mode variants when the project uses dark mode
|
||||
@ -1,23 +1,22 @@
|
||||
<!--
|
||||
Sync Impact Report
|
||||
|
||||
- Version change: 1.9.0 → 1.10.0
|
||||
- Version change: 1.8.1 → 1.8.2
|
||||
- Modified principles:
|
||||
- Operations / Run Observability Standard (clarified as non-negotiable 3-surface contract; added lifecycle, summary, guards, system-run policy)
|
||||
- RBAC Context — Planes, Roles, and Auditability (clarified admin vs tenant-context vs workspace-context)
|
||||
- Tenant Isolation is Non-negotiable (added scope + ownership rules)
|
||||
- RBAC-UX-007 — Global search must be tenant-safe (added workspace-context rules)
|
||||
- Filament UI — Action Surface Contract (NON-NEGOTIABLE) (added required spec scope fields)
|
||||
- Added sections:
|
||||
- Operations UX — 3-Surface Feedback (OPS-UX-055) (NON-NEGOTIABLE)
|
||||
- OperationRun lifecycle is service-owned (OPS-UX-LC-001)
|
||||
- Summary counts contract (OPS-UX-SUM-001)
|
||||
- Ops-UX regression guards are mandatory (OPS-UX-GUARD-001)
|
||||
- Scheduled/system runs (OPS-UX-SYS-001)
|
||||
- Scope & Ownership Clarification (SCOPE-001)
|
||||
- Spec Scope Fields (SCOPE-002)
|
||||
- Removed sections: None
|
||||
- Templates requiring updates:
|
||||
- ✅ .specify/templates/plan-template.md
|
||||
- ✅ .specify/templates/spec-template.md
|
||||
- ✅ .specify/templates/tasks-template.md
|
||||
- N/A: .specify/templates/commands/ (directory not present in this repo)
|
||||
- Follow-up TODOs:
|
||||
- Add CI regression guards for “no naked forms” + “view must use infolist” (heuristic scan) in test suite.
|
||||
- Follow-up TODOs: None
|
||||
-->
|
||||
|
||||
# TenantPilot Constitution
|
||||
@ -71,7 +70,6 @@ ### Tenant Isolation is Non-negotiable
|
||||
- Tenant-owned tables MUST include workspace_id and tenant_id as NOT NULL.
|
||||
- Workspace-owned tables MUST include workspace_id and MUST NOT include tenant_id.
|
||||
- Exception: OperationRun MAY have tenant_id nullable to support canonical workspace-context monitoring views; however, revealing any tenant-bound runs still MUST enforce entitlement checks to the referenced tenant scope.
|
||||
- Exception: AlertDelivery MAY have tenant_id nullable for workspace-scoped, non-tenant-operational artifacts (e.g., `event_type=alerts.test`). Tenant-bound delivery records still MUST enforce tenant entitlement checks, and tenantless delivery rows MUST NOT contain tenant-specific data.
|
||||
|
||||
### RBAC & UI Enforcement Standards (RBAC-UX)
|
||||
|
||||
@ -162,72 +160,6 @@ ### Operations / Run Observability Standard
|
||||
- Monitoring pages MUST be DB-only at render time (no external calls).
|
||||
- Start surfaces MUST NOT perform remote work inline; they only: authorize, create/reuse run (dedupe), enqueue work,
|
||||
confirm + “View run”.
|
||||
|
||||
### Operations UX — 3-Surface Feedback (OPS-UX-055) (NON-NEGOTIABLE)
|
||||
|
||||
If a feature creates/reuses `OperationRun`, it MUST use exactly three feedback surfaces — no others:
|
||||
|
||||
1) Toast (intent only / queued-only)
|
||||
- A toast MAY be shown only when the run is accepted/queued (intent feedback).
|
||||
- The toast MUST use `OperationUxPresenter::queuedToast($operationType)->send()`.
|
||||
- Feature code MUST NOT craft ad-hoc operation toasts.
|
||||
- A dedicated dedupe message MUST use the presenter (e.g., `alreadyQueuedToast(...)`), not `Notification::make()`.
|
||||
|
||||
2) Progress (active awareness only)
|
||||
- Live progress MUST exist only in:
|
||||
- the global active-ops widget, and
|
||||
- Monitoring → Operation Run Detail.
|
||||
- These surfaces MUST show only active runs (`queued|running`) and MUST never show terminal runs.
|
||||
- Determinate progress is allowed ONLY when `summary_counts.total` and `summary_counts.processed` are valid numeric values.
|
||||
- Determinate progress MUST be clamped to 0–100. Otherwise render indeterminate + elapsed time.
|
||||
- The widget MUST NOT show percentage text (optional `processed/total` is allowed).
|
||||
|
||||
3) Terminal DB Notification (audit outcome only)
|
||||
- Each run MUST emit exactly one persistent terminal DB notification when it becomes terminal.
|
||||
- Delivery MUST be initiator-only (no tenant-wide fan-out).
|
||||
- Completion notifications MUST be `OperationRunCompleted` only.
|
||||
- Feature code MUST NOT send custom completion DB notifications for operations (no `sendToDatabase()` for completion/abort).
|
||||
|
||||
Canonical navigation:
|
||||
- All “View run” links MUST use the canonical helper and MUST point to Monitoring → Operations → Run Detail.
|
||||
|
||||
### OperationRun lifecycle is service-owned (OPS-UX-LC-001)
|
||||
|
||||
Any change to `OperationRun.status` or `OperationRun.outcome` MUST go through `OperationRunService` (canonical transition method).
|
||||
This is the only allowed path because it enforces normalization, summary sanitization, idempotency, and terminal notification emission.
|
||||
|
||||
Forbidden outside `OperationRunService`:
|
||||
- `$operationRun->update(['status' => ...])` / `$operationRun->update(['outcome' => ...])`
|
||||
- `$operationRun->status = ...` / `$operationRun->outcome = ...`
|
||||
- Query-based updates that transition `status`/`outcome`
|
||||
|
||||
Allowed outside the service:
|
||||
- Updates to `context`, `message`, `reason_code` that do not change `status`/`outcome`.
|
||||
|
||||
### Summary counts contract (OPS-UX-SUM-001)
|
||||
|
||||
- `operation_runs.summary_counts` is the canonical metrics source for Ops-UX.
|
||||
- All keys MUST come from `OperationSummaryKeys::all()` (single source of truth).
|
||||
- Values MUST be flat numeric-only; no nested objects/arrays; no free-text.
|
||||
- Producers MUST NOT introduce new keys without:
|
||||
1) updating `OperationSummaryKeys::all()`,
|
||||
2) updating the spec canonical list,
|
||||
3) adding/adjusting tests.
|
||||
|
||||
### Ops-UX regression guards are mandatory (OPS-UX-GUARD-001)
|
||||
|
||||
The repo MUST include automated guards (Pest) that fail CI if:
|
||||
- any direct `OperationRun` status/outcome transition occurs outside `OperationRunService`,
|
||||
- jobs emit DB notifications for operation completion/abort (`OperationRunCompleted` is the single terminal notification),
|
||||
- deprecated legacy operation notification classes are referenced again.
|
||||
|
||||
These guards MUST fail with actionable output (file + snippet).
|
||||
|
||||
### Scheduled/system runs (OPS-UX-SYS-001)
|
||||
|
||||
- If a run has no initiator user, no terminal DB notification is emitted (initiator-only policy).
|
||||
- Outcomes remain auditable via Monitoring → Operations / Run Detail.
|
||||
- Any tenant-wide alerting MUST go through the Alerts system (not `OperationRun` notifications).
|
||||
- Active-run dedupe MUST be enforced at DB level (partial unique index/constraint for active states).
|
||||
- Failures MUST be stored as stable reason codes + sanitized messages; never persist secrets/tokens/PII/raw payload dumps
|
||||
in failures or notifications.
|
||||
@ -246,7 +178,7 @@ ### Filament UI — Action Surface Contract (NON-NEGOTIABLE)
|
||||
- Accepted forms: clickable rows via `recordUrl()` (preferred), a dedicated row “View” action, or a primary linked column.
|
||||
- Rule: Do NOT render a lone “View” row action button. If View is the only row action, prefer clickable rows.
|
||||
- View/Detail MUST define Header Actions (Edit + “More” group when applicable).
|
||||
- View/Detail MUST be sectioned (e.g., Infolist Sections / Cards); avoid long ungrouped field lists.
|
||||
- View/Detail SHOULD be sectioned (e.g., Infolist Sections / Cards); avoid long ungrouped field lists.
|
||||
- Create/Edit MUST provide consistent Save/Cancel UX.
|
||||
|
||||
Grouping & safety
|
||||
@ -266,38 +198,6 @@ ### Filament UI — Action Surface Contract (NON-NEGOTIABLE)
|
||||
- A change is not “Done” unless the Action Surface Contract is met OR an explicit exemption exists with documented reason.
|
||||
- CI MUST run an automated Action Surface Contract check (test suite and/or command) that fails when required surfaces are missing.
|
||||
|
||||
### Filament UI — Layout & Information Architecture Standards (UX-001)
|
||||
|
||||
Goal: Demo-level, enterprise-grade admin UX. These rules are NON-NEGOTIABLE for new or modified Filament screens.
|
||||
|
||||
Page layout
|
||||
- Create/Edit MUST default to a Main/Aside layout using a 3-column grid with `Main=columnSpan(2)` and `Aside=columnSpan(1)`.
|
||||
- All fields MUST be inside Sections/Cards. No “naked” inputs at the root schema level.
|
||||
- Main contains domain definition/content. Aside contains status/meta (status, version label, owner, scope selectors, timestamps).
|
||||
- Related data (assignments, relations, evidence, runs, findings, etc.) MUST render as separate Sections below the main/aside grid (or as tabs/sub-navigation), never mixed as unstructured long lists.
|
||||
|
||||
View pages
|
||||
- View/Detail MUST be a read-only experience using Infolists (or equivalent), not disabled edit forms.
|
||||
- Status-like values MUST render as badges/chips using the centralized badge semantics (BADGE-001).
|
||||
- Long text MUST render as readable prose (not textarea styling).
|
||||
|
||||
Empty states
|
||||
- Empty lists/tables MUST show: a specific title, one-sentence explanation, and exactly ONE primary CTA in the empty state.
|
||||
- When non-empty, the primary CTA MUST move to the table header (top-right) and MUST NOT be duplicated in the empty state.
|
||||
|
||||
Actions & flows
|
||||
- Pages SHOULD expose at most 1 primary header action and 1 secondary action; all other actions MUST be grouped (ActionGroup / BulkActionGroup).
|
||||
- Multi-step or high-risk flows MUST use a Wizard (e.g., capture/compare/restore with preview + confirmation).
|
||||
- Destructive actions MUST remain non-primary and require confirmation (RBAC-UX-005).
|
||||
|
||||
Table work-surface defaults
|
||||
- Tables SHOULD provide search (when the dataset can grow), a meaningful default sort, and filters for core dimensions (status/severity/type/tenant/time-range).
|
||||
- Tables MUST render key statuses as badges/chips (BADGE-001) and avoid ad-hoc status mappings.
|
||||
|
||||
Enforcement
|
||||
- New resources/pages SHOULD use shared layout builders (e.g., `MainAsideForm`, `MainAsideInfolist`, `StandardTableDefaults`) to keep screens consistent.
|
||||
- A change is not “Done” unless UX-001 is satisfied OR an explicit exemption exists with a documented rationale in the spec/PR.
|
||||
|
||||
Spec Scope Fields (SCOPE-002)
|
||||
|
||||
- Every feature spec MUST declare:
|
||||
@ -344,4 +244,4 @@ ### Versioning Policy (SemVer)
|
||||
- **MINOR**: new principle/section or materially expanded guidance.
|
||||
- **MAJOR**: removing/redefining principles in a backward-incompatible way.
|
||||
|
||||
**Version**: 1.10.0 | **Ratified**: 2026-01-03 | **Last Amended**: 2026-02-23
|
||||
**Version**: 1.8.2 | **Ratified**: 2026-01-03 | **Last Amended**: 2026-02-14
|
||||
|
||||
@ -41,15 +41,11 @@ ## Constitution Check
|
||||
- RBAC-UX: global search is tenant-scoped; non-members get no hints; inaccessible results are treated as not found (404 semantics)
|
||||
- Tenant isolation: all reads/writes tenant-scoped; cross-tenant views are explicit and access-checked
|
||||
- Run observability: long-running/remote/queued work creates/reuses `OperationRun`; start surfaces enqueue-only; Monitoring is DB-only; DB-only <2s actions may skip runs but security-relevant ones still audit-log; auth handshake exception OPS-EX-AUTH-001 allows synchronous outbound HTTP on `/auth/*` without `OperationRun`
|
||||
- Ops-UX 3-surface feedback: if `OperationRun` is used, feedback is exactly toast intent-only + progress surfaces + exactly-once terminal `OperationRunCompleted` (initiator-only); no queued/running DB notifications
|
||||
- Ops-UX lifecycle: `OperationRun.status` / `OperationRun.outcome` transitions are service-owned (only via `OperationRunService`); context-only updates allowed outside
|
||||
- Ops-UX summary counts: `summary_counts` keys come from `OperationSummaryKeys::all()` and values are flat numeric-only
|
||||
- Ops-UX guards: CI has regression guards that fail with actionable output (file + snippet) when these patterns regress
|
||||
- Ops-UX system runs: initiator-null runs emit no terminal DB notification; audit remains via Monitoring; tenant-wide alerting goes through Alerts (not OperationRun notifications)
|
||||
- Automation: queued/scheduled ops use locks + idempotency; handle 429/503 with backoff+jitter
|
||||
- Data minimization: Inventory stores metadata + whitelisted meta; logs contain no secrets/tokens
|
||||
- Badge semantics (BADGE-001): status-like badges use `BadgeCatalog` / `BadgeRenderer`; no ad-hoc mappings; new values include tests
|
||||
- Filament UI Action Surface Contract: for any new/modified Filament Resource/RelationManager/Page, define Header/Row/Bulk/Empty-State actions, ensure every List/Table has a record inspection affordance (prefer `recordUrl()` clickable rows; do not render a lone View row action), keep max 2 visible row actions with the rest in “More”, group bulk actions, require confirmations for destructive actions (typed confirmation for large/bulk where applicable), write audit logs for mutations, enforce RBAC via central helpers (non-member 404, member missing capability 403), and ensure CI blocks merges if the contract is violated or not explicitly exempted- Filament UI UX-001 (Layout & IA): Create/Edit uses Main/Aside (3-col grid, Main=columnSpan(2), Aside=columnSpan(1)); all fields inside Sections/Cards (no naked inputs); View uses Infolists (not disabled edit forms); status badges use BADGE-001; empty states have specific title + explanation + 1 CTA; max 1 primary + 1 secondary header action; tables provide search/sort/filters for core dimensions; shared layout builders preferred for consistency
|
||||
- Filament UI Action Surface Contract: for any new/modified Filament Resource/RelationManager/Page, define Header/Row/Bulk/Empty-State actions, ensure every List/Table has a record inspection affordance (prefer `recordUrl()` clickable rows; do not render a lone View row action), keep max 2 visible row actions with the rest in “More”, group bulk actions, require confirmations for destructive actions (typed confirmation for large/bulk where applicable), write audit logs for mutations, enforce RBAC via central helpers (non-member 404, member missing capability 403), and ensure CI blocks merges if the contract is violated or not explicitly exempted
|
||||
|
||||
## Project Structure
|
||||
|
||||
### Documentation (this feature)
|
||||
|
||||
@ -94,13 +94,6 @@ ## Requirements *(mandatory)*
|
||||
(preview/confirmation/audit), tenant isolation, run observability (`OperationRun` type/identity/visibility), and tests.
|
||||
If security-relevant DB-only actions intentionally skip `OperationRun`, the spec MUST describe `AuditLog` entries.
|
||||
|
||||
**Constitution alignment (OPS-UX):** If this feature creates/reuses an `OperationRun`, the spec MUST:
|
||||
- explicitly state compliance with the Ops-UX 3-surface feedback contract (toast intent-only, progress surfaces, terminal DB notification),
|
||||
- state that `OperationRun.status` / `OperationRun.outcome` transitions are service-owned (only via `OperationRunService`),
|
||||
- describe how `summary_counts` keys/values comply with `OperationSummaryKeys::all()` and numeric-only rules,
|
||||
- clarify scheduled/system-run behavior (initiator null → no terminal DB notification; audit is via Monitoring),
|
||||
- list which regression guard tests are added/updated to keep these rules enforceable in CI.
|
||||
|
||||
**Constitution alignment (RBAC-UX):** If this feature introduces or changes authorization behavior, the spec MUST:
|
||||
- state which authorization plane(s) are involved (tenant/admin `/admin` + tenant-context `/admin/t/{tenant}/...` vs platform `/system`),
|
||||
- ensure any cross-plane access is deny-as-not-found (404),
|
||||
@ -122,11 +115,7 @@ ## Requirements *(mandatory)*
|
||||
**Constitution alignment (Filament Action Surfaces):** If this feature adds or modifies any Filament Resource / RelationManager / Page,
|
||||
the spec MUST include a “UI Action Matrix” (see below) and explicitly state whether the Action Surface Contract is satisfied.
|
||||
If the contract is not satisfied, the spec MUST include an explicit exemption with rationale.
|
||||
**Constitution alignment (UX-001 — Layout & Information Architecture):** If this feature adds or modifies any Filament screen,
|
||||
the spec MUST describe compliance with UX-001: Create/Edit uses Main/Aside layout (3-col grid), all fields inside Sections/Cards
|
||||
(no naked inputs), View pages use Infolists (not disabled edit forms), status badges use BADGE-001, empty states have a specific
|
||||
title + explanation + exactly 1 CTA, and tables provide search/sort/filters for core dimensions.
|
||||
If UX-001 is not fully satisfied, the spec MUST include an explicit exemption with documented rationale.
|
||||
|
||||
<!--
|
||||
ACTION REQUIRED: The content in this section represents placeholders.
|
||||
Fill them out with the right functional requirements.
|
||||
|
||||
@ -14,13 +14,6 @@ # Tasks: [FEATURE NAME]
|
||||
If security-relevant DB-only actions skip `OperationRun`, include tasks for `AuditLog` entries (before/after + actor + tenant).
|
||||
Auth handshake exception (OPS-EX-AUTH-001): OIDC/SAML login handshakes may perform synchronous outbound HTTP on `/auth/*` endpoints
|
||||
without an `OperationRun`.
|
||||
If this feature creates/reuses an `OperationRun`, tasks MUST also include:
|
||||
- enforcing the Ops-UX 3-surface feedback contract (toast intent-only via `OperationUxPresenter`, progress only in widget + run detail, terminal notification is `OperationRunCompleted` exactly-once, initiator-only),
|
||||
- ensuring no queued/running DB notifications exist anywhere for operations (no `sendToDatabase()` for queued/running/completion/abort in feature code),
|
||||
- ensuring `OperationRun.status` / `OperationRun.outcome` transitions happen only via `OperationRunService`,
|
||||
- ensuring `summary_counts` keys come from `OperationSummaryKeys::all()` and values are flat numeric-only,
|
||||
- adding/updating Ops-UX regression guards (Pest) that fail CI with actionable output (file + snippet) when these patterns regress,
|
||||
- clarifying scheduled/system-run behavior (initiator null → no terminal DB notification; audit via Monitoring; tenant-wide alerting via Alerts system).
|
||||
**RBAC**: If this feature introduces or changes authorization, tasks MUST include:
|
||||
- explicit Gate/Policy enforcement for all mutation endpoints/actions,
|
||||
- explicit 404 vs 403 semantics:
|
||||
@ -41,14 +34,6 @@ # Tasks: [FEATURE NAME]
|
||||
- adding confirmations for destructive actions (and typed confirmation where required by scale),
|
||||
- adding `AuditLog` entries for relevant mutations,
|
||||
- adding/updated tests that enforce the contract and block merge on violations, OR documenting an explicit exemption with rationale.
|
||||
**Filament UI UX-001 (Layout & IA)**: If this feature adds/modifies any Filament screen, tasks MUST include:
|
||||
- ensuring Create/Edit pages use Main/Aside layout (3-col grid, Main=columnSpan(2), Aside=columnSpan(1)),
|
||||
- ensuring all form fields are inside Sections/Cards (no naked inputs at root schema level),
|
||||
- ensuring View pages use Infolists (not disabled edit forms); status badges use BADGE-001,
|
||||
- ensuring empty states show a specific title + explanation + exactly 1 CTA; non-empty tables move CTA to header,
|
||||
- capping header actions to max 1 primary + 1 secondary (rest grouped),
|
||||
- using shared layout builders (e.g., `MainAsideForm`, `MainAsideInfolist`, `StandardTableDefaults`) where available,
|
||||
- OR documenting an explicit exemption with rationale if UX-001 is not fully satisfied.
|
||||
**Badges**: If this feature changes status-like badge semantics, tasks MUST use `BadgeCatalog` / `BadgeRenderer` (BADGE-001),
|
||||
avoid ad-hoc mappings in Filament, and include mapping tests for any new/changed values.
|
||||
|
||||
|
||||
357
Agents.md
357
Agents.md
@ -389,7 +389,6 @@ ## Reference Materials
|
||||
=== .ai/filament-v5-blueprint rules ===
|
||||
|
||||
## Source of Truth
|
||||
|
||||
If any Filament behavior is uncertain, lookup the exact section in:
|
||||
- docs/research/filament-v5-notes.md
|
||||
and prefer that over guesses.
|
||||
@ -399,7 +398,6 @@ # SECTION B — FILAMENT V5 BLUEPRINT (EXECUTABLE RULES)
|
||||
# Filament Blueprint (v5)
|
||||
|
||||
## 1) Non-negotiables
|
||||
|
||||
- Filament v5 requires Livewire v4.0+.
|
||||
- Laravel 11+: register panel providers in `bootstrap/providers.php` (never `bootstrap/app.php`).
|
||||
- Global search hard rule: If a Resource should appear in Global Search, it must have an Edit or View page; otherwise it will return no results.
|
||||
@ -415,7 +413,6 @@ ## 1) Non-negotiables
|
||||
- https://filamentphp.com/docs/5.x/styling/css-hooks
|
||||
|
||||
## 2) Directory & naming conventions
|
||||
|
||||
- Default to Filament discovery conventions for Resources/Pages/Widgets unless you adopt modular architecture.
|
||||
- Clusters: directory layout is recommended, not mandatory; functional behavior depends on `$cluster`.
|
||||
|
||||
@ -424,7 +421,6 @@ ## 2) Directory & naming conventions
|
||||
- https://filamentphp.com/docs/5.x/advanced/modular-architecture
|
||||
|
||||
## 3) Panel setup defaults
|
||||
|
||||
- Default to a single `/admin` panel unless multiple audiences/configs demand multiple panels.
|
||||
- Verify provider registration (Laravel 11+: `bootstrap/providers.php`) when adding a panel.
|
||||
- Use `path()` carefully; treat `path('')` as a high-risk change requiring route conflict review.
|
||||
@ -438,7 +434,6 @@ ## 3) Panel setup defaults
|
||||
- https://filamentphp.com/docs/5.x/advanced/assets
|
||||
|
||||
## 4) Navigation & information architecture
|
||||
|
||||
- Use nav groups + sort order intentionally; apply conditional visibility for clarity, but enforce authorization separately.
|
||||
- Use clusters to introduce hierarchy and sub-navigation when sidebar complexity grows.
|
||||
- Treat cluster code structure as a recommendation (organizational benefit), not a required rule.
|
||||
@ -452,7 +447,6 @@ ## 4) Navigation & information architecture
|
||||
- https://filamentphp.com/docs/5.x/navigation/user-menu
|
||||
|
||||
## 5) Resource patterns
|
||||
|
||||
- Default to Resources for CRUD; use custom pages for non-CRUD tools/workflows.
|
||||
- Global search:
|
||||
- If a resource is intended for global search: ensure Edit/View page exists.
|
||||
@ -465,7 +459,6 @@ ## 5) Resource patterns
|
||||
- https://filamentphp.com/docs/5.x/resources/global-search
|
||||
|
||||
## 6) Page lifecycle & query rules
|
||||
|
||||
- Treat relationship-backed rendering in aggregate contexts (global search details, list summaries) as requiring eager loading.
|
||||
- Prefer render hooks for layout injection; avoid publishing internal views.
|
||||
|
||||
@ -474,7 +467,6 @@ ## 6) Page lifecycle & query rules
|
||||
- https://filamentphp.com/docs/5.x/advanced/render-hooks
|
||||
|
||||
## 7) Infolists vs RelationManagers (decision tree)
|
||||
|
||||
- Interactive CRUD / attach / detach under owner record → RelationManager.
|
||||
- Pick existing related record(s) inside owner form → Select / CheckboxList relationship fields.
|
||||
- Inline CRUD inside owner form → Repeater.
|
||||
@ -485,7 +477,6 @@ ## 7) Infolists vs RelationManagers (decision tree)
|
||||
- https://filamentphp.com/docs/5.x/infolists/overview
|
||||
|
||||
## 8) Form patterns (validation, reactivity, state)
|
||||
|
||||
- Default: minimize server-driven reactivity; only use it when schema/visibility/requirements must change server-side.
|
||||
- Prefer “on blur” semantics for chatty inputs when using reactive behavior (per docs patterns).
|
||||
- Custom field views must obey state binding modifiers.
|
||||
@ -495,7 +486,6 @@ ## 8) Form patterns (validation, reactivity, state)
|
||||
- https://filamentphp.com/docs/5.x/forms/custom-fields
|
||||
|
||||
## 9) Table & action patterns
|
||||
|
||||
- Tables: always define a meaningful empty state (and empty-state actions where appropriate).
|
||||
- Actions:
|
||||
- Execution actions use `->action(...)`.
|
||||
@ -508,7 +498,6 @@ ## 9) Table & action patterns
|
||||
- https://filamentphp.com/docs/5.x/actions/modals
|
||||
|
||||
## 10) Authorization & security
|
||||
|
||||
- Enforce panel access in non-local environments as documented.
|
||||
- UI visibility is not security; enforce policies/access checks in addition to hiding UI.
|
||||
- Bulk operations: explicitly decide between “Any” policy methods vs per-record authorization.
|
||||
@ -518,7 +507,6 @@ ## 10) Authorization & security
|
||||
- https://filamentphp.com/docs/5.x/resources/deleting-records
|
||||
|
||||
## 11) Notifications & UX feedback
|
||||
|
||||
- Default to explicit success/error notifications for user-triggered mutations that aren’t instantly obvious.
|
||||
- Treat polling as a cost; set intervals intentionally where polling is used.
|
||||
|
||||
@ -527,7 +515,6 @@ ## 11) Notifications & UX feedback
|
||||
- https://filamentphp.com/docs/5.x/widgets/stats-overview
|
||||
|
||||
## 12) Performance defaults
|
||||
|
||||
- Heavy assets: prefer on-demand loading (`loadedOnRequest()` + `x-load-css` / `x-load-js`) for heavy dependencies.
|
||||
- Styling overrides use CSS hook classes; layout injection uses render hooks; avoid view publishing.
|
||||
|
||||
@ -537,7 +524,6 @@ ## 12) Performance defaults
|
||||
- https://filamentphp.com/docs/5.x/advanced/render-hooks
|
||||
|
||||
## 13) Testing requirements
|
||||
|
||||
- Test pages/relation managers/widgets as Livewire components.
|
||||
- Test actions using Filament’s action testing guidance.
|
||||
- Do not mount non-Livewire classes in Livewire tests.
|
||||
@ -547,7 +533,6 @@ ## 13) Testing requirements
|
||||
- https://filamentphp.com/docs/5.x/testing/testing-actions
|
||||
|
||||
## 14) Forbidden patterns
|
||||
|
||||
- Mixing Filament v3/v4 APIs into v5 code.
|
||||
- Any mention of Livewire v3 for Filament v5.
|
||||
- Registering panel providers in `bootstrap/app.php` on Laravel 11+.
|
||||
@ -562,7 +547,6 @@ ## 14) Forbidden patterns
|
||||
- https://filamentphp.com/docs/5.x/advanced/assets
|
||||
|
||||
## 15) Agent output contract
|
||||
|
||||
For any implementation request, the agent must explicitly state:
|
||||
1) Livewire v4.0+ compliance.
|
||||
2) Provider registration location (Laravel 11+: `bootstrap/providers.php`).
|
||||
@ -583,7 +567,6 @@ ## 15) Agent output contract
|
||||
# SECTION C — AI REVIEW CHECKLIST (STRICT CHECKBOXES)
|
||||
|
||||
## Version Safety
|
||||
|
||||
- [ ] Filament v5 explicitly targets Livewire v4.0+ (no Livewire v3 references anywhere).
|
||||
- Source: https://filamentphp.com/docs/5.x/upgrade-guide — “Upgrading Livewire”
|
||||
- [ ] All references are Filament `/docs/5.x/` only (no v3/v4 docs, no legacy APIs).
|
||||
@ -591,7 +574,6 @@ ## Version Safety
|
||||
- Source: https://filamentphp.com/docs/5.x/upgrade-guide — “New requirements”
|
||||
|
||||
## Panel & Navigation
|
||||
|
||||
- [ ] Laravel 11+: panel providers are registered in `bootstrap/providers.php` (not `bootstrap/app.php`).
|
||||
- Source: https://filamentphp.com/docs/5.x/panel-configuration — “Creating a new panel”
|
||||
- [ ] Panel `path()` choices are intentional and do not conflict with existing routes (especially `path('')`).
|
||||
@ -606,7 +588,6 @@ ## Panel & Navigation
|
||||
- Source: https://filamentphp.com/docs/5.x/navigation/user-menu — “Introduction”
|
||||
|
||||
## Resource Structure
|
||||
|
||||
- [ ] `$recordTitleAttribute` is set for any resource intended for global search.
|
||||
- Source: https://filamentphp.com/docs/5.x/resources/overview — “Record titles”
|
||||
- [ ] Hard rule enforced: every globally searchable resource has an Edit or View page; otherwise global search is disabled for it.
|
||||
@ -615,21 +596,18 @@ ## Resource Structure
|
||||
- Source: https://filamentphp.com/docs/5.x/resources/global-search — “Adding extra details to global search results”
|
||||
|
||||
## Infolists & Relations
|
||||
|
||||
- [ ] Each relationship uses the correct tool (RelationManager vs Select/CheckboxList vs Repeater) based on required interaction.
|
||||
- Source: https://filamentphp.com/docs/5.x/resources/managing-relationships — “Choosing the right tool for the job”
|
||||
- [ ] RelationManagers remain lazy-loaded by default unless there’s an explicit UX justification.
|
||||
- Source: https://filamentphp.com/docs/5.x/resources/managing-relationships — “Disabling lazy loading”
|
||||
|
||||
## Forms
|
||||
|
||||
- [ ] Server-driven reactivity is minimal; chatty inputs do not trigger network requests unnecessarily.
|
||||
- Source: https://filamentphp.com/docs/5.x/forms/overview — “Reactive fields on blur”
|
||||
- [ ] Custom field views obey state binding modifiers (no hardcoded `wire:model` without modifiers).
|
||||
- Source: https://filamentphp.com/docs/5.x/forms/custom-fields — “Obeying state binding modifiers”
|
||||
|
||||
## Tables & Actions
|
||||
|
||||
- [ ] Tables define a meaningful empty state (and empty-state actions where appropriate).
|
||||
- Source: https://filamentphp.com/docs/5.x/tables/empty-state — “Adding empty state actions”
|
||||
- [ ] All destructive actions execute via `->action(...)` and include `->requiresConfirmation()`.
|
||||
@ -638,7 +616,6 @@ ## Tables & Actions
|
||||
- Source: https://filamentphp.com/docs/5.x/actions/modals — “Confirmation modals”
|
||||
|
||||
## Authorization & Security
|
||||
|
||||
- [ ] Panel access is enforced for non-local environments as documented.
|
||||
- Source: https://filamentphp.com/docs/5.x/users/overview — “Authorizing access to the panel”
|
||||
- [ ] UI visibility is not treated as authorization; policies/access checks still enforce boundaries.
|
||||
@ -646,28 +623,24 @@ ## Authorization & Security
|
||||
- Source: https://filamentphp.com/docs/5.x/resources/deleting-records — “Authorization”
|
||||
|
||||
## UX & Notifications
|
||||
|
||||
- [ ] User-triggered mutations provide explicit success/error notifications when outcomes aren’t instantly obvious.
|
||||
- Source: https://filamentphp.com/docs/5.x/notifications/overview — “Introduction”
|
||||
- [ ] Polling (widgets/notifications) is configured intentionally (interval set or disabled) to control load.
|
||||
- Source: https://filamentphp.com/docs/5.x/widgets/stats-overview — “Live updating stats (polling)”
|
||||
|
||||
## Performance
|
||||
|
||||
- [ ] Heavy frontend assets are loaded on-demand using `loadedOnRequest()` + `x-load-css` / `x-load-js` where appropriate.
|
||||
- Source: https://filamentphp.com/docs/5.x/advanced/assets — “Lazy loading CSS” / “Lazy loading JavaScript”
|
||||
- [ ] Styling overrides use CSS hook classes discovered via DevTools (no brittle selectors by default).
|
||||
- Source: https://filamentphp.com/docs/5.x/styling/css-hooks — “Discovering hook classes”
|
||||
|
||||
## Testing
|
||||
|
||||
- [ ] Livewire tests mount Filament pages/relation managers/widgets (Livewire components), not static resource classes.
|
||||
- Source: https://filamentphp.com/docs/5.x/testing/overview — “What is a Livewire component when using Filament?”
|
||||
- [ ] Actions that mutate data are covered using Filament’s action testing guidance.
|
||||
- Source: https://filamentphp.com/docs/5.x/testing/testing-actions — “Testing actions”
|
||||
|
||||
## Deployment / Ops
|
||||
|
||||
- [ ] `php artisan filament:assets` is included in the deployment process when using registered assets.
|
||||
- Source: https://filamentphp.com/docs/5.x/advanced/assets — “The FilamentAsset facade”
|
||||
|
||||
@ -675,13 +648,12 @@ ## Deployment / Ops
|
||||
|
||||
# Laravel Boost Guidelines
|
||||
|
||||
The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to ensure the best experience when building Laravel applications.
|
||||
The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to enhance the user's satisfaction building Laravel applications.
|
||||
|
||||
## Foundational Context
|
||||
|
||||
This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.
|
||||
|
||||
- php - 8.4.1
|
||||
- php - 8.4.15
|
||||
- filament/filament (FILAMENT) - v5
|
||||
- laravel/framework (LARAVEL) - v12
|
||||
- laravel/prompts (PROMPTS) - v0
|
||||
@ -694,73 +666,56 @@ ## Foundational Context
|
||||
- phpunit/phpunit (PHPUNIT) - v12
|
||||
- tailwindcss (TAILWINDCSS) - v4
|
||||
|
||||
## Skills Activation
|
||||
|
||||
This project has domain-specific skills available. You MUST activate the relevant skill whenever you work in that domain—don't wait until you're stuck.
|
||||
|
||||
- `pest-testing` — Tests applications using the Pest 4 PHP framework. Activates when writing tests, creating unit or feature tests, adding assertions, testing Livewire components, browser testing, debugging test failures, working with datasets or mocking; or when the user mentions test, spec, TDD, expects, assertion, coverage, or needs to verify functionality works.
|
||||
- `tailwindcss-development` — Styles applications using Tailwind CSS v4 utilities. Activates when adding styles, restyling components, working with gradients, spacing, layout, flex, grid, responsive design, dark mode, colors, typography, or borders; or when the user mentions CSS, styling, classes, Tailwind, restyle, hero section, cards, buttons, or any visual/UI changes.
|
||||
|
||||
## Conventions
|
||||
|
||||
- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming.
|
||||
- Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`.
|
||||
- Check for existing components to reuse before writing a new one.
|
||||
|
||||
## Verification Scripts
|
||||
|
||||
- Do not create verification scripts or tinker when tests cover that functionality and prove they work. Unit and feature tests are more important.
|
||||
- Do not create verification scripts or tinker when tests cover that functionality and prove it works. Unit and feature tests are more important.
|
||||
|
||||
## Application Structure & Architecture
|
||||
|
||||
- Stick to existing directory structure; don't create new base folders without approval.
|
||||
- Do not change the application's dependencies without approval.
|
||||
|
||||
## Frontend Bundling
|
||||
|
||||
- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `vendor/bin/sail npm run build`, `vendor/bin/sail npm run dev`, or `vendor/bin/sail composer run dev`. Ask them.
|
||||
|
||||
## Documentation Files
|
||||
|
||||
- You must only create documentation files if explicitly requested by the user.
|
||||
|
||||
## Replies
|
||||
|
||||
- Be concise in your explanations - focus on what's important rather than explaining obvious details.
|
||||
|
||||
## Documentation Files
|
||||
- You must only create documentation files if explicitly requested by the user.
|
||||
|
||||
=== boost rules ===
|
||||
|
||||
# Laravel Boost
|
||||
|
||||
## Laravel Boost
|
||||
- Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them.
|
||||
|
||||
## Artisan
|
||||
|
||||
- Use the `list-artisan-commands` tool when you need to call an Artisan command to double-check the available parameters.
|
||||
|
||||
## URLs
|
||||
|
||||
- Whenever you share a project URL with the user, you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain/IP, and port.
|
||||
|
||||
## Tinker / Debugging
|
||||
|
||||
- You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly.
|
||||
- Use the `database-query` tool when you only need to read from the database.
|
||||
- Use the `database-schema` tool to inspect table structure before writing migrations or models.
|
||||
|
||||
## Reading Browser Logs With the `browser-logs` Tool
|
||||
|
||||
- You can read browser logs, errors, and exceptions using the `browser-logs` tool from Boost.
|
||||
- Only recent browser logs will be useful - ignore old logs.
|
||||
|
||||
## Searching Documentation (Critically Important)
|
||||
|
||||
- Boost comes with a powerful `search-docs` tool you should use before trying other approaches when working with Laravel or Laravel ecosystem packages. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages.
|
||||
- Boost comes with a powerful `search-docs` tool you should use before any other approaches when dealing with Laravel or Laravel ecosystem packages. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages.
|
||||
- The `search-docs` tool is perfect for all Laravel-related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc.
|
||||
- You must use this tool to search for Laravel ecosystem documentation before falling back to other approaches.
|
||||
- Search the documentation before making code changes to ensure we are taking the correct approach.
|
||||
- Use multiple, broad, simple, topic-based queries at once. For example: `['rate limiting', 'routing rate limiting', 'routing']`. The most relevant results will be returned first.
|
||||
- Use multiple, broad, simple, topic-based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`.
|
||||
- Do not add package names to queries; package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`.
|
||||
|
||||
### Available Search Syntax
|
||||
- You can and should pass multiple queries at once. The most relevant results will be returned first.
|
||||
|
||||
1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'.
|
||||
2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit".
|
||||
@ -770,44 +725,38 @@ ### Available Search Syntax
|
||||
|
||||
=== php rules ===
|
||||
|
||||
# PHP
|
||||
## PHP
|
||||
|
||||
- Always use curly braces for control structures, even for single-line bodies.
|
||||
|
||||
## Constructors
|
||||
- Always use curly braces for control structures, even if it has one line.
|
||||
|
||||
### Constructors
|
||||
- Use PHP 8 constructor property promotion in `__construct()`.
|
||||
- `public function __construct(public GitHub $github) { }`
|
||||
- <code-snippet>public function __construct(public GitHub $github) { }</code-snippet>
|
||||
- Do not allow empty `__construct()` methods with zero parameters unless the constructor is private.
|
||||
|
||||
## Type Declarations
|
||||
|
||||
### Type Declarations
|
||||
- Always use explicit return type declarations for methods and functions.
|
||||
- Use appropriate PHP type hints for method parameters.
|
||||
|
||||
<!-- Explicit Return Types and Method Params -->
|
||||
```php
|
||||
<code-snippet name="Explicit Return Types and Method Params" lang="php">
|
||||
protected function isAccessible(User $user, ?string $path = null): bool
|
||||
{
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
## Enums
|
||||
|
||||
- Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`.
|
||||
</code-snippet>
|
||||
|
||||
## Comments
|
||||
|
||||
- Prefer PHPDoc blocks over inline comments. Never use comments within the code itself unless the logic is exceptionally complex.
|
||||
- Prefer PHPDoc blocks over inline comments. Never use comments within the code itself unless there is something very complex going on.
|
||||
|
||||
## PHPDoc Blocks
|
||||
- Add useful array shape type definitions for arrays when appropriate.
|
||||
|
||||
- Add useful array shape type definitions when appropriate.
|
||||
## Enums
|
||||
- Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`.
|
||||
|
||||
=== sail rules ===
|
||||
|
||||
# Laravel Sail
|
||||
## Laravel Sail
|
||||
|
||||
- This project runs inside Laravel Sail's Docker containers. You MUST execute all commands through Sail.
|
||||
- Start services using `vendor/bin/sail up -d` and stop them with `vendor/bin/sail stop`.
|
||||
@ -821,21 +770,20 @@ # Laravel Sail
|
||||
|
||||
=== tests rules ===
|
||||
|
||||
# Test Enforcement
|
||||
## Test Enforcement
|
||||
|
||||
- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass.
|
||||
- Run the minimum number of tests needed to ensure code quality and speed. Use `vendor/bin/sail artisan test --compact` with a specific filename or filter.
|
||||
|
||||
=== laravel/core rules ===
|
||||
|
||||
# Do Things the Laravel Way
|
||||
## Do Things the Laravel Way
|
||||
|
||||
- Use `vendor/bin/sail artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool.
|
||||
- If you're creating a generic PHP class, use `vendor/bin/sail artisan make:class`.
|
||||
- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.
|
||||
|
||||
## Database
|
||||
|
||||
### Database
|
||||
- Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins.
|
||||
- Use Eloquent models and relationships before suggesting raw database queries.
|
||||
- Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them.
|
||||
@ -843,53 +791,43 @@ ## Database
|
||||
- Use Laravel's query builder for very complex database operations.
|
||||
|
||||
### Model Creation
|
||||
|
||||
- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `vendor/bin/sail artisan make:model`.
|
||||
|
||||
### APIs & Eloquent Resources
|
||||
|
||||
- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention.
|
||||
|
||||
## Controllers & Validation
|
||||
|
||||
### Controllers & Validation
|
||||
- Always create Form Request classes for validation rather than inline validation in controllers. Include both validation rules and custom error messages.
|
||||
- Check sibling Form Requests to see if the application uses array or string based validation rules.
|
||||
|
||||
## Authentication & Authorization
|
||||
|
||||
- Use Laravel's built-in authentication and authorization features (gates, policies, Sanctum, etc.).
|
||||
|
||||
## URL Generation
|
||||
|
||||
- When generating links to other pages, prefer named routes and the `route()` function.
|
||||
|
||||
## Queues
|
||||
|
||||
### Queues
|
||||
- Use queued jobs for time-consuming operations with the `ShouldQueue` interface.
|
||||
|
||||
## Configuration
|
||||
### Authentication & Authorization
|
||||
- Use Laravel's built-in authentication and authorization features (gates, policies, Sanctum, etc.).
|
||||
|
||||
### URL Generation
|
||||
- When generating links to other pages, prefer named routes and the `route()` function.
|
||||
|
||||
### Configuration
|
||||
- Use environment variables only in configuration files - never use the `env()` function directly outside of config files. Always use `config('app.name')`, not `env('APP_NAME')`.
|
||||
|
||||
## Testing
|
||||
|
||||
### Testing
|
||||
- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.
|
||||
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
|
||||
- When creating tests, make use of `vendor/bin/sail artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.
|
||||
|
||||
## Vite Error
|
||||
|
||||
### Vite Error
|
||||
- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `vendor/bin/sail npm run build` or ask the user to run `vendor/bin/sail npm run dev` or `vendor/bin/sail composer run dev`.
|
||||
|
||||
=== laravel/v12 rules ===
|
||||
|
||||
# Laravel 12
|
||||
## Laravel 12
|
||||
|
||||
- CRITICAL: ALWAYS use `search-docs` tool for version-specific Laravel documentation and updated code examples.
|
||||
- Use the `search-docs` tool to get version-specific documentation.
|
||||
- Since Laravel 11, Laravel has a new streamlined file structure which this project uses.
|
||||
|
||||
## Laravel 12 Structure
|
||||
|
||||
### Laravel 12 Structure
|
||||
- In Laravel 12, middleware are no longer registered in `app/Http/Kernel.php`.
|
||||
- Middleware are configured declaratively in `bootstrap/app.php` using `Application::configure()->withMiddleware()`.
|
||||
- `bootstrap/app.php` is the file to register middleware, exceptions, and routing files.
|
||||
@ -897,39 +835,224 @@ ## Laravel 12 Structure
|
||||
- The `app\Console\Kernel.php` file no longer exists; use `bootstrap/app.php` or `routes/console.php` for console configuration.
|
||||
- Console commands in `app/Console/Commands/` are automatically available and do not require manual registration.
|
||||
|
||||
## Database
|
||||
|
||||
### Database
|
||||
- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost.
|
||||
- Laravel 12 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`.
|
||||
|
||||
### Models
|
||||
|
||||
- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models.
|
||||
|
||||
=== livewire/core rules ===
|
||||
|
||||
## Livewire
|
||||
|
||||
- Use the `search-docs` tool to find exact version-specific documentation for how to write Livewire and Livewire tests.
|
||||
- Use the `vendor/bin/sail artisan make:livewire [Posts\CreatePost]` Artisan command to create new components.
|
||||
- State should live on the server, with the UI reflecting it.
|
||||
- All Livewire requests hit the Laravel backend; they're like regular HTTP requests. Always validate form data and run authorization checks in Livewire actions.
|
||||
|
||||
## Livewire Best Practices
|
||||
- Livewire components require a single root element.
|
||||
- Use `wire:loading` and `wire:dirty` for delightful loading states.
|
||||
- Add `wire:key` in loops:
|
||||
|
||||
```blade
|
||||
@foreach ($items as $item)
|
||||
<div wire:key="item-{{ $item->id }}">
|
||||
{{ $item->name }}
|
||||
</div>
|
||||
@endforeach
|
||||
```
|
||||
|
||||
- Prefer lifecycle hooks like `mount()`, `updatedFoo()` for initialization and reactive side effects:
|
||||
|
||||
<code-snippet name="Lifecycle Hook Examples" lang="php">
|
||||
public function mount(User $user) { $this->user = $user; }
|
||||
public function updatedSearch() { $this->resetPage(); }
|
||||
</code-snippet>
|
||||
|
||||
## Testing Livewire
|
||||
|
||||
<code-snippet name="Example Livewire Component Test" lang="php">
|
||||
Livewire::test(Counter::class)
|
||||
->assertSet('count', 0)
|
||||
->call('increment')
|
||||
->assertSet('count', 1)
|
||||
->assertSee(1)
|
||||
->assertStatus(200);
|
||||
</code-snippet>
|
||||
|
||||
<code-snippet name="Testing Livewire Component Exists on Page" lang="php">
|
||||
$this->get('/posts/create')
|
||||
->assertSeeLivewire(CreatePost::class);
|
||||
</code-snippet>
|
||||
|
||||
=== pint/core rules ===
|
||||
|
||||
# Laravel Pint Code Formatter
|
||||
## Laravel Pint Code Formatter
|
||||
|
||||
- You must run `vendor/bin/sail bin pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style.
|
||||
- Do not run `vendor/bin/sail bin pint --test --format agent`, simply run `vendor/bin/sail bin pint --format agent` to fix any formatting issues.
|
||||
- You must run `vendor/bin/sail bin pint --dirty` before finalizing changes to ensure your code matches the project's expected style.
|
||||
- Do not run `vendor/bin/sail bin pint --test`, simply run `vendor/bin/sail bin pint` to fix any formatting issues.
|
||||
|
||||
=== pest/core rules ===
|
||||
|
||||
## Pest
|
||||
### Testing
|
||||
- If you need to verify a feature is working, write or update a Unit / Feature test.
|
||||
|
||||
- This project uses Pest for testing. Create tests: `vendor/bin/sail artisan make:test --pest {name}`.
|
||||
- Run tests: `vendor/bin/sail artisan test --compact` or filter: `vendor/bin/sail artisan test --compact --filter=testName`.
|
||||
- Do NOT delete tests without approval.
|
||||
- CRITICAL: ALWAYS use `search-docs` tool for version-specific Pest documentation and updated code examples.
|
||||
- IMPORTANT: Activate `pest-testing` every time you're working with a Pest or testing-related task.
|
||||
### Pest Tests
|
||||
- All tests must be written using Pest. Use `vendor/bin/sail artisan make:test --pest {name}`.
|
||||
- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files - these are core to the application.
|
||||
- Tests should test all of the happy paths, failure paths, and weird paths.
|
||||
- Tests live in the `tests/Feature` and `tests/Unit` directories.
|
||||
- Pest tests look and behave like this:
|
||||
<code-snippet name="Basic Pest Test Example" lang="php">
|
||||
it('is true', function () {
|
||||
expect(true)->toBeTrue();
|
||||
});
|
||||
</code-snippet>
|
||||
|
||||
### Running Tests
|
||||
- Run the minimal number of tests using an appropriate filter before finalizing code edits.
|
||||
- To run all tests: `vendor/bin/sail artisan test --compact`.
|
||||
- To run all tests in a file: `vendor/bin/sail artisan test --compact tests/Feature/ExampleTest.php`.
|
||||
- To filter on a particular test name: `vendor/bin/sail artisan test --compact --filter=testName` (recommended after making a change to a related file).
|
||||
- When the tests relating to your changes are passing, ask the user if they would like to run the entire test suite to ensure everything is still passing.
|
||||
|
||||
### Pest Assertions
|
||||
- When asserting status codes on a response, use the specific method like `assertForbidden` and `assertNotFound` instead of using `assertStatus(403)` or similar, e.g.:
|
||||
<code-snippet name="Pest Example Asserting postJson Response" lang="php">
|
||||
it('returns all', function () {
|
||||
$response = $this->postJson('/api/docs', []);
|
||||
|
||||
$response->assertSuccessful();
|
||||
});
|
||||
</code-snippet>
|
||||
|
||||
### Mocking
|
||||
- Mocking can be very helpful when appropriate.
|
||||
- When mocking, you can use the `Pest\Laravel\mock` Pest function, but always import it via `use function Pest\Laravel\mock;` before using it. Alternatively, you can use `$this->mock()` if existing tests do.
|
||||
- You can also create partial mocks using the same import or self method.
|
||||
|
||||
### Datasets
|
||||
- Use datasets in Pest to simplify tests that have a lot of duplicated data. This is often the case when testing validation rules, so consider this solution when writing tests for validation rules.
|
||||
|
||||
<code-snippet name="Pest Dataset Example" lang="php">
|
||||
it('has emails', function (string $email) {
|
||||
expect($email)->not->toBeEmpty();
|
||||
})->with([
|
||||
'james' => 'james@laravel.com',
|
||||
'taylor' => 'taylor@laravel.com',
|
||||
]);
|
||||
</code-snippet>
|
||||
|
||||
=== pest/v4 rules ===
|
||||
|
||||
## Pest 4
|
||||
|
||||
- Pest 4 is a huge upgrade to Pest and offers: browser testing, smoke testing, visual regression testing, test sharding, and faster type coverage.
|
||||
- Browser testing is incredibly powerful and useful for this project.
|
||||
- Browser tests should live in `tests/Browser/`.
|
||||
- Use the `search-docs` tool for detailed guidance on utilizing these features.
|
||||
|
||||
### Browser Testing
|
||||
- You can use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories within Pest 4 browser tests, as well as `RefreshDatabase` (when needed) to ensure a clean state for each test.
|
||||
- Interact with the page (click, type, scroll, select, submit, drag-and-drop, touch gestures, etc.) when appropriate to complete the test.
|
||||
- If requested, test on multiple browsers (Chrome, Firefox, Safari).
|
||||
- If requested, test on different devices and viewports (like iPhone 14 Pro, tablets, or custom breakpoints).
|
||||
- Switch color schemes (light/dark mode) when appropriate.
|
||||
- Take screenshots or pause tests for debugging when appropriate.
|
||||
|
||||
### Example Tests
|
||||
|
||||
<code-snippet name="Pest Browser Test Example" lang="php">
|
||||
it('may reset the password', function () {
|
||||
Notification::fake();
|
||||
|
||||
$this->actingAs(User::factory()->create());
|
||||
|
||||
$page = visit('/sign-in'); // Visit on a real browser...
|
||||
|
||||
$page->assertSee('Sign In')
|
||||
->assertNoJavascriptErrors() // or ->assertNoConsoleLogs()
|
||||
->click('Forgot Password?')
|
||||
->fill('email', 'nuno@laravel.com')
|
||||
->click('Send Reset Link')
|
||||
->assertSee('We have emailed your password reset link!')
|
||||
|
||||
Notification::assertSent(ResetPassword::class);
|
||||
});
|
||||
</code-snippet>
|
||||
|
||||
<code-snippet name="Pest Smoke Testing Example" lang="php">
|
||||
$pages = visit(['/', '/about', '/contact']);
|
||||
|
||||
$pages->assertNoJavascriptErrors()->assertNoConsoleLogs();
|
||||
</code-snippet>
|
||||
|
||||
=== tailwindcss/core rules ===
|
||||
|
||||
# Tailwind CSS
|
||||
## Tailwind CSS
|
||||
|
||||
- Always use existing Tailwind conventions; check project patterns before adding new ones.
|
||||
- IMPORTANT: Always use `search-docs` tool for version-specific Tailwind CSS documentation and updated code examples. Never rely on training data.
|
||||
- IMPORTANT: Activate `tailwindcss-development` every time you're working with a Tailwind CSS or styling-related task.
|
||||
- Use Tailwind CSS classes to style HTML; check and use existing Tailwind conventions within the project before writing your own.
|
||||
- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc.).
|
||||
- Think through class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child carefully to limit repetition, and group elements logically.
|
||||
- You can use the `search-docs` tool to get exact examples from the official documentation when needed.
|
||||
|
||||
### Spacing
|
||||
- When listing items, use gap utilities for spacing; don't use margins.
|
||||
|
||||
<code-snippet name="Valid Flex Gap Spacing Example" lang="html">
|
||||
<div class="flex gap-8">
|
||||
<div>Superior</div>
|
||||
<div>Michigan</div>
|
||||
<div>Erie</div>
|
||||
</div>
|
||||
</code-snippet>
|
||||
|
||||
### Dark Mode
|
||||
- If existing pages and components support dark mode, new pages and components must support dark mode in a similar way, typically using `dark:`.
|
||||
|
||||
=== tailwindcss/v4 rules ===
|
||||
|
||||
## Tailwind CSS 4
|
||||
|
||||
- Always use Tailwind CSS v4; do not use the deprecated utilities.
|
||||
- `corePlugins` is not supported in Tailwind v4.
|
||||
- In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed.
|
||||
|
||||
<code-snippet name="Extending Theme in CSS" lang="css">
|
||||
@theme {
|
||||
--color-brand: oklch(0.72 0.11 178);
|
||||
}
|
||||
</code-snippet>
|
||||
|
||||
- In Tailwind v4, you import Tailwind using a regular CSS `@import` statement, not using the `@tailwind` directives used in v3:
|
||||
|
||||
<code-snippet name="Tailwind v4 Import Tailwind Diff" lang="diff">
|
||||
- @tailwind base;
|
||||
- @tailwind components;
|
||||
- @tailwind utilities;
|
||||
+ @import "tailwindcss";
|
||||
</code-snippet>
|
||||
|
||||
### Replaced Utilities
|
||||
- Tailwind v4 removed deprecated utilities. Do not use the deprecated option; use the replacement.
|
||||
- Opacity values are still numeric.
|
||||
|
||||
| Deprecated | Replacement |
|
||||
|------------+--------------|
|
||||
| bg-opacity-* | bg-black/* |
|
||||
| text-opacity-* | text-black/* |
|
||||
| border-opacity-* | border-black/* |
|
||||
| divide-opacity-* | divide-black/* |
|
||||
| ring-opacity-* | ring-black/* |
|
||||
| placeholder-opacity-* | placeholder-black/* |
|
||||
| flex-shrink-* | shrink-* |
|
||||
| flex-grow-* | grow-* |
|
||||
| overflow-ellipsis | text-ellipsis |
|
||||
| decoration-slice | box-decoration-slice |
|
||||
| decoration-clone | box-decoration-clone |
|
||||
</laravel-boost-guidelines>
|
||||
|
||||
## Active Technologies
|
||||
|
||||
357
GEMINI.md
357
GEMINI.md
@ -229,7 +229,6 @@ ## Reference Materials
|
||||
=== .ai/filament-v5-blueprint rules ===
|
||||
|
||||
## Source of Truth
|
||||
|
||||
If any Filament behavior is uncertain, lookup the exact section in:
|
||||
- docs/research/filament-v5-notes.md
|
||||
and prefer that over guesses.
|
||||
@ -239,7 +238,6 @@ # SECTION B — FILAMENT V5 BLUEPRINT (EXECUTABLE RULES)
|
||||
# Filament Blueprint (v5)
|
||||
|
||||
## 1) Non-negotiables
|
||||
|
||||
- Filament v5 requires Livewire v4.0+.
|
||||
- Laravel 11+: register panel providers in `bootstrap/providers.php` (never `bootstrap/app.php`).
|
||||
- Global search hard rule: If a Resource should appear in Global Search, it must have an Edit or View page; otherwise it will return no results.
|
||||
@ -255,7 +253,6 @@ ## 1) Non-negotiables
|
||||
- https://filamentphp.com/docs/5.x/styling/css-hooks
|
||||
|
||||
## 2) Directory & naming conventions
|
||||
|
||||
- Default to Filament discovery conventions for Resources/Pages/Widgets unless you adopt modular architecture.
|
||||
- Clusters: directory layout is recommended, not mandatory; functional behavior depends on `$cluster`.
|
||||
|
||||
@ -264,7 +261,6 @@ ## 2) Directory & naming conventions
|
||||
- https://filamentphp.com/docs/5.x/advanced/modular-architecture
|
||||
|
||||
## 3) Panel setup defaults
|
||||
|
||||
- Default to a single `/admin` panel unless multiple audiences/configs demand multiple panels.
|
||||
- Verify provider registration (Laravel 11+: `bootstrap/providers.php`) when adding a panel.
|
||||
- Use `path()` carefully; treat `path('')` as a high-risk change requiring route conflict review.
|
||||
@ -278,7 +274,6 @@ ## 3) Panel setup defaults
|
||||
- https://filamentphp.com/docs/5.x/advanced/assets
|
||||
|
||||
## 4) Navigation & information architecture
|
||||
|
||||
- Use nav groups + sort order intentionally; apply conditional visibility for clarity, but enforce authorization separately.
|
||||
- Use clusters to introduce hierarchy and sub-navigation when sidebar complexity grows.
|
||||
- Treat cluster code structure as a recommendation (organizational benefit), not a required rule.
|
||||
@ -292,7 +287,6 @@ ## 4) Navigation & information architecture
|
||||
- https://filamentphp.com/docs/5.x/navigation/user-menu
|
||||
|
||||
## 5) Resource patterns
|
||||
|
||||
- Default to Resources for CRUD; use custom pages for non-CRUD tools/workflows.
|
||||
- Global search:
|
||||
- If a resource is intended for global search: ensure Edit/View page exists.
|
||||
@ -305,7 +299,6 @@ ## 5) Resource patterns
|
||||
- https://filamentphp.com/docs/5.x/resources/global-search
|
||||
|
||||
## 6) Page lifecycle & query rules
|
||||
|
||||
- Treat relationship-backed rendering in aggregate contexts (global search details, list summaries) as requiring eager loading.
|
||||
- Prefer render hooks for layout injection; avoid publishing internal views.
|
||||
|
||||
@ -314,7 +307,6 @@ ## 6) Page lifecycle & query rules
|
||||
- https://filamentphp.com/docs/5.x/advanced/render-hooks
|
||||
|
||||
## 7) Infolists vs RelationManagers (decision tree)
|
||||
|
||||
- Interactive CRUD / attach / detach under owner record → RelationManager.
|
||||
- Pick existing related record(s) inside owner form → Select / CheckboxList relationship fields.
|
||||
- Inline CRUD inside owner form → Repeater.
|
||||
@ -325,7 +317,6 @@ ## 7) Infolists vs RelationManagers (decision tree)
|
||||
- https://filamentphp.com/docs/5.x/infolists/overview
|
||||
|
||||
## 8) Form patterns (validation, reactivity, state)
|
||||
|
||||
- Default: minimize server-driven reactivity; only use it when schema/visibility/requirements must change server-side.
|
||||
- Prefer “on blur” semantics for chatty inputs when using reactive behavior (per docs patterns).
|
||||
- Custom field views must obey state binding modifiers.
|
||||
@ -335,7 +326,6 @@ ## 8) Form patterns (validation, reactivity, state)
|
||||
- https://filamentphp.com/docs/5.x/forms/custom-fields
|
||||
|
||||
## 9) Table & action patterns
|
||||
|
||||
- Tables: always define a meaningful empty state (and empty-state actions where appropriate).
|
||||
- Actions:
|
||||
- Execution actions use `->action(...)`.
|
||||
@ -348,7 +338,6 @@ ## 9) Table & action patterns
|
||||
- https://filamentphp.com/docs/5.x/actions/modals
|
||||
|
||||
## 10) Authorization & security
|
||||
|
||||
- Enforce panel access in non-local environments as documented.
|
||||
- UI visibility is not security; enforce policies/access checks in addition to hiding UI.
|
||||
- Bulk operations: explicitly decide between “Any” policy methods vs per-record authorization.
|
||||
@ -358,7 +347,6 @@ ## 10) Authorization & security
|
||||
- https://filamentphp.com/docs/5.x/resources/deleting-records
|
||||
|
||||
## 11) Notifications & UX feedback
|
||||
|
||||
- Default to explicit success/error notifications for user-triggered mutations that aren’t instantly obvious.
|
||||
- Treat polling as a cost; set intervals intentionally where polling is used.
|
||||
|
||||
@ -367,7 +355,6 @@ ## 11) Notifications & UX feedback
|
||||
- https://filamentphp.com/docs/5.x/widgets/stats-overview
|
||||
|
||||
## 12) Performance defaults
|
||||
|
||||
- Heavy assets: prefer on-demand loading (`loadedOnRequest()` + `x-load-css` / `x-load-js`) for heavy dependencies.
|
||||
- Styling overrides use CSS hook classes; layout injection uses render hooks; avoid view publishing.
|
||||
|
||||
@ -377,7 +364,6 @@ ## 12) Performance defaults
|
||||
- https://filamentphp.com/docs/5.x/advanced/render-hooks
|
||||
|
||||
## 13) Testing requirements
|
||||
|
||||
- Test pages/relation managers/widgets as Livewire components.
|
||||
- Test actions using Filament’s action testing guidance.
|
||||
- Do not mount non-Livewire classes in Livewire tests.
|
||||
@ -387,7 +373,6 @@ ## 13) Testing requirements
|
||||
- https://filamentphp.com/docs/5.x/testing/testing-actions
|
||||
|
||||
## 14) Forbidden patterns
|
||||
|
||||
- Mixing Filament v3/v4 APIs into v5 code.
|
||||
- Any mention of Livewire v3 for Filament v5.
|
||||
- Registering panel providers in `bootstrap/app.php` on Laravel 11+.
|
||||
@ -402,7 +387,6 @@ ## 14) Forbidden patterns
|
||||
- https://filamentphp.com/docs/5.x/advanced/assets
|
||||
|
||||
## 15) Agent output contract
|
||||
|
||||
For any implementation request, the agent must explicitly state:
|
||||
1) Livewire v4.0+ compliance.
|
||||
2) Provider registration location (Laravel 11+: `bootstrap/providers.php`).
|
||||
@ -423,7 +407,6 @@ ## 15) Agent output contract
|
||||
# SECTION C — AI REVIEW CHECKLIST (STRICT CHECKBOXES)
|
||||
|
||||
## Version Safety
|
||||
|
||||
- [ ] Filament v5 explicitly targets Livewire v4.0+ (no Livewire v3 references anywhere).
|
||||
- Source: https://filamentphp.com/docs/5.x/upgrade-guide — “Upgrading Livewire”
|
||||
- [ ] All references are Filament `/docs/5.x/` only (no v3/v4 docs, no legacy APIs).
|
||||
@ -431,7 +414,6 @@ ## Version Safety
|
||||
- Source: https://filamentphp.com/docs/5.x/upgrade-guide — “New requirements”
|
||||
|
||||
## Panel & Navigation
|
||||
|
||||
- [ ] Laravel 11+: panel providers are registered in `bootstrap/providers.php` (not `bootstrap/app.php`).
|
||||
- Source: https://filamentphp.com/docs/5.x/panel-configuration — “Creating a new panel”
|
||||
- [ ] Panel `path()` choices are intentional and do not conflict with existing routes (especially `path('')`).
|
||||
@ -446,7 +428,6 @@ ## Panel & Navigation
|
||||
- Source: https://filamentphp.com/docs/5.x/navigation/user-menu — “Introduction”
|
||||
|
||||
## Resource Structure
|
||||
|
||||
- [ ] `$recordTitleAttribute` is set for any resource intended for global search.
|
||||
- Source: https://filamentphp.com/docs/5.x/resources/overview — “Record titles”
|
||||
- [ ] Hard rule enforced: every globally searchable resource has an Edit or View page; otherwise global search is disabled for it.
|
||||
@ -455,21 +436,18 @@ ## Resource Structure
|
||||
- Source: https://filamentphp.com/docs/5.x/resources/global-search — “Adding extra details to global search results”
|
||||
|
||||
## Infolists & Relations
|
||||
|
||||
- [ ] Each relationship uses the correct tool (RelationManager vs Select/CheckboxList vs Repeater) based on required interaction.
|
||||
- Source: https://filamentphp.com/docs/5.x/resources/managing-relationships — “Choosing the right tool for the job”
|
||||
- [ ] RelationManagers remain lazy-loaded by default unless there’s an explicit UX justification.
|
||||
- Source: https://filamentphp.com/docs/5.x/resources/managing-relationships — “Disabling lazy loading”
|
||||
|
||||
## Forms
|
||||
|
||||
- [ ] Server-driven reactivity is minimal; chatty inputs do not trigger network requests unnecessarily.
|
||||
- Source: https://filamentphp.com/docs/5.x/forms/overview — “Reactive fields on blur”
|
||||
- [ ] Custom field views obey state binding modifiers (no hardcoded `wire:model` without modifiers).
|
||||
- Source: https://filamentphp.com/docs/5.x/forms/custom-fields — “Obeying state binding modifiers”
|
||||
|
||||
## Tables & Actions
|
||||
|
||||
- [ ] Tables define a meaningful empty state (and empty-state actions where appropriate).
|
||||
- Source: https://filamentphp.com/docs/5.x/tables/empty-state — “Adding empty state actions”
|
||||
- [ ] All destructive actions execute via `->action(...)` and include `->requiresConfirmation()`.
|
||||
@ -478,7 +456,6 @@ ## Tables & Actions
|
||||
- Source: https://filamentphp.com/docs/5.x/actions/modals — “Confirmation modals”
|
||||
|
||||
## Authorization & Security
|
||||
|
||||
- [ ] Panel access is enforced for non-local environments as documented.
|
||||
- Source: https://filamentphp.com/docs/5.x/users/overview — “Authorizing access to the panel”
|
||||
- [ ] UI visibility is not treated as authorization; policies/access checks still enforce boundaries.
|
||||
@ -486,28 +463,24 @@ ## Authorization & Security
|
||||
- Source: https://filamentphp.com/docs/5.x/resources/deleting-records — “Authorization”
|
||||
|
||||
## UX & Notifications
|
||||
|
||||
- [ ] User-triggered mutations provide explicit success/error notifications when outcomes aren’t instantly obvious.
|
||||
- Source: https://filamentphp.com/docs/5.x/notifications/overview — “Introduction”
|
||||
- [ ] Polling (widgets/notifications) is configured intentionally (interval set or disabled) to control load.
|
||||
- Source: https://filamentphp.com/docs/5.x/widgets/stats-overview — “Live updating stats (polling)”
|
||||
|
||||
## Performance
|
||||
|
||||
- [ ] Heavy frontend assets are loaded on-demand using `loadedOnRequest()` + `x-load-css` / `x-load-js` where appropriate.
|
||||
- Source: https://filamentphp.com/docs/5.x/advanced/assets — “Lazy loading CSS” / “Lazy loading JavaScript”
|
||||
- [ ] Styling overrides use CSS hook classes discovered via DevTools (no brittle selectors by default).
|
||||
- Source: https://filamentphp.com/docs/5.x/styling/css-hooks — “Discovering hook classes”
|
||||
|
||||
## Testing
|
||||
|
||||
- [ ] Livewire tests mount Filament pages/relation managers/widgets (Livewire components), not static resource classes.
|
||||
- Source: https://filamentphp.com/docs/5.x/testing/overview — “What is a Livewire component when using Filament?”
|
||||
- [ ] Actions that mutate data are covered using Filament’s action testing guidance.
|
||||
- Source: https://filamentphp.com/docs/5.x/testing/testing-actions — “Testing actions”
|
||||
|
||||
## Deployment / Ops
|
||||
|
||||
- [ ] `php artisan filament:assets` is included in the deployment process when using registered assets.
|
||||
- Source: https://filamentphp.com/docs/5.x/advanced/assets — “The FilamentAsset facade”
|
||||
|
||||
@ -515,13 +488,12 @@ ## Deployment / Ops
|
||||
|
||||
# Laravel Boost Guidelines
|
||||
|
||||
The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to ensure the best experience when building Laravel applications.
|
||||
The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to enhance the user's satisfaction building Laravel applications.
|
||||
|
||||
## Foundational Context
|
||||
|
||||
This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.
|
||||
|
||||
- php - 8.4.1
|
||||
- php - 8.4.15
|
||||
- filament/filament (FILAMENT) - v5
|
||||
- laravel/framework (LARAVEL) - v12
|
||||
- laravel/prompts (PROMPTS) - v0
|
||||
@ -534,73 +506,56 @@ ## Foundational Context
|
||||
- phpunit/phpunit (PHPUNIT) - v12
|
||||
- tailwindcss (TAILWINDCSS) - v4
|
||||
|
||||
## Skills Activation
|
||||
|
||||
This project has domain-specific skills available. You MUST activate the relevant skill whenever you work in that domain—don't wait until you're stuck.
|
||||
|
||||
- `pest-testing` — Tests applications using the Pest 4 PHP framework. Activates when writing tests, creating unit or feature tests, adding assertions, testing Livewire components, browser testing, debugging test failures, working with datasets or mocking; or when the user mentions test, spec, TDD, expects, assertion, coverage, or needs to verify functionality works.
|
||||
- `tailwindcss-development` — Styles applications using Tailwind CSS v4 utilities. Activates when adding styles, restyling components, working with gradients, spacing, layout, flex, grid, responsive design, dark mode, colors, typography, or borders; or when the user mentions CSS, styling, classes, Tailwind, restyle, hero section, cards, buttons, or any visual/UI changes.
|
||||
|
||||
## Conventions
|
||||
|
||||
- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming.
|
||||
- Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`.
|
||||
- Check for existing components to reuse before writing a new one.
|
||||
|
||||
## Verification Scripts
|
||||
|
||||
- Do not create verification scripts or tinker when tests cover that functionality and prove they work. Unit and feature tests are more important.
|
||||
- Do not create verification scripts or tinker when tests cover that functionality and prove it works. Unit and feature tests are more important.
|
||||
|
||||
## Application Structure & Architecture
|
||||
|
||||
- Stick to existing directory structure; don't create new base folders without approval.
|
||||
- Do not change the application's dependencies without approval.
|
||||
|
||||
## Frontend Bundling
|
||||
|
||||
- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `vendor/bin/sail npm run build`, `vendor/bin/sail npm run dev`, or `vendor/bin/sail composer run dev`. Ask them.
|
||||
|
||||
## Documentation Files
|
||||
|
||||
- You must only create documentation files if explicitly requested by the user.
|
||||
|
||||
## Replies
|
||||
|
||||
- Be concise in your explanations - focus on what's important rather than explaining obvious details.
|
||||
|
||||
## Documentation Files
|
||||
- You must only create documentation files if explicitly requested by the user.
|
||||
|
||||
=== boost rules ===
|
||||
|
||||
# Laravel Boost
|
||||
|
||||
## Laravel Boost
|
||||
- Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them.
|
||||
|
||||
## Artisan
|
||||
|
||||
- Use the `list-artisan-commands` tool when you need to call an Artisan command to double-check the available parameters.
|
||||
|
||||
## URLs
|
||||
|
||||
- Whenever you share a project URL with the user, you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain/IP, and port.
|
||||
|
||||
## Tinker / Debugging
|
||||
|
||||
- You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly.
|
||||
- Use the `database-query` tool when you only need to read from the database.
|
||||
- Use the `database-schema` tool to inspect table structure before writing migrations or models.
|
||||
|
||||
## Reading Browser Logs With the `browser-logs` Tool
|
||||
|
||||
- You can read browser logs, errors, and exceptions using the `browser-logs` tool from Boost.
|
||||
- Only recent browser logs will be useful - ignore old logs.
|
||||
|
||||
## Searching Documentation (Critically Important)
|
||||
|
||||
- Boost comes with a powerful `search-docs` tool you should use before trying other approaches when working with Laravel or Laravel ecosystem packages. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages.
|
||||
- Boost comes with a powerful `search-docs` tool you should use before any other approaches when dealing with Laravel or Laravel ecosystem packages. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages.
|
||||
- The `search-docs` tool is perfect for all Laravel-related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc.
|
||||
- You must use this tool to search for Laravel ecosystem documentation before falling back to other approaches.
|
||||
- Search the documentation before making code changes to ensure we are taking the correct approach.
|
||||
- Use multiple, broad, simple, topic-based queries at once. For example: `['rate limiting', 'routing rate limiting', 'routing']`. The most relevant results will be returned first.
|
||||
- Use multiple, broad, simple, topic-based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`.
|
||||
- Do not add package names to queries; package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`.
|
||||
|
||||
### Available Search Syntax
|
||||
- You can and should pass multiple queries at once. The most relevant results will be returned first.
|
||||
|
||||
1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'.
|
||||
2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit".
|
||||
@ -610,44 +565,38 @@ ### Available Search Syntax
|
||||
|
||||
=== php rules ===
|
||||
|
||||
# PHP
|
||||
## PHP
|
||||
|
||||
- Always use curly braces for control structures, even for single-line bodies.
|
||||
|
||||
## Constructors
|
||||
- Always use curly braces for control structures, even if it has one line.
|
||||
|
||||
### Constructors
|
||||
- Use PHP 8 constructor property promotion in `__construct()`.
|
||||
- `public function __construct(public GitHub $github) { }`
|
||||
- <code-snippet>public function __construct(public GitHub $github) { }</code-snippet>
|
||||
- Do not allow empty `__construct()` methods with zero parameters unless the constructor is private.
|
||||
|
||||
## Type Declarations
|
||||
|
||||
### Type Declarations
|
||||
- Always use explicit return type declarations for methods and functions.
|
||||
- Use appropriate PHP type hints for method parameters.
|
||||
|
||||
<!-- Explicit Return Types and Method Params -->
|
||||
```php
|
||||
<code-snippet name="Explicit Return Types and Method Params" lang="php">
|
||||
protected function isAccessible(User $user, ?string $path = null): bool
|
||||
{
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
## Enums
|
||||
|
||||
- Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`.
|
||||
</code-snippet>
|
||||
|
||||
## Comments
|
||||
|
||||
- Prefer PHPDoc blocks over inline comments. Never use comments within the code itself unless the logic is exceptionally complex.
|
||||
- Prefer PHPDoc blocks over inline comments. Never use comments within the code itself unless there is something very complex going on.
|
||||
|
||||
## PHPDoc Blocks
|
||||
- Add useful array shape type definitions for arrays when appropriate.
|
||||
|
||||
- Add useful array shape type definitions when appropriate.
|
||||
## Enums
|
||||
- Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`.
|
||||
|
||||
=== sail rules ===
|
||||
|
||||
# Laravel Sail
|
||||
## Laravel Sail
|
||||
|
||||
- This project runs inside Laravel Sail's Docker containers. You MUST execute all commands through Sail.
|
||||
- Start services using `vendor/bin/sail up -d` and stop them with `vendor/bin/sail stop`.
|
||||
@ -661,21 +610,20 @@ # Laravel Sail
|
||||
|
||||
=== tests rules ===
|
||||
|
||||
# Test Enforcement
|
||||
## Test Enforcement
|
||||
|
||||
- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass.
|
||||
- Run the minimum number of tests needed to ensure code quality and speed. Use `vendor/bin/sail artisan test --compact` with a specific filename or filter.
|
||||
|
||||
=== laravel/core rules ===
|
||||
|
||||
# Do Things the Laravel Way
|
||||
## Do Things the Laravel Way
|
||||
|
||||
- Use `vendor/bin/sail artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool.
|
||||
- If you're creating a generic PHP class, use `vendor/bin/sail artisan make:class`.
|
||||
- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.
|
||||
|
||||
## Database
|
||||
|
||||
### Database
|
||||
- Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins.
|
||||
- Use Eloquent models and relationships before suggesting raw database queries.
|
||||
- Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them.
|
||||
@ -683,53 +631,43 @@ ## Database
|
||||
- Use Laravel's query builder for very complex database operations.
|
||||
|
||||
### Model Creation
|
||||
|
||||
- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `vendor/bin/sail artisan make:model`.
|
||||
|
||||
### APIs & Eloquent Resources
|
||||
|
||||
- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention.
|
||||
|
||||
## Controllers & Validation
|
||||
|
||||
### Controllers & Validation
|
||||
- Always create Form Request classes for validation rather than inline validation in controllers. Include both validation rules and custom error messages.
|
||||
- Check sibling Form Requests to see if the application uses array or string based validation rules.
|
||||
|
||||
## Authentication & Authorization
|
||||
|
||||
- Use Laravel's built-in authentication and authorization features (gates, policies, Sanctum, etc.).
|
||||
|
||||
## URL Generation
|
||||
|
||||
- When generating links to other pages, prefer named routes and the `route()` function.
|
||||
|
||||
## Queues
|
||||
|
||||
### Queues
|
||||
- Use queued jobs for time-consuming operations with the `ShouldQueue` interface.
|
||||
|
||||
## Configuration
|
||||
### Authentication & Authorization
|
||||
- Use Laravel's built-in authentication and authorization features (gates, policies, Sanctum, etc.).
|
||||
|
||||
### URL Generation
|
||||
- When generating links to other pages, prefer named routes and the `route()` function.
|
||||
|
||||
### Configuration
|
||||
- Use environment variables only in configuration files - never use the `env()` function directly outside of config files. Always use `config('app.name')`, not `env('APP_NAME')`.
|
||||
|
||||
## Testing
|
||||
|
||||
### Testing
|
||||
- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.
|
||||
- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.
|
||||
- When creating tests, make use of `vendor/bin/sail artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.
|
||||
|
||||
## Vite Error
|
||||
|
||||
### Vite Error
|
||||
- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `vendor/bin/sail npm run build` or ask the user to run `vendor/bin/sail npm run dev` or `vendor/bin/sail composer run dev`.
|
||||
|
||||
=== laravel/v12 rules ===
|
||||
|
||||
# Laravel 12
|
||||
## Laravel 12
|
||||
|
||||
- CRITICAL: ALWAYS use `search-docs` tool for version-specific Laravel documentation and updated code examples.
|
||||
- Use the `search-docs` tool to get version-specific documentation.
|
||||
- Since Laravel 11, Laravel has a new streamlined file structure which this project uses.
|
||||
|
||||
## Laravel 12 Structure
|
||||
|
||||
### Laravel 12 Structure
|
||||
- In Laravel 12, middleware are no longer registered in `app/Http/Kernel.php`.
|
||||
- Middleware are configured declaratively in `bootstrap/app.php` using `Application::configure()->withMiddleware()`.
|
||||
- `bootstrap/app.php` is the file to register middleware, exceptions, and routing files.
|
||||
@ -737,39 +675,224 @@ ## Laravel 12 Structure
|
||||
- The `app\Console\Kernel.php` file no longer exists; use `bootstrap/app.php` or `routes/console.php` for console configuration.
|
||||
- Console commands in `app/Console/Commands/` are automatically available and do not require manual registration.
|
||||
|
||||
## Database
|
||||
|
||||
### Database
|
||||
- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost.
|
||||
- Laravel 12 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`.
|
||||
|
||||
### Models
|
||||
|
||||
- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models.
|
||||
|
||||
=== livewire/core rules ===
|
||||
|
||||
## Livewire
|
||||
|
||||
- Use the `search-docs` tool to find exact version-specific documentation for how to write Livewire and Livewire tests.
|
||||
- Use the `vendor/bin/sail artisan make:livewire [Posts\CreatePost]` Artisan command to create new components.
|
||||
- State should live on the server, with the UI reflecting it.
|
||||
- All Livewire requests hit the Laravel backend; they're like regular HTTP requests. Always validate form data and run authorization checks in Livewire actions.
|
||||
|
||||
## Livewire Best Practices
|
||||
- Livewire components require a single root element.
|
||||
- Use `wire:loading` and `wire:dirty` for delightful loading states.
|
||||
- Add `wire:key` in loops:
|
||||
|
||||
```blade
|
||||
@foreach ($items as $item)
|
||||
<div wire:key="item-{{ $item->id }}">
|
||||
{{ $item->name }}
|
||||
</div>
|
||||
@endforeach
|
||||
```
|
||||
|
||||
- Prefer lifecycle hooks like `mount()`, `updatedFoo()` for initialization and reactive side effects:
|
||||
|
||||
<code-snippet name="Lifecycle Hook Examples" lang="php">
|
||||
public function mount(User $user) { $this->user = $user; }
|
||||
public function updatedSearch() { $this->resetPage(); }
|
||||
</code-snippet>
|
||||
|
||||
## Testing Livewire
|
||||
|
||||
<code-snippet name="Example Livewire Component Test" lang="php">
|
||||
Livewire::test(Counter::class)
|
||||
->assertSet('count', 0)
|
||||
->call('increment')
|
||||
->assertSet('count', 1)
|
||||
->assertSee(1)
|
||||
->assertStatus(200);
|
||||
</code-snippet>
|
||||
|
||||
<code-snippet name="Testing Livewire Component Exists on Page" lang="php">
|
||||
$this->get('/posts/create')
|
||||
->assertSeeLivewire(CreatePost::class);
|
||||
</code-snippet>
|
||||
|
||||
=== pint/core rules ===
|
||||
|
||||
# Laravel Pint Code Formatter
|
||||
## Laravel Pint Code Formatter
|
||||
|
||||
- You must run `vendor/bin/sail bin pint --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style.
|
||||
- Do not run `vendor/bin/sail bin pint --test --format agent`, simply run `vendor/bin/sail bin pint --format agent` to fix any formatting issues.
|
||||
- You must run `vendor/bin/sail bin pint --dirty` before finalizing changes to ensure your code matches the project's expected style.
|
||||
- Do not run `vendor/bin/sail bin pint --test`, simply run `vendor/bin/sail bin pint` to fix any formatting issues.
|
||||
|
||||
=== pest/core rules ===
|
||||
|
||||
## Pest
|
||||
### Testing
|
||||
- If you need to verify a feature is working, write or update a Unit / Feature test.
|
||||
|
||||
- This project uses Pest for testing. Create tests: `vendor/bin/sail artisan make:test --pest {name}`.
|
||||
- Run tests: `vendor/bin/sail artisan test --compact` or filter: `vendor/bin/sail artisan test --compact --filter=testName`.
|
||||
- Do NOT delete tests without approval.
|
||||
- CRITICAL: ALWAYS use `search-docs` tool for version-specific Pest documentation and updated code examples.
|
||||
- IMPORTANT: Activate `pest-testing` every time you're working with a Pest or testing-related task.
|
||||
### Pest Tests
|
||||
- All tests must be written using Pest. Use `vendor/bin/sail artisan make:test --pest {name}`.
|
||||
- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files - these are core to the application.
|
||||
- Tests should test all of the happy paths, failure paths, and weird paths.
|
||||
- Tests live in the `tests/Feature` and `tests/Unit` directories.
|
||||
- Pest tests look and behave like this:
|
||||
<code-snippet name="Basic Pest Test Example" lang="php">
|
||||
it('is true', function () {
|
||||
expect(true)->toBeTrue();
|
||||
});
|
||||
</code-snippet>
|
||||
|
||||
### Running Tests
|
||||
- Run the minimal number of tests using an appropriate filter before finalizing code edits.
|
||||
- To run all tests: `vendor/bin/sail artisan test --compact`.
|
||||
- To run all tests in a file: `vendor/bin/sail artisan test --compact tests/Feature/ExampleTest.php`.
|
||||
- To filter on a particular test name: `vendor/bin/sail artisan test --compact --filter=testName` (recommended after making a change to a related file).
|
||||
- When the tests relating to your changes are passing, ask the user if they would like to run the entire test suite to ensure everything is still passing.
|
||||
|
||||
### Pest Assertions
|
||||
- When asserting status codes on a response, use the specific method like `assertForbidden` and `assertNotFound` instead of using `assertStatus(403)` or similar, e.g.:
|
||||
<code-snippet name="Pest Example Asserting postJson Response" lang="php">
|
||||
it('returns all', function () {
|
||||
$response = $this->postJson('/api/docs', []);
|
||||
|
||||
$response->assertSuccessful();
|
||||
});
|
||||
</code-snippet>
|
||||
|
||||
### Mocking
|
||||
- Mocking can be very helpful when appropriate.
|
||||
- When mocking, you can use the `Pest\Laravel\mock` Pest function, but always import it via `use function Pest\Laravel\mock;` before using it. Alternatively, you can use `$this->mock()` if existing tests do.
|
||||
- You can also create partial mocks using the same import or self method.
|
||||
|
||||
### Datasets
|
||||
- Use datasets in Pest to simplify tests that have a lot of duplicated data. This is often the case when testing validation rules, so consider this solution when writing tests for validation rules.
|
||||
|
||||
<code-snippet name="Pest Dataset Example" lang="php">
|
||||
it('has emails', function (string $email) {
|
||||
expect($email)->not->toBeEmpty();
|
||||
})->with([
|
||||
'james' => 'james@laravel.com',
|
||||
'taylor' => 'taylor@laravel.com',
|
||||
]);
|
||||
</code-snippet>
|
||||
|
||||
=== pest/v4 rules ===
|
||||
|
||||
## Pest 4
|
||||
|
||||
- Pest 4 is a huge upgrade to Pest and offers: browser testing, smoke testing, visual regression testing, test sharding, and faster type coverage.
|
||||
- Browser testing is incredibly powerful and useful for this project.
|
||||
- Browser tests should live in `tests/Browser/`.
|
||||
- Use the `search-docs` tool for detailed guidance on utilizing these features.
|
||||
|
||||
### Browser Testing
|
||||
- You can use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories within Pest 4 browser tests, as well as `RefreshDatabase` (when needed) to ensure a clean state for each test.
|
||||
- Interact with the page (click, type, scroll, select, submit, drag-and-drop, touch gestures, etc.) when appropriate to complete the test.
|
||||
- If requested, test on multiple browsers (Chrome, Firefox, Safari).
|
||||
- If requested, test on different devices and viewports (like iPhone 14 Pro, tablets, or custom breakpoints).
|
||||
- Switch color schemes (light/dark mode) when appropriate.
|
||||
- Take screenshots or pause tests for debugging when appropriate.
|
||||
|
||||
### Example Tests
|
||||
|
||||
<code-snippet name="Pest Browser Test Example" lang="php">
|
||||
it('may reset the password', function () {
|
||||
Notification::fake();
|
||||
|
||||
$this->actingAs(User::factory()->create());
|
||||
|
||||
$page = visit('/sign-in'); // Visit on a real browser...
|
||||
|
||||
$page->assertSee('Sign In')
|
||||
->assertNoJavascriptErrors() // or ->assertNoConsoleLogs()
|
||||
->click('Forgot Password?')
|
||||
->fill('email', 'nuno@laravel.com')
|
||||
->click('Send Reset Link')
|
||||
->assertSee('We have emailed your password reset link!')
|
||||
|
||||
Notification::assertSent(ResetPassword::class);
|
||||
});
|
||||
</code-snippet>
|
||||
|
||||
<code-snippet name="Pest Smoke Testing Example" lang="php">
|
||||
$pages = visit(['/', '/about', '/contact']);
|
||||
|
||||
$pages->assertNoJavascriptErrors()->assertNoConsoleLogs();
|
||||
</code-snippet>
|
||||
|
||||
=== tailwindcss/core rules ===
|
||||
|
||||
# Tailwind CSS
|
||||
## Tailwind CSS
|
||||
|
||||
- Always use existing Tailwind conventions; check project patterns before adding new ones.
|
||||
- IMPORTANT: Always use `search-docs` tool for version-specific Tailwind CSS documentation and updated code examples. Never rely on training data.
|
||||
- IMPORTANT: Activate `tailwindcss-development` every time you're working with a Tailwind CSS or styling-related task.
|
||||
- Use Tailwind CSS classes to style HTML; check and use existing Tailwind conventions within the project before writing your own.
|
||||
- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc.).
|
||||
- Think through class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child carefully to limit repetition, and group elements logically.
|
||||
- You can use the `search-docs` tool to get exact examples from the official documentation when needed.
|
||||
|
||||
### Spacing
|
||||
- When listing items, use gap utilities for spacing; don't use margins.
|
||||
|
||||
<code-snippet name="Valid Flex Gap Spacing Example" lang="html">
|
||||
<div class="flex gap-8">
|
||||
<div>Superior</div>
|
||||
<div>Michigan</div>
|
||||
<div>Erie</div>
|
||||
</div>
|
||||
</code-snippet>
|
||||
|
||||
### Dark Mode
|
||||
- If existing pages and components support dark mode, new pages and components must support dark mode in a similar way, typically using `dark:`.
|
||||
|
||||
=== tailwindcss/v4 rules ===
|
||||
|
||||
## Tailwind CSS 4
|
||||
|
||||
- Always use Tailwind CSS v4; do not use the deprecated utilities.
|
||||
- `corePlugins` is not supported in Tailwind v4.
|
||||
- In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed.
|
||||
|
||||
<code-snippet name="Extending Theme in CSS" lang="css">
|
||||
@theme {
|
||||
--color-brand: oklch(0.72 0.11 178);
|
||||
}
|
||||
</code-snippet>
|
||||
|
||||
- In Tailwind v4, you import Tailwind using a regular CSS `@import` statement, not using the `@tailwind` directives used in v3:
|
||||
|
||||
<code-snippet name="Tailwind v4 Import Tailwind Diff" lang="diff">
|
||||
- @tailwind base;
|
||||
- @tailwind components;
|
||||
- @tailwind utilities;
|
||||
+ @import "tailwindcss";
|
||||
</code-snippet>
|
||||
|
||||
### Replaced Utilities
|
||||
- Tailwind v4 removed deprecated utilities. Do not use the deprecated option; use the replacement.
|
||||
- Opacity values are still numeric.
|
||||
|
||||
| Deprecated | Replacement |
|
||||
|------------+--------------|
|
||||
| bg-opacity-* | bg-black/* |
|
||||
| text-opacity-* | text-black/* |
|
||||
| border-opacity-* | border-black/* |
|
||||
| divide-opacity-* | divide-black/* |
|
||||
| ring-opacity-* | ring-black/* |
|
||||
| placeholder-opacity-* | placeholder-black/* |
|
||||
| flex-shrink-* | shrink-* |
|
||||
| flex-grow-* | grow-* |
|
||||
| overflow-ellipsis | text-ellipsis |
|
||||
| decoration-slice | box-decoration-slice |
|
||||
| decoration-clone | box-decoration-clone |
|
||||
</laravel-boost-guidelines>
|
||||
|
||||
## Recent Changes
|
||||
|
||||
@ -3,7 +3,6 @@
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\Graph\GraphClientInterface;
|
||||
use App\Services\Graph\GraphContractRegistry;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class GraphContractCheck extends Command
|
||||
@ -12,7 +11,7 @@ class GraphContractCheck extends Command
|
||||
|
||||
protected $description = 'Validate Graph contract registry against live endpoints (lightweight probes)';
|
||||
|
||||
public function handle(GraphClientInterface $graph, GraphContractRegistry $registry): int
|
||||
public function handle(GraphClientInterface $graph): int
|
||||
{
|
||||
$contracts = config('graph_contracts.types', []);
|
||||
|
||||
@ -37,13 +36,11 @@ public function handle(GraphClientInterface $graph, GraphContractRegistry $regis
|
||||
continue;
|
||||
}
|
||||
|
||||
$queryInput = array_filter([
|
||||
$query = array_filter([
|
||||
'$top' => 1,
|
||||
'$select' => $select,
|
||||
'$expand' => $expand,
|
||||
], static fn ($value): bool => $value !== null && $value !== '' && $value !== []);
|
||||
|
||||
$query = $registry->sanitizeQuery($type, $queryInput)['query'];
|
||||
]);
|
||||
|
||||
$response = $graph->request('GET', $resource, [
|
||||
'query' => $query,
|
||||
|
||||
@ -1,77 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\ReviewPack;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class PruneReviewPacksCommand extends Command
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'tenantpilot:review-pack:prune {--hard-delete : Hard-delete expired packs past grace period}';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Expire review packs past retention and optionally hard-delete expired rows past grace period';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$expired = $this->expireReadyPacks();
|
||||
$hardDeleted = 0;
|
||||
|
||||
if ($this->option('hard-delete')) {
|
||||
$hardDeleted = $this->hardDeleteExpiredPacks();
|
||||
}
|
||||
|
||||
$this->info("{$expired} pack(s) expired, {$hardDeleted} pack(s) hard-deleted.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transition ready packs past retention to expired and delete their files.
|
||||
*/
|
||||
private function expireReadyPacks(): int
|
||||
{
|
||||
$packs = ReviewPack::query()
|
||||
->ready()
|
||||
->pastRetention()
|
||||
->get();
|
||||
|
||||
$disk = Storage::disk('exports');
|
||||
$count = 0;
|
||||
|
||||
foreach ($packs as $pack) {
|
||||
/** @var ReviewPack $pack */
|
||||
if ($pack->file_path && $disk->exists($pack->file_path)) {
|
||||
$disk->delete($pack->file_path);
|
||||
}
|
||||
|
||||
$pack->update(['status' => ReviewPack::STATUS_EXPIRED]);
|
||||
$count++;
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hard-delete expired packs that are past the grace period.
|
||||
*/
|
||||
private function hardDeleteExpiredPacks(): int
|
||||
{
|
||||
$graceDays = (int) config('tenantpilot.review_pack.hard_delete_grace_days', 30);
|
||||
|
||||
$cutoff = now()->subDays($graceDays);
|
||||
|
||||
return ReviewPack::query()
|
||||
->expired()
|
||||
->where('updated_at', '<', $cutoff)
|
||||
->delete();
|
||||
}
|
||||
}
|
||||
@ -1,42 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\StoredReport;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class PruneStoredReportsCommand extends Command
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'stored-reports:prune {--days= : Number of days to retain reports}';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Delete stored reports older than the retention period';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$days = (int) ($this->option('days') ?: config('tenantpilot.stored_reports.retention_days', 90));
|
||||
|
||||
if ($days < 1) {
|
||||
$this->error('Retention days must be at least 1.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$cutoff = now()->subDays($days);
|
||||
|
||||
$deleted = StoredReport::query()
|
||||
->where('created_at', '<', $cutoff)
|
||||
->delete();
|
||||
|
||||
$this->info("Deleted {$deleted} stored report(s) older than {$days} days.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -1,120 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Services\Runbooks\FindingsLifecycleBackfillRunbookService;
|
||||
use App\Services\Runbooks\FindingsLifecycleBackfillScope;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class TenantpilotBackfillFindingLifecycle extends Command
|
||||
{
|
||||
protected $signature = 'tenantpilot:findings:backfill-lifecycle
|
||||
{--tenant=* : Limit to tenant_id/external_id}';
|
||||
|
||||
protected $description = 'Queue tenant-scoped findings lifecycle backfill jobs idempotently.';
|
||||
|
||||
public function handle(FindingsLifecycleBackfillRunbookService $runbookService): int
|
||||
{
|
||||
$tenantIdentifiers = array_values(array_filter((array) $this->option('tenant')));
|
||||
|
||||
if ($tenantIdentifiers === []) {
|
||||
$this->error('Provide one or more tenants via --tenant={id|external_id}.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$tenants = $this->resolveTenants($tenantIdentifiers);
|
||||
|
||||
if ($tenants->isEmpty()) {
|
||||
$this->info('No tenants matched the provided identifiers.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$queued = 0;
|
||||
$skipped = 0;
|
||||
$nothingToDo = 0;
|
||||
|
||||
foreach ($tenants as $tenant) {
|
||||
if (! $tenant instanceof Tenant) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$run = $runbookService->start(
|
||||
scope: FindingsLifecycleBackfillScope::singleTenant((int) $tenant->getKey()),
|
||||
initiator: null,
|
||||
reason: null,
|
||||
source: 'cli',
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
$errors = $e->errors();
|
||||
|
||||
if (isset($errors['preflight.affected_count'])) {
|
||||
$nothingToDo++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->error(sprintf(
|
||||
'Backfill blocked for tenant %d: %s',
|
||||
(int) $tenant->getKey(),
|
||||
$e->getMessage(),
|
||||
));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if (! $run->wasRecentlyCreated) {
|
||||
$skipped++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$queued++;
|
||||
}
|
||||
|
||||
$this->info(sprintf(
|
||||
'Queued %d backfill run(s), skipped %d duplicate run(s), nothing to do %d.',
|
||||
$queued,
|
||||
$skipped,
|
||||
$nothingToDo,
|
||||
));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $tenantIdentifiers
|
||||
* @return \Illuminate\Support\Collection<int, Tenant>
|
||||
*/
|
||||
private function resolveTenants(array $tenantIdentifiers)
|
||||
{
|
||||
$tenantIds = [];
|
||||
|
||||
foreach ($tenantIdentifiers as $identifier) {
|
||||
$tenant = Tenant::query()
|
||||
->forTenant($identifier)
|
||||
->first();
|
||||
|
||||
if ($tenant instanceof Tenant) {
|
||||
$tenantIds[] = (int) $tenant->getKey();
|
||||
}
|
||||
}
|
||||
|
||||
$tenantIds = array_values(array_unique($tenantIds));
|
||||
|
||||
if ($tenantIds === []) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
return Tenant::query()
|
||||
->whereIn('id', $tenantIds)
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
}
|
||||
@ -1,106 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Jobs\Alerts\DeliverAlertsJob;
|
||||
use App\Jobs\Alerts\EvaluateAlertsJob;
|
||||
use App\Models\Workspace;
|
||||
use App\Services\OperationRunService;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class TenantpilotDispatchAlerts extends Command
|
||||
{
|
||||
protected $signature = 'tenantpilot:alerts:dispatch {--workspace=* : Limit dispatch to one or more workspace IDs}';
|
||||
|
||||
protected $description = 'Queue workspace-scoped alert evaluation and delivery jobs idempotently.';
|
||||
|
||||
public function handle(OperationRunService $operationRuns): int
|
||||
{
|
||||
if (! (bool) config('tenantpilot.alerts.enabled', true)) {
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$workspaceFilter = array_values(array_filter(array_map(
|
||||
static fn (mixed $value): int => (int) $value,
|
||||
(array) $this->option('workspace'),
|
||||
)));
|
||||
|
||||
$workspaces = $this->resolveWorkspaces($workspaceFilter);
|
||||
|
||||
$slotKey = CarbonImmutable::now('UTC')->format('YmdHi').'Z';
|
||||
|
||||
$queuedEvaluate = 0;
|
||||
$queuedDeliver = 0;
|
||||
$skippedEvaluate = 0;
|
||||
$skippedDeliver = 0;
|
||||
|
||||
foreach ($workspaces as $workspace) {
|
||||
$evaluateRun = $operationRuns->ensureWorkspaceRunWithIdentity(
|
||||
workspace: $workspace,
|
||||
type: 'alerts.evaluate',
|
||||
identityInputs: ['slot_key' => $slotKey],
|
||||
context: [
|
||||
'trigger' => 'scheduled_dispatch',
|
||||
'slot_key' => $slotKey,
|
||||
],
|
||||
initiator: null,
|
||||
);
|
||||
|
||||
if ($evaluateRun->wasRecentlyCreated) {
|
||||
EvaluateAlertsJob::dispatch((int) $workspace->getKey(), (int) $evaluateRun->getKey());
|
||||
$queuedEvaluate++;
|
||||
} else {
|
||||
$skippedEvaluate++;
|
||||
}
|
||||
|
||||
$deliverRun = $operationRuns->ensureWorkspaceRunWithIdentity(
|
||||
workspace: $workspace,
|
||||
type: 'alerts.deliver',
|
||||
identityInputs: ['slot_key' => $slotKey],
|
||||
context: [
|
||||
'trigger' => 'scheduled_dispatch',
|
||||
'slot_key' => $slotKey,
|
||||
],
|
||||
initiator: null,
|
||||
);
|
||||
|
||||
if ($deliverRun->wasRecentlyCreated) {
|
||||
DeliverAlertsJob::dispatch((int) $workspace->getKey(), (int) $deliverRun->getKey());
|
||||
$queuedDeliver++;
|
||||
} else {
|
||||
$skippedDeliver++;
|
||||
}
|
||||
}
|
||||
|
||||
$this->info(sprintf(
|
||||
'Alert dispatch scanned %d workspace(s): evaluate queued=%d skipped=%d, deliver queued=%d skipped=%d.',
|
||||
$workspaces->count(),
|
||||
$queuedEvaluate,
|
||||
$skippedEvaluate,
|
||||
$queuedDeliver,
|
||||
$skippedDeliver,
|
||||
));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, int> $workspaceIds
|
||||
* @return Collection<int, Workspace>
|
||||
*/
|
||||
private function resolveWorkspaces(array $workspaceIds): Collection
|
||||
{
|
||||
return Workspace::query()
|
||||
->when(
|
||||
$workspaceIds !== [],
|
||||
fn ($query) => $query->whereIn('id', $workspaceIds),
|
||||
fn ($query) => $query->whereHas('tenants'),
|
||||
)
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
}
|
||||
@ -1,51 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\Runbooks\FindingsLifecycleBackfillRunbookService;
|
||||
use App\Services\Runbooks\FindingsLifecycleBackfillScope;
|
||||
use App\Services\Runbooks\RunbookReason;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class TenantpilotRunDeployRunbooks extends Command
|
||||
{
|
||||
protected $signature = 'tenantpilot:run-deploy-runbooks';
|
||||
|
||||
protected $description = 'Run deploy-time runbooks idempotently.';
|
||||
|
||||
public function handle(FindingsLifecycleBackfillRunbookService $runbookService): int
|
||||
{
|
||||
try {
|
||||
$runbookService->start(
|
||||
scope: FindingsLifecycleBackfillScope::allTenants(),
|
||||
initiator: null,
|
||||
reason: new RunbookReason(
|
||||
reasonCode: RunbookReason::CODE_DATA_REPAIR,
|
||||
reasonText: 'Deploy hook automated runbooks',
|
||||
),
|
||||
source: 'deploy_hook',
|
||||
);
|
||||
|
||||
$this->info('Deploy runbooks started (if needed).');
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (ValidationException $e) {
|
||||
$errors = $e->errors();
|
||||
|
||||
$skippable = isset($errors['preflight.affected_count']) || isset($errors['scope']);
|
||||
|
||||
if ($skippable) {
|
||||
$this->info('Deploy runbooks skipped (nothing to do or already running).');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$this->error('Deploy runbooks blocked by validation errors.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,23 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Contracts\Hardening;
|
||||
|
||||
use App\Exceptions\Hardening\ProviderAccessHardeningRequired;
|
||||
use App\Models\Tenant;
|
||||
|
||||
interface WriteGateInterface
|
||||
{
|
||||
/**
|
||||
* Evaluate whether a write operation is allowed for the given tenant.
|
||||
*
|
||||
* @throws ProviderAccessHardeningRequired when the operation is blocked
|
||||
*/
|
||||
public function evaluate(Tenant $tenant, string $operationType): void;
|
||||
|
||||
/**
|
||||
* Check whether the gate would block a write operation for the given tenant.
|
||||
*
|
||||
* Non-throwing variant for UI disabled-state checks.
|
||||
*/
|
||||
public function wouldBlock(Tenant $tenant): bool;
|
||||
}
|
||||
@ -1,17 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exceptions\Hardening;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class ProviderAccessHardeningRequired extends RuntimeException
|
||||
{
|
||||
public function __construct(
|
||||
public readonly int $tenantId,
|
||||
public readonly string $operationType,
|
||||
public readonly string $reasonCode,
|
||||
public readonly string $reasonMessage,
|
||||
) {
|
||||
parent::__construct($reasonMessage);
|
||||
}
|
||||
}
|
||||
@ -7,15 +7,10 @@
|
||||
use BackedEnum;
|
||||
use Filament\Clusters\Cluster;
|
||||
use Filament\Pages\Enums\SubNavigationPosition;
|
||||
use UnitEnum;
|
||||
|
||||
class InventoryCluster extends Cluster
|
||||
{
|
||||
protected static ?SubNavigationPosition $subNavigationPosition = SubNavigationPosition::Start;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-squares-2x2';
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Inventory';
|
||||
|
||||
protected static ?string $navigationLabel = 'Items';
|
||||
}
|
||||
|
||||
@ -1,27 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Clusters\Monitoring;
|
||||
|
||||
use BackedEnum;
|
||||
use Filament\Clusters\Cluster;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Pages\Enums\SubNavigationPosition;
|
||||
use UnitEnum;
|
||||
|
||||
class AlertsCluster extends Cluster
|
||||
{
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-bell-alert';
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Monitoring';
|
||||
|
||||
protected static ?int $navigationSort = 20;
|
||||
|
||||
protected static ?SubNavigationPosition $subNavigationPosition = SubNavigationPosition::Start;
|
||||
|
||||
public static function shouldRegisterNavigation(): bool
|
||||
{
|
||||
return Filament::getCurrentPanel()?->getId() === 'admin';
|
||||
}
|
||||
}
|
||||
@ -1,304 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Filament\Resources\FindingResource;
|
||||
use App\Models\BaselineTenantAssignment;
|
||||
use App\Models\Finding;
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\Auth\CapabilityResolver;
|
||||
use App\Services\Baselines\BaselineCompareService;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\OperationRunLinks;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use UnitEnum;
|
||||
|
||||
class BaselineCompareLanding extends Page
|
||||
{
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-scale';
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Governance';
|
||||
|
||||
protected static ?string $navigationLabel = 'Baseline Compare';
|
||||
|
||||
protected static ?int $navigationSort = 10;
|
||||
|
||||
protected static ?string $title = 'Baseline Compare';
|
||||
|
||||
protected string $view = 'filament.pages.baseline-compare-landing';
|
||||
|
||||
public ?string $state = null;
|
||||
|
||||
public ?string $message = null;
|
||||
|
||||
public ?string $profileName = null;
|
||||
|
||||
public ?int $profileId = null;
|
||||
|
||||
public ?int $snapshotId = null;
|
||||
|
||||
public ?int $operationRunId = null;
|
||||
|
||||
public ?int $findingsCount = null;
|
||||
|
||||
/** @var array<string, int>|null */
|
||||
public ?array $severityCounts = null;
|
||||
|
||||
public ?string $lastComparedAt = null;
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$tenant = Tenant::current();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$resolver = app(CapabilityResolver::class);
|
||||
|
||||
return $resolver->can($user, $tenant, Capabilities::TENANT_VIEW);
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$tenant = Tenant::current();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
$this->state = 'no_tenant';
|
||||
$this->message = 'No tenant selected.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$assignment = BaselineTenantAssignment::query()
|
||||
->where('tenant_id', $tenant->getKey())
|
||||
->first();
|
||||
|
||||
if (! $assignment instanceof BaselineTenantAssignment) {
|
||||
$this->state = 'no_assignment';
|
||||
$this->message = 'This tenant has no baseline assignment. A workspace manager can assign a baseline profile to this tenant.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$profile = $assignment->baselineProfile;
|
||||
|
||||
if ($profile === null) {
|
||||
$this->state = 'no_assignment';
|
||||
$this->message = 'The assigned baseline profile no longer exists.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->profileName = (string) $profile->name;
|
||||
$this->profileId = (int) $profile->getKey();
|
||||
$this->snapshotId = $profile->active_snapshot_id !== null ? (int) $profile->active_snapshot_id : null;
|
||||
|
||||
if ($this->snapshotId === null) {
|
||||
$this->state = 'no_snapshot';
|
||||
$this->message = 'The baseline profile has no active snapshot yet. A workspace manager needs to capture a snapshot first.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$latestRun = OperationRun::query()
|
||||
->where('tenant_id', $tenant->getKey())
|
||||
->where('type', 'baseline_compare')
|
||||
->latest('id')
|
||||
->first();
|
||||
|
||||
if ($latestRun instanceof OperationRun && in_array($latestRun->status, ['queued', 'running'], true)) {
|
||||
$this->state = 'comparing';
|
||||
$this->operationRunId = (int) $latestRun->getKey();
|
||||
$this->message = 'A baseline comparison is currently in progress.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($latestRun instanceof OperationRun && $latestRun->finished_at !== null) {
|
||||
$this->lastComparedAt = $latestRun->finished_at->diffForHumans();
|
||||
}
|
||||
|
||||
$scopeKey = 'baseline_profile:'.$profile->getKey();
|
||||
|
||||
$findingsQuery = Finding::query()
|
||||
->where('tenant_id', $tenant->getKey())
|
||||
->where('finding_type', Finding::FINDING_TYPE_DRIFT)
|
||||
->where('source', 'baseline.compare')
|
||||
->where('scope_key', $scopeKey);
|
||||
|
||||
$totalFindings = (int) (clone $findingsQuery)->count();
|
||||
|
||||
if ($totalFindings > 0) {
|
||||
$this->state = 'ready';
|
||||
$this->findingsCount = $totalFindings;
|
||||
$this->severityCounts = [
|
||||
'high' => (int) (clone $findingsQuery)->where('severity', Finding::SEVERITY_HIGH)->count(),
|
||||
'medium' => (int) (clone $findingsQuery)->where('severity', Finding::SEVERITY_MEDIUM)->count(),
|
||||
'low' => (int) (clone $findingsQuery)->where('severity', Finding::SEVERITY_LOW)->count(),
|
||||
];
|
||||
|
||||
if ($latestRun instanceof OperationRun) {
|
||||
$this->operationRunId = (int) $latestRun->getKey();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($latestRun instanceof OperationRun && $latestRun->status === 'completed' && $latestRun->outcome === 'succeeded') {
|
||||
$this->state = 'ready';
|
||||
$this->findingsCount = 0;
|
||||
$this->operationRunId = (int) $latestRun->getKey();
|
||||
$this->message = 'No drift findings for this baseline comparison. The tenant matches the baseline.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->state = 'idle';
|
||||
$this->message = 'Baseline profile is assigned and has a snapshot. Run "Compare Now" to check for drift.';
|
||||
}
|
||||
|
||||
public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
|
||||
{
|
||||
return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::ListOnlyReadOnly)
|
||||
->satisfy(ActionSurfaceSlot::ListHeader, 'Header action: Compare Now (confirmation modal, capability-gated).')
|
||||
->exempt(ActionSurfaceSlot::InspectAffordance, 'This is a tenant-scoped landing page, not a record inspect surface.')
|
||||
->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'This page does not render table rows with secondary actions.')
|
||||
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'This page has no bulk actions.')
|
||||
->satisfy(ActionSurfaceSlot::ListEmptyState, 'Page renders explicit empty states for missing tenant, missing assignment, and missing snapshot, with guidance messaging.')
|
||||
->exempt(ActionSurfaceSlot::DetailHeader, 'This page does not have a record detail header; it uses a page header action instead.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<Action>
|
||||
*/
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
$this->compareNowAction(),
|
||||
];
|
||||
}
|
||||
|
||||
private function compareNowAction(): Action
|
||||
{
|
||||
return Action::make('compareNow')
|
||||
->label('Compare Now')
|
||||
->icon('heroicon-o-play')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Start baseline comparison')
|
||||
->modalDescription('This will compare the current tenant inventory against the assigned baseline snapshot and generate drift findings.')
|
||||
->visible(fn (): bool => $this->canCompare())
|
||||
->disabled(fn (): bool => ! in_array($this->state, ['idle', 'ready'], true))
|
||||
->action(function (): void {
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
Notification::make()->title('Not authenticated')->danger()->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$tenant = Tenant::current();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
Notification::make()->title('No tenant context')->danger()->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$service = app(BaselineCompareService::class);
|
||||
$result = $service->startCompare($tenant, $user);
|
||||
|
||||
if (! ($result['ok'] ?? false)) {
|
||||
Notification::make()
|
||||
->title('Cannot start comparison')
|
||||
->body('Reason: '.($result['reason_code'] ?? 'unknown'))
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$run = $result['run'] ?? null;
|
||||
|
||||
if ($run instanceof OperationRun) {
|
||||
$this->operationRunId = (int) $run->getKey();
|
||||
}
|
||||
|
||||
$this->state = 'comparing';
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::queuedToast($run instanceof OperationRun ? (string) $run->type : 'baseline_compare')
|
||||
->actions($run instanceof OperationRun ? [
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(OperationRunLinks::view($run, $tenant)),
|
||||
] : [])
|
||||
->send();
|
||||
});
|
||||
}
|
||||
|
||||
private function canCompare(): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$tenant = Tenant::current();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$resolver = app(CapabilityResolver::class);
|
||||
|
||||
return $resolver->can($user, $tenant, Capabilities::TENANT_SYNC);
|
||||
}
|
||||
|
||||
public function getFindingsUrl(): ?string
|
||||
{
|
||||
$tenant = Tenant::current();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return FindingResource::getUrl('index', tenant: $tenant);
|
||||
}
|
||||
|
||||
public function getRunUrl(): ?string
|
||||
{
|
||||
if ($this->operationRunId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$tenant = Tenant::current();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return OperationRunLinks::view($this->operationRunId, $tenant);
|
||||
}
|
||||
}
|
||||
@ -27,17 +27,6 @@ class ChooseTenant extends Page
|
||||
|
||||
protected string $view = 'filament.pages.choose-tenant';
|
||||
|
||||
/**
|
||||
* Disable the simple-layout topbar to prevent lazy-loaded
|
||||
* DatabaseNotifications from triggering Livewire update 404s.
|
||||
*/
|
||||
protected function getLayoutData(): array
|
||||
{
|
||||
return [
|
||||
'hasTopbar' => false,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Tenant>
|
||||
*/
|
||||
|
||||
@ -7,11 +7,10 @@
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Services\Audit\WorkspaceAuditLogger;
|
||||
use App\Support\Audit\AuditActionId;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use App\Support\Workspaces\WorkspaceIntendedUrl;
|
||||
use App\Support\Workspaces\WorkspaceRedirectResolver;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
@ -31,18 +30,33 @@ class ChooseWorkspace extends Page
|
||||
protected string $view = 'filament.pages.choose-workspace';
|
||||
|
||||
/**
|
||||
* Workspace roles keyed by workspace_id.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
public array $workspaceRoles = [];
|
||||
|
||||
/**
|
||||
* @return array<\Filament\Actions\Action>
|
||||
* @return array<Action>
|
||||
*/
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [];
|
||||
return [
|
||||
Action::make('createWorkspace')
|
||||
->label('Create workspace')
|
||||
->modalHeading('Create workspace')
|
||||
->visible(function (): bool {
|
||||
$user = auth()->user();
|
||||
|
||||
return $user instanceof User
|
||||
&& $user->can('create', Workspace::class);
|
||||
})
|
||||
->form([
|
||||
TextInput::make('name')
|
||||
->required()
|
||||
->maxLength(255),
|
||||
TextInput::make('slug')
|
||||
->helperText('Optional. Used in URLs if set.')
|
||||
->maxLength(255)
|
||||
->rules(['nullable', 'string', 'max:255', 'alpha_dash', 'unique:workspaces,slug'])
|
||||
->dehydrateStateUsing(fn ($state) => filled($state) ? $state : null)
|
||||
->dehydrated(fn ($state) => filled($state)),
|
||||
])
|
||||
->action(fn (array $data) => $this->createWorkspace($data)),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
@ -56,28 +70,15 @@ public function getWorkspaces(): Collection
|
||||
return Workspace::query()->whereRaw('1 = 0')->get();
|
||||
}
|
||||
|
||||
$workspaces = Workspace::query()
|
||||
return Workspace::query()
|
||||
->whereIn('id', function ($query) use ($user): void {
|
||||
$query->from('workspace_memberships')
|
||||
->select('workspace_id')
|
||||
->where('user_id', $user->getKey());
|
||||
})
|
||||
->whereNull('archived_at')
|
||||
->withCount(['tenants' => function ($query): void {
|
||||
$query->where('status', 'active');
|
||||
}])
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
// Build roles map from memberships.
|
||||
$memberships = WorkspaceMembership::query()
|
||||
->where('user_id', $user->getKey())
|
||||
->whereIn('workspace_id', $workspaces->pluck('id'))
|
||||
->pluck('role', 'workspace_id');
|
||||
|
||||
$this->workspaceRoles = $memberships->mapWithKeys(fn ($role, $id) => [(int) $id => (string) $role])->all();
|
||||
|
||||
return $workspaces;
|
||||
}
|
||||
|
||||
public function selectWorkspace(int $workspaceId): void
|
||||
@ -104,35 +105,11 @@ public function selectWorkspace(int $workspaceId): void
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$prevWorkspaceId = $context->currentWorkspaceId(request());
|
||||
|
||||
$context->setCurrentWorkspace($workspace, $user, request());
|
||||
|
||||
// Audit: manual workspace selection.
|
||||
/** @var WorkspaceAuditLogger $logger */
|
||||
$logger = app(WorkspaceAuditLogger::class);
|
||||
|
||||
$logger->log(
|
||||
workspace: $workspace,
|
||||
action: AuditActionId::WorkspaceSelected->value,
|
||||
context: [
|
||||
'metadata' => [
|
||||
'method' => 'manual',
|
||||
'reason' => 'chooser',
|
||||
'prev_workspace_id' => $prevWorkspaceId,
|
||||
],
|
||||
],
|
||||
actor: $user,
|
||||
resourceType: 'workspace',
|
||||
resourceId: (string) $workspace->getKey(),
|
||||
);
|
||||
|
||||
$intendedUrl = WorkspaceIntendedUrl::consume(request());
|
||||
|
||||
/** @var WorkspaceRedirectResolver $resolver */
|
||||
$resolver = app(WorkspaceRedirectResolver::class);
|
||||
|
||||
$this->redirect($intendedUrl ?: $resolver->resolve($workspace, $user));
|
||||
$this->redirect($intendedUrl ?: $this->redirectAfterWorkspaceSelected($user));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -170,9 +147,41 @@ public function createWorkspace(array $data): void
|
||||
|
||||
$intendedUrl = WorkspaceIntendedUrl::consume(request());
|
||||
|
||||
/** @var WorkspaceRedirectResolver $resolver */
|
||||
$resolver = app(WorkspaceRedirectResolver::class);
|
||||
$this->redirect($intendedUrl ?: $this->redirectAfterWorkspaceSelected($user));
|
||||
}
|
||||
|
||||
$this->redirect($intendedUrl ?: $resolver->resolve($workspace, $user));
|
||||
private function redirectAfterWorkspaceSelected(User $user): string
|
||||
{
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();
|
||||
|
||||
if ($workspaceId === null) {
|
||||
return self::getUrl();
|
||||
}
|
||||
|
||||
$workspace = Workspace::query()->whereKey($workspaceId)->first();
|
||||
|
||||
if (! $workspace instanceof Workspace) {
|
||||
return self::getUrl();
|
||||
}
|
||||
|
||||
$tenantsQuery = $user->tenants()
|
||||
->where('workspace_id', $workspace->getKey())
|
||||
->where('status', 'active');
|
||||
|
||||
$tenantCount = (int) $tenantsQuery->count();
|
||||
|
||||
if ($tenantCount === 0) {
|
||||
return route('admin.workspace.managed-tenants.index', ['workspace' => $workspace->slug ?? $workspace->getKey()]);
|
||||
}
|
||||
|
||||
if ($tenantCount === 1) {
|
||||
$tenant = $tenantsQuery->first();
|
||||
|
||||
if ($tenant !== null) {
|
||||
return TenantDashboard::getUrl(panel: 'tenant', tenant: $tenant);
|
||||
}
|
||||
}
|
||||
|
||||
return ChooseTenant::getUrl();
|
||||
}
|
||||
}
|
||||
|
||||
@ -20,6 +20,7 @@
|
||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use UnitEnum;
|
||||
|
||||
@ -27,7 +28,7 @@ class DriftLanding extends Page
|
||||
{
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-arrows-right-left';
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Governance';
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Drift';
|
||||
|
||||
protected static ?string $navigationLabel = 'Drift';
|
||||
|
||||
@ -239,8 +240,10 @@ public function mount(): void
|
||||
$this->state = 'generating';
|
||||
|
||||
if (! $opRun->wasRecentlyCreated) {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
|
||||
Notification::make()
|
||||
->title('Drift generation already active')
|
||||
->body('This operation is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
|
||||
@ -4,76 +4,30 @@
|
||||
|
||||
namespace App\Filament\Pages\Monitoring;
|
||||
|
||||
use App\Filament\Clusters\Monitoring\AlertsCluster;
|
||||
use App\Filament\Widgets\Alerts\AlertsKpiHeader;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Services\Auth\WorkspaceCapabilityResolver;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\OperateHub\OperateHubShell;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Pages\Page;
|
||||
use UnitEnum;
|
||||
|
||||
class Alerts extends Page
|
||||
{
|
||||
protected static ?string $cluster = AlertsCluster::class;
|
||||
protected static bool $isDiscovered = false;
|
||||
|
||||
protected static ?int $navigationSort = 20;
|
||||
protected static bool $shouldRegisterNavigation = false;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Monitoring';
|
||||
|
||||
protected static ?string $navigationLabel = 'Overview';
|
||||
protected static ?string $navigationLabel = 'Alerts';
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-bell-alert';
|
||||
|
||||
protected static ?string $slug = 'overview';
|
||||
protected static ?string $slug = 'alerts';
|
||||
|
||||
protected static ?string $title = 'Alerts';
|
||||
|
||||
protected string $view = 'filament.pages.monitoring.alerts';
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
if (Filament::getCurrentPanel()?->getId() !== 'admin') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
|
||||
if (! is_int($workspaceId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$workspace = Workspace::query()->whereKey($workspaceId)->first();
|
||||
|
||||
if (! $workspace instanceof Workspace) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @var WorkspaceCapabilityResolver $resolver */
|
||||
$resolver = app(WorkspaceCapabilityResolver::class);
|
||||
|
||||
return $resolver->isMember($user, $workspace)
|
||||
&& $resolver->can($user, $workspace, Capabilities::ALERTS_VIEW);
|
||||
}
|
||||
|
||||
protected function getHeaderWidgets(): array
|
||||
{
|
||||
return [
|
||||
AlertsKpiHeader::class,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<Action>
|
||||
*/
|
||||
|
||||
@ -1,978 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Pages\Settings;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceSetting;
|
||||
use App\Services\Auth\WorkspaceCapabilityResolver;
|
||||
use App\Services\Settings\SettingsResolver;
|
||||
use App\Services\Settings\SettingsWriter;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\Settings\SettingDefinition;
|
||||
use App\Support\Settings\SettingsRegistry;
|
||||
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\KeyValue;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use UnitEnum;
|
||||
|
||||
class WorkspaceSettings extends Page
|
||||
{
|
||||
protected static bool $isDiscovered = false;
|
||||
|
||||
protected static bool $shouldRegisterNavigation = false;
|
||||
|
||||
protected static ?string $slug = 'settings/workspace';
|
||||
|
||||
protected static ?string $title = 'Workspace settings';
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-cog-6-tooth';
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Settings';
|
||||
|
||||
protected static ?int $navigationSort = 20;
|
||||
|
||||
/**
|
||||
* @var array<string, array{domain: string, key: string, type: 'int'|'json'}>
|
||||
*/
|
||||
private const SETTING_FIELDS = [
|
||||
'backup_retention_keep_last_default' => ['domain' => 'backup', 'key' => 'retention_keep_last_default', 'type' => 'int'],
|
||||
'backup_retention_min_floor' => ['domain' => 'backup', 'key' => 'retention_min_floor', 'type' => 'int'],
|
||||
'drift_severity_mapping' => ['domain' => 'drift', 'key' => 'severity_mapping', 'type' => 'json'],
|
||||
'findings_sla_days' => ['domain' => 'findings', 'key' => 'sla_days', 'type' => 'json'],
|
||||
'operations_operation_run_retention_days' => ['domain' => 'operations', 'key' => 'operation_run_retention_days', 'type' => 'int'],
|
||||
'operations_stuck_run_threshold_minutes' => ['domain' => 'operations', 'key' => 'stuck_run_threshold_minutes', 'type' => 'int'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Fields rendered as Filament KeyValue components (array state, not JSON string).
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
private const KEYVALUE_FIELDS = [
|
||||
'drift_severity_mapping',
|
||||
];
|
||||
|
||||
/**
|
||||
* Findings SLA days are decomposed into individual form fields per severity.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private const SLA_SUB_FIELDS = [
|
||||
'findings_sla_critical' => 'critical',
|
||||
'findings_sla_high' => 'high',
|
||||
'findings_sla_medium' => 'medium',
|
||||
'findings_sla_low' => 'low',
|
||||
];
|
||||
|
||||
public Workspace $workspace;
|
||||
|
||||
/**
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
public array $data = [];
|
||||
|
||||
/**
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
public array $workspaceOverrides = [];
|
||||
|
||||
/**
|
||||
* @var array<string, array{source: string, value: mixed, system_default: mixed}>
|
||||
*/
|
||||
public array $resolvedSettings = [];
|
||||
|
||||
/**
|
||||
* Per-domain "last modified" metadata: domain => {user_name, updated_at}.
|
||||
*
|
||||
* @var array<string, array{user_name: string, updated_at: Carbon}>
|
||||
*/
|
||||
public array $domainLastModified = [];
|
||||
|
||||
/**
|
||||
* @return array<Action>
|
||||
*/
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('save')
|
||||
->label('Save')
|
||||
->action(function (): void {
|
||||
$this->save();
|
||||
})
|
||||
->disabled(fn (): bool => ! $this->currentUserCanManage())
|
||||
->tooltip(fn (): ?string => $this->currentUserCanManage()
|
||||
? null
|
||||
: 'You do not have permission to manage workspace settings.'),
|
||||
];
|
||||
}
|
||||
|
||||
public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
|
||||
{
|
||||
return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::ListOnlyReadOnly)
|
||||
->satisfy(ActionSurfaceSlot::ListHeader, 'Header action saves settings; each setting includes a confirmed reset action.')
|
||||
->exempt(ActionSurfaceSlot::InspectAffordance, 'Workspace settings are edited as a singleton form without a record inspect action.')
|
||||
->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'The page does not render table rows with secondary actions.')
|
||||
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'The page has no bulk actions because it manages a single settings scope.')
|
||||
->exempt(ActionSurfaceSlot::ListEmptyState, 'The settings form is always rendered and has no list empty state.');
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
|
||||
if ($workspaceId === null) {
|
||||
$this->redirect('/admin/choose-workspace');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$workspace = Workspace::query()->whereKey($workspaceId)->first();
|
||||
|
||||
if (! $workspace instanceof Workspace) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$this->workspace = $workspace;
|
||||
|
||||
$this->authorizeWorkspaceView($user);
|
||||
|
||||
$this->loadFormState();
|
||||
}
|
||||
|
||||
public function content(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->statePath('data')
|
||||
->schema([
|
||||
Section::make('Backup settings')
|
||||
->description($this->sectionDescription('backup', 'Workspace defaults used when a schedule has no explicit value.'))
|
||||
->schema([
|
||||
TextInput::make('backup_retention_keep_last_default')
|
||||
->label('Default retention keep-last')
|
||||
->placeholder('Unset (uses default)')
|
||||
->suffix('versions')
|
||||
->hint('1 – 365')
|
||||
->numeric()
|
||||
->integer()
|
||||
->minValue(1)
|
||||
->maxValue(365)
|
||||
->disabled(fn (): bool => ! $this->currentUserCanManage())
|
||||
->helperText(fn (): string => $this->helperTextFor('backup_retention_keep_last_default'))
|
||||
->hintAction($this->makeResetAction('backup_retention_keep_last_default')),
|
||||
TextInput::make('backup_retention_min_floor')
|
||||
->label('Minimum retention floor')
|
||||
->placeholder('Unset (uses default)')
|
||||
->suffix('versions')
|
||||
->hint('1 – 365')
|
||||
->numeric()
|
||||
->integer()
|
||||
->minValue(1)
|
||||
->maxValue(365)
|
||||
->disabled(fn (): bool => ! $this->currentUserCanManage())
|
||||
->helperText(fn (): string => $this->helperTextFor('backup_retention_min_floor'))
|
||||
->hintAction($this->makeResetAction('backup_retention_min_floor')),
|
||||
]),
|
||||
Section::make('Drift settings')
|
||||
->description($this->sectionDescription('drift', 'Map finding types to severity levels. Allowed severities: critical, high, medium, low.'))
|
||||
->schema([
|
||||
KeyValue::make('drift_severity_mapping')
|
||||
->label('Severity mapping')
|
||||
->keyLabel('Finding type')
|
||||
->valueLabel('Severity')
|
||||
->keyPlaceholder('e.g. drift')
|
||||
->valuePlaceholder('critical, high, medium, or low')
|
||||
->disabled(fn (): bool => ! $this->currentUserCanManage())
|
||||
->helperText(fn (): string => $this->helperTextFor('drift_severity_mapping'))
|
||||
->hintAction($this->makeResetAction('drift_severity_mapping')),
|
||||
]),
|
||||
Section::make('Findings settings')
|
||||
->key('findings_section')
|
||||
->description($this->sectionDescription('findings', 'Configure workspace-wide SLA days by severity. Set one or more, or leave all empty to use the system default. Unset severities use their default.'))
|
||||
->columns(2)
|
||||
->afterHeader([
|
||||
$this->makeResetAction('findings_sla_days')->label('Reset all SLA')->size('sm'),
|
||||
])
|
||||
->schema([
|
||||
TextInput::make('findings_sla_critical')
|
||||
->label('Critical severity')
|
||||
->placeholder('Unset (uses default)')
|
||||
->suffix('days')
|
||||
->hint('1 – 3,650')
|
||||
->numeric()
|
||||
->integer()
|
||||
->minValue(1)
|
||||
->maxValue(3650)
|
||||
->disabled(fn (): bool => ! $this->currentUserCanManage())
|
||||
->helperText(fn (): string => $this->slaFieldHelperText('critical')),
|
||||
TextInput::make('findings_sla_high')
|
||||
->label('High severity')
|
||||
->placeholder('Unset (uses default)')
|
||||
->suffix('days')
|
||||
->hint('1 – 3,650')
|
||||
->numeric()
|
||||
->integer()
|
||||
->minValue(1)
|
||||
->maxValue(3650)
|
||||
->disabled(fn (): bool => ! $this->currentUserCanManage())
|
||||
->helperText(fn (): string => $this->slaFieldHelperText('high')),
|
||||
TextInput::make('findings_sla_medium')
|
||||
->label('Medium severity')
|
||||
->placeholder('Unset (uses default)')
|
||||
->suffix('days')
|
||||
->hint('1 – 3,650')
|
||||
->numeric()
|
||||
->integer()
|
||||
->minValue(1)
|
||||
->maxValue(3650)
|
||||
->disabled(fn (): bool => ! $this->currentUserCanManage())
|
||||
->helperText(fn (): string => $this->slaFieldHelperText('medium')),
|
||||
TextInput::make('findings_sla_low')
|
||||
->label('Low severity')
|
||||
->placeholder('Unset (uses default)')
|
||||
->suffix('days')
|
||||
->hint('1 – 3,650')
|
||||
->numeric()
|
||||
->integer()
|
||||
->minValue(1)
|
||||
->maxValue(3650)
|
||||
->disabled(fn (): bool => ! $this->currentUserCanManage())
|
||||
->helperText(fn (): string => $this->slaFieldHelperText('low')),
|
||||
]),
|
||||
Section::make('Operations settings')
|
||||
->description($this->sectionDescription('operations', 'Workspace controls for operations retention and thresholds.'))
|
||||
->schema([
|
||||
TextInput::make('operations_operation_run_retention_days')
|
||||
->label('Operation run retention')
|
||||
->placeholder('Unset (uses default)')
|
||||
->suffix('days')
|
||||
->hint('7 – 3,650')
|
||||
->numeric()
|
||||
->integer()
|
||||
->minValue(7)
|
||||
->maxValue(3650)
|
||||
->disabled(fn (): bool => ! $this->currentUserCanManage())
|
||||
->helperText(fn (): string => $this->helperTextFor('operations_operation_run_retention_days'))
|
||||
->hintAction($this->makeResetAction('operations_operation_run_retention_days')),
|
||||
TextInput::make('operations_stuck_run_threshold_minutes')
|
||||
->label('Stuck run threshold')
|
||||
->placeholder('Unset (uses default)')
|
||||
->suffix('minutes')
|
||||
->hint('0 – 10,080')
|
||||
->numeric()
|
||||
->integer()
|
||||
->minValue(0)
|
||||
->maxValue(10080)
|
||||
->disabled(fn (): bool => ! $this->currentUserCanManage())
|
||||
->helperText(fn (): string => $this->helperTextFor('operations_stuck_run_threshold_minutes'))
|
||||
->hintAction($this->makeResetAction('operations_stuck_run_threshold_minutes')),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function save(): void
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
$this->authorizeWorkspaceManage($user);
|
||||
|
||||
$this->resetValidation();
|
||||
|
||||
$this->composeSlaSubFieldsIntoData();
|
||||
|
||||
[$normalizedValues, $validationErrors] = $this->normalizedInputValues();
|
||||
|
||||
if ($validationErrors !== []) {
|
||||
throw ValidationException::withMessages($validationErrors);
|
||||
}
|
||||
|
||||
$writer = app(SettingsWriter::class);
|
||||
$changedSettingsCount = 0;
|
||||
|
||||
foreach (self::SETTING_FIELDS as $field => $setting) {
|
||||
$incomingValue = $normalizedValues[$field] ?? null;
|
||||
$currentOverride = $this->workspaceOverrideForField($field);
|
||||
|
||||
if ($incomingValue === null) {
|
||||
if ($currentOverride === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$writer->resetWorkspaceSetting(
|
||||
actor: $user,
|
||||
workspace: $this->workspace,
|
||||
domain: $setting['domain'],
|
||||
key: $setting['key'],
|
||||
);
|
||||
|
||||
$changedSettingsCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($this->valuesEqual($incomingValue, $currentOverride)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$writer->updateWorkspaceSetting(
|
||||
actor: $user,
|
||||
workspace: $this->workspace,
|
||||
domain: $setting['domain'],
|
||||
key: $setting['key'],
|
||||
value: $incomingValue,
|
||||
);
|
||||
|
||||
$changedSettingsCount++;
|
||||
}
|
||||
|
||||
$this->loadFormState();
|
||||
|
||||
Notification::make()
|
||||
->title($changedSettingsCount > 0 ? 'Workspace settings saved' : 'No settings changes to save')
|
||||
->success()
|
||||
->send();
|
||||
}
|
||||
|
||||
public function resetSetting(string $field): void
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
$this->authorizeWorkspaceManage($user);
|
||||
|
||||
$setting = $this->settingForField($field);
|
||||
|
||||
if ($this->workspaceOverrideForField($field) === null) {
|
||||
Notification::make()
|
||||
->title('Setting already uses default')
|
||||
->success()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
app(SettingsWriter::class)->resetWorkspaceSetting(
|
||||
actor: $user,
|
||||
workspace: $this->workspace,
|
||||
domain: $setting['domain'],
|
||||
key: $setting['key'],
|
||||
);
|
||||
|
||||
$this->loadFormState();
|
||||
|
||||
Notification::make()
|
||||
->title('Workspace setting reset to default')
|
||||
->success()
|
||||
->send();
|
||||
}
|
||||
|
||||
private function loadFormState(): void
|
||||
{
|
||||
$resolver = app(SettingsResolver::class);
|
||||
|
||||
$data = [];
|
||||
$workspaceOverrides = [];
|
||||
$resolvedSettings = [];
|
||||
|
||||
foreach (self::SETTING_FIELDS as $field => $setting) {
|
||||
$resolved = $resolver->resolveDetailed(
|
||||
workspace: $this->workspace,
|
||||
domain: $setting['domain'],
|
||||
key: $setting['key'],
|
||||
);
|
||||
|
||||
$workspaceValue = $resolved['workspace_value'];
|
||||
|
||||
$workspaceOverrides[$field] = $workspaceValue;
|
||||
$resolvedSettings[$field] = [
|
||||
'source' => $resolved['source'],
|
||||
'value' => $resolved['value'],
|
||||
'system_default' => $resolved['system_default'],
|
||||
];
|
||||
|
||||
$data[$field] = $workspaceValue === null
|
||||
? (in_array($field, self::KEYVALUE_FIELDS, true) ? [] : null)
|
||||
: $this->formatValueForInput($field, $workspaceValue);
|
||||
}
|
||||
|
||||
$this->decomposeSlaSubFields($data, $workspaceOverrides, $resolvedSettings);
|
||||
|
||||
$this->data = $data;
|
||||
$this->workspaceOverrides = $workspaceOverrides;
|
||||
$this->resolvedSettings = $resolvedSettings;
|
||||
|
||||
$this->loadDomainLastModified();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load per-domain "last modified" metadata from workspace_settings.
|
||||
*/
|
||||
private function loadDomainLastModified(): void
|
||||
{
|
||||
$domains = array_unique(array_column(self::SETTING_FIELDS, 'domain'));
|
||||
|
||||
$records = WorkspaceSetting::query()
|
||||
->where('workspace_id', (int) $this->workspace->getKey())
|
||||
->whereIn('domain', $domains)
|
||||
->whereNotNull('updated_by_user_id')
|
||||
->with('updatedByUser:id,name')
|
||||
->get();
|
||||
|
||||
$domainInfo = [];
|
||||
|
||||
foreach ($records as $record) {
|
||||
/** @var WorkspaceSetting $record */
|
||||
$domain = $record->domain;
|
||||
$updatedAt = $record->updated_at;
|
||||
|
||||
if (! $updatedAt instanceof Carbon) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($domainInfo[$domain]) && $domainInfo[$domain]['updated_at']->gte($updatedAt)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$user = $record->updatedByUser;
|
||||
|
||||
$domainInfo[$domain] = [
|
||||
'user_name' => $user instanceof User ? $user->name : 'Unknown',
|
||||
'updated_at' => $updatedAt,
|
||||
];
|
||||
}
|
||||
|
||||
$this->domainLastModified = $domainInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a section description that appends "last modified" info when available.
|
||||
*/
|
||||
private function sectionDescription(string $domain, string $baseDescription): string
|
||||
{
|
||||
$meta = $this->domainLastModified[$domain] ?? null;
|
||||
|
||||
if (! is_array($meta)) {
|
||||
return $baseDescription;
|
||||
}
|
||||
|
||||
/** @var Carbon $updatedAt */
|
||||
$updatedAt = $meta['updated_at'];
|
||||
|
||||
return sprintf(
|
||||
'%s — Last modified by %s, %s.',
|
||||
$baseDescription,
|
||||
$meta['user_name'],
|
||||
$updatedAt->diffForHumans(),
|
||||
);
|
||||
}
|
||||
|
||||
private function makeResetAction(string $field): Action
|
||||
{
|
||||
return Action::make('reset_'.$field)
|
||||
->label('Reset')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->action(function () use ($field): void {
|
||||
$this->resetSetting($field);
|
||||
})
|
||||
->disabled(fn (): bool => ! $this->currentUserCanManage() || ! $this->hasWorkspaceOverride($field))
|
||||
->tooltip(function () use ($field): ?string {
|
||||
if (! $this->currentUserCanManage()) {
|
||||
return 'You do not have permission to manage workspace settings.';
|
||||
}
|
||||
|
||||
if (! $this->hasWorkspaceOverride($field)) {
|
||||
return 'No workspace override to reset.';
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private function helperTextFor(string $field): string
|
||||
{
|
||||
$resolved = $this->resolvedSettings[$field] ?? null;
|
||||
|
||||
if (! is_array($resolved)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$effectiveValue = $this->formatValueForDisplay($field, $resolved['value'] ?? null);
|
||||
|
||||
if (! $this->hasWorkspaceOverride($field)) {
|
||||
return sprintf(
|
||||
'Unset. Effective value: %s (%s).',
|
||||
$effectiveValue,
|
||||
$this->sourceLabel((string) ($resolved['source'] ?? 'system_default')),
|
||||
);
|
||||
}
|
||||
|
||||
return sprintf('Effective value: %s.', $effectiveValue);
|
||||
}
|
||||
|
||||
private function slaFieldHelperText(string $severity): string
|
||||
{
|
||||
$resolved = $this->resolvedSettings['findings_sla_days'] ?? null;
|
||||
|
||||
if (! is_array($resolved)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$effectiveValue = is_array($resolved['value'] ?? null)
|
||||
? (int) ($resolved['value'][$severity] ?? 0)
|
||||
: 0;
|
||||
|
||||
$systemDefault = is_array($resolved['system_default'] ?? null)
|
||||
? (int) ($resolved['system_default'][$severity] ?? 0)
|
||||
: 0;
|
||||
|
||||
if (! $this->hasWorkspaceOverride('findings_sla_days')) {
|
||||
return sprintf('Default: %d days.', $systemDefault);
|
||||
}
|
||||
|
||||
return sprintf('Effective: %d days.', $effectiveValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: array<string, mixed>, 1: array<string, array<int, string>>}
|
||||
*/
|
||||
private function normalizedInputValues(): array
|
||||
{
|
||||
$normalizedValues = [];
|
||||
$validationErrors = [];
|
||||
|
||||
foreach (self::SETTING_FIELDS as $field => $_setting) {
|
||||
try {
|
||||
$normalizedValues[$field] = $this->normalizeFieldInput(
|
||||
field: $field,
|
||||
value: $this->data[$field] ?? null,
|
||||
);
|
||||
} catch (ValidationException $exception) {
|
||||
$messages = [];
|
||||
|
||||
foreach ($exception->errors() as $errorMessages) {
|
||||
foreach ((array) $errorMessages as $message) {
|
||||
$messages[] = (string) $message;
|
||||
}
|
||||
}
|
||||
|
||||
if ($field === 'findings_sla_days') {
|
||||
$severityToField = array_flip(self::SLA_SUB_FIELDS);
|
||||
|
||||
$targeted = false;
|
||||
|
||||
foreach ($messages as $message) {
|
||||
if (preg_match('/include "(?<severity>critical|high|medium|low)"/i', $message, $matches) === 1) {
|
||||
$severity = strtolower((string) $matches['severity']);
|
||||
$subField = $severityToField[$severity] ?? null;
|
||||
|
||||
if (is_string($subField)) {
|
||||
$validationErrors['data.'.$subField] ??= [];
|
||||
$validationErrors['data.'.$subField][] = $message;
|
||||
$targeted = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (! $targeted) {
|
||||
foreach (self::SLA_SUB_FIELDS as $subField => $_severity) {
|
||||
$validationErrors['data.'.$subField] = $messages !== []
|
||||
? $messages
|
||||
: ['Invalid value.'];
|
||||
}
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$validationErrors['data.'.$field] = $messages !== []
|
||||
? $messages
|
||||
: ['Invalid value.'];
|
||||
}
|
||||
}
|
||||
|
||||
return [$normalizedValues, $validationErrors];
|
||||
}
|
||||
|
||||
private function normalizeFieldInput(string $field, mixed $value): mixed
|
||||
{
|
||||
$setting = $this->settingForField($field);
|
||||
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_string($value) && trim($value) === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_array($value) && $value === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($setting['type'] === 'json') {
|
||||
$value = $this->normalizeJsonInput($value);
|
||||
|
||||
if (in_array($field, self::KEYVALUE_FIELDS, true)) {
|
||||
$value = $this->normalizeKeyValueInput($value);
|
||||
|
||||
if ($value === []) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$definition = $this->settingDefinition($field);
|
||||
|
||||
$validator = Validator::make(
|
||||
data: ['value' => $value],
|
||||
rules: ['value' => $definition->rules],
|
||||
);
|
||||
|
||||
if ($validator->fails()) {
|
||||
throw ValidationException::withMessages($validator->errors()->toArray());
|
||||
}
|
||||
|
||||
return $definition->normalize($validator->validated()['value']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize KeyValue component state.
|
||||
*
|
||||
* Filament's KeyValue UI keeps an empty row by default, which can submit as
|
||||
* ['' => ''] and would otherwise fail validation. We treat empty rows as unset.
|
||||
*
|
||||
* @param array<mixed> $value
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function normalizeKeyValueInput(array $value): array
|
||||
{
|
||||
$normalized = [];
|
||||
|
||||
foreach ($value as $key => $item) {
|
||||
if (is_array($item) && array_key_exists('key', $item)) {
|
||||
$rowKey = $item['key'];
|
||||
$rowValue = $item['value'] ?? null;
|
||||
|
||||
if (! is_string($rowKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$trimmedKey = trim($rowKey);
|
||||
|
||||
if ($trimmedKey === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_string($rowValue)) {
|
||||
$trimmedValue = trim($rowValue);
|
||||
|
||||
if ($trimmedValue === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalized[$trimmedKey] = $trimmedValue;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($rowValue === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalized[$trimmedKey] = $rowValue;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! is_string($key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$trimmedKey = trim($key);
|
||||
|
||||
if ($trimmedKey === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_string($item)) {
|
||||
$trimmedValue = trim($item);
|
||||
|
||||
if ($trimmedValue === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalized[$trimmedKey] = $trimmedValue;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($item === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalized[$trimmedKey] = $item;
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
private function normalizeJsonInput(mixed $value): array
|
||||
{
|
||||
if (is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (! is_string($value)) {
|
||||
throw ValidationException::withMessages([
|
||||
'value' => ['The value must be valid JSON.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$decoded = json_decode($value, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
throw ValidationException::withMessages([
|
||||
'value' => ['The value must be valid JSON.'],
|
||||
]);
|
||||
}
|
||||
|
||||
if (! is_array($decoded)) {
|
||||
throw ValidationException::withMessages([
|
||||
'value' => ['The value must be a JSON object.'],
|
||||
]);
|
||||
}
|
||||
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
private function valuesEqual(mixed $left, mixed $right): bool
|
||||
{
|
||||
if ($left === null || $right === null) {
|
||||
return $left === $right;
|
||||
}
|
||||
|
||||
if (is_array($left) && is_array($right)) {
|
||||
return $this->encodeCanonicalArray($left) === $this->encodeCanonicalArray($right);
|
||||
}
|
||||
|
||||
if (is_numeric($left) && is_numeric($right)) {
|
||||
return (int) $left === (int) $right;
|
||||
}
|
||||
|
||||
return $left === $right;
|
||||
}
|
||||
|
||||
private function encodeCanonicalArray(array $value): string
|
||||
{
|
||||
$encoded = json_encode($this->sortNestedArray($value));
|
||||
|
||||
return is_string($encoded) ? $encoded : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<mixed> $value
|
||||
* @return array<mixed>
|
||||
*/
|
||||
private function sortNestedArray(array $value): array
|
||||
{
|
||||
foreach ($value as $key => $item) {
|
||||
if (! is_array($item)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value[$key] = $this->sortNestedArray($item);
|
||||
}
|
||||
|
||||
ksort($value);
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
private function formatValueForInput(string $field, mixed $value): mixed
|
||||
{
|
||||
$setting = $this->settingForField($field);
|
||||
|
||||
if ($setting['type'] === 'json') {
|
||||
if (! is_array($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (in_array($field, self::KEYVALUE_FIELDS, true)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$encoded = json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
|
||||
|
||||
return is_string($encoded) ? $encoded : null;
|
||||
}
|
||||
|
||||
return is_numeric($value) ? (int) $value : null;
|
||||
}
|
||||
|
||||
private function formatValueForDisplay(string $field, mixed $value): string
|
||||
{
|
||||
$setting = $this->settingForField($field);
|
||||
|
||||
if ($setting['type'] === 'json') {
|
||||
if (! is_array($value) || $value === []) {
|
||||
return '{}';
|
||||
}
|
||||
|
||||
$encoded = json_encode($value, JSON_UNESCAPED_SLASHES);
|
||||
|
||||
return is_string($encoded) ? $encoded : '{}';
|
||||
}
|
||||
|
||||
return is_numeric($value) ? (string) (int) $value : 'null';
|
||||
}
|
||||
|
||||
private function sourceLabel(string $source): string
|
||||
{
|
||||
return match ($source) {
|
||||
'workspace_override' => 'workspace override',
|
||||
'tenant_override' => 'tenant override',
|
||||
default => 'system default',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{domain: string, key: string, type: 'int'|'json'}
|
||||
*/
|
||||
private function settingForField(string $field): array
|
||||
{
|
||||
if (! isset(self::SETTING_FIELDS[$field])) {
|
||||
throw ValidationException::withMessages([
|
||||
'data' => [sprintf('Unknown settings field: %s', $field)],
|
||||
]);
|
||||
}
|
||||
|
||||
return self::SETTING_FIELDS[$field];
|
||||
}
|
||||
|
||||
private function settingDefinition(string $field): SettingDefinition
|
||||
{
|
||||
$setting = $this->settingForField($field);
|
||||
|
||||
return app(SettingsRegistry::class)->require($setting['domain'], $setting['key']);
|
||||
}
|
||||
|
||||
private function hasWorkspaceOverride(string $field): bool
|
||||
{
|
||||
return $this->workspaceOverrideForField($field) !== null;
|
||||
}
|
||||
|
||||
private function workspaceOverrideForField(string $field): mixed
|
||||
{
|
||||
return $this->workspaceOverrides[$field] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decompose the findings_sla_days JSON setting into individual SLA sub-fields.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @param array<string, mixed> $workspaceOverrides
|
||||
* @param array<string, array{source: string, value: mixed, system_default: mixed}> $resolvedSettings
|
||||
*/
|
||||
private function decomposeSlaSubFields(array &$data, array &$workspaceOverrides, array &$resolvedSettings): void
|
||||
{
|
||||
$slaOverride = $workspaceOverrides['findings_sla_days'] ?? null;
|
||||
$slaResolved = $resolvedSettings['findings_sla_days'] ?? null;
|
||||
|
||||
foreach (self::SLA_SUB_FIELDS as $subField => $severity) {
|
||||
$data[$subField] = is_array($slaOverride) && isset($slaOverride[$severity])
|
||||
? (int) $slaOverride[$severity]
|
||||
: null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-compose individual SLA sub-fields back into the findings_sla_days data key before save.
|
||||
*/
|
||||
private function composeSlaSubFieldsIntoData(): void
|
||||
{
|
||||
$values = [];
|
||||
$hasAnyValue = false;
|
||||
|
||||
foreach (self::SLA_SUB_FIELDS as $subField => $severity) {
|
||||
$val = $this->data[$subField] ?? null;
|
||||
|
||||
if ($val !== null && (is_string($val) ? trim($val) !== '' : true)) {
|
||||
$values[$severity] = (int) $val;
|
||||
$hasAnyValue = true;
|
||||
}
|
||||
}
|
||||
|
||||
$this->data['findings_sla_days'] = $hasAnyValue ? $values : null;
|
||||
}
|
||||
|
||||
private function currentUserCanManage(): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $this->workspace instanceof Workspace) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @var WorkspaceCapabilityResolver $resolver */
|
||||
$resolver = app(WorkspaceCapabilityResolver::class);
|
||||
|
||||
return $resolver->isMember($user, $this->workspace)
|
||||
&& $resolver->can($user, $this->workspace, Capabilities::WORKSPACE_SETTINGS_MANAGE);
|
||||
}
|
||||
|
||||
private function authorizeWorkspaceView(User $user): void
|
||||
{
|
||||
/** @var WorkspaceCapabilityResolver $resolver */
|
||||
$resolver = app(WorkspaceCapabilityResolver::class);
|
||||
|
||||
if (! $resolver->isMember($user, $this->workspace)) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
if (! $resolver->can($user, $this->workspace, Capabilities::WORKSPACE_SETTINGS_VIEW)) {
|
||||
abort(403);
|
||||
}
|
||||
}
|
||||
|
||||
private function authorizeWorkspaceManage(User $user): void
|
||||
{
|
||||
/** @var WorkspaceCapabilityResolver $resolver */
|
||||
$resolver = app(WorkspaceCapabilityResolver::class);
|
||||
|
||||
if (! $resolver->isMember($user, $this->workspace)) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
if (! $resolver->can($user, $this->workspace, Capabilities::WORKSPACE_SETTINGS_MANAGE)) {
|
||||
abort(403);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -4,7 +4,6 @@
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Filament\Widgets\Dashboard\BaselineCompareNow;
|
||||
use App\Filament\Widgets\Dashboard\DashboardKpis;
|
||||
use App\Filament\Widgets\Dashboard\NeedsAttention;
|
||||
use App\Filament\Widgets\Dashboard\RecentDriftFindings;
|
||||
@ -32,7 +31,6 @@ public function getWidgets(): array
|
||||
return [
|
||||
DashboardKpis::class,
|
||||
NeedsAttention::class,
|
||||
BaselineCompareNow::class,
|
||||
RecentDriftFindings::class,
|
||||
RecentOperations::class,
|
||||
];
|
||||
|
||||
@ -5,7 +5,6 @@
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Filament\Resources\ProviderConnectionResource;
|
||||
use App\Filament\Resources\TenantResource;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\WorkspaceMembership;
|
||||
@ -170,12 +169,6 @@ private function refreshViewModel(): void
|
||||
|
||||
public function reRunVerificationUrl(): string
|
||||
{
|
||||
$tenant = $this->scopedTenant;
|
||||
|
||||
if ($tenant instanceof Tenant) {
|
||||
return TenantResource::getUrl('view', ['record' => $tenant]);
|
||||
}
|
||||
|
||||
return route('admin.onboarding');
|
||||
}
|
||||
|
||||
|
||||
@ -33,8 +33,6 @@
|
||||
use App\Support\OperationRunLinks;
|
||||
use App\Support\OperationRunOutcome;
|
||||
use App\Support\OperationRunStatus;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||
use App\Support\Verification\VerificationCheckStatus;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Filament\Actions\Action;
|
||||
@ -77,18 +75,6 @@ class ManagedTenantOnboardingWizard extends Page
|
||||
|
||||
protected static ?string $slug = 'onboarding';
|
||||
|
||||
/**
|
||||
* Disable the simple-layout topbar to prevent lazy-loaded
|
||||
* DatabaseNotifications from triggering Livewire update 404s
|
||||
* on this workspace-scoped route.
|
||||
*/
|
||||
protected function getLayoutData(): array
|
||||
{
|
||||
return [
|
||||
'hasTopbar' => false,
|
||||
];
|
||||
}
|
||||
|
||||
public Workspace $workspace;
|
||||
|
||||
public ?Tenant $managedTenant = null;
|
||||
@ -520,12 +506,6 @@ private function resumeLatestOnboardingSessionIfUnambiguous(): void
|
||||
|
||||
private function initializeWizardData(): void
|
||||
{
|
||||
// Ensure all entangled schema state paths exist at render time.
|
||||
// Livewire v4 can throw when entangling to missing nested array keys.
|
||||
$this->data['notes'] ??= '';
|
||||
$this->data['override_blocked'] ??= false;
|
||||
$this->data['override_reason'] ??= '';
|
||||
|
||||
if (! array_key_exists('connection_mode', $this->data)) {
|
||||
$this->data['connection_mode'] = 'existing';
|
||||
}
|
||||
@ -1446,8 +1426,6 @@ public function startVerification(): void
|
||||
);
|
||||
|
||||
if ($result->status === 'scope_busy') {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
Notification::make()
|
||||
->title('Another operation is already running')
|
||||
->body('Please wait for the active run to finish.')
|
||||
@ -1505,27 +1483,23 @@ public function startVerification(): void
|
||||
return;
|
||||
}
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
if ($result->status === 'deduped') {
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
->url($this->tenantlessOperationRunUrl((int) $result->run->getKey())),
|
||||
])
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $result->run->type)
|
||||
$notification = Notification::make()
|
||||
->title($result->status === 'deduped' ? 'Verification already running' : 'Verification started')
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
->url($this->tenantlessOperationRunUrl((int) $result->run->getKey())),
|
||||
])
|
||||
->send();
|
||||
]);
|
||||
|
||||
if ($result->status === 'deduped') {
|
||||
$notification
|
||||
->body('A verification run is already queued or running.')
|
||||
->warning();
|
||||
} else {
|
||||
$notification->success();
|
||||
}
|
||||
|
||||
$notification->send();
|
||||
}
|
||||
|
||||
public function refreshVerificationStatus(): void
|
||||
@ -1617,7 +1591,7 @@ public function startBootstrap(array $operationTypes): void
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var array{status: 'started', runs: array<string, int>, created: array<string, bool>}|array{status: 'scope_busy', run: OperationRun} $result */
|
||||
/** @var array{status: 'started', runs: array<string, int>}|array{status: 'scope_busy', run: OperationRun} $result */
|
||||
$result = DB::transaction(function () use ($tenant, $connection, $types, $registry, $user): array {
|
||||
$lockedConnection = ProviderConnection::query()
|
||||
->whereKey($connection->getKey())
|
||||
@ -1641,7 +1615,6 @@ public function startBootstrap(array $operationTypes): void
|
||||
$runsService = app(OperationRunService::class);
|
||||
|
||||
$bootstrapRuns = [];
|
||||
$bootstrapCreated = [];
|
||||
|
||||
foreach ($types as $operationType) {
|
||||
$definition = $registry->get($operationType);
|
||||
@ -1680,19 +1653,15 @@ public function startBootstrap(array $operationTypes): void
|
||||
}
|
||||
|
||||
$bootstrapRuns[$operationType] = (int) $run->getKey();
|
||||
$bootstrapCreated[$operationType] = (bool) $run->wasRecentlyCreated;
|
||||
}
|
||||
|
||||
return [
|
||||
'status' => 'started',
|
||||
'runs' => $bootstrapRuns,
|
||||
'created' => $bootstrapCreated,
|
||||
];
|
||||
});
|
||||
|
||||
if ($result['status'] === 'scope_busy') {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
Notification::make()
|
||||
->title('Another operation is already running')
|
||||
->body('Please wait for the active run to finish.')
|
||||
@ -1724,27 +1693,10 @@ public function startBootstrap(array $operationTypes): void
|
||||
$this->onboardingSession->save();
|
||||
}
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
foreach ($types as $operationType) {
|
||||
$runId = (int) ($bootstrapRuns[$operationType] ?? 0);
|
||||
$runUrl = $runId > 0 ? $this->tenantlessOperationRunUrl($runId) : null;
|
||||
$wasCreated = (bool) ($result['created'][$operationType] ?? false);
|
||||
|
||||
$toast = $wasCreated
|
||||
? OperationUxPresenter::queuedToast($operationType)
|
||||
: OperationUxPresenter::alreadyQueuedToast($operationType);
|
||||
|
||||
if ($runUrl !== null) {
|
||||
$toast->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
->url($runUrl),
|
||||
]);
|
||||
}
|
||||
|
||||
$toast->send();
|
||||
}
|
||||
Notification::make()
|
||||
->title('Bootstrap started')
|
||||
->success()
|
||||
->send();
|
||||
}
|
||||
|
||||
private function dispatchBootstrapJob(
|
||||
|
||||
@ -18,26 +18,12 @@ class ManagedTenantsLanding extends Page
|
||||
|
||||
protected static bool $isDiscovered = false;
|
||||
|
||||
protected static string $layout = 'filament-panels::components.layout.simple';
|
||||
|
||||
protected static ?string $title = 'Managed tenants';
|
||||
|
||||
protected string $view = 'filament.pages.workspaces.managed-tenants-landing';
|
||||
|
||||
public Workspace $workspace;
|
||||
|
||||
/**
|
||||
* The Filament simple layout renders the topbar by default, which includes
|
||||
* lazy-loaded database notifications. On this workspace-scoped landing page,
|
||||
* those background Livewire requests currently 404.
|
||||
*/
|
||||
protected function getLayoutData(): array
|
||||
{
|
||||
return [
|
||||
'hasTopbar' => false,
|
||||
];
|
||||
}
|
||||
|
||||
public function mount(Workspace $workspace): void
|
||||
{
|
||||
$this->workspace = $workspace;
|
||||
|
||||
@ -1,283 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources;
|
||||
|
||||
use App\Filament\Clusters\Monitoring\AlertsCluster;
|
||||
use App\Filament\Resources\AlertDeliveryResource\Pages;
|
||||
use App\Models\AlertDelivery;
|
||||
use App\Models\AlertDestination;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Support\Badges\BadgeDomain;
|
||||
use App\Support\Badges\BadgeRenderer;
|
||||
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceInspectAffordance;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\ViewAction;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Infolists\Components\ViewEntry;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use UnitEnum;
|
||||
|
||||
class AlertDeliveryResource extends Resource
|
||||
{
|
||||
protected static bool $isScopedToTenant = false;
|
||||
|
||||
protected static ?string $model = AlertDelivery::class;
|
||||
|
||||
protected static ?string $slug = 'alert-deliveries';
|
||||
|
||||
protected static ?string $cluster = AlertsCluster::class;
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
protected static bool $isGloballySearchable = false;
|
||||
|
||||
protected static ?string $recordTitleAttribute = 'id';
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-clock';
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Monitoring';
|
||||
|
||||
protected static ?string $navigationLabel = 'Alert deliveries';
|
||||
|
||||
public static function shouldRegisterNavigation(): bool
|
||||
{
|
||||
if (Filament::getCurrentPanel()?->getId() !== 'admin') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return parent::shouldRegisterNavigation();
|
||||
}
|
||||
|
||||
public static function canViewAny(): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->can('viewAny', AlertDelivery::class);
|
||||
}
|
||||
|
||||
public static function canView(Model $record): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $record instanceof AlertDelivery) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->can('view', $record);
|
||||
}
|
||||
|
||||
public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
|
||||
{
|
||||
return ActionSurfaceDeclaration::forResource(ActionSurfaceProfile::ListOnlyReadOnly)
|
||||
->exempt(ActionSurfaceSlot::ListHeader, 'Read-only history list intentionally has no list-header actions.')
|
||||
->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value)
|
||||
->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'No secondary row actions are exposed for read-only deliveries.')
|
||||
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'No bulk actions are exposed for read-only deliveries.')
|
||||
->exempt(ActionSurfaceSlot::ListEmptyState, 'Deliveries are generated by jobs and intentionally have no empty-state CTA.')
|
||||
->exempt(ActionSurfaceSlot::DetailHeader, 'View page is informational with no mutating header actions.');
|
||||
}
|
||||
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
$user = auth()->user();
|
||||
|
||||
return parent::getEloquentQuery()
|
||||
->with(['tenant', 'rule', 'destination'])
|
||||
->when(
|
||||
! $user instanceof User,
|
||||
fn (Builder $query): Builder => $query->whereRaw('1 = 0'),
|
||||
)
|
||||
->when(
|
||||
! is_int($workspaceId),
|
||||
fn (Builder $query): Builder => $query->whereRaw('1 = 0'),
|
||||
)
|
||||
->when(
|
||||
is_int($workspaceId),
|
||||
fn (Builder $query): Builder => $query->where('workspace_id', $workspaceId),
|
||||
)
|
||||
->when(
|
||||
$user instanceof User,
|
||||
fn (Builder $query): Builder => $query->where(function (Builder $q) use ($user): void {
|
||||
$q->whereIn('tenant_id', $user->tenantMemberships()->select('tenant_id'))
|
||||
->orWhereNull('tenant_id');
|
||||
}),
|
||||
)
|
||||
->when(
|
||||
Filament::getTenant() instanceof Tenant,
|
||||
fn (Builder $query): Builder => $query->where('tenant_id', (int) Filament::getTenant()->getKey()),
|
||||
)
|
||||
->latest('id');
|
||||
}
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema;
|
||||
}
|
||||
|
||||
public static function infolist(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->schema([
|
||||
Section::make('Delivery')
|
||||
->schema([
|
||||
TextEntry::make('status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::AlertDeliveryStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::AlertDeliveryStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::AlertDeliveryStatus)),
|
||||
TextEntry::make('event_type')
|
||||
->label('Event')
|
||||
->badge()
|
||||
->formatStateUsing(fn (?string $state): string => AlertRuleResource::eventTypeLabel((string) $state)),
|
||||
TextEntry::make('severity')
|
||||
->badge()
|
||||
->formatStateUsing(fn (?string $state): string => ucfirst((string) $state))
|
||||
->placeholder('—'),
|
||||
TextEntry::make('tenant.name')
|
||||
->label('Tenant'),
|
||||
TextEntry::make('rule.name')
|
||||
->label('Rule')
|
||||
->placeholder('—'),
|
||||
TextEntry::make('destination.name')
|
||||
->label('Destination')
|
||||
->placeholder('—'),
|
||||
TextEntry::make('attempt_count')
|
||||
->label('Attempts'),
|
||||
TextEntry::make('fingerprint_hash')
|
||||
->label('Fingerprint')
|
||||
->copyable(),
|
||||
TextEntry::make('send_after')
|
||||
->dateTime()
|
||||
->placeholder('—'),
|
||||
TextEntry::make('sent_at')
|
||||
->dateTime()
|
||||
->placeholder('—'),
|
||||
TextEntry::make('last_error_code')
|
||||
->label('Last error code')
|
||||
->placeholder('—'),
|
||||
TextEntry::make('last_error_message')
|
||||
->label('Last error message')
|
||||
->placeholder('—')
|
||||
->columnSpanFull(),
|
||||
TextEntry::make('created_at')
|
||||
->dateTime(),
|
||||
TextEntry::make('updated_at')
|
||||
->dateTime(),
|
||||
])
|
||||
->columns(2)
|
||||
->columnSpanFull(),
|
||||
Section::make('Payload')
|
||||
->schema([
|
||||
ViewEntry::make('payload')
|
||||
->label('')
|
||||
->view('filament.infolists.entries.snapshot-json')
|
||||
->state(fn (AlertDelivery $record): array => is_array($record->payload) ? $record->payload : [])
|
||||
->columnSpanFull(),
|
||||
])
|
||||
->columnSpanFull(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('id', 'desc')
|
||||
->recordUrl(fn (AlertDelivery $record): ?string => static::canView($record)
|
||||
? static::getUrl('view', ['record' => $record])
|
||||
: null)
|
||||
->columns([
|
||||
TextColumn::make('created_at')
|
||||
->label('Created')
|
||||
->since(),
|
||||
TextColumn::make('tenant.name')
|
||||
->label('Tenant')
|
||||
->searchable(),
|
||||
TextColumn::make('event_type')
|
||||
->label('Event')
|
||||
->badge(),
|
||||
TextColumn::make('severity')
|
||||
->badge()
|
||||
->formatStateUsing(fn (?string $state): string => ucfirst((string) $state))
|
||||
->placeholder('—'),
|
||||
TextColumn::make('status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::AlertDeliveryStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::AlertDeliveryStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::AlertDeliveryStatus)),
|
||||
TextColumn::make('rule.name')
|
||||
->label('Rule')
|
||||
->placeholder('—'),
|
||||
TextColumn::make('destination.name')
|
||||
->label('Destination')
|
||||
->placeholder('—'),
|
||||
TextColumn::make('attempt_count')
|
||||
->label('Attempts'),
|
||||
])
|
||||
->filters([
|
||||
SelectFilter::make('status')
|
||||
->options([
|
||||
AlertDelivery::STATUS_QUEUED => 'Queued',
|
||||
AlertDelivery::STATUS_DEFERRED => 'Deferred',
|
||||
AlertDelivery::STATUS_SENT => 'Sent',
|
||||
AlertDelivery::STATUS_FAILED => 'Failed',
|
||||
AlertDelivery::STATUS_SUPPRESSED => 'Suppressed',
|
||||
AlertDelivery::STATUS_CANCELED => 'Canceled',
|
||||
]),
|
||||
SelectFilter::make('event_type')
|
||||
->label('Event type')
|
||||
->options(function (): array {
|
||||
$options = AlertRuleResource::eventTypeOptions();
|
||||
$options[AlertDelivery::EVENT_TYPE_TEST] = 'Test';
|
||||
|
||||
return $options;
|
||||
}),
|
||||
SelectFilter::make('alert_destination_id')
|
||||
->label('Destination')
|
||||
->options(function (): array {
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
|
||||
if (! is_int($workspaceId)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return AlertDestination::query()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->orderBy('name')
|
||||
->pluck('name', 'id')
|
||||
->all();
|
||||
}),
|
||||
])
|
||||
->actions([
|
||||
ViewAction::make()->label('View'),
|
||||
])
|
||||
->bulkActions([]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => Pages\ListAlertDeliveries::route('/'),
|
||||
'view' => Pages\ViewAlertDelivery::route('/{record}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,22 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\AlertDeliveryResource\Pages;
|
||||
|
||||
use App\Filament\Resources\AlertDeliveryResource;
|
||||
use App\Support\OperateHub\OperateHubShell;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListAlertDeliveries extends ListRecords
|
||||
{
|
||||
protected static string $resource = AlertDeliveryResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return app(OperateHubShell::class)->headerActions(
|
||||
scopeActionName: 'operate_hub_scope_alerts',
|
||||
returnActionName: 'operate_hub_return_alerts',
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\AlertDeliveryResource\Pages;
|
||||
|
||||
use App\Filament\Resources\AlertDeliveryResource;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
|
||||
class ViewAlertDelivery extends ViewRecord
|
||||
{
|
||||
protected static string $resource = AlertDeliveryResource::class;
|
||||
}
|
||||
@ -1,381 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources;
|
||||
|
||||
use App\Filament\Clusters\Monitoring\AlertsCluster;
|
||||
use App\Filament\Resources\AlertDestinationResource\Pages;
|
||||
use App\Models\AlertDestination;
|
||||
use App\Models\User;
|
||||
use App\Services\Audit\WorkspaceAuditLogger;
|
||||
use App\Support\Audit\AuditActionId;
|
||||
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceInspectAffordance;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\ActionGroup;
|
||||
use Filament\Actions\BulkActionGroup;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TagsInput;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use UnitEnum;
|
||||
|
||||
class AlertDestinationResource extends Resource
|
||||
{
|
||||
protected static bool $isScopedToTenant = false;
|
||||
|
||||
protected static ?string $model = AlertDestination::class;
|
||||
|
||||
protected static ?string $slug = 'alert-destinations';
|
||||
|
||||
protected static ?string $cluster = AlertsCluster::class;
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
protected static bool $isGloballySearchable = false;
|
||||
|
||||
protected static ?string $recordTitleAttribute = 'name';
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-bell-alert';
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Monitoring';
|
||||
|
||||
protected static ?string $navigationLabel = 'Alert targets';
|
||||
|
||||
public static function shouldRegisterNavigation(): bool
|
||||
{
|
||||
if (Filament::getCurrentPanel()?->getId() !== 'admin') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return parent::shouldRegisterNavigation();
|
||||
}
|
||||
|
||||
public static function canViewAny(): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->can('viewAny', AlertDestination::class);
|
||||
}
|
||||
|
||||
public static function canCreate(): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->can('create', AlertDestination::class);
|
||||
}
|
||||
|
||||
public static function canEdit(Model $record): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $record instanceof AlertDestination) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->can('update', $record);
|
||||
}
|
||||
|
||||
public static function canDelete(Model $record): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $record instanceof AlertDestination) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->can('delete', $record);
|
||||
}
|
||||
|
||||
public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
|
||||
{
|
||||
return ActionSurfaceDeclaration::forResource(ActionSurfaceProfile::CrudListAndEdit)
|
||||
->satisfy(ActionSurfaceSlot::ListHeader, 'Header actions include capability-gated create.')
|
||||
->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value)
|
||||
->satisfy(ActionSurfaceSlot::ListRowMoreMenu, 'Secondary row actions are grouped under "More".')
|
||||
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'No bulk mutations are exposed for alert destinations in v1.')
|
||||
->satisfy(ActionSurfaceSlot::ListEmptyState, 'List page defines an empty-state create CTA.')
|
||||
->satisfy(ActionSurfaceSlot::DetailHeader, 'Edit page provides default save/cancel actions.');
|
||||
}
|
||||
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
|
||||
return parent::getEloquentQuery()
|
||||
->when(
|
||||
$workspaceId !== null,
|
||||
fn (Builder $query): Builder => $query->where('workspace_id', (int) $workspaceId),
|
||||
)
|
||||
->when(
|
||||
$workspaceId === null,
|
||||
fn (Builder $query): Builder => $query->whereRaw('1 = 0'),
|
||||
);
|
||||
}
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->schema([
|
||||
TextInput::make('name')
|
||||
->required()
|
||||
->maxLength(255),
|
||||
Select::make('type')
|
||||
->required()
|
||||
->options(self::typeOptions())
|
||||
->native(false)
|
||||
->live(),
|
||||
Toggle::make('is_enabled')
|
||||
->label('Enabled')
|
||||
->default(true),
|
||||
TextInput::make('teams_webhook_url')
|
||||
->label('Teams webhook URL')
|
||||
->placeholder('https://...')
|
||||
->url()
|
||||
->visible(fn (Get $get): bool => $get('type') === AlertDestination::TYPE_TEAMS_WEBHOOK),
|
||||
TagsInput::make('email_recipients')
|
||||
->label('Email recipients')
|
||||
->visible(fn (Get $get): bool => $get('type') === AlertDestination::TYPE_EMAIL)
|
||||
->placeholder('ops@example.com')
|
||||
->nestedRecursiveRules(['email']),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('name')
|
||||
->recordUrl(fn (AlertDestination $record): ?string => static::canEdit($record)
|
||||
? static::getUrl('edit', ['record' => $record])
|
||||
: static::getUrl('view', ['record' => $record]))
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->searchable(),
|
||||
TextColumn::make('type')
|
||||
->badge()
|
||||
->formatStateUsing(fn (?string $state): string => self::typeLabel((string) $state)),
|
||||
TextColumn::make('is_enabled')
|
||||
->label('Enabled')
|
||||
->badge()
|
||||
->formatStateUsing(fn (bool $state): string => $state ? 'Yes' : 'No')
|
||||
->color(fn (bool $state): string => $state ? 'success' : 'gray'),
|
||||
TextColumn::make('updated_at')
|
||||
->since(),
|
||||
])
|
||||
->actions([
|
||||
EditAction::make()
|
||||
->label('Edit')
|
||||
->visible(fn (AlertDestination $record): bool => static::canEdit($record)),
|
||||
ActionGroup::make([
|
||||
Action::make('toggle_enabled')
|
||||
->label(fn (AlertDestination $record): string => $record->is_enabled ? 'Disable' : 'Enable')
|
||||
->icon(fn (AlertDestination $record): string => $record->is_enabled ? 'heroicon-o-pause' : 'heroicon-o-play')
|
||||
->action(function (AlertDestination $record): void {
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $user->can('update', $record)) {
|
||||
throw new AuthorizationException;
|
||||
}
|
||||
|
||||
$enabled = ! (bool) $record->is_enabled;
|
||||
$record->forceFill([
|
||||
'is_enabled' => $enabled,
|
||||
])->save();
|
||||
|
||||
$actionId = $enabled
|
||||
? AuditActionId::AlertDestinationEnabled
|
||||
: AuditActionId::AlertDestinationDisabled;
|
||||
|
||||
self::audit($record, $actionId, [
|
||||
'alert_destination_id' => (int) $record->getKey(),
|
||||
'name' => (string) $record->name,
|
||||
'type' => (string) $record->type,
|
||||
'is_enabled' => $enabled,
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title($enabled ? 'Destination enabled' : 'Destination disabled')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
Action::make('delete')
|
||||
->label('Delete')
|
||||
->icon('heroicon-o-trash')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->action(function (AlertDestination $record): void {
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $user->can('delete', $record)) {
|
||||
throw new AuthorizationException;
|
||||
}
|
||||
|
||||
self::audit($record, AuditActionId::AlertDestinationDeleted, [
|
||||
'alert_destination_id' => (int) $record->getKey(),
|
||||
'name' => (string) $record->name,
|
||||
'type' => (string) $record->type,
|
||||
]);
|
||||
|
||||
$record->delete();
|
||||
|
||||
Notification::make()
|
||||
->title('Destination deleted')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
])->label('More'),
|
||||
])
|
||||
->bulkActions([
|
||||
BulkActionGroup::make([])->label('More'),
|
||||
])
|
||||
->emptyStateActions([
|
||||
\Filament\Actions\CreateAction::make()
|
||||
->label('Create target')
|
||||
->disabled(fn (): bool => ! static::canCreate()),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => Pages\ListAlertDestinations::route('/'),
|
||||
'create' => Pages\CreateAlertDestination::route('/create'),
|
||||
'view' => Pages\ViewAlertDestination::route('/{record}'),
|
||||
'edit' => Pages\EditAlertDestination::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public static function normalizePayload(array $data, ?AlertDestination $record = null): array
|
||||
{
|
||||
$type = trim((string) ($data['type'] ?? $record?->type ?? ''));
|
||||
$existingConfig = is_array($record?->config ?? null) ? $record->config : [];
|
||||
|
||||
if ($type === AlertDestination::TYPE_TEAMS_WEBHOOK) {
|
||||
$webhookUrl = trim((string) ($data['teams_webhook_url'] ?? ''));
|
||||
|
||||
if ($webhookUrl === '' && $record instanceof AlertDestination) {
|
||||
$webhookUrl = trim((string) Arr::get($existingConfig, 'webhook_url', ''));
|
||||
}
|
||||
|
||||
$data['config'] = [
|
||||
'webhook_url' => $webhookUrl,
|
||||
];
|
||||
}
|
||||
|
||||
if ($type === AlertDestination::TYPE_EMAIL) {
|
||||
$recipients = Arr::wrap($data['email_recipients'] ?? []);
|
||||
$recipients = array_values(array_filter(array_map(static fn (mixed $value): string => trim((string) $value), $recipients)));
|
||||
|
||||
if ($recipients === [] && $record instanceof AlertDestination) {
|
||||
$existingRecipients = Arr::get($existingConfig, 'recipients', []);
|
||||
$recipients = is_array($existingRecipients) ? array_values(array_filter(array_map(static fn (mixed $value): string => trim((string) $value), $existingRecipients))) : [];
|
||||
}
|
||||
|
||||
$data['config'] = [
|
||||
'recipients' => array_values(array_unique($recipients)),
|
||||
];
|
||||
}
|
||||
|
||||
unset($data['teams_webhook_url'], $data['email_recipients']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function typeOptions(): array
|
||||
{
|
||||
return [
|
||||
AlertDestination::TYPE_TEAMS_WEBHOOK => 'Microsoft Teams webhook',
|
||||
AlertDestination::TYPE_EMAIL => 'Email',
|
||||
];
|
||||
}
|
||||
|
||||
public static function typeLabel(string $type): string
|
||||
{
|
||||
return self::typeOptions()[$type] ?? ucfirst($type);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public static function assertValidConfigPayload(array $data): void
|
||||
{
|
||||
$type = (string) ($data['type'] ?? '');
|
||||
$config = is_array($data['config'] ?? null) ? $data['config'] : [];
|
||||
|
||||
if ($type === AlertDestination::TYPE_TEAMS_WEBHOOK) {
|
||||
$webhook = trim((string) Arr::get($config, 'webhook_url', ''));
|
||||
|
||||
if ($webhook === '') {
|
||||
throw ValidationException::withMessages([
|
||||
'teams_webhook_url' => ['The Teams webhook URL is required.'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if ($type === AlertDestination::TYPE_EMAIL) {
|
||||
$recipients = Arr::get($config, 'recipients', []);
|
||||
$recipients = is_array($recipients) ? array_values(array_filter(array_map(static fn (mixed $value): string => trim((string) $value), $recipients))) : [];
|
||||
|
||||
if ($recipients === []) {
|
||||
throw ValidationException::withMessages([
|
||||
'email_recipients' => ['At least one recipient is required for email destinations.'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $metadata
|
||||
*/
|
||||
public static function audit(AlertDestination $record, AuditActionId $actionId, array $metadata): void
|
||||
{
|
||||
$workspace = $record->workspace;
|
||||
|
||||
if ($workspace === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
app(WorkspaceAuditLogger::class)->log(
|
||||
workspace: $workspace,
|
||||
action: $actionId->value,
|
||||
context: [
|
||||
'metadata' => $metadata,
|
||||
],
|
||||
actor: auth()->user() instanceof User ? auth()->user() : null,
|
||||
resourceType: 'alert_destination',
|
||||
resourceId: (string) $record->getKey(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,47 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\AlertDestinationResource\Pages;
|
||||
|
||||
use App\Filament\Resources\AlertDestinationResource;
|
||||
use App\Models\AlertDestination;
|
||||
use App\Support\Audit\AuditActionId;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateAlertDestination extends CreateRecord
|
||||
{
|
||||
protected static string $resource = AlertDestinationResource::class;
|
||||
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
$workspaceId = app(\App\Support\Workspaces\WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
$data['workspace_id'] = (int) $workspaceId;
|
||||
$data = AlertDestinationResource::normalizePayload($data);
|
||||
AlertDestinationResource::assertValidConfigPayload($data);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
protected function afterCreate(): void
|
||||
{
|
||||
$record = $this->record;
|
||||
|
||||
if (! $record instanceof AlertDestination) {
|
||||
return;
|
||||
}
|
||||
|
||||
AlertDestinationResource::audit($record, AuditActionId::AlertDestinationCreated, [
|
||||
'alert_destination_id' => (int) $record->getKey(),
|
||||
'name' => (string) $record->name,
|
||||
'type' => (string) $record->type,
|
||||
'is_enabled' => (bool) $record->is_enabled,
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title('Destination created')
|
||||
->success()
|
||||
->send();
|
||||
}
|
||||
}
|
||||
@ -1,159 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\AlertDestinationResource\Pages;
|
||||
|
||||
use App\Filament\Resources\AlertDeliveryResource;
|
||||
use App\Filament\Resources\AlertDestinationResource;
|
||||
use App\Models\AlertDestination;
|
||||
use App\Models\User;
|
||||
use App\Services\Alerts\AlertDestinationLastTestResolver;
|
||||
use App\Services\Alerts\AlertDestinationTestMessageService;
|
||||
use App\Support\Alerts\AlertDestinationLastTestStatus;
|
||||
use App\Support\Audit\AuditActionId;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditAlertDestination extends EditRecord
|
||||
{
|
||||
protected static string $resource = AlertDestinationResource::class;
|
||||
|
||||
private ?AlertDestinationLastTestStatus $lastTestStatus = null;
|
||||
|
||||
public function mount(int|string $record): void
|
||||
{
|
||||
parent::mount($record);
|
||||
$this->resolveLastTestStatus();
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
$user = auth()->user();
|
||||
$record = $this->record;
|
||||
$canManage = $user instanceof User
|
||||
&& $record instanceof AlertDestination
|
||||
&& $user->can('update', $record);
|
||||
|
||||
return [
|
||||
Action::make('send_test_message')
|
||||
->label('Send test message')
|
||||
->icon('heroicon-o-paper-airplane')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Send test message')
|
||||
->modalDescription('A test delivery will be queued for this destination. This verifies the delivery pipeline is working.')
|
||||
->modalSubmitActionLabel('Send')
|
||||
->visible(fn (): bool => $record instanceof AlertDestination)
|
||||
->disabled(fn (): bool => ! $canManage)
|
||||
->action(function () use ($record): void {
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $record instanceof AlertDestination) {
|
||||
return;
|
||||
}
|
||||
|
||||
$service = app(AlertDestinationTestMessageService::class);
|
||||
$result = $service->sendTest($record, $user);
|
||||
|
||||
if ($result['success']) {
|
||||
Notification::make()
|
||||
->title($result['message'])
|
||||
->success()
|
||||
->send();
|
||||
} else {
|
||||
Notification::make()
|
||||
->title($result['message'])
|
||||
->warning()
|
||||
->send();
|
||||
}
|
||||
|
||||
$this->resolveLastTestStatus();
|
||||
}),
|
||||
|
||||
Action::make('view_last_delivery')
|
||||
->label('View last delivery')
|
||||
->icon('heroicon-o-arrow-top-right-on-square')
|
||||
->url(fn (): ?string => $this->buildDeepLinkUrl())
|
||||
->openUrlInNewTab()
|
||||
->visible(fn (): bool => $this->lastTestStatus?->deliveryId !== null),
|
||||
];
|
||||
}
|
||||
|
||||
public function getSubheading(): ?string
|
||||
{
|
||||
if ($this->lastTestStatus === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$label = ucfirst($this->lastTestStatus->status->value);
|
||||
$timestamp = $this->lastTestStatus->timestamp?->diffForHumans();
|
||||
|
||||
return $timestamp !== null
|
||||
? "Last test: {$label} ({$timestamp})"
|
||||
: "Last test: {$label}";
|
||||
}
|
||||
|
||||
protected function mutateFormDataBeforeSave(array $data): array
|
||||
{
|
||||
$record = $this->record;
|
||||
$data = AlertDestinationResource::normalizePayload(
|
||||
data: $data,
|
||||
record: $record instanceof AlertDestination ? $record : null,
|
||||
);
|
||||
AlertDestinationResource::assertValidConfigPayload($data);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
protected function afterSave(): void
|
||||
{
|
||||
$record = $this->record;
|
||||
|
||||
if (! $record instanceof AlertDestination) {
|
||||
return;
|
||||
}
|
||||
|
||||
AlertDestinationResource::audit($record, AuditActionId::AlertDestinationUpdated, [
|
||||
'alert_destination_id' => (int) $record->getKey(),
|
||||
'name' => (string) $record->name,
|
||||
'type' => (string) $record->type,
|
||||
'is_enabled' => (bool) $record->is_enabled,
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title('Destination updated')
|
||||
->success()
|
||||
->send();
|
||||
}
|
||||
|
||||
private function resolveLastTestStatus(): void
|
||||
{
|
||||
$record = $this->record;
|
||||
|
||||
if (! $record instanceof AlertDestination) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->lastTestStatus = app(AlertDestinationLastTestResolver::class)->resolve($record);
|
||||
}
|
||||
|
||||
private function buildDeepLinkUrl(): ?string
|
||||
{
|
||||
$record = $this->record;
|
||||
|
||||
if (! $record instanceof AlertDestination || $this->lastTestStatus?->deliveryId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$baseUrl = AlertDeliveryResource::getUrl('index');
|
||||
$params = http_build_query([
|
||||
'filters' => [
|
||||
'event_type' => ['value' => 'alerts.test'],
|
||||
'alert_destination_id' => ['value' => (string) $record->getKey()],
|
||||
],
|
||||
]);
|
||||
|
||||
return "{$baseUrl}?{$params}";
|
||||
}
|
||||
}
|
||||
@ -1,32 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\AlertDestinationResource\Pages;
|
||||
|
||||
use App\Filament\Resources\AlertDestinationResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListAlertDestinations extends ListRecords
|
||||
{
|
||||
protected static string $resource = AlertDestinationResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make()
|
||||
->label('Create target')
|
||||
->disabled(fn (): bool => ! AlertDestinationResource::canCreate()),
|
||||
];
|
||||
}
|
||||
|
||||
protected function getTableEmptyStateActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make()
|
||||
->label('Create target')
|
||||
->disabled(fn (): bool => ! AlertDestinationResource::canCreate()),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,154 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\AlertDestinationResource\Pages;
|
||||
|
||||
use App\Filament\Resources\AlertDeliveryResource;
|
||||
use App\Filament\Resources\AlertDestinationResource;
|
||||
use App\Models\AlertDestination;
|
||||
use App\Models\User;
|
||||
use App\Services\Alerts\AlertDestinationLastTestResolver;
|
||||
use App\Services\Alerts\AlertDestinationTestMessageService;
|
||||
use App\Support\Alerts\AlertDestinationLastTestStatus;
|
||||
use App\Support\Badges\BadgeDomain;
|
||||
use App\Support\Badges\BadgeRenderer;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
|
||||
class ViewAlertDestination extends ViewRecord
|
||||
{
|
||||
protected static string $resource = AlertDestinationResource::class;
|
||||
|
||||
private ?AlertDestinationLastTestStatus $lastTestStatus = null;
|
||||
|
||||
public function mount(int|string $record): void
|
||||
{
|
||||
parent::mount($record);
|
||||
$this->resolveLastTestStatus();
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
$user = auth()->user();
|
||||
$record = $this->record;
|
||||
$canManage = $user instanceof User
|
||||
&& $record instanceof AlertDestination
|
||||
&& $user->can('update', $record);
|
||||
|
||||
return [
|
||||
Action::make('send_test_message')
|
||||
->label('Send test message')
|
||||
->icon('heroicon-o-paper-airplane')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Send test message')
|
||||
->modalDescription('A test delivery will be queued for this destination. This verifies the delivery pipeline is working.')
|
||||
->modalSubmitActionLabel('Send')
|
||||
->visible(fn (): bool => $record instanceof AlertDestination)
|
||||
->disabled(fn (): bool => ! $canManage)
|
||||
->action(function () use ($record): void {
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $record instanceof AlertDestination) {
|
||||
return;
|
||||
}
|
||||
|
||||
$service = app(AlertDestinationTestMessageService::class);
|
||||
$result = $service->sendTest($record, $user);
|
||||
|
||||
if ($result['success']) {
|
||||
Notification::make()
|
||||
->title($result['message'])
|
||||
->success()
|
||||
->send();
|
||||
} else {
|
||||
Notification::make()
|
||||
->title($result['message'])
|
||||
->warning()
|
||||
->send();
|
||||
}
|
||||
|
||||
$this->resolveLastTestStatus();
|
||||
}),
|
||||
|
||||
Action::make('view_last_delivery')
|
||||
->label('View last delivery')
|
||||
->icon('heroicon-o-arrow-top-right-on-square')
|
||||
->url(fn (): ?string => $this->buildDeepLinkUrl())
|
||||
->openUrlInNewTab()
|
||||
->visible(fn (): bool => $this->lastTestStatus?->deliveryId !== null),
|
||||
];
|
||||
}
|
||||
|
||||
public function infolist(Schema $schema): Schema
|
||||
{
|
||||
$lastTest = $this->lastTestStatus ?? AlertDestinationLastTestStatus::never();
|
||||
|
||||
return $schema
|
||||
->schema([
|
||||
Section::make('Last test')
|
||||
->schema([
|
||||
TextEntry::make('last_test_status')
|
||||
->label('Status')
|
||||
->badge()
|
||||
->state($lastTest->status->value)
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::AlertDestinationLastTestStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::AlertDestinationLastTestStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::AlertDestinationLastTestStatus)),
|
||||
TextEntry::make('last_test_timestamp')
|
||||
->label('Timestamp')
|
||||
->state($lastTest->timestamp?->toDateTimeString())
|
||||
->placeholder('—'),
|
||||
])
|
||||
->columns(2),
|
||||
Section::make('Details')
|
||||
->schema([
|
||||
TextEntry::make('name'),
|
||||
TextEntry::make('type')
|
||||
->badge()
|
||||
->formatStateUsing(fn (?string $state): string => AlertDestinationResource::typeLabel((string) $state)),
|
||||
TextEntry::make('is_enabled')
|
||||
->label('Enabled')
|
||||
->badge()
|
||||
->formatStateUsing(fn (bool $state): string => $state ? 'Yes' : 'No')
|
||||
->color(fn (bool $state): string => $state ? 'success' : 'gray'),
|
||||
TextEntry::make('created_at')
|
||||
->dateTime(),
|
||||
TextEntry::make('updated_at')
|
||||
->dateTime(),
|
||||
])
|
||||
->columns(2),
|
||||
]);
|
||||
}
|
||||
|
||||
private function resolveLastTestStatus(): void
|
||||
{
|
||||
$record = $this->record;
|
||||
|
||||
if (! $record instanceof AlertDestination) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->lastTestStatus = app(AlertDestinationLastTestResolver::class)->resolve($record);
|
||||
}
|
||||
|
||||
private function buildDeepLinkUrl(): ?string
|
||||
{
|
||||
$record = $this->record;
|
||||
|
||||
if (! $record instanceof AlertDestination || $this->lastTestStatus?->deliveryId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return AlertDeliveryResource::getUrl(panel: 'admin').'?'.http_build_query([
|
||||
'filters' => [
|
||||
'event_type' => ['value' => 'alerts.test'],
|
||||
'alert_destination_id' => ['value' => (string) $record->getKey()],
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1,477 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources;
|
||||
|
||||
use App\Filament\Clusters\Monitoring\AlertsCluster;
|
||||
use App\Filament\Resources\AlertRuleResource\Pages;
|
||||
use App\Models\AlertDestination;
|
||||
use App\Models\AlertRule;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\Audit\WorkspaceAuditLogger;
|
||||
use App\Support\Audit\AuditActionId;
|
||||
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceInspectAffordance;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\ActionGroup;
|
||||
use Filament\Actions\BulkActionGroup;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Arr;
|
||||
use UnitEnum;
|
||||
|
||||
class AlertRuleResource extends Resource
|
||||
{
|
||||
protected static bool $isScopedToTenant = false;
|
||||
|
||||
protected static ?string $model = AlertRule::class;
|
||||
|
||||
protected static ?string $slug = 'alert-rules';
|
||||
|
||||
protected static ?string $cluster = AlertsCluster::class;
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
protected static bool $isGloballySearchable = false;
|
||||
|
||||
protected static ?string $recordTitleAttribute = 'name';
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-funnel';
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Monitoring';
|
||||
|
||||
protected static ?string $navigationLabel = 'Alert rules';
|
||||
|
||||
public static function shouldRegisterNavigation(): bool
|
||||
{
|
||||
if (Filament::getCurrentPanel()?->getId() !== 'admin') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return parent::shouldRegisterNavigation();
|
||||
}
|
||||
|
||||
public static function canViewAny(): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->can('viewAny', AlertRule::class);
|
||||
}
|
||||
|
||||
public static function canCreate(): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->can('create', AlertRule::class);
|
||||
}
|
||||
|
||||
public static function canEdit(Model $record): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $record instanceof AlertRule) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->can('update', $record);
|
||||
}
|
||||
|
||||
public static function canDelete(Model $record): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $record instanceof AlertRule) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->can('delete', $record);
|
||||
}
|
||||
|
||||
public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
|
||||
{
|
||||
return ActionSurfaceDeclaration::forResource(ActionSurfaceProfile::CrudListAndEdit)
|
||||
->satisfy(ActionSurfaceSlot::ListHeader, 'Header actions include capability-gated create.')
|
||||
->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value)
|
||||
->satisfy(ActionSurfaceSlot::ListRowMoreMenu, 'Secondary row actions are grouped under "More".')
|
||||
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'No bulk mutations are exposed for alert rules in v1.')
|
||||
->satisfy(ActionSurfaceSlot::ListEmptyState, 'List page defines an empty-state create CTA.')
|
||||
->satisfy(ActionSurfaceSlot::DetailHeader, 'Edit page provides default save/cancel actions.');
|
||||
}
|
||||
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
|
||||
return parent::getEloquentQuery()
|
||||
->with('destinations')
|
||||
->when(
|
||||
$workspaceId !== null,
|
||||
fn (Builder $query): Builder => $query->where('workspace_id', (int) $workspaceId),
|
||||
)
|
||||
->when(
|
||||
$workspaceId === null,
|
||||
fn (Builder $query): Builder => $query->whereRaw('1 = 0'),
|
||||
);
|
||||
}
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->schema([
|
||||
Section::make('Rule')
|
||||
->schema([
|
||||
TextInput::make('name')
|
||||
->required()
|
||||
->maxLength(255),
|
||||
Toggle::make('is_enabled')
|
||||
->label('Enabled')
|
||||
->default(true),
|
||||
Select::make('event_type')
|
||||
->required()
|
||||
->options(self::eventTypeOptions())
|
||||
->native(false),
|
||||
Select::make('minimum_severity')
|
||||
->required()
|
||||
->options(self::severityOptions())
|
||||
->native(false),
|
||||
]),
|
||||
Section::make('Applies to')
|
||||
->schema([
|
||||
Select::make('tenant_scope_mode')
|
||||
->label('Applies to tenants')
|
||||
->required()
|
||||
->options([
|
||||
AlertRule::TENANT_SCOPE_ALL => 'All tenants',
|
||||
AlertRule::TENANT_SCOPE_ALLOWLIST => 'Selected tenants',
|
||||
])
|
||||
->default(AlertRule::TENANT_SCOPE_ALL)
|
||||
->native(false)
|
||||
->live()
|
||||
->helperText('This rule is workspace-wide. Use this to limit where it applies.'),
|
||||
Select::make('tenant_allowlist')
|
||||
->label('Selected tenants')
|
||||
->multiple()
|
||||
->options(self::tenantOptions())
|
||||
->visible(fn (Get $get): bool => $get('tenant_scope_mode') === AlertRule::TENANT_SCOPE_ALLOWLIST)
|
||||
->native(false)
|
||||
->helperText('Only these tenants will trigger this rule.'),
|
||||
]),
|
||||
Section::make('Delivery')
|
||||
->schema([
|
||||
TextInput::make('cooldown_seconds')
|
||||
->label('Cooldown (seconds)')
|
||||
->numeric()
|
||||
->minValue(0)
|
||||
->nullable(),
|
||||
Toggle::make('quiet_hours_enabled')
|
||||
->label('Enable quiet hours')
|
||||
->default(false)
|
||||
->live(),
|
||||
TextInput::make('quiet_hours_start')
|
||||
->label('Quiet hours start')
|
||||
->type('time')
|
||||
->visible(fn (Get $get): bool => (bool) $get('quiet_hours_enabled')),
|
||||
TextInput::make('quiet_hours_end')
|
||||
->label('Quiet hours end')
|
||||
->type('time')
|
||||
->visible(fn (Get $get): bool => (bool) $get('quiet_hours_enabled')),
|
||||
Select::make('quiet_hours_timezone')
|
||||
->label('Quiet hours timezone')
|
||||
->options(self::timezoneOptions())
|
||||
->searchable()
|
||||
->native(false)
|
||||
->visible(fn (Get $get): bool => (bool) $get('quiet_hours_enabled')),
|
||||
Select::make('destination_ids')
|
||||
->label('Destinations')
|
||||
->multiple()
|
||||
->required()
|
||||
->options(self::destinationOptions())
|
||||
->native(false),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('name')
|
||||
->recordUrl(fn (AlertRule $record): ?string => static::canEdit($record)
|
||||
? static::getUrl('edit', ['record' => $record])
|
||||
: null)
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->searchable(),
|
||||
TextColumn::make('event_type')
|
||||
->label('Event')
|
||||
->badge()
|
||||
->formatStateUsing(fn (?string $state): string => self::eventTypeLabel((string) $state)),
|
||||
TextColumn::make('minimum_severity')
|
||||
->label('Min severity')
|
||||
->badge()
|
||||
->formatStateUsing(fn (?string $state): string => self::severityOptions()[(string) $state] ?? ucfirst((string) $state)),
|
||||
TextColumn::make('destinations_count')
|
||||
->label('Destinations')
|
||||
->counts('destinations'),
|
||||
TextColumn::make('is_enabled')
|
||||
->label('Enabled')
|
||||
->badge()
|
||||
->formatStateUsing(fn (bool $state): string => $state ? 'Yes' : 'No')
|
||||
->color(fn (bool $state): string => $state ? 'success' : 'gray'),
|
||||
])
|
||||
->actions([
|
||||
EditAction::make()
|
||||
->label('Edit')
|
||||
->visible(fn (AlertRule $record): bool => static::canEdit($record)),
|
||||
ActionGroup::make([
|
||||
Action::make('toggle_enabled')
|
||||
->label(fn (AlertRule $record): string => $record->is_enabled ? 'Disable' : 'Enable')
|
||||
->icon(fn (AlertRule $record): string => $record->is_enabled ? 'heroicon-o-pause' : 'heroicon-o-play')
|
||||
->requiresConfirmation()
|
||||
->action(function (AlertRule $record): void {
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $user->can('update', $record)) {
|
||||
throw new AuthorizationException;
|
||||
}
|
||||
|
||||
$enabled = ! (bool) $record->is_enabled;
|
||||
$record->forceFill([
|
||||
'is_enabled' => $enabled,
|
||||
])->save();
|
||||
|
||||
$actionId = $enabled
|
||||
? AuditActionId::AlertRuleEnabled
|
||||
: AuditActionId::AlertRuleDisabled;
|
||||
|
||||
self::audit($record, $actionId, [
|
||||
'alert_rule_id' => (int) $record->getKey(),
|
||||
'name' => (string) $record->name,
|
||||
'event_type' => (string) $record->event_type,
|
||||
'is_enabled' => $enabled,
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title($enabled ? 'Rule enabled' : 'Rule disabled')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
Action::make('delete')
|
||||
->label('Delete')
|
||||
->icon('heroicon-o-trash')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->action(function (AlertRule $record): void {
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $user->can('delete', $record)) {
|
||||
throw new AuthorizationException;
|
||||
}
|
||||
|
||||
self::audit($record, AuditActionId::AlertRuleDeleted, [
|
||||
'alert_rule_id' => (int) $record->getKey(),
|
||||
'name' => (string) $record->name,
|
||||
'event_type' => (string) $record->event_type,
|
||||
]);
|
||||
|
||||
$record->delete();
|
||||
|
||||
Notification::make()
|
||||
->title('Rule deleted')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
])->label('More'),
|
||||
])
|
||||
->bulkActions([
|
||||
BulkActionGroup::make([])->label('More'),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => Pages\ListAlertRules::route('/'),
|
||||
'create' => Pages\CreateAlertRule::route('/create'),
|
||||
'edit' => Pages\EditAlertRule::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function normalizePayload(array $data): array
|
||||
{
|
||||
$tenantAllowlist = Arr::wrap($data['tenant_allowlist'] ?? []);
|
||||
$tenantAllowlist = array_values(array_unique(array_filter(array_map(static fn (mixed $value): int => (int) $value, $tenantAllowlist))));
|
||||
|
||||
if (($data['tenant_scope_mode'] ?? AlertRule::TENANT_SCOPE_ALL) !== AlertRule::TENANT_SCOPE_ALLOWLIST) {
|
||||
$tenantAllowlist = [];
|
||||
}
|
||||
|
||||
$quietHoursEnabled = (bool) ($data['quiet_hours_enabled'] ?? false);
|
||||
|
||||
$data['is_enabled'] = (bool) ($data['is_enabled'] ?? true);
|
||||
$data['tenant_allowlist'] = $tenantAllowlist;
|
||||
$data['cooldown_seconds'] = is_numeric($data['cooldown_seconds'] ?? null) ? (int) $data['cooldown_seconds'] : null;
|
||||
$data['quiet_hours_enabled'] = $quietHoursEnabled;
|
||||
|
||||
if (! $quietHoursEnabled) {
|
||||
$data['quiet_hours_start'] = null;
|
||||
$data['quiet_hours_end'] = null;
|
||||
$data['quiet_hours_timezone'] = null;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, int> $destinationIds
|
||||
*/
|
||||
public static function syncDestinations(AlertRule $record, array $destinationIds): void
|
||||
{
|
||||
$allowedDestinationIds = AlertDestination::query()
|
||||
->where('workspace_id', (int) $record->workspace_id)
|
||||
->whereIn('id', $destinationIds)
|
||||
->pluck('id')
|
||||
->map(static fn (mixed $value): int => (int) $value)
|
||||
->all();
|
||||
|
||||
$record->destinations()->syncWithPivotValues(
|
||||
array_values(array_unique($allowedDestinationIds)),
|
||||
['workspace_id' => (int) $record->workspace_id],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function eventTypeOptions(): array
|
||||
{
|
||||
return [
|
||||
AlertRule::EVENT_HIGH_DRIFT => 'High drift',
|
||||
AlertRule::EVENT_COMPARE_FAILED => 'Compare failed',
|
||||
AlertRule::EVENT_SLA_DUE => 'SLA due',
|
||||
AlertRule::EVENT_PERMISSION_MISSING => 'Permission missing',
|
||||
AlertRule::EVENT_ENTRA_ADMIN_ROLES_HIGH => 'Entra admin roles (high privilege)',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function severityOptions(): array
|
||||
{
|
||||
return [
|
||||
'low' => 'Low',
|
||||
'medium' => 'Medium',
|
||||
'high' => 'High',
|
||||
'critical' => 'Critical',
|
||||
];
|
||||
}
|
||||
|
||||
public static function eventTypeLabel(string $eventType): string
|
||||
{
|
||||
return self::eventTypeOptions()[$eventType] ?? ucfirst(str_replace('_', ' ', $eventType));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private static function destinationOptions(): array
|
||||
{
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
|
||||
if (! is_int($workspaceId)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return AlertDestination::query()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->orderBy('name')
|
||||
->pluck('name', 'id')
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private static function tenantOptions(): array
|
||||
{
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
|
||||
if (! is_int($workspaceId)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Tenant::query()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->where('status', 'active')
|
||||
->orderBy('name')
|
||||
->pluck('name', 'id')
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private static function timezoneOptions(): array
|
||||
{
|
||||
$identifiers = \DateTimeZone::listIdentifiers();
|
||||
sort($identifiers);
|
||||
|
||||
return array_combine($identifiers, $identifiers);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $metadata
|
||||
*/
|
||||
public static function audit(AlertRule $record, AuditActionId $actionId, array $metadata): void
|
||||
{
|
||||
$workspace = $record->workspace;
|
||||
|
||||
if ($workspace === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$actor = auth()->user();
|
||||
|
||||
app(WorkspaceAuditLogger::class)->log(
|
||||
workspace: $workspace,
|
||||
action: $actionId->value,
|
||||
context: [
|
||||
'metadata' => $metadata,
|
||||
],
|
||||
actor: $actor instanceof User ? $actor : null,
|
||||
resourceType: 'alert_rule',
|
||||
resourceId: (string) $record->getKey(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,62 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\AlertRuleResource\Pages;
|
||||
|
||||
use App\Filament\Resources\AlertRuleResource;
|
||||
use App\Models\AlertRule;
|
||||
use App\Support\Audit\AuditActionId;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
class CreateAlertRule extends CreateRecord
|
||||
{
|
||||
protected static string $resource = AlertRuleResource::class;
|
||||
|
||||
/**
|
||||
* @var array<int, int>
|
||||
*/
|
||||
private array $destinationIds = [];
|
||||
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
$workspaceId = app(\App\Support\Workspaces\WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
$data['workspace_id'] = (int) $workspaceId;
|
||||
|
||||
$this->destinationIds = array_values(array_unique(array_filter(array_map(
|
||||
static fn (mixed $value): int => (int) $value,
|
||||
Arr::wrap($data['destination_ids'] ?? []),
|
||||
))));
|
||||
|
||||
unset($data['destination_ids']);
|
||||
|
||||
return AlertRuleResource::normalizePayload($data);
|
||||
}
|
||||
|
||||
protected function afterCreate(): void
|
||||
{
|
||||
$record = $this->record;
|
||||
|
||||
if (! $record instanceof AlertRule) {
|
||||
return;
|
||||
}
|
||||
|
||||
AlertRuleResource::syncDestinations($record, $this->destinationIds);
|
||||
|
||||
AlertRuleResource::audit($record, AuditActionId::AlertRuleCreated, [
|
||||
'alert_rule_id' => (int) $record->getKey(),
|
||||
'name' => (string) $record->name,
|
||||
'event_type' => (string) $record->event_type,
|
||||
'minimum_severity' => (string) $record->minimum_severity,
|
||||
'is_enabled' => (bool) $record->is_enabled,
|
||||
'destination_ids' => $this->destinationIds,
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title('Rule created')
|
||||
->success()
|
||||
->send();
|
||||
}
|
||||
}
|
||||
@ -1,73 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\AlertRuleResource\Pages;
|
||||
|
||||
use App\Filament\Resources\AlertRuleResource;
|
||||
use App\Models\AlertRule;
|
||||
use App\Support\Audit\AuditActionId;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
class EditAlertRule extends EditRecord
|
||||
{
|
||||
protected static string $resource = AlertRuleResource::class;
|
||||
|
||||
/**
|
||||
* @var array<int, int>
|
||||
*/
|
||||
private array $destinationIds = [];
|
||||
|
||||
protected function mutateFormDataBeforeFill(array $data): array
|
||||
{
|
||||
$record = $this->record;
|
||||
|
||||
if ($record instanceof AlertRule) {
|
||||
$data['destination_ids'] = $record->destinations()
|
||||
->pluck('alert_destinations.id')
|
||||
->map(static fn (mixed $value): int => (int) $value)
|
||||
->all();
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
protected function mutateFormDataBeforeSave(array $data): array
|
||||
{
|
||||
$this->destinationIds = array_values(array_unique(array_filter(array_map(
|
||||
static fn (mixed $value): int => (int) $value,
|
||||
Arr::wrap($data['destination_ids'] ?? []),
|
||||
))));
|
||||
|
||||
unset($data['destination_ids']);
|
||||
|
||||
return AlertRuleResource::normalizePayload($data);
|
||||
}
|
||||
|
||||
protected function afterSave(): void
|
||||
{
|
||||
$record = $this->record;
|
||||
|
||||
if (! $record instanceof AlertRule) {
|
||||
return;
|
||||
}
|
||||
|
||||
AlertRuleResource::syncDestinations($record, $this->destinationIds);
|
||||
|
||||
AlertRuleResource::audit($record, AuditActionId::AlertRuleUpdated, [
|
||||
'alert_rule_id' => (int) $record->getKey(),
|
||||
'name' => (string) $record->name,
|
||||
'event_type' => (string) $record->event_type,
|
||||
'minimum_severity' => (string) $record->minimum_severity,
|
||||
'is_enabled' => (bool) $record->is_enabled,
|
||||
'destination_ids' => $this->destinationIds,
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title('Rule updated')
|
||||
->success()
|
||||
->send();
|
||||
}
|
||||
}
|
||||
@ -1,32 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\AlertRuleResource\Pages;
|
||||
|
||||
use App\Filament\Resources\AlertRuleResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListAlertRules extends ListRecords
|
||||
{
|
||||
protected static string $resource = AlertRuleResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make()
|
||||
->label('Create rule')
|
||||
->disabled(fn (): bool => ! AlertRuleResource::canCreate()),
|
||||
];
|
||||
}
|
||||
|
||||
protected function getTableEmptyStateActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make()
|
||||
->label('Create rule')
|
||||
->disabled(fn (): bool => ! AlertRuleResource::canCreate()),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -765,7 +765,7 @@ public static function table(Table $table): Table
|
||||
Action::make('view_runs')
|
||||
->label('View in Operations')
|
||||
->url(OperationRunLinks::index($tenant)),
|
||||
]);
|
||||
])->sendToDatabase($user);
|
||||
}
|
||||
|
||||
$notification->send();
|
||||
@ -862,7 +862,7 @@ public static function table(Table $table): Table
|
||||
Action::make('view_runs')
|
||||
->label('View in Operations')
|
||||
->url(OperationRunLinks::index($tenant)),
|
||||
]);
|
||||
])->sendToDatabase($user);
|
||||
}
|
||||
|
||||
$notification->send();
|
||||
|
||||
@ -36,7 +36,6 @@
|
||||
use Filament\Tables\Contracts\HasTable;
|
||||
use Filament\Tables\Filters\TrashedFilter;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use UnitEnum;
|
||||
|
||||
@ -82,17 +81,6 @@ public static function canCreate(): bool
|
||||
&& $resolver->can($user, $tenant, Capabilities::TENANT_SYNC);
|
||||
}
|
||||
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
$tenant = Filament::getTenant();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return parent::getEloquentQuery()->whereRaw('1 = 0');
|
||||
}
|
||||
|
||||
return parent::getEloquentQuery()->where('tenant_id', (int) $tenant->getKey());
|
||||
}
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
|
||||
@ -18,6 +18,7 @@
|
||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||
use App\Support\Rbac\UiEnforcement;
|
||||
use Filament\Actions;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Tables;
|
||||
use Filament\Tables\Table;
|
||||
@ -104,9 +105,10 @@ public function table(Table $table): Table
|
||||
);
|
||||
|
||||
if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'], true)) {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
|
||||
Notification::make()
|
||||
->title('Removal already queued')
|
||||
->body('A matching remove operation is already queued or running.')
|
||||
->info()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -194,9 +196,10 @@ public function table(Table $table): Table
|
||||
);
|
||||
|
||||
if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'], true)) {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
|
||||
Notification::make()
|
||||
->title('Removal already queued')
|
||||
->body('A matching remove operation is already queued or running.')
|
||||
->info()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
|
||||
@ -1,410 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources;
|
||||
|
||||
use App\Filament\Resources\BaselineProfileResource\Pages;
|
||||
use App\Models\BaselineProfile;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Services\Audit\WorkspaceAuditLogger;
|
||||
use App\Support\Audit\AuditActionId;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\Badges\BadgeDomain;
|
||||
use App\Support\Badges\BadgeRenderer;
|
||||
use App\Support\Inventory\InventoryPolicyTypeMeta;
|
||||
use App\Support\Rbac\WorkspaceUiEnforcement;
|
||||
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceInspectAffordance;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\ActionGroup;
|
||||
use Filament\Actions\BulkActionGroup;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use UnitEnum;
|
||||
|
||||
class BaselineProfileResource extends Resource
|
||||
{
|
||||
protected static bool $isScopedToTenant = false;
|
||||
|
||||
protected static ?string $model = BaselineProfile::class;
|
||||
|
||||
protected static ?string $slug = 'baseline-profiles';
|
||||
|
||||
protected static bool $isGloballySearchable = false;
|
||||
|
||||
protected static ?string $recordTitleAttribute = 'name';
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-shield-check';
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Governance';
|
||||
|
||||
protected static ?string $navigationLabel = 'Baselines';
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
public static function shouldRegisterNavigation(): bool
|
||||
{
|
||||
if (Filament::getCurrentPanel()?->getId() !== 'admin') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return parent::shouldRegisterNavigation();
|
||||
}
|
||||
|
||||
public static function canViewAny(): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$workspace = self::resolveWorkspace();
|
||||
|
||||
if (! $workspace instanceof Workspace) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$resolver = app(\App\Services\Auth\WorkspaceCapabilityResolver::class);
|
||||
|
||||
return $resolver->isMember($user, $workspace)
|
||||
&& $resolver->can($user, $workspace, Capabilities::WORKSPACE_BASELINES_VIEW);
|
||||
}
|
||||
|
||||
public static function canCreate(): bool
|
||||
{
|
||||
return self::hasManageCapability();
|
||||
}
|
||||
|
||||
public static function canEdit(Model $record): bool
|
||||
{
|
||||
return self::hasManageCapability();
|
||||
}
|
||||
|
||||
public static function canDelete(Model $record): bool
|
||||
{
|
||||
return self::hasManageCapability();
|
||||
}
|
||||
|
||||
public static function canView(Model $record): bool
|
||||
{
|
||||
return self::canViewAny();
|
||||
}
|
||||
|
||||
public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
|
||||
{
|
||||
return ActionSurfaceDeclaration::forResource(ActionSurfaceProfile::CrudListAndView)
|
||||
->satisfy(ActionSurfaceSlot::ListHeader, 'Header action: Create baseline profile (capability-gated).')
|
||||
->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ViewAction->value)
|
||||
->satisfy(ActionSurfaceSlot::ListRowMoreMenu, 'Secondary row actions (edit, archive) under "More".')
|
||||
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'No bulk mutations for baseline profiles in v1.')
|
||||
->satisfy(ActionSurfaceSlot::ListEmptyState, 'List defines empty-state create CTA.')
|
||||
->satisfy(ActionSurfaceSlot::DetailHeader, 'View page provides capture + edit actions.');
|
||||
}
|
||||
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
|
||||
return parent::getEloquentQuery()
|
||||
->with(['activeSnapshot', 'createdByUser'])
|
||||
->when(
|
||||
$workspaceId !== null,
|
||||
fn (Builder $query): Builder => $query->where('workspace_id', (int) $workspaceId),
|
||||
)
|
||||
->when(
|
||||
$workspaceId === null,
|
||||
fn (Builder $query): Builder => $query->whereRaw('1 = 0'),
|
||||
);
|
||||
}
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->schema([
|
||||
Section::make('Profile')
|
||||
->schema([
|
||||
TextInput::make('name')
|
||||
->required()
|
||||
->maxLength(255)
|
||||
->helperText('A descriptive name for this baseline profile.'),
|
||||
Textarea::make('description')
|
||||
->rows(3)
|
||||
->maxLength(1000)
|
||||
->helperText('Explain the purpose and scope of this baseline.'),
|
||||
TextInput::make('version_label')
|
||||
->label('Version label')
|
||||
->maxLength(50)
|
||||
->placeholder('e.g. v2.1 — February rollout')
|
||||
->helperText('Optional label to identify this version.'),
|
||||
Select::make('status')
|
||||
->required()
|
||||
->options([
|
||||
BaselineProfile::STATUS_DRAFT => 'Draft',
|
||||
BaselineProfile::STATUS_ACTIVE => 'Active',
|
||||
BaselineProfile::STATUS_ARCHIVED => 'Archived',
|
||||
])
|
||||
->default(BaselineProfile::STATUS_DRAFT)
|
||||
->native(false)
|
||||
->helperText('Only active baselines are enforced during compliance checks.'),
|
||||
])
|
||||
->columns(2)
|
||||
->columnSpanFull(),
|
||||
Section::make('Scope')
|
||||
->schema([
|
||||
Select::make('scope_jsonb.policy_types')
|
||||
->label('Policy type scope')
|
||||
->multiple()
|
||||
->options(self::policyTypeOptions())
|
||||
->helperText('Leave empty to include all policy types.')
|
||||
->native(false),
|
||||
])
|
||||
->columnSpanFull(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function infolist(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->schema([
|
||||
Section::make('Profile')
|
||||
->schema([
|
||||
TextEntry::make('name'),
|
||||
TextEntry::make('status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::BaselineProfileStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::BaselineProfileStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::BaselineProfileStatus)),
|
||||
TextEntry::make('version_label')
|
||||
->label('Version')
|
||||
->placeholder('—'),
|
||||
TextEntry::make('description')
|
||||
->placeholder('No description')
|
||||
->columnSpanFull(),
|
||||
])
|
||||
->columns(2)
|
||||
->columnSpanFull(),
|
||||
Section::make('Scope')
|
||||
->schema([
|
||||
TextEntry::make('scope_jsonb.policy_types')
|
||||
->label('Policy type scope')
|
||||
->badge()
|
||||
->formatStateUsing(function (string $state): string {
|
||||
$options = self::policyTypeOptions();
|
||||
|
||||
return $options[$state] ?? $state;
|
||||
})
|
||||
->placeholder('All policy types'),
|
||||
])
|
||||
->columnSpanFull(),
|
||||
Section::make('Metadata')
|
||||
->schema([
|
||||
TextEntry::make('createdByUser.name')
|
||||
->label('Created by')
|
||||
->placeholder('—'),
|
||||
TextEntry::make('activeSnapshot.captured_at')
|
||||
->label('Last snapshot')
|
||||
->dateTime()
|
||||
->placeholder('No snapshot yet'),
|
||||
TextEntry::make('created_at')
|
||||
->dateTime(),
|
||||
TextEntry::make('updated_at')
|
||||
->dateTime(),
|
||||
])
|
||||
->columns(2)
|
||||
->columnSpanFull(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
$workspace = self::resolveWorkspace();
|
||||
|
||||
return $table
|
||||
->defaultSort('name')
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->searchable()
|
||||
->sortable(),
|
||||
TextColumn::make('status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::BaselineProfileStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::BaselineProfileStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::BaselineProfileStatus))
|
||||
->sortable(),
|
||||
TextColumn::make('version_label')
|
||||
->label('Version')
|
||||
->placeholder('—'),
|
||||
TextColumn::make('activeSnapshot.captured_at')
|
||||
->label('Last snapshot')
|
||||
->dateTime()
|
||||
->placeholder('No snapshot'),
|
||||
TextColumn::make('created_at')
|
||||
->dateTime()
|
||||
->sortable()
|
||||
->toggleable(isToggledHiddenByDefault: true),
|
||||
])
|
||||
->actions([
|
||||
Action::make('view')
|
||||
->label('View')
|
||||
->url(fn (BaselineProfile $record): string => static::getUrl('view', ['record' => $record]))
|
||||
->icon('heroicon-o-eye'),
|
||||
ActionGroup::make([
|
||||
Action::make('edit')
|
||||
->label('Edit')
|
||||
->url(fn (BaselineProfile $record): string => static::getUrl('edit', ['record' => $record]))
|
||||
->icon('heroicon-o-pencil-square')
|
||||
->visible(fn (): bool => self::hasManageCapability()),
|
||||
self::archiveTableAction($workspace),
|
||||
])->label('More'),
|
||||
])
|
||||
->bulkActions([
|
||||
BulkActionGroup::make([])->label('More'),
|
||||
])
|
||||
->emptyStateHeading('No baseline profiles')
|
||||
->emptyStateDescription('Create a baseline profile to define what "good" looks like for your tenants.')
|
||||
->emptyStateActions([
|
||||
Action::make('create')
|
||||
->label('Create baseline profile')
|
||||
->url(fn (): string => static::getUrl('create'))
|
||||
->icon('heroicon-o-plus')
|
||||
->visible(fn (): bool => self::hasManageCapability()),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
BaselineProfileResource\RelationManagers\BaselineTenantAssignmentsRelationManager::class,
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => Pages\ListBaselineProfiles::route('/'),
|
||||
'create' => Pages\CreateBaselineProfile::route('/create'),
|
||||
'view' => Pages\ViewBaselineProfile::route('/{record}'),
|
||||
'edit' => Pages\EditBaselineProfile::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function policyTypeOptions(): array
|
||||
{
|
||||
return collect(InventoryPolicyTypeMeta::all())
|
||||
->filter(fn (array $row): bool => filled($row['type'] ?? null))
|
||||
->mapWithKeys(fn (array $row): array => [
|
||||
(string) $row['type'] => (string) ($row['label'] ?? $row['type']),
|
||||
])
|
||||
->sort()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $metadata
|
||||
*/
|
||||
public static function audit(BaselineProfile $record, AuditActionId $actionId, array $metadata): void
|
||||
{
|
||||
$workspace = $record->workspace;
|
||||
|
||||
if ($workspace === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$actor = auth()->user();
|
||||
|
||||
app(WorkspaceAuditLogger::class)->log(
|
||||
workspace: $workspace,
|
||||
action: $actionId->value,
|
||||
context: ['metadata' => $metadata],
|
||||
actor: $actor instanceof User ? $actor : null,
|
||||
resourceType: 'baseline_profile',
|
||||
resourceId: (string) $record->getKey(),
|
||||
);
|
||||
}
|
||||
|
||||
private static function resolveWorkspace(): ?Workspace
|
||||
{
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
|
||||
if ($workspaceId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Workspace::query()->whereKey($workspaceId)->first();
|
||||
}
|
||||
|
||||
private static function hasManageCapability(): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
$workspace = self::resolveWorkspace();
|
||||
|
||||
if (! $user instanceof User || ! $workspace instanceof Workspace) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$resolver = app(\App\Services\Auth\WorkspaceCapabilityResolver::class);
|
||||
|
||||
return $resolver->isMember($user, $workspace)
|
||||
&& $resolver->can($user, $workspace, Capabilities::WORKSPACE_BASELINES_MANAGE);
|
||||
}
|
||||
|
||||
private static function archiveTableAction(?Workspace $workspace): Action
|
||||
{
|
||||
$action = Action::make('archive')
|
||||
->label('Archive')
|
||||
->icon('heroicon-o-archive-box')
|
||||
->color('warning')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Archive baseline profile')
|
||||
->modalDescription('Archiving is permanent in v1. This profile can no longer be used for captures or compares.')
|
||||
->visible(fn (BaselineProfile $record): bool => $record->status !== BaselineProfile::STATUS_ARCHIVED && self::hasManageCapability())
|
||||
->action(function (BaselineProfile $record): void {
|
||||
if (! self::hasManageCapability()) {
|
||||
throw new AuthorizationException;
|
||||
}
|
||||
|
||||
$record->forceFill(['status' => BaselineProfile::STATUS_ARCHIVED])->save();
|
||||
|
||||
self::audit($record, AuditActionId::BaselineProfileArchived, [
|
||||
'baseline_profile_id' => (int) $record->getKey(),
|
||||
'name' => (string) $record->name,
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title('Baseline profile archived')
|
||||
->success()
|
||||
->send();
|
||||
});
|
||||
|
||||
if ($workspace instanceof Workspace) {
|
||||
$action = WorkspaceUiEnforcement::forTableAction($action, $workspace)
|
||||
->requireCapability(Capabilities::WORKSPACE_BASELINES_MANAGE)
|
||||
->destructive()
|
||||
->apply();
|
||||
}
|
||||
|
||||
return $action;
|
||||
}
|
||||
}
|
||||
@ -1,56 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\BaselineProfileResource\Pages;
|
||||
|
||||
use App\Filament\Resources\BaselineProfileResource;
|
||||
use App\Models\BaselineProfile;
|
||||
use App\Models\User;
|
||||
use App\Support\Audit\AuditActionId;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateBaselineProfile extends CreateRecord
|
||||
{
|
||||
protected static string $resource = BaselineProfileResource::class;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
$data['workspace_id'] = (int) $workspaceId;
|
||||
|
||||
$user = auth()->user();
|
||||
$data['created_by_user_id'] = $user instanceof User ? $user->getKey() : null;
|
||||
|
||||
$policyTypes = $data['scope_jsonb']['policy_types'] ?? [];
|
||||
$data['scope_jsonb'] = ['policy_types' => is_array($policyTypes) ? array_values($policyTypes) : []];
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
protected function afterCreate(): void
|
||||
{
|
||||
$record = $this->record;
|
||||
|
||||
if (! $record instanceof BaselineProfile) {
|
||||
return;
|
||||
}
|
||||
|
||||
BaselineProfileResource::audit($record, AuditActionId::BaselineProfileCreated, [
|
||||
'baseline_profile_id' => (int) $record->getKey(),
|
||||
'name' => (string) $record->name,
|
||||
'status' => (string) $record->status,
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title('Baseline profile created')
|
||||
->success()
|
||||
->send();
|
||||
}
|
||||
}
|
||||
@ -1,48 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\BaselineProfileResource\Pages;
|
||||
|
||||
use App\Filament\Resources\BaselineProfileResource;
|
||||
use App\Models\BaselineProfile;
|
||||
use App\Support\Audit\AuditActionId;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditBaselineProfile extends EditRecord
|
||||
{
|
||||
protected static string $resource = BaselineProfileResource::class;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeSave(array $data): array
|
||||
{
|
||||
$policyTypes = $data['scope_jsonb']['policy_types'] ?? [];
|
||||
$data['scope_jsonb'] = ['policy_types' => is_array($policyTypes) ? array_values($policyTypes) : []];
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
protected function afterSave(): void
|
||||
{
|
||||
$record = $this->record;
|
||||
|
||||
if (! $record instanceof BaselineProfile) {
|
||||
return;
|
||||
}
|
||||
|
||||
BaselineProfileResource::audit($record, AuditActionId::BaselineProfileUpdated, [
|
||||
'baseline_profile_id' => (int) $record->getKey(),
|
||||
'name' => (string) $record->name,
|
||||
'status' => (string) $record->status,
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title('Baseline profile updated')
|
||||
->success()
|
||||
->send();
|
||||
}
|
||||
}
|
||||
@ -1,24 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\BaselineProfileResource\Pages;
|
||||
|
||||
use App\Filament\Resources\BaselineProfileResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListBaselineProfiles extends ListRecords
|
||||
{
|
||||
protected static string $resource = BaselineProfileResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make()
|
||||
->label('Create baseline profile')
|
||||
->disabled(fn (): bool => ! BaselineProfileResource::canCreate())
|
||||
->visible(fn (): bool => $this->getTableRecords()->count() > 0),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,171 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\BaselineProfileResource\Pages;
|
||||
|
||||
use App\Filament\Resources\BaselineProfileResource;
|
||||
use App\Models\BaselineProfile;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Services\Baselines\BaselineCaptureService;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\OperationRunLinks;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
|
||||
class ViewBaselineProfile extends ViewRecord
|
||||
{
|
||||
protected static string $resource = BaselineProfileResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
$this->captureAction(),
|
||||
EditAction::make()
|
||||
->visible(fn (): bool => $this->hasManageCapability()),
|
||||
];
|
||||
}
|
||||
|
||||
private function captureAction(): Action
|
||||
{
|
||||
return Action::make('capture')
|
||||
->label('Capture Snapshot')
|
||||
->icon('heroicon-o-camera')
|
||||
->color('primary')
|
||||
->visible(fn (): bool => $this->hasManageCapability())
|
||||
->disabled(fn (): bool => ! $this->hasManageCapability())
|
||||
->tooltip(fn (): ?string => ! $this->hasManageCapability() ? 'You need manage permission to capture snapshots.' : null)
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Capture Baseline Snapshot')
|
||||
->modalDescription('Select the source tenant whose current inventory will be captured as the baseline snapshot.')
|
||||
->form([
|
||||
Select::make('source_tenant_id')
|
||||
->label('Source Tenant')
|
||||
->options(fn (): array => $this->getWorkspaceTenantOptions())
|
||||
->required()
|
||||
->searchable(),
|
||||
])
|
||||
->action(function (array $data): void {
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $this->hasManageCapability()) {
|
||||
Notification::make()
|
||||
->title('Permission denied')
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var BaselineProfile $profile */
|
||||
$profile = $this->getRecord();
|
||||
$sourceTenant = Tenant::query()->find((int) $data['source_tenant_id']);
|
||||
|
||||
if (! $sourceTenant instanceof Tenant) {
|
||||
Notification::make()
|
||||
->title('Source tenant not found')
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$service = app(BaselineCaptureService::class);
|
||||
$result = $service->startCapture($profile, $sourceTenant, $user);
|
||||
|
||||
if (! $result['ok']) {
|
||||
Notification::make()
|
||||
->title('Cannot start capture')
|
||||
->body('Reason: '.str_replace('.', ' ', (string) ($result['reason_code'] ?? 'unknown')))
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$run = $result['run'] ?? null;
|
||||
|
||||
if (! $run instanceof \App\Models\OperationRun) {
|
||||
Notification::make()
|
||||
->title('Cannot start capture')
|
||||
->body('Reason: missing operation run')
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$viewAction = Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(OperationRunLinks::view($run, $sourceTenant));
|
||||
|
||||
if (! $run->wasRecentlyCreated && in_array((string) $run->status, ['queued', 'running'], true)) {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $run->type)
|
||||
->actions([$viewAction])
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $run->type)
|
||||
->actions([$viewAction])
|
||||
->send();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function getWorkspaceTenantOptions(): array
|
||||
{
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
|
||||
if ($workspaceId === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Tenant::query()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->orderBy('name')
|
||||
->pluck('name', 'id')
|
||||
->all();
|
||||
}
|
||||
|
||||
private function hasManageCapability(): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
|
||||
if ($workspaceId === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$workspace = Workspace::query()->whereKey($workspaceId)->first();
|
||||
|
||||
if (! $workspace instanceof Workspace) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$resolver = app(\App\Services\Auth\WorkspaceCapabilityResolver::class);
|
||||
|
||||
return $resolver->isMember($user, $workspace)
|
||||
&& $resolver->can($user, $workspace, Capabilities::WORKSPACE_BASELINES_MANAGE);
|
||||
}
|
||||
}
|
||||
@ -1,246 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\BaselineProfileResource\RelationManagers;
|
||||
|
||||
use App\Models\BaselineProfile;
|
||||
use App\Models\BaselineTenantAssignment;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Services\Audit\WorkspaceAuditLogger;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceInspectAffordance;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Tables;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class BaselineTenantAssignmentsRelationManager extends RelationManager
|
||||
{
|
||||
protected static string $relationship = 'tenantAssignments';
|
||||
|
||||
protected static ?string $title = 'Tenant assignments';
|
||||
|
||||
public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
|
||||
{
|
||||
return ActionSurfaceDeclaration::forRelationManager(ActionSurfaceProfile::RelationManager)
|
||||
->satisfy(ActionSurfaceSlot::ListHeader, 'Header action: Assign tenant (manage-gated).')
|
||||
->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value)
|
||||
->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'v1 assignments have no row-level actions beyond delete.')
|
||||
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'No bulk mutations for assignments in v1.')
|
||||
->satisfy(ActionSurfaceSlot::ListEmptyState, 'Empty state encourages assigning a tenant.');
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
Tables\Columns\TextColumn::make('tenant.name')
|
||||
->label('Tenant')
|
||||
->searchable(),
|
||||
Tables\Columns\TextColumn::make('assignedByUser.name')
|
||||
->label('Assigned by')
|
||||
->placeholder('—'),
|
||||
Tables\Columns\TextColumn::make('created_at')
|
||||
->label('Assigned at')
|
||||
->dateTime()
|
||||
->sortable(),
|
||||
])
|
||||
->headerActions([
|
||||
$this->assignTenantAction(),
|
||||
])
|
||||
->actions([
|
||||
$this->removeAssignmentAction(),
|
||||
])
|
||||
->emptyStateHeading('No tenants assigned')
|
||||
->emptyStateDescription('Assign a tenant to compare its state against this baseline profile.')
|
||||
->emptyStateActions([
|
||||
$this->assignTenantAction(),
|
||||
]);
|
||||
}
|
||||
|
||||
private function assignTenantAction(): Action
|
||||
{
|
||||
return Action::make('assign')
|
||||
->label('Assign Tenant')
|
||||
->icon('heroicon-o-plus')
|
||||
->visible(fn (): bool => $this->hasManageCapability())
|
||||
->form([
|
||||
Select::make('tenant_id')
|
||||
->label('Tenant')
|
||||
->options(fn (): array => $this->getAvailableTenantOptions())
|
||||
->required()
|
||||
->searchable(),
|
||||
])
|
||||
->action(function (array $data): void {
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $this->hasManageCapability()) {
|
||||
Notification::make()
|
||||
->title('Permission denied')
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var BaselineProfile $profile */
|
||||
$profile = $this->getOwnerRecord();
|
||||
$tenantId = (int) $data['tenant_id'];
|
||||
|
||||
$existing = BaselineTenantAssignment::query()
|
||||
->where('workspace_id', $profile->workspace_id)
|
||||
->where('tenant_id', $tenantId)
|
||||
->first();
|
||||
|
||||
if ($existing instanceof BaselineTenantAssignment) {
|
||||
Notification::make()
|
||||
->title('Tenant already assigned')
|
||||
->body('This tenant already has a baseline assignment in this workspace.')
|
||||
->warning()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$assignment = BaselineTenantAssignment::create([
|
||||
'workspace_id' => (int) $profile->workspace_id,
|
||||
'tenant_id' => $tenantId,
|
||||
'baseline_profile_id' => (int) $profile->getKey(),
|
||||
'assigned_by_user_id' => (int) $user->getKey(),
|
||||
]);
|
||||
|
||||
$this->auditAssignment($profile, $assignment, $user, 'created');
|
||||
|
||||
Notification::make()
|
||||
->title('Tenant assigned')
|
||||
->success()
|
||||
->send();
|
||||
});
|
||||
}
|
||||
|
||||
private function removeAssignmentAction(): Action
|
||||
{
|
||||
return Action::make('remove')
|
||||
->label('Remove')
|
||||
->icon('heroicon-o-trash')
|
||||
->color('danger')
|
||||
->visible(fn (): bool => $this->hasManageCapability())
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Remove tenant assignment')
|
||||
->modalDescription('Are you sure you want to remove this tenant assignment? This will not delete any existing findings.')
|
||||
->action(function (BaselineTenantAssignment $record): void {
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $this->hasManageCapability()) {
|
||||
Notification::make()
|
||||
->title('Permission denied')
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var BaselineProfile $profile */
|
||||
$profile = $this->getOwnerRecord();
|
||||
|
||||
$this->auditAssignment($profile, $record, $user, 'removed');
|
||||
|
||||
$record->delete();
|
||||
|
||||
Notification::make()
|
||||
->title('Assignment removed')
|
||||
->success()
|
||||
->send();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function getAvailableTenantOptions(): array
|
||||
{
|
||||
/** @var BaselineProfile $profile */
|
||||
$profile = $this->getOwnerRecord();
|
||||
|
||||
$assignedTenantIds = BaselineTenantAssignment::query()
|
||||
->where('workspace_id', $profile->workspace_id)
|
||||
->pluck('tenant_id')
|
||||
->all();
|
||||
|
||||
$query = Tenant::query()
|
||||
->where('workspace_id', $profile->workspace_id)
|
||||
->orderBy('name');
|
||||
|
||||
if (! empty($assignedTenantIds)) {
|
||||
$query->whereNotIn('id', $assignedTenantIds);
|
||||
}
|
||||
|
||||
return $query->pluck('name', 'id')->all();
|
||||
}
|
||||
|
||||
private function auditAssignment(
|
||||
BaselineProfile $profile,
|
||||
BaselineTenantAssignment $assignment,
|
||||
User $user,
|
||||
string $action,
|
||||
): void {
|
||||
$workspace = Workspace::query()->find($profile->workspace_id);
|
||||
|
||||
if (! $workspace instanceof Workspace) {
|
||||
return;
|
||||
}
|
||||
|
||||
$tenant = Tenant::query()->find($assignment->tenant_id);
|
||||
|
||||
$auditLogger = app(WorkspaceAuditLogger::class);
|
||||
|
||||
$auditLogger->log(
|
||||
workspace: $workspace,
|
||||
action: 'baseline.assignment.'.$action,
|
||||
context: [
|
||||
'baseline_profile_id' => (int) $profile->getKey(),
|
||||
'baseline_profile_name' => (string) $profile->name,
|
||||
'tenant_id' => (int) $assignment->tenant_id,
|
||||
'tenant_name' => $tenant instanceof Tenant ? (string) $tenant->display_name : '—',
|
||||
],
|
||||
actor: $user,
|
||||
resourceType: 'baseline_profile',
|
||||
resourceId: (string) $profile->getKey(),
|
||||
);
|
||||
}
|
||||
|
||||
private function hasManageCapability(): bool
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
|
||||
if ($workspaceId === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$workspace = Workspace::query()->whereKey($workspaceId)->first();
|
||||
|
||||
if (! $workspace instanceof Workspace) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$resolver = app(\App\Services\Auth\WorkspaceCapabilityResolver::class);
|
||||
|
||||
return $resolver->isMember($user, $workspace)
|
||||
&& $resolver->can($user, $workspace, Capabilities::WORKSPACE_BASELINES_MANAGE);
|
||||
}
|
||||
}
|
||||
@ -10,10 +10,9 @@
|
||||
use App\Services\OperationRunService;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\OperationRunLinks;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||
use App\Support\Rbac\UiEnforcement;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListEntraGroups extends ListRecords
|
||||
@ -32,7 +31,7 @@ protected function getHeaderActions(): array
|
||||
Action::make('sync_groups')
|
||||
->label('Sync Groups')
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->color('primary')
|
||||
->color('warning')
|
||||
->action(function (): void {
|
||||
$user = auth()->user();
|
||||
$tenant = Tenant::current();
|
||||
@ -58,8 +57,10 @@ protected function getHeaderActions(): array
|
||||
);
|
||||
|
||||
if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'])) {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
|
||||
Notification::make()
|
||||
->title('Group sync already active')
|
||||
->body('This operation is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View Run')
|
||||
@ -79,13 +80,16 @@ protected function getHeaderActions(): array
|
||||
operationRun: $opRun
|
||||
));
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
OperationUxPresenter::queuedToast((string) $opRun->type)
|
||||
Notification::make()
|
||||
->title('Group sync started')
|
||||
->body('Sync dispatched.')
|
||||
->success()
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View Run')
|
||||
->url(OperationRunLinks::view($opRun, $tenant)),
|
||||
])
|
||||
->sendToDatabase($user)
|
||||
->send();
|
||||
})
|
||||
)
|
||||
|
||||
@ -7,10 +7,8 @@
|
||||
use App\Models\InventoryItem;
|
||||
use App\Models\PolicyVersion;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantMembership;
|
||||
use App\Models\User;
|
||||
use App\Services\Drift\DriftFindingDiffBuilder;
|
||||
use App\Services\Findings\FindingWorkflowService;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\Badges\BadgeDomain;
|
||||
use App\Support\Badges\BadgeRenderer;
|
||||
@ -25,8 +23,6 @@
|
||||
use Filament\Actions\BulkAction;
|
||||
use Filament\Actions\BulkActionGroup;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Infolists\Components\ViewEntry;
|
||||
@ -40,8 +36,6 @@
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Collection;
|
||||
use InvalidArgumentException;
|
||||
use Throwable;
|
||||
use UnitEnum;
|
||||
|
||||
class FindingResource extends Resource
|
||||
@ -52,7 +46,7 @@ class FindingResource extends Resource
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-exclamation-triangle';
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Governance';
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Drift';
|
||||
|
||||
protected static ?string $navigationLabel = 'Findings';
|
||||
|
||||
@ -70,7 +64,7 @@ public static function canViewAny(): bool
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->can(Capabilities::TENANT_FINDINGS_VIEW, $tenant);
|
||||
return $user->can(Capabilities::TENANT_VIEW, $tenant);
|
||||
}
|
||||
|
||||
public static function canView(Model $record): bool
|
||||
@ -87,7 +81,7 @@ public static function canView(Model $record): bool
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! $user->can(Capabilities::TENANT_FINDINGS_VIEW, $tenant)) {
|
||||
if (! $user->can(Capabilities::TENANT_VIEW, $tenant)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -101,12 +95,12 @@ public static function canView(Model $record): bool
|
||||
public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
|
||||
{
|
||||
return ActionSurfaceDeclaration::forResource(ActionSurfaceProfile::CrudListAndView)
|
||||
->satisfy(ActionSurfaceSlot::ListHeader, 'Header actions support filtered findings operations (legacy acknowledge-all-matching remains until bulk workflow migration).')
|
||||
->satisfy(ActionSurfaceSlot::ListHeader, 'Header action supports acknowledging all matching findings.')
|
||||
->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ViewAction->value)
|
||||
->satisfy(ActionSurfaceSlot::ListRowMoreMenu, 'Secondary row actions are grouped under "More".')
|
||||
->satisfy(ActionSurfaceSlot::ListBulkMoreGroup, 'Bulk actions are grouped under "More".')
|
||||
->exempt(ActionSurfaceSlot::ListEmptyState, 'Findings are generated by drift detection and intentionally have no create CTA.')
|
||||
->satisfy(ActionSurfaceSlot::DetailHeader, 'View page exposes capability-gated workflow actions for finding lifecycle management.');
|
||||
->exempt(ActionSurfaceSlot::DetailHeader, 'View page intentionally has no additional header actions.');
|
||||
}
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
@ -152,34 +146,12 @@ public static function infolist(Schema $schema): Schema
|
||||
->openUrlInNewTab(),
|
||||
TextEntry::make('acknowledged_at')->dateTime()->placeholder('—'),
|
||||
TextEntry::make('acknowledged_by_user_id')->label('Acknowledged by')->placeholder('—'),
|
||||
TextEntry::make('first_seen_at')->label('First seen')->dateTime()->placeholder('—'),
|
||||
TextEntry::make('last_seen_at')->label('Last seen')->dateTime()->placeholder('—'),
|
||||
TextEntry::make('times_seen')->label('Times seen')->placeholder('—'),
|
||||
TextEntry::make('sla_days')->label('SLA days')->placeholder('—'),
|
||||
TextEntry::make('due_at')->label('Due at')->dateTime()->placeholder('—'),
|
||||
TextEntry::make('owner_user_id')
|
||||
->label('Owner')
|
||||
->formatStateUsing(fn (mixed $state, Finding $record): string => $record->ownerUser?->name ?? ($state ? 'User #'.$state : '—')),
|
||||
TextEntry::make('assignee_user_id')
|
||||
->label('Assignee')
|
||||
->formatStateUsing(fn (mixed $state, Finding $record): string => $record->assigneeUser?->name ?? ($state ? 'User #'.$state : '—')),
|
||||
TextEntry::make('triaged_at')->label('Triaged at')->dateTime()->placeholder('—'),
|
||||
TextEntry::make('in_progress_at')->label('In progress at')->dateTime()->placeholder('—'),
|
||||
TextEntry::make('reopened_at')->label('Reopened at')->dateTime()->placeholder('—'),
|
||||
TextEntry::make('resolved_at')->label('Resolved at')->dateTime()->placeholder('—'),
|
||||
TextEntry::make('resolved_reason')->label('Resolved reason')->placeholder('—'),
|
||||
TextEntry::make('closed_at')->label('Closed at')->dateTime()->placeholder('—'),
|
||||
TextEntry::make('closed_reason')->label('Closed/risk reason')->placeholder('—'),
|
||||
TextEntry::make('closed_by_user_id')
|
||||
->label('Closed by')
|
||||
->formatStateUsing(fn (mixed $state, Finding $record): string => $record->closedByUser?->name ?? ($state ? 'User #'.$state : '—')),
|
||||
TextEntry::make('created_at')->label('Created')->dateTime(),
|
||||
])
|
||||
->columns(2)
|
||||
->columnSpanFull(),
|
||||
|
||||
Section::make('Diff')
|
||||
->visible(fn (Finding $record): bool => $record->finding_type === Finding::FINDING_TYPE_DRIFT)
|
||||
->schema([
|
||||
ViewEntry::make('settings_diff')
|
||||
->label('')
|
||||
@ -305,65 +277,22 @@ public static function table(Table $table): Table
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::FindingSeverity)),
|
||||
Tables\Columns\TextColumn::make('subject_display_name')->label('Subject')->placeholder('—'),
|
||||
Tables\Columns\TextColumn::make('subject_type')->label('Subject type')->searchable(),
|
||||
Tables\Columns\TextColumn::make('due_at')
|
||||
->label('Due')
|
||||
->dateTime()
|
||||
->sortable()
|
||||
->placeholder('—'),
|
||||
Tables\Columns\TextColumn::make('assigneeUser.name')
|
||||
->label('Assignee')
|
||||
->placeholder('—'),
|
||||
Tables\Columns\TextColumn::make('subject_external_id')->label('External ID')->toggleable(isToggledHiddenByDefault: true),
|
||||
Tables\Columns\TextColumn::make('scope_key')->label('Scope')->toggleable(isToggledHiddenByDefault: true),
|
||||
Tables\Columns\TextColumn::make('created_at')->since()->label('Created'),
|
||||
])
|
||||
->filters([
|
||||
Tables\Filters\Filter::make('open')
|
||||
->label('Open')
|
||||
->default()
|
||||
->query(fn (Builder $query): Builder => $query->whereIn('status', Finding::openStatusesForQuery())),
|
||||
Tables\Filters\Filter::make('overdue')
|
||||
->label('Overdue')
|
||||
->query(fn (Builder $query): Builder => $query
|
||||
->whereIn('status', Finding::openStatusesForQuery())
|
||||
->whereNotNull('due_at')
|
||||
->where('due_at', '<', now())),
|
||||
Tables\Filters\Filter::make('high_severity')
|
||||
->label('High severity')
|
||||
->query(fn (Builder $query): Builder => $query->whereIn('severity', [
|
||||
Finding::SEVERITY_HIGH,
|
||||
Finding::SEVERITY_CRITICAL,
|
||||
])),
|
||||
Tables\Filters\Filter::make('my_assigned')
|
||||
->label('My assigned')
|
||||
->query(function (Builder $query): Builder {
|
||||
$userId = auth()->id();
|
||||
|
||||
if (! is_numeric($userId)) {
|
||||
return $query->whereRaw('1 = 0');
|
||||
}
|
||||
|
||||
return $query->where('assignee_user_id', (int) $userId);
|
||||
}),
|
||||
Tables\Filters\SelectFilter::make('status')
|
||||
->options([
|
||||
Finding::STATUS_NEW => 'New',
|
||||
Finding::STATUS_TRIAGED => 'Triaged',
|
||||
Finding::STATUS_ACKNOWLEDGED => 'Triaged (legacy acknowledged)',
|
||||
Finding::STATUS_IN_PROGRESS => 'In progress',
|
||||
Finding::STATUS_REOPENED => 'Reopened',
|
||||
Finding::STATUS_RESOLVED => 'Resolved',
|
||||
Finding::STATUS_CLOSED => 'Closed',
|
||||
Finding::STATUS_RISK_ACCEPTED => 'Risk accepted',
|
||||
Finding::STATUS_ACKNOWLEDGED => 'Acknowledged',
|
||||
])
|
||||
->label('Status'),
|
||||
->default(Finding::STATUS_NEW),
|
||||
Tables\Filters\SelectFilter::make('finding_type')
|
||||
->options([
|
||||
Finding::FINDING_TYPE_DRIFT => 'Drift',
|
||||
Finding::FINDING_TYPE_PERMISSION_POSTURE => 'Permission posture',
|
||||
Finding::FINDING_TYPE_ENTRA_ADMIN_ROLES => 'Entra admin roles',
|
||||
])
|
||||
->label('Type'),
|
||||
->default(Finding::FINDING_TYPE_DRIFT),
|
||||
Tables\Filters\Filter::make('scope_key')
|
||||
->form([
|
||||
TextInput::make('scope_key')
|
||||
@ -407,7 +336,42 @@ public static function table(Table $table): Table
|
||||
->actions([
|
||||
Actions\ViewAction::make(),
|
||||
Actions\ActionGroup::make([
|
||||
...static::workflowActions(),
|
||||
UiEnforcement::forAction(
|
||||
Actions\Action::make('acknowledge')
|
||||
->label('Acknowledge')
|
||||
->icon('heroicon-o-check')
|
||||
->color('gray')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (Finding $record): bool => $record->status === Finding::STATUS_NEW)
|
||||
->action(function (Finding $record): void {
|
||||
$tenant = Tenant::current();
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $tenant || ! $user instanceof User) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ((int) $record->tenant_id !== (int) $tenant->getKey()) {
|
||||
Notification::make()
|
||||
->title('Finding belongs to a different tenant')
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$record->acknowledge($user);
|
||||
|
||||
Notification::make()
|
||||
->title('Finding acknowledged')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
)
|
||||
->preserveVisibility()
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_ACKNOWLEDGE)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply(),
|
||||
])
|
||||
->label('More')
|
||||
->icon('heroicon-o-ellipsis-vertical')
|
||||
@ -416,12 +380,12 @@ public static function table(Table $table): Table
|
||||
->bulkActions([
|
||||
BulkActionGroup::make([
|
||||
UiEnforcement::forBulkAction(
|
||||
BulkAction::make('triage_selected')
|
||||
->label('Triage selected')
|
||||
BulkAction::make('acknowledge_selected')
|
||||
->label('Acknowledge selected')
|
||||
->icon('heroicon-o-check')
|
||||
->color('gray')
|
||||
->requiresConfirmation()
|
||||
->action(function (Collection $records, FindingWorkflowService $workflow): void {
|
||||
->action(function (Collection $records): void {
|
||||
$tenant = Filament::getTenant();
|
||||
$user = auth()->user();
|
||||
|
||||
@ -429,9 +393,8 @@ public static function table(Table $table): Table
|
||||
return;
|
||||
}
|
||||
|
||||
$triagedCount = 0;
|
||||
$acknowledgedCount = 0;
|
||||
$skippedCount = 0;
|
||||
$failedCount = 0;
|
||||
|
||||
foreach ($records as $record) {
|
||||
if (! $record instanceof Finding) {
|
||||
@ -446,343 +409,30 @@ public static function table(Table $table): Table
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! in_array((string) $record->status, [
|
||||
Finding::STATUS_NEW,
|
||||
Finding::STATUS_REOPENED,
|
||||
Finding::STATUS_ACKNOWLEDGED,
|
||||
], true)) {
|
||||
if ($record->status !== Finding::STATUS_NEW) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$workflow->triage($record, $tenant, $user);
|
||||
$triagedCount++;
|
||||
} catch (Throwable) {
|
||||
$failedCount++;
|
||||
}
|
||||
$record->acknowledge($user);
|
||||
$acknowledgedCount++;
|
||||
}
|
||||
|
||||
$body = "Triaged {$triagedCount} finding".($triagedCount === 1 ? '' : 's').'.';
|
||||
$body = "Acknowledged {$acknowledgedCount} finding".($acknowledgedCount === 1 ? '' : 's').'.';
|
||||
if ($skippedCount > 0) {
|
||||
$body .= " Skipped {$skippedCount}.";
|
||||
}
|
||||
if ($failedCount > 0) {
|
||||
$body .= " Failed {$failedCount}.";
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Bulk triage completed')
|
||||
->title('Bulk acknowledge completed')
|
||||
->body($body)
|
||||
->status($failedCount > 0 ? 'warning' : 'success')
|
||||
->success()
|
||||
->send();
|
||||
})
|
||||
->deselectRecordsAfterCompletion(),
|
||||
)
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_TRIAGE)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply(),
|
||||
|
||||
UiEnforcement::forBulkAction(
|
||||
BulkAction::make('assign_selected')
|
||||
->label('Assign selected')
|
||||
->icon('heroicon-o-user-plus')
|
||||
->color('gray')
|
||||
->requiresConfirmation()
|
||||
->form([
|
||||
Select::make('assignee_user_id')
|
||||
->label('Assignee')
|
||||
->placeholder('Unassigned')
|
||||
->options(fn (): array => static::tenantMemberOptions())
|
||||
->searchable(),
|
||||
Select::make('owner_user_id')
|
||||
->label('Owner')
|
||||
->placeholder('Unassigned')
|
||||
->options(fn (): array => static::tenantMemberOptions())
|
||||
->searchable(),
|
||||
])
|
||||
->action(function (Collection $records, array $data, FindingWorkflowService $workflow): void {
|
||||
$tenant = Filament::getTenant();
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $tenant instanceof Tenant || ! $user instanceof User) {
|
||||
return;
|
||||
}
|
||||
|
||||
$assigneeUserId = is_numeric($data['assignee_user_id'] ?? null) ? (int) $data['assignee_user_id'] : null;
|
||||
$ownerUserId = is_numeric($data['owner_user_id'] ?? null) ? (int) $data['owner_user_id'] : null;
|
||||
|
||||
$assignedCount = 0;
|
||||
$skippedCount = 0;
|
||||
$failedCount = 0;
|
||||
|
||||
foreach ($records as $record) {
|
||||
if (! $record instanceof Finding) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((int) $record->tenant_id !== (int) $tenant->getKey()) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $record->hasOpenStatus()) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$workflow->assign($record, $tenant, $user, $assigneeUserId, $ownerUserId);
|
||||
$assignedCount++;
|
||||
} catch (Throwable) {
|
||||
$failedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
$body = "Updated {$assignedCount} finding".($assignedCount === 1 ? '' : 's').'.';
|
||||
if ($skippedCount > 0) {
|
||||
$body .= " Skipped {$skippedCount}.";
|
||||
}
|
||||
if ($failedCount > 0) {
|
||||
$body .= " Failed {$failedCount}.";
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Bulk assign completed')
|
||||
->body($body)
|
||||
->status($failedCount > 0 ? 'warning' : 'success')
|
||||
->send();
|
||||
})
|
||||
->deselectRecordsAfterCompletion(),
|
||||
)
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_ASSIGN)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply(),
|
||||
|
||||
UiEnforcement::forBulkAction(
|
||||
BulkAction::make('resolve_selected')
|
||||
->label('Resolve selected')
|
||||
->icon('heroicon-o-check-badge')
|
||||
->color('success')
|
||||
->requiresConfirmation()
|
||||
->form([
|
||||
Textarea::make('resolved_reason')
|
||||
->label('Resolution reason')
|
||||
->rows(3)
|
||||
->required()
|
||||
->maxLength(255),
|
||||
])
|
||||
->action(function (Collection $records, array $data, FindingWorkflowService $workflow): void {
|
||||
$tenant = Filament::getTenant();
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $tenant instanceof Tenant || ! $user instanceof User) {
|
||||
return;
|
||||
}
|
||||
|
||||
$reason = (string) ($data['resolved_reason'] ?? '');
|
||||
|
||||
$resolvedCount = 0;
|
||||
$skippedCount = 0;
|
||||
$failedCount = 0;
|
||||
|
||||
foreach ($records as $record) {
|
||||
if (! $record instanceof Finding) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((int) $record->tenant_id !== (int) $tenant->getKey()) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $record->hasOpenStatus()) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$workflow->resolve($record, $tenant, $user, $reason);
|
||||
$resolvedCount++;
|
||||
} catch (Throwable) {
|
||||
$failedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
$body = "Resolved {$resolvedCount} finding".($resolvedCount === 1 ? '' : 's').'.';
|
||||
if ($skippedCount > 0) {
|
||||
$body .= " Skipped {$skippedCount}.";
|
||||
}
|
||||
if ($failedCount > 0) {
|
||||
$body .= " Failed {$failedCount}.";
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Bulk resolve completed')
|
||||
->body($body)
|
||||
->status($failedCount > 0 ? 'warning' : 'success')
|
||||
->send();
|
||||
})
|
||||
->deselectRecordsAfterCompletion(),
|
||||
)
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_RESOLVE)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply(),
|
||||
|
||||
UiEnforcement::forBulkAction(
|
||||
BulkAction::make('close_selected')
|
||||
->label('Close selected')
|
||||
->icon('heroicon-o-x-circle')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->form([
|
||||
Textarea::make('closed_reason')
|
||||
->label('Close reason')
|
||||
->rows(3)
|
||||
->required()
|
||||
->maxLength(255),
|
||||
])
|
||||
->action(function (Collection $records, array $data, FindingWorkflowService $workflow): void {
|
||||
$tenant = Filament::getTenant();
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $tenant instanceof Tenant || ! $user instanceof User) {
|
||||
return;
|
||||
}
|
||||
|
||||
$reason = (string) ($data['closed_reason'] ?? '');
|
||||
|
||||
$closedCount = 0;
|
||||
$skippedCount = 0;
|
||||
$failedCount = 0;
|
||||
|
||||
foreach ($records as $record) {
|
||||
if (! $record instanceof Finding) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((int) $record->tenant_id !== (int) $tenant->getKey()) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $record->hasOpenStatus()) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$workflow->close($record, $tenant, $user, $reason);
|
||||
$closedCount++;
|
||||
} catch (Throwable) {
|
||||
$failedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
$body = "Closed {$closedCount} finding".($closedCount === 1 ? '' : 's').'.';
|
||||
if ($skippedCount > 0) {
|
||||
$body .= " Skipped {$skippedCount}.";
|
||||
}
|
||||
if ($failedCount > 0) {
|
||||
$body .= " Failed {$failedCount}.";
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Bulk close completed')
|
||||
->body($body)
|
||||
->status($failedCount > 0 ? 'warning' : 'success')
|
||||
->send();
|
||||
})
|
||||
->deselectRecordsAfterCompletion(),
|
||||
)
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_CLOSE)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply(),
|
||||
|
||||
UiEnforcement::forBulkAction(
|
||||
BulkAction::make('risk_accept_selected')
|
||||
->label('Risk accept selected')
|
||||
->icon('heroicon-o-shield-check')
|
||||
->color('warning')
|
||||
->requiresConfirmation()
|
||||
->form([
|
||||
Textarea::make('closed_reason')
|
||||
->label('Risk acceptance reason')
|
||||
->rows(3)
|
||||
->required()
|
||||
->maxLength(255),
|
||||
])
|
||||
->action(function (Collection $records, array $data, FindingWorkflowService $workflow): void {
|
||||
$tenant = Filament::getTenant();
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $tenant instanceof Tenant || ! $user instanceof User) {
|
||||
return;
|
||||
}
|
||||
|
||||
$reason = (string) ($data['closed_reason'] ?? '');
|
||||
|
||||
$acceptedCount = 0;
|
||||
$skippedCount = 0;
|
||||
$failedCount = 0;
|
||||
|
||||
foreach ($records as $record) {
|
||||
if (! $record instanceof Finding) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((int) $record->tenant_id !== (int) $tenant->getKey()) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $record->hasOpenStatus()) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$workflow->riskAccept($record, $tenant, $user, $reason);
|
||||
$acceptedCount++;
|
||||
} catch (Throwable) {
|
||||
$failedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
$body = "Risk accepted {$acceptedCount} finding".($acceptedCount === 1 ? '' : 's').'.';
|
||||
if ($skippedCount > 0) {
|
||||
$body .= " Skipped {$skippedCount}.";
|
||||
}
|
||||
if ($failedCount > 0) {
|
||||
$body .= " Failed {$failedCount}.";
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Bulk risk accept completed')
|
||||
->body($body)
|
||||
->status($failedCount > 0 ? 'warning' : 'success')
|
||||
->send();
|
||||
})
|
||||
->deselectRecordsAfterCompletion(),
|
||||
)
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_RISK_ACCEPT)
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_ACKNOWLEDGE)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply(),
|
||||
])->label('More'),
|
||||
@ -794,7 +444,6 @@ public static function getEloquentQuery(): Builder
|
||||
$tenantId = Tenant::current()?->getKey();
|
||||
|
||||
return parent::getEloquentQuery()
|
||||
->with(['assigneeUser', 'ownerUser', 'closedByUser'])
|
||||
->addSelect([
|
||||
'subject_display_name' => InventoryItem::query()
|
||||
->select('display_name')
|
||||
@ -812,300 +461,4 @@ public static function getPages(): array
|
||||
'view' => Pages\ViewFinding::route('/{record}'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, Actions\Action>
|
||||
*/
|
||||
public static function workflowActions(): array
|
||||
{
|
||||
return [
|
||||
static::triageAction(),
|
||||
static::startProgressAction(),
|
||||
static::assignAction(),
|
||||
static::resolveAction(),
|
||||
static::closeAction(),
|
||||
static::riskAcceptAction(),
|
||||
static::reopenAction(),
|
||||
];
|
||||
}
|
||||
|
||||
public static function triageAction(): Actions\Action
|
||||
{
|
||||
return UiEnforcement::forAction(
|
||||
Actions\Action::make('triage')
|
||||
->label('Triage')
|
||||
->icon('heroicon-o-check')
|
||||
->color('gray')
|
||||
->visible(fn (Finding $record): bool => in_array((string) $record->status, [
|
||||
Finding::STATUS_NEW,
|
||||
Finding::STATUS_REOPENED,
|
||||
Finding::STATUS_ACKNOWLEDGED,
|
||||
], true))
|
||||
->action(function (Finding $record, FindingWorkflowService $workflow): void {
|
||||
static::runWorkflowMutation(
|
||||
record: $record,
|
||||
successTitle: 'Finding triaged',
|
||||
callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->triage($finding, $tenant, $user),
|
||||
);
|
||||
})
|
||||
)
|
||||
->preserveVisibility()
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_TRIAGE)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply();
|
||||
}
|
||||
|
||||
public static function startProgressAction(): Actions\Action
|
||||
{
|
||||
return UiEnforcement::forAction(
|
||||
Actions\Action::make('start_progress')
|
||||
->label('Start progress')
|
||||
->icon('heroicon-o-play')
|
||||
->color('info')
|
||||
->visible(fn (Finding $record): bool => in_array((string) $record->status, [
|
||||
Finding::STATUS_TRIAGED,
|
||||
Finding::STATUS_ACKNOWLEDGED,
|
||||
], true))
|
||||
->action(function (Finding $record, FindingWorkflowService $workflow): void {
|
||||
static::runWorkflowMutation(
|
||||
record: $record,
|
||||
successTitle: 'Finding moved to in progress',
|
||||
callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->startProgress($finding, $tenant, $user),
|
||||
);
|
||||
})
|
||||
)
|
||||
->preserveVisibility()
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_TRIAGE)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply();
|
||||
}
|
||||
|
||||
public static function assignAction(): Actions\Action
|
||||
{
|
||||
return UiEnforcement::forAction(
|
||||
Actions\Action::make('assign')
|
||||
->label('Assign')
|
||||
->icon('heroicon-o-user-plus')
|
||||
->color('gray')
|
||||
->visible(fn (Finding $record): bool => $record->hasOpenStatus())
|
||||
->fillForm(fn (Finding $record): array => [
|
||||
'assignee_user_id' => $record->assignee_user_id,
|
||||
'owner_user_id' => $record->owner_user_id,
|
||||
])
|
||||
->form([
|
||||
Select::make('assignee_user_id')
|
||||
->label('Assignee')
|
||||
->placeholder('Unassigned')
|
||||
->options(fn (): array => static::tenantMemberOptions())
|
||||
->searchable(),
|
||||
Select::make('owner_user_id')
|
||||
->label('Owner')
|
||||
->placeholder('Unassigned')
|
||||
->options(fn (): array => static::tenantMemberOptions())
|
||||
->searchable(),
|
||||
])
|
||||
->action(function (Finding $record, array $data, FindingWorkflowService $workflow): void {
|
||||
static::runWorkflowMutation(
|
||||
record: $record,
|
||||
successTitle: 'Finding assignment updated',
|
||||
callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->assign(
|
||||
$finding,
|
||||
$tenant,
|
||||
$user,
|
||||
is_numeric($data['assignee_user_id'] ?? null) ? (int) $data['assignee_user_id'] : null,
|
||||
is_numeric($data['owner_user_id'] ?? null) ? (int) $data['owner_user_id'] : null,
|
||||
),
|
||||
);
|
||||
})
|
||||
)
|
||||
->preserveVisibility()
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_ASSIGN)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply();
|
||||
}
|
||||
|
||||
public static function resolveAction(): Actions\Action
|
||||
{
|
||||
return UiEnforcement::forAction(
|
||||
Actions\Action::make('resolve')
|
||||
->label('Resolve')
|
||||
->icon('heroicon-o-check-badge')
|
||||
->color('success')
|
||||
->visible(fn (Finding $record): bool => $record->hasOpenStatus())
|
||||
->requiresConfirmation()
|
||||
->form([
|
||||
Textarea::make('resolved_reason')
|
||||
->label('Resolution reason')
|
||||
->rows(3)
|
||||
->required()
|
||||
->maxLength(255),
|
||||
])
|
||||
->action(function (Finding $record, array $data, FindingWorkflowService $workflow): void {
|
||||
static::runWorkflowMutation(
|
||||
record: $record,
|
||||
successTitle: 'Finding resolved',
|
||||
callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->resolve(
|
||||
$finding,
|
||||
$tenant,
|
||||
$user,
|
||||
(string) ($data['resolved_reason'] ?? ''),
|
||||
),
|
||||
);
|
||||
})
|
||||
)
|
||||
->preserveVisibility()
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_RESOLVE)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply();
|
||||
}
|
||||
|
||||
public static function closeAction(): Actions\Action
|
||||
{
|
||||
return UiEnforcement::forAction(
|
||||
Actions\Action::make('close')
|
||||
->label('Close')
|
||||
->icon('heroicon-o-x-circle')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->form([
|
||||
Textarea::make('closed_reason')
|
||||
->label('Close reason')
|
||||
->rows(3)
|
||||
->required()
|
||||
->maxLength(255),
|
||||
])
|
||||
->action(function (Finding $record, array $data, FindingWorkflowService $workflow): void {
|
||||
static::runWorkflowMutation(
|
||||
record: $record,
|
||||
successTitle: 'Finding closed',
|
||||
callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->close(
|
||||
$finding,
|
||||
$tenant,
|
||||
$user,
|
||||
(string) ($data['closed_reason'] ?? ''),
|
||||
),
|
||||
);
|
||||
})
|
||||
)
|
||||
->preserveVisibility()
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_CLOSE)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply();
|
||||
}
|
||||
|
||||
public static function riskAcceptAction(): Actions\Action
|
||||
{
|
||||
return UiEnforcement::forAction(
|
||||
Actions\Action::make('risk_accept')
|
||||
->label('Risk accept')
|
||||
->icon('heroicon-o-shield-check')
|
||||
->color('warning')
|
||||
->requiresConfirmation()
|
||||
->form([
|
||||
Textarea::make('closed_reason')
|
||||
->label('Risk acceptance reason')
|
||||
->rows(3)
|
||||
->required()
|
||||
->maxLength(255),
|
||||
])
|
||||
->action(function (Finding $record, array $data, FindingWorkflowService $workflow): void {
|
||||
static::runWorkflowMutation(
|
||||
record: $record,
|
||||
successTitle: 'Finding marked as risk accepted',
|
||||
callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->riskAccept(
|
||||
$finding,
|
||||
$tenant,
|
||||
$user,
|
||||
(string) ($data['closed_reason'] ?? ''),
|
||||
),
|
||||
);
|
||||
})
|
||||
)
|
||||
->preserveVisibility()
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_RISK_ACCEPT)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply();
|
||||
}
|
||||
|
||||
public static function reopenAction(): Actions\Action
|
||||
{
|
||||
return UiEnforcement::forAction(
|
||||
Actions\Action::make('reopen')
|
||||
->label('Reopen')
|
||||
->icon('heroicon-o-arrow-uturn-left')
|
||||
->color('warning')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (Finding $record): bool => Finding::isTerminalStatus((string) $record->status))
|
||||
->action(function (Finding $record, FindingWorkflowService $workflow): void {
|
||||
static::runWorkflowMutation(
|
||||
record: $record,
|
||||
successTitle: 'Finding reopened',
|
||||
callback: fn (Finding $finding, Tenant $tenant, User $user): Finding => $workflow->reopen($finding, $tenant, $user),
|
||||
);
|
||||
})
|
||||
)
|
||||
->preserveVisibility()
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_TRIAGE)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable(Finding, Tenant, User): Finding $callback
|
||||
*/
|
||||
private static function runWorkflowMutation(Finding $record, string $successTitle, callable $callback): void
|
||||
{
|
||||
$tenant = Tenant::current();
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $tenant instanceof Tenant || ! $user instanceof User) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ((int) $record->tenant_id !== (int) $tenant->getKey()) {
|
||||
Notification::make()
|
||||
->title('Finding belongs to a different tenant')
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$callback($record, $tenant, $user);
|
||||
} catch (InvalidArgumentException $e) {
|
||||
Notification::make()
|
||||
->title('Workflow action failed')
|
||||
->body($e->getMessage())
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title($successTitle)
|
||||
->success()
|
||||
->send();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private static function tenantMemberOptions(): array
|
||||
{
|
||||
$tenant = Tenant::current();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return TenantMembership::query()
|
||||
->where('tenant_id', (int) $tenant->getKey())
|
||||
->join('users', 'users.id', '=', 'tenant_memberships.user_id')
|
||||
->orderBy('users.name')
|
||||
->pluck('users.name', 'users.id')
|
||||
->mapWithKeys(fn (string $name, int|string $id): array => [(int) $id => $name])
|
||||
->all();
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,16 +3,8 @@
|
||||
namespace App\Filament\Resources\FindingResource\Pages;
|
||||
|
||||
use App\Filament\Resources\FindingResource;
|
||||
use App\Jobs\BackfillFindingLifecycleJob;
|
||||
use App\Models\Finding;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\Findings\FindingWorkflowService;
|
||||
use App\Services\OperationRunService;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\OperationRunLinks;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||
use App\Support\Rbac\UiEnforcement;
|
||||
use App\Support\Rbac\UiTooltips;
|
||||
use Filament\Actions;
|
||||
@ -21,7 +13,6 @@
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Arr;
|
||||
use Throwable;
|
||||
|
||||
class ListFindings extends ListRecords
|
||||
{
|
||||
@ -29,195 +20,71 @@ class ListFindings extends ListRecords
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
$actions = [];
|
||||
|
||||
if ((bool) config('tenantpilot.allow_admin_maintenance_actions', false)) {
|
||||
$actions[] = UiEnforcement::forAction(
|
||||
Actions\Action::make('backfill_lifecycle')
|
||||
->label('Backfill findings lifecycle')
|
||||
->icon('heroicon-o-wrench-screwdriver')
|
||||
return [
|
||||
UiEnforcement::forAction(
|
||||
Actions\Action::make('acknowledge_all_matching')
|
||||
->label('Acknowledge all matching')
|
||||
->icon('heroicon-o-check')
|
||||
->color('gray')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Backfill findings lifecycle')
|
||||
->modalDescription('This will backfill legacy Findings data (lifecycle fields, SLA due dates, and drift duplicate consolidation) for the current tenant. The operation runs in the background.')
|
||||
->action(function (OperationRunService $operationRuns): void {
|
||||
$user = auth()->user();
|
||||
->visible(fn (): bool => $this->getStatusFilterValue() === Finding::STATUS_NEW)
|
||||
->modalDescription(function (): string {
|
||||
$count = $this->getAllMatchingCount();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
abort(403);
|
||||
return "You are about to acknowledge {$count} finding".($count === 1 ? '' : 's').' matching the current filters.';
|
||||
})
|
||||
->form(function (): array {
|
||||
$count = $this->getAllMatchingCount();
|
||||
|
||||
if ($count <= 100) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$tenant = \Filament\Facades\Filament::getTenant();
|
||||
return [
|
||||
TextInput::make('confirmation')
|
||||
->label('Type ACKNOWLEDGE to confirm')
|
||||
->required()
|
||||
->in(['ACKNOWLEDGE'])
|
||||
->validationMessages([
|
||||
'in' => 'Please type ACKNOWLEDGE to confirm.',
|
||||
]),
|
||||
];
|
||||
})
|
||||
->action(function (array $data): void {
|
||||
$query = $this->buildAllMatchingQuery();
|
||||
$count = (clone $query)->count();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$opRun = $operationRuns->ensureRunWithIdentity(
|
||||
tenant: $tenant,
|
||||
type: 'findings.lifecycle.backfill',
|
||||
identityInputs: [
|
||||
'tenant_id' => (int) $tenant->getKey(),
|
||||
'trigger' => 'backfill',
|
||||
],
|
||||
context: [
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'initiator_user_id' => (int) $user->getKey(),
|
||||
],
|
||||
initiator: $user,
|
||||
);
|
||||
|
||||
$runUrl = OperationRunLinks::view($opRun, $tenant);
|
||||
|
||||
if ($opRun->wasRecentlyCreated === false) {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url($runUrl),
|
||||
])
|
||||
if ($count === 0) {
|
||||
Notification::make()
|
||||
->title('No matching findings')
|
||||
->body('There are no new findings matching the current filters.')
|
||||
->warning()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$operationRuns->dispatchOrFail($opRun, function () use ($tenant, $user): void {
|
||||
BackfillFindingLifecycleJob::dispatch(
|
||||
tenantId: (int) $tenant->getKey(),
|
||||
workspaceId: (int) $tenant->workspace_id,
|
||||
initiatorUserId: (int) $user->getKey(),
|
||||
);
|
||||
});
|
||||
$updated = $query->update([
|
||||
'status' => Finding::STATUS_ACKNOWLEDGED,
|
||||
'acknowledged_at' => now(),
|
||||
'acknowledged_by_user_id' => auth()->id(),
|
||||
]);
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
$this->deselectAllTableRecords();
|
||||
$this->resetPage();
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $opRun->type)
|
||||
->body('The backfill will run in the background. You can continue working while it completes.')
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url($runUrl),
|
||||
])
|
||||
Notification::make()
|
||||
->title('Bulk acknowledge completed')
|
||||
->body("Acknowledged {$updated} finding".($updated === 1 ? '' : 's').'.')
|
||||
->success()
|
||||
->send();
|
||||
})
|
||||
)
|
||||
->preserveVisibility()
|
||||
->requireCapability(Capabilities::TENANT_MANAGE)
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_ACKNOWLEDGE)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply();
|
||||
}
|
||||
|
||||
$actions[] = UiEnforcement::forAction(
|
||||
Actions\Action::make('triage_all_matching')
|
||||
->label('Triage all matching')
|
||||
->icon('heroicon-o-check')
|
||||
->color('gray')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (): bool => $this->getStatusFilterValue() === Finding::STATUS_NEW)
|
||||
->modalDescription(function (): string {
|
||||
$count = $this->getAllMatchingCount();
|
||||
|
||||
return "You are about to triage {$count} finding".($count === 1 ? '' : 's').' matching the current filters.';
|
||||
})
|
||||
->form(function (): array {
|
||||
$count = $this->getAllMatchingCount();
|
||||
|
||||
if ($count <= 100) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
TextInput::make('confirmation')
|
||||
->label('Type TRIAGE to confirm')
|
||||
->required()
|
||||
->in(['TRIAGE'])
|
||||
->validationMessages([
|
||||
'in' => 'Please type TRIAGE to confirm.',
|
||||
]),
|
||||
];
|
||||
})
|
||||
->action(function (FindingWorkflowService $workflow): void {
|
||||
$query = $this->buildAllMatchingQuery();
|
||||
$count = (clone $query)->count();
|
||||
|
||||
if ($count === 0) {
|
||||
Notification::make()
|
||||
->title('No matching findings')
|
||||
->body('There are no new findings matching the current filters to triage.')
|
||||
->warning()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$user = auth()->user();
|
||||
$tenant = \Filament\Facades\Filament::getTenant();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$triagedCount = 0;
|
||||
$skippedCount = 0;
|
||||
$failedCount = 0;
|
||||
|
||||
$query->orderBy('id')->chunkById(200, function ($findings) use ($workflow, $tenant, $user, &$triagedCount, &$skippedCount, &$failedCount): void {
|
||||
foreach ($findings as $finding) {
|
||||
if (! $finding instanceof Finding) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! in_array((string) $finding->status, [
|
||||
Finding::STATUS_NEW,
|
||||
Finding::STATUS_REOPENED,
|
||||
Finding::STATUS_ACKNOWLEDGED,
|
||||
], true)) {
|
||||
$skippedCount++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$workflow->triage($finding, $tenant, $user);
|
||||
$triagedCount++;
|
||||
} catch (Throwable) {
|
||||
$failedCount++;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
$this->deselectAllTableRecords();
|
||||
$this->resetPage();
|
||||
|
||||
$body = "Triaged {$triagedCount} finding".($triagedCount === 1 ? '' : 's').'.';
|
||||
if ($skippedCount > 0) {
|
||||
$body .= " Skipped {$skippedCount}.";
|
||||
}
|
||||
if ($failedCount > 0) {
|
||||
$body .= " Failed {$failedCount}.";
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Bulk triage completed')
|
||||
->body($body)
|
||||
->status($failedCount > 0 ? 'warning' : 'success')
|
||||
->send();
|
||||
})
|
||||
)
|
||||
->preserveVisibility()
|
||||
->requireCapability(Capabilities::TENANT_FINDINGS_TRIAGE)
|
||||
->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
|
||||
->apply();
|
||||
|
||||
return $actions;
|
||||
->apply(),
|
||||
];
|
||||
}
|
||||
|
||||
protected function buildAllMatchingQuery(): Builder
|
||||
@ -239,27 +106,6 @@ protected function buildAllMatchingQuery(): Builder
|
||||
$query->where('finding_type', $findingType);
|
||||
}
|
||||
|
||||
if ($this->filterIsActive('overdue')) {
|
||||
$query->whereNotNull('due_at')->where('due_at', '<', now());
|
||||
}
|
||||
|
||||
if ($this->filterIsActive('high_severity')) {
|
||||
$query->whereIn('severity', [
|
||||
Finding::SEVERITY_HIGH,
|
||||
Finding::SEVERITY_CRITICAL,
|
||||
]);
|
||||
}
|
||||
|
||||
if ($this->filterIsActive('my_assigned')) {
|
||||
$userId = auth()->id();
|
||||
|
||||
if (is_numeric($userId)) {
|
||||
$query->where('assignee_user_id', (int) $userId);
|
||||
} else {
|
||||
$query->whereRaw('1 = 0');
|
||||
}
|
||||
}
|
||||
|
||||
$scopeKeyState = $this->getTableFilterState('scope_key') ?? [];
|
||||
$scopeKey = Arr::get($scopeKeyState, 'scope_key');
|
||||
if (is_string($scopeKey) && $scopeKey !== '') {
|
||||
@ -280,23 +126,6 @@ protected function buildAllMatchingQuery(): Builder
|
||||
return $query;
|
||||
}
|
||||
|
||||
private function filterIsActive(string $filterName): bool
|
||||
{
|
||||
$state = $this->getTableFilterState($filterName);
|
||||
|
||||
if ($state === true) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (is_array($state)) {
|
||||
$isActive = Arr::get($state, 'isActive');
|
||||
|
||||
return $isActive === true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected function getAllMatchingCount(): int
|
||||
{
|
||||
return (int) $this->buildAllMatchingQuery()->count();
|
||||
@ -312,13 +141,13 @@ protected function getStatusFilterValue(): string
|
||||
: Finding::STATUS_NEW;
|
||||
}
|
||||
|
||||
protected function getFindingTypeFilterValue(): ?string
|
||||
protected function getFindingTypeFilterValue(): string
|
||||
{
|
||||
$state = $this->getTableFilterState('finding_type') ?? [];
|
||||
$value = Arr::get($state, 'value');
|
||||
|
||||
return is_string($value) && $value !== ''
|
||||
? $value
|
||||
: null;
|
||||
: Finding::FINDING_TYPE_DRIFT;
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,20 +3,9 @@
|
||||
namespace App\Filament\Resources\FindingResource\Pages;
|
||||
|
||||
use App\Filament\Resources\FindingResource;
|
||||
use Filament\Actions;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
|
||||
class ViewFinding extends ViewRecord
|
||||
{
|
||||
protected static string $resource = FindingResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Actions\ActionGroup::make(FindingResource::workflowActions())
|
||||
->label('Actions')
|
||||
->icon('heroicon-o-ellipsis-vertical')
|
||||
->color('gray'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@ -44,7 +44,7 @@ protected function getHeaderActions(): array
|
||||
Action::make('run_inventory_sync')
|
||||
->label('Run Inventory Sync')
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->color('primary')
|
||||
->color('warning')
|
||||
->form([
|
||||
Select::make('policy_types')
|
||||
->label('Policy types')
|
||||
@ -167,7 +167,10 @@ protected function getHeaderActions(): array
|
||||
);
|
||||
|
||||
if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'], true)) {
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
|
||||
Notification::make()
|
||||
->title('Inventory sync already active')
|
||||
->body('This operation is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View Run')
|
||||
|
||||
@ -471,8 +471,10 @@ public static function table(Table $table): Table
|
||||
);
|
||||
|
||||
if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'], true)) {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
|
||||
Notification::make()
|
||||
->title('Policy sync already active')
|
||||
->body('This operation is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -601,7 +603,7 @@ public static function table(Table $table): Table
|
||||
|
||||
return [];
|
||||
})
|
||||
->action(function (Collection $records, HasTable $livewire): void {
|
||||
->action(function (Collection $records): void {
|
||||
$tenant = Tenant::current();
|
||||
$user = auth()->user();
|
||||
$count = $records->count();
|
||||
@ -641,30 +643,19 @@ public static function table(Table $table): Table
|
||||
emitQueuedNotification: false,
|
||||
);
|
||||
|
||||
$runUrl = OperationRunLinks::view($opRun, $tenant);
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
|
||||
if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'], true)) {
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
|
||||
->body("Queued deletion for {$count} policies.")
|
||||
->actions([
|
||||
\Filament\Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url($runUrl),
|
||||
])
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $opRun->type)
|
||||
Notification::make()
|
||||
->title('Policy delete queued')
|
||||
->body("Queued deletion for {$count} policies.")
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->iconColor('warning')
|
||||
->info()
|
||||
->actions([
|
||||
\Filament\Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url($runUrl),
|
||||
->url(OperationRunLinks::view($opRun, $tenant)),
|
||||
])
|
||||
->duration(8000)
|
||||
->sendToDatabase($user)
|
||||
->send();
|
||||
})
|
||||
->deselectRecordsAfterCompletion(),
|
||||
@ -739,6 +730,18 @@ public static function table(Table $table): Table
|
||||
emitQueuedNotification: false,
|
||||
);
|
||||
|
||||
if ($count >= 20) {
|
||||
Notification::make()
|
||||
->title('Bulk restore started')
|
||||
->body("Restoring {$count} policies in the background. Check the progress bar in the bottom right corner.")
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->iconColor('warning')
|
||||
->info()
|
||||
->duration(8000)
|
||||
->sendToDatabase($user)
|
||||
->send();
|
||||
}
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $opRun->type)
|
||||
@ -800,8 +803,10 @@ public static function table(Table $table): Table
|
||||
);
|
||||
|
||||
if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'], true)) {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
|
||||
Notification::make()
|
||||
->title('Policy sync already active')
|
||||
->body('This operation is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -895,6 +900,18 @@ public static function table(Table $table): Table
|
||||
emitQueuedNotification: false,
|
||||
);
|
||||
|
||||
if ($count >= 20) {
|
||||
Notification::make()
|
||||
->title('Bulk export started')
|
||||
->body("Exporting {$count} policies to backup '{$data['backup_name']}' in the background. Check the progress bar in the bottom right corner.")
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->iconColor('warning')
|
||||
->info()
|
||||
->duration(8000)
|
||||
->sendToDatabase($user)
|
||||
->send();
|
||||
}
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $opRun->type)
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
|
||||
@ -13,6 +13,7 @@
|
||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||
use App\Support\Rbac\UiEnforcement;
|
||||
use Filament\Actions;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListPolicies extends ListRecords
|
||||
@ -67,8 +68,10 @@ private function makeSyncAction(): Actions\Action
|
||||
);
|
||||
|
||||
if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'], true)) {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
|
||||
Notification::make()
|
||||
->title('Policy sync already active')
|
||||
->body('This operation is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
|
||||
@ -303,6 +303,20 @@ public static function table(Table $table): Table
|
||||
emitQueuedNotification: false,
|
||||
);
|
||||
|
||||
Notification::make()
|
||||
->title('Policy version prune queued')
|
||||
->body("Queued prune for {$count} policy versions.")
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->iconColor('warning')
|
||||
->info()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(OperationRunLinks::view($opRun, $tenant)),
|
||||
])
|
||||
->duration(8000)
|
||||
->sendToDatabase($initiator);
|
||||
|
||||
OperationUxPresenter::queuedToast('policy_version.prune')
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
@ -462,6 +476,20 @@ public static function table(Table $table): Table
|
||||
emitQueuedNotification: false,
|
||||
);
|
||||
|
||||
Notification::make()
|
||||
->title('Policy version force delete queued')
|
||||
->body("Queued force delete for {$count} policy versions.")
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->iconColor('warning')
|
||||
->info()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(OperationRunLinks::view($opRun, $tenant)),
|
||||
])
|
||||
->duration(8000)
|
||||
->sendToDatabase($initiator);
|
||||
|
||||
OperationUxPresenter::queuedToast('policy_version.force_delete')
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
|
||||
@ -18,8 +18,6 @@
|
||||
use App\Support\Badges\BadgeDomain;
|
||||
use App\Support\Badges\BadgeRenderer;
|
||||
use App\Support\OperationRunLinks;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||
use App\Support\Providers\ProviderReasonCodes;
|
||||
use App\Support\Rbac\UiEnforcement;
|
||||
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
|
||||
@ -34,7 +32,6 @@
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables;
|
||||
use Filament\Tables\Filters\Filter;
|
||||
@ -404,39 +401,29 @@ public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->schema([
|
||||
Section::make('Connection')
|
||||
->schema([
|
||||
TextInput::make('display_name')
|
||||
->label('Display name')
|
||||
->required()
|
||||
->disabled(fn (): bool => ! static::hasTenantCapability(Capabilities::PROVIDER_MANAGE))
|
||||
->maxLength(255),
|
||||
TextInput::make('entra_tenant_id')
|
||||
->label('Entra tenant ID')
|
||||
->required()
|
||||
->maxLength(255)
|
||||
->disabled(fn (): bool => ! static::hasTenantCapability(Capabilities::PROVIDER_MANAGE))
|
||||
->rules(['uuid']),
|
||||
Toggle::make('is_default')
|
||||
->label('Default connection')
|
||||
->disabled(fn (): bool => ! static::hasTenantCapability(Capabilities::PROVIDER_MANAGE))
|
||||
->helperText('Exactly one default connection is required per tenant/provider.'),
|
||||
])
|
||||
->columns(2)
|
||||
->columnSpanFull(),
|
||||
Section::make('Status')
|
||||
->schema([
|
||||
TextInput::make('status')
|
||||
->label('Status')
|
||||
->disabled()
|
||||
->dehydrated(false),
|
||||
TextInput::make('health_status')
|
||||
->label('Health')
|
||||
->disabled()
|
||||
->dehydrated(false),
|
||||
])
|
||||
->columns(2)
|
||||
->columnSpanFull(),
|
||||
TextInput::make('display_name')
|
||||
->label('Display name')
|
||||
->required()
|
||||
->disabled(fn (): bool => ! static::hasTenantCapability(Capabilities::PROVIDER_MANAGE))
|
||||
->maxLength(255),
|
||||
TextInput::make('entra_tenant_id')
|
||||
->label('Entra tenant ID')
|
||||
->required()
|
||||
->maxLength(255)
|
||||
->disabled(fn (): bool => ! static::hasTenantCapability(Capabilities::PROVIDER_MANAGE))
|
||||
->rules(['uuid']),
|
||||
Toggle::make('is_default')
|
||||
->label('Default connection')
|
||||
->disabled(fn (): bool => ! static::hasTenantCapability(Capabilities::PROVIDER_MANAGE))
|
||||
->helperText('Exactly one default connection is required per tenant/provider.'),
|
||||
TextInput::make('status')
|
||||
->label('Status')
|
||||
->disabled()
|
||||
->dehydrated(false),
|
||||
TextInput::make('health_status')
|
||||
->label('Health')
|
||||
->disabled()
|
||||
->dehydrated(false),
|
||||
]);
|
||||
}
|
||||
|
||||
@ -588,7 +575,7 @@ public static function table(Table $table): Table
|
||||
->icon('heroicon-o-check-badge')
|
||||
->color('success')
|
||||
->visible(fn (ProviderConnection $record): bool => $record->status !== 'disabled')
|
||||
->action(function (ProviderConnection $record, StartVerification $verification, \Filament\Tables\Contracts\HasTable $livewire): void {
|
||||
->action(function (ProviderConnection $record, StartVerification $verification): void {
|
||||
$tenant = static::resolveTenantForRecord($record);
|
||||
$user = auth()->user();
|
||||
|
||||
@ -625,9 +612,10 @@ public static function table(Table $table): Table
|
||||
}
|
||||
|
||||
if ($result->status === 'deduped') {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Run already queued')
|
||||
->body('A connection check is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -663,9 +651,10 @@ public static function table(Table $table): Table
|
||||
return;
|
||||
}
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Connection check queued')
|
||||
->body('Health check was queued and will run in the background.')
|
||||
->success()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -684,7 +673,7 @@ public static function table(Table $table): Table
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->color('info')
|
||||
->visible(fn (ProviderConnection $record): bool => $record->status !== 'disabled')
|
||||
->action(function (ProviderConnection $record, ProviderOperationStartGate $gate, \Filament\Tables\Contracts\HasTable $livewire): void {
|
||||
->action(function (ProviderConnection $record, ProviderOperationStartGate $gate): void {
|
||||
$tenant = static::resolveTenantForRecord($record);
|
||||
$user = auth()->user();
|
||||
|
||||
@ -725,9 +714,10 @@ public static function table(Table $table): Table
|
||||
}
|
||||
|
||||
if ($result->status === 'deduped') {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Run already queued')
|
||||
->body('An inventory sync is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -757,9 +747,10 @@ public static function table(Table $table): Table
|
||||
return;
|
||||
}
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Inventory sync queued')
|
||||
->body('Inventory sync was queued and will run in the background.')
|
||||
->success()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -778,7 +769,7 @@ public static function table(Table $table): Table
|
||||
->icon('heroicon-o-shield-check')
|
||||
->color('info')
|
||||
->visible(fn (ProviderConnection $record): bool => $record->status !== 'disabled')
|
||||
->action(function (ProviderConnection $record, ProviderOperationStartGate $gate, \Filament\Tables\Contracts\HasTable $livewire): void {
|
||||
->action(function (ProviderConnection $record, ProviderOperationStartGate $gate): void {
|
||||
$tenant = static::resolveTenantForRecord($record);
|
||||
$user = auth()->user();
|
||||
|
||||
@ -819,9 +810,10 @@ public static function table(Table $table): Table
|
||||
}
|
||||
|
||||
if ($result->status === 'deduped') {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Run already queued')
|
||||
->body('A compliance snapshot is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -851,9 +843,10 @@ public static function table(Table $table): Table
|
||||
return;
|
||||
}
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Compliance snapshot queued')
|
||||
->body('Compliance snapshot was queued and will run in the background.')
|
||||
->success()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
|
||||
@ -16,8 +16,6 @@
|
||||
use App\Services\Verification\StartVerification;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\OperationRunLinks;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||
use App\Support\Rbac\UiEnforcement;
|
||||
use Filament\Actions;
|
||||
use Filament\Actions\Action;
|
||||
@ -256,9 +254,10 @@ protected function getHeaderActions(): array
|
||||
}
|
||||
|
||||
if ($result->status === 'deduped') {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Run already queued')
|
||||
->body('A connection check is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -294,9 +293,10 @@ protected function getHeaderActions(): array
|
||||
return;
|
||||
}
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Connection check queued')
|
||||
->body('Health check was queued and will run in the background.')
|
||||
->success()
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -493,9 +493,10 @@ protected function getHeaderActions(): array
|
||||
}
|
||||
|
||||
if ($result->status === 'deduped') {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Run already queued')
|
||||
->body('An inventory sync is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -525,9 +526,10 @@ protected function getHeaderActions(): array
|
||||
return;
|
||||
}
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Inventory sync queued')
|
||||
->body('Inventory sync was queued and will run in the background.')
|
||||
->success()
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -604,9 +606,10 @@ protected function getHeaderActions(): array
|
||||
}
|
||||
|
||||
if ($result->status === 'deduped') {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Run already queued')
|
||||
->body('A compliance snapshot is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -636,9 +639,10 @@ protected function getHeaderActions(): array
|
||||
return;
|
||||
}
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Compliance snapshot queued')
|
||||
->body('Compliance snapshot was queued and will run in the background.')
|
||||
->success()
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
|
||||
@ -2,8 +2,6 @@
|
||||
|
||||
namespace App\Filament\Resources;
|
||||
|
||||
use App\Contracts\Hardening\WriteGateInterface;
|
||||
use App\Exceptions\Hardening\ProviderAccessHardeningRequired;
|
||||
use App\Filament\Resources\RestoreRunResource\Pages;
|
||||
use App\Jobs\BulkRestoreRunDeleteJob;
|
||||
use App\Jobs\BulkRestoreRunForceDeleteJob;
|
||||
@ -53,7 +51,6 @@
|
||||
use Filament\Tables\Filters\TrashedFilter;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Str;
|
||||
@ -774,7 +771,216 @@ public static function table(Table $table): Table
|
||||
->actions([
|
||||
Actions\ViewAction::make(),
|
||||
ActionGroup::make([
|
||||
static::rerunActionWithGate(),
|
||||
UiEnforcement::forTableAction(
|
||||
Actions\Action::make('rerun')
|
||||
->label('Rerun')
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->color('primary')
|
||||
->requiresConfirmation()
|
||||
->visible(function (RestoreRun $record): bool {
|
||||
$backupSet = $record->backupSet;
|
||||
|
||||
return ! $record->trashed()
|
||||
&& $record->isDeletable()
|
||||
&& $backupSet !== null
|
||||
&& ! $backupSet->trashed();
|
||||
})
|
||||
->action(function (
|
||||
RestoreRun $record,
|
||||
RestoreService $restoreService,
|
||||
\App\Services\Intune\AuditLogger $auditLogger,
|
||||
HasTable $livewire
|
||||
) {
|
||||
$tenant = $record->tenant;
|
||||
$backupSet = $record->backupSet;
|
||||
|
||||
if ($record->trashed() || ! $tenant || ! $backupSet || $backupSet->trashed()) {
|
||||
Notification::make()
|
||||
->title('Restore run cannot be rerun')
|
||||
->body('Restore run or backup set is archived or unavailable.')
|
||||
->warning()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! (bool) $record->is_dry_run) {
|
||||
$selectedItemIds = is_array($record->requested_items) ? $record->requested_items : null;
|
||||
$groupMapping = is_array($record->group_mapping) ? $record->group_mapping : [];
|
||||
$actorEmail = auth()->user()?->email;
|
||||
$actorName = auth()->user()?->name;
|
||||
$tenantIdentifier = $tenant->tenant_id ?? $tenant->external_id;
|
||||
$highlanderLabel = (string) ($tenant->name ?? $tenantIdentifier ?? $tenant->getKey());
|
||||
|
||||
$preview = $restoreService->preview($tenant, $backupSet, $selectedItemIds);
|
||||
$metadata = [
|
||||
'scope_mode' => $selectedItemIds === null ? 'all' : 'selected',
|
||||
'environment' => app()->environment('production') ? 'prod' : 'test',
|
||||
'highlander_label' => $highlanderLabel,
|
||||
'confirmed_at' => now()->toIso8601String(),
|
||||
'confirmed_by' => $actorEmail,
|
||||
'confirmed_by_name' => $actorName,
|
||||
'rerun_of_restore_run_id' => $record->id,
|
||||
];
|
||||
|
||||
$idempotencyKey = RestoreRunIdempotency::restoreExecuteKey(
|
||||
tenantId: (int) $tenant->getKey(),
|
||||
backupSetId: (int) $backupSet->getKey(),
|
||||
selectedItemIds: $selectedItemIds,
|
||||
groupMapping: $groupMapping,
|
||||
);
|
||||
|
||||
$existing = RestoreRunIdempotency::findActiveRestoreRun((int) $tenant->getKey(), $idempotencyKey);
|
||||
|
||||
if ($existing) {
|
||||
Notification::make()
|
||||
->title('Restore already queued')
|
||||
->body('Reusing the active restore run.')
|
||||
->info()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$newRun = RestoreRun::create([
|
||||
'tenant_id' => $tenant->id,
|
||||
'backup_set_id' => $backupSet->id,
|
||||
'requested_by' => $actorEmail,
|
||||
'is_dry_run' => false,
|
||||
'status' => RestoreRunStatus::Queued->value,
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'requested_items' => $selectedItemIds,
|
||||
'preview' => $preview,
|
||||
'metadata' => $metadata,
|
||||
'group_mapping' => $groupMapping !== [] ? $groupMapping : null,
|
||||
]);
|
||||
} catch (QueryException $exception) {
|
||||
$existing = RestoreRunIdempotency::findActiveRestoreRun((int) $tenant->getKey(), $idempotencyKey);
|
||||
|
||||
if ($existing) {
|
||||
Notification::make()
|
||||
->title('Restore already queued')
|
||||
->body('Reusing the active restore run.')
|
||||
->info()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$auditLogger->log(
|
||||
tenant: $tenant,
|
||||
action: 'restore.queued',
|
||||
context: [
|
||||
'metadata' => [
|
||||
'restore_run_id' => $newRun->id,
|
||||
'backup_set_id' => $backupSet->id,
|
||||
'rerun_of_restore_run_id' => $record->id,
|
||||
],
|
||||
],
|
||||
actorEmail: $actorEmail,
|
||||
actorName: $actorName,
|
||||
resourceType: 'restore_run',
|
||||
resourceId: (string) $newRun->id,
|
||||
status: 'success',
|
||||
);
|
||||
|
||||
/** @var OperationRunService $runs */
|
||||
$runs = app(OperationRunService::class);
|
||||
$initiator = auth()->user();
|
||||
$initiator = $initiator instanceof \App\Models\User ? $initiator : null;
|
||||
|
||||
$opRun = $runs->ensureRun(
|
||||
tenant: $tenant,
|
||||
type: 'restore.execute',
|
||||
inputs: [
|
||||
'restore_run_id' => (int) $newRun->getKey(),
|
||||
'backup_set_id' => (int) $backupSet->getKey(),
|
||||
'is_dry_run' => (bool) ($newRun->is_dry_run ?? false),
|
||||
],
|
||||
initiator: $initiator,
|
||||
);
|
||||
|
||||
if ((int) ($newRun->operation_run_id ?? 0) !== (int) $opRun->getKey()) {
|
||||
$newRun->update(['operation_run_id' => $opRun->getKey()]);
|
||||
}
|
||||
|
||||
ExecuteRestoreRunJob::dispatch($newRun->id, $actorEmail, $actorName, $opRun);
|
||||
|
||||
$auditLogger->log(
|
||||
tenant: $tenant,
|
||||
action: 'restore_run.rerun',
|
||||
resourceType: 'restore_run',
|
||||
resourceId: (string) $newRun->id,
|
||||
status: 'success',
|
||||
context: [
|
||||
'metadata' => [
|
||||
'original_restore_run_id' => $record->id,
|
||||
'backup_set_id' => $backupSet->id,
|
||||
],
|
||||
],
|
||||
actorEmail: $actorEmail,
|
||||
actorName: $actorName,
|
||||
);
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
OperationUxPresenter::queuedToast('restore.execute')
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(OperationRunLinks::view($opRun, $tenant)),
|
||||
])
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$newRun = $restoreService->execute(
|
||||
tenant: $tenant,
|
||||
backupSet: $backupSet,
|
||||
selectedItemIds: $record->requested_items ?? null,
|
||||
dryRun: (bool) $record->is_dry_run,
|
||||
actorEmail: auth()->user()?->email,
|
||||
actorName: auth()->user()?->name,
|
||||
groupMapping: $record->group_mapping ?? []
|
||||
);
|
||||
} catch (\Throwable $throwable) {
|
||||
Notification::make()
|
||||
->title('Restore run failed to start')
|
||||
->body($throwable->getMessage())
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$auditLogger->log(
|
||||
tenant: $tenant,
|
||||
action: 'restore_run.rerun',
|
||||
resourceType: 'restore_run',
|
||||
resourceId: (string) $newRun->id,
|
||||
status: 'success',
|
||||
context: [
|
||||
'metadata' => [
|
||||
'original_restore_run_id' => $record->id,
|
||||
'backup_set_id' => $backupSet->id,
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
OperationUxPresenter::queuedToast('restore.execute')
|
||||
->send();
|
||||
}),
|
||||
fn () => Tenant::current(),
|
||||
)
|
||||
->requireCapability(Capabilities::TENANT_MANAGE)
|
||||
->preserveVisibility()
|
||||
->apply(),
|
||||
UiEnforcement::forTableAction(
|
||||
Actions\Action::make('restore')
|
||||
->label('Restore')
|
||||
@ -1351,37 +1557,6 @@ public static function createRestoreRun(array $data): RestoreRun
|
||||
abort(403);
|
||||
}
|
||||
|
||||
try {
|
||||
app(WriteGateInterface::class)->evaluate($tenant, 'restore.execute');
|
||||
} catch (ProviderAccessHardeningRequired $e) {
|
||||
app(\App\Services\Intune\AuditLogger::class)->log(
|
||||
tenant: $tenant,
|
||||
action: 'intune_rbac.write_blocked',
|
||||
status: 'blocked',
|
||||
actorId: (int) $user->getKey(),
|
||||
actorEmail: $user->email,
|
||||
actorName: $user->name,
|
||||
resourceType: 'restore_run',
|
||||
context: [
|
||||
'metadata' => [
|
||||
'operation_type' => 'restore.execute',
|
||||
'reason_code' => $e->reasonCode,
|
||||
'backup_set_id' => $data['backup_set_id'] ?? null,
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
Notification::make()
|
||||
->title('Write operation blocked')
|
||||
->body($e->reasonMessage)
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'backup_set_id' => $e->reasonMessage,
|
||||
]);
|
||||
}
|
||||
|
||||
/** @var BackupSet $backupSet */
|
||||
$backupSet = BackupSet::findOrFail($data['backup_set_id']);
|
||||
|
||||
@ -1535,23 +1710,11 @@ public static function createRestoreRun(array $data): RestoreRun
|
||||
$existing = RestoreRunIdempotency::findActiveRestoreRun((int) $tenant->getKey(), $idempotencyKey);
|
||||
|
||||
if ($existing) {
|
||||
$existingOpRunId = (int) ($existing->operation_run_id ?? 0);
|
||||
$existingOpRun = $existingOpRunId > 0
|
||||
? \App\Models\OperationRun::query()->find($existingOpRunId)
|
||||
: null;
|
||||
|
||||
$toast = OperationUxPresenter::alreadyQueuedToast('restore.execute')
|
||||
->body('Reusing the active restore run.');
|
||||
|
||||
if ($existingOpRun) {
|
||||
$toast->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(OperationRunLinks::view($existingOpRun, $tenant)),
|
||||
]);
|
||||
}
|
||||
|
||||
$toast->send();
|
||||
Notification::make()
|
||||
->title('Restore already queued')
|
||||
->body('Reusing the active restore run.')
|
||||
->info()
|
||||
->send();
|
||||
|
||||
return $existing;
|
||||
}
|
||||
@ -1573,23 +1736,11 @@ public static function createRestoreRun(array $data): RestoreRun
|
||||
$existing = RestoreRunIdempotency::findActiveRestoreRun((int) $tenant->getKey(), $idempotencyKey);
|
||||
|
||||
if ($existing) {
|
||||
$existingOpRunId = (int) ($existing->operation_run_id ?? 0);
|
||||
$existingOpRun = $existingOpRunId > 0
|
||||
? \App\Models\OperationRun::query()->find($existingOpRunId)
|
||||
: null;
|
||||
|
||||
$toast = OperationUxPresenter::alreadyQueuedToast('restore.execute')
|
||||
->body('Reusing the active restore run.');
|
||||
|
||||
if ($existingOpRun) {
|
||||
$toast->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(OperationRunLinks::view($existingOpRun, $tenant)),
|
||||
]);
|
||||
}
|
||||
|
||||
$toast->send();
|
||||
Notification::make()
|
||||
->title('Restore already queued')
|
||||
->body('Reusing the active restore run.')
|
||||
->info()
|
||||
->send();
|
||||
|
||||
return $existing;
|
||||
}
|
||||
@ -1825,343 +1976,4 @@ private static function normalizeGroupMapping(mixed $mapping): array
|
||||
|
||||
return array_filter($result, static fn (?string $value): bool => is_string($value) && $value !== '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the rerun table action with UiEnforcement + write gate disabled state.
|
||||
*
|
||||
* UiEnforcement::apply() overrides ->disabled() and ->tooltip(), so the gate
|
||||
* check must compose on top of the enforcement action AFTER apply(). This method
|
||||
* extracts the rerun action into its own builder to keep the table definition clean.
|
||||
*/
|
||||
private static function rerunActionWithGate(): Actions\Action|BulkAction
|
||||
{
|
||||
/** @var Actions\Action $action */
|
||||
$action = UiEnforcement::forTableAction(
|
||||
Actions\Action::make('rerun')
|
||||
->label('Rerun')
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->color('primary')
|
||||
->requiresConfirmation()
|
||||
->visible(function (RestoreRun $record): bool {
|
||||
$backupSet = $record->backupSet;
|
||||
|
||||
return ! $record->trashed()
|
||||
&& $record->isDeletable()
|
||||
&& $backupSet !== null
|
||||
&& ! $backupSet->trashed();
|
||||
})
|
||||
->action(function (
|
||||
RestoreRun $record,
|
||||
RestoreService $restoreService,
|
||||
\App\Services\Intune\AuditLogger $auditLogger,
|
||||
HasTable $livewire
|
||||
) {
|
||||
$tenant = $record->tenant;
|
||||
$backupSet = $record->backupSet;
|
||||
|
||||
if ($record->trashed() || ! $tenant || ! $backupSet || $backupSet->trashed()) {
|
||||
Notification::make()
|
||||
->title('Restore run cannot be rerun')
|
||||
->body('Restore run or backup set is archived or unavailable.')
|
||||
->warning()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
app(WriteGateInterface::class)->evaluate($tenant, 'restore.rerun');
|
||||
} catch (ProviderAccessHardeningRequired $e) {
|
||||
app(\App\Services\Intune\AuditLogger::class)->log(
|
||||
tenant: $tenant,
|
||||
action: 'intune_rbac.write_blocked',
|
||||
status: 'blocked',
|
||||
actorEmail: auth()->user()?->email,
|
||||
actorName: auth()->user()?->name,
|
||||
resourceType: 'restore_run',
|
||||
resourceId: (string) $record->getKey(),
|
||||
context: [
|
||||
'metadata' => [
|
||||
'operation_type' => 'restore.rerun',
|
||||
'reason_code' => $e->reasonCode,
|
||||
'backup_set_id' => $backupSet?->getKey(),
|
||||
'original_restore_run_id' => $record->getKey(),
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
Notification::make()
|
||||
->title('Write operation blocked')
|
||||
->body($e->reasonMessage)
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! (bool) $record->is_dry_run) {
|
||||
$selectedItemIds = is_array($record->requested_items) ? $record->requested_items : null;
|
||||
$groupMapping = is_array($record->group_mapping) ? $record->group_mapping : [];
|
||||
$actorEmail = auth()->user()?->email;
|
||||
$actorName = auth()->user()?->name;
|
||||
$tenantIdentifier = $tenant->tenant_id ?? $tenant->external_id;
|
||||
$highlanderLabel = (string) ($tenant->name ?? $tenantIdentifier ?? $tenant->getKey());
|
||||
|
||||
$preview = $restoreService->preview($tenant, $backupSet, $selectedItemIds);
|
||||
$metadata = [
|
||||
'scope_mode' => $selectedItemIds === null ? 'all' : 'selected',
|
||||
'environment' => app()->environment('production') ? 'prod' : 'test',
|
||||
'highlander_label' => $highlanderLabel,
|
||||
'confirmed_at' => now()->toIso8601String(),
|
||||
'confirmed_by' => $actorEmail,
|
||||
'confirmed_by_name' => $actorName,
|
||||
'rerun_of_restore_run_id' => $record->id,
|
||||
];
|
||||
|
||||
$idempotencyKey = RestoreRunIdempotency::restoreExecuteKey(
|
||||
tenantId: (int) $tenant->getKey(),
|
||||
backupSetId: (int) $backupSet->getKey(),
|
||||
selectedItemIds: $selectedItemIds,
|
||||
groupMapping: $groupMapping,
|
||||
);
|
||||
|
||||
$existing = RestoreRunIdempotency::findActiveRestoreRun((int) $tenant->getKey(), $idempotencyKey);
|
||||
|
||||
if ($existing) {
|
||||
$existingOpRunId = (int) ($existing->operation_run_id ?? 0);
|
||||
$existingOpRun = $existingOpRunId > 0
|
||||
? \App\Models\OperationRun::query()->find($existingOpRunId)
|
||||
: null;
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
|
||||
$toast = OperationUxPresenter::alreadyQueuedToast('restore.execute')
|
||||
->body('Reusing the active restore run.');
|
||||
|
||||
if ($existingOpRun) {
|
||||
$toast->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(OperationRunLinks::view($existingOpRun, $tenant)),
|
||||
]);
|
||||
}
|
||||
|
||||
$toast->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$newRun = RestoreRun::create([
|
||||
'tenant_id' => $tenant->id,
|
||||
'backup_set_id' => $backupSet->id,
|
||||
'requested_by' => $actorEmail,
|
||||
'is_dry_run' => false,
|
||||
'status' => RestoreRunStatus::Queued->value,
|
||||
'idempotency_key' => $idempotencyKey,
|
||||
'requested_items' => $selectedItemIds,
|
||||
'preview' => $preview,
|
||||
'metadata' => $metadata,
|
||||
'group_mapping' => $groupMapping !== [] ? $groupMapping : null,
|
||||
]);
|
||||
} catch (QueryException $exception) {
|
||||
$existing = RestoreRunIdempotency::findActiveRestoreRun((int) $tenant->getKey(), $idempotencyKey);
|
||||
|
||||
if ($existing) {
|
||||
$existingOpRunId = (int) ($existing->operation_run_id ?? 0);
|
||||
$existingOpRun = $existingOpRunId > 0
|
||||
? \App\Models\OperationRun::query()->find($existingOpRunId)
|
||||
: null;
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
|
||||
$toast = OperationUxPresenter::alreadyQueuedToast('restore.execute')
|
||||
->body('Reusing the active restore run.');
|
||||
|
||||
if ($existingOpRun) {
|
||||
$toast->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(OperationRunLinks::view($existingOpRun, $tenant)),
|
||||
]);
|
||||
}
|
||||
|
||||
$toast->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$auditLogger->log(
|
||||
tenant: $tenant,
|
||||
action: 'restore.queued',
|
||||
context: [
|
||||
'metadata' => [
|
||||
'restore_run_id' => $newRun->id,
|
||||
'backup_set_id' => $backupSet->id,
|
||||
'rerun_of_restore_run_id' => $record->id,
|
||||
],
|
||||
],
|
||||
actorEmail: $actorEmail,
|
||||
actorName: $actorName,
|
||||
resourceType: 'restore_run',
|
||||
resourceId: (string) $newRun->id,
|
||||
status: 'success',
|
||||
);
|
||||
|
||||
/** @var OperationRunService $runs */
|
||||
$runs = app(OperationRunService::class);
|
||||
$initiator = auth()->user();
|
||||
$initiator = $initiator instanceof \App\Models\User ? $initiator : null;
|
||||
|
||||
$opRun = $runs->ensureRun(
|
||||
tenant: $tenant,
|
||||
type: 'restore.execute',
|
||||
inputs: [
|
||||
'restore_run_id' => (int) $newRun->getKey(),
|
||||
'backup_set_id' => (int) $backupSet->getKey(),
|
||||
'is_dry_run' => (bool) ($newRun->is_dry_run ?? false),
|
||||
],
|
||||
initiator: $initiator,
|
||||
);
|
||||
|
||||
if ((int) ($newRun->operation_run_id ?? 0) !== (int) $opRun->getKey()) {
|
||||
$newRun->update(['operation_run_id' => $opRun->getKey()]);
|
||||
}
|
||||
|
||||
ExecuteRestoreRunJob::dispatch($newRun->id, $actorEmail, $actorName, $opRun);
|
||||
|
||||
$auditLogger->log(
|
||||
tenant: $tenant,
|
||||
action: 'restore_run.rerun',
|
||||
resourceType: 'restore_run',
|
||||
resourceId: (string) $newRun->id,
|
||||
status: 'success',
|
||||
context: [
|
||||
'metadata' => [
|
||||
'original_restore_run_id' => $record->id,
|
||||
'backup_set_id' => $backupSet->id,
|
||||
],
|
||||
],
|
||||
actorEmail: $actorEmail,
|
||||
actorName: $actorName,
|
||||
);
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
OperationUxPresenter::queuedToast('restore.execute')
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(OperationRunLinks::view($opRun, $tenant)),
|
||||
])
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$newRun = $restoreService->execute(
|
||||
tenant: $tenant,
|
||||
backupSet: $backupSet,
|
||||
selectedItemIds: $record->requested_items ?? null,
|
||||
dryRun: (bool) $record->is_dry_run,
|
||||
actorEmail: auth()->user()?->email,
|
||||
actorName: auth()->user()?->name,
|
||||
groupMapping: $record->group_mapping ?? []
|
||||
);
|
||||
} catch (\Throwable $throwable) {
|
||||
Notification::make()
|
||||
->title('Restore run failed to start')
|
||||
->body($throwable->getMessage())
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$auditLogger->log(
|
||||
tenant: $tenant,
|
||||
action: 'restore_run.rerun',
|
||||
resourceType: 'restore_run',
|
||||
resourceId: (string) $newRun->id,
|
||||
status: 'success',
|
||||
context: [
|
||||
'metadata' => [
|
||||
'original_restore_run_id' => $record->id,
|
||||
'backup_set_id' => $backupSet->id,
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
OperationUxPresenter::queuedToast('restore.execute')
|
||||
->send();
|
||||
}),
|
||||
fn () => Tenant::current(),
|
||||
)
|
||||
->requireCapability(Capabilities::TENANT_MANAGE)
|
||||
->preserveVisibility()
|
||||
->apply();
|
||||
|
||||
// Compose write gate disabled/tooltip on top of UiEnforcement's RBAC check.
|
||||
// UiEnforcement::apply() sets its own ->disabled() / ->tooltip();
|
||||
// we override here to merge both concerns.
|
||||
$action->disabled(function (?Model $record = null): bool {
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$tenant = $record instanceof RestoreRun ? $record->tenant : Tenant::current();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check RBAC capability first (mirrors UiEnforcement logic)
|
||||
$resolver = app(CapabilityResolver::class);
|
||||
|
||||
if (! $resolver->can($user, $tenant, Capabilities::TENANT_MANAGE)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Then check write gate
|
||||
return app(WriteGateInterface::class)->wouldBlock($tenant);
|
||||
});
|
||||
|
||||
$action->tooltip(function (?Model $record = null): ?string {
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return \App\Support\Auth\UiTooltips::insufficientPermission();
|
||||
}
|
||||
|
||||
$tenant = $record instanceof RestoreRun ? $record->tenant : Tenant::current();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return 'Tenant unavailable';
|
||||
}
|
||||
|
||||
// Check RBAC capability first
|
||||
$resolver = app(CapabilityResolver::class);
|
||||
|
||||
if (! $resolver->can($user, $tenant, Capabilities::TENANT_MANAGE)) {
|
||||
return \App\Support\Auth\UiTooltips::insufficientPermission();
|
||||
}
|
||||
|
||||
// Then check write gate
|
||||
try {
|
||||
app(WriteGateInterface::class)->evaluate($tenant, 'restore.rerun');
|
||||
} catch (ProviderAccessHardeningRequired $e) {
|
||||
return $e->reasonMessage;
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
return $action;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,352 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources;
|
||||
|
||||
use App\Filament\Resources\ReviewPackResource\Pages;
|
||||
use App\Models\ReviewPack;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\ReviewPackService;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\Badges\BadgeDomain;
|
||||
use App\Support\Badges\BadgeRenderer;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\Rbac\UiEnforcement;
|
||||
use App\Support\ReviewPackStatus;
|
||||
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceInspectAffordance;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
|
||||
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
|
||||
use BackedEnum;
|
||||
use Filament\Actions;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Number;
|
||||
use UnitEnum;
|
||||
|
||||
class ReviewPackResource extends Resource
|
||||
{
|
||||
protected static ?string $model = ReviewPack::class;
|
||||
|
||||
protected static ?string $tenantOwnershipRelationshipName = 'tenant';
|
||||
|
||||
protected static bool $isGloballySearchable = false;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-document-arrow-down';
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Reporting';
|
||||
|
||||
protected static ?string $navigationLabel = 'Review Packs';
|
||||
|
||||
protected static ?int $navigationSort = 50;
|
||||
|
||||
public static function canViewAny(): bool
|
||||
{
|
||||
$tenant = Tenant::current();
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $tenant instanceof Tenant || ! $user instanceof User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! $user->canAccessTenant($tenant)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->can(Capabilities::REVIEW_PACK_VIEW, $tenant);
|
||||
}
|
||||
|
||||
public static function canView(Model $record): bool
|
||||
{
|
||||
$tenant = Tenant::current();
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $tenant instanceof Tenant || ! $user instanceof User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! $user->canAccessTenant($tenant)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! $user->can(Capabilities::REVIEW_PACK_VIEW, $tenant)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($record instanceof ReviewPack) {
|
||||
return (int) $record->tenant_id === (int) $tenant->getKey();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
|
||||
{
|
||||
return ActionSurfaceDeclaration::forResource(ActionSurfaceProfile::CrudListAndView)
|
||||
->satisfy(ActionSurfaceSlot::ListHeader, 'Generate Pack action available in list header.')
|
||||
->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ViewAction->value)
|
||||
->satisfy(ActionSurfaceSlot::ListEmptyState, 'Empty state includes Generate CTA.')
|
||||
->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'Only two primary row actions (Download, Expire); no secondary menu needed.')
|
||||
->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'No bulk operations are supported for review packs.')
|
||||
->satisfy(ActionSurfaceSlot::DetailHeader, 'Download and Regenerate actions in ViewReviewPack header.');
|
||||
}
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema;
|
||||
}
|
||||
|
||||
public static function infolist(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->schema([
|
||||
Section::make('Status')
|
||||
->schema([
|
||||
TextEntry::make('status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::ReviewPackStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::ReviewPackStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::ReviewPackStatus))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::ReviewPackStatus)),
|
||||
TextEntry::make('tenant.name')->label('Tenant'),
|
||||
TextEntry::make('generated_at')->dateTime()->placeholder('—'),
|
||||
TextEntry::make('expires_at')->dateTime()->placeholder('—'),
|
||||
TextEntry::make('file_size')
|
||||
->label('File size')
|
||||
->formatStateUsing(fn ($state): string => $state ? Number::fileSize((int) $state) : '—'),
|
||||
TextEntry::make('sha256')->label('SHA-256')->copyable()->placeholder('—'),
|
||||
])
|
||||
->columns(2)
|
||||
->columnSpanFull(),
|
||||
|
||||
Section::make('Summary')
|
||||
->schema([
|
||||
TextEntry::make('summary.finding_count')->label('Findings')->placeholder('—'),
|
||||
TextEntry::make('summary.report_count')->label('Reports')->placeholder('—'),
|
||||
TextEntry::make('summary.operation_count')->label('Operations')->placeholder('—'),
|
||||
TextEntry::make('summary.data_freshness.permission_posture')
|
||||
->label('Permission posture freshness')
|
||||
->placeholder('—'),
|
||||
TextEntry::make('summary.data_freshness.entra_admin_roles')
|
||||
->label('Entra admin roles freshness')
|
||||
->placeholder('—'),
|
||||
TextEntry::make('summary.data_freshness.findings')
|
||||
->label('Findings freshness')
|
||||
->placeholder('—'),
|
||||
TextEntry::make('summary.data_freshness.hardening')
|
||||
->label('Hardening freshness')
|
||||
->placeholder('—'),
|
||||
])
|
||||
->columns(2)
|
||||
->columnSpanFull(),
|
||||
|
||||
Section::make('Options')
|
||||
->schema([
|
||||
TextEntry::make('options.include_pii')
|
||||
->label('Include PII')
|
||||
->formatStateUsing(fn ($state): string => $state ? 'Yes' : 'No'),
|
||||
TextEntry::make('options.include_operations')
|
||||
->label('Include operations')
|
||||
->formatStateUsing(fn ($state): string => $state ? 'Yes' : 'No'),
|
||||
])
|
||||
->columns(2)
|
||||
->columnSpanFull(),
|
||||
|
||||
Section::make('Metadata')
|
||||
->schema([
|
||||
TextEntry::make('initiator.name')->label('Initiated by')->placeholder('—'),
|
||||
TextEntry::make('operationRun.id')
|
||||
->label('Operation run')
|
||||
->url(fn (ReviewPack $record): ?string => $record->operation_run_id
|
||||
? route('admin.operations.view', ['run' => (int) $record->operation_run_id])
|
||||
: null)
|
||||
->openUrlInNewTab()
|
||||
->placeholder('—'),
|
||||
TextEntry::make('fingerprint')->label('Fingerprint')->copyable()->placeholder('—'),
|
||||
TextEntry::make('previous_fingerprint')->label('Previous fingerprint')->copyable()->placeholder('—'),
|
||||
TextEntry::make('created_at')->label('Created')->dateTime(),
|
||||
])
|
||||
->columns(2)
|
||||
->columnSpanFull(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('created_at', 'desc')
|
||||
->recordUrl(fn (ReviewPack $record): string => static::getUrl('view', ['record' => $record]))
|
||||
->columns([
|
||||
Tables\Columns\TextColumn::make('status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::ReviewPackStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::ReviewPackStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::ReviewPackStatus))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::ReviewPackStatus))
|
||||
->sortable(),
|
||||
Tables\Columns\TextColumn::make('tenant.name')
|
||||
->label('Tenant')
|
||||
->searchable(),
|
||||
Tables\Columns\TextColumn::make('generated_at')
|
||||
->dateTime()
|
||||
->sortable()
|
||||
->placeholder('—'),
|
||||
Tables\Columns\TextColumn::make('expires_at')
|
||||
->dateTime()
|
||||
->sortable()
|
||||
->placeholder('—'),
|
||||
Tables\Columns\TextColumn::make('file_size')
|
||||
->label('Size')
|
||||
->formatStateUsing(fn ($state): string => $state ? Number::fileSize((int) $state) : '—')
|
||||
->sortable(),
|
||||
Tables\Columns\TextColumn::make('created_at')
|
||||
->label('Created')
|
||||
->since()
|
||||
->toggleable(isToggledHiddenByDefault: true),
|
||||
])
|
||||
->filters([
|
||||
Tables\Filters\SelectFilter::make('status')
|
||||
->options(collect(ReviewPackStatus::cases())
|
||||
->mapWithKeys(fn (ReviewPackStatus $s): array => [$s->value => ucfirst($s->value)])
|
||||
->all()),
|
||||
])
|
||||
->actions([
|
||||
Actions\Action::make('download')
|
||||
->label('Download')
|
||||
->icon('heroicon-o-arrow-down-tray')
|
||||
->color('success')
|
||||
->visible(fn (ReviewPack $record): bool => $record->status === ReviewPackStatus::Ready->value)
|
||||
->url(function (ReviewPack $record): string {
|
||||
return app(ReviewPackService::class)->generateDownloadUrl($record);
|
||||
})
|
||||
->openUrlInNewTab(),
|
||||
UiEnforcement::forAction(
|
||||
Actions\Action::make('expire')
|
||||
->label('Expire')
|
||||
->icon('heroicon-o-clock')
|
||||
->color('danger')
|
||||
->visible(fn (ReviewPack $record): bool => $record->status === ReviewPackStatus::Ready->value)
|
||||
->requiresConfirmation()
|
||||
->modalDescription('This will mark the pack as expired and delete the file. This cannot be undone.')
|
||||
->action(function (ReviewPack $record): void {
|
||||
if ($record->file_path && $record->file_disk) {
|
||||
\Illuminate\Support\Facades\Storage::disk($record->file_disk)->delete($record->file_path);
|
||||
}
|
||||
|
||||
$record->update(['status' => ReviewPackStatus::Expired->value]);
|
||||
|
||||
Notification::make()
|
||||
->success()
|
||||
->title('Review pack expired')
|
||||
->send();
|
||||
})
|
||||
)
|
||||
->preserveVisibility()
|
||||
->requireCapability(Capabilities::REVIEW_PACK_MANAGE)
|
||||
->apply(),
|
||||
])
|
||||
->emptyStateHeading('No review packs yet')
|
||||
->emptyStateDescription('Generate a review pack to export tenant data for external review.')
|
||||
->emptyStateIcon('heroicon-o-document-arrow-down')
|
||||
->emptyStateActions([
|
||||
UiEnforcement::forAction(
|
||||
Actions\Action::make('generate_first')
|
||||
->label('Generate first pack')
|
||||
->icon('heroicon-o-plus')
|
||||
->action(function (array $data): void {
|
||||
static::executeGeneration($data);
|
||||
})
|
||||
->form([
|
||||
Section::make('Pack options')
|
||||
->schema([
|
||||
Toggle::make('include_pii')
|
||||
->label('Include PII')
|
||||
->helperText('Include personally identifiable information in the export.')
|
||||
->default(config('tenantpilot.review_pack.include_pii_default', true)),
|
||||
Toggle::make('include_operations')
|
||||
->label('Include operations')
|
||||
->helperText('Include recent operation history in the export.')
|
||||
->default(config('tenantpilot.review_pack.include_operations_default', true)),
|
||||
]),
|
||||
])
|
||||
)
|
||||
->requireCapability(Capabilities::REVIEW_PACK_MANAGE)
|
||||
->apply(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
$tenant = Filament::getTenant();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return parent::getEloquentQuery()->whereRaw('1 = 0');
|
||||
}
|
||||
|
||||
return parent::getEloquentQuery()->where('tenant_id', (int) $tenant->getKey());
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => Pages\ListReviewPacks::route('/'),
|
||||
'view' => Pages\ViewReviewPack::route('/{record}'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public static function executeGeneration(array $data): void
|
||||
{
|
||||
$tenant = Filament::getTenant();
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $tenant instanceof Tenant || ! $user instanceof User) {
|
||||
Notification::make()->danger()->title('Unable to generate pack — missing context.')->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$service = app(ReviewPackService::class);
|
||||
|
||||
if ($service->checkActiveRun($tenant)) {
|
||||
Notification::make()->warning()->title('A review pack is already being generated.')->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$options = [
|
||||
'include_pii' => (bool) ($data['include_pii'] ?? true),
|
||||
'include_operations' => (bool) ($data['include_operations'] ?? true),
|
||||
];
|
||||
|
||||
$reviewPack = $service->generate($tenant, $user, $options);
|
||||
|
||||
if (! $reviewPack->wasRecentlyCreated) {
|
||||
Notification::make()
|
||||
->success()
|
||||
->title('Review pack already available')
|
||||
->body('A matching review pack is already ready. No new run was started.')
|
||||
->actions([
|
||||
Actions\Action::make('view_pack')
|
||||
->label('View pack')
|
||||
->url(static::getUrl('view', ['record' => $reviewPack], tenant: $tenant)),
|
||||
])
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
OperationUxPresenter::queuedToast('tenant.review_pack.generate')->send();
|
||||
}
|
||||
}
|
||||
@ -1,45 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\ReviewPackResource\Pages;
|
||||
|
||||
use App\Filament\Resources\ReviewPackResource;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\Rbac\UiEnforcement;
|
||||
use Filament\Actions;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Filament\Schemas\Components\Section;
|
||||
|
||||
class ListReviewPacks extends ListRecords
|
||||
{
|
||||
protected static string $resource = ReviewPackResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
UiEnforcement::forAction(
|
||||
Actions\Action::make('generate_pack')
|
||||
->label('Generate Pack')
|
||||
->icon('heroicon-o-plus')
|
||||
->action(function (array $data): void {
|
||||
ReviewPackResource::executeGeneration($data);
|
||||
})
|
||||
->form([
|
||||
Section::make('Pack options')
|
||||
->schema([
|
||||
Toggle::make('include_pii')
|
||||
->label('Include PII')
|
||||
->helperText('Include personally identifiable information in the export.')
|
||||
->default(config('tenantpilot.review_pack.include_pii_default', true)),
|
||||
Toggle::make('include_operations')
|
||||
->label('Include operations')
|
||||
->helperText('Include recent operation history in the export.')
|
||||
->default(config('tenantpilot.review_pack.include_operations_default', true)),
|
||||
]),
|
||||
])
|
||||
)
|
||||
->requireCapability(Capabilities::REVIEW_PACK_MANAGE)
|
||||
->apply(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,73 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\ReviewPackResource\Pages;
|
||||
|
||||
use App\Filament\Resources\ReviewPackResource;
|
||||
use App\Models\ReviewPack;
|
||||
use App\Services\ReviewPackService;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\Rbac\UiEnforcement;
|
||||
use App\Support\ReviewPackStatus;
|
||||
use Filament\Actions;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Filament\Schemas\Components\Section;
|
||||
|
||||
class ViewReviewPack extends ViewRecord
|
||||
{
|
||||
protected static string $resource = ReviewPackResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Actions\Action::make('download')
|
||||
->label('Download')
|
||||
->icon('heroicon-o-arrow-down-tray')
|
||||
->color('success')
|
||||
->visible(fn (): bool => $this->record->status === ReviewPackStatus::Ready->value)
|
||||
->url(fn (): string => app(ReviewPackService::class)->generateDownloadUrl($this->record))
|
||||
->openUrlInNewTab(),
|
||||
|
||||
UiEnforcement::forAction(
|
||||
Actions\Action::make('regenerate')
|
||||
->label('Regenerate')
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->color('primary')
|
||||
->requiresConfirmation()
|
||||
->modalDescription('This will generate a new review pack with the same options. The current pack will remain available until it expires.')
|
||||
->action(function (array $data): void {
|
||||
/** @var ReviewPack $record */
|
||||
$record = $this->record;
|
||||
|
||||
$options = array_merge($record->options ?? [], [
|
||||
'include_pii' => (bool) ($data['include_pii'] ?? ($record->options['include_pii'] ?? true)),
|
||||
'include_operations' => (bool) ($data['include_operations'] ?? ($record->options['include_operations'] ?? true)),
|
||||
]);
|
||||
|
||||
ReviewPackResource::executeGeneration($options);
|
||||
})
|
||||
->form(function (): array {
|
||||
/** @var ReviewPack $record */
|
||||
$record = $this->record;
|
||||
$currentOptions = $record->options ?? [];
|
||||
|
||||
return [
|
||||
Section::make('Pack options')
|
||||
->schema([
|
||||
Toggle::make('include_pii')
|
||||
->label('Include PII')
|
||||
->helperText('Include personally identifiable information in the export.')
|
||||
->default((bool) ($currentOptions['include_pii'] ?? true)),
|
||||
Toggle::make('include_operations')
|
||||
->label('Include operations')
|
||||
->helperText('Include recent operation history in the export.')
|
||||
->default((bool) ($currentOptions['include_operations'] ?? true)),
|
||||
]),
|
||||
];
|
||||
})
|
||||
)
|
||||
->requireCapability(Capabilities::REVIEW_PACK_MANAGE)
|
||||
->apply(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -12,6 +12,7 @@
|
||||
use App\Models\ProviderConnection;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Services\Auth\CapabilityResolver;
|
||||
use App\Services\Auth\RoleCapabilityMap;
|
||||
use App\Services\Directory\EntraGroupLabelResolver;
|
||||
@ -45,7 +46,6 @@
|
||||
use Filament\Infolists;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Components\Utilities\Set;
|
||||
use Filament\Schemas\Schema;
|
||||
@ -75,13 +75,29 @@ class TenantResource extends Resource
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Settings';
|
||||
|
||||
/**
|
||||
* Tenant creation is handled exclusively by the onboarding wizard.
|
||||
* The CRUD create page has been removed.
|
||||
*/
|
||||
public static function canCreate(): bool
|
||||
{
|
||||
return false;
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (static::userCanManageAnyTenant($user)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();
|
||||
|
||||
if ($workspaceId === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return WorkspaceMembership::query()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->where('user_id', $user->getKey())
|
||||
->whereIn('role', ['owner', 'manager'])
|
||||
->exists();
|
||||
}
|
||||
|
||||
public static function canEdit(Model $record): bool
|
||||
@ -354,8 +370,10 @@ public static function table(Table $table): Table
|
||||
}
|
||||
|
||||
if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'], true)) {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
|
||||
Notification::make()
|
||||
->title('Policy sync already active')
|
||||
->body('This operation is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View Run')
|
||||
@ -470,7 +488,6 @@ public static function table(Table $table): Table
|
||||
->action(function (
|
||||
Tenant $record,
|
||||
StartVerification $verification,
|
||||
\Filament\Tables\Contracts\HasTable $livewire,
|
||||
): void {
|
||||
$user = auth()->user();
|
||||
|
||||
@ -495,8 +512,6 @@ public static function table(Table $table): Table
|
||||
$runUrl = OperationRunLinks::tenantlessView($result->run);
|
||||
|
||||
if ($result->status === 'scope_busy') {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
|
||||
Notification::make()
|
||||
->title('Another operation is already running')
|
||||
->body('Please wait for the active run to finish.')
|
||||
@ -512,9 +527,10 @@ public static function table(Table $table): Table
|
||||
}
|
||||
|
||||
if ($result->status === 'deduped') {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Verification already running')
|
||||
->body('A verification run is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -568,9 +584,9 @@ public static function table(Table $table): Table
|
||||
return;
|
||||
}
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Verification started')
|
||||
->success()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -753,6 +769,7 @@ public static function table(Table $table): Table
|
||||
->body('No eligible tenants selected.')
|
||||
->icon('heroicon-o-information-circle')
|
||||
->info()
|
||||
->sendToDatabase($user)
|
||||
->send();
|
||||
|
||||
return;
|
||||
@ -815,153 +832,69 @@ public static function infolist(Schema $schema): Schema
|
||||
// ... [Infolist Omitted - No Change] ...
|
||||
return $schema
|
||||
->schema([
|
||||
Section::make('Identity')
|
||||
Infolists\Components\TextEntry::make('name'),
|
||||
Infolists\Components\TextEntry::make('tenant_id')->label('Tenant ID')->copyable(),
|
||||
Infolists\Components\TextEntry::make('domain')->copyable(),
|
||||
Infolists\Components\TextEntry::make('status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::TenantStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::TenantStatus))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantStatus)),
|
||||
Infolists\Components\TextEntry::make('app_status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantAppStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::TenantAppStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::TenantAppStatus))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantAppStatus)),
|
||||
Infolists\Components\ViewEntry::make('provider_connection_state')
|
||||
->label('Provider connection')
|
||||
->state(fn (Tenant $record): array => static::providerConnectionState($record))
|
||||
->view('filament.infolists.entries.provider-connection-state')
|
||||
->columnSpanFull(),
|
||||
Infolists\Components\TextEntry::make('created_at')->dateTime(),
|
||||
Infolists\Components\TextEntry::make('updated_at')->dateTime(),
|
||||
Infolists\Components\TextEntry::make('rbac_status')
|
||||
->label('RBAC status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantRbacStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::TenantRbacStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::TenantRbacStatus))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantRbacStatus)),
|
||||
Infolists\Components\TextEntry::make('rbac_status_reason')->label('RBAC reason'),
|
||||
Infolists\Components\TextEntry::make('rbac_last_checked_at')->label('RBAC last checked')->since(),
|
||||
Infolists\Components\TextEntry::make('rbac_role_display_name')->label('RBAC role'),
|
||||
Infolists\Components\TextEntry::make('rbac_role_definition_id')->label('Role definition ID')->copyable(),
|
||||
Infolists\Components\TextEntry::make('rbac_scope_mode')->label('RBAC scope'),
|
||||
Infolists\Components\TextEntry::make('rbac_scope_id')->label('Scope ID'),
|
||||
Infolists\Components\TextEntry::make('rbac_group_id')->label('RBAC group ID')->copyable(),
|
||||
Infolists\Components\TextEntry::make('rbac_role_assignment_id')->label('Role assignment ID')->copyable(),
|
||||
Infolists\Components\ViewEntry::make('rbac_summary')
|
||||
->label('Last RBAC Setup')
|
||||
->view('filament.infolists.entries.rbac-summary')
|
||||
->visible(fn (Tenant $record) => filled($record->rbac_last_setup_at)),
|
||||
Infolists\Components\TextEntry::make('admin_consent_url')
|
||||
->label('Admin consent URL')
|
||||
->state(fn (Tenant $record) => static::adminConsentUrl($record))
|
||||
->visible(fn (?string $state) => filled($state))
|
||||
->copyable(),
|
||||
Infolists\Components\RepeatableEntry::make('permissions')
|
||||
->label('Required permissions')
|
||||
->state(fn (Tenant $record) => static::storedPermissionSnapshot($record))
|
||||
->schema([
|
||||
Infolists\Components\TextEntry::make('name'),
|
||||
Infolists\Components\TextEntry::make('tenant_id')->label('Tenant ID')->copyable(),
|
||||
Infolists\Components\TextEntry::make('domain')->copyable(),
|
||||
Infolists\Components\TextEntry::make('key')->label('Permission')->badge(),
|
||||
Infolists\Components\TextEntry::make('type')->badge(),
|
||||
Infolists\Components\TextEntry::make('features')
|
||||
->label('Features')
|
||||
->formatStateUsing(fn ($state) => is_array($state) ? implode(', ', $state) : (string) $state),
|
||||
Infolists\Components\TextEntry::make('status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::TenantStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::TenantStatus))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantStatus)),
|
||||
Infolists\Components\TextEntry::make('app_status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantAppStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::TenantAppStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::TenantAppStatus))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantAppStatus)),
|
||||
])
|
||||
->columns(2)
|
||||
->columnSpanFull(),
|
||||
Section::make('Provider')
|
||||
->schema([
|
||||
Infolists\Components\ViewEntry::make('provider_connection_state')
|
||||
->label('Provider connection')
|
||||
->state(fn (Tenant $record): array => static::providerConnectionState($record))
|
||||
->view('filament.infolists.entries.provider-connection-state')
|
||||
->columnSpanFull(),
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantPermissionStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::TenantPermissionStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::TenantPermissionStatus))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantPermissionStatus)),
|
||||
])
|
||||
->columnSpanFull(),
|
||||
Section::make('RBAC')
|
||||
->schema([
|
||||
Infolists\Components\TextEntry::make('rbac_not_configured_hint')
|
||||
->label('Status')
|
||||
->state('Not configured — Intune RBAC has not been set up for this tenant. Write operations will be blocked.')
|
||||
->icon('heroicon-o-shield-exclamation')
|
||||
->color('warning')
|
||||
->columnSpanFull()
|
||||
->visible(fn (Tenant $record): bool => blank($record->rbac_status)),
|
||||
Infolists\Components\TextEntry::make('rbac_status')
|
||||
->label('RBAC status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantRbacStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::TenantRbacStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::TenantRbacStatus))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantRbacStatus))
|
||||
->visible(fn (Tenant $record): bool => filled($record->rbac_status)),
|
||||
Infolists\Components\TextEntry::make('rbac_explanation')
|
||||
->label('Summary')
|
||||
->state(function (Tenant $record): string {
|
||||
$status = $record->rbac_status;
|
||||
$lastChecked = $record->rbac_last_checked_at;
|
||||
$threshold = (int) config('tenantpilot.hardening.intune_write_gate.freshness_threshold_hours', 24);
|
||||
|
||||
if (blank($status) || $status === 'not_configured') {
|
||||
return 'RBAC is not configured. Write operations to this tenant are blocked until RBAC is set up.';
|
||||
}
|
||||
|
||||
if (in_array($status, ['degraded', 'failed', 'error', 'missing', 'partial'], true)) {
|
||||
return 'RBAC health check reported an unhealthy state. Write operations are blocked.';
|
||||
}
|
||||
|
||||
if ($status === 'ok' && ($lastChecked === null || $lastChecked->diffInHours(now()) >= $threshold)) {
|
||||
return "RBAC status is OK but the last health check is older than {$threshold} hours. Write operations are blocked until refreshed.";
|
||||
}
|
||||
|
||||
return 'RBAC is healthy and up to date. Write operations are permitted.';
|
||||
})
|
||||
->columnSpanFull()
|
||||
->visible(fn (Tenant $record): bool => filled($record->rbac_status)),
|
||||
Infolists\Components\TextEntry::make('rbac_last_checked_at')
|
||||
->label('Last checked')
|
||||
->since()
|
||||
->visible(fn (Tenant $record): bool => filled($record->rbac_status)),
|
||||
Infolists\Components\TextEntry::make('rbac_role_display_name')
|
||||
->label('RBAC role')
|
||||
->visible(fn (Tenant $record): bool => filled($record->rbac_status)),
|
||||
Section::make('RBAC Details')
|
||||
->schema([
|
||||
Infolists\Components\TextEntry::make('rbac_status_reason')
|
||||
->label('Reason'),
|
||||
Infolists\Components\TextEntry::make('rbac_role_definition_id')
|
||||
->label('Role definition ID')
|
||||
->copyable(),
|
||||
Infolists\Components\TextEntry::make('rbac_scope_mode')
|
||||
->label('Scope'),
|
||||
Infolists\Components\TextEntry::make('rbac_scope_id')
|
||||
->label('Scope ID'),
|
||||
Infolists\Components\TextEntry::make('rbac_group_id')
|
||||
->label('Group ID')
|
||||
->copyable(),
|
||||
Infolists\Components\TextEntry::make('rbac_role_assignment_id')
|
||||
->label('Role assignment ID')
|
||||
->copyable(),
|
||||
Infolists\Components\ViewEntry::make('rbac_summary')
|
||||
->label('Last RBAC Setup')
|
||||
->view('filament.infolists.entries.rbac-summary')
|
||||
->visible(fn (Tenant $record) => filled($record->rbac_last_setup_at)),
|
||||
])
|
||||
->columns(2)
|
||||
->collapsible()
|
||||
->collapsed()
|
||||
->visible(fn (Tenant $record): bool => filled($record->rbac_status)),
|
||||
])
|
||||
->columns(2)
|
||||
->columnSpanFull()
|
||||
->collapsible(),
|
||||
Section::make('Integration')
|
||||
->schema([
|
||||
Infolists\Components\TextEntry::make('admin_consent_url')
|
||||
->label('Admin consent URL')
|
||||
->state(fn (Tenant $record) => static::adminConsentUrl($record))
|
||||
->visible(fn (?string $state) => filled($state))
|
||||
->copyable()
|
||||
->columnSpanFull(),
|
||||
])
|
||||
->columnSpanFull()
|
||||
->collapsible(),
|
||||
Section::make('Metadata')
|
||||
->schema([
|
||||
Infolists\Components\TextEntry::make('created_at')->dateTime(),
|
||||
Infolists\Components\TextEntry::make('updated_at')->dateTime(),
|
||||
])
|
||||
->columns(2)
|
||||
->columnSpanFull()
|
||||
->collapsed(),
|
||||
Section::make('Required permissions')
|
||||
->schema([
|
||||
Infolists\Components\RepeatableEntry::make('permissions')
|
||||
->label('')
|
||||
->state(fn (Tenant $record) => static::storedPermissionSnapshot($record))
|
||||
->schema([
|
||||
Infolists\Components\TextEntry::make('key')->label('Permission')->badge(),
|
||||
Infolists\Components\TextEntry::make('type')->badge(),
|
||||
Infolists\Components\TextEntry::make('features')
|
||||
->label('Features')
|
||||
->formatStateUsing(fn ($state) => is_array($state) ? implode(', ', $state) : (string) $state),
|
||||
Infolists\Components\TextEntry::make('status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantPermissionStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::TenantPermissionStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::TenantPermissionStatus))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantPermissionStatus)),
|
||||
])
|
||||
->columnSpanFull(),
|
||||
])
|
||||
->columnSpanFull()
|
||||
->collapsible(),
|
||||
]);
|
||||
}
|
||||
|
||||
@ -1005,6 +938,7 @@ public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => Pages\ListTenants::route('/'),
|
||||
'create' => Pages\CreateTenant::route('/create'),
|
||||
'view' => Pages\ViewTenant::route('/{record}'),
|
||||
'edit' => Pages\EditTenant::route('/{record}/edit'),
|
||||
'memberships' => Pages\ManageTenantMemberships::route('/{record}/memberships'),
|
||||
@ -1233,10 +1167,17 @@ public static function adminConsentUrl(Tenant $tenant): ?string
|
||||
return null;
|
||||
}
|
||||
|
||||
// Admin consent should use `.default` so the tenant consents to the app's configured
|
||||
// application permissions. Keeping the URL short also avoids edge cases where a long
|
||||
// scope string gets truncated and causes AADSTS900144 (missing `scope`).
|
||||
$scopes = 'https://graph.microsoft.com/.default';
|
||||
// Build explicit scope list from required permissions
|
||||
$requiredPermissions = config('intune_permissions.permissions', []);
|
||||
$scopes = collect($requiredPermissions)
|
||||
->pluck('key')
|
||||
->map(fn (string $permission) => "https://graph.microsoft.com/{$permission}")
|
||||
->join(' ');
|
||||
|
||||
// Fallback to .default if no permissions configured
|
||||
if (empty($scopes)) {
|
||||
$scopes = 'https://graph.microsoft.com/.default';
|
||||
}
|
||||
|
||||
$query = http_build_query([
|
||||
'client_id' => $clientId,
|
||||
@ -1605,7 +1546,10 @@ public static function syncRoleDefinitionsAction(): Actions\Action
|
||||
$runUrl = OperationRunLinks::tenantlessView($opRun);
|
||||
|
||||
if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'], true)) {
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
|
||||
Notification::make()
|
||||
->title('Role definitions sync already active')
|
||||
->body('This operation is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
|
||||
41
app/Filament/Resources/TenantResource/Pages/CreateTenant.php
Normal file
41
app/Filament/Resources/TenantResource/Pages/CreateTenant.php
Normal file
@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\TenantResource\Pages;
|
||||
|
||||
use App\Filament\Resources\TenantResource;
|
||||
use App\Models\User;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateTenant extends CreateRecord
|
||||
{
|
||||
protected static string $resource = TenantResource::class;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();
|
||||
|
||||
if ($workspaceId !== null) {
|
||||
$data['workspace_id'] = $workspaceId;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
protected function afterCreate(): void
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return;
|
||||
}
|
||||
|
||||
$user->tenants()->syncWithoutDetaching([
|
||||
$this->record->getKey() => ['role' => 'owner'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -13,10 +13,9 @@ class ListTenants extends ListRecords
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Actions\Action::make('add_tenant')
|
||||
->label('Add tenant')
|
||||
->icon('heroicon-m-plus')
|
||||
->url(route('admin.onboarding'))
|
||||
Actions\CreateAction::make()
|
||||
->disabled(fn (): bool => ! TenantResource::canCreate())
|
||||
->tooltip(fn (): ?string => TenantResource::canCreate() ? null : 'You do not have permission to register tenants.')
|
||||
->visible(fn (): bool => $this->getTableRecords()->count() > 0),
|
||||
];
|
||||
}
|
||||
@ -24,10 +23,9 @@ protected function getHeaderActions(): array
|
||||
protected function getTableEmptyStateActions(): array
|
||||
{
|
||||
return [
|
||||
Actions\Action::make('add_tenant')
|
||||
->label('Add tenant')
|
||||
->icon('heroicon-m-plus')
|
||||
->url(route('admin.onboarding')),
|
||||
Actions\CreateAction::make()
|
||||
->disabled(fn (): bool => ! TenantResource::canCreate())
|
||||
->tooltip(fn (): ?string => TenantResource::canCreate() ? null : 'You do not have permission to register tenants.'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,21 +4,15 @@
|
||||
|
||||
use App\Filament\Resources\ProviderConnectionResource;
|
||||
use App\Filament\Resources\TenantResource;
|
||||
use App\Filament\Widgets\Tenant\AdminRolesSummaryWidget;
|
||||
use App\Filament\Widgets\Tenant\RecentOperationsSummary;
|
||||
use App\Filament\Widgets\Tenant\TenantArchivedBanner;
|
||||
use App\Filament\Widgets\Tenant\TenantVerificationReport;
|
||||
use App\Jobs\RefreshTenantRbacHealthJob;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\Intune\AuditLogger;
|
||||
use App\Services\OperationRunService;
|
||||
use App\Services\Verification\StartVerification;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\OperationRunLinks;
|
||||
use App\Support\OperationRunType;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||
use App\Support\Rbac\UiEnforcement;
|
||||
use Filament\Actions;
|
||||
use Filament\Notifications\Notification;
|
||||
@ -28,18 +22,12 @@ class ViewTenant extends ViewRecord
|
||||
{
|
||||
protected static string $resource = TenantResource::class;
|
||||
|
||||
public function getHeaderWidgetsColumns(): int|array
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
protected function getHeaderWidgets(): array
|
||||
{
|
||||
return [
|
||||
TenantArchivedBanner::class,
|
||||
RecentOperationsSummary::class,
|
||||
TenantVerificationReport::class,
|
||||
AdminRolesSummaryWidget::class,
|
||||
];
|
||||
}
|
||||
|
||||
@ -109,8 +97,6 @@ protected function getHeaderActions(): array
|
||||
$runUrl = OperationRunLinks::tenantlessView($result->run);
|
||||
|
||||
if ($result->status === 'scope_busy') {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
Notification::make()
|
||||
->title('Another operation is already running')
|
||||
->body('Please wait for the active run to finish.')
|
||||
@ -126,9 +112,10 @@ protected function getHeaderActions(): array
|
||||
}
|
||||
|
||||
if ($result->status === 'deduped') {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Verification already running')
|
||||
->body('A verification run is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -182,9 +169,9 @@ protected function getHeaderActions(): array
|
||||
return;
|
||||
}
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Verification started')
|
||||
->success()
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -197,73 +184,6 @@ protected function getHeaderActions(): array
|
||||
->requireCapability(Capabilities::PROVIDER_RUN)
|
||||
->apply(),
|
||||
TenantResource::rbacAction(),
|
||||
UiEnforcement::forAction(
|
||||
Actions\Action::make('refresh_rbac')
|
||||
->label('Refresh RBAC status')
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->color('primary')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (Tenant $record): bool => $record->isActive())
|
||||
->action(function (Tenant $record): void {
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
if (! $user->canAccessTenant($record)) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
/** @var OperationRunService $runs */
|
||||
$runs = app(OperationRunService::class);
|
||||
|
||||
$opRun = $runs->ensureRun(
|
||||
tenant: $record,
|
||||
type: OperationRunType::RbacHealthCheck->value,
|
||||
inputs: [
|
||||
'tenant_id' => (int) $record->getKey(),
|
||||
'surface' => 'tenant_view_header',
|
||||
],
|
||||
initiator: $user,
|
||||
);
|
||||
|
||||
$runUrl = OperationRunLinks::tenantlessView($opRun);
|
||||
|
||||
if ($opRun->wasRecentlyCreated === false) {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url($runUrl),
|
||||
])
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
RefreshTenantRbacHealthJob::dispatch(
|
||||
(int) $record->getKey(),
|
||||
(int) $user->getKey(),
|
||||
$opRun,
|
||||
);
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $opRun->type)
|
||||
->actions([
|
||||
Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url($runUrl),
|
||||
])
|
||||
->send();
|
||||
}),
|
||||
)
|
||||
->preserveVisibility()
|
||||
->requireCapability(Capabilities::PROVIDER_RUN)
|
||||
->apply(),
|
||||
UiEnforcement::forAction(
|
||||
Actions\Action::make('archive')
|
||||
->label('Deactivate')
|
||||
|
||||
@ -9,42 +9,18 @@
|
||||
use App\Services\Intune\AuditLogger;
|
||||
use Filament\Auth\Http\Responses\Contracts\LoginResponse;
|
||||
use Filament\Auth\Pages\Login as BaseLogin;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class Login extends BaseLogin
|
||||
{
|
||||
/**
|
||||
* Filament's base login page uses Livewire-level rate limiting. We override it
|
||||
* to enforce the System panel policy via Laravel's RateLimiter (SR-003).
|
||||
*/
|
||||
protected function rateLimit($maxAttempts, $decaySeconds = 60, $method = null, $component = null): void
|
||||
{
|
||||
}
|
||||
|
||||
public function authenticate(): ?LoginResponse
|
||||
{
|
||||
$data = $this->form->getState();
|
||||
$email = (string) ($data['email'] ?? '');
|
||||
$throttleKey = $this->throttleKey($email);
|
||||
|
||||
if (RateLimiter::tooManyAttempts($throttleKey, 10)) {
|
||||
$this->audit(status: 'failure', email: $email, actor: null, reason: 'throttled');
|
||||
|
||||
$seconds = RateLimiter::availableIn($throttleKey);
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'data.email' => __('auth.throttle', [
|
||||
'seconds' => $seconds,
|
||||
'minutes' => (int) ceil($seconds / 60),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
try {
|
||||
$response = parent::authenticate();
|
||||
} catch (ValidationException $exception) {
|
||||
RateLimiter::hit($throttleKey, 60);
|
||||
$this->audit(status: 'failure', email: $email, actor: null, reason: 'invalid_credentials');
|
||||
|
||||
throw $exception;
|
||||
@ -64,7 +40,6 @@ public function authenticate(): ?LoginResponse
|
||||
if (! $user->is_active) {
|
||||
auth('platform')->logout();
|
||||
|
||||
RateLimiter::hit($throttleKey, 60);
|
||||
$this->audit(status: 'failure', email: $email, actor: null, reason: 'inactive');
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
@ -72,7 +47,6 @@ public function authenticate(): ?LoginResponse
|
||||
]);
|
||||
}
|
||||
|
||||
RateLimiter::clear($throttleKey);
|
||||
$user->forceFill(['last_login_at' => now()])->saveQuietly();
|
||||
|
||||
$this->audit(status: 'success', email: $email, actor: $user);
|
||||
@ -80,14 +54,6 @@ public function authenticate(): ?LoginResponse
|
||||
return $response;
|
||||
}
|
||||
|
||||
private function throttleKey(string $email): string
|
||||
{
|
||||
$ip = (string) request()->ip();
|
||||
$normalizedEmail = mb_strtolower(trim($email));
|
||||
|
||||
return "system-login:{$ip}:{$normalizedEmail}";
|
||||
}
|
||||
|
||||
private function audit(string $status, string $email, ?PlatformUser $actor, ?string $reason = null): void
|
||||
{
|
||||
$tenant = Tenant::query()->where('external_id', 'platform')->first();
|
||||
|
||||
@ -4,79 +4,16 @@
|
||||
|
||||
namespace App\Filament\System\Pages;
|
||||
|
||||
use App\Filament\System\Widgets\ControlTowerHealthIndicator;
|
||||
use App\Filament\System\Widgets\ControlTowerKpis;
|
||||
use App\Filament\System\Widgets\ControlTowerRecentFailures;
|
||||
use App\Filament\System\Widgets\ControlTowerTopOffenders;
|
||||
use App\Models\PlatformUser;
|
||||
use App\Services\Auth\BreakGlassSession;
|
||||
use App\Support\Auth\PlatformCapabilities;
|
||||
use App\Support\SystemConsole\SystemConsoleWindow;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Dashboard as BaseDashboard;
|
||||
use Filament\Widgets\Widget;
|
||||
use Filament\Widgets\WidgetConfiguration;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Dashboard extends BaseDashboard
|
||||
{
|
||||
public string $window = SystemConsoleWindow::LastDay;
|
||||
|
||||
/**
|
||||
* @param array<mixed> $parameters
|
||||
*/
|
||||
public static function getUrl(array $parameters = [], bool $isAbsolute = true, ?string $panel = null, ?Model $tenant = null, bool $shouldGuessMissingParameters = false): string
|
||||
{
|
||||
return parent::getUrl($parameters, $isAbsolute, $panel ?? 'system', $tenant, $shouldGuessMissingParameters);
|
||||
}
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
if (! $user instanceof PlatformUser) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! $user->hasCapability(PlatformCapabilities::ACCESS_SYSTEM_PANEL)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->hasCapability(PlatformCapabilities::CONSOLE_VIEW)
|
||||
|| ($user->hasCapability(PlatformCapabilities::OPS_VIEW) && $user->hasCapability(PlatformCapabilities::RUNBOOKS_VIEW));
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->window = SystemConsoleWindow::fromNullable((string) request()->query('window', $this->window))->value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<class-string<Widget> | WidgetConfiguration>
|
||||
*/
|
||||
public function getWidgets(): array
|
||||
{
|
||||
return [
|
||||
ControlTowerHealthIndicator::class,
|
||||
ControlTowerKpis::class,
|
||||
ControlTowerTopOffenders::class,
|
||||
ControlTowerRecentFailures::class,
|
||||
];
|
||||
}
|
||||
|
||||
public function getColumns(): int|array
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public function selectedWindow(): SystemConsoleWindow
|
||||
{
|
||||
return SystemConsoleWindow::fromNullable($this->window);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<Action>
|
||||
*/
|
||||
@ -90,27 +27,6 @@ protected function getHeaderActions(): array
|
||||
&& $user->hasCapability(PlatformCapabilities::USE_BREAK_GLASS);
|
||||
|
||||
return [
|
||||
Action::make('set_window')
|
||||
->label('Time window')
|
||||
->icon('heroicon-o-clock')
|
||||
->color('gray')
|
||||
->form([
|
||||
Select::make('window')
|
||||
->label('Window')
|
||||
->options(SystemConsoleWindow::options())
|
||||
->default($this->window)
|
||||
->required(),
|
||||
])
|
||||
->action(function (array $data): void {
|
||||
$window = SystemConsoleWindow::fromNullable((string) ($data['window'] ?? null));
|
||||
|
||||
$this->window = $window->value;
|
||||
|
||||
$this->redirect(static::getUrl([
|
||||
'window' => $window->value,
|
||||
]));
|
||||
}),
|
||||
|
||||
Action::make('enter_break_glass')
|
||||
->label('Enter break-glass mode')
|
||||
->color('danger')
|
||||
|
||||
@ -1,107 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Pages\Directory;
|
||||
|
||||
use App\Models\PlatformUser;
|
||||
use App\Models\Tenant;
|
||||
use App\Support\Auth\PlatformCapabilities;
|
||||
use App\Support\Badges\BadgeDomain;
|
||||
use App\Support\Badges\BadgeRenderer;
|
||||
use App\Support\System\SystemDirectoryLinks;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Concerns\InteractsWithTable;
|
||||
use Filament\Tables\Contracts\HasTable;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class Tenants extends Page implements HasTable
|
||||
{
|
||||
use InteractsWithTable;
|
||||
|
||||
protected static ?string $navigationLabel = 'Tenants';
|
||||
|
||||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-users';
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Directory';
|
||||
|
||||
protected static ?string $slug = 'directory/tenants';
|
||||
|
||||
protected string $view = 'filament.system.pages.directory.tenants';
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
return $user instanceof PlatformUser
|
||||
&& $user->hasCapability(PlatformCapabilities::DIRECTORY_VIEW);
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->mountInteractsWithTable();
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('name')
|
||||
->query(function (): Builder {
|
||||
return Tenant::query()
|
||||
->with('workspace')
|
||||
->withCount([
|
||||
'providerConnections',
|
||||
'providerConnections as unhealthy_connections_count' => fn (Builder $query): Builder => $query->where('health_status', 'unhealthy'),
|
||||
'permissions as missing_permissions_count' => fn (Builder $query): Builder => $query->where('status', '!=', 'granted'),
|
||||
]);
|
||||
})
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->label('Tenant')
|
||||
->searchable(),
|
||||
TextColumn::make('workspace.name')
|
||||
->label('Workspace')
|
||||
->searchable(),
|
||||
TextColumn::make('status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::TenantStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::TenantStatus))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantStatus)),
|
||||
TextColumn::make('health')
|
||||
->label('Health')
|
||||
->state(fn (Tenant $record): string => $this->healthForTenant($record))
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::SystemHealth))
|
||||
->color(BadgeRenderer::color(BadgeDomain::SystemHealth))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::SystemHealth))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::SystemHealth)),
|
||||
])
|
||||
->recordUrl(fn (Tenant $record): string => SystemDirectoryLinks::tenantDetail($record))
|
||||
->emptyStateHeading('No tenants found')
|
||||
->emptyStateDescription('Tenants will appear here as inventory is onboarded.');
|
||||
}
|
||||
|
||||
private function healthForTenant(Tenant $tenant): string
|
||||
{
|
||||
if ((string) $tenant->status === Tenant::STATUS_ARCHIVED) {
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
if ((int) ($tenant->getAttribute('unhealthy_connections_count') ?? 0) > 0) {
|
||||
return 'critical';
|
||||
}
|
||||
|
||||
if ((int) ($tenant->getAttribute('missing_permissions_count') ?? 0) > 0) {
|
||||
return 'warn';
|
||||
}
|
||||
|
||||
if ((string) $tenant->status === Tenant::STATUS_ONBOARDING) {
|
||||
return 'warn';
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
}
|
||||
@ -1,95 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Pages\Directory;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\PlatformUser;
|
||||
use App\Models\ProviderConnection;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantPermission;
|
||||
use App\Support\Auth\PlatformCapabilities;
|
||||
use App\Support\OperationCatalog;
|
||||
use App\Support\System\SystemDirectoryLinks;
|
||||
use App\Support\System\SystemOperationRunLinks;
|
||||
use Filament\Pages\Page;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class ViewTenant extends Page
|
||||
{
|
||||
protected static bool $shouldRegisterNavigation = false;
|
||||
|
||||
protected static ?string $slug = 'directory/tenants/{tenant}';
|
||||
|
||||
protected string $view = 'filament.system.pages.directory.view-tenant';
|
||||
|
||||
public Tenant $tenant;
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
return $user instanceof PlatformUser
|
||||
&& $user->hasCapability(PlatformCapabilities::DIRECTORY_VIEW);
|
||||
}
|
||||
|
||||
public function mount(Tenant $tenant): void
|
||||
{
|
||||
$tenant->load('workspace');
|
||||
|
||||
$this->tenant = $tenant;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, ProviderConnection>
|
||||
*/
|
||||
public function providerConnections(): Collection
|
||||
{
|
||||
return ProviderConnection::query()
|
||||
->where('tenant_id', (int) $this->tenant->getKey())
|
||||
->orderByDesc('is_default')
|
||||
->orderBy('provider')
|
||||
->get(['id', 'provider', 'status', 'health_status', 'is_default', 'last_health_check_at']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, TenantPermission>
|
||||
*/
|
||||
public function tenantPermissions(): Collection
|
||||
{
|
||||
return TenantPermission::query()
|
||||
->where('tenant_id', (int) $this->tenant->getKey())
|
||||
->orderBy('permission_key')
|
||||
->limit(20)
|
||||
->get(['id', 'permission_key', 'status', 'last_checked_at']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, array{id: int, label: string, started: string, url: string}>
|
||||
*/
|
||||
public function recentRuns(): Collection
|
||||
{
|
||||
return OperationRun::query()
|
||||
->where('tenant_id', (int) $this->tenant->getKey())
|
||||
->latest('id')
|
||||
->limit(8)
|
||||
->get(['id', 'type', 'created_at'])
|
||||
->map(fn (OperationRun $run): array => [
|
||||
'id' => (int) $run->getKey(),
|
||||
'label' => OperationCatalog::label((string) $run->type),
|
||||
'started' => $run->created_at?->diffForHumans() ?? '—',
|
||||
'url' => SystemOperationRunLinks::view($run),
|
||||
]);
|
||||
}
|
||||
|
||||
public function adminTenantUrl(): string
|
||||
{
|
||||
return SystemDirectoryLinks::adminTenant($this->tenant);
|
||||
}
|
||||
|
||||
public function runsUrl(): string
|
||||
{
|
||||
return SystemOperationRunLinks::index();
|
||||
}
|
||||
}
|
||||
@ -1,82 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Pages\Directory;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\PlatformUser;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\Workspace;
|
||||
use App\Support\Auth\PlatformCapabilities;
|
||||
use App\Support\OperationCatalog;
|
||||
use App\Support\System\SystemDirectoryLinks;
|
||||
use App\Support\System\SystemOperationRunLinks;
|
||||
use Filament\Pages\Page;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class ViewWorkspace extends Page
|
||||
{
|
||||
protected static bool $shouldRegisterNavigation = false;
|
||||
|
||||
protected static ?string $slug = 'directory/workspaces/{workspace}';
|
||||
|
||||
protected string $view = 'filament.system.pages.directory.view-workspace';
|
||||
|
||||
public Workspace $workspace;
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
return $user instanceof PlatformUser
|
||||
&& $user->hasCapability(PlatformCapabilities::DIRECTORY_VIEW);
|
||||
}
|
||||
|
||||
public function mount(Workspace $workspace): void
|
||||
{
|
||||
$workspace->loadCount('tenants');
|
||||
|
||||
$this->workspace = $workspace;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Tenant>
|
||||
*/
|
||||
public function workspaceTenants(): Collection
|
||||
{
|
||||
return Tenant::query()
|
||||
->where('workspace_id', (int) $this->workspace->getKey())
|
||||
->orderBy('name')
|
||||
->limit(10)
|
||||
->get(['id', 'name', 'status', 'workspace_id']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, array{id: int, label: string, started: string, url: string}>
|
||||
*/
|
||||
public function recentRuns(): Collection
|
||||
{
|
||||
return OperationRun::query()
|
||||
->where('workspace_id', (int) $this->workspace->getKey())
|
||||
->latest('id')
|
||||
->limit(8)
|
||||
->get(['id', 'type', 'created_at'])
|
||||
->map(fn (OperationRun $run): array => [
|
||||
'id' => (int) $run->getKey(),
|
||||
'label' => OperationCatalog::label((string) $run->type),
|
||||
'started' => $run->created_at?->diffForHumans() ?? '—',
|
||||
'url' => SystemOperationRunLinks::view($run),
|
||||
]);
|
||||
}
|
||||
|
||||
public function adminWorkspaceUrl(): string
|
||||
{
|
||||
return SystemDirectoryLinks::adminWorkspace($this->workspace);
|
||||
}
|
||||
|
||||
public function runsUrl(): string
|
||||
{
|
||||
return SystemOperationRunLinks::index();
|
||||
}
|
||||
}
|
||||
@ -1,116 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Pages\Directory;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\PlatformUser;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\Workspace;
|
||||
use App\Support\Auth\PlatformCapabilities;
|
||||
use App\Support\Badges\BadgeDomain;
|
||||
use App\Support\Badges\BadgeRenderer;
|
||||
use App\Support\OperationRunOutcome;
|
||||
use App\Support\OperationRunStatus;
|
||||
use App\Support\System\SystemDirectoryLinks;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Concerns\InteractsWithTable;
|
||||
use Filament\Tables\Contracts\HasTable;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class Workspaces extends Page implements HasTable
|
||||
{
|
||||
use InteractsWithTable;
|
||||
|
||||
protected static ?string $navigationLabel = 'Workspaces';
|
||||
|
||||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-building-office-2';
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Directory';
|
||||
|
||||
protected static ?string $slug = 'directory/workspaces';
|
||||
|
||||
protected string $view = 'filament.system.pages.directory.workspaces';
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
return $user instanceof PlatformUser
|
||||
&& $user->hasCapability(PlatformCapabilities::DIRECTORY_VIEW);
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->mountInteractsWithTable();
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('name')
|
||||
->query(function (): Builder {
|
||||
return Workspace::query()
|
||||
->withCount([
|
||||
'tenants',
|
||||
'tenants as onboarding_tenants_count' => fn (Builder $query): Builder => $query->where('status', Tenant::STATUS_ONBOARDING),
|
||||
]);
|
||||
})
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->label('Workspace')
|
||||
->searchable(),
|
||||
TextColumn::make('tenants_count')
|
||||
->label('Tenants'),
|
||||
TextColumn::make('health')
|
||||
->label('Health')
|
||||
->state(fn (Workspace $record): string => $this->healthForWorkspace($record))
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::SystemHealth))
|
||||
->color(BadgeRenderer::color(BadgeDomain::SystemHealth))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::SystemHealth))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::SystemHealth)),
|
||||
TextColumn::make('failed_runs_24h')
|
||||
->label('Failed (24h)')
|
||||
->state(fn (Workspace $record): int => (int) OperationRun::query()
|
||||
->where('workspace_id', (int) $record->getKey())
|
||||
->where('created_at', '>=', now()->subDay())
|
||||
->where('status', OperationRunStatus::Completed->value)
|
||||
->where('outcome', OperationRunOutcome::Failed->value)
|
||||
->count()),
|
||||
])
|
||||
->recordUrl(fn (Workspace $record): string => SystemDirectoryLinks::workspaceDetail($record))
|
||||
->emptyStateHeading('No workspaces found')
|
||||
->emptyStateDescription('Workspace inventory will appear here once workspaces are created.');
|
||||
}
|
||||
|
||||
private function healthForWorkspace(Workspace $workspace): string
|
||||
{
|
||||
$tenantsCount = (int) ($workspace->getAttribute('tenants_count') ?? 0);
|
||||
$onboardingTenantsCount = (int) ($workspace->getAttribute('onboarding_tenants_count') ?? 0);
|
||||
|
||||
if ($tenantsCount === 0) {
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
$hasRecentFailures = OperationRun::query()
|
||||
->where('workspace_id', (int) $workspace->getKey())
|
||||
->where('created_at', '>=', now()->subDay())
|
||||
->where('status', OperationRunStatus::Completed->value)
|
||||
->where('outcome', OperationRunOutcome::Failed->value)
|
||||
->exists();
|
||||
|
||||
if ($hasRecentFailures) {
|
||||
return 'critical';
|
||||
}
|
||||
|
||||
if ($onboardingTenantsCount > 0) {
|
||||
return 'warn';
|
||||
}
|
||||
|
||||
return 'ok';
|
||||
}
|
||||
}
|
||||
@ -1,190 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Pages\Ops;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\PlatformUser;
|
||||
use App\Services\SystemConsole\OperationRunTriageService;
|
||||
use App\Support\Auth\PlatformCapabilities;
|
||||
use App\Support\Badges\BadgeDomain;
|
||||
use App\Support\Badges\BadgeRenderer;
|
||||
use App\Support\OperationCatalog;
|
||||
use App\Support\OperationRunOutcome;
|
||||
use App\Support\OperationRunStatus;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\System\SystemOperationRunLinks;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Concerns\InteractsWithTable;
|
||||
use Filament\Tables\Contracts\HasTable;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class Failures extends Page implements HasTable
|
||||
{
|
||||
use InteractsWithTable;
|
||||
|
||||
protected static ?string $navigationLabel = 'Failures';
|
||||
|
||||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-exclamation-triangle';
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Ops';
|
||||
|
||||
protected static ?string $slug = 'ops/failures';
|
||||
|
||||
protected string $view = 'filament.system.pages.ops.failures';
|
||||
|
||||
public static function getNavigationBadge(): ?string
|
||||
{
|
||||
$count = OperationRun::query()
|
||||
->where('status', OperationRunStatus::Completed->value)
|
||||
->where('outcome', OperationRunOutcome::Failed->value)
|
||||
->count();
|
||||
|
||||
return $count > 0 ? (string) $count : null;
|
||||
}
|
||||
|
||||
public static function getNavigationBadgeColor(): string|array|null
|
||||
{
|
||||
return 'danger';
|
||||
}
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
if (! $user instanceof PlatformUser) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->hasCapability(PlatformCapabilities::OPERATIONS_VIEW)
|
||||
|| ($user->hasCapability(PlatformCapabilities::OPS_VIEW) && $user->hasCapability(PlatformCapabilities::RUNBOOKS_VIEW));
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->mountInteractsWithTable();
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('id', 'desc')
|
||||
->query(function (): Builder {
|
||||
return OperationRun::query()
|
||||
->with(['tenant', 'workspace'])
|
||||
->where('status', OperationRunStatus::Completed->value)
|
||||
->where('outcome', OperationRunOutcome::Failed->value);
|
||||
})
|
||||
->columns([
|
||||
TextColumn::make('id')
|
||||
->label('Run')
|
||||
->state(fn (OperationRun $record): string => '#'.$record->getKey()),
|
||||
TextColumn::make('status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::OperationRunStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::OperationRunStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::OperationRunStatus))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::OperationRunStatus)),
|
||||
TextColumn::make('outcome')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::OperationRunOutcome))
|
||||
->color(BadgeRenderer::color(BadgeDomain::OperationRunOutcome))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::OperationRunOutcome))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::OperationRunOutcome)),
|
||||
TextColumn::make('type')
|
||||
->label('Operation')
|
||||
->formatStateUsing(fn (?string $state): string => OperationCatalog::label((string) $state))
|
||||
->searchable(),
|
||||
TextColumn::make('workspace.name')
|
||||
->label('Workspace')
|
||||
->toggleable(),
|
||||
TextColumn::make('tenant.name')
|
||||
->label('Tenant')
|
||||
->formatStateUsing(fn (?string $state): string => $state ?: 'Tenantless')
|
||||
->toggleable(),
|
||||
TextColumn::make('created_at')->label('Started')->since(),
|
||||
])
|
||||
->recordUrl(fn (OperationRun $record): string => SystemOperationRunLinks::view($record))
|
||||
->actions([
|
||||
Action::make('retry')
|
||||
->label('Retry')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (OperationRun $record): bool => $this->canManageOperations() && app(OperationRunTriageService::class)->canRetry($record))
|
||||
->action(function (OperationRun $record, OperationRunTriageService $triageService): void {
|
||||
$user = $this->requireManageUser();
|
||||
$retryRun = $triageService->retry($record, $user);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $retryRun->type)
|
||||
->actions([
|
||||
\Filament\Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(SystemOperationRunLinks::view($retryRun)),
|
||||
])
|
||||
->send();
|
||||
}),
|
||||
Action::make('cancel')
|
||||
->label('Cancel')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (OperationRun $record): bool => $this->canManageOperations() && app(OperationRunTriageService::class)->canCancel($record))
|
||||
->action(function (OperationRun $record, OperationRunTriageService $triageService): void {
|
||||
$user = $this->requireManageUser();
|
||||
$triageService->cancel($record, $user);
|
||||
|
||||
Notification::make()
|
||||
->title('Run cancelled')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
Action::make('mark_investigated')
|
||||
->label('Mark investigated')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (): bool => $this->canManageOperations())
|
||||
->form([
|
||||
Textarea::make('reason')
|
||||
->label('Reason')
|
||||
->required()
|
||||
->minLength(5)
|
||||
->maxLength(500)
|
||||
->rows(4),
|
||||
])
|
||||
->action(function (OperationRun $record, array $data, OperationRunTriageService $triageService): void {
|
||||
$user = $this->requireManageUser();
|
||||
$triageService->markInvestigated($record, $user, (string) ($data['reason'] ?? ''));
|
||||
|
||||
Notification::make()
|
||||
->title('Run marked as investigated')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
])
|
||||
->emptyStateHeading('No failed runs found')
|
||||
->emptyStateDescription('Failed operations will appear here for triage.')
|
||||
->bulkActions([]);
|
||||
}
|
||||
|
||||
private function canManageOperations(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
return $user instanceof PlatformUser
|
||||
&& $user->hasCapability(PlatformCapabilities::OPERATIONS_MANAGE);
|
||||
}
|
||||
|
||||
private function requireManageUser(): PlatformUser
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
if (! $user instanceof PlatformUser || ! $user->hasCapability(PlatformCapabilities::OPERATIONS_MANAGE)) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
@ -1,272 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Pages\Ops;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\PlatformUser;
|
||||
use App\Models\Tenant;
|
||||
use App\Services\Auth\BreakGlassSession;
|
||||
use App\Services\Runbooks\FindingsLifecycleBackfillRunbookService;
|
||||
use App\Services\Runbooks\FindingsLifecycleBackfillScope;
|
||||
use App\Services\Runbooks\RunbookReason;
|
||||
use App\Services\System\AllowedTenantUniverse;
|
||||
use App\Support\Auth\PlatformCapabilities;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\System\SystemOperationRunLinks;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class Runbooks extends Page
|
||||
{
|
||||
protected static ?string $navigationLabel = 'Runbooks';
|
||||
|
||||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-wrench-screwdriver';
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Ops';
|
||||
|
||||
protected static ?string $slug = 'ops/runbooks';
|
||||
|
||||
protected string $view = 'filament.system.pages.ops.runbooks';
|
||||
|
||||
public string $scopeMode = FindingsLifecycleBackfillScope::MODE_ALL_TENANTS;
|
||||
|
||||
public ?int $tenantId = null;
|
||||
|
||||
/**
|
||||
* @var array{affected_count: int, total_count: int, estimated_tenants?: int|null}|null
|
||||
*/
|
||||
public ?array $preflight = null;
|
||||
|
||||
public function scopeLabel(): string
|
||||
{
|
||||
if ($this->scopeMode === FindingsLifecycleBackfillScope::MODE_ALL_TENANTS) {
|
||||
return 'All tenants';
|
||||
}
|
||||
|
||||
$tenantName = $this->selectedTenantName();
|
||||
|
||||
if ($tenantName !== null) {
|
||||
return "Single tenant ({$tenantName})";
|
||||
}
|
||||
|
||||
return $this->tenantId !== null ? "Single tenant (#{$this->tenantId})" : 'Single tenant';
|
||||
}
|
||||
|
||||
public function lastRun(): ?OperationRun
|
||||
{
|
||||
$platformTenant = Tenant::query()->where('external_id', 'platform')->first();
|
||||
|
||||
if (! $platformTenant instanceof Tenant) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return OperationRun::query()
|
||||
->where('workspace_id', (int) $platformTenant->workspace_id)
|
||||
->where('type', FindingsLifecycleBackfillRunbookService::RUNBOOK_KEY)
|
||||
->latest('id')
|
||||
->first();
|
||||
}
|
||||
|
||||
public function selectedTenantName(): ?string
|
||||
{
|
||||
if ($this->tenantId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Tenant::query()->whereKey($this->tenantId)->value('name');
|
||||
}
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
if (! $user instanceof PlatformUser) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->hasCapability(PlatformCapabilities::OPS_VIEW)
|
||||
&& $user->hasCapability(PlatformCapabilities::RUNBOOKS_VIEW);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<Action>
|
||||
*/
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('preflight')
|
||||
->label('Preflight')
|
||||
->color('gray')
|
||||
->icon('heroicon-o-magnifying-glass')
|
||||
->form($this->scopeForm())
|
||||
->action(function (array $data, FindingsLifecycleBackfillRunbookService $runbookService): void {
|
||||
$scope = FindingsLifecycleBackfillScope::fromArray([
|
||||
'mode' => $data['scope_mode'] ?? null,
|
||||
'tenant_id' => $data['tenant_id'] ?? null,
|
||||
]);
|
||||
|
||||
$this->scopeMode = $scope->mode;
|
||||
$this->tenantId = $scope->tenantId;
|
||||
|
||||
$this->preflight = $runbookService->preflight($scope);
|
||||
|
||||
Notification::make()
|
||||
->title('Preflight complete')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
|
||||
Action::make('run')
|
||||
->label('Run…')
|
||||
->icon('heroicon-o-play')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Run: Rebuild Findings Lifecycle')
|
||||
->modalDescription('This operation may modify customer data. Review the preflight and confirm before running.')
|
||||
->form($this->runForm())
|
||||
->disabled(fn (): bool => ! is_array($this->preflight) || (int) ($this->preflight['affected_count'] ?? 0) <= 0)
|
||||
->action(function (array $data, FindingsLifecycleBackfillRunbookService $runbookService): void {
|
||||
if (! is_array($this->preflight) || (int) ($this->preflight['affected_count'] ?? 0) <= 0) {
|
||||
throw ValidationException::withMessages([
|
||||
'preflight' => 'Run preflight first.',
|
||||
]);
|
||||
}
|
||||
|
||||
$scope = $this->scopeMode === FindingsLifecycleBackfillScope::MODE_SINGLE_TENANT
|
||||
? FindingsLifecycleBackfillScope::singleTenant((int) $this->tenantId)
|
||||
: FindingsLifecycleBackfillScope::allTenants();
|
||||
|
||||
$user = auth('platform')->user();
|
||||
|
||||
if (! $user instanceof PlatformUser) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
if (! $user->hasCapability(PlatformCapabilities::RUNBOOKS_RUN)
|
||||
|| ! $user->hasCapability(PlatformCapabilities::RUNBOOKS_FINDINGS_LIFECYCLE_BACKFILL)
|
||||
) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
if ($scope->isAllTenants()) {
|
||||
$typedConfirmation = (string) ($data['typed_confirmation'] ?? '');
|
||||
|
||||
if ($typedConfirmation !== 'BACKFILL') {
|
||||
throw ValidationException::withMessages([
|
||||
'typed_confirmation' => 'Please type BACKFILL to confirm.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$reason = RunbookReason::fromNullableArray([
|
||||
'reason_code' => $data['reason_code'] ?? null,
|
||||
'reason_text' => $data['reason_text'] ?? null,
|
||||
]);
|
||||
|
||||
$run = $runbookService->start(
|
||||
scope: $scope,
|
||||
initiator: $user,
|
||||
reason: $reason,
|
||||
source: 'system_ui',
|
||||
);
|
||||
|
||||
$viewUrl = SystemOperationRunLinks::view($run);
|
||||
|
||||
$toast = $run->wasRecentlyCreated
|
||||
? OperationUxPresenter::queuedToast((string) $run->type)->body('The runbook will execute in the background.')
|
||||
: OperationUxPresenter::alreadyQueuedToast((string) $run->type);
|
||||
|
||||
$toast
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
->url($viewUrl),
|
||||
])
|
||||
->send();
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, \Filament\Schemas\Components\Component>
|
||||
*/
|
||||
private function scopeForm(): array
|
||||
{
|
||||
return [
|
||||
Radio::make('scope_mode')
|
||||
->label('Scope')
|
||||
->options([
|
||||
FindingsLifecycleBackfillScope::MODE_ALL_TENANTS => 'All tenants',
|
||||
FindingsLifecycleBackfillScope::MODE_SINGLE_TENANT => 'Single tenant',
|
||||
])
|
||||
->default($this->scopeMode)
|
||||
->live()
|
||||
->required(),
|
||||
|
||||
Select::make('tenant_id')
|
||||
->label('Tenant')
|
||||
->searchable()
|
||||
->visible(fn (callable $get): bool => $get('scope_mode') === FindingsLifecycleBackfillScope::MODE_SINGLE_TENANT)
|
||||
->required(fn (callable $get): bool => $get('scope_mode') === FindingsLifecycleBackfillScope::MODE_SINGLE_TENANT)
|
||||
->getSearchResultsUsing(function (string $search, AllowedTenantUniverse $universe): array {
|
||||
return $universe
|
||||
->query()
|
||||
->where('name', 'like', "%{$search}%")
|
||||
->orderBy('name')
|
||||
->limit(25)
|
||||
->pluck('name', 'id')
|
||||
->all();
|
||||
})
|
||||
->getOptionLabelUsing(function ($value, AllowedTenantUniverse $universe): ?string {
|
||||
if (! is_numeric($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $universe
|
||||
->query()
|
||||
->whereKey((int) $value)
|
||||
->value('name');
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, \Filament\Schemas\Components\Component>
|
||||
*/
|
||||
private function runForm(): array
|
||||
{
|
||||
return [
|
||||
TextInput::make('typed_confirmation')
|
||||
->label('Type BACKFILL to confirm')
|
||||
->visible(fn (): bool => $this->scopeMode === FindingsLifecycleBackfillScope::MODE_ALL_TENANTS)
|
||||
->required(fn (): bool => $this->scopeMode === FindingsLifecycleBackfillScope::MODE_ALL_TENANTS)
|
||||
->in(['BACKFILL'])
|
||||
->validationMessages([
|
||||
'in' => 'Please type BACKFILL to confirm.',
|
||||
]),
|
||||
|
||||
Select::make('reason_code')
|
||||
->label('Reason code')
|
||||
->options(RunbookReason::options())
|
||||
->required(function (BreakGlassSession $breakGlass): bool {
|
||||
return $this->scopeMode === FindingsLifecycleBackfillScope::MODE_ALL_TENANTS || $breakGlass->isActive();
|
||||
}),
|
||||
|
||||
Textarea::make('reason_text')
|
||||
->label('Reason')
|
||||
->rows(4)
|
||||
->maxLength(500)
|
||||
->required(function (BreakGlassSession $breakGlass): bool {
|
||||
return $this->scopeMode === FindingsLifecycleBackfillScope::MODE_ALL_TENANTS || $breakGlass->isActive();
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,172 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Pages\Ops;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\PlatformUser;
|
||||
use App\Services\SystemConsole\OperationRunTriageService;
|
||||
use App\Support\Auth\PlatformCapabilities;
|
||||
use App\Support\Badges\BadgeDomain;
|
||||
use App\Support\Badges\BadgeRenderer;
|
||||
use App\Support\OperationCatalog;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\System\SystemOperationRunLinks;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Concerns\InteractsWithTable;
|
||||
use Filament\Tables\Contracts\HasTable;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class Runs extends Page implements HasTable
|
||||
{
|
||||
use InteractsWithTable;
|
||||
|
||||
protected static ?string $navigationLabel = 'Runs';
|
||||
|
||||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-queue-list';
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Ops';
|
||||
|
||||
protected static ?string $slug = 'ops/runs';
|
||||
|
||||
protected string $view = 'filament.system.pages.ops.runs';
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
if (! $user instanceof PlatformUser) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->hasCapability(PlatformCapabilities::OPERATIONS_VIEW)
|
||||
|| ($user->hasCapability(PlatformCapabilities::OPS_VIEW) && $user->hasCapability(PlatformCapabilities::RUNBOOKS_VIEW));
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->mountInteractsWithTable();
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('id', 'desc')
|
||||
->query(function (): Builder {
|
||||
return OperationRun::query()
|
||||
->with(['tenant', 'workspace']);
|
||||
})
|
||||
->columns([
|
||||
TextColumn::make('id')
|
||||
->label('Run')
|
||||
->state(fn (OperationRun $record): string => '#'.$record->getKey()),
|
||||
TextColumn::make('status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::OperationRunStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::OperationRunStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::OperationRunStatus))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::OperationRunStatus)),
|
||||
TextColumn::make('outcome')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::OperationRunOutcome))
|
||||
->color(BadgeRenderer::color(BadgeDomain::OperationRunOutcome))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::OperationRunOutcome))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::OperationRunOutcome)),
|
||||
TextColumn::make('type')
|
||||
->label('Operation')
|
||||
->formatStateUsing(fn (?string $state): string => OperationCatalog::label((string) $state))
|
||||
->searchable(),
|
||||
TextColumn::make('workspace.name')
|
||||
->label('Workspace')
|
||||
->toggleable(),
|
||||
TextColumn::make('tenant.name')
|
||||
->label('Tenant')
|
||||
->formatStateUsing(fn (?string $state): string => $state ?: 'Tenantless')
|
||||
->toggleable(),
|
||||
TextColumn::make('initiator_name')->label('Initiator'),
|
||||
TextColumn::make('created_at')->label('Started')->since(),
|
||||
])
|
||||
->recordUrl(fn (OperationRun $record): string => SystemOperationRunLinks::view($record))
|
||||
->actions([
|
||||
Action::make('retry')
|
||||
->label('Retry')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (OperationRun $record): bool => $this->canManageOperations() && app(OperationRunTriageService::class)->canRetry($record))
|
||||
->action(function (OperationRun $record, OperationRunTriageService $triageService): void {
|
||||
$user = $this->requireManageUser();
|
||||
$retryRun = $triageService->retry($record, $user);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $retryRun->type)
|
||||
->actions([
|
||||
\Filament\Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(SystemOperationRunLinks::view($retryRun)),
|
||||
])
|
||||
->send();
|
||||
}),
|
||||
Action::make('cancel')
|
||||
->label('Cancel')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (OperationRun $record): bool => $this->canManageOperations() && app(OperationRunTriageService::class)->canCancel($record))
|
||||
->action(function (OperationRun $record, OperationRunTriageService $triageService): void {
|
||||
$user = $this->requireManageUser();
|
||||
$triageService->cancel($record, $user);
|
||||
|
||||
Notification::make()
|
||||
->title('Run cancelled')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
Action::make('mark_investigated')
|
||||
->label('Mark investigated')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (): bool => $this->canManageOperations())
|
||||
->form([
|
||||
Textarea::make('reason')
|
||||
->label('Reason')
|
||||
->required()
|
||||
->minLength(5)
|
||||
->maxLength(500)
|
||||
->rows(4),
|
||||
])
|
||||
->action(function (OperationRun $record, array $data, OperationRunTriageService $triageService): void {
|
||||
$user = $this->requireManageUser();
|
||||
$triageService->markInvestigated($record, $user, (string) ($data['reason'] ?? ''));
|
||||
|
||||
Notification::make()
|
||||
->title('Run marked as investigated')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
])
|
||||
->emptyStateHeading('No operation runs yet')
|
||||
->emptyStateDescription('Runs from all workspaces will appear here when operations are queued.')
|
||||
->bulkActions([]);
|
||||
}
|
||||
|
||||
private function canManageOperations(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
return $user instanceof PlatformUser
|
||||
&& $user->hasCapability(PlatformCapabilities::OPERATIONS_MANAGE);
|
||||
}
|
||||
|
||||
private function requireManageUser(): PlatformUser
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
if (! $user instanceof PlatformUser || ! $user->hasCapability(PlatformCapabilities::OPERATIONS_MANAGE)) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
@ -1,190 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Pages\Ops;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\PlatformUser;
|
||||
use App\Services\SystemConsole\OperationRunTriageService;
|
||||
use App\Support\Auth\PlatformCapabilities;
|
||||
use App\Support\Badges\BadgeDomain;
|
||||
use App\Support\Badges\BadgeRenderer;
|
||||
use App\Support\OperationCatalog;
|
||||
use App\Support\OperationRunStatus;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\System\SystemOperationRunLinks;
|
||||
use App\Support\SystemConsole\StuckRunClassifier;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Concerns\InteractsWithTable;
|
||||
use Filament\Tables\Contracts\HasTable;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class Stuck extends Page implements HasTable
|
||||
{
|
||||
use InteractsWithTable;
|
||||
|
||||
protected static ?string $navigationLabel = 'Stuck';
|
||||
|
||||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-clock';
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Ops';
|
||||
|
||||
protected static ?string $slug = 'ops/stuck';
|
||||
|
||||
protected string $view = 'filament.system.pages.ops.stuck';
|
||||
|
||||
public static function getNavigationBadge(): ?string
|
||||
{
|
||||
$count = app(StuckRunClassifier::class)
|
||||
->apply(OperationRun::query())
|
||||
->count();
|
||||
|
||||
return $count > 0 ? (string) $count : null;
|
||||
}
|
||||
|
||||
public static function getNavigationBadgeColor(): string|array|null
|
||||
{
|
||||
return 'warning';
|
||||
}
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
if (! $user instanceof PlatformUser) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->hasCapability(PlatformCapabilities::OPERATIONS_VIEW)
|
||||
|| ($user->hasCapability(PlatformCapabilities::OPS_VIEW) && $user->hasCapability(PlatformCapabilities::RUNBOOKS_VIEW));
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->mountInteractsWithTable();
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('id', 'desc')
|
||||
->query(function (): Builder {
|
||||
return app(StuckRunClassifier::class)->apply(
|
||||
OperationRun::query()
|
||||
->with(['tenant', 'workspace'])
|
||||
);
|
||||
})
|
||||
->columns([
|
||||
TextColumn::make('id')
|
||||
->label('Run')
|
||||
->state(fn (OperationRun $record): string => '#'.$record->getKey()),
|
||||
TextColumn::make('status')
|
||||
->badge()
|
||||
->formatStateUsing(BadgeRenderer::label(BadgeDomain::OperationRunStatus))
|
||||
->color(BadgeRenderer::color(BadgeDomain::OperationRunStatus))
|
||||
->icon(BadgeRenderer::icon(BadgeDomain::OperationRunStatus))
|
||||
->iconColor(BadgeRenderer::iconColor(BadgeDomain::OperationRunStatus)),
|
||||
TextColumn::make('stuck_class')
|
||||
->label('Stuck class')
|
||||
->state(function (OperationRun $record): string {
|
||||
$classification = app(StuckRunClassifier::class)->classify($record);
|
||||
|
||||
return $classification === OperationRunStatus::Queued->value ? 'Queued too long' : 'Running too long';
|
||||
}),
|
||||
TextColumn::make('type')
|
||||
->label('Operation')
|
||||
->formatStateUsing(fn (?string $state): string => OperationCatalog::label((string) $state))
|
||||
->searchable(),
|
||||
TextColumn::make('workspace.name')
|
||||
->label('Workspace')
|
||||
->toggleable(),
|
||||
TextColumn::make('tenant.name')
|
||||
->label('Tenant')
|
||||
->formatStateUsing(fn (?string $state): string => $state ?: 'Tenantless')
|
||||
->toggleable(),
|
||||
TextColumn::make('created_at')->label('Started')->since(),
|
||||
])
|
||||
->recordUrl(fn (OperationRun $record): string => SystemOperationRunLinks::view($record))
|
||||
->actions([
|
||||
Action::make('retry')
|
||||
->label('Retry')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (OperationRun $record): bool => $this->canManageOperations() && app(OperationRunTriageService::class)->canRetry($record))
|
||||
->action(function (OperationRun $record, OperationRunTriageService $triageService): void {
|
||||
$user = $this->requireManageUser();
|
||||
$retryRun = $triageService->retry($record, $user);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $retryRun->type)
|
||||
->actions([
|
||||
\Filament\Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(SystemOperationRunLinks::view($retryRun)),
|
||||
])
|
||||
->send();
|
||||
}),
|
||||
Action::make('cancel')
|
||||
->label('Cancel')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (OperationRun $record): bool => $this->canManageOperations() && app(OperationRunTriageService::class)->canCancel($record))
|
||||
->action(function (OperationRun $record, OperationRunTriageService $triageService): void {
|
||||
$user = $this->requireManageUser();
|
||||
$triageService->cancel($record, $user);
|
||||
|
||||
Notification::make()
|
||||
->title('Run cancelled')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
Action::make('mark_investigated')
|
||||
->label('Mark investigated')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (): bool => $this->canManageOperations())
|
||||
->form([
|
||||
Textarea::make('reason')
|
||||
->label('Reason')
|
||||
->required()
|
||||
->minLength(5)
|
||||
->maxLength(500)
|
||||
->rows(4),
|
||||
])
|
||||
->action(function (OperationRun $record, array $data, OperationRunTriageService $triageService): void {
|
||||
$user = $this->requireManageUser();
|
||||
$triageService->markInvestigated($record, $user, (string) ($data['reason'] ?? ''));
|
||||
|
||||
Notification::make()
|
||||
->title('Run marked as investigated')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
])
|
||||
->emptyStateHeading('No stuck runs found')
|
||||
->emptyStateDescription('Queued and running runs outside thresholds will appear here.')
|
||||
->bulkActions([]);
|
||||
}
|
||||
|
||||
private function canManageOperations(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
return $user instanceof PlatformUser
|
||||
&& $user->hasCapability(PlatformCapabilities::OPERATIONS_MANAGE);
|
||||
}
|
||||
|
||||
private function requireManageUser(): PlatformUser
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
if (! $user instanceof PlatformUser || ! $user->hasCapability(PlatformCapabilities::OPERATIONS_MANAGE)) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
@ -1,128 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Pages\Ops;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\PlatformUser;
|
||||
use App\Services\SystemConsole\OperationRunTriageService;
|
||||
use App\Support\Auth\PlatformCapabilities;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\System\SystemOperationRunLinks;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
|
||||
class ViewRun extends Page
|
||||
{
|
||||
protected static bool $shouldRegisterNavigation = false;
|
||||
|
||||
protected static ?string $slug = 'ops/runs/{run}';
|
||||
|
||||
protected string $view = 'filament.system.pages.ops.view-run';
|
||||
|
||||
public OperationRun $run;
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
if (! $user instanceof PlatformUser) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->hasCapability(PlatformCapabilities::OPERATIONS_VIEW)
|
||||
|| ($user->hasCapability(PlatformCapabilities::OPS_VIEW) && $user->hasCapability(PlatformCapabilities::RUNBOOKS_VIEW));
|
||||
}
|
||||
|
||||
public function mount(OperationRun $run): void
|
||||
{
|
||||
$run->load(['tenant', 'workspace']);
|
||||
|
||||
$this->run = $run;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<Action>
|
||||
*/
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('go_to_runbooks')
|
||||
->label('Go to runbooks')
|
||||
->url(Runbooks::getUrl(panel: 'system')),
|
||||
Action::make('retry')
|
||||
->label('Retry')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (): bool => $this->canManageOperations() && app(OperationRunTriageService::class)->canRetry($this->run))
|
||||
->action(function (OperationRunTriageService $triageService): void {
|
||||
$user = $this->requireManageUser();
|
||||
$retryRun = $triageService->retry($this->run, $user);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $retryRun->type)
|
||||
->actions([
|
||||
\Filament\Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(SystemOperationRunLinks::view($retryRun)),
|
||||
])
|
||||
->send();
|
||||
}),
|
||||
Action::make('cancel')
|
||||
->label('Cancel')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (): bool => $this->canManageOperations() && app(OperationRunTriageService::class)->canCancel($this->run))
|
||||
->action(function (OperationRunTriageService $triageService): void {
|
||||
$user = $this->requireManageUser();
|
||||
$triageService->cancel($this->run, $user);
|
||||
|
||||
Notification::make()
|
||||
->title('Run cancelled')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
Action::make('mark_investigated')
|
||||
->label('Mark investigated')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (): bool => $this->canManageOperations())
|
||||
->form([
|
||||
Textarea::make('reason')
|
||||
->label('Reason')
|
||||
->required()
|
||||
->minLength(5)
|
||||
->maxLength(500)
|
||||
->rows(4),
|
||||
])
|
||||
->action(function (array $data, OperationRunTriageService $triageService): void {
|
||||
$user = $this->requireManageUser();
|
||||
$triageService->markInvestigated($this->run, $user, (string) ($data['reason'] ?? ''));
|
||||
|
||||
Notification::make()
|
||||
->title('Run marked as investigated')
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
private function canManageOperations(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
return $user instanceof PlatformUser
|
||||
&& $user->hasCapability(PlatformCapabilities::OPERATIONS_MANAGE);
|
||||
}
|
||||
|
||||
private function requireManageUser(): PlatformUser
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
if (! $user instanceof PlatformUser || ! $user->hasCapability(PlatformCapabilities::OPERATIONS_MANAGE)) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
@ -4,8 +4,6 @@
|
||||
|
||||
namespace App\Filament\System\Pages;
|
||||
|
||||
use App\Filament\System\Widgets\RepairWorkspaceOwnersStats;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\PlatformUser;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
@ -20,18 +18,9 @@
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Concerns\InteractsWithTable;
|
||||
use Filament\Tables\Contracts\HasTable;
|
||||
use Filament\Tables\Table;
|
||||
use Filament\Widgets\Widget;
|
||||
use Filament\Widgets\WidgetConfiguration;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class RepairWorkspaceOwners extends Page implements HasTable
|
||||
class RepairWorkspaceOwners extends Page
|
||||
{
|
||||
use InteractsWithTable;
|
||||
|
||||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-wrench-screwdriver';
|
||||
|
||||
protected static ?string $navigationLabel = 'Repair workspace owners';
|
||||
@ -51,102 +40,6 @@ public static function canAccess(): bool
|
||||
return $user->hasCapability(PlatformCapabilities::USE_BREAK_GLASS);
|
||||
}
|
||||
|
||||
public static function getNavigationBadge(): ?string
|
||||
{
|
||||
$total = Workspace::query()->count();
|
||||
$withOwners = WorkspaceMembership::query()
|
||||
->where('role', WorkspaceRole::Owner->value)
|
||||
->distinct('workspace_id')
|
||||
->count('workspace_id');
|
||||
|
||||
$ownerless = $total - $withOwners;
|
||||
|
||||
return $ownerless > 0 ? (string) $ownerless : null;
|
||||
}
|
||||
|
||||
public static function getNavigationBadgeColor(): string|array|null
|
||||
{
|
||||
return 'danger';
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->mountInteractsWithTable();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<class-string<Widget>|WidgetConfiguration>
|
||||
*/
|
||||
protected function getHeaderWidgets(): array
|
||||
{
|
||||
return [
|
||||
RepairWorkspaceOwnersStats::class,
|
||||
];
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->heading('Workspaces')
|
||||
->description('Current workspace ownership status.')
|
||||
->defaultSort('name', 'asc')
|
||||
->query(function (): Builder {
|
||||
return Workspace::query()
|
||||
->withCount([
|
||||
'memberships as owner_count' => function (Builder $query): void {
|
||||
$query->where('role', WorkspaceRole::Owner->value);
|
||||
},
|
||||
'memberships as member_count',
|
||||
'tenants as tenant_count',
|
||||
]);
|
||||
})
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->label('Workspace')
|
||||
->searchable()
|
||||
->sortable(),
|
||||
TextColumn::make('owner_count')
|
||||
->label('Owners')
|
||||
->badge()
|
||||
->color(fn (int $state): string => $state > 0 ? 'success' : 'danger')
|
||||
->sortable(),
|
||||
TextColumn::make('member_count')
|
||||
->label('Members')
|
||||
->sortable(),
|
||||
TextColumn::make('tenant_count')
|
||||
->label('Tenants')
|
||||
->sortable(),
|
||||
TextColumn::make('updated_at')
|
||||
->label('Last activity')
|
||||
->since()
|
||||
->sortable(),
|
||||
])
|
||||
->emptyStateHeading('No workspaces')
|
||||
->emptyStateDescription('No workspaces exist in the system yet.')
|
||||
->bulkActions([]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array{action: string, actor: string|null, workspace: string|null, recorded_at: string}>
|
||||
*/
|
||||
public function getRecentBreakGlassActions(): array
|
||||
{
|
||||
return AuditLog::query()
|
||||
->where('action', 'like', '%break_glass%')
|
||||
->orderByDesc('recorded_at')
|
||||
->limit(10)
|
||||
->get()
|
||||
->map(fn (AuditLog $log): array => [
|
||||
'action' => (string) $log->action,
|
||||
'actor' => $log->actor_email ?: 'Unknown',
|
||||
'workspace' => $log->metadata['metadata']['workspace_id'] ?? null
|
||||
? Workspace::query()->whereKey((int) $log->metadata['metadata']['workspace_id'])->value('name')
|
||||
: null,
|
||||
'recorded_at' => $log->recorded_at?->diffForHumans() ?? 'Unknown',
|
||||
])
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<Action>
|
||||
*/
|
||||
@ -156,8 +49,7 @@ protected function getHeaderActions(): array
|
||||
|
||||
return [
|
||||
Action::make('assign_owner')
|
||||
->label('Emergency: Assign Owner')
|
||||
->icon('heroicon-o-shield-exclamation')
|
||||
->label('Assign owner (break-glass)')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Assign workspace owner')
|
||||
@ -271,8 +163,7 @@ protected function getHeaderActions(): array
|
||||
->success()
|
||||
->send();
|
||||
})
|
||||
->disabled(fn (): bool => ! $breakGlass->isActive())
|
||||
->tooltip(fn (): ?string => ! $breakGlass->isActive() ? 'Activate break-glass mode on the Dashboard first.' : null),
|
||||
->disabled(fn (): bool => ! $breakGlass->isActive()),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,73 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Pages\Security;
|
||||
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\PlatformUser;
|
||||
use App\Support\Auth\PlatformCapabilities;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Concerns\InteractsWithTable;
|
||||
use Filament\Tables\Contracts\HasTable;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class AccessLogs extends Page implements HasTable
|
||||
{
|
||||
use InteractsWithTable;
|
||||
|
||||
protected static ?string $navigationLabel = 'Access logs';
|
||||
|
||||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-shield-check';
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Security';
|
||||
|
||||
protected static ?string $slug = 'security/access-logs';
|
||||
|
||||
protected string $view = 'filament.system.pages.security.access-logs';
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
$user = auth('platform')->user();
|
||||
|
||||
return $user instanceof PlatformUser
|
||||
&& $user->hasCapability(PlatformCapabilities::CONSOLE_VIEW);
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->mountInteractsWithTable();
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('recorded_at', 'desc')
|
||||
->query(function (): Builder {
|
||||
return AuditLog::query()
|
||||
->where(function (Builder $query): void {
|
||||
$query
|
||||
->where('action', 'platform.auth.login')
|
||||
->orWhere('action', 'like', 'platform.break_glass.%');
|
||||
});
|
||||
})
|
||||
->columns([
|
||||
TextColumn::make('recorded_at')
|
||||
->label('Recorded')
|
||||
->since(),
|
||||
TextColumn::make('action')
|
||||
->label('Action')
|
||||
->searchable(),
|
||||
TextColumn::make('status')
|
||||
->badge()
|
||||
->color(fn (?string $state): string => $state === 'failure' ? 'danger' : 'success'),
|
||||
TextColumn::make('actor_email')
|
||||
->label('Actor')
|
||||
->formatStateUsing(fn (?string $state): string => $state ?: 'Unknown'),
|
||||
])
|
||||
->emptyStateHeading('No access logs found')
|
||||
->emptyStateDescription('Platform login and break-glass events will appear here.');
|
||||
}
|
||||
}
|
||||
@ -1,73 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Widgets;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Support\OperationRunOutcome;
|
||||
use App\Support\OperationRunStatus;
|
||||
use App\Support\SystemConsole\StuckRunClassifier;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Filament\Widgets\Widget;
|
||||
|
||||
class ControlTowerHealthIndicator extends Widget
|
||||
{
|
||||
protected string $view = 'filament.system.widgets.control-tower-health-indicator';
|
||||
|
||||
protected static bool $isLazy = false;
|
||||
|
||||
protected int|string|array $columnSpan = 'full';
|
||||
|
||||
/**
|
||||
* @return array{level: string, color: string, icon: string, label: string, failed: int, stuck: int}
|
||||
*/
|
||||
public function getHealthData(): array
|
||||
{
|
||||
$now = CarbonImmutable::now();
|
||||
$last24h = $now->subHours(24);
|
||||
|
||||
$failedRuns = OperationRun::query()
|
||||
->where('created_at', '>=', $last24h)
|
||||
->where('status', OperationRunStatus::Completed->value)
|
||||
->where('outcome', OperationRunOutcome::Failed->value)
|
||||
->count();
|
||||
|
||||
$stuckRuns = app(StuckRunClassifier::class)
|
||||
->apply(OperationRun::query())
|
||||
->count();
|
||||
|
||||
if ($failedRuns > 0 || $stuckRuns > 0) {
|
||||
$level = ($failedRuns >= 5 || $stuckRuns >= 3) ? 'critical' : 'warning';
|
||||
} else {
|
||||
$level = 'healthy';
|
||||
}
|
||||
|
||||
return match ($level) {
|
||||
'critical' => [
|
||||
'level' => 'critical',
|
||||
'color' => 'danger',
|
||||
'icon' => 'heroicon-o-x-circle',
|
||||
'label' => 'Critical',
|
||||
'failed' => $failedRuns,
|
||||
'stuck' => $stuckRuns,
|
||||
],
|
||||
'warning' => [
|
||||
'level' => 'warning',
|
||||
'color' => 'warning',
|
||||
'icon' => 'heroicon-o-exclamation-triangle',
|
||||
'label' => 'Attention needed',
|
||||
'failed' => $failedRuns,
|
||||
'stuck' => $stuckRuns,
|
||||
],
|
||||
default => [
|
||||
'level' => 'healthy',
|
||||
'color' => 'success',
|
||||
'icon' => 'heroicon-o-check-circle',
|
||||
'label' => 'All systems healthy',
|
||||
'failed' => 0,
|
||||
'stuck' => 0,
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -1,65 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Widgets;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Support\OperationRunOutcome;
|
||||
use App\Support\OperationRunStatus;
|
||||
use App\Support\System\SystemOperationRunLinks;
|
||||
use App\Support\SystemConsole\StuckRunClassifier;
|
||||
use App\Support\SystemConsole\SystemConsoleWindow;
|
||||
use Filament\Widgets\StatsOverviewWidget;
|
||||
use Filament\Widgets\StatsOverviewWidget\Stat;
|
||||
|
||||
class ControlTowerKpis extends StatsOverviewWidget
|
||||
{
|
||||
protected static bool $isLazy = false;
|
||||
|
||||
protected int|string|array $columnSpan = 'full';
|
||||
|
||||
/**
|
||||
* @return array<Stat>
|
||||
*/
|
||||
protected function getStats(): array
|
||||
{
|
||||
$window = SystemConsoleWindow::fromNullable((string) request()->query('window'));
|
||||
$start = $window->startAt();
|
||||
|
||||
$baseQuery = OperationRun::query()->where('created_at', '>=', $start);
|
||||
|
||||
$totalRuns = (clone $baseQuery)->count();
|
||||
|
||||
$activeRuns = (clone $baseQuery)
|
||||
->whereIn('status', [
|
||||
OperationRunStatus::Queued->value,
|
||||
OperationRunStatus::Running->value,
|
||||
])
|
||||
->count();
|
||||
|
||||
$failedRuns = (clone $baseQuery)
|
||||
->where('status', OperationRunStatus::Completed->value)
|
||||
->where('outcome', OperationRunOutcome::Failed->value)
|
||||
->count();
|
||||
|
||||
$stuckRuns = app(StuckRunClassifier::class)
|
||||
->apply((clone $baseQuery))
|
||||
->count();
|
||||
|
||||
return [
|
||||
Stat::make('Runs in window', $totalRuns)
|
||||
->description($window::options()[$window->value] ?? 'Last 24 hours')
|
||||
->url(SystemOperationRunLinks::index()),
|
||||
Stat::make('Active', $activeRuns)
|
||||
->color($activeRuns > 0 ? 'warning' : 'gray')
|
||||
->url(SystemOperationRunLinks::index()),
|
||||
Stat::make('Failed', $failedRuns)
|
||||
->color($failedRuns > 0 ? 'danger' : 'gray')
|
||||
->url(SystemOperationRunLinks::index()),
|
||||
Stat::make('Stuck', $stuckRuns)
|
||||
->color($stuckRuns > 0 ? 'danger' : 'gray')
|
||||
->url(SystemOperationRunLinks::index()),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,61 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Widgets;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Support\OperationCatalog;
|
||||
use App\Support\OperationRunOutcome;
|
||||
use App\Support\OperationRunStatus;
|
||||
use App\Support\System\SystemOperationRunLinks;
|
||||
use App\Support\SystemConsole\SystemConsoleWindow;
|
||||
use Filament\Widgets\Widget;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class ControlTowerRecentFailures extends Widget
|
||||
{
|
||||
protected static bool $isLazy = false;
|
||||
|
||||
protected int|string|array $columnSpan = 'full';
|
||||
|
||||
protected string $view = 'filament.system.widgets.control-tower-recent-failures';
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function getViewData(): array
|
||||
{
|
||||
$window = SystemConsoleWindow::fromNullable((string) request()->query('window'));
|
||||
$start = $window->startAt();
|
||||
|
||||
/** @var Collection<int, OperationRun> $runs */
|
||||
$runs = OperationRun::query()
|
||||
->with('tenant')
|
||||
->where('created_at', '>=', $start)
|
||||
->where('status', OperationRunStatus::Completed->value)
|
||||
->where('outcome', OperationRunOutcome::Failed->value)
|
||||
->latest('id')
|
||||
->limit(8)
|
||||
->get();
|
||||
|
||||
return [
|
||||
'windowLabel' => SystemConsoleWindow::options()[$window->value] ?? 'Last 24 hours',
|
||||
'runs' => $runs->map(function (OperationRun $run): array {
|
||||
$failureSummary = is_array($run->failure_summary) ? $run->failure_summary : [];
|
||||
$primaryFailure = is_array($failureSummary[0] ?? null) ? $failureSummary[0] : [];
|
||||
$failureMessage = trim((string) ($primaryFailure['message'] ?? ''));
|
||||
|
||||
return [
|
||||
'id' => (int) $run->getKey(),
|
||||
'operation' => OperationCatalog::label((string) $run->type),
|
||||
'tenant' => $run->tenant?->name ?? 'Tenantless',
|
||||
'created_at' => $run->created_at?->diffForHumans() ?? '—',
|
||||
'failure_message' => $failureMessage !== '' ? $failureMessage : 'No failure details available',
|
||||
'url' => SystemOperationRunLinks::view($run),
|
||||
];
|
||||
}),
|
||||
'runsUrl' => SystemOperationRunLinks::index(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,91 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Widgets;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\Workspace;
|
||||
use App\Support\OperationCatalog;
|
||||
use App\Support\OperationRunOutcome;
|
||||
use App\Support\OperationRunStatus;
|
||||
use App\Support\System\SystemOperationRunLinks;
|
||||
use App\Support\SystemConsole\SystemConsoleWindow;
|
||||
use Filament\Widgets\Widget;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class ControlTowerTopOffenders extends Widget
|
||||
{
|
||||
protected static bool $isLazy = false;
|
||||
|
||||
protected int|string|array $columnSpan = 'full';
|
||||
|
||||
protected string $view = 'filament.system.widgets.control-tower-top-offenders';
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function getViewData(): array
|
||||
{
|
||||
$window = SystemConsoleWindow::fromNullable((string) request()->query('window'));
|
||||
$start = $window->startAt();
|
||||
|
||||
/** @var Collection<int, OperationRun> $grouped */
|
||||
$grouped = OperationRun::query()
|
||||
->selectRaw('workspace_id, tenant_id, type, COUNT(*) AS failed_count')
|
||||
->where('created_at', '>=', $start)
|
||||
->where('status', OperationRunStatus::Completed->value)
|
||||
->where('outcome', OperationRunOutcome::Failed->value)
|
||||
->groupBy('workspace_id', 'tenant_id', 'type')
|
||||
->orderByDesc('failed_count')
|
||||
->limit(10)
|
||||
->get();
|
||||
|
||||
$workspaceIds = $grouped
|
||||
->pluck('workspace_id')
|
||||
->filter(fn ($value): bool => is_numeric($value))
|
||||
->map(fn ($value): int => (int) $value)
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
|
||||
$tenantIds = $grouped
|
||||
->pluck('tenant_id')
|
||||
->filter(fn ($value): bool => is_numeric($value))
|
||||
->map(fn ($value): int => (int) $value)
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
|
||||
$workspaceNames = Workspace::query()
|
||||
->whereIn('id', $workspaceIds)
|
||||
->pluck('name', 'id')
|
||||
->all();
|
||||
|
||||
$tenantNames = Tenant::query()
|
||||
->whereIn('id', $tenantIds)
|
||||
->pluck('name', 'id')
|
||||
->all();
|
||||
|
||||
return [
|
||||
'windowLabel' => SystemConsoleWindow::options()[$window->value] ?? 'Last 24 hours',
|
||||
'offenders' => $grouped->map(function (OperationRun $record) use ($workspaceNames, $tenantNames): array {
|
||||
$workspaceId = is_numeric($record->workspace_id) ? (int) $record->workspace_id : null;
|
||||
$tenantId = is_numeric($record->tenant_id) ? (int) $record->tenant_id : null;
|
||||
|
||||
return [
|
||||
'workspace_label' => $workspaceId !== null
|
||||
? ($workspaceNames[$workspaceId] ?? ('Workspace #'.$workspaceId))
|
||||
: 'Unknown workspace',
|
||||
'tenant_label' => $tenantId !== null
|
||||
? ($tenantNames[$tenantId] ?? ('Tenant #'.$tenantId))
|
||||
: 'Tenantless',
|
||||
'operation_label' => OperationCatalog::label((string) $record->type),
|
||||
'failed_count' => (int) $record->getAttribute('failed_count'),
|
||||
];
|
||||
}),
|
||||
'runsUrl' => SystemOperationRunLinks::index(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,50 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\System\Widgets;
|
||||
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Support\Auth\WorkspaceRole;
|
||||
use Filament\Widgets\StatsOverviewWidget;
|
||||
use Filament\Widgets\StatsOverviewWidget\Stat;
|
||||
|
||||
class RepairWorkspaceOwnersStats extends StatsOverviewWidget
|
||||
{
|
||||
protected static bool $isLazy = false;
|
||||
|
||||
protected int|string|array $columnSpan = 'full';
|
||||
|
||||
/**
|
||||
* @return array<Stat>
|
||||
*/
|
||||
protected function getStats(): array
|
||||
{
|
||||
$totalWorkspaces = Workspace::query()->count();
|
||||
|
||||
$workspacesWithOwners = WorkspaceMembership::query()
|
||||
->where('role', WorkspaceRole::Owner->value)
|
||||
->distinct('workspace_id')
|
||||
->count('workspace_id');
|
||||
|
||||
$ownerlessWorkspaces = $totalWorkspaces - $workspacesWithOwners;
|
||||
|
||||
$totalMembers = WorkspaceMembership::query()->count();
|
||||
|
||||
return [
|
||||
Stat::make('Total workspaces', $totalWorkspaces)
|
||||
->color('gray')
|
||||
->icon('heroicon-o-rectangle-stack'),
|
||||
Stat::make('Healthy (has owner)', $workspacesWithOwners)
|
||||
->color($workspacesWithOwners > 0 ? 'success' : 'gray')
|
||||
->icon('heroicon-o-check-circle'),
|
||||
Stat::make('Ownerless', $ownerlessWorkspaces)
|
||||
->color($ownerlessWorkspaces > 0 ? 'danger' : 'success')
|
||||
->icon($ownerlessWorkspaces > 0 ? 'heroicon-o-exclamation-triangle' : 'heroicon-o-check-circle'),
|
||||
Stat::make('Total memberships', $totalMembers)
|
||||
->color('gray')
|
||||
->icon('heroicon-o-users'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,107 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Widgets\Alerts;
|
||||
|
||||
use App\Filament\Resources\AlertDeliveryResource;
|
||||
use App\Filament\Resources\AlertDestinationResource;
|
||||
use App\Filament\Resources\AlertRuleResource;
|
||||
use App\Models\AlertDelivery;
|
||||
use App\Models\AlertDestination;
|
||||
use App\Models\AlertRule;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Support\OperateHub\OperateHubShell;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Filament\Widgets\StatsOverviewWidget;
|
||||
use Filament\Widgets\StatsOverviewWidget\Stat;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class AlertsKpiHeader extends StatsOverviewWidget
|
||||
{
|
||||
protected static bool $isLazy = false;
|
||||
|
||||
protected int|string|array $columnSpan = 'full';
|
||||
|
||||
/**
|
||||
* @return array<Stat>
|
||||
*/
|
||||
protected function getStats(): array
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
|
||||
if (! is_int($workspaceId)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$stats = [];
|
||||
|
||||
if (AlertRuleResource::canViewAny()) {
|
||||
$totalRules = (int) AlertRule::query()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->count();
|
||||
|
||||
$enabledRules = (int) AlertRule::query()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->where('is_enabled', true)
|
||||
->count();
|
||||
|
||||
$stats[] = Stat::make('Enabled rules', $enabledRules)
|
||||
->description('Total '.$totalRules);
|
||||
}
|
||||
|
||||
if (AlertDestinationResource::canViewAny()) {
|
||||
$totalDestinations = (int) AlertDestination::query()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->count();
|
||||
|
||||
$enabledDestinations = (int) AlertDestination::query()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->where('is_enabled', true)
|
||||
->count();
|
||||
|
||||
$stats[] = Stat::make('Enabled targets', $enabledDestinations)
|
||||
->description('Total '.$totalDestinations);
|
||||
}
|
||||
|
||||
if (AlertDeliveryResource::canViewAny()) {
|
||||
$deliveriesQuery = $this->deliveriesQueryForViewer($user, $workspaceId);
|
||||
|
||||
$deliveries24Hours = (int) (clone $deliveriesQuery)
|
||||
->where('created_at', '>=', now()->subDay())
|
||||
->count();
|
||||
|
||||
$failed7Days = (int) (clone $deliveriesQuery)
|
||||
->where('created_at', '>=', now()->subDays(7))
|
||||
->where('status', AlertDelivery::STATUS_FAILED)
|
||||
->count();
|
||||
|
||||
$stats[] = Stat::make('Deliveries (24h)', $deliveries24Hours);
|
||||
$stats[] = Stat::make('Failed (7d)', $failed7Days);
|
||||
}
|
||||
|
||||
return $stats;
|
||||
}
|
||||
|
||||
private function deliveriesQueryForViewer(User $user, int $workspaceId): Builder
|
||||
{
|
||||
$query = AlertDelivery::query()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->whereIn('tenant_id', $user->tenantMemberships()->select('tenant_id'));
|
||||
|
||||
$activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request());
|
||||
|
||||
if ($activeTenant instanceof Tenant) {
|
||||
$query->where('tenant_id', (int) $activeTenant->getKey());
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
}
|
||||
@ -1,91 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Widgets\Dashboard;
|
||||
|
||||
use App\Models\BaselineTenantAssignment;
|
||||
use App\Models\Finding;
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\Tenant;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Widgets\Widget;
|
||||
|
||||
class BaselineCompareNow extends Widget
|
||||
{
|
||||
protected static bool $isLazy = false;
|
||||
|
||||
protected string $view = 'filament.widgets.dashboard.baseline-compare-now';
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function getViewData(): array
|
||||
{
|
||||
$tenant = Filament::getTenant();
|
||||
|
||||
$empty = [
|
||||
'hasAssignment' => false,
|
||||
'profileName' => null,
|
||||
'findingsCount' => 0,
|
||||
'highCount' => 0,
|
||||
'mediumCount' => 0,
|
||||
'lowCount' => 0,
|
||||
'lastComparedAt' => null,
|
||||
'landingUrl' => null,
|
||||
];
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return $empty;
|
||||
}
|
||||
|
||||
$assignment = BaselineTenantAssignment::query()
|
||||
->where('tenant_id', $tenant->getKey())
|
||||
->with('baselineProfile')
|
||||
->first();
|
||||
|
||||
if (! $assignment instanceof BaselineTenantAssignment || $assignment->baselineProfile === null) {
|
||||
return $empty;
|
||||
}
|
||||
|
||||
$profile = $assignment->baselineProfile;
|
||||
$scopeKey = 'baseline_profile:'.$profile->getKey();
|
||||
|
||||
$findingsQuery = Finding::query()
|
||||
->where('tenant_id', $tenant->getKey())
|
||||
->where('finding_type', Finding::FINDING_TYPE_DRIFT)
|
||||
->where('source', 'baseline.compare')
|
||||
->where('scope_key', $scopeKey)
|
||||
->where('status', Finding::STATUS_NEW);
|
||||
|
||||
$findingsCount = (int) (clone $findingsQuery)->count();
|
||||
$highCount = (int) (clone $findingsQuery)
|
||||
->where('severity', Finding::SEVERITY_HIGH)
|
||||
->count();
|
||||
$mediumCount = (int) (clone $findingsQuery)
|
||||
->where('severity', Finding::SEVERITY_MEDIUM)
|
||||
->count();
|
||||
$lowCount = (int) (clone $findingsQuery)
|
||||
->where('severity', Finding::SEVERITY_LOW)
|
||||
->count();
|
||||
|
||||
$latestRun = OperationRun::query()
|
||||
->where('tenant_id', $tenant->getKey())
|
||||
->where('type', 'baseline_compare')
|
||||
->where('context->baseline_profile_id', (string) $profile->getKey())
|
||||
->whereNotNull('completed_at')
|
||||
->latest('completed_at')
|
||||
->first();
|
||||
|
||||
return [
|
||||
'hasAssignment' => true,
|
||||
'profileName' => (string) $profile->name,
|
||||
'findingsCount' => $findingsCount,
|
||||
'highCount' => $highCount,
|
||||
'mediumCount' => $mediumCount,
|
||||
'lowCount' => $lowCount,
|
||||
'lastComparedAt' => $latestRun?->finished_at?->diffForHumans(),
|
||||
'landingUrl' => \App\Filament\Pages\BaselineCompareLanding::getUrl(tenant: $tenant),
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,178 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Widgets\Tenant;
|
||||
|
||||
use App\Jobs\ScanEntraAdminRolesJob;
|
||||
use App\Models\StoredReport;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\OperationRunService;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\OperationRunLinks;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Widgets\Widget;
|
||||
|
||||
class AdminRolesSummaryWidget extends Widget
|
||||
{
|
||||
protected static bool $isLazy = false;
|
||||
|
||||
protected string $view = 'filament.widgets.tenant.admin-roles-summary';
|
||||
|
||||
public ?Tenant $record = null;
|
||||
|
||||
private function resolveTenant(): ?Tenant
|
||||
{
|
||||
$tenant = Filament::getTenant();
|
||||
|
||||
if ($tenant instanceof Tenant) {
|
||||
return $tenant;
|
||||
}
|
||||
|
||||
return $this->record instanceof Tenant ? $this->record : null;
|
||||
}
|
||||
|
||||
public function scanNow(): void
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
$tenant = $this->resolveTenant();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
if (! $user->canAccessTenant($tenant)) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
if (! $user->can(Capabilities::ENTRA_ROLES_MANAGE, $tenant)) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
/** @var OperationRunService $operationRuns */
|
||||
$operationRuns = app(OperationRunService::class);
|
||||
|
||||
$opRun = $operationRuns->ensureRunWithIdentity(
|
||||
tenant: $tenant,
|
||||
type: 'entra.admin_roles.scan',
|
||||
identityInputs: [
|
||||
'tenant_id' => (int) $tenant->getKey(),
|
||||
'trigger' => 'scan',
|
||||
],
|
||||
context: [
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'initiator_user_id' => (int) $user->getKey(),
|
||||
],
|
||||
initiator: $user,
|
||||
);
|
||||
|
||||
$runUrl = OperationRunLinks::tenantlessView($opRun);
|
||||
|
||||
if ($opRun->wasRecentlyCreated === false) {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
->url($runUrl),
|
||||
])
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$operationRuns->dispatchOrFail($opRun, function () use ($tenant, $user): void {
|
||||
ScanEntraAdminRolesJob::dispatch(
|
||||
tenantId: (int) $tenant->getKey(),
|
||||
workspaceId: (int) $tenant->workspace_id,
|
||||
initiatorUserId: (int) $user->getKey(),
|
||||
);
|
||||
});
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $opRun->type)
|
||||
->body('The scan will run in the background. Results appear once complete.')
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
->url($runUrl),
|
||||
])
|
||||
->send();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function getViewData(): array
|
||||
{
|
||||
$tenant = $this->resolveTenant();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return $this->emptyState();
|
||||
}
|
||||
|
||||
$user = auth()->user();
|
||||
$isTenantMember = $user instanceof User && $user->canAccessTenant($tenant);
|
||||
$canView = $isTenantMember && $user->can(Capabilities::ENTRA_ROLES_VIEW, $tenant);
|
||||
$canManage = $isTenantMember && $user->can(Capabilities::ENTRA_ROLES_MANAGE, $tenant);
|
||||
|
||||
$report = StoredReport::query()
|
||||
->where('tenant_id', (int) $tenant->getKey())
|
||||
->where('report_type', StoredReport::REPORT_TYPE_ENTRA_ADMIN_ROLES)
|
||||
->orderByDesc('created_at')
|
||||
->first();
|
||||
|
||||
if (! $report instanceof StoredReport) {
|
||||
return [
|
||||
'tenant' => $tenant,
|
||||
'reportSummary' => null,
|
||||
'lastScanAt' => null,
|
||||
'highPrivilegeCount' => 0,
|
||||
'canManage' => $canManage,
|
||||
'canView' => $canView,
|
||||
'viewReportUrl' => null,
|
||||
];
|
||||
}
|
||||
|
||||
$payload = is_array($report->payload) ? $report->payload : [];
|
||||
$totals = is_array($payload['totals'] ?? null) ? $payload['totals'] : [];
|
||||
$highPrivilegeCount = (int) ($totals['high_privilege_assignments'] ?? 0);
|
||||
|
||||
return [
|
||||
'tenant' => $tenant,
|
||||
'reportSummary' => $totals,
|
||||
'lastScanAt' => $report->created_at?->diffForHumans() ?? '—',
|
||||
'highPrivilegeCount' => $highPrivilegeCount,
|
||||
'canManage' => $canManage,
|
||||
'canView' => $canView,
|
||||
'viewReportUrl' => null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function emptyState(): array
|
||||
{
|
||||
return [
|
||||
'tenant' => null,
|
||||
'reportSummary' => null,
|
||||
'lastScanAt' => null,
|
||||
'highPrivilegeCount' => 0,
|
||||
'canManage' => false,
|
||||
'canView' => false,
|
||||
'viewReportUrl' => null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -1,190 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Widgets\Tenant;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\ReviewPack;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\ReviewPackService;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use App\Support\OperationRunLinks;
|
||||
use App\Support\OperationRunType;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||
use App\Support\ReviewPackStatus;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Widgets\Widget;
|
||||
|
||||
class TenantReviewPackCard extends Widget
|
||||
{
|
||||
protected static bool $isLazy = false;
|
||||
|
||||
protected string $view = 'filament.widgets.tenant.tenant-review-pack-card';
|
||||
|
||||
public ?Tenant $record = null;
|
||||
|
||||
private function resolveTenant(): ?Tenant
|
||||
{
|
||||
$tenant = Filament::getTenant();
|
||||
|
||||
if ($tenant instanceof Tenant) {
|
||||
return $tenant;
|
||||
}
|
||||
|
||||
return $this->record instanceof Tenant ? $this->record : null;
|
||||
}
|
||||
|
||||
public function generatePack(bool $includePii = true, bool $includeOperations = true): void
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
$tenant = $this->resolveTenant();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
if (! $user->canAccessTenant($tenant)) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
if (! $user->can(Capabilities::REVIEW_PACK_MANAGE, $tenant)) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
/** @var ReviewPackService $service */
|
||||
$service = app(ReviewPackService::class);
|
||||
|
||||
$activeRun = $service->checkActiveRun($tenant)
|
||||
? OperationRun::query()
|
||||
->where('tenant_id', (int) $tenant->getKey())
|
||||
->where('type', OperationRunType::ReviewPackGenerate->value)
|
||||
->active()
|
||||
->orderByDesc('id')
|
||||
->first()
|
||||
: null;
|
||||
|
||||
if ($activeRun) {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $activeRun->type)
|
||||
->body('A review pack is already queued or running for this tenant.')
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
->url(OperationRunLinks::tenantlessView($activeRun)),
|
||||
])
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$reviewPack = $service->generate($tenant, $user, [
|
||||
'include_pii' => $includePii,
|
||||
'include_operations' => $includeOperations,
|
||||
]);
|
||||
|
||||
$runUrl = $reviewPack->operationRun
|
||||
? OperationRunLinks::tenantlessView($reviewPack->operationRun)
|
||||
: null;
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
$toast = OperationUxPresenter::queuedToast(OperationRunType::ReviewPackGenerate->value)
|
||||
->body('The pack will be generated in the background. You will be notified when it is ready.');
|
||||
|
||||
if ($runUrl !== null) {
|
||||
$toast->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
->url($runUrl),
|
||||
]);
|
||||
}
|
||||
|
||||
$toast->send();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function getViewData(): array
|
||||
{
|
||||
$tenant = $this->resolveTenant();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return $this->emptyState();
|
||||
}
|
||||
|
||||
$user = auth()->user();
|
||||
$isTenantMember = $user instanceof User && $user->canAccessTenant($tenant);
|
||||
$canView = $isTenantMember && $user->can(Capabilities::REVIEW_PACK_VIEW, $tenant);
|
||||
$canManage = $isTenantMember && $user->can(Capabilities::REVIEW_PACK_MANAGE, $tenant);
|
||||
|
||||
$latestPack = ReviewPack::query()
|
||||
->where('tenant_id', (int) $tenant->getKey())
|
||||
->orderByDesc('created_at')
|
||||
->orderByDesc('id')
|
||||
->first();
|
||||
|
||||
if (! $latestPack instanceof ReviewPack) {
|
||||
return [
|
||||
'tenant' => $tenant,
|
||||
'pack' => null,
|
||||
'statusEnum' => null,
|
||||
'canView' => $canView,
|
||||
'canManage' => $canManage,
|
||||
'downloadUrl' => null,
|
||||
'failedReason' => null,
|
||||
];
|
||||
}
|
||||
|
||||
$statusEnum = ReviewPackStatus::tryFrom((string) $latestPack->status);
|
||||
|
||||
$downloadUrl = null;
|
||||
if ($statusEnum === ReviewPackStatus::Ready && $canView) {
|
||||
/** @var ReviewPackService $service */
|
||||
$service = app(ReviewPackService::class);
|
||||
$downloadUrl = $service->generateDownloadUrl($latestPack);
|
||||
}
|
||||
|
||||
$failedReason = null;
|
||||
if ($statusEnum === ReviewPackStatus::Failed && $latestPack->operationRun) {
|
||||
$opContext = is_array($latestPack->operationRun->context) ? $latestPack->operationRun->context : [];
|
||||
$failedReason = (string) ($opContext['reason_code'] ?? 'Unknown error');
|
||||
}
|
||||
|
||||
return [
|
||||
'tenant' => $tenant,
|
||||
'pack' => $latestPack,
|
||||
'statusEnum' => $statusEnum,
|
||||
'canView' => $canView,
|
||||
'canManage' => $canManage,
|
||||
'downloadUrl' => $downloadUrl,
|
||||
'failedReason' => $failedReason,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function emptyState(): array
|
||||
{
|
||||
return [
|
||||
'tenant' => null,
|
||||
'pack' => null,
|
||||
'statusEnum' => null,
|
||||
'canView' => false,
|
||||
'canManage' => false,
|
||||
'downloadUrl' => null,
|
||||
'failedReason' => null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -13,8 +13,6 @@
|
||||
use App\Support\Auth\UiTooltips;
|
||||
use App\Support\OperationRunLinks;
|
||||
use App\Support\OperationRunStatus;
|
||||
use App\Support\OpsUx\OperationUxPresenter;
|
||||
use App\Support\OpsUx\OpsUxBrowserEvents;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Notifications\Notification;
|
||||
@ -70,8 +68,6 @@ public function startVerification(StartVerification $verification): void
|
||||
$runUrl = OperationRunLinks::tenantlessView($result->run);
|
||||
|
||||
if ($result->status === 'scope_busy') {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
Notification::make()
|
||||
->title('Another operation is already running')
|
||||
->body('Please wait for the active run to finish.')
|
||||
@ -87,9 +83,10 @@ public function startVerification(StartVerification $verification): void
|
||||
}
|
||||
|
||||
if ($result->status === 'deduped') {
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::alreadyQueuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Verification already running')
|
||||
->body('A verification run is already queued or running.')
|
||||
->warning()
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
@ -143,9 +140,9 @@ public function startVerification(StartVerification $verification): void
|
||||
return;
|
||||
}
|
||||
|
||||
OpsUxBrowserEvents::dispatchRunEnqueued($this);
|
||||
|
||||
OperationUxPresenter::queuedToast((string) $result->run->type)
|
||||
Notification::make()
|
||||
->title('Verification started')
|
||||
->success()
|
||||
->actions([
|
||||
Action::make('view_run')
|
||||
->label('View run')
|
||||
|
||||
@ -20,7 +20,6 @@ public function __invoke(
|
||||
AuditLogger $auditLogger,
|
||||
): View {
|
||||
$expectedState = $request->session()->pull('tenant_onboard_state');
|
||||
$workspaceId = $request->session()->pull('tenant_onboard_workspace_id');
|
||||
$tenantKey = $request->string('tenant')->toString();
|
||||
$state = $request->string('state')->toString();
|
||||
$tenantIdentifier = $tenantKey ?: $this->parseState($state);
|
||||
@ -31,7 +30,7 @@ public function __invoke(
|
||||
|
||||
abort_if(empty($tenantIdentifier), 404);
|
||||
|
||||
$tenant = $this->resolveTenant($tenantIdentifier, is_numeric($workspaceId) ? (int) $workspaceId : null);
|
||||
$tenant = $this->resolveTenant($tenantIdentifier);
|
||||
|
||||
$error = $request->string('error')->toString() ?: null;
|
||||
$consentGranted = $request->has('admin_consent')
|
||||
@ -76,7 +75,7 @@ public function __invoke(
|
||||
]);
|
||||
}
|
||||
|
||||
private function resolveTenant(string $tenantIdentifier, ?int $workspaceId): Tenant
|
||||
private function resolveTenant(string $tenantIdentifier): Tenant
|
||||
{
|
||||
/** @var Tenant|null $tenant */
|
||||
$tenant = Tenant::withTrashed()
|
||||
@ -88,19 +87,12 @@ private function resolveTenant(string $tenantIdentifier, ?int $workspaceId): Ten
|
||||
}
|
||||
|
||||
if ($tenant instanceof Tenant) {
|
||||
if ($tenant->workspace_id === null && $workspaceId !== null) {
|
||||
$tenant->forceFill(['workspace_id' => $workspaceId])->save();
|
||||
}
|
||||
|
||||
return $tenant;
|
||||
}
|
||||
|
||||
abort_if($workspaceId === null, ResponseAlias::HTTP_FORBIDDEN, 'Missing workspace context');
|
||||
|
||||
return Tenant::create([
|
||||
'tenant_id' => $tenantIdentifier,
|
||||
'name' => 'New Tenant',
|
||||
'workspace_id' => $workspaceId,
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@ -1,43 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\ReviewPack;
|
||||
use App\Support\ReviewPackStatus;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class ReviewPackDownloadController extends Controller
|
||||
{
|
||||
public function __invoke(Request $request, ReviewPack $reviewPack): StreamedResponse
|
||||
{
|
||||
if ($reviewPack->status !== ReviewPackStatus::Ready->value) {
|
||||
throw new NotFoundHttpException;
|
||||
}
|
||||
|
||||
if ($reviewPack->expires_at && $reviewPack->expires_at->isPast()) {
|
||||
throw new NotFoundHttpException;
|
||||
}
|
||||
|
||||
$disk = Storage::disk($reviewPack->file_disk ?? 'exports');
|
||||
|
||||
if (! $disk->exists($reviewPack->file_path)) {
|
||||
throw new NotFoundHttpException;
|
||||
}
|
||||
|
||||
$tenant = $reviewPack->tenant;
|
||||
$filename = sprintf(
|
||||
'review-pack-%s-%s.zip',
|
||||
$tenant?->external_id ?? 'unknown',
|
||||
$reviewPack->generated_at?->format('Y-m-d') ?? now()->format('Y-m-d'),
|
||||
);
|
||||
|
||||
return $disk->download($reviewPack->file_path, $filename, [
|
||||
'X-Review-Pack-SHA256' => $reviewPack->sha256 ?? '',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -4,13 +4,12 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Filament\Pages\ChooseTenant;
|
||||
use App\Filament\Pages\TenantDashboard;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Services\Audit\WorkspaceAuditLogger;
|
||||
use App\Support\Audit\AuditActionId;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use App\Support\Workspaces\WorkspaceIntendedUrl;
|
||||
use App\Support\Workspaces\WorkspaceRedirectResolver;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
@ -44,37 +43,32 @@ public function __invoke(Request $request): RedirectResponse
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$prevWorkspaceId = $context->currentWorkspaceId($request);
|
||||
|
||||
$context->setCurrentWorkspace($workspace, $user, $request);
|
||||
|
||||
/** @var WorkspaceAuditLogger $auditLogger */
|
||||
$auditLogger = app(WorkspaceAuditLogger::class);
|
||||
|
||||
$auditLogger->log(
|
||||
workspace: $workspace,
|
||||
action: AuditActionId::WorkspaceSelected->value,
|
||||
context: [
|
||||
'metadata' => [
|
||||
'method' => 'manual',
|
||||
'reason' => 'context_bar',
|
||||
'prev_workspace_id' => $prevWorkspaceId,
|
||||
],
|
||||
],
|
||||
actor: $user,
|
||||
resourceType: 'workspace',
|
||||
resourceId: (string) $workspace->getKey(),
|
||||
);
|
||||
|
||||
$intendedUrl = WorkspaceIntendedUrl::consume($request);
|
||||
|
||||
if ($intendedUrl !== null) {
|
||||
return redirect()->to($intendedUrl);
|
||||
}
|
||||
|
||||
/** @var WorkspaceRedirectResolver $resolver */
|
||||
$resolver = app(WorkspaceRedirectResolver::class);
|
||||
$tenantsQuery = $user->tenants()
|
||||
->where('workspace_id', $workspace->getKey())
|
||||
->where('status', 'active');
|
||||
|
||||
return redirect()->to($resolver->resolve($workspace, $user));
|
||||
$tenantCount = (int) $tenantsQuery->count();
|
||||
|
||||
if ($tenantCount === 0) {
|
||||
return redirect()->route('admin.onboarding');
|
||||
}
|
||||
|
||||
if ($tenantCount === 1) {
|
||||
$tenant = $tenantsQuery->first();
|
||||
|
||||
if ($tenant !== null) {
|
||||
return redirect()->to(TenantDashboard::getUrl(panel: 'tenant', tenant: $tenant));
|
||||
}
|
||||
}
|
||||
|
||||
return redirect()->to(ChooseTenant::getUrl());
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,7 +2,6 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
@ -21,12 +20,6 @@ public function __invoke(Request $request): RedirectResponse
|
||||
$state = Str::uuid()->toString();
|
||||
$request->session()->put('tenant_onboard_state', $state);
|
||||
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId($request);
|
||||
|
||||
if ($workspaceId !== null) {
|
||||
$request->session()->put('tenant_onboard_workspace_id', (int) $workspaceId);
|
||||
}
|
||||
|
||||
$url = "https://login.microsoftonline.com/{$tenantSegment}/v2.0/adminconsent?".http_build_query([
|
||||
'client_id' => $clientId,
|
||||
'redirect_uri' => $redirectUri,
|
||||
|
||||
@ -29,7 +29,7 @@ public function handle(Request $request, Closure $next, string $capability): Res
|
||||
}
|
||||
|
||||
if (! Gate::forUser($user)->allows($capability)) {
|
||||
abort(403);
|
||||
abort(404);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
|
||||
@ -1,20 +1,17 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Services\Audit\WorkspaceAuditLogger;
|
||||
use App\Support\Audit\AuditActionId;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use App\Support\Workspaces\WorkspaceIntendedUrl;
|
||||
use App\Support\Workspaces\WorkspaceRedirectResolver;
|
||||
use Closure;
|
||||
use Filament\Notifications\Notification;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response as HttpResponse;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class EnsureWorkspaceSelected
|
||||
@ -22,20 +19,10 @@ class EnsureWorkspaceSelected
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* Spec 107 — 7-step algorithm:
|
||||
* 1. If workspace-optional path → allow
|
||||
* 2. If ?choose=1 → redirect to chooser
|
||||
* 3. If session set → validate membership; stale → clear + warn + chooser
|
||||
* 4. Load selectable memberships
|
||||
* 5. If exactly 1 → auto-select + audit + redirect via tenant branching
|
||||
* 6. If last_workspace_id valid → auto-select + audit + redirect
|
||||
* 7. Else → redirect to chooser
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
// Auth-related routes are always allowed.
|
||||
$routeName = $request->route()?->getName();
|
||||
|
||||
if (is_string($routeName) && str_contains($routeName, '.auth.')) {
|
||||
@ -44,12 +31,10 @@ public function handle(Request $request, Closure $next): Response
|
||||
|
||||
$path = '/'.ltrim($request->path(), '/');
|
||||
|
||||
// --- Step 1: workspace-optional bypass ---
|
||||
if ($this->isWorkspaceOptionalPath($request, $path)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// Tenant-scoped routes are handled separately.
|
||||
if (str_starts_with($path, '/admin/t/')) {
|
||||
return $next($request);
|
||||
}
|
||||
@ -63,105 +48,44 @@ public function handle(Request $request, Closure $next): Response
|
||||
/** @var WorkspaceContext $context */
|
||||
$context = app(WorkspaceContext::class);
|
||||
|
||||
// --- Step 2: forced chooser via ?choose=1 ---
|
||||
if ($request->query('choose') === '1') {
|
||||
return $this->redirectToChooser();
|
||||
$workspace = $context->resolveInitialWorkspaceFor($user, $request);
|
||||
|
||||
if ($workspace !== null) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// --- Step 3: validate active session ---
|
||||
$currentId = $context->currentWorkspaceId($request);
|
||||
$membershipQuery = WorkspaceMembership::query()->where('user_id', $user->getKey());
|
||||
|
||||
if ($currentId !== null) {
|
||||
$workspace = Workspace::query()->whereKey($currentId)->first();
|
||||
$hasAnyActiveMembership = Schema::hasColumn('workspaces', 'archived_at')
|
||||
? $membershipQuery
|
||||
->join('workspaces', 'workspace_memberships.workspace_id', '=', 'workspaces.id')
|
||||
->whereNull('workspaces.archived_at')
|
||||
->exists()
|
||||
: $membershipQuery->exists();
|
||||
|
||||
if (
|
||||
$workspace instanceof Workspace
|
||||
&& empty($workspace->archived_at)
|
||||
&& $context->isMember($user, $workspace)
|
||||
) {
|
||||
return $next($request);
|
||||
}
|
||||
$canCreateWorkspace = Gate::forUser($user)->check('create', Workspace::class);
|
||||
|
||||
// Stale session — clear and warn.
|
||||
$this->clearStaleSession($context, $user, $request, $workspace);
|
||||
|
||||
return $this->redirectToChooser();
|
||||
if (! $hasAnyActiveMembership && $this->isOperateHubPath($path)) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
// --- Step 4: load selectable workspace memberships ---
|
||||
$selectableMemberships = WorkspaceMembership::query()
|
||||
->where('user_id', $user->getKey())
|
||||
->join('workspaces', 'workspace_memberships.workspace_id', '=', 'workspaces.id')
|
||||
->whereNull('workspaces.archived_at')
|
||||
->select('workspace_memberships.*')
|
||||
->get();
|
||||
|
||||
// --- Step 5: single membership auto-resume ---
|
||||
if ($selectableMemberships->count() === 1) {
|
||||
/** @var WorkspaceMembership $membership */
|
||||
$membership = $selectableMemberships->first();
|
||||
$workspace = Workspace::query()->whereKey($membership->workspace_id)->first();
|
||||
|
||||
if ($workspace instanceof Workspace) {
|
||||
$context->setCurrentWorkspace($workspace, $user, $request);
|
||||
|
||||
$this->emitAuditEvent(
|
||||
workspace: $workspace,
|
||||
user: $user,
|
||||
actionId: AuditActionId::WorkspaceAutoSelected,
|
||||
method: 'auto',
|
||||
reason: 'single_membership',
|
||||
);
|
||||
|
||||
return $this->redirectViaTenantBranching($workspace, $user);
|
||||
}
|
||||
if (! $hasAnyActiveMembership && str_starts_with($path, '/admin/tenants')) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
// --- Step 6: last_workspace_id auto-resume ---
|
||||
if ($user->last_workspace_id !== null) {
|
||||
$lastWorkspace = Workspace::query()->whereKey($user->last_workspace_id)->first();
|
||||
|
||||
if (
|
||||
$lastWorkspace instanceof Workspace
|
||||
&& empty($lastWorkspace->archived_at)
|
||||
&& $context->isMember($user, $lastWorkspace)
|
||||
) {
|
||||
$context->setCurrentWorkspace($lastWorkspace, $user, $request);
|
||||
|
||||
$this->emitAuditEvent(
|
||||
workspace: $lastWorkspace,
|
||||
user: $user,
|
||||
actionId: AuditActionId::WorkspaceAutoSelected,
|
||||
method: 'auto',
|
||||
reason: 'last_used',
|
||||
);
|
||||
|
||||
return $this->redirectViaTenantBranching($lastWorkspace, $user);
|
||||
}
|
||||
|
||||
// Stale last_workspace_id — clear and warn.
|
||||
$workspaceName = $lastWorkspace?->name;
|
||||
$user->forceFill(['last_workspace_id' => null])->save();
|
||||
|
||||
if ($workspaceName !== null) {
|
||||
Notification::make()
|
||||
->title("Your access to {$workspaceName} was removed.")
|
||||
->danger()
|
||||
->send();
|
||||
}
|
||||
if (! $hasAnyActiveMembership && str_starts_with($path, '/admin/provider-connections')) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
// --- Step 7: fallback to chooser ---
|
||||
if ($selectableMemberships->isNotEmpty()) {
|
||||
WorkspaceIntendedUrl::storeFromRequest($request);
|
||||
}
|
||||
|
||||
$canCreate = $user->can('create', Workspace::class);
|
||||
$target = ($selectableMemberships->isNotEmpty() || $canCreate)
|
||||
$target = ($hasAnyActiveMembership || $canCreateWorkspace)
|
||||
? '/admin/choose-workspace'
|
||||
: '/admin/no-access';
|
||||
|
||||
return new \Illuminate\Http\Response('', 302, ['Location' => $target]);
|
||||
if ($target === '/admin/choose-workspace') {
|
||||
WorkspaceIntendedUrl::storeFromRequest($request);
|
||||
}
|
||||
|
||||
return new HttpResponse('', 302, ['Location' => $target]);
|
||||
}
|
||||
|
||||
private function isWorkspaceOptionalPath(Request $request, string $path): bool
|
||||
@ -170,7 +94,7 @@ private function isWorkspaceOptionalPath(Request $request, string $path): bool
|
||||
return true;
|
||||
}
|
||||
|
||||
if (in_array($path, ['/admin/choose-workspace', '/admin/no-access', '/admin/onboarding', '/admin/settings/workspace'], true)) {
|
||||
if (in_array($path, ['/admin/choose-workspace', '/admin/no-access', '/admin/onboarding'], true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -186,64 +110,12 @@ private function isWorkspaceOptionalPath(Request $request, string $path): bool
|
||||
return preg_match('#^/admin/operations/[^/]+$#', $path) === 1;
|
||||
}
|
||||
|
||||
private function redirectToChooser(): Response
|
||||
private function isOperateHubPath(string $path): bool
|
||||
{
|
||||
return new \Illuminate\Http\Response('', 302, ['Location' => '/admin/choose-workspace']);
|
||||
}
|
||||
|
||||
private function redirectViaTenantBranching(Workspace $workspace, User $user): Response
|
||||
{
|
||||
/** @var WorkspaceRedirectResolver $resolver */
|
||||
$resolver = app(WorkspaceRedirectResolver::class);
|
||||
|
||||
$url = $resolver->resolve($workspace, $user);
|
||||
|
||||
return new \Illuminate\Http\Response('', 302, ['Location' => $url]);
|
||||
}
|
||||
|
||||
private function clearStaleSession(WorkspaceContext $context, User $user, Request $request, ?Workspace $workspace): void
|
||||
{
|
||||
$workspaceName = $workspace?->name;
|
||||
|
||||
$session = $request->hasSession() ? $request->session() : session();
|
||||
$session->forget(WorkspaceContext::SESSION_KEY);
|
||||
|
||||
if ($user->last_workspace_id !== null && $context->currentWorkspaceId($request) === null) {
|
||||
$user->forceFill(['last_workspace_id' => null])->save();
|
||||
}
|
||||
|
||||
if ($workspaceName !== null) {
|
||||
Notification::make()
|
||||
->title("Your access to {$workspaceName} was removed.")
|
||||
->danger()
|
||||
->send();
|
||||
}
|
||||
}
|
||||
|
||||
private function emitAuditEvent(
|
||||
Workspace $workspace,
|
||||
User $user,
|
||||
AuditActionId $actionId,
|
||||
string $method,
|
||||
string $reason,
|
||||
?int $prevWorkspaceId = null,
|
||||
): void {
|
||||
/** @var WorkspaceAuditLogger $logger */
|
||||
$logger = app(WorkspaceAuditLogger::class);
|
||||
|
||||
$logger->log(
|
||||
workspace: $workspace,
|
||||
action: $actionId->value,
|
||||
context: [
|
||||
'metadata' => [
|
||||
'method' => $method,
|
||||
'reason' => $reason,
|
||||
'prev_workspace_id' => $prevWorkspaceId,
|
||||
],
|
||||
],
|
||||
actor: $user,
|
||||
resourceType: 'workspace',
|
||||
resourceId: (string) $workspace->getKey(),
|
||||
);
|
||||
return in_array($path, [
|
||||
'/admin/operations',
|
||||
'/admin/alerts',
|
||||
'/admin/audit-log',
|
||||
], true);
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user