implement admin panel

This commit is contained in:
Meghdad committed 2026-07-22 17:22:33 +03:30
1 parent 56a52be180
commit e8223fbc3e
92 files changed
+5426 -9

No files matched your search

@@ -0,0 +1,78 @@
<?php
namespace App\Filament\Resources\LoanTypes;
use App\Filament\Resources\LoanTypes\Pages\CreateLoanType;
use App\Filament\Resources\LoanTypes\Pages\EditLoanType;
use App\Filament\Resources\LoanTypes\Pages\ListLoanTypes;
use App\Filament\Resources\LoanTypes\Pages\ViewLoanType;
use App\Filament\Resources\LoanTypes\RelationManagers\LoansRelationManager;
use App\Filament\Resources\LoanTypes\RelationManagers\WorkflowConfigurationsRelationManager;
use App\Filament\Resources\LoanTypes\Schemas\LoanTypeForm;
use App\Filament\Resources\LoanTypes\Schemas\LoanTypeInfolist;
use App\Filament\Resources\LoanTypes\Tables\LoanTypesTable;
use App\Models\LoanType;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use UnitEnum;
class LoanTypeResource extends Resource
{
protected static ?string $model = LoanType::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedBuildingLibrary;
protected static string|UnitEnum|null $navigationGroup = 'Configuration';
protected static ?string $navigationLabel = 'Loan types';
protected static ?string $recordTitleAttribute = 'name';
protected static ?int $navigationSort = 1;
public static function form(Schema $schema): Schema
{
return LoanTypeForm::configure($schema);
}
public static function infolist(Schema $schema): Schema
{
return LoanTypeInfolist::configure($schema);
}
public static function table(Table $table): Table
{
return LoanTypesTable::configure($table);
}
public static function getRelations(): array
{
return [
WorkflowConfigurationsRelationManager::class,
LoansRelationManager::class,
];
}
public static function getPages(): array
{
return [
'index' => ListLoanTypes::route('/'),
'create' => CreateLoanType::route('/create'),
'view' => ViewLoanType::route('/{record}'),
'edit' => EditLoanType::route('/{record}/edit'),
];
}
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()
->withCount(['loans', 'workflowConfigurations'])
->with(['workflowConfigurations' => fn ($query) => $query
->where('status', 'PUBLISHED')
->latest('version')]);
}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\LoanTypes\Pages;
use App\Filament\Resources\LoanTypes\LoanTypeResource;
use Filament\Resources\Pages\CreateRecord;
class CreateLoanType extends CreateRecord
{
protected static string $resource = LoanTypeResource::class;
}
@@ -0,0 +1,34 @@
<?php
namespace App\Filament\Resources\LoanTypes\Pages;
use App\Filament\Resources\LoanTypes\LoanTypeResource;
use Filament\Actions\ViewAction;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Validation\ValidationException;
class EditLoanType extends EditRecord
{
protected static string $resource = LoanTypeResource::class;
protected function getHeaderActions(): array
{
return [
ViewAction::make(),
];
}
protected function mutateFormDataBeforeSave(array $data): array
{
unset($data['code']);
if (($data['is_active'] ?? false)
&& ! $this->record->workflowConfigurations()->where('status', 'PUBLISHED')->exists()) {
throw ValidationException::withMessages([
'data.is_active' => 'Publish a workflow before activating this loan type.',
]);
}
return $data;
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Filament\Resources\LoanTypes\Pages;
use App\Filament\Resources\LoanTypes\LoanTypeResource;
use App\Models\LoanType;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Livewire\Attributes\Computed;
class ListLoanTypes extends ListRecords
{
protected static string $resource = LoanTypeResource::class;
protected string $view = 'filament.resources.loan-types.pages.list-loan-types';
#[Computed]
public function loanTypeCards(): Collection
{
return LoanType::query()
->withCount([
'loans',
'loans as open_loans_count' => fn (Builder $query): Builder => $query
->whereIn('status', ['SUBMITTED', 'IN_PROGRESS']),
])
->with(['workflowConfigurations' => fn ($query) => $query
->where('status', 'PUBLISHED')
->withCount('steps')
->latest('version')])
->orderByDesc('is_active')
->orderBy('name')
->get();
}
protected function getHeaderActions(): array
{
return [
CreateAction::make()
->label('New loan type')
->icon('heroicon-o-plus'),
];
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\LoanTypes\Pages;
use App\Filament\Resources\LoanTypes\LoanTypeResource;
use Filament\Actions\EditAction;
use Filament\Resources\Pages\ViewRecord;
class ViewLoanType extends ViewRecord
{
protected static string $resource = LoanTypeResource::class;
protected function getHeaderActions(): array
{
return [
EditAction::make(),
];
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\LoanTypes\RelationManagers;
use App\Filament\Resources\Loans\LoanResource;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables\Table;
class LoansRelationManager extends RelationManager
{
protected static string $relationship = 'loans';
protected static ?string $relatedResource = LoanResource::class;
public function table(Table $table): Table
{
return $table
->defaultSort('created_at', 'desc');
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\LoanTypes\RelationManagers;
use App\Filament\Resources\WorkflowConfigurations\WorkflowConfigurationResource;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables\Table;
class WorkflowConfigurationsRelationManager extends RelationManager
{
protected static string $relationship = 'workflowConfigurations';
protected static ?string $relatedResource = WorkflowConfigurationResource::class;
public function table(Table $table): Table
{
return $table
->defaultSort('version', 'desc');
}
}
@@ -0,0 +1,53 @@
<?php
namespace App\Filament\Resources\LoanTypes\Schemas;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Illuminate\Support\Str;
class LoanTypeForm
{
public static function configure(Schema $schema): Schema
{
return $schema
->components([
Section::make('Loan product identity')
->description('The code is a permanent API identifier. The display name can evolve with the product.')
->icon('heroicon-o-identification')
->schema([
TextInput::make('name')
->label('Display name')
->placeholder('e.g. Personal Flex Loan')
->required()
->maxLength(120)
->live(onBlur: true)
->afterStateUpdated(function (?string $state, callable $set, string $operation): void {
if ($operation === 'create') {
$set('code', Str::of($state ?? '')->trim()->upper()->snake()->toString());
}
}),
TextInput::make('code')
->label('Stable API code')
->helperText('Uppercase letters, numbers, and underscores only. It cannot be changed later.')
->required()
->maxLength(50)
->regex('/^[A-Z][A-Z0-9_]*$/')
->unique(ignoreRecord: true)
->disabledOn('edit')
->dehydrated(),
Toggle::make('is_active')
->label('Accept new applications')
->helperText('Existing applications and workflow history are never affected.')
->default(false)
->disabledOn('create')
->dehydrated()
->inline(false)
->required(),
])
->columns(2),
]);
}
}
@@ -0,0 +1,46 @@
<?php
namespace App\Filament\Resources\LoanTypes\Schemas;
use Filament\Infolists\Components\IconEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
class LoanTypeInfolist
{
public static function configure(Schema $schema): Schema
{
return $schema
->components([
Grid::make(3)
->schema([
Section::make('Product')
->icon('heroicon-o-building-library')
->schema([
TextEntry::make('name')->label('Display name'),
TextEntry::make('code')->badge()->color('gray'),
IconEntry::make('is_active')
->label('Accepting applications')
->boolean(),
])
->columnSpan(2),
Section::make('Portfolio')
->icon('heroicon-o-chart-bar')
->schema([
TextEntry::make('loans_count')
->label('Applications')
->numeric(),
TextEntry::make('workflow_configurations_count')
->label('Workflow versions')
->numeric(),
TextEntry::make('updated_at')
->label('Last changed')
->since()
->placeholder('Never'),
]),
]),
]);
}
}
@@ -0,0 +1,94 @@
<?php
namespace App\Filament\Resources\LoanTypes\Tables;
use App\Models\LoanType;
use Filament\Actions\Action;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Notifications\Notification;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Gate;
class LoanTypesTable
{
public static function configure(Table $table): Table
{
return $table
->columns([
TextColumn::make('code')
->badge()
->color('gray')
->searchable(),
TextColumn::make('name')
->description(fn (LoanType $record): string => $record->is_active ? 'Accepting new applications' : 'Paused for new applications')
->weight('semibold')
->searchable(),
TextColumn::make('loans_count')
->label('Applications')
->counts('loans')
->numeric()
->sortable()
->alignEnd(),
TextColumn::make('workflow_configurations_count')
->label('Versions')
->counts('workflowConfigurations')
->numeric()
->sortable()
->alignEnd(),
TextColumn::make('is_active')
->label('Availability')
->badge()
->formatStateUsing(fn (bool $state): string => $state ? 'Active' : 'Paused')
->color(fn (bool $state): string => $state ? 'success' : 'gray'),
TextColumn::make('updated_at')
->label('Updated')
->since()
->sortable(),
])
->filters([
TernaryFilter::make('is_active')
->label('Availability')
->trueLabel('Active products')
->falseLabel('Paused products'),
])
->defaultSort('updated_at', 'desc')
->recordActions([
ViewAction::make(),
EditAction::make(),
Action::make('toggleAvailability')
->label(fn (LoanType $record): string => $record->is_active ? 'Pause applications' : 'Resume applications')
->icon(fn (LoanType $record): string => $record->is_active ? 'heroicon-o-pause-circle' : 'heroicon-o-play-circle')
->color(fn (LoanType $record): string => $record->is_active ? 'warning' : 'success')
->requiresConfirmation()
->modalDescription(fn (LoanType $record): string => $record->is_active
? 'New applications will no longer be accepted for this loan type. Existing loans stay untouched.'
: 'New applications can be assigned to the currently published workflow again.')
->action(function (LoanType $record): void {
Gate::authorize('update', $record);
if (! $record->is_active && ! $record->workflowConfigurations()->where('status', 'PUBLISHED')->exists()) {
Notification::make()
->title('Publish a workflow first')
->body('This product cannot accept applications until it has a published workflow version.')
->danger()
->send();
return;
}
$record->update(['is_active' => ! $record->is_active]);
Notification::make()
->title($record->is_active ? 'Applications resumed' : 'Applications paused')
->success()
->send();
}),
])
->emptyStateHeading('Create your first loan product')
->emptyStateDescription('A loan type becomes ready after it has an active published workflow.')
->emptyStateIcon('heroicon-o-building-library');
}
}
@@ -0,0 +1,66 @@
<?php
namespace App\Filament\Resources\Loans;
use App\Filament\Resources\Loans\Pages\ListLoans;
use App\Filament\Resources\Loans\Pages\ViewLoan;
use App\Filament\Resources\Loans\RelationManagers\HistoriesRelationManager;
use App\Filament\Resources\Loans\Schemas\LoanInfolist;
use App\Filament\Resources\Loans\Tables\LoansTable;
use App\Models\Loan;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use UnitEnum;
class LoanResource extends Resource
{
protected static ?string $model = Loan::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedDocumentText;
protected static string|UnitEnum|null $navigationGroup = 'Operations';
protected static ?string $recordTitleAttribute = 'public_id';
protected static ?int $navigationSort = 1;
public static function infolist(Schema $schema): Schema
{
return LoanInfolist::configure($schema);
}
public static function table(Table $table): Table
{
return LoansTable::configure($table);
}
public static function getRelations(): array
{
return [
HistoriesRelationManager::class,
];
}
public static function getPages(): array
{
return [
'index' => ListLoans::route('/'),
'view' => ViewLoan::route('/{record}'),
];
}
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()
->withCount('histories')
->with([
'loanType:id,name,code',
'workflowConfiguration:id,name,version',
'currentStep.stageDefinition:id,name,code',
]);
}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\Loans\Pages;
use App\Filament\Resources\Loans\LoanResource;
use Filament\Resources\Pages\ListRecords;
class ListLoans extends ListRecords
{
protected static string $resource = LoanResource::class;
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\Loans\Pages;
use App\Filament\Resources\Loans\LoanResource;
use Filament\Resources\Pages\ViewRecord;
class ViewLoan extends ViewRecord
{
protected static string $resource = LoanResource::class;
}
@@ -0,0 +1,68 @@
<?php
namespace App\Filament\Resources\Loans\RelationManagers;
use App\Domain\Loan\Enums\StageResultType;
use Filament\Actions\ViewAction;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class HistoriesRelationManager extends RelationManager
{
protected static string $relationship = 'histories';
protected static ?string $title = 'Execution history';
public function infolist(Schema $schema): Schema
{
return $schema
->components([
TextEntry::make('stage_code')->label('Stage')->badge()->color('info'),
TextEntry::make('result')
->badge()
->color(fn (StageResultType $state): string => match ($state) {
StageResultType::Pass => 'success',
StageResultType::Fail => 'danger',
StageResultType::ManualReview => 'warning',
}),
TextEntry::make('reason'),
TextEntry::make('executed_at')->dateTime(),
TextEntry::make('rules_snapshot')
->label('Rule snapshot')
->formatStateUsing(fn (array $state): string => json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))
->fontFamily('mono')
->columnSpanFull(),
])
->columns(2);
}
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('stage_code')
->columns([
TextColumn::make('stage_code')
->label('Stage')
->badge()
->color('info'),
TextColumn::make('result')
->badge()
->color(fn (StageResultType $state): string => match ($state) {
StageResultType::Pass => 'success',
StageResultType::Fail => 'danger',
StageResultType::ManualReview => 'warning',
}),
TextColumn::make('reason')->wrap(),
TextColumn::make('executed_at')->label('Executed')->dateTime()->sortable(),
])
->defaultSort('executed_at')
->recordActions([
ViewAction::make(),
])
->emptyStateHeading('No stages executed yet')
->emptyStateIcon('heroicon-o-clock');
}
}
@@ -0,0 +1,65 @@
<?php
namespace App\Filament\Resources\Loans\Schemas;
use App\Domain\Loan\Enums\LoanStatus;
use Filament\Infolists\Components\IconEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
class LoanInfolist
{
public static function configure(Schema $schema): Schema
{
return $schema
->components([
Grid::make(3)
->schema([
Section::make('Application state')
->icon('heroicon-o-signal')
->schema([
TextEntry::make('public_id')->label('Loan ID')->copyable()->weight('semibold'),
TextEntry::make('status')
->badge()
->formatStateUsing(fn (LoanStatus $state): string => str($state->value)->headline()->toString())
->color(fn (LoanStatus $state): string => match ($state) {
LoanStatus::Submitted => 'gray',
LoanStatus::InProgress => 'info',
LoanStatus::ManualReview => 'warning',
LoanStatus::Approved => 'success',
LoanStatus::Rejected => 'danger',
}),
TextEntry::make('currentStep.stageDefinition.name')
->label('Current stage')
->placeholder('Processing complete'),
TextEntry::make('workflowConfiguration.name')
->label('Workflow')
->formatStateUsing(fn (string $state, $record): string => "{$state} · v{$record->workflowConfiguration->version}"),
])
->columns(2)
->columnSpan(2),
Section::make('Timeline')
->icon('heroicon-o-clock')
->schema([
TextEntry::make('created_at')->label('Submitted')->dateTime(),
TextEntry::make('updated_at')->label('Last activity')->since(),
TextEntry::make('histories_count')->label('Executed stages')->numeric(),
]),
]),
Section::make('Applicant and terms')
->icon('heroicon-o-user-circle')
->schema([
TextEntry::make('customer_id')->label('Customer ID')->copyable(),
TextEntry::make('phone')->copyable(),
TextEntry::make('loanType.name')->label('Loan type'),
TextEntry::make('amount')->numeric()->suffix(' IRR'),
TextEntry::make('monthly_income')->label('Monthly income')->numeric()->suffix(' IRR'),
TextEntry::make('credit_score')->label('Credit score')->numeric()->suffix(' / 1000'),
IconEntry::make('has_guarantor')->label('Has guarantor')->boolean(),
])
->columns(4),
]);
}
}
@@ -0,0 +1,85 @@
<?php
namespace App\Filament\Resources\Loans\Tables;
use App\Domain\Loan\Enums\LoanStatus;
use Filament\Actions\ViewAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
class LoansTable
{
public static function configure(Table $table): Table
{
return $table
->columns([
TextColumn::make('public_id')
->label('Loan ID')
->copyable()
->weight('semibold')
->searchable(),
TextColumn::make('customer_id')
->label('Customer')
->description(fn ($record): string => $record->phone)
->searchable(['customer_id', 'phone']),
TextColumn::make('loanType.name')
->label('Product')
->badge()
->color('gray')
->sortable(),
TextColumn::make('amount')
->numeric()
->suffix(' IRR')
->sortable()
->alignEnd(),
TextColumn::make('credit_score')
->label('Credit')
->numeric()
->suffix(' / 1000')
->sortable()
->alignEnd(),
TextColumn::make('status')
->badge()
->formatStateUsing(fn (LoanStatus $state): string => str($state->value)->headline()->toString())
->color(fn (LoanStatus $state): string => match ($state) {
LoanStatus::Submitted => 'gray',
LoanStatus::InProgress => 'info',
LoanStatus::ManualReview => 'warning',
LoanStatus::Approved => 'success',
LoanStatus::Rejected => 'danger',
}),
TextColumn::make('currentStep.stageDefinition.name')
->label('Current stage')
->placeholder('Complete')
->toggleable(),
TextColumn::make('created_at')
->label('Submitted')
->since()
->sortable(),
])
->filters([
SelectFilter::make('loan_type_id')
->label('Loan type')
->relationship('loanType', 'name')
->preload(),
SelectFilter::make('status')
->multiple()
->options(collect(LoanStatus::cases())
->mapWithKeys(fn (LoanStatus $status): array => [$status->value => str($status->value)->headline()->toString()])
->all()),
SelectFilter::make('workflow_configuration_id')
->label('Workflow version')
->relationship('workflowConfiguration', 'name')
->searchable()
->preload(),
])
->defaultSort('created_at', 'desc')
->recordActions([
ViewAction::make(),
])
->emptyStateHeading('No loan applications')
->emptyStateDescription('Applications submitted through the API will appear here.')
->emptyStateIcon('heroicon-o-document-text');
}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\StageDefinitions\Pages;
use App\Filament\Resources\StageDefinitions\StageDefinitionResource;
use Filament\Resources\Pages\CreateRecord;
class CreateStageDefinition extends CreateRecord
{
protected static string $resource = StageDefinitionResource::class;
}
@@ -0,0 +1,38 @@
<?php
namespace App\Filament\Resources\StageDefinitions\Pages;
use App\Domain\Loan\Enums\WorkflowConfigurationStatus;
use App\Filament\Resources\StageDefinitions\StageDefinitionResource;
use Filament\Actions\ViewAction;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Validation\ValidationException;
class EditStageDefinition extends EditRecord
{
protected static string $resource = StageDefinitionResource::class;
protected function getHeaderActions(): array
{
return [
ViewAction::make(),
];
}
protected function mutateFormDataBeforeSave(array $data): array
{
unset($data['code']);
if (! ($data['is_active'] ?? false)
&& $this->record->workflowConfigurationSteps()
->whereHas('workflowConfiguration', fn ($query) => $query
->where('status', WorkflowConfigurationStatus::Published))
->exists()) {
throw ValidationException::withMessages([
'data.is_active' => 'This stage is used by a published workflow and cannot be disabled.',
]);
}
return $data;
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\StageDefinitions\Pages;
use App\Filament\Resources\StageDefinitions\StageDefinitionResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListStageDefinitions extends ListRecords
{
protected static string $resource = StageDefinitionResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\StageDefinitions\Pages;
use App\Filament\Resources\StageDefinitions\StageDefinitionResource;
use Filament\Actions\EditAction;
use Filament\Resources\Pages\ViewRecord;
class ViewStageDefinition extends ViewRecord
{
protected static string $resource = StageDefinitionResource::class;
protected function getHeaderActions(): array
{
return [
EditAction::make(),
];
}
}
@@ -0,0 +1,43 @@
<?php
namespace App\Filament\Resources\StageDefinitions\Schemas;
use App\Domain\Loan\Enums\LoanStage;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
class StageDefinitionForm
{
public static function configure(Schema $schema): Schema
{
return $schema
->components([
Section::make('Trusted stage')
->description('Only application-registered stage codes can be exposed to workflow designers.')
->icon('heroicon-o-shield-check')
->schema([
Select::make('code')
->options(collect(LoanStage::cases())
->mapWithKeys(fn (LoanStage $stage): array => [$stage->value => str($stage->value)->headline()->toString()])
->all())
->required()
->unique(ignoreRecord: true)
->disabledOn('edit')
->dehydrated(),
TextInput::make('name')
->label('Admin-facing name')
->required()
->maxLength(120),
Toggle::make('is_active')
->label('Available in workflow designer')
->default(true)
->inline(false)
->required(),
])
->columns(2),
]);
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Filament\Resources\StageDefinitions\Schemas;
use Filament\Infolists\Components\IconEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Schemas\Schema;
class StageDefinitionInfolist
{
public static function configure(Schema $schema): Schema
{
return $schema
->components([
TextEntry::make('code'),
TextEntry::make('name'),
IconEntry::make('is_active')
->boolean(),
TextEntry::make('created_at')
->dateTime()
->placeholder('-'),
TextEntry::make('updated_at')
->dateTime()
->placeholder('-'),
]);
}
}
@@ -0,0 +1,65 @@
<?php
namespace App\Filament\Resources\StageDefinitions;
use App\Filament\Resources\StageDefinitions\Pages\CreateStageDefinition;
use App\Filament\Resources\StageDefinitions\Pages\EditStageDefinition;
use App\Filament\Resources\StageDefinitions\Pages\ListStageDefinitions;
use App\Filament\Resources\StageDefinitions\Pages\ViewStageDefinition;
use App\Filament\Resources\StageDefinitions\Schemas\StageDefinitionForm;
use App\Filament\Resources\StageDefinitions\Schemas\StageDefinitionInfolist;
use App\Filament\Resources\StageDefinitions\Tables\StageDefinitionsTable;
use App\Models\StageDefinition;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use UnitEnum;
class StageDefinitionResource extends Resource
{
protected static ?string $model = StageDefinition::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedSquaresPlus;
protected static string|UnitEnum|null $navigationGroup = 'Configuration';
protected static ?string $navigationLabel = 'Stage catalog';
protected static ?string $recordTitleAttribute = 'name';
protected static ?int $navigationSort = 3;
public static function form(Schema $schema): Schema
{
return StageDefinitionForm::configure($schema);
}
public static function infolist(Schema $schema): Schema
{
return StageDefinitionInfolist::configure($schema);
}
public static function table(Table $table): Table
{
return StageDefinitionsTable::configure($table);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => ListStageDefinitions::route('/'),
'create' => CreateStageDefinition::route('/create'),
'view' => ViewStageDefinition::route('/{record}'),
'edit' => EditStageDefinition::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,50 @@
<?php
namespace App\Filament\Resources\StageDefinitions\Tables;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class StageDefinitionsTable
{
public static function configure(Table $table): Table
{
return $table
->columns([
TextColumn::make('code')
->badge()
->color('info')
->searchable(),
TextColumn::make('name')
->weight('semibold')
->searchable(),
IconColumn::make('is_active')
->label('Available')
->boolean(),
TextColumn::make('workflow_configuration_steps_count')
->label('Workflow usage')
->counts('workflowConfigurationSteps')
->numeric()
->sortable(),
TextColumn::make('created_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('updated_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
//
])
->recordActions([
ViewAction::make(),
EditAction::make(),
])
->defaultSort('name');
}
}
@@ -0,0 +1,35 @@
<?php
namespace App\Filament\Resources\WorkflowConfigurations\Pages;
use App\Actions\WorkflowConfiguration\CreateWorkflowConfigurationAction;
use App\Filament\Resources\WorkflowConfigurations\WorkflowConfigurationResource;
use App\Models\LoanType;
use App\Models\User;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Database\Eloquent\Model;
class CreateWorkflowConfiguration extends CreateRecord
{
protected static string $resource = WorkflowConfigurationResource::class;
private CreateWorkflowConfigurationAction $createWorkflowConfiguration;
public function boot(CreateWorkflowConfigurationAction $createWorkflowConfiguration): void
{
$this->createWorkflowConfiguration = $createWorkflowConfiguration;
}
protected function handleRecordCreation(array $data): Model
{
$user = auth()->user();
abort_unless($user instanceof User, 403);
return $this->createWorkflowConfiguration->handle(
LoanType::query()->findOrFail($data['loan_type_id']),
$data['name'],
$user,
$data['steps'],
);
}
}
@@ -0,0 +1,75 @@
<?php
namespace App\Filament\Resources\WorkflowConfigurations\Pages;
use App\Actions\WorkflowConfiguration\PublishWorkflowConfigurationAction;
use App\Actions\WorkflowConfiguration\UpdateWorkflowConfigurationAction;
use App\Filament\Resources\WorkflowConfigurations\WorkflowConfigurationResource;
use App\Models\User;
use App\Models\WorkflowConfiguration;
use Filament\Actions\Action;
use Filament\Actions\ViewAction;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;
class EditWorkflowConfiguration extends EditRecord
{
protected static string $resource = WorkflowConfigurationResource::class;
private UpdateWorkflowConfigurationAction $updateWorkflowConfiguration;
private PublishWorkflowConfigurationAction $publishWorkflowConfiguration;
public function boot(
UpdateWorkflowConfigurationAction $updateWorkflowConfiguration,
PublishWorkflowConfigurationAction $publishWorkflowConfiguration,
): void {
$this->updateWorkflowConfiguration = $updateWorkflowConfiguration;
$this->publishWorkflowConfiguration = $publishWorkflowConfiguration;
}
protected function mutateFormDataBeforeFill(array $data): array
{
/** @var WorkflowConfiguration $record */
$record = $this->record;
$data['steps'] = $record->steps()
->get(['stage_definition_id', 'rules', 'is_enabled'])
->map(fn ($step): array => [
'stage_definition_id' => $step->stage_definition_id,
'rules' => $step->rules,
'is_enabled' => $step->is_enabled,
])
->all();
return $data;
}
protected function handleRecordUpdate(Model $record, array $data): Model
{
/** @var WorkflowConfiguration $record */
return $this->updateWorkflowConfiguration->handle($record, $data['name'], $data['steps']);
}
protected function getHeaderActions(): array
{
return [
ViewAction::make(),
Action::make('publish')
->icon('heroicon-o-rocket-launch')
->color('success')
->requiresConfirmation()
->modalDescription('This archives the currently published version. Existing loans remain attached to their original workflow.')
->action(function () {
$user = auth()->user();
abort_unless($user instanceof User, 403);
$published = $this->publishWorkflowConfiguration->handle($this->record, $user);
Notification::make()->title('Workflow published')->success()->send();
return redirect(WorkflowConfigurationResource::getUrl('view', ['record' => $published]));
}),
];
}
}
@@ -0,0 +1,38 @@
<?php
namespace App\Filament\Resources\WorkflowConfigurations\Pages;
use App\Domain\Loan\Enums\WorkflowConfigurationStatus;
use App\Filament\Resources\WorkflowConfigurations\WorkflowConfigurationResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
use Filament\Schemas\Components\Tabs\Tab;
use Illuminate\Database\Eloquent\Builder;
class ListWorkflowConfigurations extends ListRecords
{
protected static string $resource = WorkflowConfigurationResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()->label('New workflow draft')->icon('heroicon-o-plus'),
];
}
public function getTabs(): array
{
return [
'all' => Tab::make('All versions'),
'draft' => Tab::make('Drafts')
->icon('heroicon-o-pencil-square')
->modifyQueryUsing(fn (Builder $query): Builder => $query->where('status', WorkflowConfigurationStatus::Draft)),
'published' => Tab::make('Published')
->icon('heroicon-o-check-badge')
->modifyQueryUsing(fn (Builder $query): Builder => $query->where('status', WorkflowConfigurationStatus::Published)),
'archived' => Tab::make('Archive')
->icon('heroicon-o-archive-box')
->modifyQueryUsing(fn (Builder $query): Builder => $query->where('status', WorkflowConfigurationStatus::Archived)),
];
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Filament\Resources\WorkflowConfigurations\Pages;
use App\Actions\WorkflowConfiguration\PublishWorkflowConfigurationAction;
use App\Filament\Resources\WorkflowConfigurations\WorkflowConfigurationResource;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Actions\EditAction;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;
class ViewWorkflowConfiguration extends ViewRecord
{
protected static string $resource = WorkflowConfigurationResource::class;
private PublishWorkflowConfigurationAction $publishWorkflowConfiguration;
public function boot(PublishWorkflowConfigurationAction $publishWorkflowConfiguration): void
{
$this->publishWorkflowConfiguration = $publishWorkflowConfiguration;
}
protected function getHeaderActions(): array
{
return [
EditAction::make()->visible(fn (): bool => $this->record->isEditable()),
Action::make('publish')
->icon('heroicon-o-rocket-launch')
->color('success')
->visible(fn (): bool => $this->record->isEditable())
->requiresConfirmation()
->action(function (): void {
$user = auth()->user();
abort_unless($user instanceof User, 403);
$this->record = $this->publishWorkflowConfiguration->handle($this->record, $user);
Notification::make()->title('Workflow published')->success()->send();
}),
];
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Filament\Resources\WorkflowConfigurations\RelationManagers;
use App\Filament\Resources\Loans\LoanResource;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables\Table;
class LoansRelationManager extends RelationManager
{
protected static string $relationship = 'loans';
protected static ?string $relatedResource = LoanResource::class;
public function table(Table $table): Table
{
return $table
->defaultSort('created_at', 'desc');
}
}
@@ -0,0 +1,203 @@
<?php
namespace App\Filament\Resources\WorkflowConfigurations\Schemas;
use App\Domain\Loan\Enums\LoanStage;
use App\Models\StageDefinition;
use App\Models\WorkflowConfiguration;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Illuminate\Support\Number;
class WorkflowConfigurationForm
{
public static function configure(Schema $schema): Schema
{
return $schema
->components([
Section::make('Workflow identity')
->description('Drafts are isolated versions. Publishing never changes loans already assigned to an older version.')
->icon('heroicon-o-finger-print')
->schema([
Select::make('loan_type_id')
->label('Loan type')
->relationship('loanType', 'name')
->searchable()
->preload()
->required()
->disabled(fn (?WorkflowConfiguration $record): bool => $record !== null)
->dehydrated(),
TextInput::make('name')
->placeholder('e.g. Personal lending — summer policy')
->required()
->maxLength(150),
Placeholder::make('version_summary')
->label('Version')
->content(fn (?WorkflowConfiguration $record): string => $record === null
? 'Assigned automatically when the draft is created'
: "Version {$record->version} · {$record->status->value}"),
])
->columns(3),
Section::make('Execution path')
->description('Drag stages into execution order. Rule fields change with the selected stage.')
->icon('heroicon-o-arrows-right-left')
->schema([
Repeater::make('steps')
->hiddenLabel()
->schema([
Select::make('stage_definition_id')
->label('Stage')
->options(fn (): array => StageDefinition::query()
->where('is_active', true)
->orderBy('name')
->pluck('name', 'id')
->all())
->searchable()
->required()
->distinct()
->disableOptionsWhenSelectedInSiblingRepeaterItems()
->live()
->afterStateUpdated(function (Set $set, mixed $state): void {
$stageCode = StageDefinition::query()->whereKey($state)->value('code');
$set('rules', self::defaultRules($stageCode));
}),
Toggle::make('is_enabled')
->label('Enabled')
->default(true)
->inline(false),
Grid::make(4)
->schema(fn (Get $get): array => self::ruleFields(
StageDefinition::query()->whereKey($get('stage_definition_id'))->value('code'),
))
->key('stageRules')
->columnSpanFull(),
])
->columns(2)
->itemLabel(fn (array $state): string => StageDefinition::query()
->whereKey($state['stage_definition_id'] ?? null)
->value('name') ?? 'Choose a stage')
->addActionLabel('Add workflow stage')
->reorderable()
->collapsible()
->minItems(1)
->required(),
]),
]);
}
/**
* @return array<int, TextInput|Toggle|Placeholder>
*/
private static function ruleFields(?string $stageCode): array
{
return match ($stageCode) {
LoanStage::FraudCheck->value => [
TextInput::make('rules.fraudPrefix')
->label('Reject prefix')
->required()
->maxLength(50),
TextInput::make('rules.manualReviewPrefix')
->label('Manual-review prefix')
->required()
->maxLength(50),
],
LoanStage::GuarantorCheck->value => [
Toggle::make('rules.guarantorRequired')
->label('Guarantor required')
->default(true)
->inline(false),
],
LoanStage::CreditCheck->value => [
TextInput::make('rules.rejectBelow')
->label('Reject below')
->numeric()
->minValue(0)
->maxValue(1000)
->required(),
TextInput::make('rules.manualReviewMin')
->label('Review from')
->numeric()
->minValue(0)
->maxValue(1000)
->required(),
TextInput::make('rules.manualReviewMax')
->label('Review through')
->numeric()
->minValue(0)
->maxValue(1000)
->required(),
TextInput::make('rules.approveFrom')
->label('Approve from')
->numeric()
->minValue(0)
->maxValue(1000)
->required(),
],
LoanStage::ManagerApproval->value => [
TextInput::make('rules.activationThreshold')
->label('Activation threshold')
->helperText('Manager approval is skipped at or below this amount.')
->numeric()
->minValue(0)
->prefix('IRR')
->formatStateUsing(fn (mixed $state): mixed => $state)
->required()
->columnSpan(2),
TextInput::make('rules.incomeMultiplier')
->label('Income multiplier')
->numeric()
->minValue(1)
->suffix('×')
->required(),
Placeholder::make('threshold_preview')
->label('Default policy')
->content(fn (Get $get): string => Number::format((int) ($get('rules.activationThreshold') ?? 0)).' IRR'),
],
LoanStage::Validation->value => [
Placeholder::make('validation_policy')
->label('Built-in validation')
->content('Transport-safe values are checked against the BankFlow validation policy.')
->columnSpanFull(),
],
default => [
Placeholder::make('choose_stage')
->label('Stage rules')
->content('Choose a stage to configure its policy.')
->columnSpanFull(),
],
};
}
/**
* @return array<string, mixed>
*/
private static function defaultRules(?string $stageCode): array
{
return match ($stageCode) {
LoanStage::FraudCheck->value => [
'fraudPrefix' => 'FRAUD',
'manualReviewPrefix' => 'REVIEW',
],
LoanStage::GuarantorCheck->value => ['guarantorRequired' => true],
LoanStage::CreditCheck->value => [
'rejectBelow' => 500,
'manualReviewMin' => 500,
'manualReviewMax' => 649,
'approveFrom' => 650,
],
LoanStage::ManagerApproval->value => [
'activationThreshold' => 500_000_000,
'incomeMultiplier' => 20,
],
default => [],
};
}
}
@@ -0,0 +1,69 @@
<?php
namespace App\Filament\Resources\WorkflowConfigurations\Schemas;
use App\Domain\Loan\Enums\WorkflowConfigurationStatus;
use Filament\Infolists\Components\IconEntry;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Components\TextEntry;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
class WorkflowConfigurationInfolist
{
public static function configure(Schema $schema): Schema
{
return $schema
->components([
Grid::make(3)
->schema([
Section::make('Workflow')
->icon('heroicon-o-queue-list')
->schema([
TextEntry::make('name')->weight('semibold'),
TextEntry::make('loanType.name')->label('Loan type'),
TextEntry::make('version')->badge()->prefix('Version '),
TextEntry::make('status')
->badge()
->formatStateUsing(fn (WorkflowConfigurationStatus $state): string => str($state->value)->headline()->toString())
->color(fn (WorkflowConfigurationStatus $state): string => match ($state) {
WorkflowConfigurationStatus::Draft => 'warning',
WorkflowConfigurationStatus::Published => 'success',
WorkflowConfigurationStatus::Archived => 'gray',
}),
])
->columns(2)
->columnSpan(2),
Section::make('Audit')
->icon('heroicon-o-clock')
->schema([
TextEntry::make('creator.name')->label('Created by')->placeholder('System'),
TextEntry::make('published_at')->dateTime()->placeholder('Not published'),
TextEntry::make('loans_count')->label('Assigned loans')->numeric(),
]),
]),
Section::make('Execution path')
->description('The rule snapshot shown here is the policy attached to this exact version.')
->icon('heroicon-o-arrows-right-left')
->schema([
RepeatableEntry::make('steps')
->hiddenLabel()
->schema([
TextEntry::make('position')->label('#')->badge()->color('gray'),
TextEntry::make('stageDefinition.name')->label('Stage')->weight('semibold'),
TextEntry::make('stageDefinition.code')->label('Code')->badge()->color('info'),
IconEntry::make('is_enabled')->label('Enabled')->boolean(),
TextEntry::make('rules')
->label('Rules')
->formatStateUsing(fn (array $state): string => collect($state)
->map(fn (mixed $value, string $key): string => str($key)->headline().': '.(is_bool($value) ? ($value ? 'Yes' : 'No') : $value))
->implode(' · '))
->placeholder('No configurable rules')
->columnSpanFull(),
])
->columns(4),
]),
]);
}
}
@@ -0,0 +1,130 @@
<?php
namespace App\Filament\Resources\WorkflowConfigurations\Tables;
use App\Actions\WorkflowConfiguration\CreateWorkflowConfigurationAction;
use App\Actions\WorkflowConfiguration\PublishWorkflowConfigurationAction;
use App\Domain\Loan\Enums\WorkflowConfigurationStatus;
use App\Filament\Resources\WorkflowConfigurations\WorkflowConfigurationResource;
use App\Models\User;
use App\Models\WorkflowConfiguration;
use Filament\Actions\Action;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
class WorkflowConfigurationsTable
{
public static function configure(Table $table): Table
{
return $table
->columns([
TextColumn::make('loanType.name')
->label('Loan type')
->icon('heroicon-o-building-library')
->searchable()
->sortable(),
TextColumn::make('name')
->weight('semibold')
->searchable(),
TextColumn::make('version')
->badge()
->prefix('v')
->color('gray')
->sortable(),
TextColumn::make('status')
->badge()
->formatStateUsing(fn (WorkflowConfigurationStatus $state): string => str($state->value)->headline()->toString())
->color(fn (WorkflowConfigurationStatus $state): string => match ($state) {
WorkflowConfigurationStatus::Draft => 'warning',
WorkflowConfigurationStatus::Published => 'success',
WorkflowConfigurationStatus::Archived => 'gray',
}),
TextColumn::make('steps_count')
->label('Stages')
->counts('steps')
->numeric()
->alignEnd(),
TextColumn::make('loans_count')
->label('Assigned')
->counts('loans')
->numeric()
->alignEnd(),
TextColumn::make('published_at')
->label('Published')
->since()
->placeholder('Not yet')
->sortable(),
])
->filters([
SelectFilter::make('loan_type_id')
->label('Loan type')
->relationship('loanType', 'name')
->preload(),
SelectFilter::make('status')
->options(collect(WorkflowConfigurationStatus::cases())
->mapWithKeys(fn (WorkflowConfigurationStatus $status): array => [$status->value => str($status->value)->headline()->toString()])
->all()),
])
->defaultSort('version', 'desc')
->recordActions([
ViewAction::make(),
EditAction::make()->visible(fn (WorkflowConfiguration $record): bool => $record->isEditable()),
Action::make('copy')
->label('Copy as draft')
->icon('heroicon-o-document-duplicate')
->color('gray')
->schema([
TextInput::make('name')
->label('New draft name')
->required()
->maxLength(150),
])
->fillForm(fn (WorkflowConfiguration $record): array => ['name' => "{$record->name} copy"])
->action(function (
array $data,
WorkflowConfiguration $record,
CreateWorkflowConfigurationAction $createWorkflowConfiguration,
) {
$user = auth()->user();
abort_unless($user instanceof User, 403);
$draft = $createWorkflowConfiguration->handle(
$record->loanType,
$data['name'],
$user,
copyFrom: $record,
);
Notification::make()->title('Draft copy created')->success()->send();
return redirect(WorkflowConfigurationResource::getUrl('edit', ['record' => $draft]));
}),
Action::make('publish')
->icon('heroicon-o-rocket-launch')
->color('success')
->visible(fn (WorkflowConfiguration $record): bool => $record->isEditable())
->requiresConfirmation()
->modalHeading('Publish this workflow version?')
->modalDescription('The currently published workflow for this loan type will be archived. Existing loans keep their assigned version.')
->action(function (
WorkflowConfiguration $record,
PublishWorkflowConfigurationAction $publishWorkflowConfiguration,
): void {
$user = auth()->user();
abort_unless($user instanceof User, 403);
$publishWorkflowConfiguration->handle($record, $user);
Notification::make()->title('Workflow published')->success()->send();
}),
])
->emptyStateHeading('No workflow versions yet')
->emptyStateDescription('Create a draft, arrange its stages, then publish it for new applications.')
->emptyStateIcon('heroicon-o-queue-list');
}
}
@@ -0,0 +1,74 @@
<?php
namespace App\Filament\Resources\WorkflowConfigurations;
use App\Filament\Resources\WorkflowConfigurations\Pages\CreateWorkflowConfiguration;
use App\Filament\Resources\WorkflowConfigurations\Pages\EditWorkflowConfiguration;
use App\Filament\Resources\WorkflowConfigurations\Pages\ListWorkflowConfigurations;
use App\Filament\Resources\WorkflowConfigurations\Pages\ViewWorkflowConfiguration;
use App\Filament\Resources\WorkflowConfigurations\RelationManagers\LoansRelationManager;
use App\Filament\Resources\WorkflowConfigurations\Schemas\WorkflowConfigurationForm;
use App\Filament\Resources\WorkflowConfigurations\Schemas\WorkflowConfigurationInfolist;
use App\Filament\Resources\WorkflowConfigurations\Tables\WorkflowConfigurationsTable;
use App\Models\WorkflowConfiguration;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use UnitEnum;
class WorkflowConfigurationResource extends Resource
{
protected static ?string $model = WorkflowConfiguration::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedQueueList;
protected static string|UnitEnum|null $navigationGroup = 'Configuration';
protected static ?string $navigationLabel = 'Workflows';
protected static ?string $recordTitleAttribute = 'name';
protected static ?int $navigationSort = 2;
public static function form(Schema $schema): Schema
{
return WorkflowConfigurationForm::configure($schema);
}
public static function infolist(Schema $schema): Schema
{
return WorkflowConfigurationInfolist::configure($schema);
}
public static function table(Table $table): Table
{
return WorkflowConfigurationsTable::configure($table);
}
public static function getRelations(): array
{
return [
LoansRelationManager::class,
];
}
public static function getPages(): array
{
return [
'index' => ListWorkflowConfigurations::route('/'),
'create' => CreateWorkflowConfiguration::route('/create'),
'view' => ViewWorkflowConfiguration::route('/{record}'),
'edit' => EditWorkflowConfiguration::route('/{record}/edit'),
];
}
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()
->with(['loanType', 'creator'])
->withCount(['steps', 'loans']);
}
}