-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathAgentBalanceMiddleware.php
More file actions
65 lines (55 loc) · 2.31 KB
/
Copy pathAgentBalanceMiddleware.php
File metadata and controls
65 lines (55 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
namespace App\Http\Middleware;
use App\Exceptions\AgentRiskBalanceExceeded;
use App\Exceptions\DownPaymentBiggerThanAmountException;
use App\Exceptions\DownPaymentNotFoundException;
use App\Exceptions\TransactionAmountNotFoundException;
use App\Models\AgentAssignedAppliances;
use App\Services\AgentAssignedApplianceService;
use App\Services\AgentService;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
class AgentBalanceMiddleware {
public function __construct(
private AgentService $agentService,
private AgentAssignedApplianceService $agentAssignedApplianceService,
) {}
/**
* Handle an incoming request.
*
* @param Request $request
*
* @return mixed
*/
public function handle($request, \Closure $next) {
$routeName = request()->route()->getName();
$agent = $this->agentService->getByAuthenticatedUser();
$commission = $agent->commission()->first();
$agentBalance = $agent->balance;
if ($routeName === 'agent-sell-appliance') {
$assignedApplianceCost = $this->agentAssignedApplianceService->getById($request->input('agent_assigned_appliance_id'));
$downPayment = $request->input('down_payment');
if (!$assignedApplianceCost instanceof AgentAssignedAppliances) {
throw new ModelNotFoundException('Assigned Appliance not found');
}
if (!isset($downPayment)) {
throw new DownPaymentNotFoundException('DownPayment not found');
}
$agentBalance -= $downPayment;
if ($assignedApplianceCost->cost < $request->input('down_payment')) {
throw new DownPaymentBiggerThanAmountException('Down payment is bigger than amount');
}
}
if (in_array($routeName, ['agent-transaction', 'agent-app-transaction'], true)) {
if ($transactionAmount = $request->input('amount')) {
$agentBalance -= $transactionAmount;
} else {
throw new TransactionAmountNotFoundException('Transaction amount not found');
}
}
if ($agentBalance < $commission->risk_balance) {
throw new AgentRiskBalanceExceeded('Risk balance exceeded');
}
return $next($request);
}
}