feat: implement BankFlow loan workflow API endpoints
This commit is contained in:
1 parent
56a52be180
commit
7824e8f015
43 files changed
+1403
-10
No files matched your search
@@ -0,0 +1,82 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions\Loan;
|
||||||
|
|
||||||
|
use App\Domain\Loan\Enums\LoanStatus;
|
||||||
|
use App\Domain\Loan\Enums\WorkflowConfigurationStatus;
|
||||||
|
use App\Domain\Loan\Exceptions\InvalidRequestException;
|
||||||
|
use App\Domain\Loan\Exceptions\InvalidWorkflowConfiguration;
|
||||||
|
use App\Models\Loan;
|
||||||
|
use App\Models\LoanType;
|
||||||
|
use App\Models\WorkflowConfiguration;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
class CreateLoanAction
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array{
|
||||||
|
* customerId: string,
|
||||||
|
* amount: int,
|
||||||
|
* phone: string,
|
||||||
|
* loanType: string,
|
||||||
|
* monthlyIncome: int,
|
||||||
|
* creditScore: int,
|
||||||
|
* hasGuarantor: bool
|
||||||
|
* } $data
|
||||||
|
*/
|
||||||
|
public function handle(array $data): Loan
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($data): Loan {
|
||||||
|
$loanType = LoanType::query()
|
||||||
|
->where('code', $data['loanType'])
|
||||||
|
->where('is_active', true)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($loanType === null) {
|
||||||
|
throw new InvalidRequestException('The requested Loan type is unavailable.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$workflowConfiguration = $this->publishedWorkflowFor($loanType);
|
||||||
|
$firstStep = $workflowConfiguration->steps->firstWhere('is_enabled', true);
|
||||||
|
|
||||||
|
if ($firstStep === null) {
|
||||||
|
throw new InvalidWorkflowConfiguration('The published Workflow has no enabled steps.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$loan = Loan::query()->create([
|
||||||
|
'public_id' => 'L-'.Str::ulid(),
|
||||||
|
'customer_id' => $data['customerId'],
|
||||||
|
'loan_type_id' => $loanType->getKey(),
|
||||||
|
'workflow_configuration_id' => $workflowConfiguration->getKey(),
|
||||||
|
'current_workflow_configuration_step_id' => $firstStep->getKey(),
|
||||||
|
'amount' => $data['amount'],
|
||||||
|
'phone' => $data['phone'],
|
||||||
|
'monthly_income' => $data['monthlyIncome'],
|
||||||
|
'credit_score' => $data['creditScore'],
|
||||||
|
'has_guarantor' => $data['hasGuarantor'],
|
||||||
|
'status' => LoanStatus::Submitted,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $loan->setRelations([
|
||||||
|
'loanType' => $loanType,
|
||||||
|
'workflowConfiguration' => $workflowConfiguration,
|
||||||
|
'currentStep' => $firstStep,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function publishedWorkflowFor(LoanType $loanType): WorkflowConfiguration
|
||||||
|
{
|
||||||
|
$workflowConfiguration = $loanType->workflowConfigurations()
|
||||||
|
->where('status', WorkflowConfigurationStatus::Published)
|
||||||
|
->with('steps.stageDefinition')
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($workflowConfiguration === null) {
|
||||||
|
throw new InvalidWorkflowConfiguration("Loan type {$loanType->code} has no published Workflow.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return $workflowConfiguration;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions\Loan;
|
||||||
|
|
||||||
|
use App\Domain\Loan\Exceptions\LoanNotFoundException;
|
||||||
|
use App\Models\Loan;
|
||||||
|
|
||||||
|
class GetLoanAction
|
||||||
|
{
|
||||||
|
public function handle(string $loanId): Loan
|
||||||
|
{
|
||||||
|
$loan = Loan::query()
|
||||||
|
->with(['loanType', 'currentStep.stageDefinition'])
|
||||||
|
->where('public_id', $loanId)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($loan === null) {
|
||||||
|
throw new LoanNotFoundException("Loan {$loanId} was not found.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return $loan;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions\Loan;
|
||||||
|
|
||||||
|
use App\Domain\Loan\Exceptions\LoanNotFoundException;
|
||||||
|
use App\Models\Loan;
|
||||||
|
use App\Models\LoanHistory;
|
||||||
|
use Illuminate\Database\Eloquent\Collection;
|
||||||
|
|
||||||
|
class GetLoanHistoryAction
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return Collection<int, LoanHistory>
|
||||||
|
*/
|
||||||
|
public function handle(string $loanId): Collection
|
||||||
|
{
|
||||||
|
$loan = Loan::query()
|
||||||
|
->select(['id', 'public_id'])
|
||||||
|
->where('public_id', $loanId)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($loan === null) {
|
||||||
|
throw new LoanNotFoundException("Loan {$loanId} was not found.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return $loan->histories()
|
||||||
|
->orderBy('executed_at')
|
||||||
|
->orderBy('id')
|
||||||
|
->get();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions\Loan;
|
||||||
|
|
||||||
|
use App\Domain\Loan\Exceptions\LoanNotFoundException;
|
||||||
|
use App\Domain\Loan\Workflow\WorkflowEngine;
|
||||||
|
use App\Models\Loan;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
class ProcessLoanAction
|
||||||
|
{
|
||||||
|
public function __construct(private WorkflowEngine $workflowEngine) {}
|
||||||
|
|
||||||
|
public function handle(string $loanId): Loan
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($loanId): Loan {
|
||||||
|
$loan = Loan::query()
|
||||||
|
->where('public_id', $loanId)
|
||||||
|
->lockForUpdate()
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($loan === null) {
|
||||||
|
throw new LoanNotFoundException("Loan {$loanId} was not found.");
|
||||||
|
}
|
||||||
|
|
||||||
|
$loan->load([
|
||||||
|
'loanType',
|
||||||
|
'workflowConfiguration.steps.stageDefinition',
|
||||||
|
'histories',
|
||||||
|
'currentStep.stageDefinition',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$processedLoan = $this->workflowEngine->process($loan);
|
||||||
|
|
||||||
|
return $processedLoan->load(['loanType', 'currentStep.stageDefinition']);
|
||||||
|
}, 3);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domain\Loan\Contracts;
|
||||||
|
|
||||||
|
use App\Models\Loan;
|
||||||
|
|
||||||
|
interface ConditionalStageInterface extends StageInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $rules
|
||||||
|
*/
|
||||||
|
public function appliesTo(Loan $loan, array $rules): bool;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domain\Loan\Contracts;
|
||||||
|
|
||||||
|
use App\Domain\Loan\Data\ExecutionResult;
|
||||||
|
use App\Models\Loan;
|
||||||
|
|
||||||
|
interface StageInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $rules
|
||||||
|
*/
|
||||||
|
public function execute(Loan $loan, array $rules): ExecutionResult;
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domain\Loan\Data;
|
||||||
|
|
||||||
|
use App\Domain\Loan\Enums\StageResultType;
|
||||||
|
|
||||||
|
final readonly class ExecutionResult
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public StageResultType $type,
|
||||||
|
public string $reason,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public static function pass(): self
|
||||||
|
{
|
||||||
|
return new self(StageResultType::Pass, 'SUCCESS');
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function fail(string $reason): self
|
||||||
|
{
|
||||||
|
return new self(StageResultType::Fail, $reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function manualReview(string $reason): self
|
||||||
|
{
|
||||||
|
return new self(StageResultType::ManualReview, $reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domain\Loan\Exceptions;
|
||||||
|
|
||||||
|
use Illuminate\Contracts\Debug\ShouldntReport;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class InvalidRequestException extends RuntimeException implements ShouldntReport
|
||||||
|
{
|
||||||
|
public function render(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
return response()->json(['error' => 'INVALID_REQUEST'], 400);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domain\Loan\Exceptions;
|
||||||
|
|
||||||
|
class InvalidWorkflowConfiguration extends WorkflowException
|
||||||
|
{
|
||||||
|
//
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domain\Loan\Exceptions;
|
||||||
|
|
||||||
|
use Illuminate\Contracts\Debug\ShouldntReport;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class LoanNotFoundException extends RuntimeException implements ShouldntReport
|
||||||
|
{
|
||||||
|
public function render(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
return response()->json(['error' => 'LOAN_NOT_FOUND'], 404);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domain\Loan\Exceptions;
|
||||||
|
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class WorkflowException extends RuntimeException
|
||||||
|
{
|
||||||
|
//
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Api\V1;
|
||||||
|
|
||||||
|
use App\Actions\Loan\CreateLoanAction;
|
||||||
|
use App\Actions\Loan\GetLoanAction;
|
||||||
|
use App\Actions\Loan\GetLoanHistoryAction;
|
||||||
|
use App\Actions\Loan\ProcessLoanAction;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use App\Http\Requests\StoreLoanRequest;
|
||||||
|
use App\Http\Resources\LoanHistoryResource;
|
||||||
|
use App\Http\Resources\LoanProcessResource;
|
||||||
|
use App\Http\Resources\LoanResource;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||||
|
|
||||||
|
class LoanController extends Controller
|
||||||
|
{
|
||||||
|
public function store(StoreLoanRequest $request, CreateLoanAction $createLoan): JsonResponse
|
||||||
|
{
|
||||||
|
$loan = $createLoan->handle($request->validated());
|
||||||
|
|
||||||
|
return (new LoanProcessResource($loan))->response()->setStatusCode(201);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function process(string $loanId, ProcessLoanAction $processLoan): JsonResponse
|
||||||
|
{
|
||||||
|
return (new LoanProcessResource($processLoan->handle($loanId)))->response();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function show(string $loanId, GetLoanAction $getLoan): JsonResponse
|
||||||
|
{
|
||||||
|
return (new LoanResource($getLoan->handle($loanId)))->response();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function history(string $loanId, GetLoanHistoryAction $getLoanHistory): AnonymousResourceCollection
|
||||||
|
{
|
||||||
|
return LoanHistoryResource::collection($getLoanHistory->handle($loanId));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
|
||||||
|
class HealthCheckController extends Controller
|
||||||
|
{
|
||||||
|
public function __invoke(): JsonResponse
|
||||||
|
{
|
||||||
|
return response()->json(['status' => 'UP']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Requests;
|
||||||
|
|
||||||
|
use App\Domain\Loan\Exceptions\InvalidRequestException;
|
||||||
|
use Illuminate\Contracts\Validation\Validator;
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
use JsonException;
|
||||||
|
|
||||||
|
class StoreLoanRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, array<int, string>>
|
||||||
|
*/
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'customerId' => ['present', 'string', 'max:255'],
|
||||||
|
'amount' => ['present', 'integer'],
|
||||||
|
'phone' => ['present', 'string', 'max:255'],
|
||||||
|
'loanType' => ['present', 'string', 'max:255'],
|
||||||
|
'monthlyIncome' => ['present', 'integer'],
|
||||||
|
'creditScore' => ['present', 'integer'],
|
||||||
|
'hasGuarantor' => ['present', 'boolean'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function validationData(): array
|
||||||
|
{
|
||||||
|
if (! $this->isJson()) {
|
||||||
|
throw new InvalidRequestException('The request body must use JSON.');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$data = json_decode($this->getContent(), true, 512, JSON_THROW_ON_ERROR);
|
||||||
|
} catch (JsonException) {
|
||||||
|
throw new InvalidRequestException('The request body is not valid JSON.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! is_array($data)) {
|
||||||
|
throw new InvalidRequestException('The request body must be a JSON object.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function failedValidation(Validator $validator): never
|
||||||
|
{
|
||||||
|
throw new InvalidRequestException('The request structure is invalid.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Resources;
|
||||||
|
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
class LoanHistoryResource extends JsonResource
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'stage' => $this->stage_code->value,
|
||||||
|
'result' => $this->result->value,
|
||||||
|
'timestamp' => $this->executed_at->toIso8601ZuluString(),
|
||||||
|
'reason' => $this->reason,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Resources;
|
||||||
|
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
class LoanProcessResource extends JsonResource
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'loanId' => $this->public_id,
|
||||||
|
'status' => $this->status->value,
|
||||||
|
'currentStage' => $this->currentStep?->stageDefinition->code,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Resources;
|
||||||
|
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
class LoanResource extends JsonResource
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'loanId' => $this->public_id,
|
||||||
|
'customerId' => $this->customer_id,
|
||||||
|
'amount' => $this->amount,
|
||||||
|
'phone' => $this->phone,
|
||||||
|
'loanType' => $this->loanType->code,
|
||||||
|
'monthlyIncome' => $this->monthly_income,
|
||||||
|
'creditScore' => $this->credit_score,
|
||||||
|
'hasGuarantor' => $this->has_guarantor,
|
||||||
|
'status' => $this->status->value,
|
||||||
|
'currentStage' => $this->currentStep?->stageDefinition->code,
|
||||||
|
'createdAt' => $this->created_at->toIso8601ZuluString(),
|
||||||
|
'updatedAt' => $this->updated_at->toIso8601ZuluString(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
namespace App\Providers;
|
namespace App\Providers;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
|
||||||
class AppServiceProvider extends ServiceProvider
|
class AppServiceProvider extends ServiceProvider
|
||||||
@@ -19,6 +21,7 @@ class AppServiceProvider extends ServiceProvider
|
|||||||
*/
|
*/
|
||||||
public function boot(): void
|
public function boot(): void
|
||||||
{
|
{
|
||||||
//
|
Model::preventLazyLoading(! app()->isProduction());
|
||||||
|
JsonResource::withoutWrapping();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -8,8 +8,8 @@ use Illuminate\Http\Request;
|
|||||||
return Application::configure(basePath: dirname(__DIR__))
|
return Application::configure(basePath: dirname(__DIR__))
|
||||||
->withRouting(
|
->withRouting(
|
||||||
web: __DIR__.'/../routes/web.php',
|
web: __DIR__.'/../routes/web.php',
|
||||||
|
api: __DIR__.'/../routes/api.php',
|
||||||
commands: __DIR__.'/../routes/console.php',
|
commands: __DIR__.'/../routes/console.php',
|
||||||
health: '/up',
|
|
||||||
)
|
)
|
||||||
->withMiddleware(function (Middleware $middleware): void {
|
->withMiddleware(function (Middleware $middleware): void {
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domain\Loan\Workflow\Stages\CreditCheckStage;
|
||||||
|
use App\Domain\Loan\Workflow\Stages\FraudCheckStage;
|
||||||
|
use App\Domain\Loan\Workflow\Stages\GuarantorCheckStage;
|
||||||
|
use App\Domain\Loan\Workflow\Stages\ManagerApprovalStage;
|
||||||
|
use App\Domain\Loan\Workflow\Stages\ValidationStage;
|
||||||
|
|
||||||
|
return [
|
||||||
|
'VALIDATION' => ValidationStage::class,
|
||||||
|
'FRAUD_CHECK' => FraudCheckStage::class,
|
||||||
|
'GUARANTOR_CHECK' => GuarantorCheckStage::class,
|
||||||
|
'CREDIT_CHECK' => CreditCheckStage::class,
|
||||||
|
'MANAGER_APPROVAL' => ManagerApprovalStage::class,
|
||||||
|
];
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Database\Seeders;
|
||||||
|
|
||||||
|
use App\Domain\Loan\Enums\LoanStage;
|
||||||
|
use App\Domain\Loan\Enums\WorkflowConfigurationStatus;
|
||||||
|
use App\Models\LoanType;
|
||||||
|
use App\Models\StageDefinition;
|
||||||
|
use App\Models\WorkflowConfiguration;
|
||||||
|
use Illuminate\Database\Seeder;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
class BankFlowSeeder extends Seeder
|
||||||
|
{
|
||||||
|
public function run(): void
|
||||||
|
{
|
||||||
|
DB::transaction(function (): void {
|
||||||
|
$stageDefinitions = collect(LoanStage::cases())->mapWithKeys(
|
||||||
|
function (LoanStage $stage): array {
|
||||||
|
$stageDefinition = StageDefinition::query()->firstOrCreate(
|
||||||
|
['code' => $stage->value],
|
||||||
|
['name' => str($stage->name)->headline()->toString(), 'is_active' => true],
|
||||||
|
);
|
||||||
|
|
||||||
|
return [$stage->value => $stageDefinition];
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
$personalLoanType = LoanType::query()->firstOrCreate(
|
||||||
|
['code' => 'PERSONAL'],
|
||||||
|
['name' => 'Personal Loan', 'is_active' => true],
|
||||||
|
);
|
||||||
|
|
||||||
|
$businessLoanType = LoanType::query()->firstOrCreate(
|
||||||
|
['code' => 'BUSINESS'],
|
||||||
|
['name' => 'Business Loan', 'is_active' => true],
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->createInitialWorkflow(
|
||||||
|
$personalLoanType,
|
||||||
|
'Personal Loan Workflow',
|
||||||
|
[
|
||||||
|
[LoanStage::Validation, []],
|
||||||
|
[LoanStage::FraudCheck, $this->fraudRules()],
|
||||||
|
[LoanStage::CreditCheck, $this->creditRules()],
|
||||||
|
[LoanStage::ManagerApproval, $this->managerRules()],
|
||||||
|
],
|
||||||
|
$stageDefinitions->all(),
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->createInitialWorkflow(
|
||||||
|
$businessLoanType,
|
||||||
|
'Business Loan Workflow',
|
||||||
|
[
|
||||||
|
[LoanStage::Validation, []],
|
||||||
|
[LoanStage::FraudCheck, $this->fraudRules()],
|
||||||
|
[LoanStage::GuarantorCheck, []],
|
||||||
|
[LoanStage::CreditCheck, $this->creditRules()],
|
||||||
|
[LoanStage::ManagerApproval, $this->managerRules()],
|
||||||
|
],
|
||||||
|
$stageDefinitions->all(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, array{LoanStage, array<string, mixed>}> $steps
|
||||||
|
* @param array<string, StageDefinition> $stageDefinitions
|
||||||
|
*/
|
||||||
|
private function createInitialWorkflow(
|
||||||
|
LoanType $loanType,
|
||||||
|
string $name,
|
||||||
|
array $steps,
|
||||||
|
array $stageDefinitions,
|
||||||
|
): void {
|
||||||
|
$publishedWorkflowExists = $loanType->workflowConfigurations()
|
||||||
|
->where('status', WorkflowConfigurationStatus::Published)
|
||||||
|
->exists();
|
||||||
|
|
||||||
|
if ($publishedWorkflowExists) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$workflowConfiguration = WorkflowConfiguration::query()->create([
|
||||||
|
'loan_type_id' => $loanType->getKey(),
|
||||||
|
'name' => $name,
|
||||||
|
'version' => 1,
|
||||||
|
'status' => WorkflowConfigurationStatus::Published,
|
||||||
|
'published_at' => now('UTC'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
foreach ($steps as $index => [$stage, $rules]) {
|
||||||
|
$workflowConfiguration->steps()->create([
|
||||||
|
'stage_definition_id' => $stageDefinitions[$stage->value]->getKey(),
|
||||||
|
'position' => $index + 1,
|
||||||
|
'rules' => $rules,
|
||||||
|
'is_enabled' => true,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{fraudPrefix: string, manualReviewPrefix: string}
|
||||||
|
*/
|
||||||
|
private function fraudRules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'fraudPrefix' => 'FRAUD',
|
||||||
|
'manualReviewPrefix' => 'REVIEW',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{rejectBelow: int, manualReviewMin: int, manualReviewMax: int, approveFrom: int}
|
||||||
|
*/
|
||||||
|
private function creditRules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'rejectBelow' => 500,
|
||||||
|
'manualReviewMin' => 500,
|
||||||
|
'manualReviewMax' => 649,
|
||||||
|
'approveFrom' => 650,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{activationThreshold: int, incomeMultiplier: int}
|
||||||
|
*/
|
||||||
|
private function managerRules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'activationThreshold' => 500_000_000,
|
||||||
|
'incomeMultiplier' => 20,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,8 +14,6 @@ class DatabaseSeeder extends Seeder
|
|||||||
*/
|
*/
|
||||||
public function run(): void
|
public function run(): void
|
||||||
{
|
{
|
||||||
if (app()->environment('local')) {
|
$this->call(BankFlowSeeder::class);
|
||||||
$this->call(BankFlowDevelopmentSeeder::class);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Http\Controllers\Api\V1\LoanController;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
|
Route::prefix('v1')->name('api.v1.')->group(function (): void {
|
||||||
|
Route::post('/loans', [LoanController::class, 'store'])->name('loans.store');
|
||||||
|
Route::post('/loans/{loanId}/process', [LoanController::class, 'process'])->name('loans.process');
|
||||||
|
Route::get('/loans/{loanId}', [LoanController::class, 'show'])->name('loans.show');
|
||||||
|
Route::get('/loans/{loanId}/history', [LoanController::class, 'history'])->name('loans.history');
|
||||||
|
});
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
use App\Http\Controllers\HealthCheckController;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
Route::get('/', function () {
|
Route::get('/', function () {
|
||||||
return view('welcome');
|
return view('welcome');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Route::get('/health', HealthCheckController::class)->name('health');
|
||||||
@@ -3,5 +3,5 @@
|
|||||||
test('the application returns a successful response', function () {
|
test('the application returns a successful response', function () {
|
||||||
$response = $this->get('/');
|
$response = $this->get('/');
|
||||||
|
|
||||||
$response->assertStatus(200);
|
$response->assertSuccessful();
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domain\Loan\Enums\LoanStatus;
|
||||||
|
use App\Models\Loan;
|
||||||
|
use Database\Seeders\BankFlowSeeder;
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
$this->seed(BankFlowSeeder::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates a submitted loan assigned to the published workflow', function () {
|
||||||
|
$response = $this->postJson('/api/v1/loans', validLoanPayload());
|
||||||
|
|
||||||
|
$response->assertCreated()->assertExactJson([
|
||||||
|
'loanId' => $response->json('loanId'),
|
||||||
|
'status' => 'SUBMITTED',
|
||||||
|
'currentStage' => 'VALIDATION',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$loan = Loan::query()->where('public_id', $response->json('loanId'))->firstOrFail();
|
||||||
|
|
||||||
|
expect($loan->status)->toBe(LoanStatus::Submitted)
|
||||||
|
->and($loan->workflow_configuration_id)->not->toBeNull()
|
||||||
|
->and($loan->current_workflow_configuration_step_id)->not->toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('defers semantic validation until processing', function (array $overrides, string $reason) {
|
||||||
|
$createResponse = $this->postJson('/api/v1/loans', validLoanPayload($overrides));
|
||||||
|
|
||||||
|
$createResponse->assertCreated();
|
||||||
|
|
||||||
|
$this->postJson("/api/v1/loans/{$createResponse->json('loanId')}/process")
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertJsonPath('status', 'REJECTED');
|
||||||
|
|
||||||
|
$loan = Loan::query()->where('public_id', $createResponse->json('loanId'))->firstOrFail();
|
||||||
|
|
||||||
|
expect($loan->histories()->value('reason'))->toBe($reason);
|
||||||
|
})->with([
|
||||||
|
'customer ID' => [['customerId' => ''], 'INVALID_CUSTOMER_ID'],
|
||||||
|
'amount' => [['amount' => 0], 'INVALID_AMOUNT'],
|
||||||
|
'phone' => [['phone' => '08121234567'], 'INVALID_PHONE'],
|
||||||
|
'monthly income' => [['monthlyIncome' => -1], 'INVALID_MONTHLY_INCOME'],
|
||||||
|
'credit score' => [['creditScore' => 1001], 'INVALID_CREDIT_SCORE'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
it('returns invalid request for malformed JSON', function () {
|
||||||
|
$response = $this->call(
|
||||||
|
'POST',
|
||||||
|
'/api/v1/loans',
|
||||||
|
server: ['CONTENT_TYPE' => 'application/json', 'HTTP_ACCEPT' => 'application/json'],
|
||||||
|
content: '{"customerId":',
|
||||||
|
);
|
||||||
|
|
||||||
|
$response->assertBadRequest()->assertExactJson(['error' => 'INVALID_REQUEST']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns invalid request for an unavailable loan type', function () {
|
||||||
|
$this->postJson('/api/v1/loans', validLoanPayload(['loanType' => 'UNKNOWN']))
|
||||||
|
->assertBadRequest()
|
||||||
|
->assertExactJson(['error' => 'INVALID_REQUEST']);
|
||||||
|
});
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Database\Seeders\BankFlowSeeder;
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
$this->seed(BankFlowSeeder::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns unwrapped history in deterministic chronological order', function () {
|
||||||
|
$loanId = $this->postJson('/api/v1/loans', validLoanPayload())->json('loanId');
|
||||||
|
$this->postJson("/api/v1/loans/{$loanId}/process")->assertSuccessful();
|
||||||
|
|
||||||
|
$this->getJson("/api/v1/loans/{$loanId}/history")
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertJsonCount(3)
|
||||||
|
->assertJsonPath('0.stage', 'VALIDATION')
|
||||||
|
->assertJsonPath('1.stage', 'FRAUD_CHECK')
|
||||||
|
->assertJsonPath('2.stage', 'CREDIT_CHECK')
|
||||||
|
->assertJsonStructure([
|
||||||
|
'*' => ['stage', 'result', 'timestamp', 'reason'],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns the documented error for an unknown loan', function () {
|
||||||
|
$this->getJson('/api/v1/loans/L-UNKNOWN/history')
|
||||||
|
->assertNotFound()
|
||||||
|
->assertExactJson(['error' => 'LOAN_NOT_FOUND']);
|
||||||
|
});
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Database\Seeders\BankFlowSeeder;
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
$this->seed(BankFlowSeeder::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns the complete loan representation', function () {
|
||||||
|
$loanId = $this->postJson('/api/v1/loans', validLoanPayload())->json('loanId');
|
||||||
|
|
||||||
|
$this->getJson("/api/v1/loans/{$loanId}")
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertJson([
|
||||||
|
'loanId' => $loanId,
|
||||||
|
'customerId' => 'C-1001',
|
||||||
|
'amount' => 400_000_000,
|
||||||
|
'phone' => '09121234567',
|
||||||
|
'loanType' => 'PERSONAL',
|
||||||
|
'monthlyIncome' => 50_000_000,
|
||||||
|
'creditScore' => 720,
|
||||||
|
'hasGuarantor' => false,
|
||||||
|
'status' => 'SUBMITTED',
|
||||||
|
'currentStage' => 'VALIDATION',
|
||||||
|
])
|
||||||
|
->assertJsonStructure(['createdAt', 'updatedAt']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns the documented error for an unknown loan', function () {
|
||||||
|
$this->getJson('/api/v1/loans/L-UNKNOWN')
|
||||||
|
->assertNotFound()
|
||||||
|
->assertExactJson(['error' => 'LOAN_NOT_FOUND']);
|
||||||
|
});
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
it('reports service health', function () {
|
||||||
|
$this->getJson('/health')
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertExactJson(['status' => 'UP']);
|
||||||
|
});
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\Loan;
|
||||||
|
use Database\Seeders\BankFlowSeeder;
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
$this->seed(BankFlowSeeder::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('approves a valid personal loan and records applicable stages', function () {
|
||||||
|
$loanId = $this->postJson('/api/v1/loans', validLoanPayload())->json('loanId');
|
||||||
|
|
||||||
|
$this->postJson("/api/v1/loans/{$loanId}/process")
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertExactJson([
|
||||||
|
'loanId' => $loanId,
|
||||||
|
'status' => 'APPROVED',
|
||||||
|
'currentStage' => null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$loan = Loan::query()->where('public_id', $loanId)->firstOrFail();
|
||||||
|
|
||||||
|
expect($loan->histories()->orderBy('id')->pluck('stage_code')->all())->toBe([
|
||||||
|
'VALIDATION',
|
||||||
|
'FRAUD_CHECK',
|
||||||
|
'CREDIT_CHECK',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a business loan without a guarantor', function () {
|
||||||
|
$loanId = $this->postJson('/api/v1/loans', validLoanPayload([
|
||||||
|
'loanType' => 'BUSINESS',
|
||||||
|
'hasGuarantor' => false,
|
||||||
|
]))->json('loanId');
|
||||||
|
|
||||||
|
$this->postJson("/api/v1/loans/{$loanId}/process")
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertJsonPath('status', 'REJECTED');
|
||||||
|
|
||||||
|
$loan = Loan::query()->where('public_id', $loanId)->firstOrFail();
|
||||||
|
|
||||||
|
expect($loan->histories()->latest('id')->value('reason'))->toBe('GUARANTOR_REQUIRED');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('approves a valid business loan with a guarantor', function () {
|
||||||
|
$loanId = $this->postJson('/api/v1/loans', validLoanPayload([
|
||||||
|
'loanType' => 'BUSINESS',
|
||||||
|
'hasGuarantor' => true,
|
||||||
|
]))->json('loanId');
|
||||||
|
|
||||||
|
$this->postJson("/api/v1/loans/{$loanId}/process")
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertJsonPath('status', 'APPROVED');
|
||||||
|
|
||||||
|
$loan = Loan::query()->where('public_id', $loanId)->firstOrFail();
|
||||||
|
|
||||||
|
expect($loan->histories()->orderBy('id')->pluck('stage_code')->all())->toBe([
|
||||||
|
'VALIDATION',
|
||||||
|
'FRAUD_CHECK',
|
||||||
|
'GUARANTOR_CHECK',
|
||||||
|
'CREDIT_CHECK',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stops for fraud and credit manual review decisions', function (array $overrides, string $stage) {
|
||||||
|
$loanId = $this->postJson('/api/v1/loans', validLoanPayload($overrides))->json('loanId');
|
||||||
|
|
||||||
|
$this->postJson("/api/v1/loans/{$loanId}/process")
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertJsonPath('status', 'MANUAL_REVIEW')
|
||||||
|
->assertJsonPath('currentStage', null);
|
||||||
|
|
||||||
|
$loan = Loan::query()->where('public_id', $loanId)->firstOrFail();
|
||||||
|
|
||||||
|
expect($loan->histories()->latest('id')->value('stage_code'))->toBe($stage);
|
||||||
|
})->with([
|
||||||
|
'fraud review' => [['customerId' => 'REVIEW-1001'], 'FRAUD_CHECK'],
|
||||||
|
'credit review' => [['creditScore' => 600], 'CREDIT_CHECK'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
it('executes manager approval only above its threshold', function (
|
||||||
|
int $amount,
|
||||||
|
int $monthlyIncome,
|
||||||
|
string $expectedStatus,
|
||||||
|
int $expectedHistoryCount,
|
||||||
|
) {
|
||||||
|
$loanId = $this->postJson('/api/v1/loans', validLoanPayload([
|
||||||
|
'amount' => $amount,
|
||||||
|
'monthlyIncome' => $monthlyIncome,
|
||||||
|
]))->json('loanId');
|
||||||
|
|
||||||
|
$this->postJson("/api/v1/loans/{$loanId}/process")
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertJsonPath('status', $expectedStatus);
|
||||||
|
|
||||||
|
$loan = Loan::query()->where('public_id', $loanId)->firstOrFail();
|
||||||
|
|
||||||
|
expect($loan->histories()->count())->toBe($expectedHistoryCount);
|
||||||
|
})->with([
|
||||||
|
'skipped at threshold' => [500_000_000, 20_000_000, 'APPROVED', 3],
|
||||||
|
'manager rejection' => [600_000_000, 20_000_000, 'REJECTED', 4],
|
||||||
|
'manager approval' => [600_000_000, 50_000_000, 'APPROVED', 4],
|
||||||
|
]);
|
||||||
|
|
||||||
|
it('is idempotent after reaching a terminal status', function (array $overrides, string $status) {
|
||||||
|
$loanId = $this->postJson('/api/v1/loans', validLoanPayload($overrides))->json('loanId');
|
||||||
|
|
||||||
|
$this->postJson("/api/v1/loans/{$loanId}/process")->assertSuccessful();
|
||||||
|
|
||||||
|
$loan = Loan::query()->where('public_id', $loanId)->firstOrFail();
|
||||||
|
$historyCount = $loan->histories()->count();
|
||||||
|
|
||||||
|
$this->postJson("/api/v1/loans/{$loanId}/process")
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertJsonPath('status', $status);
|
||||||
|
|
||||||
|
expect($loan->histories()->count())->toBe($historyCount);
|
||||||
|
})->with([
|
||||||
|
'approved' => [[], 'APPROVED'],
|
||||||
|
'rejected' => [['customerId' => 'FRAUD-1001'], 'REJECTED'],
|
||||||
|
'manual review' => [['customerId' => 'REVIEW-1001'], 'MANUAL_REVIEW'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
it('returns the documented error for an unknown loan', function () {
|
||||||
|
$this->postJson('/api/v1/loans/L-UNKNOWN/process')
|
||||||
|
->assertNotFound()
|
||||||
|
->assertExactJson(['error' => 'LOAN_NOT_FOUND']);
|
||||||
|
});
|
||||||
+15
-4
@@ -1,6 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
use Illuminate\Foundation\Testing\LazilyRefreshDatabase;
|
||||||
use Tests\TestCase;
|
use Tests\TestCase;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -15,7 +15,7 @@ use Tests\TestCase;
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
pest()->extend(TestCase::class)
|
pest()->extend(TestCase::class)
|
||||||
// ->use(RefreshDatabase::class)
|
->use(LazilyRefreshDatabase::class)
|
||||||
->in('Feature');
|
->in('Feature');
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -44,7 +44,18 @@ expect()->extend('toBeOne', function () {
|
|||||||
|
|
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
function something()
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
function validLoanPayload(array $overrides = []): array
|
||||||
{
|
{
|
||||||
// ..
|
return array_replace([
|
||||||
|
'customerId' => 'C-1001',
|
||||||
|
'amount' => 400_000_000,
|
||||||
|
'phone' => '09121234567',
|
||||||
|
'loanType' => 'PERSONAL',
|
||||||
|
'monthlyIncome' => 50_000_000,
|
||||||
|
'creditScore' => 720,
|
||||||
|
'hasGuarantor' => false,
|
||||||
|
], $overrides);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domain\Loan\Enums\StageResultType;
|
||||||
|
use App\Domain\Loan\Workflow\Stages\CreditCheckStage;
|
||||||
|
use App\Models\Loan;
|
||||||
|
|
||||||
|
it('handles credit score boundaries', function (int $creditScore, StageResultType $expected) {
|
||||||
|
$result = (new CreditCheckStage)->execute(
|
||||||
|
new Loan(['credit_score' => $creditScore]),
|
||||||
|
[
|
||||||
|
'rejectBelow' => 500,
|
||||||
|
'manualReviewMin' => 500,
|
||||||
|
'manualReviewMax' => 649,
|
||||||
|
'approveFrom' => 650,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
expect($result->type)->toBe($expected);
|
||||||
|
})->with([
|
||||||
|
'below manual range' => [499, StageResultType::Fail],
|
||||||
|
'manual lower boundary' => [500, StageResultType::ManualReview],
|
||||||
|
'manual upper boundary' => [649, StageResultType::ManualReview],
|
||||||
|
'approval boundary' => [650, StageResultType::Pass],
|
||||||
|
]);
|
||||||
|
|
||||||
|
it('uses overridden credit rules', function () {
|
||||||
|
$result = (new CreditCheckStage)->execute(
|
||||||
|
new Loan(['credit_score' => 699]),
|
||||||
|
[
|
||||||
|
'rejectBelow' => 650,
|
||||||
|
'manualReviewMin' => 650,
|
||||||
|
'manualReviewMax' => 699,
|
||||||
|
'approveFrom' => 700,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
expect($result->type)->toBe(StageResultType::ManualReview);
|
||||||
|
});
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domain\Loan\Enums\StageResultType;
|
||||||
|
use App\Domain\Loan\Workflow\Stages\FraudCheckStage;
|
||||||
|
use App\Models\Loan;
|
||||||
|
|
||||||
|
it('maps customer prefixes to fraud outcomes', function (string $customerId, StageResultType $expected) {
|
||||||
|
$result = (new FraudCheckStage)->execute(
|
||||||
|
new Loan(['customer_id' => $customerId]),
|
||||||
|
['fraudPrefix' => 'FRAUD', 'manualReviewPrefix' => 'REVIEW'],
|
||||||
|
);
|
||||||
|
|
||||||
|
expect($result->type)->toBe($expected);
|
||||||
|
})->with([
|
||||||
|
'fraud' => ['FRAUD-1001', StageResultType::Fail],
|
||||||
|
'manual review' => ['REVIEW-1001', StageResultType::ManualReview],
|
||||||
|
'pass' => ['C-1001', StageResultType::Pass],
|
||||||
|
]);
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domain\Loan\Enums\StageResultType;
|
||||||
|
use App\Domain\Loan\Workflow\Stages\GuarantorCheckStage;
|
||||||
|
use App\Models\Loan;
|
||||||
|
|
||||||
|
it('requires a guarantor', function (bool $hasGuarantor, StageResultType $expected) {
|
||||||
|
$result = (new GuarantorCheckStage)->execute(
|
||||||
|
new Loan(['has_guarantor' => $hasGuarantor]),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
expect($result->type)->toBe($expected);
|
||||||
|
})->with([
|
||||||
|
'missing' => [false, StageResultType::Fail],
|
||||||
|
'present' => [true, StageResultType::Pass],
|
||||||
|
]);
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domain\Loan\Enums\StageResultType;
|
||||||
|
use App\Domain\Loan\Workflow\Stages\ManagerApprovalStage;
|
||||||
|
use App\Models\Loan;
|
||||||
|
|
||||||
|
it('only applies above the activation threshold', function (int $amount, bool $expected) {
|
||||||
|
$stage = new ManagerApprovalStage;
|
||||||
|
|
||||||
|
expect($stage->appliesTo(
|
||||||
|
new Loan(['amount' => $amount]),
|
||||||
|
['activationThreshold' => 500_000_000],
|
||||||
|
))->toBe($expected);
|
||||||
|
})->with([
|
||||||
|
'below' => [499_999_999, false],
|
||||||
|
'at threshold' => [500_000_000, false],
|
||||||
|
'above' => [500_000_001, true],
|
||||||
|
]);
|
||||||
|
|
||||||
|
it('compares the requested amount with configured income capacity', function (
|
||||||
|
int $amount,
|
||||||
|
int $monthlyIncome,
|
||||||
|
StageResultType $expected,
|
||||||
|
) {
|
||||||
|
$result = (new ManagerApprovalStage)->execute(
|
||||||
|
new Loan(['amount' => $amount, 'monthly_income' => $monthlyIncome]),
|
||||||
|
['incomeMultiplier' => 20],
|
||||||
|
);
|
||||||
|
|
||||||
|
expect($result->type)->toBe($expected);
|
||||||
|
})->with([
|
||||||
|
'denied' => [600_000_000, 20_000_000, StageResultType::Fail],
|
||||||
|
'approved' => [600_000_000, 50_000_000, StageResultType::Pass],
|
||||||
|
]);
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domain\Loan\Enums\StageResultType;
|
||||||
|
use App\Domain\Loan\Workflow\Stages\ValidationStage;
|
||||||
|
use App\Models\Loan;
|
||||||
|
use App\Models\LoanType;
|
||||||
|
|
||||||
|
it('passes a valid application', function () {
|
||||||
|
$loan = (new Loan([
|
||||||
|
'customer_id' => 'C-1001',
|
||||||
|
'amount' => 400_000_000,
|
||||||
|
'phone' => '09121234567',
|
||||||
|
'monthly_income' => 50_000_000,
|
||||||
|
'credit_score' => 720,
|
||||||
|
'has_guarantor' => false,
|
||||||
|
]))->setRelation('loanType', new LoanType(['code' => 'PERSONAL']));
|
||||||
|
|
||||||
|
expect((new ValidationStage)->execute($loan, [])->type)->toBe(StageResultType::Pass);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns the first validation failure', function (array $attributes, string $reason) {
|
||||||
|
$loanType = new LoanType(['code' => $attributes['loan_type_code'] ?? 'PERSONAL']);
|
||||||
|
unset($attributes['loan_type_code']);
|
||||||
|
|
||||||
|
$loan = (new Loan(array_replace([
|
||||||
|
'customer_id' => 'C-1001',
|
||||||
|
'amount' => 400_000_000,
|
||||||
|
'phone' => '09121234567',
|
||||||
|
'monthly_income' => 50_000_000,
|
||||||
|
'credit_score' => 720,
|
||||||
|
'has_guarantor' => false,
|
||||||
|
], $attributes)))->setRelation('loanType', $loanType);
|
||||||
|
|
||||||
|
$result = (new ValidationStage)->execute($loan, []);
|
||||||
|
|
||||||
|
expect($result->type)->toBe(StageResultType::Fail)
|
||||||
|
->and($result->reason)->toBe($reason);
|
||||||
|
})->with([
|
||||||
|
'customer ID' => [['customer_id' => ''], 'INVALID_CUSTOMER_ID'],
|
||||||
|
'amount' => [['amount' => 0], 'INVALID_AMOUNT'],
|
||||||
|
'phone' => [['phone' => '08121234567'], 'INVALID_PHONE'],
|
||||||
|
'loan type' => [['loan_type_code' => 'OTHER'], 'INVALID_LOAN_TYPE'],
|
||||||
|
'monthly income' => [['monthly_income' => -1], 'INVALID_MONTHLY_INCOME'],
|
||||||
|
'credit score below range' => [['credit_score' => -1], 'INVALID_CREDIT_SCORE'],
|
||||||
|
'credit score above range' => [['credit_score' => 1001], 'INVALID_CREDIT_SCORE'],
|
||||||
|
]);
|
||||||
Reference in new issue
Block a user