From 7824e8f015745316826dc240af24e095dcd05068 Mon Sep 17 00:00:00 2001 From: "m.ebrahimi" Date: Wed, 22 Jul 2026 17:31:18 +0330 Subject: [PATCH] feat: implement BankFlow loan workflow API endpoints --- app/Actions/Loan/CreateLoanAction.php | 82 +++++++++++ app/Actions/Loan/GetLoanAction.php | 23 +++ app/Actions/Loan/GetLoanHistoryAction.php | 31 ++++ app/Actions/Loan/ProcessLoanAction.php | 38 +++++ .../Contracts/ConditionalStageInterface.php | 13 ++ app/Domain/Loan/Contracts/StageInterface.php | 14 ++ app/Domain/Loan/Data/ExecutionResult.php | 28 ++++ .../Exceptions/InvalidRequestException.php | 16 +++ .../InvalidWorkflowConfiguration.php | 8 ++ .../Loan/Exceptions/LoanNotFoundException.php | 16 +++ .../Loan/Exceptions/WorkflowException.php | 10 ++ .../Loan/Workflow/Stages/CreditCheckStage.php | 54 +++++++ .../Loan/Workflow/Stages/FraudCheckStage.php | 45 ++++++ .../Workflow/Stages/GuarantorCheckStage.php | 22 +++ .../Workflow/Stages/ManagerApprovalStage.php | 47 ++++++ .../Loan/Workflow/Stages/ValidationStage.php | 42 ++++++ .../WorkflowConfigurationResolver.php | 41 ++++++ app/Domain/Loan/Workflow/WorkflowEngine.php | 90 ++++++++++++ .../Controllers/Api/V1/LoanController.php | 40 ++++++ .../Controllers/HealthCheckController.php | 13 ++ app/Http/Requests/StoreLoanRequest.php | 59 ++++++++ app/Http/Resources/LoanHistoryResource.php | 22 +++ app/Http/Resources/LoanProcessResource.php | 21 +++ app/Http/Resources/LoanResource.php | 30 ++++ app/Providers/AppServiceProvider.php | 5 +- bootstrap/app.php | 2 +- config/workflow-stages.php | 15 ++ database/seeders/BankFlowSeeder.php | 136 ++++++++++++++++++ database/seeders/DatabaseSeeder.php | 4 +- routes/api.php | 11 ++ routes/web.php | 3 + tests/Feature/ExampleTest.php | 2 +- tests/Feature/Loan/CreateLoanTest.php | 62 ++++++++ tests/Feature/Loan/GetLoanHistoryTest.php | 28 ++++ tests/Feature/Loan/GetLoanTest.php | 33 +++++ tests/Feature/Loan/HealthCheckTest.php | 7 + tests/Feature/Loan/ProcessLoanTest.php | 128 +++++++++++++++++ tests/Pest.php | 19 ++- .../Loan/Workflow/CreditCheckStageTest.php | 38 +++++ .../Loan/Workflow/FraudCheckStageTest.php | 18 +++ .../Loan/Workflow/GuarantorCheckStageTest.php | 17 +++ .../Workflow/ManagerApprovalStageTest.php | 34 +++++ .../Loan/Workflow/ValidationStageTest.php | 46 ++++++ 43 files changed, 1403 insertions(+), 10 deletions(-) create mode 100644 app/Actions/Loan/CreateLoanAction.php create mode 100644 app/Actions/Loan/GetLoanAction.php create mode 100644 app/Actions/Loan/GetLoanHistoryAction.php create mode 100644 app/Actions/Loan/ProcessLoanAction.php create mode 100644 app/Domain/Loan/Contracts/ConditionalStageInterface.php create mode 100644 app/Domain/Loan/Contracts/StageInterface.php create mode 100644 app/Domain/Loan/Data/ExecutionResult.php create mode 100644 app/Domain/Loan/Exceptions/InvalidRequestException.php create mode 100644 app/Domain/Loan/Exceptions/InvalidWorkflowConfiguration.php create mode 100644 app/Domain/Loan/Exceptions/LoanNotFoundException.php create mode 100644 app/Domain/Loan/Exceptions/WorkflowException.php create mode 100644 app/Domain/Loan/Workflow/Stages/CreditCheckStage.php create mode 100644 app/Domain/Loan/Workflow/Stages/FraudCheckStage.php create mode 100644 app/Domain/Loan/Workflow/Stages/GuarantorCheckStage.php create mode 100644 app/Domain/Loan/Workflow/Stages/ManagerApprovalStage.php create mode 100644 app/Domain/Loan/Workflow/Stages/ValidationStage.php create mode 100644 app/Domain/Loan/Workflow/WorkflowConfigurationResolver.php create mode 100644 app/Domain/Loan/Workflow/WorkflowEngine.php create mode 100644 app/Http/Controllers/Api/V1/LoanController.php create mode 100644 app/Http/Controllers/HealthCheckController.php create mode 100644 app/Http/Requests/StoreLoanRequest.php create mode 100644 app/Http/Resources/LoanHistoryResource.php create mode 100644 app/Http/Resources/LoanProcessResource.php create mode 100644 app/Http/Resources/LoanResource.php create mode 100644 config/workflow-stages.php create mode 100644 database/seeders/BankFlowSeeder.php create mode 100644 routes/api.php create mode 100644 tests/Feature/Loan/CreateLoanTest.php create mode 100644 tests/Feature/Loan/GetLoanHistoryTest.php create mode 100644 tests/Feature/Loan/GetLoanTest.php create mode 100644 tests/Feature/Loan/HealthCheckTest.php create mode 100644 tests/Feature/Loan/ProcessLoanTest.php create mode 100644 tests/Unit/Domain/Loan/Workflow/CreditCheckStageTest.php create mode 100644 tests/Unit/Domain/Loan/Workflow/FraudCheckStageTest.php create mode 100644 tests/Unit/Domain/Loan/Workflow/GuarantorCheckStageTest.php create mode 100644 tests/Unit/Domain/Loan/Workflow/ManagerApprovalStageTest.php create mode 100644 tests/Unit/Domain/Loan/Workflow/ValidationStageTest.php diff --git a/app/Actions/Loan/CreateLoanAction.php b/app/Actions/Loan/CreateLoanAction.php new file mode 100644 index 0000000..9b9f353 --- /dev/null +++ b/app/Actions/Loan/CreateLoanAction.php @@ -0,0 +1,82 @@ +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; + } +} diff --git a/app/Actions/Loan/GetLoanAction.php b/app/Actions/Loan/GetLoanAction.php new file mode 100644 index 0000000..4697060 --- /dev/null +++ b/app/Actions/Loan/GetLoanAction.php @@ -0,0 +1,23 @@ +with(['loanType', 'currentStep.stageDefinition']) + ->where('public_id', $loanId) + ->first(); + + if ($loan === null) { + throw new LoanNotFoundException("Loan {$loanId} was not found."); + } + + return $loan; + } +} diff --git a/app/Actions/Loan/GetLoanHistoryAction.php b/app/Actions/Loan/GetLoanHistoryAction.php new file mode 100644 index 0000000..3e81c79 --- /dev/null +++ b/app/Actions/Loan/GetLoanHistoryAction.php @@ -0,0 +1,31 @@ + + */ + 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(); + } +} diff --git a/app/Actions/Loan/ProcessLoanAction.php b/app/Actions/Loan/ProcessLoanAction.php new file mode 100644 index 0000000..0dd68a2 --- /dev/null +++ b/app/Actions/Loan/ProcessLoanAction.php @@ -0,0 +1,38 @@ +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); + } +} diff --git a/app/Domain/Loan/Contracts/ConditionalStageInterface.php b/app/Domain/Loan/Contracts/ConditionalStageInterface.php new file mode 100644 index 0000000..b1e9d81 --- /dev/null +++ b/app/Domain/Loan/Contracts/ConditionalStageInterface.php @@ -0,0 +1,13 @@ + $rules + */ + public function appliesTo(Loan $loan, array $rules): bool; +} diff --git a/app/Domain/Loan/Contracts/StageInterface.php b/app/Domain/Loan/Contracts/StageInterface.php new file mode 100644 index 0000000..2cfbd4e --- /dev/null +++ b/app/Domain/Loan/Contracts/StageInterface.php @@ -0,0 +1,14 @@ + $rules + */ + public function execute(Loan $loan, array $rules): ExecutionResult; +} diff --git a/app/Domain/Loan/Data/ExecutionResult.php b/app/Domain/Loan/Data/ExecutionResult.php new file mode 100644 index 0000000..bdf7c2d --- /dev/null +++ b/app/Domain/Loan/Data/ExecutionResult.php @@ -0,0 +1,28 @@ +json(['error' => 'INVALID_REQUEST'], 400); + } +} diff --git a/app/Domain/Loan/Exceptions/InvalidWorkflowConfiguration.php b/app/Domain/Loan/Exceptions/InvalidWorkflowConfiguration.php new file mode 100644 index 0000000..1f27b41 --- /dev/null +++ b/app/Domain/Loan/Exceptions/InvalidWorkflowConfiguration.php @@ -0,0 +1,8 @@ +json(['error' => 'LOAN_NOT_FOUND'], 404); + } +} diff --git a/app/Domain/Loan/Exceptions/WorkflowException.php b/app/Domain/Loan/Exceptions/WorkflowException.php new file mode 100644 index 0000000..c1b4d9c --- /dev/null +++ b/app/Domain/Loan/Exceptions/WorkflowException.php @@ -0,0 +1,10 @@ + $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 $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; + } +} diff --git a/app/Domain/Loan/Workflow/Stages/FraudCheckStage.php b/app/Domain/Loan/Workflow/Stages/FraudCheckStage.php new file mode 100644 index 0000000..20ced36 --- /dev/null +++ b/app/Domain/Loan/Workflow/Stages/FraudCheckStage.php @@ -0,0 +1,45 @@ + $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 $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; + } +} diff --git a/app/Domain/Loan/Workflow/Stages/GuarantorCheckStage.php b/app/Domain/Loan/Workflow/Stages/GuarantorCheckStage.php new file mode 100644 index 0000000..095f193 --- /dev/null +++ b/app/Domain/Loan/Workflow/Stages/GuarantorCheckStage.php @@ -0,0 +1,22 @@ + $rules + */ + public function execute(Loan $loan, array $rules): ExecutionResult + { + if (! $loan->has_guarantor) { + return ExecutionResult::fail('GUARANTOR_REQUIRED'); + } + + return ExecutionResult::pass(); + } +} diff --git a/app/Domain/Loan/Workflow/Stages/ManagerApprovalStage.php b/app/Domain/Loan/Workflow/Stages/ManagerApprovalStage.php new file mode 100644 index 0000000..73f1d13 --- /dev/null +++ b/app/Domain/Loan/Workflow/Stages/ManagerApprovalStage.php @@ -0,0 +1,47 @@ + $rules + */ + public function appliesTo(Loan $loan, array $rules): bool + { + return $loan->amount > $this->positiveIntegerRule($rules, 'activationThreshold'); + } + + /** + * @param array $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 $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; + } +} diff --git a/app/Domain/Loan/Workflow/Stages/ValidationStage.php b/app/Domain/Loan/Workflow/Stages/ValidationStage.php new file mode 100644 index 0000000..b49fa3a --- /dev/null +++ b/app/Domain/Loan/Workflow/Stages/ValidationStage.php @@ -0,0 +1,42 @@ + $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(); + } +} diff --git a/app/Domain/Loan/Workflow/WorkflowConfigurationResolver.php b/app/Domain/Loan/Workflow/WorkflowConfigurationResolver.php new file mode 100644 index 0000000..05e5d9a --- /dev/null +++ b/app/Domain/Loan/Workflow/WorkflowConfigurationResolver.php @@ -0,0 +1,41 @@ +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; + } +} diff --git a/app/Domain/Loan/Workflow/WorkflowEngine.php b/app/Domain/Loan/Workflow/WorkflowEngine.php new file mode 100644 index 0000000..d4ae3d1 --- /dev/null +++ b/app/Domain/Loan/Workflow/WorkflowEngine.php @@ -0,0 +1,90 @@ +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(); + } + } +} diff --git a/app/Http/Controllers/Api/V1/LoanController.php b/app/Http/Controllers/Api/V1/LoanController.php new file mode 100644 index 0000000..7e84096 --- /dev/null +++ b/app/Http/Controllers/Api/V1/LoanController.php @@ -0,0 +1,40 @@ +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)); + } +} diff --git a/app/Http/Controllers/HealthCheckController.php b/app/Http/Controllers/HealthCheckController.php new file mode 100644 index 0000000..06155ad --- /dev/null +++ b/app/Http/Controllers/HealthCheckController.php @@ -0,0 +1,13 @@ +json(['status' => 'UP']); + } +} diff --git a/app/Http/Requests/StoreLoanRequest.php b/app/Http/Requests/StoreLoanRequest.php new file mode 100644 index 0000000..cc094a4 --- /dev/null +++ b/app/Http/Requests/StoreLoanRequest.php @@ -0,0 +1,59 @@ +> + */ + 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 + */ + 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.'); + } +} diff --git a/app/Http/Resources/LoanHistoryResource.php b/app/Http/Resources/LoanHistoryResource.php new file mode 100644 index 0000000..a70cf5d --- /dev/null +++ b/app/Http/Resources/LoanHistoryResource.php @@ -0,0 +1,22 @@ + + */ + public function toArray(Request $request): array + { + return [ + 'stage' => $this->stage_code->value, + 'result' => $this->result->value, + 'timestamp' => $this->executed_at->toIso8601ZuluString(), + 'reason' => $this->reason, + ]; + } +} diff --git a/app/Http/Resources/LoanProcessResource.php b/app/Http/Resources/LoanProcessResource.php new file mode 100644 index 0000000..d9e389c --- /dev/null +++ b/app/Http/Resources/LoanProcessResource.php @@ -0,0 +1,21 @@ + + */ + public function toArray(Request $request): array + { + return [ + 'loanId' => $this->public_id, + 'status' => $this->status->value, + 'currentStage' => $this->currentStep?->stageDefinition->code, + ]; + } +} diff --git a/app/Http/Resources/LoanResource.php b/app/Http/Resources/LoanResource.php new file mode 100644 index 0000000..a8bbed3 --- /dev/null +++ b/app/Http/Resources/LoanResource.php @@ -0,0 +1,30 @@ + + */ + 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(), + ]; + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 452e6b6..d3537bc 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,6 +2,8 @@ namespace App\Providers; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider @@ -19,6 +21,7 @@ class AppServiceProvider extends ServiceProvider */ public function boot(): void { - // + Model::preventLazyLoading(! app()->isProduction()); + JsonResource::withoutWrapping(); } } diff --git a/bootstrap/app.php b/bootstrap/app.php index 7a2848f..ea39400 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -8,8 +8,8 @@ use Illuminate\Http\Request; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', + api: __DIR__.'/../routes/api.php', commands: __DIR__.'/../routes/console.php', - health: '/up', ) ->withMiddleware(function (Middleware $middleware): void { // diff --git a/config/workflow-stages.php b/config/workflow-stages.php new file mode 100644 index 0000000..7d2fda1 --- /dev/null +++ b/config/workflow-stages.php @@ -0,0 +1,15 @@ + ValidationStage::class, + 'FRAUD_CHECK' => FraudCheckStage::class, + 'GUARANTOR_CHECK' => GuarantorCheckStage::class, + 'CREDIT_CHECK' => CreditCheckStage::class, + 'MANAGER_APPROVAL' => ManagerApprovalStage::class, +]; diff --git a/database/seeders/BankFlowSeeder.php b/database/seeders/BankFlowSeeder.php new file mode 100644 index 0000000..3db1572 --- /dev/null +++ b/database/seeders/BankFlowSeeder.php @@ -0,0 +1,136 @@ +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}> $steps + * @param array $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, + ]; + } +} diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index 78a8340..fab0288 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -14,8 +14,6 @@ class DatabaseSeeder extends Seeder */ public function run(): void { - if (app()->environment('local')) { - $this->call(BankFlowDevelopmentSeeder::class); - } + $this->call(BankFlowSeeder::class); } } diff --git a/routes/api.php b/routes/api.php new file mode 100644 index 0000000..c2f7bda --- /dev/null +++ b/routes/api.php @@ -0,0 +1,11 @@ +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'); +}); diff --git a/routes/web.php b/routes/web.php index 86a06c5..a52c803 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,7 +1,10 @@ name('health'); diff --git a/tests/Feature/ExampleTest.php b/tests/Feature/ExampleTest.php index 8fdc86b..826289c 100644 --- a/tests/Feature/ExampleTest.php +++ b/tests/Feature/ExampleTest.php @@ -3,5 +3,5 @@ test('the application returns a successful response', function () { $response = $this->get('/'); - $response->assertStatus(200); + $response->assertSuccessful(); }); diff --git a/tests/Feature/Loan/CreateLoanTest.php b/tests/Feature/Loan/CreateLoanTest.php new file mode 100644 index 0000000..894f156 --- /dev/null +++ b/tests/Feature/Loan/CreateLoanTest.php @@ -0,0 +1,62 @@ +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']); +}); diff --git a/tests/Feature/Loan/GetLoanHistoryTest.php b/tests/Feature/Loan/GetLoanHistoryTest.php new file mode 100644 index 0000000..f82e056 --- /dev/null +++ b/tests/Feature/Loan/GetLoanHistoryTest.php @@ -0,0 +1,28 @@ +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']); +}); diff --git a/tests/Feature/Loan/GetLoanTest.php b/tests/Feature/Loan/GetLoanTest.php new file mode 100644 index 0000000..96bea8a --- /dev/null +++ b/tests/Feature/Loan/GetLoanTest.php @@ -0,0 +1,33 @@ +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']); +}); diff --git a/tests/Feature/Loan/HealthCheckTest.php b/tests/Feature/Loan/HealthCheckTest.php new file mode 100644 index 0000000..f2686ed --- /dev/null +++ b/tests/Feature/Loan/HealthCheckTest.php @@ -0,0 +1,7 @@ +getJson('/health') + ->assertSuccessful() + ->assertExactJson(['status' => 'UP']); +}); diff --git a/tests/Feature/Loan/ProcessLoanTest.php b/tests/Feature/Loan/ProcessLoanTest.php new file mode 100644 index 0000000..46f5675 --- /dev/null +++ b/tests/Feature/Loan/ProcessLoanTest.php @@ -0,0 +1,128 @@ +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']); +}); diff --git a/tests/Pest.php b/tests/Pest.php index 2c5012c..63c5523 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1,6 +1,6 @@ extend(TestCase::class) - // ->use(RefreshDatabase::class) + ->use(LazilyRefreshDatabase::class) ->in('Feature'); /* @@ -44,7 +44,18 @@ expect()->extend('toBeOne', function () { | */ -function something() +/** + * @return array + */ +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); } diff --git a/tests/Unit/Domain/Loan/Workflow/CreditCheckStageTest.php b/tests/Unit/Domain/Loan/Workflow/CreditCheckStageTest.php new file mode 100644 index 0000000..0083134 --- /dev/null +++ b/tests/Unit/Domain/Loan/Workflow/CreditCheckStageTest.php @@ -0,0 +1,38 @@ +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); +}); diff --git a/tests/Unit/Domain/Loan/Workflow/FraudCheckStageTest.php b/tests/Unit/Domain/Loan/Workflow/FraudCheckStageTest.php new file mode 100644 index 0000000..3b93150 --- /dev/null +++ b/tests/Unit/Domain/Loan/Workflow/FraudCheckStageTest.php @@ -0,0 +1,18 @@ +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], +]); diff --git a/tests/Unit/Domain/Loan/Workflow/GuarantorCheckStageTest.php b/tests/Unit/Domain/Loan/Workflow/GuarantorCheckStageTest.php new file mode 100644 index 0000000..00414b0 --- /dev/null +++ b/tests/Unit/Domain/Loan/Workflow/GuarantorCheckStageTest.php @@ -0,0 +1,17 @@ +execute( + new Loan(['has_guarantor' => $hasGuarantor]), + [], + ); + + expect($result->type)->toBe($expected); +})->with([ + 'missing' => [false, StageResultType::Fail], + 'present' => [true, StageResultType::Pass], +]); diff --git a/tests/Unit/Domain/Loan/Workflow/ManagerApprovalStageTest.php b/tests/Unit/Domain/Loan/Workflow/ManagerApprovalStageTest.php new file mode 100644 index 0000000..46fa9de --- /dev/null +++ b/tests/Unit/Domain/Loan/Workflow/ManagerApprovalStageTest.php @@ -0,0 +1,34 @@ +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], +]); diff --git a/tests/Unit/Domain/Loan/Workflow/ValidationStageTest.php b/tests/Unit/Domain/Loan/Workflow/ValidationStageTest.php new file mode 100644 index 0000000..ecffd0b --- /dev/null +++ b/tests/Unit/Domain/Loan/Workflow/ValidationStageTest.php @@ -0,0 +1,46 @@ + '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'], +]);