user-service/app/Traits/Helper.php

361 lines
12 KiB
PHP

<?php
namespace App\Traits;
use App\Exceptions\AppException;
use App\Models\CountriesCurrency;
use App\Models\Country;
use App\Models\Identification;
use App\Models\Network;
use Brick\Money\Context\AutoContext;
use Brick\Money\Money;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
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());
}
// 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);
}
}
/**
* @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;
}
function formatCustomerRequest($request){
if(!empty($request->opening_amount)) {
$request->opening_amount = $this->toMoneyWithNetwork($request->opening_amount,$request->network_id);
}
$request->status = __('states.'.$request->status);
}
}