Viewing file: CustomerController.php (33.55 KB) -rw-r--r-- Select action/file-type: (+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
<?php
namespace App\Http\Controllers;
use App\Exports\CustomerExport; use App\Imports\CustomerImport; use App\Models\Customer; use App\Models\CustomField; use App\Models\Meterage; use App\Models\Mileage; use App\Models\TaxiOrder; use App\Models\Transaction; use App\Models\Utility; use App\PaymentProvider\ProcessPayment; use Auth; use App\Models\User; use App\Models\Plan; use File; use Illuminate\Http\Request; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Mail; use Maatwebsite\Excel\Facades\Excel; use Spatie\Permission\Models\Role; use Illuminate\Validation\Rule; use GuzzleHttp\Client; use Illuminate\Support\Carbon;
class CustomerController extends Controller {
public function dashboard() { $data['invoiceChartData'] = \Auth::user()->invoiceChartData();
return view('customer.dashboard', $data); }
public function index() { if(\Auth::user()->can('manage customer')) { $customers = Customer::where('created_by', \Auth::user()->creatorId())->get();
return view('customer.index', compact('customers')); } else { return redirect()->back()->with('error', __('Permission denied.')); } }
public function create() { if(\Auth::user()->can('create customer')) { $customFields = CustomField::where('created_by', '=', \Auth::user()->creatorId())->where('module', '=', 'customer')->get();
return view('customer.create', compact('customFields')); } else { return redirect()->back()->with('error', __('Permission denied.')); } }
public function store(Request $request) { if(\Auth::user()->can('create customer')) {
$rules = [ 'name' => 'required', 'contact' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/', 'email' => [ 'required', Rule::unique('customers')->where(function ($query) { return $query->where('created_by', \Auth::user()->id); }) ], ];
$validator = \Validator::make($request->all(), $rules);
if($validator->fails()) { $messages = $validator->getMessageBag(); return redirect()->route('customer.index')->with('error', $messages->first()); }
$objCustomer = \Auth::user(); $creator = User::find($objCustomer->creatorId()); $total_customer = $objCustomer->countCustomers(); $plan = Plan::find($creator->plan);
$default_language = DB::table('settings')->select('value')->where('name', 'default_language')->first(); if($total_customer < $plan->max_customers || $plan->max_customers == -1) { $customer = new Customer(); $customer->customer_id = $this->customerNumber(); $customer->name = $request->name; $customer->contact = $request->contact; $customer->email = $request->email; $customer->tax_number =$request->tax_number; $customer->created_by = \Auth::user()->creatorId(); $customer->billing_name = $request->billing_name; $customer->billing_country = $request->billing_country; $customer->billing_state = $request->billing_state; $customer->billing_city = $request->billing_city; $customer->billing_phone = $request->billing_phone; $customer->billing_zip = $request->billing_zip; $customer->billing_address = $request->billing_address;
$customer->shipping_name = $request->shipping_name; $customer->shipping_country = $request->shipping_country; $customer->shipping_state = $request->shipping_state; $customer->shipping_city = $request->shipping_city; $customer->shipping_phone = $request->shipping_phone; $customer->shipping_zip = $request->shipping_zip; $customer->shipping_address = $request->shipping_address;
$customer->lang = !empty($default_language) ? $default_language->value : '';
$customer->save(); CustomField::saveData($customer, $request->customField); } else { return redirect()->back()->with('error', __('Your user limit is over, Please upgrade plan.')); }
//For Notification $setting = Utility::settings(\Auth::user()->creatorId()); $customerNotificationArr = [ 'user_name' => \Auth::user()->name, 'customer_name' => $customer->name, 'customer_email' => $customer->email, ];
//Twilio Notification if(isset($setting['twilio_customer_notification']) && $setting['twilio_customer_notification'] ==1) { Utility::send_twilio_msg($request->contact,'new_customer', $customerNotificationArr); }
return redirect()->route('customer.index')->with('success', __('Customer successfully created.')); } else { return redirect()->back()->with('error', __('Permission denied.')); } }
public function show($ids) { try { $id = Crypt::decrypt($ids); } catch (\Throwable $th) { return redirect()->back()->with('error', __('Customer Not Found.')); } $id = \Crypt::decrypt($ids); $customer = Customer::find($id);
return view('customer.show', compact('customer')); }
public function edit($id) { if(\Auth::user()->can('edit customer')) { $customer = Customer::find($id); $customer->customField = CustomField::getData($customer, 'customer');
$customFields = CustomField::where('created_by', '=', \Auth::user()->creatorId())->where('module', '=', 'customer')->get();
return view('customer.edit', compact('customer', 'customFields')); } else { return redirect()->back()->with('error', __('Permission denied.')); } }
public function update(Request $request, Customer $customer) {
if(\Auth::user()->can('edit customer')) {
$rules = [ 'name' => 'required', 'contact' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/', ];
$validator = \Validator::make($request->all(), $rules); if($validator->fails()) { $messages = $validator->getMessageBag();
return redirect()->route('customer.index')->with('error', $messages->first()); }
$customer->name = $request->name; $customer->contact = $request->contact; $customer->email = $request->email; $customer->tax_number =$request->tax_number; $customer->created_by = \Auth::user()->creatorId(); $customer->billing_name = $request->billing_name; $customer->billing_country = $request->billing_country; $customer->billing_state = $request->billing_state; $customer->billing_city = $request->billing_city; $customer->billing_phone = $request->billing_phone; $customer->billing_zip = $request->billing_zip; $customer->billing_address = $request->billing_address; $customer->shipping_name = $request->shipping_name; $customer->shipping_country = $request->shipping_country; $customer->shipping_state = $request->shipping_state; $customer->shipping_city = $request->shipping_city; $customer->shipping_phone = $request->shipping_phone; $customer->shipping_zip = $request->shipping_zip; $customer->shipping_address = $request->shipping_address; $customer->save();
CustomField::saveData($customer, $request->customField);
return redirect()->route('customer.index')->with('success', __('Customer successfully updated.')); } else { return redirect()->back()->with('error', __('Permission denied.')); } }
public function destroy(Customer $customer) { if(\Auth::user()->can('delete customer')) { if($customer->created_by == \Auth::user()->creatorId()) { $customer->delete();
return redirect()->route('customer.index')->with('success', __('Customer successfully deleted.')); } else { return redirect()->back()->with('error', __('Permission denied.')); } } else { return redirect()->back()->with('error', __('Permission denied.')); } }
function customerNumber() { $latest = Customer::where('created_by', '=', \Auth::user()->creatorId())->latest()->first(); if(!$latest) { return 1; }
return $latest->customer_id + 1; }
public function customerLogout(Request $request) { \Auth::guard('customer')->logout();
$request->session()->invalidate();
return redirect()->route('customer.login'); }
public function payment(Request $request) {
if(\Auth::user()->can('manage customer payment')) { $category = [ 'Invoice' => 'Invoice', 'Deposit' => 'Deposit', 'Sales' => 'Sales', ];
$query = Transaction::where('user_id', \Auth::user()->id)->where('user_type', 'Customer')->where('type', 'Payment'); if(!empty($request->date)) { $date_range = explode(' - ', $request->date); $query->whereBetween('date', $date_range); }
if(!empty($request->category)) { $query->where('category', '=', $request->category); } $payments = $query->get();
return view('customer.payment', compact('payments', 'category')); } else { return redirect()->back()->with('error', __('Permission denied.')); } }
public function transaction(Request $request) { if(\Auth::user()->can('manage customer payment')) { $category = [ 'Invoice' => 'Invoice', 'Deposit' => 'Deposit', 'Sales' => 'Sales', ];
$query = Transaction::where('user_id', \Auth::user()->id)->where('user_type', 'Customer');
if(!empty($request->date)) { $date_range = explode(' - ', $request->date); $query->whereBetween('date', $date_range); }
if(!empty($request->category)) { $query->where('category', '=', $request->category); } $transactions = $query->get();
return view('customer.transaction', compact('transactions', 'category')); } else { return redirect()->back()->with('error', __('Permission denied.')); } }
public function profile() { $userDetail = \Auth::user(); $userDetail->customField = CustomField::getData($userDetail, 'customer'); $customFields = CustomField::where('created_by', '=', \Auth::user()->creatorId())->where('module', '=', 'customer')->get();
return view('customer.profile', compact('userDetail', 'customFields')); }
public function editprofile(Request $request) { $userDetail = \Auth::user(); $user = Customer::findOrFail($userDetail['id']);
$this->validate( $request, [ 'name' => 'required|max:120', 'contact' => 'required', 'email' => 'required|email|unique:users,email,' . $userDetail['id'], ] );
if($request->hasFile('profile')) { $filenameWithExt = $request->file('profile')->getClientOriginalName(); $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME); $extension = $request->file('profile')->getClientOriginalExtension(); $fileNameToStore = $filename . '_' . time() . '.' . $extension;
$dir = storage_path('uploads/avatar/'); $image_path = $dir . $userDetail['avatar'];
if(File::exists($image_path)) { File::delete($image_path); }
if(!file_exists($dir)) { mkdir($dir, 0777, true); }
$path = $request->file('profile')->storeAs('uploads/avatar/', $fileNameToStore);
}
if(!empty($request->profile)) { $user['avatar'] = $fileNameToStore; } $user['name'] = $request['name']; $user['email'] = $request['email']; $user['contact'] = $request['contact']; $user->save(); CustomField::saveData($user, $request->customField);
return redirect()->back()->with( 'success', 'Profile successfully updated.' ); }
public function editBilling(Request $request) { $userDetail = \Auth::user(); $user = Customer::findOrFail($userDetail['id']); $this->validate( $request, [ 'billing_name' => 'required', 'billing_country' => 'required', 'billing_state' => 'required', 'billing_city' => 'required', 'billing_phone' => 'required', 'billing_zip' => 'required', 'billing_address' => 'required', ] ); $input = $request->all(); $user->fill($input)->save();
return redirect()->back()->with( 'success', 'Profile successfully updated.' ); }
public function editShipping(Request $request) { $userDetail = \Auth::user(); $user = Customer::findOrFail($userDetail['id']); $this->validate( $request, [ 'shipping_name' => 'required', 'shipping_country' => 'required', 'shipping_state' => 'required', 'shipping_city' => 'required', 'shipping_phone' => 'required', 'shipping_zip' => 'required', 'shipping_address' => 'required', ] ); $input = $request->all(); $user->fill($input)->save();
return redirect()->back()->with( 'success', 'Profile successfully updated.' ); }
public function changeLanquage($lang) {
$user = Auth::user(); $user->lang = $lang; $user->save();
return redirect()->back()->with('success', __('Language Change Successfully!'));
}
public function export() { $name = 'customer_' . date('Y-m-d i:h:s'); $data = Excel::download(new CustomerExport(), $name . '.xlsx'); ob_end_clean();
return $data; }
public function importFile() { return view('customer.import'); }
public function import(Request $request) {
$rules = [ 'file' => 'required|mimes:csv,txt', ];
$validator = \Validator::make($request->all(), $rules);
if($validator->fails()) { $messages = $validator->getMessageBag();
return redirect()->back()->with('error', $messages->first()); }
$customers = (new CustomerImport())->toArray(request()->file('file'))[0];
$totalCustomer = count($customers) - 1; $errorArray = []; for($i = 1; $i <= count($customers) - 1; $i++) { $customer = $customers[$i];
$customerByEmail = Customer::where('email', $customer[2])->first(); if(!empty($customerByEmail)) { $customerData = $customerByEmail; } else { $customerData = new Customer(); $customerData->customer_id = $this->customerNumber(); }
$customerData->customer_id = $customer[0]; $customerData->name = $customer[1]; $customerData->email = $customer[2]; $customerData->contact = $customer[3]; $customerData->is_active = 1; $customerData->billing_name = $customer[4]; $customerData->billing_country = $customer[5]; $customerData->billing_state = $customer[6]; $customerData->billing_city = $customer[7]; $customerData->billing_phone = $customer[8]; $customerData->billing_zip = $customer[9]; $customerData->billing_address = $customer[10]; $customerData->shipping_name = $customer[11]; $customerData->shipping_country = $customer[12]; $customerData->shipping_state = $customer[13]; $customerData->shipping_city = $customer[14]; $customerData->shipping_phone = $customer[15]; $customerData->shipping_zip = $customer[16]; $customerData->shipping_address = $customer[17]; $customerData->balance = $customer[18]; $customerData->created_by = \Auth::user()->creatorId();
if(empty($customerData)) { $errorArray[] = $customerData; } else { $customerData->save(); } }
$errorRecord = []; if(empty($errorArray)) { $data['status'] = 'success'; $data['msg'] = __('Record successfully imported'); } else { $data['status'] = 'error'; $data['msg'] = count($errorArray) . ' ' . __('Record imported fail out of' . ' ' . $totalCustomer . ' ' . 'record');
foreach($errorArray as $errorData) {
$errorRecord[] = implode(',', $errorData);
}
\Session::put('errorArray', $errorRecord); }
return redirect()->back()->with($data['status'], $data['msg']); }
public function searchCustomers(Request $request) { if (\Illuminate\Support\Facades\Auth::user()->can('manage customer')) { $customers = []; $search = $request->search; if ($request->ajax() && isset($search) && !empty($search)) { $customers = Customer::select('id as value', 'name as label', 'email')->where('is_active', '=', 1)->where('created_by', '=', Auth::user()->getCreatedBy())->Where('name', 'LIKE', '%' . $search . '%')->orWhere('email', 'LIKE', '%' . $search . '%')->get();
return json_encode($customers); }
return $customers; } else { return redirect()->back()->with('error', __('Permission denied.')); } }
public function customer_order_request() { $auth = \Auth::user();
if($auth->type=='customer'){ $all_taxi_orders = TaxiOrder::where('assigned_customer_id', $auth->id) ->where('status', 'accepted') ->get(); $data['all_orders'] = $all_taxi_orders->count(); $currentDate = Carbon::now()->toDateString(); $data['todays_orders'] = TaxiOrder::where('assigned_customer_id', $auth->id)->where('status', 'accepted')->whereDate('created_at', $currentDate)->count();
$texiorders = TaxiOrder::where('email',$auth->email)->get(); return view('customer.index',compact('texiorders')); }else { return redirect()->back()->with('error', __('Permission denied.')); }
} public function order_create() { if (!user_current_plan()) { return abort(404); } $auth = \Auth::user(); $auth_created_id = $auth->created_by; $data['meterage'] = Meterage::where('created_by',$auth_created_id)->first(); $data['company_payment_setting'] = Utility::getCompanyPaymentSetting(\Auth::user()->creatorId()); $data['last_order'] = TaxiOrder::where('assigned_customer_id',$auth->id)->orderByDesc('created_at')->first(); return view('customer.order_create', $data); }
public function customer_order_request_store(Request $request){ DB::beginTransaction(); try{ if (!user_current_plan()) { return abort(404); } $validator = \Validator::make( $request->all(), [ 'name' => 'required', 'phone_number' => 'required', 'pickup_address' => 'required', 'destination_address' => 'required', 'payment_type' => 'required', ] ); if($validator->fails()) { $messages = $validator->getMessageBag(); return redirect()->back()->with('error', $messages->first())->withInput($request->all()); } $auth = \Auth::user(); $client = new Client(); $auth_created_id = $auth->created_by; $meterage_charge = Meterage::where('created_by',$auth_created_id)->first(); $per_milege_charge=isset($meterage_charge->per_meterage_charge)?$meterage_charge->per_meterage_charge:0; $trip_charges=isset($meterage_charge->trip_charge)?$meterage_charge->trip_charge:0; $extra_chrages=isset($meterage_charge->extra_chrage)?$meterage_charge->extra_chrage:0; $apiKey = env('GOOGLE_API_KEY'); // Replace with your actual Google Maps API key $pickup_lat_lng = $request->pickup_lat_lng; $destination_lat_lng = $request->destination_lat_lng; // Calculate distance $response = $client->get("https://maps.googleapis.com/maps/api/distancematrix/json?key=$apiKey&origins=$pickup_lat_lng&destinations=$destination_lat_lng&mode=driving"); $data = json_decode($response->getBody(), true); $distance = $data['rows'][0]['elements'][0]['distance']['value']; // Distance in meters $distance_in_miles = $distance / 1609.344; // Calculate cost or do whatever you want with distance $others_charges = $trip_charges+$extra_chrages; $sub_total = $distance_in_miles * $per_milege_charge; // Calculate cost or do whatever you want with distance $total_cost = $sub_total + $others_charges; if($meterage_charge){ $taxi_order = new TaxiOrder(); $taxi_order->name = $auth->name; $taxi_order->phone_number = $auth->phone_number; $taxi_order->email = $auth->email; $taxi_order->pickup_address = $request->pickup_address; $taxi_order->destination_address = $request->destination_address; $taxi_order->total_km = $distance_in_miles; $taxi_order->kilometer_price = $per_milege_charge; $taxi_order->total_cost = $total_cost; $taxi_order->pickup_lat_lng = $request->pickup_lat_lng; $taxi_order->destination_lat_lng = $request->destination_lat_lng; $taxi_order->status = 'pending'; $taxi_order->created_by = \Auth::user()->creatorId(); $taxi_order->company_id = \Auth::user()->creatorId(); $taxi_order->how_mobile_in_the_member = $request->how_mobile_in_the_member; $taxi_order->steps_or_ramp = $request->steps_or_ramp; $taxi_order->special_needs = $request->special_needs; $taxi_order->height_of_member = $request->height_of_member; $taxi_order->weight_of_member = $request->weight_of_member; $taxi_order->someone_knows_this_trip = $request->someone_knows_this_trip; // $taxi_order->transfer_wheelchair_to_car = $request->transfer_wheelchair_to_car; $taxi_order->wheelchair_type = $request->wheelchair_type; $taxi_order->preferred_pickup_time = $request->preferred_pickup_time; $taxi_order->personal_care_attendants = $request->personal_care_attendants; $taxi_order->adult_escorts = $request->adult_escorts; $taxi_order->child_escorts = $request->child_escorts; $taxi_order->child_seats = $request->child_seats; // $taxi_order->member_sign_drivers_log = $request->member_sign_drivers_log; $taxi_order->pickup_location_phone_number = $request->pickup_location_phone_number; $taxi_order->instuctions_for_driver = $request->instuctions_for_driver; $taxi_order->pickup_date = $request->pickup_date; $taxi_order->appointment_time = $request->appointment_time; $taxi_order->drop_off_location_phone_number = $request->drop_off_location_phone_number; $taxi_order->payment_type= $request->payment_type; $taxi_order->trx_id = \Str::random(15); $taxi_order->save(); DB::commit(); $company_payment_setting = Utility::getCompanyPaymentSetting(\Auth::user()->creatorId()); if($request->payment_type=='paypal'){ if(isset($company_payment_setting['is_paypal_enabled']) && $company_payment_setting['is_paypal_enabled']=='on' && isset($company_payment_setting['paypal_client_id']) && $company_payment_setting['paypal_secret_key']){ $process_pyment= new ProcessPayment(); $process_pyment=$process_pyment->gateway('paypal') ->type('taxi-order') ->credentials($company_payment_setting) ->amount($total_cost) ->data($taxi_order) ->process(); if ($process_pyment->error_message) { return redirect()->route('customer.order.request')->with('success', __('Order partially created.')); } if ($process_pyment->return_view) { return $process_pyment->return_view; } elseif ($process_pyment->will_redirect && $process_pyment->redirect_url) { return redirect()->to($process_pyment->redirect_url); } else { return redirect()->route('customer.order.request')->with('success', __('Order partially created.')); } } } return redirect()->back()->with('success', __('Order Successfully created!')); } else { return redirect()->back()->with('error', __('Something wrong please try later')); } } catch (\Exception $e) { DB::rollback(); return redirect()->back()->with('error', __('Something went wrong. Please try again later.')); } }
public function customer_order_request_edit($id){ if (!user_current_plan()) { return abort(404); } $auth = \Auth::user(); $auth_created_id = $auth->created_by; $taxi_order = TaxiOrder::findOrFail($id); $meterage = Meterage::where('created_by',$auth_created_id)->first(); if ($taxi_order->email == \Auth::user()->email) { return view('customer.edit_order', compact('taxi_order','meterage')); } }
public function customer_order_update(Request $request, $id){ if (!user_current_plan()) { return abort(404); } $taxi_order = TaxiOrder::findOrFail($request->id); $validator = \Validator::make( $request->all(), [ 'pickup_address' => 'required', 'destination_address' => 'required', 'payment_type' => 'required', ] ); if($validator->fails()) { $messages = $validator->getMessageBag();
return redirect()->back()->with('error', $messages->first()); } $auth = \Auth::user(); $auth_created_id = $auth->created_by; $client = new Client(); $meterage_charge = Meterage::where('created_by',$auth_created_id)->first(); $per_milege_charge=isset($meterage_charge->per_meterage_charge)?$meterage_charge->per_meterage_charge:0; $trip_charges=isset($meterage_charge->trip_charge)?$meterage_charge->trip_charge:0; $extra_chrages=isset($meterage_charge->extra_chrage)?$meterage_charge->extra_chrage:0;
$apiKey = env('GOOGLE_API_KEY'); // Replace with your actual Google Maps API key
$pickup_lat_lng = $request->pickup_lat_lng; $destination_lat_lng = $request->destination_lat_lng;
// Calculate distance $response = $client->get("https://maps.googleapis.com/maps/api/distancematrix/json?key=$apiKey&origins=$pickup_lat_lng&destinations=$destination_lat_lng&mode=driving"); $data = json_decode($response->getBody(), true); $distance = $data['rows'][0]['elements'][0]['distance']['value']; // Distance in meters $distance_in_miles = $distance / 1609.344;
// Calculate cost or do whatever you want with distance $total_cost = $distance_in_miles * $per_milege_charge; // Define YOUR_COST_PER_METER accordingly
if($per_milege_charge){ $taxi_order->name = $auth->name; $taxi_order->phone_number = $auth->phone_number; $taxi_order->email = $auth->email; $taxi_order->pickup_address = $request->pickup_address; $taxi_order->destination_address = $request->destination_address; $taxi_order->total_km = $distance_in_miles; $taxi_order->kilometer_price = $per_milege_charge; $taxi_order->total_cost = $total_cost; $taxi_order->pickup_lat_lng = $request->pickup_lat_lng; $taxi_order->destination_lat_lng = $request->destination_lat_lng; $taxi_order->status = 'pending'; $taxi_order->created_by = \Auth::user()->creatorId(); $taxi_order->company_id = \Auth::user()->creatorId(); $taxi_order->how_mobile_in_the_member = $request->how_mobile_in_the_member; $taxi_order->steps_or_ramp = $request->steps_or_ramp; $taxi_order->special_needs = $request->special_needs; $taxi_order->height_of_member = $request->height_of_member; $taxi_order->weight_of_member = $request->weight_of_member; $taxi_order->someone_knows_this_trip = $request->someone_knows_this_trip; // $taxi_order->transfer_wheelchair_to_car = $request->transfer_wheelchair_to_car; $taxi_order->wheelchair_type = $request->wheelchair_type; $taxi_order->preferred_pickup_time = $request->preferred_pickup_time; $taxi_order->personal_care_attendants = $request->personal_care_attendants; $taxi_order->adult_escorts = $request->adult_escorts; $taxi_order->child_escorts = $request->child_escorts; $taxi_order->child_seats = $request->child_seats; // $taxi_order->member_sign_drivers_log = $request->member_sign_drivers_log; $taxi_order->pickup_location_phone_number = $request->pickup_location_phone_number; $taxi_order->instuctions_for_driver = $request->instuctions_for_driver; $taxi_order->pickup_date = $request->pickup_date; $taxi_order->appointment_time = $request->appointment_time; $taxi_order->drop_off_location_phone_number = $request->drop_off_location_phone_number; $taxi_order->payment_type= $request->payment_type; if($request->payment_type=='offline'){ $taxi_order->trx_id = \Str::random(15); } $taxi_order->save(); return redirect()->back()->with('success', __('Order Successfully updated!')); } else { return redirect()->back()->with('error', __('Something wrong please try later')); } }
public function customer_order_destroy($id){ if (!user_current_plan()) { return abort(404); } $order = TaxiOrder::findOrFail($id); if($order) { $order->delete(); return redirect()->back()->with('success', __('Order successfully deleted.')); } else { return redirect()->back()->with('error', __('Permission denied.')); } }
}
|