/
home
/
corsairdevelopme
/
public_html
/
amplivo-console
/
app
/
Helpers
/
Upload File
HOME
<?php use App\Models\BV; use App\Models\CsrRedemptionSetting; use App\Models\Member; use App\Models\CSRNow\LoginUserUddid; use App\Models\UserTeamsiteLicense; use App\Services\BigNumber; use Carbon\Carbon; use App\Models\Cart; use App\Models\CSRNow\City; use App\Models\User; use App\Mail\FaReset; use App\Models\CSRNow\State; use App\Models\CSRNow\Country; use App\Models\GiftCode; use App\Models\Purchase; use App\Models\WalletLog; use App\Jobs\SendEmailJob; use App\Models\ApiSettings; use App\Models\CSRNow\Language as CSRNowLanguage; use Illuminate\Support\Arr; use Illuminate\Support\Str; use App\Models\CurrencyRate; use App\Models\SiteConfiguration; use App\Models\Wallet; use App\Models\ShortUrl; use App\Models\EmailSwitches; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use Illuminate\Encryption\Encrypter; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Cache; use App\Models\CurrencyRedemptionRate; use App\Models\EmailManagement; use App\Models\MachineFootPrint; use App\Models\UserSetting; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Notification; use Illuminate\Contracts\Encryption\DecryptException; use Spatie\Permission\Models\Role; use App\Models\Activity; use App\Models\WalletLogDRY; use App\Models\UserQualificationLog; use App\Models\Customer; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Cookie; if (!function_exists('uploadImage')) { function uploadImage($file, $path) { $name = uniqid() . '.' . $file->getClientOriginalExtension(); $destinationPath = public_path() . $path; $file->move($destinationPath, $name); return $path . $name; } } if (!function_exists('uploadFile')) { function uploadFile($file, string $path = '') { $name = uniqid() . '.' . $file->getClientOriginalExtension(); $destinationPath = public_path() . '/' . $path; $file->move($destinationPath, $name); return $name; } } if (!function_exists('uploadFileSupportAdmin')) { function uploadFileSupportAdmin($file, string $path = '') { $name = uniqid() . '.' . $file->getClientOriginalExtension(); $destinationPath = config('app.SUPPORT_ADMIN_PUBLIC_PATH') . $path; $file->move($destinationPath, $name); return $name; } } if (!function_exists('locals')) { function locals() { return CSRNowLanguage::all(); } } if (!function_exists('getClassName')) { function getClassName($class) { $arr = preg_split('/(?=[A-Z])/', class_basename($class)); array_shift($arr); array_pop($arr); return implode(' ', $arr); } } if (!function_exists('reportLog')) { /** * @param $exception */ function reportLog($exception) { if (is_string($exception)) { Log::channel('abuse')->info($exception); } else { Log::channel('abuse')->info($exception->getMessage()); } } } if (!function_exists('diffForHumans')) { function diffForHumans($date) { return Carbon::parse($date)->diffForHumans(); } } if (!function_exists('formatRole')) { function formatRole($argument): string { return ucwords(str_replace('-', ' ', $argument)); } } if (!function_exists('singleImageUploadHandler')) { function singleImageUploadHandler($request, $filename, $uploadedFile = '', $uniqueKey = '', $location = '') { $fileNameToStore = $request->hasFile($uploadedFile); if ($request->hasFile($uploadedFile)) { //Get file from client side $file = $request->file($uploadedFile); $extension = $file->getClientOriginalExtension(); $fileFormat = strtolower('/' . $filename . '-' . $uniqueKey) . '.' . $extension; $fileNameToStore = $location . str_replace(' ', '-', $fileFormat); // Store in Storage Filesystem Storage::disk('local_public')->putFileAs($location, $file, $fileFormat); } return $fileNameToStore; } } if (!function_exists('singleImageUpdateHandler')) { function singleImageUpdateHandler($request, $filename, $dbFilename, $uploadedFile = '', $uniqueKey = '', $location = '') { $fileNameToStore = $dbFilename; if ($request->hasFile($uploadedFile)) { // delete old image first if (Storage::disk('local_public')->exists($dbFilename)) { Storage::disk('local_public')->delete($dbFilename); } //Get file from client side $file = $request->file($uploadedFile); $extension = $file->getClientOriginalExtension(); $fileFormat = strtolower('/' . $filename . '-' . $uniqueKey) . '.' . $extension; $fileNameToStore = $location . str_replace(' ', '-', $fileFormat); // Store in Storage Filesystem Storage::disk('local_public')->putFileAs($location, $file, $fileFormat); } return $fileNameToStore; } } if (!function_exists('activeGuard')) { /** * check active auth guard */ function activeGuard() { foreach (array_keys(config('auth.guards')) as $guard) { if (auth()->guard($guard)->check()) { return $guard; } } return null; } } if (!function_exists('saveLog')) { function saveLog($log, $performedOn, $property = [], $logName = "", $causedBy = null) { $request = request(); $role = Auth::user() && isset(Auth::user()->roles[0]->name) ? Auth::user()->roles[0]->name : ''; $property['logged_by'] = $role; if (empty($causedBy)) { if (Auth::check()) { $causedBy = Auth::user(); } else { if ($performedOn) { $causedBy = $performedOn; } else { $causedBy = User::first(); } } } $lastLoggedActivity = activity($logName) ->withProperties($property) ->causedBy($causedBy) ->performedOn($performedOn ?? User::first()) ->log($log); if (empty($lastLoggedActivity->log_name) && empty($lastLoggedActivity->event)) { $lastLoggedActivity->log_name = $logName; $lastLoggedActivity->event = $logName; $lastLoggedActivity->save(); } $lastLoggedActivity->ip_address = getClientIp($request); $lastLoggedActivity->save(); } } if (!function_exists('setFieldName')) { /** * transform field name * @param $fieldName * * @return string */ function setFieldName($fieldName) { return ucwords(str_replace('_', ' ', $fieldName)); } } /** * This function will truncate tables without foreign key check */ if (!function_exists('truncateTables')) { /** * @param array $toTruncate */ function truncateTables(array $toTruncate) { DB::statement('SET FOREIGN_KEY_CHECKS=0;'); foreach ($toTruncate as $table) { DB::table($table)->truncate(); } DB::statement('SET FOREIGN_KEY_CHECKS=1;'); } } if (!function_exists('days')) { function days() { return [1, 7, 15, 30, 60, 90, 120, 180, 360]; } } if (!function_exists('checkAuthModel')) { function checkAuthModel(array $models, $email) { $data = []; foreach ($models as $model) { $data[] = $model::where('email', $email)->first(); } return collect(Arr::flatten(Arr::whereNotNull($data)))->first(); } } if (!function_exists('getClientIp')) { /** * @param $request * * @return mixed */ function getClientIp($request = null) { $ip = session('user_ip'); return $ip; } } /** * BootstrapTable * * This is a callback function to replace date-time with new format */ if (!function_exists('arrayReplacingDateTime')) { function arrayReplacingDateTime(&$item, $key) { if (!is_null($item)) { if ($key == 'created_at' || $key == 'updated_at' || $key == 'deleted_at') { $item = Carbon::parse($item)->format('d-m-Y h:i:s a'); } } } } if (!function_exists('getSiteSettings')) { function getSiteSettings($key) { $adminSettings = Cache::rememberForever('AdminSettings', function () { return SiteConfiguration::get()->pluck('value', 'key'); })->toArray(); if (isset($adminSettings[$key])) { return $adminSettings[$key]; } return ""; } } if (!function_exists('createOrUpdateSiteSettings')) { function createOrUpdateSiteSettings($key, $value) { if (SiteConfiguration::where('key', $key)->exists()) { SiteConfiguration::where('key', $key)->update(['value' => $value]); } else { SiteConfiguration::create(['key' => $key, 'value' => $value]); } Cache::forget("AdminSettings"); } } if (!function_exists('maskToken')) { function maskToken($token) { return substr($token, 0, 6) . ' ...... ' . substr($token, -6); } } if (!function_exists('resetUser2FA')) { function resetUser2FA($id) { $user = User::find($id); $user->google_auth_key = ""; $user->fa_setting = [null]; $user->fa3_setting = [null]; $user->save(); $details = [ 'email' => $user->email, 'name' => $user->name, 'subject' => '2FA reset successfully', ]; $emailSwitch = getEmailSettings('fa_enable_disable'); if ($emailSwitch == 'on') { $emailClassRef = new FaReset($details); SendEmailJob::dispatch($user->email, $emailClassRef); } saveLog("2FA reset by " . Auth::user()->name . " for user {$user->name}", Auth::user(), [], "users-management"); return true; } } /** * Custom carbon instance * * This function will return human friendly date format */ if (!function_exists('diffHumanCustom')) { /** * @param $date * @return string */ function diffHumanCustom($date) { if (Carbon::parse($date)->diffInSeconds(Carbon::now()) < 59) { return 'just now'; } elseif (Carbon::parse($date)->diffInWeeks(Carbon::now()) < 1) { return Carbon::parse($date)->diffForHumans(); } return Carbon::parse($date)->diffForHumans(['parts' => 2, 'join' => ', ']); } } /** * Custom encryption for javascript * * This function will return encrypted data with key pair */ if (!function_exists('laravelEncrypt')) { /** * @param $data * @return array */ function laravelEncrypt($data): array { $key = Encrypter::generateKey(config('app.cipher')); $newEncrypted = new Encrypter($key, config('app.cipher')); $encryptedData['encrypted'] = $newEncrypted->encryptString($data); $encryptedData['key'] = base64_encode($key); return $encryptedData; } } if (!function_exists('laravelDecrypt')) { /** * @param $encrypted * @return string */ function laravelDecrypt($encrypted): string { $converted = json_decode(base64_decode($encrypted), true); $data = $converted['encrypted']; $key = base64_decode($converted['key']); $newEncrypter = new Encrypter($key, config('app.cipher')); return $newEncrypter->decryptString($data); } } /** * Custom encryption for javascript * * This function will return encrypted data with key pair */ if (!function_exists('basicEncrypt')) { /** * @param $data * @return string */ function basicEncrypt($data): string { return encrypt($data); } } if (!function_exists('basicDecrypt')) { /** * @param $encrypted * @return string */ function basicDecrypt($encrypted): string { try { return decrypt($encrypted); } catch (DecryptException $e) { reportLog($e); return ""; } } } if (!function_exists('generateNumericOTP')) { function generateNumericOTP($otpLength = 6) { $generator = "1357902468"; $result = ""; for ($index = 1; $index <= $otpLength; $index++) { $result .= substr($generator, (rand() % (strlen($generator))), 1); } return $result; } } if (!function_exists('readOnlyMode')) { function readOnlyMode(): bool { return Session::has('readOnlyMode'); } } if (!function_exists('getParticularCountry')) { function getParticularCountry($id) { return Country::where(['is_active' => 1, 'id' => $id])->first(); } } if (!function_exists('getCountry')) { function getCountry() { return Country::where('is_active', 1)->get(); } } if (!function_exists('getState')) { function getState($countryId) { return State::where('country_id', $countryId)->orderBy('name', 'asc')->get(); } } if (!function_exists('getCity')) { function getCity($stateId) { return City::where('state_id', $stateId)->orderBy('name', 'asc')->get(); } } if (!function_exists('getIdentifyDataFromExternal')) { function getIdentifyDataFromExternal(array $data = []) { $url = config('amplivo.external_configuration.get_url') . '?email=' . $data['email']; $response = Http::get($url); $output = $response->json(); if ($output) { return json_decode($output); } return false; } } if (!function_exists('storeIdentifyDataToExternal')) { function storeIdentifyDataToExternal($data = []) { Http::post(config('amplivo.external_configuration.store_url'), $data); } } if (!function_exists('readCSVFile')) { function readCSVFile($filePath, string $delimiter = ',') { if (!file_exists($filePath) || !is_readable($filePath)) { return false; } $header = null; $records = []; if (($handle = fopen($filePath, 'r')) !== false) { while (($row = fgetcsv($handle, 1000, $delimiter)) !== false) { if (!$header) { $header = $row; } else { if (count($row) == count($header)) { $records[] = array_combine($header, $row); } } } fclose($handle); } return [ 'header' => $header, 'records' => $records, ]; } } if (!function_exists('filterArray')) { function filterArray($needle, $haystack) { foreach ($haystack as $v) { if (stripos($v, $needle) !== false) { return true; } } return false; } } if (!function_exists('clearCache')) { function clearCache() { Artisan::call('cache:clear'); Artisan::call('config:clear'); Artisan::call('config:cache'); Artisan::call('view:clear'); } } if (!function_exists('createFromFormatCustom')) { function createFromFormatCustom(&$date, $formatting = false): mixed { try { $date = $formatting ? Carbon::createFromFormat(config('amplivo.date_configuration.to_date_format'), $date)->format(config('amplivo.date_configuration.to_date_format')) : Carbon::createFromFormat(config('amplivo.date_configuration.to_date_format'), $date)->toDateString(); } catch (Exception $exception) { reportLog($exception); } return $date; } } /** * CheckcheckEmailValidation */ if (!function_exists('checkEmailValidation')) { function checkEmailValidation() { return 'required|email:rfc,dns'; } } if (!function_exists('dateCustom')) { function dateCustom($date, $formatting = true) { try { if (!$date) return '-'; $date = $formatting ? Carbon::parse($date)->format(config('amplivo.date_configuration.to_date_format')) : Carbon::parse($date); } catch (Exception $exception) { reportLog($exception); } return $date; } } if (!function_exists('gateRate')) { function gateRate($wallet) { $cid = CurrencyRedemptionRate::WALLET_TYPE[$wallet] ?? 1; return CurrencyRate::where('currency_id', $cid)->first()->rate ?? 0; } } if (!function_exists('distributeBonus')) { function distributeBonus($user, $bonus, $wallets, $attributes = [], $ratecheck = false) { // For every wallet a new wallet_log entry is created. foreach ($wallets as $type => $parameters) { $action = $parameters[0]; $multiplier = $parameters[1]; $value = $bonus * $multiplier; if ($ratecheck) { $value = $value * gateRate($action); } Log::info("Type $type V $value P1 $action P2 $multiplier"); $wid = Wallet::firstOrCreate([ 'type' => $type, 'user_id' => $user->id, ]); Wallet::where('id', $wid->id)->update(['wallet_list_id' => $type]); $log = ""; if (!empty($attributes['unique_id'])) { $log = WalletLog::where([ ['wallet_id', $wid->id], ['action', $action], ['unique_id', $attributes['unique_id']], ])->first(); } if (!$log) { $log = WalletLog::create([ 'wallet_id' => $wid->id, 'value' => $value, 'action' => $action, ]); } $log->value = $value; foreach ($attributes as $key => $value) { $log[$key] = $value; } $log->save(); } } } if (!function_exists('distributeBonusDRY')) { function distributeBonusDRY($user, $bonus, $wallets, $attributes = [], $ratecheck = false) { // For every wallet a new wallet_log entry is created. foreach ($wallets as $type => $parameters) { $action = $parameters[0]; $multiplier = $parameters[1]; $value = $bonus * $multiplier; if ($ratecheck) { $value = $value * gateRate($action); } Log::info("Type $type V $value P1 $action P2 $multiplier"); $wid = Wallet::firstOrCreate([ 'type' => $type, 'user_id' => $user->id, ]); Wallet::where('id', $wid->id)->update(['wallet_list_id' => $type]); $log = ""; if (!empty($attributes['unique_id'])) { $log = WalletLogDRY::where([ ['wallet_id', $wid->id], ['action', $action], ['unique_id', $attributes['unique_id']], ])->first(); } if (!$log) { $log = WalletLogDRY::create([ 'wallet_id' => $wid->id, 'value' => $value, 'action' => $action, ]); } $log->value = $value; foreach ($attributes as $key => $value) { $log[$key] = $value; } $log->save(); } } } if (!function_exists('getCitiesByName')) { function getCitiesByName($stateName) { $state = State::select('id')->where('name', $stateName)->first(); return City::where('state_id', $state->id)->orderBy('name', 'asc')->get(); } } if (!function_exists('createOrder')) { function createOrder($walletId, $userId, $cartIds = [], $calculateTax = true) { $user = User::find($userId); if (!empty($cartIds)) { $cartProducts = Cart::with('productStaticOption')->where('user_id', $userId)->whereIn('id', $cartIds)->get(); } else { $cartProducts = Cart::with('productStaticOption')->where('user_id', $userId)->get(); } if (count($cartProducts) == 0) { return true; } $cartTotal = 0; $productNameArray = []; foreach ($cartProducts as $cart) { $cartTotal += $cart->quantity * $cart->price; $productNameArray[] = $cart->productStaticOption->title ?? 'Plastic Neutrality Package - ' . $cart->productStaticOption->price; } $transactionInputData = []; $transactionInputData['packageName'] = implode(', ', $productNameArray); if ($calculateTax) { /*-------- START for Tax --------*/ $taxArray = calculateTax($cartTotal, $userId); $transactionInputData = ['tax_data' => $taxArray['tax_data'] ?? null]; $cartTotal += $taxArray['total_tax'] ?? 0; /*-------- END for Tax --------*/ } /** Deduct product amount */ $userWallet = Wallet::firstOrCreate(['user_id' => $userId, 'id' => $walletId]); $userWallet->balance -= $cartTotal; $userWallet->save(); $transactionInput['wallet_id'] = $userWallet->id; $transactionInput['data'] = json_encode($transactionInputData); $transactionInput['action'] = WalletLog::ACTION_PURCHASE; $transactionInput['value'] = $cartTotal; $transactionInput['balance'] = $userWallet->balance; $transactionInput['transaction_id'] = getLastTransactionUniqueId(); $transaction = WalletLog::create($transactionInput); $input['type'] = 'product'; $input['wallet_type'] = 'amplivo cash'; $response = []; foreach ($cartProducts as $cartProduct) { for ($i = 0; $i < $cartProduct->quantity; $i++) { $input['user_id'] = $cartProduct->user_id; $input['price'] = $cartProduct->price; $input['bv'] = $cartProduct->price; $input['csr'] = $cartProduct->csr; $input['transaction_id'] = $transaction->id; $input['created_at'] = Carbon::now(); $input['updated_at'] = $input['created_at']; $input['product_static_option_id'] = $cartProduct->product_static_option_id; $product_name = 'plastic neutrality package'; if (!empty($cartProduct->product_static_option_id)) { $input['product_type'] = $cartProduct->productStaticOption->type; $product_name = $cartProduct->productStaticOption->title; } else { $input['product_type'] = 1; // ---- Product } // static data end $purchase = Purchase::create($input); /** Generate gift card */ $giftCard['user_id'] = $cartProduct->user_id; $giftCard['purchase_id'] = $purchase->id; $giftCard['gift_code'] = generateRandomCode(); if (!empty($cartProduct->product_static_option_id) && isset($cartProduct->productStaticOption->redemption_expire_days)) { $giftCard['expire_date'] = Carbon::now()->addDays($cartProduct->productStaticOption->redemption_expire_days); } else { $giftCard['expire_date'] = Carbon::now()->addMonths(getSiteSettings('gift_code_expiration_time')); } GiftCode::create($giftCard); $logMessage = $user->details->first_name . " " . $user->details->last_name . ' has buy ' . $product_name . ' product (Transaction Id : ' . $transactionInput['transaction_id'] . ')'; $response[] = [ 'product_name' => $product_name, 'product_price' => $cartProduct->productStaticOption->price, 'gift_code' => $giftCard['gift_code'], 'log_message' => $logMessage, ]; } $cartProduct->delete(); } return $response; } } if (!function_exists('calculateTax')) { function calculateTax($totalAmount, $userId) { $user = User::find($userId); /*-------- START for Tax --------*/ $walletTaxData = $taxArray = []; if (!empty($user->details->address->state_id)) { $walletTaxData = [ 'state_id' => $user->details->address->state_id, 'state_name' => $user->details->address->state->name, ]; $taxArray = \App\Models\TaxManagement::where('state_id', $user->details->address->state_id)->where('status', '1')->get(); } if (!empty($user->details->address->country_id) && count($taxArray) <= 0) { $walletTaxData = [ 'country_id' => $user->details->address->country_id, 'country_name' => $user->details->address->country->country_name, ]; $taxArray = \App\Models\TaxManagement::whereNull('state_id')->where('country_id', $user->details->address->country_id)->where('status', '1')->get(); } $taxAmount = 0; if (isset($taxArray) && !empty($taxArray)) { foreach ($taxArray as $row) { $per = \App\Services\BigNumber::create($row->tax_percentage)->div(100)->value; $tax = \App\Services\BigNumber::create($totalAmount)->mul($per)->value; $walletTaxData['details'][] = [ 'name' => $row->tax_name, 'percentage' => $row->tax_percentage, 'value' => $tax, 'id' => $row->id, ]; $taxAmount += $tax; } $walletTaxData['total_amount'] = $taxAmount; } /*-------- END for Tax --------*/ return [ 'total_tax' => $taxAmount, 'tax_data' => $walletTaxData, ]; } } if (!function_exists('redeemGiftCode')) { function redeemGiftCode($giftCode, $userId, $orderNo) { $user = User::find($userId); $giftCode = GiftCode::with('purchaseProduct')->where('gift_code', $giftCode)->first(); if ($giftCode) { if (strtotime(date('Y-m-d')) > strtotime($giftCode->expire_date)) { $logMessage = ($user->details->first_name ?? '') . " " . ($user->details->last_name ?? '') . ' has enter expired gift code '; saveLog($logMessage, $user, ['logType' => 'gift_code'], 'GiftCode'); return 'The gift code is expired.'; } $giftCode->redeem_by = $user->id; $giftCode->status = 2; $giftCode->redeemed_date = Carbon::now(); /** Add BV **/ if ($giftCode->purchaseProduct->product_type == 1) { //---- product type is product $bvInput['user_id'] = $user->id; $refBV = 0; for ($i = 1; $i <= 2; $i++) { $bvInput['value'] = $giftCode->purchaseProduct->bv / 2; $bvInput['origin'] = $i; $dataArray = []; if ($i == 2) { $dataArray['reference_bv_id'] = $refBV; } $dataArray['gift_code_id'] = $giftCode->gift_code; $bvInput['data'] = json_encode($dataArray); $bvInput['source'] = BV::SOURCE_COUPON_REDEEM; $bvInput['created_at'] = Carbon::now(); $data = BV::create($bvInput); if ($i == 1) { $refBV = $data->id; } saveLog("BV (value : " . $bvInput['value'] . ") created for gift code $giftCode->gift_code", $user, ['logType' => 'BV'], 'BV', $user); } calculateUserPerformance($user->id); // ---- Calculate user performance runtime } else { //---- product type is License $oldLicenseEndDate = UserTeamsiteLicense::where(['user_id' => $user->id])->orderBy('end', 'DESC')->value('end'); if (empty($oldLicenseEndDate) || (!empty($oldLicenseEndDate) && date('Y', strtotime($oldLicenseEndDate)) < date('Y'))) { $oldLicenseEndDate = date('Y-m-d H:i:s'); } $start = date('Y-m-d H:i:s', strtotime($oldLicenseEndDate)); $end = date('Y-m-d H:i:s', strtotime("$oldLicenseEndDate + 12 months")); UserTeamsiteLicense::create([ 'user_id' => $user->id, 'gift_code_id' => $giftCode->id, 'type' => UserTeamsiteLicense::TYPE_12_MONTHS, 'start' => $start, 'end' => $end, ]); saveLog("Business License (Start Date: $start, End Date: $end ) created for gift code $giftCode->gift_code", $user, ['logType' => 'business_license'], 'BusinessLicense', $user); calculateUserPerformance($user->id); // ---- Calculate user performance runtime /*------ START to update member level to 3 ------*/ $member = Member::where('user_id', $user->id)->first(); if (empty($member->level) || $member->level < 3) { $oldValue = $member->level; $newValue = 3; $member->update(['level' => $newValue]); $qualificationLog = UserQualificationLog::firstOrCreate( [ 'user_id' => $user->id, 'type' => UserQualificationLog::TYPE_LEVEL, 'value' => $newValue, 'source' => UserQualificationLog::SOURCE_PERFORMANCE, ], [ 'value_before' => $oldValue, // only used when creating 'created_at' => Carbon::now(), 'updated_at' => Carbon::now(), ] ); /*---- START for activity log ----*/ $identities = Customer::whereIn('customer_no', [$oldValue, $newValue])->pluck('customer_identity', 'customer_no'); $oldCustomerLevel = ucwords(str_replace('_', ' ', strtolower($identities[$oldValue] ?? '-'))); $newCustomerLevel = ucwords(str_replace('_', ' ', strtolower($identities[$newValue] ?? '-'))); saveLog("Customer Level updated from $oldCustomerLevel to $newCustomerLevel.", $qualificationLog, $qualificationLog, 'Customer Level', $user); /*---- END for activity log ----*/ } /*------ END to update member level to 3 ------*/ } /*---- START for redemption ----*/ if ($giftCode->purchaseProduct->product_type == 1) { //---- product type is product $csrAmount = $giftCode->purchaseProduct->csr; $randomRefNo = wordwrap(generateRandomCode(12), 4, "-", true); $referenceNo = "PNP-$randomRefNo"; /*---- redemption ----*/ $weekNumber = date('W'); $CsrRedemptionSetting = CsrRedemptionSetting::whereDate('date', date('Y-m-d'))->first(); $giftCode->reference_no = $referenceNo; $giftCode->principal_kgs = round(($csrAmount / 10)); //---- convert into kg $giftCode->save(); $insertData = [ 'user_id' => $user->external_id, 'gift_code' => $giftCode->gift_code, 'reference_no' => $referenceNo, 'csr_amount' => $csrAmount, 'source' => 'Purchase', 'redemption_date' => now(), 'pool_ref' => "PNP -" . date('Y') . "-" . $weekNumber, 'csr_redemption_setting' => null, 'order_no' => $orderNo ]; if (!empty($CsrRedemptionSetting)) { $weekWiseData = []; if (strtolower($CsrRedemptionSetting->is_week_wise_advance) == strtolower('yes')) { $advance_week_percentage = explode(',', $CsrRedemptionSetting->primary_advance_week_percentage) ?? ''; foreach (explode(',', $CsrRedemptionSetting->primary_advance_week_number ?? '') as $key => $value) { $weekWiseData[] = [ 'week_number' => $value, 'percentage' => $advance_week_percentage[$key] ?? 0, ]; } } $insertData['csr_redemption_setting'] = [ 'csr_segmentation' => $CsrRedemptionSetting->primary_csr_segmentation, 'no_of_deliveries' => $CsrRedemptionSetting->primary_no_of_deliveries, 'delivery_interval' => $CsrRedemptionSetting->primary_delivery_interval, 'delivery_start_week' => $CsrRedemptionSetting->primary_delivery_start_week, 'week_wise_advance_data' => $weekWiseData ]; } Http::withHeaders(getCsrNowApiHeader())->post(config('csrnow.api.live_endpoint') . 'become-plastic-neutral/csr-redemption/store', $insertData); /*---- Bonus / Discount ----*/ $promotionType = $CsrRedemptionSetting->promotion_type ?? null; $promotionValue = $CsrRedemptionSetting->promotion_value ?? null; $initialEuroAmount = $giftCode->purchaseProduct->price ?? null; if ($CsrRedemptionSetting && !empty($promotionType) && !empty($promotionValue)) { if ($promotionType === 'Bonus') { $bonusPercentage = BigNumber::create($promotionValue)->div(100)->value; $csrRedemptionValue = BigNumber::create($csrAmount)->mul($bonusPercentage)->value; $poolRefPrefix = 'BNS'; $giftCode->bonus_kgs = round(($csrRedemptionValue / 10)); //---- convert into kg $giftCode->save(); } else { $csrPriceAtPurchaseTime = BigNumber::create($giftCode->purchaseProduct->price)->div($giftCode->purchaseProduct->csr)->value; $baseCsrPercentage = BigNumber::create($csrPriceAtPurchaseTime)->mul($promotionValue)->div(100)->value; $discountCsrPercentage = BigNumber::create($csrPriceAtPurchaseTime)->sub($baseCsrPercentage)->value; $discount = BigNumber::create($giftCode->purchaseProduct->price)->div($discountCsrPercentage)->value; // ---- Final Bonus $csrRedemptionValue = round(BigNumber::create($discount)->sub($csrAmount)->value); $poolRefPrefix = 'DIS'; $giftCode->discount_kgs = round(($csrRedemptionValue / 10)); //---- convert into kg $giftCode->save(); } $insertData = [ 'user_id' => $user->external_id, 'gift_code' => $giftCode->gift_code, 'reference_no' => "$poolRefPrefix-$randomRefNo", 'pool_ref' => $poolRefPrefix . "-" . date('Y') . "-" . $weekNumber, 'csr_amount' => $csrRedemptionValue, 'base_csr_amount' => $csrAmount, 'base_euro_amount' => $initialEuroAmount, 'csr_redemption_setting' => null, 'order_no' => $orderNo, 'gift_code_reference_no' => "PNP-$randomRefNo" ]; $weekWiseData = []; if (strtolower($CsrRedemptionSetting->is_week_wise_advance) == strtolower('yes')) { $advance_week_percentage = explode(',', $CsrRedemptionSetting->promotion_advance_week_percentage) ?? ''; foreach (explode(',', $CsrRedemptionSetting->promotion_advance_week_number ?? '') as $key => $value) { $weekWiseData[] = [ 'week_number' => $value, 'percentage' => $advance_week_percentage[$key] ?? 0, ]; } } $insertData['csr_redemption_setting'] = [ 'type' => $CsrRedemptionSetting->promotion_type, 'csr_segmentation' => $CsrRedemptionSetting->promotion_csr_segmentation, 'no_of_deliveries' => $CsrRedemptionSetting->promotion_no_of_deliveries, 'delivery_interval' => $CsrRedemptionSetting->promotion_delivery_interval, 'delivery_start_week' => $CsrRedemptionSetting->promotion_delivery_start_week, 'promotion_value' => $promotionValue, 'week_wise_advance_data' => $weekWiseData, ]; Http::withHeaders(getCsrNowApiHeader())->post(config('csrnow.api.live_endpoint') . 'become-plastic-neutral/csr-award/store', $insertData); } } else { $randomRefNo = wordwrap(generateRandomCode(12), 4, "-", true); $referenceNo = "LIC-$randomRefNo"; $giftCode->reference_no = $referenceNo; $giftCode->save(); } /*---- END for redemption ----*/ $logMessage = "Gift code $giftCode->gift_code has been successfully redeemed"; saveLog($logMessage, $user, ['logType' => 'gift_code'], 'GiftCode', $user); if ($giftCode->user_id != $giftCode->redeem_by) { $logMessage = "Gift code $giftCode->gift_code has been redeemed by " . ($user->details->first_name ?? '') . " " . ($user->details->last_name ?? ''); saveLog($logMessage, $giftCode->user, ['logType' => 'gift_code'], 'GiftCode', $giftCode->user); } return true; } } } if (!function_exists('generateRandomCode')) { function generateRandomCode($length = 10) { $code = Str::random($length); $exists = GiftCode::where('gift_code', $code)->count(); if ($exists > 0) { generateRandomCode(); } return strtoupper($code); } } if (!function_exists('getEmailBody')) { function getEmailBody($title, $url = "", $userFullName = "") { $emailData = EmailManagement::where('title', $title)->first(); /*------ START for replace btn and other text ------*/ if ($title == 'Verify email address') { $linkTitle = "👉 Verify Email Address"; } else { $linkTitle = "👉 Click Here"; } $btnStyle = 'style="color: #0066cc ; font-weight: bold ; text-decoration: none ; font-size: 16px ; display: inline-flex"'; $clickBtn = '<a href="[link]" ' . $btnStyle . '> ' . $linkTitle . '</a>'; $body = str_replace(['[button]', '[userFullName]'], [$clickBtn, $userFullName], $emailData->body ?? ''); $body = str_replace(["[link]", "%5Blink%5D"], [$url, $url], $body); /*------ END for replace btn and other text ------*/ $emailData->body = $body; return $emailData; } } if (!function_exists('convertCurrency')) { function convertCurrency($from, $to) { $url = 'https://api.coinbase.com/v2/exchange-rates' . '?currency=' . $from; $response = Http::get($url); $outputs = $response->json(); $currencyRates = $outputs['data']['rates']; $toValue = $currencyRates[$to] ?? 0; return $toValue; } } if (!function_exists('checkAuthenticationProcess')) { function checkAuthenticationProcess($userSetting, $email, $moduleName = 'login', $sendMail = true) { $siteSetting = getSiteSettings('2fa'); // Check 2fa is not expire than not show 2fa if (Cookie::has('amplivo_admin_2fa_verified') && $moduleName == 'login') { $userId = decrypt(Cookie::get('amplivo_admin_2fa_verified')); if ($userSetting->user_id == $userId) { return false; } } if ($siteSetting == "on" && (($userSetting->google_auth_key && in_array($moduleName, $userSetting->fa_setting)) || in_array($moduleName, $userSetting->fa3_setting))) { if (in_array($moduleName, $userSetting->fa3_setting) && !in_array($moduleName, $userSetting->fa_setting) && $sendMail) { Notification::route('mail', $email)->notify(new \App\Notifications\OTPVerificationNotification()); } return ($moduleName == 'login') ? url('validate/2fa') : true; } return false; } } if (!function_exists('getBrowserAndVersion')) { function getBrowserAndVersion($userAgent) { $browsers = ['Chrome', 'Firefox', 'Safari', 'Opera', 'MSIE', 'Edge']; foreach ($browsers as $browser) { if (preg_match('/' . $browser . '[\/ ]([0-9.]+)/', $userAgent, $matches)) { return ['name' => $browser, 'version' => $matches[1]]; } } return []; } } if (!function_exists('getVPNDetails')) { function getVPNDetails($ip) { try { // Call VPN API $response = Http::get(config('amplivo.vpn_api.api_endpoint') . $ip, [ 'key' => config('amplivo.vpn_api.api_key') ]); if ($response->successful()) { $data = $response->json(); return $data; } } catch (\Exception $e) { Log::info($e); } return []; } } if (!function_exists('calculateDistance')) { function calculateDistance($lat1, $lon1, $lat2, $lon2) { $earthRadius = 6371; // Earth's radius in kilometers $latDiff = deg2rad($lat2 - $lat1); $lonDiff = deg2rad($lon2 - $lon1); $a = sin($latDiff / 2) * sin($latDiff / 2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($lonDiff / 2) * sin($lonDiff / 2); $c = 2 * atan2(sqrt($a), sqrt(1 - $a)); return $earthRadius * $c; // Distance in kilometers } } if (!function_exists('getDeviceDetails')) { function getDeviceDetails($request) { $deviceDetails['user_agent_string'] = $_SERVER['HTTP_USER_AGENT'] ?? ''; $deviceDetails['ip_address'] = getClientIp($request); $getBrowser = getBrowserAndVersion($deviceDetails['user_agent_string']); $getVPNDetails = getVPNDetails($deviceDetails['ip_address']); if ( isset($getVPNDetails['location']['latitude'], $getVPNDetails['location']['longitude']) && $getVPNDetails['location']['latitude'] && $getVPNDetails['location']['longitude'] ) { $coordinates = getFormattedCoordinates( $getVPNDetails['location']['latitude'], $getVPNDetails['location']['longitude'] ); } else { $coordinates = ''; } $userAgent = $request->header('User-Agent'); $deviceType = 'Desktop'; // default if (preg_match('/mobile|android|touch|webos|hpwos/i', $userAgent)) { $deviceType = 'Mobile'; } if (preg_match('/tablet|ipad/i', $userAgent)) { $deviceType = 'Tablet'; } $deviceDetails['geolocation'] = $getVPNDetails['location']['city'] ?? null; $deviceDetails['latitude'] = $getVPNDetails['location']['latitude'] ?? null; $deviceDetails['longitude'] = $getVPNDetails['location']['longitude'] ?? null; $deviceDetails['coordinates'] = $coordinates; $deviceDetails['operating_system'] = $request->operating_system; $deviceDetails['os_version'] = $request->os_version; $deviceDetails['device_type'] = $deviceType; $deviceDetails['language'] = $request->language; $deviceDetails['browser_name'] = $getBrowser['name']; $deviceDetails['browser_version'] = $getBrowser['version']; $deviceDetails['local_timezone'] = $request->local_timezone; $deviceDetails['cookies'] = $request->cookies_enabled; $deviceDetails['javascript'] = $request->javascript_enabled; $deviceDetails['do_not_track_setting'] = $request->do_not_track_setting; return $deviceDetails; } } if (!function_exists('getFormattedCoordinates')) { function getFormattedCoordinates($lat, $lng) { $latSuffix = $lat >= 0 ? 'N' : 'S'; $lngSuffix = $lng >= 0 ? 'E' : 'W'; return abs($lat) . '° ' . $latSuffix . ', ' . abs($lng) . '° ' . $lngSuffix; } } if (!function_exists('createMFP')) { function createMFP($deviceDetails) { Session::forget('MFPAuthType'); /*------ Start find mfp record ------*/ $whereArray = [ 'user_id' => Auth::user()->id, 'operating_system' => $deviceDetails['operating_system'], 'os_version' => $deviceDetails['os_version'], 'device_type' => $deviceDetails['device_type'], 'browser_name' => $deviceDetails['browser_name'], 'browser_version' => $deviceDetails['browser_version'], 'geolocation' => $deviceDetails['geolocation'], 'local_timezone' => $deviceDetails['local_timezone'], 'cookies' => $deviceDetails['cookies'], 'javascript' => $deviceDetails['javascript'], 'do_not_track_setting' => $deviceDetails['do_not_track_setting'], ]; $MFPDeviceKey = \Illuminate\Support\Facades\Cookie::get('mfp_device_key') ?? ''; if (!empty($MFPDeviceKey)) { $whereArray['device_key'] = $MFPDeviceKey; $MFPDetails = MachineFootPrint::where($whereArray)->first(); } else { $whereArray['ip_address'] = $deviceDetails['ip_address']; $MFPDetails = MachineFootPrint::where($whereArray)->first(); } /*------ End find mfp record ------*/ $MFPData = [ 'user_id' => Auth::user()->id, 'ip_address' => $deviceDetails['ip_address'], 'geolocation' => $deviceDetails['geolocation'], 'latitude' => $deviceDetails['latitude'], 'longitude' => $deviceDetails['longitude'], 'operating_system' => $deviceDetails['operating_system'], 'os_version' => $deviceDetails['os_version'], 'device_type' => $deviceDetails['device_type'], 'language' => $deviceDetails['language'], 'browser_name' => $deviceDetails['browser_name'], 'browser_version' => $deviceDetails['browser_version'], 'user_agent_string' => $deviceDetails['user_agent_string'], 'local_timezone' => $deviceDetails['local_timezone'], 'cookies' => $deviceDetails['cookies'], 'javascript' => $deviceDetails['javascript'], 'do_not_track_setting' => $deviceDetails['do_not_track_setting'] ]; if (empty($MFPDetails)) { $MFPData['device_key'] = generateDeviceKey($deviceDetails); \Illuminate\Support\Facades\Cookie::queue('mfp_device_key', $MFPData['device_key'], 100 * 365 * 24 * 60); // 100 years in minutes MachineFootPrint::create($MFPData); } else { $MFPDetails->update($MFPData); } } } if (!function_exists('MFPIsValidate')) { function MFPIsValidate($deviceDetails, $sendOtpMail = true) { /*------ Start delete 14 day old record ------*/ MachineFootPrint::where('user_id', Auth::user()->id)->whereDate('updated_at', "<=", Carbon::now()->subDays(14))->delete(); /*------ END delete 14 day old record ------*/ /*------ Start find mfp record ------*/ $whereArray = [ 'user_id' => Auth::user()->id, 'operating_system' => $deviceDetails['operating_system'], 'os_version' => $deviceDetails['os_version'], 'device_type' => $deviceDetails['device_type'], 'browser_name' => $deviceDetails['browser_name'], 'browser_version' => $deviceDetails['browser_version'], 'geolocation' => $deviceDetails['geolocation'], 'local_timezone' => $deviceDetails['local_timezone'], 'cookies' => $deviceDetails['cookies'], 'javascript' => $deviceDetails['javascript'], 'do_not_track_setting' => $deviceDetails['do_not_track_setting'], ]; $MFPDeviceKey = \Illuminate\Support\Facades\Cookie::get('mfp_device_key') ?? ''; if (!empty($MFPDeviceKey)) { $whereArray['device_key'] = $MFPDeviceKey; $MFPDetails = MachineFootPrint::where($whereArray)->first(); } else { $whereArray['ip_address'] = $deviceDetails['ip_address']; $MFPDetails = MachineFootPrint::where($whereArray)->first(); } /*------ End find mfp record ------*/ $isValidate = false; if (!empty($MFPDetails)) { $distance = calculateDistance( $MFPDetails->latitude, $MFPDetails->longitude, $deviceDetails['latitude'], $deviceDetails['longitude'] ); if ($distance >= 400) { $MFPDetails->delete(); } else { $MFPDetails->update(['updated_at' => Carbon::now()]); $isValidate = true; } } if ($isValidate === false) { $siteSetting = getSiteSettings('2fa'); if ($siteSetting == "on") { //------ Authenticate fro MFP if ((!empty(Auth::user()->setting->google_auth_key) && in_array('login', Auth::user()->setting->fa_setting ?? []))) { $authType = "2fa"; } else { if ($sendOtpMail) { $email = Auth::user()->details->email; Notification::route('mail', $email)->notify(new \App\Notifications\OTPVerificationNotification()); } $authType = "otp"; } return ["url" => url('validate/2fa'), "authType" => $authType]; } return true; } else { return $isValidate; } } } if (!function_exists('generateDeviceKey')) { function generateDeviceKey($deviceDetails) { $rawString = implode('|', [ $deviceDetails['operating_system'] ?? '', $deviceDetails['os_version'] ?? '', $deviceDetails['device_type'] ?? '', $deviceDetails['browser_name'] ?? '', $deviceDetails['browser_version'] ?? '', $deviceDetails['user_agent_string'] ?? '', ]); return hash('sha256', $rawString); } } if (!function_exists('generateRandomUrlKey')) { function generateRandomUrlKey($parameter, $expireTime) { // Generate a unique short URL do { $k1 = Carbon::now()->format('i'); $k2 = strtolower(Str::random(4)); $k3 = Carbon::now()->format('s'); $shortKey = $k1 . $k2 . $k3; } while (ShortUrl::where('short_key', $shortKey)->exists()); // Save key ShortUrl::create([ 'parameters' => json_encode($parameter), 'short_key' => $shortKey, 'expire_time' => $expireTime ]); return $shortKey; } } if (!function_exists('getShortKeyParameters')) { function getShortKeyParameters($key) { $url = ShortUrl::where('short_key', $key)->first(); if ($url) { $status = 'true'; $reqTime = Carbon::parse($url['created_at']); //Add expire minutes $timePlus60Minutes = $reqTime->addMinutes($url['expire_time']); //Get the current time $currentTime = Carbon::now(); if ($currentTime->greaterThan($timePlus60Minutes)) { $status = 'expired'; } // Access the parameters attribute $parameters = json_decode($url['parameters']); $url->delete(); } else { $status = 404; $parameters = []; } return $data = [ 'status' => $status, 'parameters' => $parameters ]; } } if (!function_exists('createNotification')) { function createNotification($title, $message, $userId, $link = null) { return \App\Models\Notification::create([ 'title' => $title, 'message' => $message, 'user_id' => $userId, 'link' => $link, ]); } } if (!function_exists('formatDisplayNumber')) { function formatDisplayNumber($number, $decimals = 2) { $number = $number ?? 0; return number_format((float)$number, $decimals, '.', ','); } } if (!function_exists('getLastTransactionUniqueId')) { function getLastTransactionUniqueId() { $lastTransactionId = getSiteSettings('last_transaction_unique_id'); if (empty($lastTransactionId)) { $lastTransactionId = 100000; SiteConfiguration::firstOrCreate(['key' => 'last_transaction_unique_id'], ['value' => $lastTransactionId]); } ++$lastTransactionId; SiteConfiguration::where('key', 'last_transaction_unique_id')->update(['value' => $lastTransactionId]); return $lastTransactionId; } } if (!function_exists('getEmailSettings')) { function getEmailSettings($key) { $emailSwitch = EmailSwitches::where('key', $key)->first(); if (!empty($emailSwitch)) { return $emailSwitch->value; } return ''; } } if (!function_exists('getCustomizeAmountWalletLog')) { function getCustomizeAmountWalletLog($value, $action = null) { $value = formatDisplayNumber($value); $debitActionArray = [ WalletLog::ACTION_WITHDRAW, WalletLog::ACTION_TRANSFER_OUT, WalletLog::ACTION_PURCHASE, WalletLog::ACTION_DEBIT, WalletLog::ACTION_CSR_PURCHASE, ]; if (in_array($action, $debitActionArray)) { $value = "-$value"; } return $value; } } if (!function_exists('getActionMessageOfWalletLog')) { function getActionMessageOfWalletLog($item) { $data = json_decode($item['data'] ?? '', true); /*---- START for Automation ----*/ if (isset($data['actionBy']) && $data['actionBy'] == 'Automation'){ return ($data['description'] ?? null)." - Automation"; } /*---- END for Automation ----*/ if ($item['action'] == 8 || $item['action'] == 9) { $actionMessage = $item['wallet_name'] . ' generated by ' . (\App\Models\Member::where('id', $data['user_id'])->first()->user->details->username ?? '') . ' for level ' . $data['level']; } elseif ($item['action'] == 10 || $item['action'] == 20) { $actionMessage = "Matching bonus" . ' generated by ' . (\App\Models\Member::where('id', $data['user_id'])->first()->user->details->username ?? '') . ' for level ' . $data['level']; } elseif ($item['action'] == 26) { $actionMessage = "CAB " . ' generated by ' . (\App\Models\Member::where('id', $data['user_id'])->first()->user->details->username ?? '') . ' for level ' . $data['level']; } elseif ($item['action'] == 21) { $actionMessage = $item['action_name'] ?? '-'; } elseif ($item['action'] == WalletLog::ACTION_CREDIT) { if (isset($data['actionBy']) && $data['actionBy'] == 'Admin') { $actionMessage = "Amount Credited By Admin"; if (isset($data['become_plastic_neutral_order_number']) && !empty($data['become_plastic_neutral_order_number'])) { $actionMessage .= " (Order Number: " . $data['become_plastic_neutral_order_number'] . ")"; } } else if (isset($data['canceled_gift_code'])) { $actionMessage = "Amount Credited Against Canceled Gift Code (" . $data['canceled_gift_code'] . ")"; } else { $actionMessage = "Amount Credit"; } } elseif ($item['action'] == WalletLog::ACTION_DEBIT) { if (isset($data['actionBy']) && $data['actionBy'] == 'Admin') { $actionMessage = "Amount Debited By Admin"; } else { $actionMessage = "Amount Debit"; } } elseif ($item['action'] == WalletLog::ACTION_DEPOSIT) { $currency = $data['currency'] ?? ''; $actionMessage = isset($data['deposit']) ? formatDisplayNumber($data['deposit']) . " $currency deposited" : '-'; } elseif ($item['action'] == WalletLog::ACTION_WITHDRAW) { $currency = $data['currency'] ?? ''; $withdrawalFee = $data['withdrawal_fee'] ?? '0.00'; $actionMessage = isset($data['withdrawal']) ? formatDisplayNumber($data['withdrawal']) . " $currency withdrawn (including a $withdrawalFee EUR fee)" : '-'; } elseif ($item['action'] == WalletLog::ACTION_WITHDRAW_FEE) { if (isset($data['withdrawal_fee']) && isset($data['reference_no'])) { $actionMessage = "A withdrawal fee " . $data['withdrawal_fee'] . " EUR for Reference No: " . $data['reference_no'] . " will be credited"; } else { $actionMessage = "Withdrawal fee credit"; } } elseif ($item['action'] == WalletLog::ACTION_PURCHASE) { $actionMessage = $data['packageName'] ?? 'Purchase Product'; } elseif ($item['action'] == WalletLog::ACTION_CSR_PURCHASE) { $actionMessage = "" . $data['amount'] . " EUR deducted for CSR purchase"; } elseif ($item['action'] == WalletLog::ACTION_TRANSFER_IN) { if (isset($data['sender'])) { $actionMessage = "Received from " . ($data['sender'] ?? '-'); if (isset($data['reason'])) { $actionMessage .= " (Reason :" . $data['reason'] . ")"; } } else { $actionMessage = $data['username'] ?? 'Amount Received'; } } elseif ($item['action'] == WalletLog::ACTION_TRANSFER_OUT) { if (isset($data['sender'])) { $actionMessage = "Transferred to " . ($data['receiver'] ?? '-'); if (isset($data['reason'])) { $actionMessage .= " (Reason :" . $data['reason'] . ")"; } } else { $actionMessage = $data['username'] ?? 'Amount Transferred'; } } elseif (isset($data['description'])){ $actionMessage = $data['description'] ?? null; } else { $actionMessage = $item['action_name'] ?? null; } return $actionMessage; } } if (!function_exists('checkAndCreateWallet')) { function checkAndCreateWallet($userId) { $walletList = \App\Models\WalletList::get(); foreach ($walletList as $row) { if (!Wallet::where(['user_id' => $userId, 'wallet_list_id' => $row->id])->exists()) { Wallet::create([ 'user_id' => $userId, 'wallet_list_id' => $row->id, 'balance' => 0, 'type' => $row->id, ]); } } } } if (!function_exists('getBrevoApiSettings')) { function getBrevoApiSettings() { $brevoEmailAPI = ApiSettings::where( 'domain_holder', ApiSettings::DOMAIN_HOLDER['brevo_email_api'] )->first(); return $brevoEmailAPI; } } if (!function_exists('getTokenData')) { function getTokenData() { $response = Http::withHeaders(getCsrNowApiHeader())->get(config('csrnow.api.live_endpoint') . 'token-price'); if ($response->successful()) { $data = $response->object(); $token = []; if (isset($data->data)) { foreach ($data->data->token as $row) { $token[$row->type] = $row->value_eur; } } return [ 'current_token' => $data->data->current_token ?? '', 'token_list' => $token, ]; } else { return false; } } } if (!function_exists('getGivenTokenPrice')) { function getGivenTokenPrice($token) { $data = getTokenData(); $tokenList = $data['token_list']; $price = $tokenList[$token] ?? null; if (!empty($price)) { return $price; } else { return false; } } } if (!function_exists('getCurrentTokenAndPrice')) { function getCurrentTokenAndPrice($getOnlyPrice = false) { $data = getTokenData(); $currentToken = $data['current_token']; $tokens = $data['token_list']; if ($getOnlyPrice) { return $tokens[$currentToken] ?? 0; } else { return [ 'name' => $currentToken, 'price' => $tokens[$currentToken] ?? 0, ]; } } } if (!function_exists('getCsrNowApiHeader')) { function getCsrNowApiHeader() { return [ 'Accept' => 'application/json', 'x-api-key' => config('csrnow.api.auth_key'), ]; } } if (!function_exists('getMaskedString')) { function getMaskedString($string, $numberOfX = 12, $prefixNumberToShow = 4, $suffixNumberToShow = 4) { $prefix = substr($string, 0, $prefixNumberToShow); $suffix = substr($string, -$suffixNumberToShow); $masked = str_repeat('x', $numberOfX); return $prefix . $masked . $suffix; } } if (!function_exists('createRole')) { function createRole($roleId, $roleName, $isArchived = "No") { // Check if the role already exists in the database $existingRole = Role::where('id', $roleId)->first(); if (!$existingRole) { // Create role if not exist Role::create(['id' => $roleId, 'name' => $roleName, 'is_archived' => $isArchived]); } else { $existingRole->update(['name' => $roleName, 'is_archived' => $isArchived]); } } } if (!function_exists('storeGoogleAuthKey')) { function storeGoogleAuthKey($googleAuthKey) { $userSetting = UserSetting::where('user_id', Auth::user()->id)->first(); if (empty($googleAuthKey)) { $userSetting->update(['google_auth_key' => null, 'fa_setting' => null]); } elseif (empty($userSetting->google_auth_key) || $userSetting->google_auth_key != $googleAuthKey) { $userSetting->update(['google_auth_key' => $googleAuthKey, 'fa_setting' => 'login']); } } } if (!function_exists('updateSponsorIdFromCsrNowIntroducedBy')) { function updateSponsorIdFromCsrNowIntroducedBy($csrNowProfile, $member) { $csrNowProfile = (is_object($csrNowProfile)) ? (array) $csrNowProfile : $csrNowProfile; $member = (is_object($member)) ? (array) $member : $member; if (isset($csrNowProfile['introduced_by']) && !empty($csrNowProfile['introduced_by']) && empty($member['sponsor_id'])) { $sponsorUser = User::firstOrCreate(['external_id' => $csrNowProfile['introduced_by']]); $sponsorMember = Member::firstOrCreate(['user_id' => $sponsorUser->id]); $updateArray = ['sponsor_id' => $sponsorMember->user_id]; if (empty($member['personal_sponsor_id'])) { $updateArray['personal_sponsor_id'] = $sponsorMember->user_id; } Member::where('member_id', $member['member_id'])->update($updateArray); return true; } else { return false; } } } if (!function_exists('getDateWithIcon')) { function getDateWithIcon($date) { $timeZone = Auth::user()->setting->timezone ?? 'UTC'; $timezone = new \DateTimeZone($timeZone); $datetime = new \DateTime('now', $timezone); $offset = $datetime->format('P'); $label = "(GMT {$offset})"; return '<span class="dateWithIcon" data-toggle="tooltip" data-html="true" data-original-title="' . date('d-m-Y h:i:s A', strtotime($date)) . '<br>' . $label . '">' . date('d-m-Y', strtotime($date)) . '</span>'; } } if (!function_exists('getFilterOperatorAndValue')) { function getFilterOperatorAndValue($item) { $item = trim((string) $item); // Match optional operator and optional numeric value if (preg_match('/^(>=|<=|>|<|=)?\s*(\d+(?:\.\d+)?|\.\d+)?$/', $item, $matches)) { $operator = (isset($matches[1]) && !empty($matches[1])) ? $matches[1] : '='; $value = isset($matches[2]) && is_numeric($matches[2]) ? $matches[2] + 0 : 0; return [$operator, $value]; } return ['=', 0]; // Fallback } } if (!function_exists('convertDateToUserTimeZone')) { function convertDateToUserTimeZone(&$date, $formatting = false, $timezone = 'UTC') { return $formatting ? Carbon::parse($date)->setTimezone($timezone)->format($formatting) : Carbon::parse($date)->setTimezone($timezone)->format('d-m-y h:i:s'); } } if (!function_exists('getUserTimeZone')) { function getUserTimeZone() { return Session::get('user_timezone') ?? 'UTC'; } } if (!function_exists('shuftipro_delete_user_ref')) { function shuftipro_delete_user_ref($user_ref, $message) { $shuftiAPI = ApiSettings::where('domain_holder', 'shufti_pro_api')->first(); $auth = base64_encode($shuftiAPI->api_key . ':' . $shuftiAPI->api_secret); $url = $shuftiAPI->live_api_source . 'delete'; $response = Http::withHeaders([ 'Content-Type' => 'application/json', 'Authorization' => 'Basic ' . $auth, ])->post($url, [ 'reference' => $user_ref, 'comment' => $message, ]); return $response; } } if (!function_exists('getIconClassMap')) { function getIconClassMap() { return [ 'add' => 'bi bi-plus-square', 'edit' => 'bi bi-pencil-square', 'delete' => 'bi bi-trash', 'archive' => 'bi bi-archive', 'restore' => 'bi bi-arrow-counterclockwise', 'save' => 'bi bi-save', 'cancel' => 'bi bi-x-square', 'update' => 'bi bi-save', 'view' => 'bi bi-eye', 'previous' => 'bi bi-arrow-left-square', 'next' => 'bi bi-arrow-right-square', 'refresh' => 'bi bi-arrow-repeat', 'balance' => 'bi bi-wallet', 'logs' => 'bi bi-newspaper', 'invoice' => 'bi bi-receipt', 'link' => 'bi bi-link-45deg', 'approve' => 'bi bi-check-square', 'reject' => 'bi bi-x-square', 'back' => 'bi bi-box-arrow-left', 'pending' => 'bi bi-hourglass-split', 'viewall' => 'bi bi-card-list', 'download' => 'bi bi-download', 'filter' => 'bi bi-funnel', 'import' => 'bi bi-box-arrow-down', 'file' => 'bi bi-file-earmark', 'load' => 'bi bi-arrow-clockwise', 'search' => 'bi bi-search', 'info' => 'bi bi-info-circle', 'upload' => 'bi bi-upload', 'confirmyes' => 'bi bi-check-square', 'signin' => 'bi bi-box-arrow-in-right', 'extend' => 'bi bi-arrows-fullscreen', 'disable' => 'bi bi-ban', 'reset' => 'bi bi-arrow-counterclockwise' ]; } } if (!function_exists('renderIconHtml')) { function renderIconHtml($name, $extraClass = 'me-1') { $icons = getIconClassMap($name); $baseClass = $icons[$name] ?? ''; return $baseClass ? '<i class="' . trim($extraClass . ' ' . $baseClass) . '"></i>' : ''; } } if (!function_exists('shuftipro_get_document')) { function shuftipro_get_document($proof_url, $access_token) { $response = Http::withHeaders([ 'Content-Type' => 'application/json', 'Cookie' => '__cf_bm=YtjknGMboFXRYSsfUH_WdGmxJ.Hf0tYed9by3WzpCxg-1718861404-1.0.1.1-xKGJ3XN96K54TGPpSuMAr5YQNP25z9ZOV.6iwdbMABBmqkzwZjPGoXPyYQFjOvRhM0X4aeZEYT9P4r5v1OurMA', ])->post($proof_url, [ 'access_token' => $access_token ]); return $response; } } if (!function_exists('shuftipro_status_get')) { function shuftipro_status_get($ref_id) { $shuftiAPI = ApiSettings::where('domain_holder', 'shufti_pro_api')->first(); $auth = base64_encode($shuftiAPI->api_key . ':' . $shuftiAPI->api_secret); $response = Http::withHeaders([ 'Content-Type' => 'application/json', 'Authorization' => 'Basic ' . $auth, 'Cookie' => '__cf_bm=YtjknGMboFXRYSsfUH_WdGmxJ.Hf0tYed9by3WzpCxg-1718861404-1.0.1.1-xKGJ3XN96K54TGPpSuMAr5YQNP25z9ZOV.6iwdbMABBmqkzwZjPGoXPyYQFjOvRhM0X4aeZEYT9P4r5v1OurMA', ])->post($shuftiAPI->live_api_source . 'status', [ 'reference' => $ref_id ]); return $response; } } if (!function_exists('withoutActivityLogging')) { function withoutActivityLogging(string $modelClass, callable $callback) { // Disable event listeners on the actual model being logged $modelClass::flushEventListeners(); try { return $callback(); } finally { $modelClass::boot(); // Reboot model to restore observers } } } if (!function_exists('calculateUserPerformance')) { function calculateUserPerformance($userId) { $to = date('Y-m-d 23:59:59'); $from = date('Y-m-d 00:00:01', strtotime('-1 day')); \App\Jobs\CustomerLevelRecalculate::dispatch($userId); \App\Jobs\CalculateSponsorLevelByDateRange::dispatch("2018-12-18", $to, $userId); \App\Jobs\StarRankCalculate::dispatch($from, $to, $userId); return 1; } } if (!function_exists('getMemberPanelRequiringGoogle2FA')) { function getMemberPanelRequiringGoogle2FA() { $requiredMemberGoogle2fa = json_decode(getSiteSettings('mandatory_member_google_2fa')); return $requiredMemberGoogle2fa ?? []; } } if (!function_exists('getAllDownlineUserIds')) { function getAllDownlineUserIds(int $startingUserId): Collection { $allIds = collect(); $queue = collect([$startingUserId]); while ($queue->isNotEmpty()) { $batch = Member::whereIn('sponsor_id', $queue)->pluck('user_id'); $queue = $batch; $allIds = $allIds->merge($batch); } return $allIds->unique(); } } if (!function_exists('getAllUplineUserIds')) { function getAllUplineUserIds(int $userId): Collection { $uplines = collect(); while ($userId) { $userId = Member::where('user_id', $userId)->value('sponsor_id'); if ($userId && !$uplines->contains($userId)) { $uplines->push($userId); } else { break; } } return $uplines; } } if (!function_exists('storeUuidNumber')) { function storeUuidNumber() { if (!Auth::check() || !Auth::user()) { return null; // Safeguard } $email = Auth::user()->details->email; $id = Auth::user()->details->id; $name = Auth::user()->details->first_name . Auth::user()->details->last_name; $role = 'superUser'; $cookieString = $id . '|' . $email . '|' . $name . '|' . $role; $uniqueUuid = (string) Str::uuid(); $currentUUId = LoginUserUddid::Create( [ 'udid' => $uniqueUuid, 'user_id' => $id, 'email' => $email, 'name' => $name, 'cookieString' => '' ] ); $cookieString = $uniqueUuid . '|' . $cookieString; //Store in DB $currentUUId->update(['cookieString' => $cookieString]); // Store in browser Cookie::queue( Cookie::make( 'login_udid', $cookieString, 60 * 24 * 365, // 1 year '/', config('app.domain'), filter_var(config('app.secure'), FILTER_VALIDATE_BOOLEAN), true, false, config('app.same_site', 'Lax') ) ); return $cookieString; } } if (!function_exists('abandonedUserProcess')) { function abandonedUserProcess($userId) { $user = User::with('member')->find($userId); $allWallet = Wallet::whereHas('wallet_list')->with('wallet_list')->where('user_id',$userId)->get(); if (!empty($allWallet)){ foreach ($allWallet as $wallet){ $walletBalance = $wallet->balance; if ($walletBalance != 0) { $wallet->update(['balance' => 0.00]); // ---- User Log $balanceLog = 'Your ' . ($wallet->wallet_list->name ?? '') . ' balance changed from ' . formatDisplayNumber($walletBalance) . ' to ' . formatDisplayNumber(0.00) . ' – due to change status to abandoned'; saveLog($balanceLog, $user, ['logType' => 'wallet balance'], 'wallet balance', $user); $data = ['description' => "Abandoned account reset"]; WalletLog::create([ 'wallet_id' => $wallet->id, 'data' => json_encode($data), 'action' => WalletLog::ACTION_CHARGE, 'value' => $walletBalance, 'balance' => 0.00, ]); } } } /*---- START for drop KYC/KYB ----*/ if ($user->member->kyc_status != 'dropped') { Member::where('user_id', $user->id)->update(['kyc_status' => 'dropped']); // ---- User Log $balanceLog = 'Your KYC/KYB has been dropped – due to abandoned account'; saveLog($balanceLog, $user, ['logType' => 'KYC/KYB'], 'KYC/KYB', $user); } /*---- END for drop KYC/KYB ----*/ } }