465 lines
16 KiB
PHP
465 lines
16 KiB
PHP
<?php
|
|
|
|
|
|
namespace App\Traits;
|
|
|
|
|
|
use App\Exceptions\AppException;
|
|
use App\Models\Agent;
|
|
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 Barryvdh\DomPDF\Facade as PDF;
|
|
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 Exception;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\File;
|
|
use Illuminate\Support\Facades\Input;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Facades\Mail;
|
|
use Illuminate\Support\Str;
|
|
use PDO;
|
|
use Throwable;
|
|
|
|
trait Helper
|
|
{
|
|
public function sendMail($email, $title, $messageText)
|
|
{
|
|
if (config('variables.send_email')) {
|
|
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(app()->getLocale());
|
|
}
|
|
|
|
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(app()->getLocale());
|
|
}
|
|
|
|
public function toMoneyWithCurrencyCode($amount, $currency_code)
|
|
{
|
|
$money = Money::of(round($amount, 2), $currency_code, new AutoContext());
|
|
return $money->formatTo(app()->getLocale());
|
|
}
|
|
|
|
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(app()->getLocale());
|
|
}
|
|
|
|
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));
|
|
}
|
|
|
|
|
|
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');
|
|
}
|
|
|
|
// Verifier l'identification d'un utilisateur à partir de son id
|
|
|
|
/**
|
|
* @throws Exception
|
|
*/
|
|
public function checkUserIdentification($id_user)
|
|
{
|
|
$identification = Identification::where('id_user', $id_user)->first();
|
|
if (isset($identification)) {
|
|
if ($identification->status == 0)
|
|
throw new AppException(trans('errors.validation_user_identification_required'), 422);
|
|
else
|
|
return $identification;
|
|
} else {
|
|
throw new AppException(trans('errors.user_identification_required'), 422);
|
|
}
|
|
}
|
|
|
|
public function generateQRCode($user_id, $user_type)
|
|
{
|
|
if ($user_type == 'user') {
|
|
$user = User::findOrFail($user_id);
|
|
} else {
|
|
$user = Agent::findOrFail($user_id);
|
|
}
|
|
|
|
//Check if the directory already exists.
|
|
$directoryName = '/qrcodes/' . $user_type . 's/';
|
|
if (!is_dir(public_path() . $directoryName)) {
|
|
File::makeDirectory(public_path() . $directoryName, 0777, true);
|
|
}
|
|
|
|
$path = $directoryName . $user->id . '.pdf';
|
|
$pdf = PDF::loadView('emails.qr_code', ['lastname' => $user->lastname, 'data' => 'type=' . $user_type . '&user_id=' . $user->id])
|
|
->setPaper('a4', 'portrait')->setWarnings(false)->save(public_path($path));
|
|
|
|
$user->qr_code = config('app.url') . $path;
|
|
$user->save();
|
|
|
|
return $pdf;
|
|
}
|
|
|
|
/**
|
|
* @throws Exception
|
|
*/
|
|
public function validatePassword($password, $encrypted_password, $salt)
|
|
{
|
|
if (!$this->checkPassword($password, $encrypted_password, $salt)) {
|
|
throw new AppException(trans('messages.incorrect_user_password'), 422);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @throws AppException
|
|
*/
|
|
public function uploadImage(Request $request, $key, $imageCode, $folderName)
|
|
{
|
|
|
|
// if ($request->hasFile('image')) {
|
|
$original_filename = $request->file($key)->getClientOriginalName();
|
|
$original_filename_arr = explode('.', $original_filename);
|
|
$file_ext = end($original_filename_arr);
|
|
$image = $imageCode . '-' . Str::uuid() . '.' . $file_ext;
|
|
|
|
//Check if the directory already exists.
|
|
$directoryName = './' . $folderName;
|
|
if (!is_dir($directoryName)) {
|
|
//Directory does not exist, so lets create it.
|
|
mkdir($directoryName, 0755);
|
|
}
|
|
|
|
// Allow certain file formats
|
|
// $allowTypes = array('jpg', 'png', 'jpeg', 'gif');
|
|
// if (in_array(strtolower($file_ext), $allowTypes)) {
|
|
|
|
$compressedImage = $this->compressImage($request->file($key), './' . $folderName . '/' . $image, 70);
|
|
if ($compressedImage) {
|
|
return url($folderName . '/' . $image);
|
|
} else {
|
|
throw new AppException(trans('errors.compression_failed'));
|
|
}
|
|
// } else {
|
|
// return $this->errorResponse('Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.');
|
|
// }
|
|
|
|
// } else {
|
|
// return $this->errorResponse('File not found');
|
|
// }
|
|
|
|
}
|
|
|
|
|
|
|
|
public function deleteImageFile($filename, $folderName)
|
|
{
|
|
// unlink(storage_path('./'.$folderName.'/' . $filename));
|
|
$path = './' . $folderName . '/' . $filename;
|
|
if (File::exists($path))
|
|
File::delete($path);
|
|
}
|
|
|
|
/*
|
|
* Custom function to compress image size and
|
|
* upload to the server using PHP
|
|
*/
|
|
public function compressImage($source, $destination, $quality)
|
|
{
|
|
// Get image info
|
|
$imgInfo = getimagesize($source);
|
|
$mime = $imgInfo['mime'];
|
|
|
|
// Create a new image from file
|
|
switch ($mime) {
|
|
case 'image/jpeg':
|
|
$image = imagecreatefromjpeg($source);
|
|
break;
|
|
case 'image/png':
|
|
$image = imagecreatefrompng($source);
|
|
break;
|
|
case 'image/gif':
|
|
$image = imagecreatefromgif($source);
|
|
break;
|
|
default:
|
|
$image = imagecreatefromjpeg($source);
|
|
}
|
|
|
|
// Save image
|
|
imagejpeg($image, $destination, $quality);
|
|
|
|
// Return compressed image
|
|
return $destination;
|
|
}
|
|
|
|
}
|