From 5f2d68a7daabc2e0738ff185670f4df9672679a4 Mon Sep 17 00:00:00 2001 From: Djery-Tom Date: Mon, 28 Sep 2020 16:39:57 +0100 Subject: [PATCH] + Automatic reimbursement of credit requests at midnight + Regulations limits --- app/Console/Kernel.php | 9 +- app/Http/Controllers/HelperController.php | 21 ++- app/Http/Controllers/NanoCreditController.php | 9 +- .../iLinkTransactionController.php | 109 +++++++++-- app/Models/Country.php | 25 ++- app/Models/Regulation.php | 40 ++++ app/Models/UsersDemandesCredit.php | 6 + app/Traits/Helper.php | 171 +++++++++++++++--- resources/lang/en/errors.php | 6 +- resources/lang/en/messages.php | 2 + resources/lang/fr/errors.php | 6 +- resources/lang/fr/messages.php | 5 +- 12 files changed, 350 insertions(+), 59 deletions(-) create mode 100644 app/Models/Regulation.php diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index ad6e311..106bbf9 100755 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -2,11 +2,14 @@ namespace App\Console; +use App\Traits\Helper; use Illuminate\Console\Scheduling\Schedule; use Laravel\Lumen\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { + use Helper; + /** * The Artisan commands provided by your application. * @@ -24,6 +27,10 @@ class Kernel extends ConsoleKernel */ protected function schedule(Schedule $schedule) { - // + // Tache cron s'execute tous les jours a minuit + $schedule->call(function () { + $this->refundAllNanoCredit(); + })->dailyAt('00:00')->runInBackground(); +// })->everyMinute()->runInBackground(); } } diff --git a/app/Http/Controllers/HelperController.php b/app/Http/Controllers/HelperController.php index e5c0473..0733057 100755 --- a/app/Http/Controllers/HelperController.php +++ b/app/Http/Controllers/HelperController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers; +use App\Jobs\TestJob; use App\Models\ConfigWallet; use App\Models\Country; use App\Models\NetworksAgent; @@ -17,6 +18,7 @@ class HelperController extends Controller { use ApiResponser; use Helper; + /** * Create a new controller instance. * @@ -104,15 +106,18 @@ class HelperController extends Controller public function init(){ //Mettre a jour tous les utilisateurs qui n'ont pas de wallet iLink $users = User::whereNull('user_code')->orWhere('user_code','')->get(); - foreach ($users as $user){ - do{ - $user_code=$this->generateUserCode(); - $result = collect(DB::select('SELECT * FROM users WHERE user_code = :code',['code'=>$user_code])); - $codeCorrect=sizeof($result)<0; - }while($codeCorrect); + foreach ($users as $user) { + do { + $user_code = $this->generateUserCode(); + $result = collect(DB::select('SELECT * FROM users WHERE user_code = :code', ['code' => $user_code])); + $codeCorrect = sizeof($result) < 0; + } while ($codeCorrect); $user->user_code = $user_code; - DB::insert('INSERT INTO wallets_users (idUser) VALUES (?);', [$user->id]); - $user->save(); + $wallet = WalletsUser::where('idUser', $user->id)->first(); + if (!$wallet) { + DB::insert('INSERT INTO wallets_users (idUser) VALUES (?);', [$user->id]); + $user->save(); + } } return $this->successResponse('OK :-) , Have a nice day dear ! '); } diff --git a/app/Http/Controllers/NanoCreditController.php b/app/Http/Controllers/NanoCreditController.php index fc3268f..699c7c3 100755 --- a/app/Http/Controllers/NanoCreditController.php +++ b/app/Http/Controllers/NanoCreditController.php @@ -8,6 +8,7 @@ use App\Models\ConfigWallet; use App\Models\Identification; use App\Models\InfosUsersGroup; use App\Models\NetworksAgent; +use App\Models\User; use App\Models\UsersDemandesCredit; use App\Models\UsersEpargne; use App\Models\UsersGroup; @@ -18,8 +19,6 @@ use App\Models\WalletsUser; use App\Traits\ApiResponser; use App\Traits\Helper; use Illuminate\Http\Request; -use App\Models\User; -use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\DB; class NanoCreditController extends Controller @@ -235,7 +234,7 @@ class NanoCreditController extends Controller $user_country = $user->network->country->id; if ($user_country != $agent_country) - return $this->errorResponse('errors.operation_cannot_performed_in_country'); + return $this->errorResponse(trans('errors.operation_cannot_performed_in_country')); $montant_total = $demande_credit->montant + $demande_credit->interet + $demande_credit->taxe; @@ -288,7 +287,6 @@ class NanoCreditController extends Controller ]); $user = User::findOrFail($request->id_user); - $group = InfosUsersGroup::findOrFail($user->group_id); if (!$this->checkPassword($request->password, $user->encrypted_password, $user->salt)) return $this->errorResponse(trans('messages.incorrect_user_password')); @@ -338,8 +336,9 @@ class NanoCreditController extends Controller } if ($demande_credit->type_caution == 'groupe') { - // Recuperation des wallets hyperviseur et superviseur + $group = InfosUsersGroup::findOrFail($user->group_id); + // Recuperation des wallets hyperviseur et superviseur $walletHyper = WalletAgent::where('category', 'hyper')->where('network_id', $group->id_network)->firstOrFail(); $walletHyper = Wallet::findOrFail($walletHyper->wallet_id); diff --git a/app/Http/Controllers/iLinkTransactionController.php b/app/Http/Controllers/iLinkTransactionController.php index fb69449..32469cd 100755 --- a/app/Http/Controllers/iLinkTransactionController.php +++ b/app/Http/Controllers/iLinkTransactionController.php @@ -9,21 +9,20 @@ use App\Models\Country; use App\Models\Identification; use App\Models\NetworksAgent; use App\Models\PayingNetwork; +use App\Models\Regulation; use App\Models\TypeIlinkTransaction; -use App\Models\PaliersConfigWallet; use App\Models\User; use App\Models\Wallet; use App\Models\WalletAgent; use App\Models\WalletIlinkTransaction; use App\Models\WalletsUser; -use App\Models\WalletTransaction; use App\Traits\ApiResponser; use App\Traits\Helper; +use Carbon\Carbon; +use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Facades\DB; -use function DeepCopy\deep_copy; -use function GuzzleHttp\Promise\all; class iLinkTransactionController extends Controller { @@ -128,11 +127,21 @@ class iLinkTransactionController extends Controller $this->validate($request, $transaction->send_wallet_wallet_rules()); $user = $walletUser->user; if ($this->checkPassword($request->password, $user->encrypted_password, $user->salt)) { - if($init_country != $request->final_country) - return $this->checkUserIdentification($user->id); + if ($init_country != $request->final_country) { + $rep = $this->checkUserIdentification($user->id); +// dd($rep); + if ($rep instanceof JsonResponse) + return $rep; + } + if ($request->montant > $walletUser->balance) { return $this->errorResponse(trans('errors.insufficient_balance')); } else { + //Verification des limites reglementaires + $rep = $this->checkReguationsLimits($walletUser->id, $init_country, $transaction->montant); + if ($rep instanceof JsonResponse) + return $rep; + $transaction->frais = $frais = ($init_country != $request->final_country) ? $this->calculateFees($plr_user_wallet_wallet, $request->montant) : $this->calculateFees($plr_user_wallet_wallet_national, $request->montant); $transaction->taxe = $taxe = ($init_country != $request->final_country) ? $this->calculateTax($taxesInternationales, $frais) : $this->calculateTax($taxesNationales, $frais); $transaction->montant_net = $montantDepot = $transaction->montant - $frais - $taxe; @@ -272,11 +281,20 @@ class iLinkTransactionController extends Controller $this->validate($request, $transaction->send_wallet_cash_rules()); $user = $walletUser->user; if ($this->checkPassword($request->password, $user->encrypted_password, $user->salt)) { - if($init_country != $request->final_country) - return $this->checkUserIdentification($user->id);; + if ($init_country != $request->final_country) { + $rep = $this->checkUserIdentification($user->id); + if ($rep instanceof JsonResponse) + return $rep; + } + if ($request->montant > $walletUser->balance) { return $this->errorResponse(trans('errors.insufficient_balance')); } else { + //Verification des limites reglementaires + $rep = $this->checkReguationsLimits($walletUser->id, $init_country, $transaction->montant); + if ($rep instanceof JsonResponse) + return $rep; + $transaction->frais = $frais = ($init_country != $request->final_country) ? $this->calculateFees($plr_user_wallet_cash, $request->montant) : $this->calculateFees($plr_user_wallet_cash_national, $request->montant); $transaction->taxe = $taxe = ($init_country != $request->final_country) ? $this->calculateTax($taxesInternationales, $frais) : $this->calculateTax($taxesNationales, $frais); $transaction->montant_net = $montantRetrait = $transaction->montant - $frais - $taxe; @@ -364,7 +382,10 @@ class iLinkTransactionController extends Controller if ($request->montant > $walletUser->balance) { return $this->errorResponse(trans('errors.insufficient_balance')); } else { - return $this->checkUserIdentification($user->id);; + $rep = $this->checkUserIdentification($user->id); + if ($rep instanceof JsonResponse) + return $rep; + $transaction->final_country = $init_country; $transaction->frais = $frais = $this->calculateFees($plr_user_wallet_cash_national, $request->montant); $transaction->taxe = $taxe = $this->calculateTax($taxesNationales, $frais); @@ -463,7 +484,9 @@ class iLinkTransactionController extends Controller $this->validate($request, $transaction->user_card_rules()); $user = $walletUser->user; if ($this->checkPassword($request->password, $user->encrypted_password, $user->salt)) { - return $this->checkUserIdentification($user->id);; + $rep = $this->checkUserIdentification($user->id); + if ($rep instanceof JsonResponse) + return $rep; if (!(isset($user->numero_carte) && isset($user->expiration_date))) return $this->errorResponse(trans('errors.no_bank_card_attached')); @@ -479,7 +502,7 @@ class iLinkTransactionController extends Controller $body['cvv'] = $request->cvv; // $body['expiry_date'] = $user->expiration_date->format('Y-m'); $body['expiry_date'] = $user->expiration_date->format('m/y'); - $body['amount'] = $montantDepot; + $body['amount'] = $montantRetrait; $identification = Identification::where('id_user', $user->id)->first(); $body['cardholder_name'] = $identification ? $identification->lastname . ' ' . $identification->firstname : $user->lastname . ' ' . $user->firstname; //"John Smith" ; $body['currency'] = $this->getCurrency($init_country); @@ -688,6 +711,11 @@ class iLinkTransactionController extends Controller $walletUser = WalletsUser::where('idUser', $user->id)->firstOrFail(); $transaction->final_country = $final_country = $user->network->country->id; + //Verification des limites reglementaires + $rep = $this->checkReguationsLimits($walletUser->id, $init_country, $transaction->montant); + if ($rep instanceof JsonResponse) + return $rep; + $frais = ($init_country != $final_country) ? $this->calculateFees($plr_agent_depot_wallet_ilink, $request->montant) : $this->calculateFees($plr_agent_depot_wallet_ilink_national, $request->montant); $taxe = ($init_country != $final_country) ? $this->calculateTax($taxesInternationales, $frais) : $this->calculateTax($taxesNationales, $frais); $montantDepot = $request->montant - $frais - $taxe; @@ -735,6 +763,12 @@ class iLinkTransactionController extends Controller if ($this->checkPassword($request->password, $agent->encrypted_password, $agent->salt)) { if ($request->montant > $walletAgent->balance_princ) return $this->errorResponse(trans('errors.insufficient_balance')); + + //Verification des limites reglementaires + $rep = $this->checkReguationsLimits($request->id_document_emetteur, $init_country, $transaction->montant, true); + if ($rep instanceof JsonResponse) + return $rep; + $frais = ($init_country != $request->final_country) ? $this->calculateFees($plr_agent_depot_autre_wallet, $request->montant) : $this->calculateFees($plr_agent_depot_autre_wallet_national, $request->montant); $taxe = ($init_country != $request->final_country) ? $this->calculateTax($taxesInternationales, $frais) : $this->calculateTax($taxesNationales, $frais); $montantDepot = $request->montant - $frais - $taxe; @@ -865,6 +899,12 @@ class iLinkTransactionController extends Controller if ($this->checkPassword($request->password, $agent->encrypted_password, $agent->salt)) { if ($request->montant > $walletAgent->balance_princ) return $this->errorResponse(trans('errors.insufficient_balance')); + + //Verification des limites reglementaires + $rep = $this->checkReguationsLimits($request->id_document_emetteur, $init_country, $transaction->montant, true); + if ($rep instanceof JsonResponse) + return $rep; + $frais = ($init_country != $request->final_country) ? $this->calculateFees($plr_agent_cash_cash, $request->montant) : $this->calculateFees($plr_agent_cash_cash_national, $request->montant); $taxe = ($init_country != $request->final_country) ? $this->calculateTax($taxesInternationales, $frais) : $this->calculateTax($taxesNationales, $frais); $montantRetrait = $request->montant - $frais - $taxe; @@ -1370,4 +1410,51 @@ class iLinkTransactionController extends Controller return $this->successResponse(trans('messages.canceled_transaction')); } + //Verfier les limites reglementaires + public function checkReguationsLimits($identifiant, $init_country, $montant_transaction, $is_id_document_emetteur = false) + { + + $regulation = Regulation::where('id_country', $init_country)->first(); + + if (!$regulation) + return; + + // Total montants journalier + if ($is_id_document_emetteur) + $daily_sum = WalletIlinkTransaction::where('id_document_emetteur', $identifiant)->whereDate('date', Carbon::today())->sum('montant'); + else + $daily_sum = WalletIlinkTransaction::where('id_wallet_user', $identifiant)->whereDate('date', Carbon::today())->sum('montant'); + $amount_admitted = $regulation->montant_max_jour - $daily_sum; +// dd(($daily_sum + $montant_transaction) > $regulation->montant_max_jour); + if (($daily_sum + $montant_transaction) > $regulation->montant_max_jour) + return $this->errorResponse(trans('errors.daily_regulations_limits_reached') . '\n' + . ($amount_admitted > 0 ? trans('errors.regulations_limits_amount_transaction', ['amount' => $this->toMoney($amount_admitted, $init_country)]) : '')); + + // Total montants hebdomadaire +// To set the week start/end: +// Carbon::setLocale('en_US'); // Set week to start on Sunday +// Carbon::setWeekStartsAt(Carbon::SUNDAY); +// Carbon::setWeekEndsAt(Carbon::SATURDAY); + if ($is_id_document_emetteur) + $weekly_sum = WalletIlinkTransaction::where('id_document_emetteur', $identifiant)->whereBetween('date', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->sum('montant'); + else + $weekly_sum = WalletIlinkTransaction::where('id_wallet_user', $identifiant)->whereBetween('date', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->sum('montant'); + $amount_admitted = $regulation->montant_max_hedbo - $weekly_sum; + if (($weekly_sum + $montant_transaction) > $regulation->montant_max_hebdo) + return $this->errorResponse(trans('errors.weekly_regulations_limits_reached') . '\n' + . ($amount_admitted > 0 ? trans('errors.regulations_limits_amount_transaction', ['amount' => $this->toMoney($amount_admitted, $init_country)]) : '')); + + + // Total montants mensuel + if ($is_id_document_emetteur) + $monthly_sum = WalletIlinkTransaction::where('id_document_emetteur', $identifiant)->whereBetween('date', [Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()])->sum('montant'); + else + $monthly_sum = WalletIlinkTransaction::where('id_wallet_user', $identifiant)->whereBetween('date', [Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()])->sum('montant'); + $amount_admitted = $regulation->montant_max_mensuel - $monthly_sum; + if (($monthly_sum + $montant_transaction) > $regulation->montant_max_mensuel) + return $this->errorResponse(trans('errors.monthly_regulations_limits_reached') . '\n' + . ($amount_admitted > 0 ? trans('errors.regulations_limits_amount_transaction', ['amount' => $this->toMoney($amount_admitted, $init_country)]) : '')); + + } + } diff --git a/app/Models/Country.php b/app/Models/Country.php index 4fac39b..9ea8a80 100755 --- a/app/Models/Country.php +++ b/app/Models/Country.php @@ -11,7 +11,7 @@ use Illuminate\Database\Eloquent\Model; /** * Class Country - * + * * @property int $id * @property string $code_dial * @property string $name @@ -19,7 +19,7 @@ use Illuminate\Database\Eloquent\Model; * @property float $longitude * @property float $latitude * @property int $idCurrency - * + * * @property Currency $currency * @property Collection|Admin[] $admins * @property Collection|ConfigGame[] $config_games @@ -63,13 +63,18 @@ class Country extends Model return $this->hasMany(ConfigGame::class, 'id_pays'); } - public function identifications() - { - return $this->hasMany(Identification::class); - } + public function identifications() + { + return $this->hasMany(Identification::class); + } - public function wallet_ilink_transactions() - { - return $this->hasMany(WalletIlinkTransaction::class, 'final_country'); - } + public function wallet_ilink_transactions() + { + return $this->hasMany(WalletIlinkTransaction::class, 'final_country'); + } + + public function regulation() + { + return $this->belongsTo(Regulation::class, 'id_country'); + } } diff --git a/app/Models/Regulation.php b/app/Models/Regulation.php new file mode 100644 index 0000000..f9098cd --- /dev/null +++ b/app/Models/Regulation.php @@ -0,0 +1,40 @@ + 'int', + 'montant_max_jour' => 'float', + 'montant_max_hebdo' => 'float', + 'montant_max_mensuel' => 'float' + ]; + + protected $fillable = [ + 'id_country', + 'montant_max_jour', + 'montant_max_hebdo', + 'montant_max_mensuel' + ]; +} diff --git a/app/Models/UsersDemandesCredit.php b/app/Models/UsersDemandesCredit.php index 5c6bfa0..bc31996 100644 --- a/app/Models/UsersDemandesCredit.php +++ b/app/Models/UsersDemandesCredit.php @@ -15,6 +15,8 @@ use Illuminate\Database\Eloquent\Model; * @property int $id * @property string $id_demande * @property float $montant + * @property float $montant_rembourse + * @property bool partiellement_rembourse; * @property int $duree_mois * @property string $type_caution * @property string $etat @@ -38,6 +40,8 @@ class UsersDemandesCredit extends Model protected $casts = [ 'montant' => 'float', + 'montant_rembourse' => 'float', + 'partiellement_rembourse' => 'bool', 'duree_mois' => 'int', 'interet' => 'float', 'taxe' => 'float', @@ -57,6 +61,8 @@ class UsersDemandesCredit extends Model protected $fillable = [ 'id_demande', 'montant', + 'montant_rembourse', + 'partiellement_rembourse', 'duree_mois', 'type_caution', 'etat', diff --git a/app/Traits/Helper.php b/app/Traits/Helper.php index 89984be..ff510bf 100644 --- a/app/Traits/Helper.php +++ b/app/Traits/Helper.php @@ -4,24 +4,31 @@ namespace App\Traits; +use App\Models\AgentPlus; +use App\Models\CodeGenerer; +use App\Models\ConfigWallet; use App\Models\CountriesCurrency; use App\Models\Country; use App\Models\Identification; +use App\Models\InfosUsersGroup; use App\Models\Network; +use App\Models\NetworksAgent; +use App\Models\User; +use App\Models\UsersDemandesCredit; +use App\Models\Wallet; +use App\Models\WalletAgent; +use App\Models\WalletsUser; +use Brick\Math\RoundingMode; use Brick\Money\Context\AutoContext; -use Brick\Money\Context\CustomContext; -use DateTime; -use GuzzleHttp\Exception\RequestException; -use Illuminate\Support\Facades\Mail; use Brick\Money\CurrencyConverter; +use Brick\Money\ExchangeRateProvider\BaseCurrencyProvider; use Brick\Money\ExchangeRateProvider\PDOProvider; use Brick\Money\ExchangeRateProvider\PDOProviderConfiguration; -use Brick\Money\ExchangeRateProvider\BaseCurrencyProvider; use Brick\Money\Money; -use Brick\Math\RoundingMode; -use PDO; +use Carbon\Carbon; use Illuminate\Support\Facades\DB; -use Psr\Http\Message\ResponseInterface; +use Illuminate\Support\Facades\Mail; +use PDO; trait Helper { @@ -92,17 +99,20 @@ trait Helper return $hash; } - public function getCountryName($id_country){ + public function getCountryName($id_country) + { return Country::findOrFail($id_country)->name; } - public function getNetworkName($id_network){ + public function getNetworkName($id_network) + { return Network::findOrFail($id_network)->name; } - public function toMoneyWithNetwork($amount , $id_network){ + public function toMoneyWithNetwork($amount, $id_network) + { $currency = collect(DB::select('SELECT cu.code FROM networks n INNER JOIN countries c ON c.id = n.country_id INNER JOIN currencies cu ON cu.id = c.idCurrency - WHERE n.id = :id',['id'=>$id_network]))->first(); + WHERE n.id = :id', ['id' => $id_network]))->first(); $money = Money::of(round($amount, 2), $currency ? $currency->code : 'XAF', new AutoContext()); return $money->formatTo('fr_FR'); @@ -146,24 +156,27 @@ trait Helper $converter = new CurrencyConverter($provider); $init_country = Country::findOrFail($init_country); $final_country = Country::findOrFail($final_country); - $init_money = Money::of(round($amount, 2),$init_country->currency->code,new AutoContext()); + $init_money = Money::of(round($amount, 2), $init_country->currency->code, new AutoContext()); return $converter->convert($init_money, $final_country->currency->code, RoundingMode::DOWN); } - public function toMoneyWithCurrency($amount , $init_country , $final_country){ - return $this->convertMoney($amount , $init_country , $final_country)->formatTo('fr_FR'); + public function toMoneyWithCurrency($amount, $init_country, $final_country) + { + return $this->convertMoney($amount, $init_country, $final_country)->formatTo('fr_FR'); } - public function toMoneyAmount($amount , $init_country , $final_country){ - return $this->convertMoney($amount , $init_country , $final_country)->getAmount()->toFloat(); + public function toMoneyAmount($amount, $init_country, $final_country) + { + return $this->convertMoney($amount, $init_country, $final_country)->getAmount()->toFloat(); } - public function toUSDAmount($amount , $init_country , $final_currency_code = 'USD'){ + public function toUSDAmount($amount, $init_country, $final_currency_code = 'USD') + { // set to whatever your rates are relative to $baseCurrency = 'USD'; // use your own credentials, or re-use your existing PDO connection - $pdo = new PDO('mysql:host=' .env('DB_HOST') . ';dbname=' .env('DB_DATABASE'), env('DB_USERNAME'), env('DB_PASSWORD')); + $pdo = new PDO('mysql:host=' . env('DB_HOST') . ';dbname=' . env('DB_DATABASE'), env('DB_USERNAME'), env('DB_PASSWORD')); $configuration = new PDOProviderConfiguration(); @@ -181,7 +194,7 @@ trait Helper // this currency converter can now handle any currency pair $converter = new CurrencyConverter($provider); $init_country = Country::findOrFail($init_country); - $init_money = Money::of(round($amount, 2),$init_country->currency->code,new AutoContext()); + $init_money = Money::of(round($amount, 2), $init_country->currency->code, new AutoContext()); return $converter->convert($init_money, $final_currency_code, RoundingMode::DOWN)->getAmount()->toFloat(); } @@ -192,7 +205,8 @@ trait Helper // return str_replace(' ' ,'.',$first); // } - public function getCurrency($id_country){ + public function getCurrency($id_country) + { $cc = CountriesCurrency::findOrFail($id_country); return $cc->currency_code; } @@ -251,4 +265,119 @@ trait Helper } return $randomString; } + + public function refundAllNanoCredit() + { + \Log::info('cron refund credit --'); + + $credits = UsersDemandesCredit::where('etat', 'VALIDE')->where('date_remboursement_prevu', '<=', Carbon::today())->get(); + foreach ($credits as $demande_credit) { + \Log::info('Init credit ' . $demande_credit->id_demande); + +// $refundDate = $demande_credit->date_remboursement_prevu; +// //Compare la date de remboursement prevu à celle d'aujourd'hui +// $today = (new DateTime())->format('Y-m-d'); +// $expiry = (new DateTime($refundDate))->format('Y-m-d'); +// +// if(isset($refundDate) && (strtotime($today) >= strtotime($expiry))){ + //Reprise de la methode de remboursement + + $user = User::findOrFail($demande_credit->id_user); + $walletUser = WalletsUser::where('idUser', $demande_credit->id_user)->firstOrFail(); + + $this->refundNanoCredit($demande_credit, $user, $walletUser); + \Log::info('Nano credit refunded ' . $demande_credit->id_demande); + +// } + } + } + + public function refundNanoCredit(UsersDemandesCredit $demande_credit, User $user, WalletsUser $walletUser) + { + + $init_country = $user->network->country->id; + + $montantDejaRembourse = $demande_credit->montant_rembourse; + $montantCreditRestant = $user->balance_credit; + + $montantARembourser = ($montantCreditRestant > $walletUser->balance) ? $walletUser->balance : $montantCreditRestant; + + $quota = $montantARembourser / ($montantDejaRembourse + $montantCreditRestant); + + + if ($quota == 0) { + // Solde egale zero donc pas de remboursement + $this->sendMail($user->email, trans('messages.failed_nano_credit_refunded'), trans('messages.reload_your_account')); + } else { + $partialRefund = false; + + $user->balance_credit -= $montantARembourser; + $walletUser->balance -= $montantARembourser; + $demande_credit->montant_rembourse += $montantARembourser; + + $resteARembourser = $user->balance_credit; + if ($resteARembourser == 0) + $demande_credit->etat = 'REMBOURSE'; + else { + $partialRefund = true; + $demande_credit->partiellement_rembourse = true; + } + + if ($demande_credit->type_caution == 'individuel') { + // Repartition des interet entre agents + + $walletAgent = Wallet::findOrFail($demande_credit->id_wallet_agent); + $network_agent = NetworksAgent::findOrFail($walletAgent->id_networkAgent); + + $config = ConfigWallet::where('id_network', $network_agent->network_id)->firstOrFail(); + + // Recuperation des wallets hyperviseur et superviseur + $codeGenerer = CodeGenerer::findOrFail($network_agent->codeGenerer_id); + $superviseur = AgentPlus::where('code_membre', $codeGenerer->code_parrain)->firstOrFail(); + $hyperviseur = AgentPlus::where('code_membre', $superviseur->code_parrain)->firstOrFail(); + + $wallet_agent_sup = WalletAgent::where('agent_id', $superviseur->id)->firstOrFail(); + $wallet_agent_hyp = WalletAgent::where('agent_id', $hyperviseur->id)->firstOrFail(); + $walletSuperviseur = Wallet::findOrFail($wallet_agent_sup->wallet_id); + $walletHyperviseur = Wallet::findOrFail($wallet_agent_hyp->wallet_id); + + $walletAgent->balance_com += floatval($demande_credit->interet * $quota * $config->taux_com_ag_nano_credit / 100); + $walletSuperviseur->balance_com += floatval($demande_credit->interet * $quota * $config->taux_com_sup_nano_credit / 100); + $walletHyperviseur->balance_com += floatval($demande_credit->interet * $quota * $config->taux_com_hyp_nano_credit / 100); + + $walletAgent->save(); + $walletSuperviseur->save(); + $walletHyperviseur->save(); + } + + if ($demande_credit->type_caution == 'groupe') { + // Recuperation des wallets hyperviseur et superviseur + $group = InfosUsersGroup::findOrFail($user->group_id); + + $walletHyper = WalletAgent::where('category', 'hyper')->where('network_id', $group->id_network)->firstOrFail(); + $walletHyper = Wallet::findOrFail($walletHyper->wallet_id); + + $walletHyper->balance_princ += $montantARembourser * $quota; + $walletHyper->balance_com += $demande_credit->interet * $quota; + $walletHyper->save(); + } + + $demande_credit->date_remboursement = new \DateTime(); + $demande_credit->montant = $resteARembourser; + + $walletUser->save(); + $user->save(); + $demande_credit->save(); + + $message = trans('messages.successful_nano_credit_demand_refunded', + ['id_demand' => $demande_credit->id_demande, 'amount' => $this->toMoney($montantARembourser, $init_country), 'duration' => $demande_credit->duree_mois, + 'net' => $this->toMoney($montantARembourser * $quota, $init_country), 'fees' => $this->toMoney($demande_credit->interet * $quota, $init_country), + 'tax' => $this->toMoney($demande_credit->taxe * $quota, $init_country), + 'caution' => $demande_credit->type_caution == 'groupe' ? 'Groupe' : 'Individuel']); + + $this->sendMail($user->email, (!$partialRefund) ? trans('messages.successful_nano_credit_refunded') : + trans('messages.successful_nano_credit_partially_refunded'), $message); + } + + } } diff --git a/resources/lang/en/errors.php b/resources/lang/en/errors.php index 1ddad03..b8ecdda 100755 --- a/resources/lang/en/errors.php +++ b/resources/lang/en/errors.php @@ -58,5 +58,9 @@ Paying network : :network :country', "savings_already_broken" => "Savings already broken", "group_not_allow_to_borrow" => "The group is not allowed to borrow", "borrowing_capacity_exceeded" => "The borrowing capacity is exceeded", - "savings_not_found" => "This savings does not exist" + "savings_not_found" => "This savings does not exist", + "regulations_limits_amount_transaction" => "You can make a transaction of :amount .", + "daily_regulations_limits_reached" => "You have reached your daily limit.", + "weekly_regulations_limits_reached" => "You have reached your weekly limit.", + "monthly_regulations_limits_reached" => "You have reached your monthly limit.", ]; diff --git a/resources/lang/en/messages.php b/resources/lang/en/messages.php index 13345c7..324d70d 100755 --- a/resources/lang/en/messages.php +++ b/resources/lang/en/messages.php @@ -209,6 +209,7 @@ Request Information: NB: The reimbursement process is automatic on the due date if the reimbursement is not initiated", 'successful_guarantee_nano_credit_demand' => 'Guaranteed nanocredit request', 'successful_nano_credit_refunded' => 'Nano credit repayment made', + 'successful_nano_credit_partially_refunded' => 'Partially completed nano credit automatic repayment', 'successful_nano_credit_demand_refunded' => "Nano credit refunded Request Information: - Request number: :id_demand @@ -242,4 +243,5 @@ Savings Information : - Taxes : :tax - Net amount saved : :net", "successful_broken_saving" => "Broken savings", + "reload_your_account" => "Reload your account", ]; diff --git a/resources/lang/fr/errors.php b/resources/lang/fr/errors.php index 4d7f6e8..41e943c 100755 --- a/resources/lang/fr/errors.php +++ b/resources/lang/fr/errors.php @@ -58,5 +58,9 @@ Réseau payeur : :network :country', "savings_already_broken" => "Épargne déjà cassée", "group_not_allow_to_borrow" => "Le groupe n'a pas le droit d'emprunter", "borrowing_capacity_exceeded" => "La capacité d'emprunt est dépassée", - "savings_not_found" => "Cette épargne n'existe pas" + "savings_not_found" => "Cette épargne n'existe pas", + "regulations_limits_amount_transaction" => "Vous pouvez effectuer une transaction de :amount .", + "daily_regulations_limits_reached" => "Vous avez atteint votre limite journalière.", + "weekly_regulations_limits_reached" => "Vous avez atteint votre limite hebdomadaire.", + "monthly_regulations_limits_reached" => "Vous avez atteint votre limite mensuelle.", ]; diff --git a/resources/lang/fr/messages.php b/resources/lang/fr/messages.php index c00f700..a473c21 100755 --- a/resources/lang/fr/messages.php +++ b/resources/lang/fr/messages.php @@ -200,7 +200,7 @@ Informations de la demande : - Montant du crédit : :amount - Intérêts : :fees - Taxes : :tax - - Montant net à percu : :net + - Montant net à percevoir : :net - Duréé (en mois) : :duration - Date de remboursement : :date - Noms du client : :user_name @@ -209,6 +209,8 @@ Informations de la demande : NB: Le processus de remboursement est automatique à la date d'échéance si le remboursement n'est pas initié", 'successful_guarantee_nano_credit_demand' => 'Demande de nano crédit cautionnée', 'successful_nano_credit_refunded' => 'Remboursement de nano crédit effectué', + 'successful_nano_credit_partially_refunded' => 'Remboursement automatique de nano crédit partiellement effectué', + 'failed_nano_credit_refunded' => 'Remboursement automatique de nano crédit échoué', 'successful_nano_credit_demand_refunded' => "Nano crédit remboursé Informations de la demande : - Numéro de la demande : :id_demand @@ -244,4 +246,5 @@ Informations sur l'epargne : - Montant net epargné : :net ", "successful_broken_saving" => "Epargne cassée", + "reload_your_account" => "Rechargez votre compte", ];