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,62 @@
<?php
namespace App\Actions\WorkflowConfiguration;
use App\Domain\Loan\Enums\WorkflowConfigurationStatus;
use App\Models\LoanType;
use App\Models\User;
use App\Models\WorkflowConfiguration;
use Illuminate\Support\Facades\DB;
class CreateWorkflowConfigurationAction
{
public function __construct(private ValidateWorkflowStepDataAction $validateWorkflowStepData) {}
/**
* @param array<int, array{stage_definition_id: int, rules?: array<string, mixed>, is_enabled?: bool}> $steps
*/
public function handle(
LoanType $loanType,
string $name,
User $creator,
array $steps = [],
?WorkflowConfiguration $copyFrom = null,
): WorkflowConfiguration {
return DB::transaction(function () use ($loanType, $name, $creator, $steps, $copyFrom): WorkflowConfiguration {
$lockedLoanType = LoanType::query()->lockForUpdate()->findOrFail($loanType->getKey());
$nextVersion = ((int) $lockedLoanType->workflowConfigurations()->max('version')) + 1;
$workflowConfiguration = $lockedLoanType->workflowConfigurations()->create([
'name' => $name,
'version' => $nextVersion,
'status' => WorkflowConfigurationStatus::Draft,
'created_by' => $creator->getKey(),
]);
$stepsToCreate = $copyFrom === null
? $steps
: $copyFrom->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();
$validatedSteps = $this->validateWorkflowStepData->handle($stepsToCreate);
foreach ($validatedSteps as $index => $step) {
$workflowConfiguration->steps()->create([
'stage_definition_id' => $step['stage_definition_id'],
'position' => $index + 1,
'rules' => $step['rules'] ?? [],
'is_enabled' => $step['is_enabled'] ?? true,
]);
}
return $workflowConfiguration->load(['loanType', 'steps.stageDefinition', 'creator']);
});
}
}
@@ -0,0 +1,46 @@
<?php
namespace App\Actions\WorkflowConfiguration;
use App\Domain\Loan\Enums\WorkflowConfigurationStatus;
use App\Models\User;
use App\Models\WorkflowConfiguration;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class PublishWorkflowConfigurationAction
{
public function __construct(private ValidateWorkflowConfigurationAction $validateWorkflowConfiguration) {}
public function handle(WorkflowConfiguration $workflowConfiguration, User $publisher): WorkflowConfiguration
{
return DB::transaction(function () use ($workflowConfiguration, $publisher): WorkflowConfiguration {
$lockedConfiguration = WorkflowConfiguration::query()
->with(['loanType', 'steps.stageDefinition'])
->lockForUpdate()
->findOrFail($workflowConfiguration->getKey());
if (! $lockedConfiguration->isEditable()) {
throw ValidationException::withMessages([
'status' => 'Only a draft workflow configuration can be published.',
]);
}
$this->validateWorkflowConfiguration->handle($lockedConfiguration);
WorkflowConfiguration::query()
->whereBelongsTo($lockedConfiguration->loanType)
->where('status', WorkflowConfigurationStatus::Published)
->lockForUpdate()
->update(['status' => WorkflowConfigurationStatus::Archived]);
$lockedConfiguration->update([
'status' => WorkflowConfigurationStatus::Published,
'published_at' => now(),
'created_by' => $publisher->getKey(),
]);
return $lockedConfiguration->refresh()->load(['loanType', 'steps.stageDefinition', 'creator']);
});
}
}
@@ -0,0 +1,46 @@
<?php
namespace App\Actions\WorkflowConfiguration;
use App\Models\WorkflowConfiguration;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class UpdateWorkflowConfigurationAction
{
public function __construct(private ValidateWorkflowStepDataAction $validateWorkflowStepData) {}
/**
* @param array<int, array{stage_definition_id: int, rules?: array<string, mixed>, is_enabled?: bool}> $steps
*/
public function handle(WorkflowConfiguration $workflowConfiguration, string $name, array $steps): WorkflowConfiguration
{
$validatedSteps = $this->validateWorkflowStepData->handle($steps);
return DB::transaction(function () use ($workflowConfiguration, $name, $validatedSteps): WorkflowConfiguration {
$lockedConfiguration = WorkflowConfiguration::query()
->lockForUpdate()
->findOrFail($workflowConfiguration->getKey());
if (! $lockedConfiguration->isEditable()) {
throw ValidationException::withMessages([
'status' => 'Only draft workflow configurations can be changed.',
]);
}
$lockedConfiguration->update(['name' => $name]);
$lockedConfiguration->steps()->delete();
foreach ($validatedSteps as $index => $step) {
$lockedConfiguration->steps()->create([
'stage_definition_id' => $step['stage_definition_id'],
'position' => $index + 1,
'rules' => $step['rules'] ?? [],
'is_enabled' => $step['is_enabled'] ?? true,
]);
}
return $lockedConfiguration->load(['loanType', 'steps.stageDefinition', 'creator']);
});
}
}
@@ -0,0 +1,63 @@
<?php
namespace App\Actions\WorkflowConfiguration;
use App\Domain\Loan\Enums\LoanStage;
use App\Models\WorkflowConfiguration;
use Illuminate\Validation\ValidationException;
class ValidateWorkflowConfigurationAction
{
public function __construct(private ValidateWorkflowStepDataAction $validateWorkflowStepData) {}
public function handle(WorkflowConfiguration $workflowConfiguration): void
{
$workflowConfiguration->loadMissing(['loanType', 'steps.stageDefinition']);
$enabledSteps = $workflowConfiguration->steps
->where('is_enabled', true)
->values();
$stepData = $enabledSteps
->map(fn ($step): array => [
'stage_definition_id' => $step->stage_definition_id,
'rules' => $step->rules,
'is_enabled' => true,
])
->all();
$this->validateWorkflowStepData->handle($stepData);
$enabledCodes = $enabledSteps->pluck('stageDefinition.code')->all();
$errors = [];
foreach ($this->requiredStageCodes($workflowConfiguration->loanType->code) as $requiredStageCode) {
if (! in_array($requiredStageCode, $enabledCodes, true)) {
$errors['steps'] = "The {$requiredStageCode} stage is required for {$workflowConfiguration->loanType->name}.";
}
}
if ($errors !== []) {
throw ValidationException::withMessages($errors);
}
}
/**
* @return list<string>
*/
private function requiredStageCodes(string $loanTypeCode): array
{
$required = [
LoanStage::Validation->value,
LoanStage::FraudCheck->value,
LoanStage::CreditCheck->value,
LoanStage::ManagerApproval->value,
];
if ($loanTypeCode === 'BUSINESS') {
$required[] = LoanStage::GuarantorCheck->value;
}
return $required;
}
}
@@ -0,0 +1,115 @@
<?php
namespace App\Actions\WorkflowConfiguration;
use App\Domain\Loan\Enums\LoanStage;
use App\Models\StageDefinition;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
class ValidateWorkflowStepDataAction
{
/**
* @param array<int, array{stage_definition_id: int, rules?: array<string, mixed>, is_enabled?: bool}> $steps
* @return array<int, array{stage_definition_id: int, rules: array<string, mixed>, is_enabled: bool}>
*/
public function handle(array $steps): array
{
$validatedSteps = Validator::make(['steps' => $steps], [
'steps' => ['required', 'array', 'min:1'],
'steps.*.stage_definition_id' => ['required', 'integer', 'distinct', 'exists:stage_definitions,id'],
'steps.*.rules' => ['present', 'array'],
'steps.*.is_enabled' => ['required', 'boolean'],
])->validate()['steps'];
$stageDefinitions = StageDefinition::query()
->whereKey(collect($validatedSteps)->pluck('stage_definition_id'))
->get()
->keyBy('id');
$registeredStageCodes = collect(LoanStage::cases())->pluck('value')->all();
$errors = [];
foreach ($validatedSteps as $index => $step) {
$stageDefinition = $stageDefinitions[$step['stage_definition_id']];
if (! $stageDefinition->is_active) {
$errors["steps.{$index}.stage_definition_id"] = "{$stageDefinition->code} is inactive.";
}
if (! in_array($stageDefinition->code, $registeredStageCodes, true)) {
$errors["steps.{$index}.stage_definition_id"] = "{$stageDefinition->code} is not registered by the application.";
}
$rulesValidator = Validator::make($step['rules'], $this->rulesFor($stageDefinition->code));
foreach ($rulesValidator->errors()->toArray() as $field => $messages) {
$errors["steps.{$index}.rules.{$field}"] = Arr::first($messages);
}
$this->validateCreditRanges($stageDefinition->code, $step['rules'], $index, $errors);
}
if ($errors !== []) {
throw ValidationException::withMessages($errors);
}
return array_map(fn (array $step): array => [
'stage_definition_id' => $step['stage_definition_id'],
'rules' => $step['rules'],
'is_enabled' => $step['is_enabled'],
], $validatedSteps);
}
/**
* @return array<string, list<string>>
*/
private function rulesFor(string $stageCode): array
{
return match ($stageCode) {
LoanStage::FraudCheck->value => [
'fraudPrefix' => ['required', 'string', 'max:50'],
'manualReviewPrefix' => ['required', 'string', 'max:50', 'different:fraudPrefix'],
],
LoanStage::GuarantorCheck->value => [
'guarantorRequired' => ['required', 'boolean'],
],
LoanStage::CreditCheck->value => [
'rejectBelow' => ['required', 'integer', 'between:0,1000'],
'manualReviewMin' => ['required', 'integer', 'between:0,1000'],
'manualReviewMax' => ['required', 'integer', 'between:0,1000'],
'approveFrom' => ['required', 'integer', 'between:0,1000'],
],
LoanStage::ManagerApproval->value => [
'activationThreshold' => ['required', 'integer', 'min:0'],
'incomeMultiplier' => ['required', 'integer', 'min:1'],
],
default => [],
};
}
/**
* @param array<string, mixed> $rules
* @param array<string, string|null> $errors
*/
private function validateCreditRanges(string $stageCode, array $rules, int $index, array &$errors): void
{
if ($stageCode !== LoanStage::CreditCheck->value
|| ! isset($rules['rejectBelow'], $rules['manualReviewMin'], $rules['manualReviewMax'], $rules['approveFrom'])) {
return;
}
if ($rules['rejectBelow'] !== $rules['manualReviewMin']) {
$errors["steps.{$index}.rules.rejectBelow"] = 'The rejection boundary must meet the manual-review minimum without a gap.';
}
if ($rules['manualReviewMin'] > $rules['manualReviewMax']) {
$errors["steps.{$index}.rules.manualReviewMax"] = 'The manual-review maximum must be at least its minimum.';
}
if ($rules['approveFrom'] !== $rules['manualReviewMax'] + 1) {
$errors["steps.{$index}.rules.approveFrom"] = 'The approval boundary must immediately follow the manual-review range.';
}
}
}
@@ -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']);
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Filament\Widgets;
use App\Domain\Loan\Enums\LoanStatus;
use App\Domain\Loan\Enums\WorkflowConfigurationStatus;
use App\Filament\Resources\Loans\LoanResource;
use App\Filament\Resources\WorkflowConfigurations\WorkflowConfigurationResource;
use App\Models\Loan;
use App\Models\WorkflowConfiguration;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Number;
class BankFlowStats extends StatsOverviewWidget
{
protected ?string $heading = 'Lending operations';
protected ?string $description = 'A live view of application throughput and workflow readiness.';
protected static bool $isLazy = false;
protected function getStats(): array
{
$totalLoans = Loan::query()->count();
$openLoans = Loan::query()->whereIn('status', [LoanStatus::Submitted, LoanStatus::InProgress])->count();
$manualReviewLoans = Loan::query()->where('status', LoanStatus::ManualReview)->count();
$publishedWorkflows = WorkflowConfiguration::query()
->where('status', WorkflowConfigurationStatus::Published)
->count();
return [
Stat::make('Total applications', Number::format($totalLoans))
->description('Complete lending portfolio')
->descriptionIcon('heroicon-m-document-text')
->color('primary')
->url(LoanResource::getUrl()),
Stat::make('Open processing', Number::format($openLoans))
->description($openLoans === 0 ? 'Processing queue is clear' : 'Submitted or in progress')
->descriptionIcon($openLoans === 0 ? 'heroicon-m-check-circle' : 'heroicon-m-arrow-path')
->color($openLoans === 0 ? 'success' : 'info')
->url(LoanResource::getUrl()),
Stat::make('Manual review', Number::format($manualReviewLoans))
->description($manualReviewLoans === 0 ? 'No applications waiting' : 'Requires operational attention')
->descriptionIcon($manualReviewLoans === 0 ? 'heroicon-m-check-circle' : 'heroicon-m-exclamation-triangle')
->color($manualReviewLoans === 0 ? 'success' : 'warning')
->url(LoanResource::getUrl()),
Stat::make('Published workflows', Number::format($publishedWorkflows))
->description('Active version assignments')
->descriptionIcon('heroicon-m-rocket-launch')
->color('success')
->url(WorkflowConfigurationResource::getUrl()),
];
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace App\Filament\Widgets;
use App\Domain\Loan\Enums\LoanStatus;
use App\Models\Loan;
use Filament\Widgets\ChartWidget;
class LoanStatusChart extends ChartWidget
{
protected ?string $heading = 'Portfolio by status';
protected ?string $description = 'Distribution across the automatic processing lifecycle.';
protected static bool $isLazy = false;
protected int|string|array $columnSpan = 1;
protected function getData(): array
{
$counts = Loan::query()
->select('status')
->selectRaw('COUNT(*) AS aggregate')
->groupBy('status')
->pluck('aggregate', 'status');
$statuses = LoanStatus::cases();
return [
'datasets' => [[
'label' => 'Loans',
'data' => array_map(fn (LoanStatus $status): int => (int) $counts->get($status->value, 0), $statuses),
'backgroundColor' => ['#94a3b8', '#38bdf8', '#f59e0b', '#10b981', '#ef4444'],
'borderWidth' => 0,
]],
'labels' => array_map(fn (LoanStatus $status): string => str($status->value)->headline()->toString(), $statuses),
];
}
protected function getType(): string
{
return 'doughnut';
}
}
+8 -1
View File
@@ -4,6 +4,8 @@ namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Database\Factories\UserFactory;
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -12,11 +14,16 @@ use Illuminate\Notifications\Notifiable;
#[Fillable(['name', 'email', 'password'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable
class User extends Authenticatable implements FilamentUser
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable;
public function canAccessPanel(Panel $panel): bool
{
return $panel->getId() === 'admin' && $this->hasVerifiedEmail();
}
/**
* Get the attributes that should be cast.
*
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Policies;
use App\Models\Loan;
use App\Models\User;
class LoanPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, Loan $loan): bool
{
return true;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
return false;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, Loan $loan): bool
{
return false;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, Loan $loan): bool
{
return false;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, Loan $loan): bool
{
return false;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, Loan $loan): bool
{
return false;
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Policies;
use App\Models\LoanType;
use App\Models\User;
class LoanTypePolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, LoanType $loanType): bool
{
return true;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, LoanType $loanType): bool
{
return true;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, LoanType $loanType): bool
{
return false;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, LoanType $loanType): bool
{
return false;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, LoanType $loanType): bool
{
return false;
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Policies;
use App\Models\StageDefinition;
use App\Models\User;
class StageDefinitionPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, StageDefinition $stageDefinition): bool
{
return true;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, StageDefinition $stageDefinition): bool
{
return false;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, StageDefinition $stageDefinition): bool
{
return false;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, StageDefinition $stageDefinition): bool
{
return false;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, StageDefinition $stageDefinition): bool
{
return false;
}
}
@@ -0,0 +1,65 @@
<?php
namespace App\Policies;
use App\Models\User;
use App\Models\WorkflowConfiguration;
class WorkflowConfigurationPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return true;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, WorkflowConfiguration $workflowConfiguration): bool
{
return true;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, WorkflowConfiguration $workflowConfiguration): bool
{
return $workflowConfiguration->isEditable();
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, WorkflowConfiguration $workflowConfiguration): bool
{
return false;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, WorkflowConfiguration $workflowConfiguration): bool
{
return false;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, WorkflowConfiguration $workflowConfiguration): bool
{
return false;
}
}
@@ -0,0 +1,62 @@
<?php
namespace App\Providers\Filament;
use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
use Filament\Http\Middleware\DispatchServingFilamentEvent;
use Filament\Pages\Dashboard;
use Filament\Panel;
use Filament\PanelProvider;
use Filament\Support\Colors\Color;
use Filament\Support\Enums\Width;
use Filament\Widgets\AccountWidget;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\PreventRequestForgery;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;
class AdminPanelProvider extends PanelProvider
{
public function panel(Panel $panel): Panel
{
return $panel
->default()
->id('admin')
->path('admin')
->login()
->brandName('BankFlow Control')
->viteTheme('resources/css/filament/admin/theme.css')
->maxContentWidth(Width::Full)
->sidebarCollapsibleOnDesktop()
->colors([
'primary' => Color::Teal,
])
->discoverResources(in: app_path('Filament/Resources'), for: 'App\Filament\Resources')
->discoverPages(in: app_path('Filament/Pages'), for: 'App\Filament\Pages')
->pages([
Dashboard::class,
])
->discoverWidgets(in: app_path('Filament/Widgets'), for: 'App\Filament\Widgets')
->widgets([
AccountWidget::class,
])
->middleware([
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
AuthenticateSession::class,
ShareErrorsFromSession::class,
PreventRequestForgery::class,
SubstituteBindings::class,
DisableBladeIconComponents::class,
DispatchServingFilamentEvent::class,
])
->authMiddleware([
Authenticate::class,
]);
}
}