feat: implement BankFlow loan workflow API endpoints

This commit is contained in:
m.ebrahimi committed 2026-07-22 17:31:18 +03:30
1 parent 56a52be180
commit 7824e8f015
43 files changed
+1403 -10

No files matched your search

@@ -0,0 +1,54 @@
<?php
namespace App\Domain\Loan\Workflow\Stages;
use App\Domain\Loan\Contracts\StageInterface;
use App\Domain\Loan\Data\ExecutionResult;
use App\Domain\Loan\Exceptions\InvalidWorkflowConfiguration;
use App\Models\Loan;
class CreditCheckStage implements StageInterface
{
/**
* @param array<string, mixed> $rules
*/
public function execute(Loan $loan, array $rules): ExecutionResult
{
$rejectBelow = $this->integerRule($rules, 'rejectBelow');
$manualReviewMin = $this->integerRule($rules, 'manualReviewMin');
$manualReviewMax = $this->integerRule($rules, 'manualReviewMax');
$approveFrom = $this->integerRule($rules, 'approveFrom');
if ($rejectBelow !== $manualReviewMin || $manualReviewMax + 1 !== $approveFrom) {
throw new InvalidWorkflowConfiguration('Credit score ranges must be contiguous.');
}
if ($loan->credit_score < $rejectBelow) {
return ExecutionResult::fail('CREDIT_SCORE_TOO_LOW');
}
if ($loan->credit_score >= $manualReviewMin && $loan->credit_score <= $manualReviewMax) {
return ExecutionResult::manualReview('CREDIT_SCORE_REQUIRES_REVIEW');
}
if ($loan->credit_score >= $approveFrom) {
return ExecutionResult::pass();
}
throw new InvalidWorkflowConfiguration('Credit score ranges contain a gap.');
}
/**
* @param array<string, mixed> $rules
*/
private function integerRule(array $rules, string $key): int
{
$value = $rules[$key] ?? null;
if (! is_int($value)) {
throw new InvalidWorkflowConfiguration("The {$key} rule must be an integer.");
}
return $value;
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Domain\Loan\Workflow\Stages;
use App\Domain\Loan\Contracts\StageInterface;
use App\Domain\Loan\Data\ExecutionResult;
use App\Domain\Loan\Exceptions\InvalidWorkflowConfiguration;
use App\Models\Loan;
use Illuminate\Support\Str;
class FraudCheckStage implements StageInterface
{
/**
* @param array<string, mixed> $rules
*/
public function execute(Loan $loan, array $rules): ExecutionResult
{
$fraudPrefix = $this->stringRule($rules, 'fraudPrefix');
$manualReviewPrefix = $this->stringRule($rules, 'manualReviewPrefix');
if (Str::startsWith($loan->customer_id, $fraudPrefix)) {
return ExecutionResult::fail('FRAUD_DETECTED');
}
if (Str::startsWith($loan->customer_id, $manualReviewPrefix)) {
return ExecutionResult::manualReview('CUSTOMER_REQUIRES_REVIEW');
}
return ExecutionResult::pass();
}
/**
* @param array<string, mixed> $rules
*/
private function stringRule(array $rules, string $key): string
{
$value = $rules[$key] ?? null;
if (! is_string($value) || $value === '') {
throw new InvalidWorkflowConfiguration("The {$key} rule must be a non-empty string.");
}
return $value;
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Domain\Loan\Workflow\Stages;
use App\Domain\Loan\Contracts\StageInterface;
use App\Domain\Loan\Data\ExecutionResult;
use App\Models\Loan;
class GuarantorCheckStage implements StageInterface
{
/**
* @param array<string, mixed> $rules
*/
public function execute(Loan $loan, array $rules): ExecutionResult
{
if (! $loan->has_guarantor) {
return ExecutionResult::fail('GUARANTOR_REQUIRED');
}
return ExecutionResult::pass();
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Domain\Loan\Workflow\Stages;
use App\Domain\Loan\Contracts\ConditionalStageInterface;
use App\Domain\Loan\Data\ExecutionResult;
use App\Domain\Loan\Exceptions\InvalidWorkflowConfiguration;
use App\Models\Loan;
class ManagerApprovalStage implements ConditionalStageInterface
{
/**
* @param array<string, mixed> $rules
*/
public function appliesTo(Loan $loan, array $rules): bool
{
return $loan->amount > $this->positiveIntegerRule($rules, 'activationThreshold');
}
/**
* @param array<string, mixed> $rules
*/
public function execute(Loan $loan, array $rules): ExecutionResult
{
$incomeMultiplier = $this->positiveIntegerRule($rules, 'incomeMultiplier');
if ($loan->amount > $loan->monthly_income * $incomeMultiplier) {
return ExecutionResult::fail('MANAGER_APPROVAL_DENIED');
}
return ExecutionResult::pass();
}
/**
* @param array<string, mixed> $rules
*/
private function positiveIntegerRule(array $rules, string $key): int
{
$value = $rules[$key] ?? null;
if (! is_int($value) || $value <= 0) {
throw new InvalidWorkflowConfiguration("The {$key} rule must be a positive integer.");
}
return $value;
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Domain\Loan\Workflow\Stages;
use App\Domain\Loan\Contracts\StageInterface;
use App\Domain\Loan\Data\ExecutionResult;
use App\Models\Loan;
class ValidationStage implements StageInterface
{
/**
* @param array<string, mixed> $rules
*/
public function execute(Loan $loan, array $rules): ExecutionResult
{
if (trim($loan->customer_id) === '') {
return ExecutionResult::fail('INVALID_CUSTOMER_ID');
}
if ($loan->amount <= 0) {
return ExecutionResult::fail('INVALID_AMOUNT');
}
if (preg_match('/^09\d{9}$/', $loan->phone) !== 1) {
return ExecutionResult::fail('INVALID_PHONE');
}
if (! in_array($loan->loanType->code, ['PERSONAL', 'BUSINESS'], true)) {
return ExecutionResult::fail('INVALID_LOAN_TYPE');
}
if ($loan->monthly_income < 0) {
return ExecutionResult::fail('INVALID_MONTHLY_INCOME');
}
if ($loan->credit_score < 0 || $loan->credit_score > 1000) {
return ExecutionResult::fail('INVALID_CREDIT_SCORE');
}
return ExecutionResult::pass();
}
}
@@ -0,0 +1,41 @@
<?php
namespace App\Domain\Loan\Workflow;
use App\Domain\Loan\Contracts\StageInterface;
use App\Domain\Loan\Enums\LoanStage;
use App\Domain\Loan\Exceptions\InvalidWorkflowConfiguration;
use App\Models\WorkflowConfigurationStep;
use Illuminate\Contracts\Container\Container;
class WorkflowConfigurationResolver
{
public function __construct(private Container $container) {}
public function resolve(WorkflowConfigurationStep $step): StageInterface
{
$stageDefinition = $step->stageDefinition;
if (! $stageDefinition->is_active) {
throw new InvalidWorkflowConfiguration("Stage {$stageDefinition->code} is inactive.");
}
if (LoanStage::tryFrom($stageDefinition->code) === null) {
throw new InvalidWorkflowConfiguration("Stage {$stageDefinition->code} is not a known Loan stage.");
}
$handlerClass = config("workflow-stages.{$stageDefinition->code}");
if (! is_string($handlerClass) || ! is_a($handlerClass, StageInterface::class, true)) {
throw new InvalidWorkflowConfiguration("Stage {$stageDefinition->code} has no trusted handler.");
}
$handler = $this->container->make($handlerClass);
if (! $handler instanceof StageInterface) {
throw new InvalidWorkflowConfiguration("Stage {$stageDefinition->code} handler is invalid.");
}
return $handler;
}
}
@@ -0,0 +1,90 @@
<?php
namespace App\Domain\Loan\Workflow;
use App\Domain\Loan\Contracts\ConditionalStageInterface;
use App\Domain\Loan\Enums\LoanStage;
use App\Domain\Loan\Enums\LoanStatus;
use App\Domain\Loan\Enums\StageResultType;
use App\Domain\Loan\Exceptions\InvalidWorkflowConfiguration;
use App\Models\Loan;
use App\Models\WorkflowConfigurationStep;
class WorkflowEngine
{
public function __construct(private WorkflowConfigurationResolver $resolver) {}
public function process(Loan $loan): Loan
{
if ($loan->status->isTerminal()) {
return $loan;
}
if (! $loan->relationLoaded('loanType') || ! $loan->relationLoaded('workflowConfiguration')) {
throw new InvalidWorkflowConfiguration('The Loan workflow relationships must be loaded before processing.');
}
$loan->forceFill(['status' => LoanStatus::InProgress])->save();
$executedStepIds = $loan->histories->pluck('workflow_configuration_step_id')->all();
foreach ($loan->workflowConfiguration->steps as $step) {
if (! $step->is_enabled || in_array($step->getKey(), $executedStepIds, true)) {
continue;
}
$this->executeStep($loan, $step);
if ($loan->status->isTerminal()) {
return $loan;
}
}
$loan->forceFill([
'status' => LoanStatus::Approved,
'current_workflow_configuration_step_id' => null,
])->save();
return $loan;
}
private function executeStep(Loan $loan, WorkflowConfigurationStep $step): void
{
$handler = $this->resolver->resolve($step);
$rules = $step->rules;
if ($handler instanceof ConditionalStageInterface && ! $handler->appliesTo($loan, $rules)) {
return;
}
$loan->forceFill([
'current_workflow_configuration_step_id' => $step->getKey(),
])->save();
$result = $handler->execute($loan, $rules);
$stage = LoanStage::from($step->stageDefinition->code);
$loan->histories()->create([
'workflow_configuration_step_id' => $step->getKey(),
'stage_code' => $stage,
'rules_snapshot' => $rules,
'result' => $result->type,
'reason' => $result->reason,
'executed_at' => now('UTC'),
]);
if ($result->type === StageResultType::Fail) {
$loan->forceFill([
'status' => LoanStatus::Rejected,
'current_workflow_configuration_step_id' => null,
])->save();
}
if ($result->type === StageResultType::ManualReview) {
$loan->forceFill([
'status' => LoanStatus::ManualReview,
'current_workflow_configuration_step_id' => null,
])->save();
}
}
}