Files
repo-backend/app/Http/Controllers/Admin/LoanController.php
T

113 lines
3.4 KiB
PHP

<?php
namespace App\Http\Controllers\Admin;
use App\Loan;
use App\UsersWallet;
use App\AccountLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class LoanController extends Controller
{
public function index()
{
return view('manages.loan.index');
}
public function list(Request $request)
{
$limit = $request->input('limit', 20);
$status = $request->input('status', '');
$query = Loan::query()
->leftJoin('users', 'loan.user_id', '=', 'users.id')
->select('loan.*', 'users.phone as user_phone', 'users.email as user_email', 'users.account_number');
if ($status !== '') {
$query->where('loan.status', $status);
}
$keyword = $request->input('keyword');
if ($keyword) {
$query->where(function ($q) use ($keyword) {
$q->where('loan.user_id', $keyword)
->orWhere('users.phone', 'like', "%{$keyword}%")
->orWhere('users.email', 'like', "%{$keyword}%");
});
}
$data = $query->orderBy('loan.id', 'desc')->paginate($limit);
return $this->layuiData($data);
}
public function approve(Request $request)
{
$id = $request->input('id');
$loan = Loan::find($id);
if (!$loan) return $this->error('Loan not found');
if ($loan->status != 0) return $this->error('Loan already processed');
DB::beginTransaction();
try {
$wallet = UsersWallet::where('user_id', $loan->user_id)
->where('currency', 3)->lockForUpdate()->first();
if (!$wallet) {
DB::rollBack();
return $this->error('User wallet not found');
}
$before = $wallet->legal_balance;
$wallet->legal_balance = bc_add($wallet->legal_balance, $loan->amount, 6);
$wallet->save();
AccountLog::insertLog(
[
'user_id' => $loan->user_id,
'value' => $loan->amount,
'created_time' => time(),
'info' => 'Loan Approved - ' . $loan->institution,
'type' => AccountLog::USER_LOAN_ORDER_BUY,
'currency' => 3,
],
[
'balance_type' => 1,
'wallet_id' => $wallet->id,
'lock_type' => 0,
'before' => $before,
'change' => $loan->amount,
'after' => $wallet->legal_balance,
'create_time' => time(),
]
);
$loan->status = 1;
$loan->update_time = now();
$loan->save();
DB::commit();
return $this->success('Loan approved');
} catch (\Exception $e) {
DB::rollBack();
return $this->error('Error: ' . $e->getMessage());
}
}
public function reject(Request $request)
{
$id = $request->input('id');
$remark = $request->input('remark', '');
$loan = Loan::find($id);
if (!$loan) return $this->error('Loan not found');
if ($loan->status != 0) return $this->error('Loan already processed');
$loan->status = 2;
$loan->remark = $remark;
$loan->update_time = now();
$loan->save();
return $this->success('Loan rejected');
}
}