walletservice/app/Traits/Helper.php

233 lines
8.4 KiB
PHP

<?php
namespace App\Traits;
use App\Models\CountriesCurrency;
use App\Models\Country;
use App\Models\Identification;
use App\Models\Network;
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\PDOProvider;
use Brick\Money\ExchangeRateProvider\PDOProviderConfiguration;
use Brick\Money\ExchangeRateProvider\BaseCurrencyProvider;
use Brick\Money\Money;
use Brick\Math\RoundingMode;
use PDO;
use Illuminate\Support\Facades\DB;
use Psr\Http\Message\ResponseInterface;
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");
}
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();
}
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');
}
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)
{
$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;
}
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;
}
}