• File: UserKyc.php
  • Full Path: /var/www/imaliapitest/app/Classes/UserKyc.php
  • Date Modified: 05/19/2025 4:29 PM
  • File size: 12.81 KB
  • MIME-type: text/x-php
  • Charset: utf-8
<?php

namespace App\Classes;

use App\Bank\Payment;
use App\Credelec;
use App\Imali\ImaliAccount;
use App\Imali\RechargeImaliAccount;
use App\Imali\Transfer;
use App\PurchaseVoucher;
use App\User;
use App\Water;
use App\Classes\PushNotification;
use App\WithdrawalsRequest;

class UserKyc
{
    private $user = null;
    private $push = null;

    public function __construct($user)
    {
        $this->user = $user;

        // $this->userIA = ImaliAccount::query()->where('user_id', $user_id)->first();

        // $this->user = ImaliAccount::query()
        //     ->join('imali_account_configs', 'imali_account_configs.id', 'imali_accounts.imali_account_config')
        //     ->where('user_id', $user_id)
        //     ->select('imali_account_configs.*')
        //     ->first();

        $this->push = new PushNotification('Erro de Restrição', '', '', $this->user->firebase_token);
    }

    public function checkSenderKYC($amount)
    {
        if ($this->validateAmount($amount)) return response()->json(['message' => 'Montante invalido'], 400);

        // todo ... verificar para transferencia e pagamentos
        // if ($amount < 10) return response()->json(['message' => 'Não podes transferir valores abaixo de 10MT'], 400);

        if ($this->checkNrTransactions()) {
            $this->push->setShortMsg($this->user->name . ' atingiu o limite diário');
            // $this->push->setLongMsg($this->user->name . ' atingiu o limite diário');
            $this->push->sendPush(array('sms' => $this->user->name . ' atingiu o limite diário'));
            return response()->json(['message' => $this->user->name . ' atingiu o limite diário'], 400);
        }

        if ($this->checkMaxValOperation($amount)) {
            $this->push->setShortMsg('O teu limite por transacção permite até ' . $this->user->max_value_operation . 'MT. Para transacionar valores acima deve submeter os teus documentos para actualização dos teus dados.');
            // $this->push->setLongMsg('O teu limite por transacção permite até ' . $this->user->max_value_operation . 'MT. Para transacionar valores acima deve submeter os teus documentos para actualização dos teus dados.');
            $this->push->sendPush(array('sms' => 'O teu limite por transacção permite até ' . $this->user->max_value_operation . 'MT. Para transacionar valores acima deve submeter os teus documentos para actualização dos teus dados.'));
            return response()->json(['message' => 'O teu limite por transacção permite até ' . $this->user->max_value_operation . 'MT.'], 400);
        }

        if ($this->checkMaxValueTransactionYear()) {
            $this->push->setShortMsg('Atingiu o limite anual de transancções');
            // $this->push->setLongMsg('Atingiu o limite anual de transancções');
            $this->push->sendPush(array('sms' => 'Atingiu o limite anual de transancções'));
            return response()->json(['message' => 'Atingiu o limite anual de transancções'], 400);
        }

        return response()->json(['message' => 'All test done successfuly!!!'], 200);
    }

    public function checkReceiverKYC($amount)
    {
        if ($this->validateAmount($amount)) return response()->json(['message' => 'Montante invalido'], 400);

        if ($this->checkMaxBalance($amount)) {
            $this->push->setShortMsg('A tua conta só permite saldo até ' . $this->user->max_balance . 'MT');
            // $this->push->setLongMsg('A tua conta só permite saldo até ' . $this->user->max_balance . 'MT');
            $this->push->sendPush(array('sms' => 'A tua conta só permite saldo até ' . $this->user->max_balance . 'MT'));
            return response()->json(['message' => 'A tua conta só permite saldo até ' . $this->user->max_balance . 'MT'], 400);
        }

        return response()->json(['message' => 'All test done successfuly!!!'], 200);
    }

    public function checkUserKYC($amount, $status_code = 400)
    {
        // todo -- adicionado 
        if ($amount < 100) return response()->json(['message' => 'Não podes carregar a tua conta com valores abaixo de 100MT'], 400);

        if ($this->validateAmount($amount)) return response()->json(['message' => 'Montante invalido'], 400);

        if ($this->checkNrTransactions()) {
            $this->push->setShortMsg($this->user->name . ' atingiu o limite diário');
            // $this->push->setLongMsg($this->user->name . ' atingiu o limite diário');
            $this->push->sendPush(array('sms' => $this->user->name . ' atingiu o limite diário'));
            return response()->json(['message' => $this->user->name . ' atingiu o limite diário'], 400);
        }

        if ($this->checkMaxValOperation($amount)) {
            $this->push->setShortMsg('O teu limite por transacção permite até ' . $this->user->max_value_operation . 'MT. Para transacionar valores acima deve submeter os teus documentos para actualização dos teus dados.');
            // $this->push->setLongMsg('O teu limite por transacção permite até ' . $this->user->max_value_operation . 'MT. Para transacionar valores acima deve submeter os teus documentos para actualização dos teus dados.');
            $this->push->sendPush(array('sms' => 'O teu limite por transacção permite até ' . $this->user->max_value_operation . 'MT. Para transacionar valores acima deve submeter os teus documentos para actualização dos teus dados.'));
            return response()->json(['message' => 'O teu limite por transacção permite até ' . $this->user->max_value_operation . 'MT.'], $status_code);
        }

        if ($this->checkMaxBalance($amount)) {
            $this->push->setShortMsg('A tua conta só permite saldo até ' . $this->user->max_balance . 'MT');
            // $this->push->setLongMsg('A tua conta só permite saldo até ' . $this->user->max_balance . 'MT');
            $this->push->sendPush(array('sms' => 'A tua conta só permite saldo até ' . $this->user->max_balance . 'MT'));
            return response()->json(['message' => 'A tua conta só permite saldo até ' . $this->user->max_balance . 'MT'], $status_code);
        }

        if ($this->checkMaxValueTransactionYear()) {
            $this->push->setShortMsg('Atingiu o limite anual de transancções');
            // $this->push->setLongMsg('Atingiu o limite anual de transancções');
            $this->push->sendPush(array('sms' => 'Atingiu o limite anual de transancções'));
            return response()->json(['message' => 'Atingiu o limite anual de transancções'], 400);
        }

        return response()->json(['message' => 'All test done successfuly!!!'], 200);
    }

    public function checkUserBalance($amount)
    {
        if ($this->validateAmount($amount)) return response()->json(['message' => 'Montante invalido'], 400);
        if ($this->checkBalance($amount)) return response()->json(['message' => 'Cliente iMali com saldo insuficiente'], 400);
        return response()->json(['message' => 'All test done successfuly!!!'], 200);
    }


    // todo --- 09 -May -2024
    public function checkUserCardBalance($amount)
    {
        if ($this->validateAmount($amount)) return response()->json(['message' => 'Montante invalido'], 400);
        if ($this->checkCardBalance($amount)) return response()->json(['message' => 'O cartão ' . $this->user->card_number . ' com saldo actual de ' . $this->user->balance . 'MT, somado ao montante de ' . $amount . 'MT a ser pago, ultrapassa o limite máximo de saldo de -500MT permitido para pagamento.'], 400);
        return response()->json(['message' => 'All test done successfuly!!!'], 200);
    }
    // todo --- 09 -May -2024

    /**
     * Retorna o numero total de transacoes do dia,
     * efectuados pelo utilizador. Dependendo do nivel de KYC.
     */

    private function getNrTransactions()
    {

        $payMent = Payment::query()->where('payments.sender_id', $this->user->id)
            ->whereDate('payments.created_at', 'LIKE', "%" . date('Y-m-d') . "%")
            ->get()->count();


        $credeleCT = Credelec::query()
            ->where('credelecs.user_id', $this->user->id)
            ->whereDate('credelecs.created_at', 'LIKE', "%" . date('Y-m-d') . "%")
            ->get()->count();


        $transferT = Transfer::query()
            ->where('transfers.sender_id', $this->user->id)
            ->whereDate('transfers.created_at', 'LIKE', "%" . date('Y-m-d') . "%")
            ->get()->count();

        $waterT = Water::query()
            ->where('waters.user_id', $this->user->id)
            ->whereDate('waters.created_at', 'LIKE', "%" . date('Y-m-d') . "%")
            ->get()->count();


        $voucherT = PurchaseVoucher::query()
            ->where('purchase_vouchers.user_id', $this->user->id)
            ->whereDate('purchase_vouchers.created_at', 'LIKE', "%" . date('Y-m-d') . "%")
            ->get()->count();


        // todo REVER ..
        // $rechargeT = RechargeImaliAccount::query()
        //     ->where('recharge_imali_accounts.imali_account_id', $this->userIA->id)
        //     ->whereDate('recharge_imali_accounts.created_at', 'LIKE', "%" . date('Y-m-d') . "%")
        //     ->get()->count();

        $rechargeT = RechargeImaliAccount::query()
            ->where('recharge_imali_accounts.imali_account_id', $this->user->account_id)
            ->whereDate('recharge_imali_accounts.created_at', 'LIKE', "%" . date('Y-m-d') . "%")
            ->get()->count();

        //? Novo
        $withDrawallsT = WithdrawalsRequest::query()
            ->where('withdrawals_requests.user_id', $this->user->id)
            ->whereDate('withdrawals_requests.created_at', 'LIKE', "%" . date('Y-m-d') . "%")
            ->get()->count();
        //? Novo

        return $payMent + $waterT + $credeleCT + $transferT + $voucherT + $rechargeT + $withDrawallsT;
        // return $payMent + $waterT + $credeleCT + $transferT + $voucherT + $withDrawallsT;
    }

    /**
     * Retorna o valor total de transacoes movimentadas por um determinado utilizador 
     * durante o ano, em todas transacoes iMali.
     * Excluindo os carregamentos.
     */
    private function getMaxValueYear()
    {

        $payMent = Payment::query()->where('payments.sender_id', $this->user->id)
            ->whereDate('payments.created_at', 'LIKE', "%" . date('Y') . "%")
            ->get()->sum('amount');


        $credeleCT = Credelec::query()
            ->where('credelecs.user_id', $this->user->id)
            ->whereDate('credelecs.created_at', 'LIKE', "%" . date('Y') . "%")
            ->get()->sum('amount');

        $transferT = Transfer::query()
            ->where('transfers.sender_id', $this->user->id)
            ->whereDate('transfers.created_at', 'LIKE', "%" . date('Y') . "%")
            ->get()->sum('amount');

        $waterT = Water::query()
            ->where('waters.user_id', $this->user->id)
            ->whereDate('waters.created_at', 'LIKE', "%" . date('Y') . "%")
            ->get()->sum('purchaseValue');

        $voucherT = PurchaseVoucher::query()
            ->where('purchase_vouchers.user_id', $this->user->id)
            ->whereDate('purchase_vouchers.created_at', 'LIKE', "%" . date('Y') . "%")
            ->get()->sum('vouchervalue');

        //? Novo
        $withDrawallsT = WithdrawalsRequest::query()
            ->where('withdrawals_requests.user_id', $this->user->id)
            ->whereDate('withdrawals_requests.created_at', 'LIKE', "%" . date('Y') . "%")
            ->get()->sum('total');
        //? Novo

        return $payMent + $waterT + $credeleCT + $transferT + $voucherT + $withDrawallsT;
    }


    private function checkMaxValOperation($amount)
    {
        if ($amount > $this->user->max_value_operation)  return true;
        return  false;
    }

    private function checkNrTransactions()
    {
        if ($this->getNrTransactions() >= $this->user->nr_transaction)  return true;
        return  false;
    }

    private function checkMaxBalance($amount)
    {

        $total_amount = $amount + $this->user->balance;
        if ($total_amount > $this->user->max_balance)  return true;
        return  false;
    }

    private function checkMaxValueTransactionYear()
    {
        if ($this->getMaxValueYear() > $this->user->max_value_year)  return true;
        return  false;
    }

    private function validateAmount($amount)
    {

        if (!is_numeric($amount)) return true;

        if ($amount <= 0) return true;

        return false;
    }

    private function checkBalance($amount)
    {
        if ($amount > $this->user->balance) return true;
        return false;
    }

    private function checkCardBalance($amount)
    {
        //  if ($this->user->balance < 0) {
        //      $total_amount = $this->user->balance - $amount;
        //      if ($total_amount < -500) return true;
        //      else return false;
        //  }

        //  return false;

        $total_amount = $this->user->balance - $amount;
        if (($total_amount < 0) && ($total_amount < -500)) return true;
        else return false;
    }
}