walletservice/app/Traits/Helper.php

384 lines
15 KiB
PHP
Raw Normal View History

<?php
namespace App\Traits;
use App\Models\AgentPlus;
use App\Models\CodeGenerer;
use App\Models\ConfigWallet;
2020-06-25 08:01:59 +00:00
use App\Models\CountriesCurrency;
use App\Models\Country;
2020-08-17 12:22:40 +00:00
use App\Models\Identification;
use App\Models\InfosUsersGroup;
2020-07-08 16:51:11 +00:00
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;
2020-06-25 19:06:43 +00:00
use Brick\Money\Context\AutoContext;
use Brick\Money\CurrencyConverter;
use Brick\Money\ExchangeRateProvider\BaseCurrencyProvider;
use Brick\Money\ExchangeRateProvider\PDOProvider;
use Brick\Money\ExchangeRateProvider\PDOProviderConfiguration;
use Brick\Money\Money;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use PDO;
trait Helper
{
public function sendMail($email, $title, $messageText)
{
$recipients = [$email];
Mail::mailer('smtp')->raw($messageText, function ($message) use ($recipients, $title) {
$message->subject($title);
$message->to($recipients);
});
// return $this->successResponse("mail envoye");
}
2020-08-06 06:21:41 +00:00
public function sendPushNotificationToUser($user_code, $message, $data = null)
{
$client = new \GuzzleHttp\Client([
'base_uri' => env('NOTIFICATION_SERVICE_URL'),
]);
$headers = [
'Authorization' => env('NOTIFICATION_SERVICE_KEY'),
];
$body = new \stdClass();
$body->user_code = $user_code;
$body->message = $message;
$body->data = $data;
$promise = $client->requestAsync('POST', '/onesignal/pushToUser', ['json' => $body, 'headers' => $headers])->then();
// function (ResponseInterface $res) {
// echo $res->getStatusCode() . "\n";
// },
// function (RequestException $e) {
// echo $e->getMessage() . "\n";
// echo $e->getRequest()->getMethod();
// }
// );
$promise->wait();
// return $response->getBody()->getContents();
}
2020-08-24 16:29:50 +00:00
public function sendPushNotificationToAgent($agent_code, $message, $data = null)
{
$client = new \GuzzleHttp\Client([
'base_uri' => env('NOTIFICATION_SERVICE_URL'),
]);
$headers = [
'Authorization' => env('NOTIFICATION_SERVICE_KEY'),
];
$body = new \stdClass();
$body->agent_code = $agent_code;
$body->message = $message;
$body->data = $data;
$promise = $client->requestAsync('POST', '/onesignal/pushToAgent', ['json' => $body, 'headers' => $headers])->then();
$promise->wait();
}
public function checkPassword($password, $encrypted_password, $salt)
{
$encrypted_password_to_check = base64_encode(sha1($password . $salt, true) . $salt);
return $encrypted_password_to_check == $encrypted_password;
}
2020-06-19 18:33:10 +00:00
public function hashSSHA($string)
{
2020-06-19 18:33:10 +00:00
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($string . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
public function getCountryName($id_country)
{
return Country::findOrFail($id_country)->name;
}
public function getNetworkName($id_network)
{
2020-07-08 16:51:11 +00:00
return Network::findOrFail($id_network)->name;
}
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();
2020-08-24 16:29:50 +00:00
$money = Money::of(round($amount, 2), $currency ? $currency->code : 'XAF', new AutoContext());
return $money->formatTo('fr_FR');
}
public function toMoney($amount, $id_country)
{
$country = Country::findOrFail($id_country);
2020-08-24 16:29:50 +00:00
$money = Money::of(round($amount, 2), $country->currency->code, new AutoContext());
return $money->formatTo('fr_FR');
}
public function toMoneyWithCurrencyCode($amount, $currency_code)
{
$money = Money::of(round($amount, 2), $currency_code, new AutoContext());
return $money->formatTo('fr_FR');
}
2020-08-24 16:29:50 +00:00
private function convertMoney($amount, $init_country, $final_country)
{
// set to whatever your rates are relative to
$baseCurrency = 'USD';
// use your own credentials, or re-use your existing PDO connection
2020-08-24 16:29:50 +00:00
$pdo = new PDO('mysql:host=' . env('DB_HOST') . ';dbname=' . env('DB_DATABASE'), env('DB_USERNAME'), env('DB_PASSWORD'));
$configuration = new PDOProviderConfiguration();
$configuration->tableName = 'exchange_rate';
$configuration->exchangeRateColumnName = 'exchange_rate';
$configuration->targetCurrencyColumnName = 'target_currency';
$configuration->sourceCurrencyCode = $baseCurrency;
// this provider loads exchange rates from your database
$provider = new PDOProvider($pdo, $configuration);
// this provider calculates exchange rates relative to the base currency
$provider = new BaseCurrencyProvider($provider, $baseCurrency);
// this currency converter can now handle any currency pair
$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());
2020-06-25 08:01:59 +00:00
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');
2020-06-25 08:01:59 +00:00
}
public function toMoneyAmount($amount, $init_country, $final_country)
{
return $this->convertMoney($amount, $init_country, $final_country)->getAmount()->toFloat();
2020-06-25 08:01:59 +00:00
}
2020-06-24 07:36:54 +00:00
public function toUSDAmount($amount, $init_country, $final_currency_code = 'USD')
{
2020-06-29 16:46:43 +00:00
// 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'));
2020-06-29 16:46:43 +00:00
$configuration = new PDOProviderConfiguration();
$configuration->tableName = 'exchange_rate';
$configuration->exchangeRateColumnName = 'exchange_rate';
$configuration->targetCurrencyColumnName = 'target_currency';
$configuration->sourceCurrencyCode = $baseCurrency;
// this provider loads exchange rates from your database
$provider = new PDOProvider($pdo, $configuration);
// this provider calculates exchange rates relative to the base currency
$provider = new BaseCurrencyProvider($provider, $baseCurrency);
// 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());
2020-06-29 16:46:43 +00:00
return $converter->convert($init_money, $final_currency_code, RoundingMode::DOWN)->getAmount()->toFloat();
}
2020-07-06 16:09:25 +00:00
// public function getTransactionID(){
// $d = new DateTime();
// $first = str_replace(['-',':'], '',$d->format("y-m-d H:i:s.u"));
// return str_replace(' ' ,'.',$first);
// }
2020-06-24 07:36:54 +00:00
public function getCurrency($id_country)
{
2020-06-25 08:01:59 +00:00
$cc = CountriesCurrency::findOrFail($id_country);
return $cc->currency_code;
}
2020-07-17 13:48:50 +00:00
public function arrayPaginator($array, $request)
{
$page = Input::get('page', 1);
$perPage = 10;
$offset = ($page * $perPage) - $perPage;
return new LengthAwarePaginator(array_slice($array, $offset, $perPage, true), count($array), $perPage, $page,
['path' => $request->url(), 'query' => $request->query()]);
}
public function array_has_dupes($array)
{
// streamline per @Felix
return count($array) !== count(array_unique($array));
}
//Calcul des taxes
public function calculateTax(array $taxes, $frais)
{
$sommeTaux = 0;
$sommeFixe = 0;
foreach ($taxes as $tax) {
if ($tax->type == '%')
$sommeTaux += $tax->valeur;
if ($tax->type == 'fixe')
$sommeFixe += $tax->valeur;
}
return ($frais * $sommeTaux / 100) + $sommeFixe;
}
2020-08-17 12:22:40 +00:00
public function checkMyIdentification($id)
{
$identification = Identification::where('id_user', $id)->first();
if (isset($identification)) {
if ($identification->status == 0)
return $this->errorResponse(trans('errors.validation_identification_required'));
2020-08-19 18:46:52 +00:00
else
return $identification;
2020-08-17 12:22:40 +00:00
} else {
return $this->errorResponse(trans('errors.identification_required'));
}
}
public function generateGroupCode($length = 8)
{
$characters = '23456789ABCDEFGHJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
public function refundAllNanoCredit()
{
2020-09-28 19:04:07 +00:00
// \Log::info('cron refund credit --');
$credits = UsersDemandesCredit::where('etat', 'VALIDE')->where('date_remboursement_prevu', '<=', Carbon::today())->get();
foreach ($credits as $demande_credit) {
2020-09-28 19:04:07 +00:00
// \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);
2020-09-28 19:04:07 +00:00
// \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);
}
}
}