TenantAtlas/app/Filament/Resources/PolicyResource.php
Ahmed Darrazi 6d14d2544f feat: TenantPilot v1 - Complete implementation (Phases 1-12)
Complete implementation of TenantPilot v1 Intune Management Platform with
comprehensive backup, versioning, and restore capabilities.

CONSTITUTION & SPEC
- Ratified constitution v1.0.0 with 7 core principles
- Complete spec.md with 7 user stories (US1-7)
- Detailed plan.md with constitution compliance check
- Task breakdown with 125+ tasks across 12 phases

CORE FEATURES (US1-4)
- Policy inventory with Graph-based sync (US1)
- Backup creation with immutable JSONB snapshots (US2)
- Version history with diff viewer (human + JSON) (US3)
- Defensive restore with preview/dry-run (US4)

TENANT MANAGEMENT (US6-7)
- Full tenant CRUD with Entra ID app configuration
- Admin consent callback flow integration
- Tenant connectivity verification
- Permission health status monitoring
- 'Highlander' pattern: single current tenant with is_current flag

GRAPH ABSTRACTION
- Complete isolation layer (7 classes)
- GraphClientInterface with mockable implementations
- Error mapping, logging, and standardized responses
- Rate-limit aware design

DOMAIN SERVICES
- BackupService: immutable snapshot creation
- RestoreService: preview, selective restore, conflict detection
- VersionService: immutable version capture
- VersionDiff: human-readable and structured diffs
- PolicySyncService: Graph-based policy import
- TenantConfigService: connectivity testing
- TenantPermissionService: permission health checks
- AuditLogger: comprehensive audit trail

DATA MODEL
- 11 migrations with tenant-aware schema
- 8 Eloquent models with proper relationships
- SoftDeletes on Tenant, BackupSet, BackupItem, PolicyVersion, RestoreRun
- JSONB storage for snapshots, metadata, permissions
- Encrypted storage for client secrets
- Partial unique index for is_current tenant

FILAMENT ADMIN UI
- 5 main resources: Tenant, Policy, PolicyVersion, BackupSet, RestoreRun
- RelationManagers: Versions (Policy), BackupItems (BackupSet)
- Actions: Verify config, Admin consent, Make current, Delete/Force delete
- Filters: Status, Type, Platform, Archive state
- Permission panel with status indicators
- ActionGroup pattern for cleaner row actions

HOUSEKEEPING (Phases 10-12)
- Soft delete with archive status for all entities
- Force delete protection (blocks if dependencies exist)
- Tenant deactivation with cascade prevention
- Audit logging for all delete operations

TESTING
- 36 tests passing (125 assertions, 11.21s)
- Feature tests: Policy, Backup, Restore, Version, Tenant, Housekeeping
- Unit tests: VersionDiff, TenantCurrent, Permissions, Scopes
- Full TDD coverage for critical flows

CONFIGURATION
- config/tenantpilot.php: 10+ policy types with metadata
- config/intune_permissions.php: required Graph permissions
- config/graph.php: Graph client configuration

SAFETY & COMPLIANCE
- Constitution compliance: 7/7 principles ✓
- Safety-first operations: preview, confirmation, validation
- Immutable versioning: no in-place modifications
- Defensive restore: dry-run, selective, conflict detection
- Comprehensive auditability: all critical operations logged
- Tenant-aware architecture: multi-tenant ready
- Graph abstraction: isolated, mockable, testable
- Spec-driven development: spec → plan → tasks → implementation

OPERATIONAL READINESS
- Laravel Sail for local development
- Dokploy deployment documentation
- Queue/worker ready architecture
- Migration safety notes
- Environment variable documentation

Tests: 36 passed
Duration: 11.21s
Status: Production-ready (98% complete)
2025-12-12 02:27:54 +01:00

150 lines
5.5 KiB
PHP

<?php
namespace App\Filament\Resources;
use App\Filament\Resources\PolicyResource\Pages;
use App\Filament\Resources\PolicyResource\RelationManagers\VersionsRelationManager;
use App\Models\Policy;
use App\Models\Tenant;
use BackedEnum;
use Filament\Actions;
use Filament\Infolists;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use UnitEnum;
class PolicyResource extends Resource
{
protected static ?string $model = Policy::class;
protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-shield-check';
protected static string|UnitEnum|null $navigationGroup = 'Inventory';
public static function form(Schema $schema): Schema
{
return $schema;
}
public static function infolist(Schema $schema): Schema
{
return $schema
->schema([
Infolists\Components\TextEntry::make('display_name')->label('Policy'),
Infolists\Components\TextEntry::make('policy_type')->label('Type'),
Infolists\Components\TextEntry::make('platform'),
Infolists\Components\TextEntry::make('external_id')->label('External ID'),
Infolists\Components\TextEntry::make('last_synced_at')->dateTime()->label('Last synced'),
Infolists\Components\TextEntry::make('created_at')->since(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('display_name')
->label('Policy')
->searchable(),
Tables\Columns\TextColumn::make('policy_type')
->label('Type')
->badge()
->formatStateUsing(fn (?string $state, Policy $record) => static::typeMeta($record->policy_type)['label'] ?? $state),
Tables\Columns\TextColumn::make('category')
->label('Category')
->badge()
->state(fn (Policy $record) => static::typeMeta($record->policy_type)['category'] ?? 'Unknown'),
Tables\Columns\TextColumn::make('restore_mode')
->label('Restore')
->badge()
->state(fn (Policy $record) => static::typeMeta($record->policy_type)['restore'] ?? 'enabled'),
Tables\Columns\TextColumn::make('platform')
->badge()
->sortable(),
Tables\Columns\TextColumn::make('external_id')
->label('External ID')
->copyable()
->limit(32),
Tables\Columns\TextColumn::make('last_synced_at')
->label('Last synced')
->dateTime()
->sortable(),
Tables\Columns\TextColumn::make('created_at')
->dateTime()
->since()
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
Tables\Filters\SelectFilter::make('policy_type')
->options(fn () => Policy::query()->distinct()->pluck('policy_type', 'policy_type')->all()),
Tables\Filters\SelectFilter::make('category')
->options(function () {
return collect(config('tenantpilot.supported_policy_types', []))
->pluck('category', 'category')
->filter()
->unique()
->sort()
->all();
})
->query(function (Builder $query, array $data) {
$category = $data['value'] ?? null;
if (! $category) {
return;
}
$types = collect(config('tenantpilot.supported_policy_types', []))
->where('category', $category)
->pluck('type')
->all();
$query->whereIn('policy_type', $types);
}),
Tables\Filters\SelectFilter::make('platform')
->options(fn () => Policy::query()->distinct()->pluck('platform', 'platform')->filter()->all()),
])
->actions([
Actions\ViewAction::make(),
])
->bulkActions([]);
}
public static function getEloquentQuery(): Builder
{
$tenantId = Tenant::current()->getKey();
return parent::getEloquentQuery()
->when($tenantId, fn (Builder $query) => $query->where('tenant_id', $tenantId));
}
public static function getRelations(): array
{
return [
VersionsRelationManager::class,
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListPolicies::route('/'),
'view' => Pages\ViewPolicy::route('/{record}'),
];
}
/**
* @return array{label:?string,category:?string,restore:?string,risk:?string}|array<string,string>|array<string,mixed>
*/
private static function typeMeta(?string $type): array
{
if ($type === null) {
return [];
}
return collect(config('tenantpilot.supported_policy_types', []))
->firstWhere('type', $type) ?? [];
}
}