walletserviceExterne/app/Traits/Helper.php

339 lines
12 KiB
PHP

<?php
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\WalletIlinkTransaction;
use App\Models\WalletsUser;
use Brick\Math\RoundingMode;
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\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use PDO;
trait Helper
{
public function sendMail($email, $title, $messageText)
{
try{
$recipients = [preg_replace("/\s+/", "", $email)]; // Supprimer les espaces dans le mail
Mail::mailer('smtp')->raw($messageText, function ($message) use ($recipients, $title) {
$message->subject($title);
$message->to($recipients);
});
}catch (\Throwable $t){
Log::error('-------- Mail not sent -----------');
Log::error($t->getMessage());
}
// return $this->successResponse("mail envoye");
}
public function sendPushNotificationToUser($user_code, $message, $data = null, $date = null)
{
try{
$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;
try {
$body->date = ($date instanceof \DateTime) ? $date->format('Y-m-d H:i:s') : $date;
} catch (\Throwable $t) {
Log::error($t->getMessage());
$body->date = $date;
}
$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();
}catch (\Throwable $t){
Log::error('-------- User notification not sent-----------');
Log::error($t->getMessage());
}
}
public function sendPushNotificationToAgent($agent_code, $message, $data = null, $date = null)
{
try{
$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;
try {
$body->date = ($date instanceof \DateTime) ? $date->format('Y-m-d H:i:s') : $date;
} catch (\Throwable $t) {
Log::error($t->getMessage());
$body->date = $date;
}
$promise = $client->requestAsync('POST', '/onesignal/pushToAgent', ['json' => $body, 'headers' => $headers])->then();
$promise->wait();
}catch (\Throwable $t){
Log::error('-------- Agent notification not sent-----------');
Log::error($t->getMessage());
}
}
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;
}
public function hashSSHA($string)
{
$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)
{
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();
$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);
$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');
}
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
$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());
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 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')
{
// 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'));
$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());
return $converter->convert($init_money, $final_currency_code, RoundingMode::DOWN)->getAmount()->toFloat();
}
// public function getTransactionID(){
// $d = new DateTime();
// $first = str_replace(['-',':'], '',$d->format("y-m-d H:i:s.u"));
// return str_replace(' ' ,'.',$first);
// }
public function getCurrency($id_country)
{
$cc = CountriesCurrency::findOrFail($id_country);
return $cc->currency_code;
}
public function arrayPaginator($array, Request $request)
{
$page = $request->query('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;
}
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'));
else
return $identification;
} 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 generateTransactionCode($length = 12)
{
$characters = '23456789ABCDEFGHJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
// Fonction de tri par date
public function sortFunction($a, $b)
{
return strtotime($b->date_creation) - strtotime($a->date_creation);
}
// Obtenir l'heure en fonction du pays de l'utilisateur
public function getCurrentTime($id_country)
{
$country = Country::find($id_country);
$country_code = isset($country) ? $country->code_country : 'GA';
$timezone = \DateTimeZone::listIdentifiers(\DateTimeZone::PER_COUNTRY, $country_code);
$date = (sizeof($timezone) > 0) ? new \DateTime('now', new \DateTimeZone($timezone[0])) : new \DateTime();
return $date->format('Y-m-d H:i:s');
}
// Obtenir l'heure en fonction du code du pays de l'utilisateur
public function getCurrentTimeByCountryCode($country_code = 'GA')
{
$timezone = \DateTimeZone::listIdentifiers(\DateTimeZone::PER_COUNTRY, $country_code);
$date = (sizeof($timezone) > 0) ? new \DateTime('now', new \DateTimeZone($timezone[0])) : new \DateTime();
return $date->format('Y-m-d H:i:s');
}
}