Viewing File: /home/ubuntu/vedadeals-backend-base/app/Helpers/Helper.php
<?php
namespace App\Helpers;
use Hash, Exception, Auth, Mail, File, Log, Storage, Setting, DB, Validator, Image;
use App\Models\{ Admin, User, Settings, StaticPage, UserWalletPayment, UserWithdrawal, Category, Product, SubCategory, Order, OrderPayment, DeliveryAddress };
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
class Helper {
public static function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}
public static function generate_random_string() {
return sha1(time().rand());
}
public static function generate_token() {
return Helper::clean(Hash::make(rand() . time() . rand()));
}
public static function generate_token_expiry() {
$token_expiry_hour = Setting::get('token_expiry_hour') ? Setting::get('token_expiry_hour') : 1;
return time() + $token_expiry_hour*3600; // 1 Hour
}
public static function storage_upload_file($input_file, $folder_path = COMMON_FILE_PATH) {
$ext = $input_file->getClientOriginalExtension();
$file_name = self::generate_random_string().".".$ext;
$public_folder_path = "public/".$folder_path;
Storage::putFileAs($public_folder_path, $input_file, $file_name);
$storage_file_path = $folder_path.$file_name;
return asset(Storage::url($storage_file_path)); // Returning file url
}
public static function storage_delete_file($url, $folder_path = COMMON_FILE_PATH) {
$storage_file_path = $folder_path.basename($url);
if($url != '' && Storage::disk('public')->exists($storage_file_path)) {
Storage::disk('public')->delete($storage_file_path);
}
}
public static function settings_generate_json() {
$settings = Settings::get();
$sample_data = [];
foreach ($settings as $key => $setting) {
$sample_data[$setting->key] = $setting->value;
}
$static_page_ids1 = ['about', 'terms', 'privacy', 'contact'];
$footer_pages1 = StaticPage::whereIn('type', $static_page_ids1)->where('status', APPROVED)->get();
$static_page_ids2 = ['help', 'faq', 'others'];
$footer_pages2 = StaticPage::whereIn('type', $static_page_ids2)->where('status', APPROVED)->get();
$sample_data['footer_pages1'] = $footer_pages1;
$sample_data['footer_pages2'] = $footer_pages2;
// Social logins
$social_login_keys = ['FB_CLIENT_ID', 'FB_CLIENT_SECRET', 'FB_CALL_BACK' , 'TWITTER_CLIENT_ID', 'TWITTER_CLIENT_SECRET', 'TWITTER_CALL_BACK', 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', 'GOOGLE_CALL_BACK'];
$social_logins = Settings::whereIn('key', $social_login_keys)->get();
$social_login_data = [];
foreach ($social_logins as $key => $social_login) {
$social_login_data[$social_login->key] = $social_login->value;
}
$sample_data['social_logins'] = $social_login_data;
$data['data'] = $sample_data;
$data = json_encode($data);
$folder_path_name = 'default-json/settings.json';
Storage::disk('public')->put($folder_path_name, $data);
}
public static function generate_email_code($value = "") {
return mt_rand(100000, 999999);
}
public static function generate_email_expiry() {
$token_expiry = Setting::get('token_expiry_hour') ?: 1;
return time() + $token_expiry*3600; // 1 Hour
}
public static function get_static_page_types() {
$page_types = ['about' , 'contact' , 'privacy' , 'terms' , 'help' , 'faq'];
foreach ($page_types as $key => $page_type) {
$check_page = StaticPage::where('type', $page_type)->first();
if($check_page) {
unset($page_types[$key]);
}
}
$page_types[] = 'others';
return $page_types;
}
public static function storage_upload_file_base($input_file, $folder_path = COMMON_FILE_PATH) {
$ext = explode('/', explode(':', substr($input_file, 0, strpos($input_file, ';')))[1])[1];
$replace = substr($input_file, 0, strpos($input_file, ',')+1);
$image = str_replace($replace, '', $input_file);
$image = str_replace(' ', '+', $image);
$file_name = self::generate_random_string().".".$ext;
$storage_file_path = $folder_path.$file_name;
Storage::disk('public')->put($storage_file_path, base64_decode($image));
return asset(Storage::url($storage_file_path));
}
public static function custom_validator($request, $request_inputs, $custom_errors = []) {
$validator = Validator::make($request, $request_inputs, $custom_errors);
if($validator->fails()) {
$error = implode(',', $validator->messages()->all());
throw new Exception($error, 101);
}
return $validator->validated();
}
public static function is_token_valid($entity, $id, $token, &$error) {
if (( $entity== USER && ($row = User::where('id', $id)->where('token', $token)->first()) )) {
if ($row->token_expiry > time()) {
$error = NULL;
return true;
} else {
$row->update(['is_logged_in' => NO]);
$error = ['success' => false, 'error' => api_error(1003), 'error_code' => 1003];
return FALSE;
}
}
$error = ['success' => false, 'error' => api_error(1004), 'error_code' => 1004];
return FALSE;
}
public static function check_model_exists($id, $type) {
switch($type) {
case USER :
$model = User::find($id, ['id', 'name']);
break;
case CATEGORY :
$model = Category::find($id, ['id', 'name']);
break;
case PRODUCT :
$model = Product::find($id, ['id', 'name']);
break;
case SUB_CATEGORY :
$model = SubCategory::find($id, ['id', 'name']);
break;
case DELIVERY_ADDRESS :
$model = DeliveryAddress::find($id, ['id', 'name']);
}
if(!$model) {
throw new Exception(tr('model_not_found', $type));
}
return $model;
}
public static function bids_stats_in_last_one_year() {
$bids = [];
for($month = 0; $month < 12 ; $month++) {
$formatted_date = now()->subMonth($month);
$last_one_year = Carbon::createFromFormat('m Y', $formatted_date->format('m Y'))->format('M - Y');
$bids[$last_one_year] = Bid::whereMonth('created_at', $formatted_date->format('m'))
->whereYear('created_at', $formatted_date->format('Y'))->count();
}
return array_reverse($bids);
}
public static function user_payments_stats_in_last_one_year() {
$user_wallet_payments = [];
for($month = 0; $month < 12 ; $month++) {
$formatted_date = now()->subMonth($month);
$last_one_year = Carbon::createFromFormat('m Y', $formatted_date->format('m Y'))->format('M - Y');
$user_wallet_payments[$last_one_year] = UserWalletPayment::where(['payment_type' => WALLET_PAYMENT_TYPE_CREDIT, 'status' => PAID])
->whereMonth('paid_date', $formatted_date->format('m'))
->whereYear('paid_date', $formatted_date->format('Y'))
->sum('amount');
}
return array_reverse($user_wallet_payments);
}
public static function user_withdrawals_stats_in_last_one_year() {
$user_withdrawals = [];
for($month = 0; $month < 12 ; $month++) {
$formatted_date = now()->subMonth($month);
$last_one_year = Carbon::createFromFormat('m Y', $formatted_date->format('m Y'))->format('M - Y');
$user_withdrawals[$last_one_year] = UserWithdrawal::where(['status' => PAID])
->whereMonth('updated_at', $formatted_date->format('m'))
->whereYear('updated_at', $formatted_date->format('Y'))
->sum('paid_amount');
}
return array_reverse($user_withdrawals);
}
/**
* @method cache_update_for_products()
*
* @uses to update user wishlists & carts product ids in cache to reduce sql requests.
*
* CACHE_REMEMBER_DURATION - Constant - cache will be rememberd for 10 mins.
*
* @created Karthick
*
* @updated
*
* @param
*
* @return
*/
public static function cache_update_for_products($user_id, $type) {
$user = User::find($user_id);
if($user) {
if($type == CART) {
Cache::forget("user_carts_$user_id");
Cache::remember("user_carts_$user_id", CACHE_REMEMBER_DURATION, function() use ($user) {
return $user->carts->count() ? $user->carts->pluck('product_id')->toArray() : [];
});
} elseif ($type == WISHLIST) {
Cache::forget("user_wishlists_$user_id");
Cache::remember("user_wishlists_$user_id", CACHE_REMEMBER_DURATION, function() use ($user) {
return $user->wishlists->count() ? $user->wishlists->pluck('product_id')->toArray() : [];
});
} else {
Cache::forget("user_carts_$user_id");
Cache::remember("user_carts_$user_id", CACHE_REMEMBER_DURATION, function() use ($user) {
return $user->carts->count() ? $user->carts->pluck('product_id')->toArray() : [];
});
Cache::forget("user_wishlists_$user_id");
Cache::remember("user_wishlists_$user_id", CACHE_REMEMBER_DURATION, function() use ($user) {
return $user->wishlists->count() ? $user->wishlists->pluck('product_id')->toArray() : [];
});
}
}
}
/**
* @method orders_day_graph()
*
* @uses to get the orders in last n days
*
* @created Karthick
*
* @updated
*
* @param
*
* @return days_count
*/
public static function orders_day_graph($days_count, $status = '') {
$orders = [];
for($day = 0; $day < $days_count ; $day++) {
$formatted_date = now()->subDays($day);
$last_n_days = Carbon::createFromFormat('d m Y', $formatted_date->format('d m Y'))->format('d M - Y');
$orders[$last_n_days] = Order::when($status, function($query) use ($status) {
$query->where(['status' => $status]);
})->whereDate('created_at', $formatted_date)
->count();
}
return array_reverse($orders);
}
/**
* @method orders_n_days_graph()
*
* @uses to get the order payment transactions in last n days
*
* @created Karthick
*
* @updated
*
* @param
*
* @return days_count, status
*/
public static function orders_n_days_graph($days_count, $status = '') {
$order_payments = [];
for($day = 0; $day < $days_count ; $day++) {
$formatted_date = now()->subDays($day);
$last_n_days = Carbon::createFromFormat('d m Y', $formatted_date->format('d m Y'))->format('d M - Y');
$order_payments[$last_n_days] = Order::when($status, function($query) use ($status) {
$query->where(['status' => $status]);
})->whereDate('created_at', $formatted_date)
->count();
}
return array_reverse($order_payments);
}
/**
* @method orders_month_graph()
*
* @uses to get the payment transactions in last n months
*
* @created Karthick
*
* @updated
*
* @param
*
* @return month_count, status
*/
public static function orders_month_graph($month_count, $status = '') {
$orders = [];
for($month = 0; $month < $month_count ; $month++) {
$formatted_date = now()->subMonth($month);
$last_n_months = Carbon::createFromFormat('m Y', $formatted_date->format('m Y'))->format('M - Y');
$orders[$last_n_months] = Order::when($status, function($query) use ($status) {
$query->where(['status' => $status]);
})
->whereMonth('created_at', $formatted_date->format('m'))
->whereYear('created_at', $formatted_date->format('Y'))
->count();
}
return array_reverse($orders);
}
/**
* @method order_payments_n_days_graph()
*
* @uses to get the order payment transactions in last n days
*
* @created Karthick
*
* @updated
*
* @param
*
* @return days_count, status
*/
public static function order_payments_n_days_graph($days_count, $status = '') {
$order_payments = [];
for($day = 0; $day < $days_count ; $day++) {
$formatted_date = now()->subDays($day);
$last_n_days = Carbon::createFromFormat('d m Y', $formatted_date->format('d m Y'))->format('d M - Y');
$order_payments[$last_n_days] = Order::when($status, function($query) use ($status) {
$query->where(['status' => $status]);
})->whereDate('created_at', $formatted_date)
->sum('total');
}
return array_reverse($order_payments);
}
/**
* @method order_payments_month_graph()
*
* @uses to get the order payments transactions in last n months
*
* @created Karthick
*
* @updated
*
* @param
*
* @return month_count, status
*/
public static function order_payments_month_graph($month_count, $status = '') {
$orders = [];
for($month = 0; $month < $month_count ; $month++) {
$formatted_date = now()->subMonth($month);
$last_n_months = Carbon::createFromFormat('m Y', $formatted_date->format('m Y'))->format('M - Y');
$orders[$last_n_months] = Order::when($status, function($query) use ($status) {
$query->where(['status' => $status]);
})
->whereMonth('created_at', $formatted_date->format('m'))
->whereYear('created_at', $formatted_date->format('Y'))
->sum('total');
}
return array_reverse($orders);
}
/**
* @method order_payments_month_graph_for_single_product()
*
* @uses to get the order payments transactions in last n months
*
* @created Karthick
*
* @updated
*
* @param
*
* @return month_count, status
*/
public static function order_payments_month_graph_for_single_product($month_count, $order_ids) {
$orders = [];
$months = [];
for($month = 0; $month < $month_count ; $month++) {
$formatted_date = now()->subMonth($month);
$months[] = Carbon::createFromFormat('m Y', $formatted_date->format('m Y'))->format('M - Y');
$orders[$month] = Order::whereIn('id', $order_ids)
->whereMonth('created_at', $formatted_date->format('m'))
->whereYear('created_at', $formatted_date->format('Y'))
->sum('total');
}
$data['orders'] = array_reverse($orders);
$data['months'] = array_reverse($months);
return $data;
}
}
Back to Directory
File Manager