getQuoteRepository = $getQuoteRepository; $this->quoteService = $quoteService; } public function index(Request $request) { //Removing data of previous quotes if in session. $request->session()->forget('quotes'); $request->session()->forget('parcels'); $request->session()->forget('quote_input'); $countries = Country::all(); return view('quotes.index', [ 'countries' => $countries, ]); } public function showResult(Request $request) { $responseData = $request->session()->get('quotes'); if ($responseData) { $sort = $request->query('sort'); if ($sort) { if ($sort == 'lowToHigh') { usort($responseData, function ($a, $b) { return $a['price']['total'] <=> $b['price']['total']; }); } elseif ($sort == 'highToLow') { usort($responseData, function ($a, $b) { return $b['price']['total'] <=> $a['price']['total']; }); } } return view('quotes.qoute-result', compact('responseData')); } else { return redirect()->back(); } } public function getQuote(Request $request) { $packageType = $request->input('package_type'); $request->session()->put('quote_input', $request->all()); if ($packageType == 'parcel') { return $this->getParcelQuote($request); } elseif ($packageType == 'pallet') { return $this->getPalletQuote($request); // return response()->json(['error' => "No quotes were found for the provided data. We apologize for the inconvenience."], 200); } return redirect()->back(); } public function getParcelQuote(Request $request) { // Validate the request $validator = Validator::make($request->all(), [ 'country' => 'required', 'postal' => 'required', 'dim_length.*' => 'required|numeric', 'dim_width.*' => 'required|numeric', 'dim_height.*' => 'required|numeric', 'dim_unit.*' => 'required', 'unit_weight.*' => 'required|numeric', 'weight_unit.*' => 'required', ]); if ($validator->fails()) { $errors = $validator->errors(); return response()->json(['errors' => $errors], 422); } // Prepare the request body $parcels = []; $dimLength = $request->input('dim_length'); $dimWidth = $request->input('dim_width'); $dimHeight = $request->input('dim_height'); $dimUnit = $request->input('dim_unit'); $unitWeight = $request->input('unit_weight'); $weightUnit = $request->input('weight_unit'); for ($i = 0; $i < count($dimLength); $i++) { $parcel = [ 'dim_length' => $dimLength[$i], 'dim_width' => $dimWidth[$i], 'dim_height' => $dimHeight[$i], 'dim_unit' => $dimUnit[$i], 'items' => [ [ "description" => "item " . ($i + 1), "sku" => $this->generateRandomOrderId(), 'quantity' => 1, 'weight' => (int) $unitWeight[$i], 'unit_weight' => $unitWeight[$i], 'weight_unit' => $weightUnit[$i], 'hs_code' => '', ], ], ]; $parcels[] = $parcel; } $response = $this->generateQuotes($parcels, $request); // Handle the API response if ($response->getStatusCode() === 200) { $responseData = json_decode($response->getBody()->getContents(), true); if (!auth()->user()->hasPermissionTo('couriers')) { // Get the allowed courier IDs $allowedCouriers = AllowedCourriers::where('user_id', auth()->user()->id) ->join('parent_couriers', 'user_allowed_courriers.courier_id', '=', 'parent_couriers.id') ->where('parent_couriers.active', 1) ->get(); $allowedCourierNames = []; foreach ($allowedCouriers as $c) { $courier = ParentCourier::find($c->courier_id); $allowedCourierNames[] = $courier->courier_name; } // Filter the responseData based on allowed courier names $responseData = array_filter($responseData, function ($item) use ($allowedCourierNames) { return in_array($item['courier'], $allowedCourierNames); }); } // Add margin to each quote's total price foreach ($responseData as &$quote) { // Find the allowed courier's margin if (!auth()->user()->hasPermissionTo('couriers')) { $allowedCourier = AllowedCourriers::where('user_id', auth()->user()->id) ->join('parent_couriers', 'user_allowed_courriers.courier_id', '=', 'parent_couriers.id') ->where('parent_couriers.courier_name', $quote['courier']) ->first(); } else { $allowedCourier = ParentCourier::where('parent_couriers.courier_name', $quote['courier']) ->first(); } if ($allowedCourier) { // Calculate the margin amount (percentage of total) $marginPercentage = $allowedCourier->courier_margin ?? 0; $vat = ($quote['price']['total']) * (auth()->user()->isVat ? (float) (auth()->user()->vatPercentage / 100) : 0); $totalPrice = round($quote['price']['total'] + $vat, 2); $margin = round(($totalPrice * $marginPercentage) / 100, 2); // Add the margin to the quote's data $quote['margin'] = $margin; if ($allowedCourier->display_name) { $quote['display_name'] = $allowedCourier->display_name; } else { $quote['display_name'] = $allowedCourier->courier_name; } // Calculate the new total price with margin $quote['total_with_margin'] = round($totalPrice + $margin, 2); } } if (!auth()->user()->hasPermissionTo('couriers')) { // Re-index the array after filtering $responseData = array_values($responseData); } // Process the response data and return the result if (!empty($responseData)) { $request->session()->put('parcels', $parcels); $request->session()->put('quotes', $responseData); return response()->json(['success' => $responseData], $response->getStatusCode()); } else { // Handle the case when there are no quotes available for the allowed couriers return response()->json(['error' => 'No quotes available for allowed couriers'], 404); } } else { // Handle the API error response $errorResponse = $response->getBody()->getContents(); return response()->json(['error' => $errorResponse], $response->getStatusCode()); } } public function getPalletQuote(Request $request) { // return $request->all(); // Validate the request $validator = Validator::make($request->all(), [ 'country' => 'required', 'postal' => 'required', ]); if ($validator->fails()) { $errors = $validator->errors(); return response()->json(['errors' => $errors], 422); } // Prepare the request body $parcels = []; if (!empty($request->input('micro_dim_quantity'))) { $parcels[] = [ 'dim_length' => '100', 'dim_width' => '120', 'dim_height' => '60', 'dim_unit' => 'cm', 'items' => [ [ "description" => "mirco pallet", "sku" => $this->generateRandomOrderId(), 'quantity' => (int) $request->input('micro_dim_quantity'), 'weight' => (int) $request->input('micro_dim_weight'), 'unit_weight' => $request->input('micro_dim_weight'), 'weight_unit' => 'kg', 'hs_code' => '', ], ], ]; } if (!empty($request->input('medium_dim_quantity'))) { $parcels[] = [ 'dim_length' => '120', 'dim_width' => '100', 'dim_height' => '60', 'dim_unit' => 'cm', 'items' => [ [ "description" => "medium pallet", "sku" => $this->generateRandomOrderId(), 'quantity' => (int) $request->input('medium_dim_quantity'), 'weight' => (int) $request->input('medium_dim_weight'), 'unit_weight' => $request->input('medium_dim_weight'), 'weight_unit' => 'kg', 'hs_code' => '', ], ], ]; } if (!empty($request->input('large_dim_quantity'))) { $parcels[] = [ 'dim_length' => '120', 'dim_width' => '100', 'dim_height' => '60', 'dim_unit' => 'cm', 'items' => [ [ "description" => "large pallet", "sku" => $this->generateRandomOrderId(), 'quantity' => (int) $request->input('large_dim_quantity'), 'weight' => (int) $request->input('large_dim_weight'), 'unit_weight' => $request->input('large_dim_weight'), 'weight_unit' => 'kg', 'hs_code' => '', ], ], ]; } if (!empty($request->input('custom_dim_quantity'))) { $parcels[] = [ 'dim_length' => $request->input('custom_dim_length'), 'dim_width' => $request->input('custom_dim_width'), 'dim_height' => $request->input('custom_dim_height'), 'dim_unit' => 'cm', 'items' => [ [ "description" => "custom pallet", "sku" => $this->generateRandomOrderId(), 'quantity' => (int) $request->input('custom_dim_quantity'), 'weight' => (int) $request->input('custom_dim_weight'), 'unit_weight' => $request->input('custom_dim_weight'), 'weight_unit' => 'kg', 'hs_code' => '', ], ], ]; } $response = $this->generateQuotes($parcels, $request); // Handle the API response if ($response->getStatusCode() === 200) { $responseData = json_decode($response->getBody()->getContents(), true); if (!auth()->user()->hasPermissionTo('couriers')) { // Get the allowed courier IDs $allowedCouriers = AllowedCourriers::where('user_id', auth()->user()->id) ->join('parent_couriers', 'user_allowed_courriers.courier_id', '=', 'parent_couriers.id') ->where('parent_couriers.active', 1) ->get(); $allowedCourierNames = []; foreach ($allowedCouriers as $c) { $courier = ParentCourier::find($c->courier_id); $allowedCourierNames[] = $courier->courier_name; } // Filter the responseData based on allowed courier names $responseData = array_filter($responseData, function ($item) use ($allowedCourierNames) { return in_array($item['courier'], $allowedCourierNames) && $item['courier'] == 'PalletWays'; }); } // Add margin to each quote's total price foreach ($responseData as &$quote) { // Find the allowed courier's margin if (!auth()->user()->hasPermissionTo('couriers')) { $allowedCourier = AllowedCourriers::where('user_id', auth()->user()->id) ->join('parent_couriers', 'user_allowed_courriers.courier_id', '=', 'parent_couriers.id') ->where('parent_couriers.courier_name', $quote['courier']) ->first(); } else { $allowedCourier = ParentCourier::where('parent_couriers.courier_name', $quote['courier']) ->first(); } if ($allowedCourier) { // Calculate the margin amount (percentage of total) $marginPercentage = $allowedCourier->courier_margin ?? 0; $vat = ($quote['price']['total']) * (auth()->user()->isVat ? (float) (auth()->user()->vatPercentage / 100) : 0); $totalPrice = $quote['price']['total'] + $vat; $margin = ($totalPrice * $marginPercentage) / 100; // Add the margin to the quote's data $quote['margin'] = $margin; if ($allowedCourier->display_name) { $quote['display_name'] = $allowedCourier->display_name; } else { $quote['display_name'] = $allowedCourier->courier_name; } // Calculate the new total price with margin $quote['total_with_margin'] = $totalPrice + $margin; } } if (!auth()->user()->hasPermissionTo('couriers')) { // Re-index the array after filtering $responseData = array_values($responseData); } // Process the response data and return the result if (!empty($responseData)) { $request->session()->put('parcels', $parcels); $request->session()->put('quotes', $responseData); return response()->json(['success' => $responseData], $response->getStatusCode()); } else { // Handle the case when there are no quotes available for the allowed couriers return response()->json(['error' => 'No quotes available for allowed couriers'], 404); } } else { // Handle the API error response $errorResponse = $response->getBody()->getContents(); return response()->json(['error' => $errorResponse], $response->getStatusCode()); } } public function generateQuotes($parcels, $request) { $request->session()->forget('parcels'); $request->session()->forget('quotes'); $requestBody = [ 'shipment' => [ 'order_id' => $this->generateRandomOrderId(), 'ship_to' => [ 'name' => '', 'postcode' => $request->input('postal'), 'country_iso' => $request->input('country'), ], 'parcels' => $parcels, 'customer_dc_id' => auth()->user()->dcID, 'despatch_date' => now()->toISOString(), ], ]; // Make the API call $client = new Client; $response = $client->post('https://production.billingapi.co.uk/api/get-quote', [ 'headers' => [ // 'Authorization' => 'Bearer ' . env('BILLINGAPI_TOKEN'), 'Authorization' => 'Bearer ' . 'IBSQr2rihrBYnRnN', //use env variable letter 'Content-Type' => 'application/json', ], 'json' => $requestBody, ]); // $request->session()->put('parcels', $parcels); return $response; } // Generate a random order ID private function generateRandomOrderId() { $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $orderId = ''; for ($i = 0; $i < 10; $i++) { $orderId .= $chars[rand(0, strlen($chars) - 1)]; } return $orderId; } public function generateLabel(Request $request) { if (empty(Auth::user()->cart)) { return redirect('/quotes'); } $payStatus = false; $invoicePay = false; if (!isset($request->id)) { return redirect()->back()->with('error', 'Unable to generate the label.'); } $orderId = $request->id; $order = Order::find($orderId); if ($request->noPay == 'yes') { if (!Auth::user()->hasPermissionTo('noPay')) { return redirect()->back()->with('error', 'You dont have access to order without pay.'); } $stripe = new StripeClient(env('STRIPE_SECRET')); $paymentIntent = $stripe->paymentIntents->retrieve($order->payment_intent_id); if ($paymentIntent->status != 'succeeded' && $order->status == 'pending') { // Cancel the payment intent $stripe->paymentIntents->cancel($order->payment_intent_id); $order->status = 'unpaid'; $order->save(); } } else if($request->noPay == 'invoice'){ $invoicePay=true; if (!Auth::user()->hasPermissionTo('noPay')) { return redirect()->back()->with('error', 'You dont have access to order without pay.'); } $stripe = new StripeClient(env('STRIPE_SECRET')); $paymentIntent = $stripe->paymentIntents->retrieve($order->payment_intent_id); if ($paymentIntent->status != 'succeeded' && $order->status == 'pending') { // Cancel the payment intent $stripe->paymentIntents->cancel($order->payment_intent_id); $order->status = 'unpaid'; $order->save(); } } else { if ($order) { // Check if the payment intent status is succeeded $stripe = new StripeClient(env('STRIPE_SECRET')); $paymentIntent = $stripe->paymentIntents->retrieve($order->payment_intent_id); if ($paymentIntent->status === 'succeeded') { $payStatus = true; // Update the order status to 'paid' $order->status = 'paid'; $order->transaction_id = $paymentIntent->latest_charge; $order->save(); } else { return redirect()->back()->with('error', 'Payment was not succcess please try again'); } } } $labelsData = []; // Initialize an array to store label data $refSufixCounter=1; foreach (Auth::user()->cart as $cartItem) { try { $requestBody = json_decode($cartItem->item); $vat_price = $requestBody->totalPrice * (auth()->user()->isVat ? (float) (auth()->user()->vatPercentage / 100) : 0); $latestBookingId = Booking::latest('id')->first()->id ?? 0; $nextBookingId = $latestBookingId + 1; // Format the next booking ID as needed $formattedNextBookingId = str_pad($nextBookingId, 4, '0', STR_PAD_LEFT); // Generate the initial reference $reference = Auth::user()->user_code ? Auth::user()->user_code : env('SH_CODE') . Auth::user()->id; $reference .= "-" . $formattedNextBookingId; // Check if the initial reference already exists in the bookings table $existingBooking = Booking::where('reference', $reference)->first(); // If the initial reference already exists, keep adding a suffix and a random letter until a unique reference is found if ($existingBooking) { // Initialize a counter for adding a suffix $suffixCounter = 1; // Loop until a unique reference is found do { // Add the suffix and random letter $modifiedReference = $reference . 'x' . chr(rand(97, 122)); // Check if the modified reference exists in the bookings table $existingBooking = Booking::where('reference', $modifiedReference)->first(); // Increment the suffix counter for the next iteration $suffixCounter++; // Define a maximum number of attempts to avoid infinite looping $maxAttempts = 1000; } while ($existingBooking && $suffixCounter <= $maxAttempts); if ($existingBooking) { // Handle the case where a unique reference couldn't be found after the maximum attempts // (e.g., throw an error, log a message, etc.) } else { // Use the modified reference for the new booking $reference = $modifiedReference; } } // At this point, $reference contains the unique reference to use for the new booking $requestBody->shipment->reference = $reference.'-'.$refSufixCounter; $refSufixCounter++; $client = new Client; $response = $client->post('https://production.courierapi.co.uk/api/couriers/v1/' . $requestBody->courier . '/create-label', [ 'headers' => [ 'api-user' => "GCL Courier Accounts", 'api-token' => "cwqpnhmjtrvbyafs", 'Content-Type' => 'application/json', ], 'json' => $requestBody, ]); if ($response->getStatusCode() === 200) { $responseData = $response->getBody()->getContents(); $result = json_decode($responseData); // Construct data for the label $labelData = [ "user_id" => Auth::User()->id, "pay_status" => $payStatus, "invoice_pay" => $invoicePay, "origin_phone" => $requestBody->shipment->ship_from->phone, "origin_email" => $requestBody->shipment->ship_from->email, "origin_name" => $requestBody->shipment->ship_from->name, "origin_company" => $requestBody->shipment->ship_from->company_name, "origin_address" => $requestBody->shipment->ship_from->address_1, "origin_city" => $requestBody->shipment->ship_from->city, "origin_postal" => $requestBody->shipment->ship_from->postcode1, "origin_country" => $requestBody->shipment->ship_from->country_iso, "origin_notes" => $requestBody->shipment->ship_from->notes, 'description' =>$requestBody->description, "destination_notes" => $requestBody->shipment->ship_from->notes, "destination_phone" => $requestBody->shipment->ship_to->phone, "destination_email" => $requestBody->shipment->ship_to->email, "destination_name" => $requestBody->shipment->ship_to->name, "destination_company" => $requestBody->shipment->ship_to->company_name, "destination_address" => $requestBody->shipment->ship_to->address_1, "destination_city" => $requestBody->shipment->ship_to->city, "destination_postal" => $requestBody->shipment->ship_to->postcode, "destination_country" => $requestBody->shipment->ship_to->country_iso, 'total_weight' => $requestBody->totalWeight, 'total_items' => $requestBody->totalQty, 'vat_price' => $vat_price, 'shipping_price' => $requestBody->totalPrice - $vat_price, // 'shipping_price' => $requestBody->shippingPrice - $vat_price, 'total_price' => $requestBody->totalPrice, 'service_code' => $requestBody->service->service_code, 'type' => $result->type, 'tracking_codes' => $result->tracking_codes[0], 'tracking_urls' => $result->tracking_urls[0], 'uri' => $this->quoteService->downloadAndSavePdf($result->uri), 'key' => $result->key, 'tracking_request_id' => $result->tracking_request_id, 'tracking_request_hash' => $result->tracking_request_hash, 'label_size' => $result->label_size, 'courier' => $result->courier, 'reference' => $requestBody->shipment->reference, 'courier_name' => $requestBody->courier_name, 'display_name' => $requestBody->display_name, 'dc_service_id' => $result->dc_service_id ?? null, 'dc_request_id' => $result->dc_request_id ?? null, 'req_json' => json_encode($requestBody) ?? null, 'order_id' => $orderId, ]; // Add the label data to the array // Save the booking $booking = new Booking($labelData); $booking->save(); $labelsData[] = $booking; Cart::destroy([$cartItem->id]); // Create a new notification $notification = new Notification([ 'user_id' => auth()->user()->id, 'booking_id' => $booking->id, 'title' => 'New Order | Ref no - ' . $requestBody->shipment->reference, 'content' => 'Order placed by ' . auth()->user()->first_name . ' ' . auth()->user()->last_name, ]); $notification->save(); $notification = new Notification([ 'user_id' => auth()->user()->id, 'booking_id' => $booking->id, 'title' => 'Congratulations | Ref no - ' . $requestBody->shipment->reference, 'content' => 'Your label is ready for print', 'toUser' => true, ]); $notification->save(); } else { // Handle the API error response $errorResponse = $response->getBody()->getContents(); // Construct data for the label $labelData = [ "user_id" => Auth::User()->id, "isError" => true, "pay_status" => $payStatus, "invoice_pay" => $invoicePay, "error_message" => $errorResponse, "origin_phone" => $requestBody->shipment->ship_from->phone, "origin_email" => $requestBody->shipment->ship_from->email, "origin_name" => $requestBody->shipment->ship_from->name, "origin_company" => $requestBody->shipment->ship_from->company_name, "origin_address" => $requestBody->shipment->ship_from->address_1, "origin_city" => $requestBody->shipment->ship_from->city, "origin_postal" => $requestBody->shipment->ship_from->postcode1, "origin_country" => $requestBody->shipment->ship_from->country_iso, "origin_notes" => $requestBody->shipment->ship_from->notes, 'description' =>$requestBody->description, "destination_notes" => $requestBody->shipment->ship_from->notes, "destination_phone" => $requestBody->shipment->ship_to->phone, "destination_email" => $requestBody->shipment->ship_to->email, "destination_name" => $requestBody->shipment->ship_to->name, "destination_company" => $requestBody->shipment->ship_to->company_name, "destination_address" => $requestBody->shipment->ship_to->address_1, "destination_city" => $requestBody->shipment->ship_to->city, "destination_postal" => $requestBody->shipment->ship_to->postcode, "destination_country" => $requestBody->shipment->ship_to->country_iso, 'total_weight' => $requestBody->totalWeight, 'total_items' => $requestBody->totalQty, 'vat_price' => $vat_price, 'shipping_price' => $requestBody->totalPrice - $vat_price, // 'shipping_price' => $requestBody->shippingPrice - $vat_price, 'total_price' => $requestBody->totalPrice, 'service_code' => $requestBody->service->service_code, 'type' => '', 'tracking_codes' => '', 'tracking_urls' => '', 'uri' => '', 'key' => '', 'tracking_request_id' => '', 'tracking_request_hash' => '', 'label_size' => '', 'courier' => $requestBody->courier_name, 'reference' => $requestBody->shipment->reference, 'courier_name' => $requestBody->courier_name, 'display_name' => $requestBody->display_name, 'dc_service_id' => '', 'dc_request_id' => '', 'req_json' => json_encode($requestBody) ?? null, 'order_id' => $orderId, ]; // Add the label data to the array // Save the booking $booking = new Booking($labelData); $booking->save(); $labelsData[] = $booking; Cart::destroy([$cartItem->id]); $notification = new Notification([ 'user_id' => auth()->user()->id, 'booking_id' => $booking->id, 'title' => 'New Error | Ref no - ' . $requestBody->shipment->reference, 'content' => 'Order placed by ' . auth()->user()->first_name . ' ' . auth()->user()->last_name, ]); $notification->save(); $notification = new Notification([ 'user_id' => auth()->user()->id, 'booking_id' => $booking->id, 'title' => 'Error | Ref no - ' . $requestBody->shipment->reference, 'content' => 'Contact support to fix it.', 'toUser' => true, ]); $notification->save(); } } catch (Exception $e) { // Construct data for the label $labelData = [ "user_id" => Auth::User()->id, "isError" => true, "pay_status" => $payStatus, "invoice_pay" => $invoicePay, "error_message" => $e->getMessage(), "origin_phone" => $requestBody->shipment->ship_from->phone, "origin_email" => $requestBody->shipment->ship_from->email, "origin_name" => $requestBody->shipment->ship_from->name, "origin_company" => $requestBody->shipment->ship_from->company_name, "origin_address" => $requestBody->shipment->ship_from->alt_address_1, "origin_city" => $requestBody->shipment->ship_from->alt_city, "origin_postal" => $requestBody->shipment->ship_from->postcode1, "origin_country" => $requestBody->shipment->ship_from->alt_country_iso, "origin_notes" => $requestBody->shipment->ship_from->notes, 'description' =>$requestBody->description, "destination_notes" => $requestBody->shipment->ship_from->notes, "destination_phone" => $requestBody->shipment->ship_to->phone, "destination_email" => $requestBody->shipment->ship_to->email, "destination_name" => $requestBody->shipment->ship_to->name, "destination_company" => $requestBody->shipment->ship_to->company_name, "destination_address" => $requestBody->shipment->ship_to->address_1, "destination_city" => $requestBody->shipment->ship_to->city, "destination_postal" => $requestBody->shipment->ship_to->postcode, "destination_country" => $requestBody->shipment->ship_to->country_iso, 'total_weight' => $requestBody->totalWeight, 'total_items' => $requestBody->totalQty, 'vat_price' => $vat_price, 'shipping_price' => $requestBody->totalPrice - $vat_price, // 'shipping_price' => $requestBody->shippingPrice - $vat_price, 'total_price' => $requestBody->totalPrice, 'service_code' => $requestBody->service->service_code, 'type' => '', 'tracking_codes' => '', 'tracking_urls' => '', 'uri' => '', 'key' => '', 'tracking_request_id' => '', 'tracking_request_hash' => '', 'label_size' => '', 'courier' => $requestBody->courier_name, 'reference' => $requestBody->shipment->reference, 'courier_name' => $requestBody->courier_name, 'display_name' => $requestBody->display_name, 'dc_service_id' => '', 'dc_request_id' => '', 'req_json' => json_encode($requestBody) ?? null, 'order_id' => $orderId, ]; // Add the label data to the array // Save the booking $booking = new Booking($labelData); $booking->save(); $labelsData[] = $booking; Cart::destroy([$cartItem->id]); $notification = new Notification([ 'user_id' => auth()->user()->id, 'booking_id' => $booking->id, 'title' => 'New Error | Ref no - ' . $requestBody->shipment->reference, 'content' => 'Order placed by ' . auth()->user()->first_name . ' ' . auth()->user()->last_name, ]); $notification->save(); $notification = new Notification([ 'user_id' => auth()->user()->id, 'booking_id' => $booking->id, 'title' => 'Error | Ref no - ' . $requestBody->shipment->reference, 'content' => 'Contact support to fix it.', 'toUser' => true, ]); $notification->save(); continue; // Continue to the next item } } // $pdfDownloadLinks = collect($labelsData)->pluck('uri')->toArray(); // Send an email to the logged-in user with the download links Mail::to(auth()->user()->email)->send(new LabelDownloadLink($labelsData, $orderId)); // Return the labels data as JSON response return response()->json(['labels' => $labelsData]); } // public function generateLabel(Request $request) // { // if (empty($request->session('parcels'))) { // return redirect('/quotes'); // } // try { // $parcels = $parcels = $request->session()->get('parcels', []); // $courier_price = $request->input('courier_price'); // $price = $courier_price / count($parcels[0]['items']); // $currency = 'EUR'; // foreach ($parcels as &$package) { // foreach ($package['items'] as &$item) { // $item['value'] = $price; // $item['value_currency'] = $currency; // } // } // // Validate the request // $validator = Validator::make($request->all(), [ // 'country' => 'required', // 'postal' => 'required', // 'origin_postal' => 'required', // 'origin_country' => 'required', // 'origin_name' => 'required', // 'origin_city' => 'required', // 'origin_address_1' => 'required', // 'origin_contact_name' => 'required', // 'origin_contact_phone' => 'required', // 'origin_contact_email' => 'required', // // 'dim_length.*' => 'required|numeric', // // 'dim_width.*' => 'required|numeric', // // 'dim_height.*' => 'required|numeric', // // 'dim_unit.*' => 'required', // // 'unit_weight.*' => 'required|numeric', // // 'weight_unit.*' => 'required', // 'shipt_to_collection_date' => 'required', // 'shipt_to_collection_time' => 'required', // 'ship_to_name' => 'required', // 'ship_to_phone' => 'required', // 'ship_to_email' => 'required|email', // 'ship_to_address_1' => 'required', // 'ship_to_city' => 'required', // 'ship_to_reference' => 'required', // ]); // if ($validator->fails()) { // $errors = $validator->errors(); // return response()->json(['errors' => $errors], 422); // } // // prepare required fields as per selected Courier // $courier_service = Courier::with('parentCourier') // ->where('service_id', $request->input('preset_id')) // ->orWhere('preset_id', $request->input('preset_id')) // ->first(); // $courier = $request->input('courier'); // // $selectedQuote = $this->quoteService->getSelectedQuote($request, $request->input('preset_id'), $courier); // // dd($selectedQuote); // $courier_req = []; // if ($courier_service && $courier) { // $courier = str_replace(' ', '', $courier); // if ($courier == 'DHL') { // $courier_req = [ // "global_product_code" => $courier_service->global_product_code, // ]; // } else if ($courier == 'DHL ParcelUK') { // $courier_req = [ // "service_key" => $courier_service->service_key, // ]; // } else if ($courier == 'PalletWays') { // $courier_req = [ // "service_code" => $courier_service->service_code, // "service_surcharge" => $courier_service->service_surcharge, // ]; // } // } else { // $courier = str_replace(' ', '', $courier); // $courier_req = [ // "service_code" => $courier_service->service_code, // "service_key" => $courier_service->service_key, // "service_surcharge" => $courier_service->service_surcharge, // "global_product_code" => $courier_service->global_product_code, // ]; // // return response()->json(['error' => "Something went wrong!"], 422); // } // if ($courier == 'DXExpress') { // $courier = $courier_service->parentCourier->courier_name; // } else { // $courier = $courier_service->parentCourier->courier_name; // } // // prepare ship from and to address // $ship_from = [ // "name" => $request->input('origin_contact_name'), // "phone" => $request->input('origin_contact_phone'), // "email" => $request->input('origin_contact_email'), // "company_name" => $request->input('origin_name'), // "address_1" => $request->input('origin_address_1'), // "address_2" => $request->input('origin_address_2'), // "city" => $request->input('origin_city'), // "postcode" => $request->input('origin_postal'), // "county" => "", // "country_iso" => $request->input('origin_country'), // ]; // $ship_to = [ // "name" => $request->input('ship_to_reference'), // "phone" => $request->input('ship_to_phone'), // "email" => $request->input('ship_to_email'), // "company_name" => $request->input('ship_to_name'), // "address_1" => $request->input('ship_to_address_1'), // "address_2" => $request->input('ship_to_address_2'), // "city" => $request->input('ship_to_city'), // "postcode" => $request->input('postal'), // "county" => "", // "country_iso" => $request->input('country'), // ]; // // collection date // $dateTimeString = $request->input('shipt_to_collection_date') . ' ' . $request->input('shipt_to_collection_time'); // $collectionDateTime = new DateTime($dateTimeString); // $collectionDateTime = $collectionDateTime->format('Y-m-d\TH:i:s.u\Z'); // $latestBookingId = Booking::latest('id')->first()->id ?? 0; // $nextBookingId = $latestBookingId + 1; // // Format the next booking ID as needed // $formattedNextBookingId = str_pad($nextBookingId, 4, '0', STR_PAD_LEFT); // $reference = Auth::user()->user_code ? Auth::user()->user_code : env('SH_CODE') . Auth::user()->id; // $reference .= "-" . $formattedNextBookingId; // $requestBody = [ // // 'auth_company' => env('AUTH_COMPANY'), // 'testing' => false, // 'auth_company' => $courier_service->parentCourier->auth_company, // 'format_address_default' => true, // 'shipment' => [ // "dc_service_id" => $courier_service->service_id ?? $request->input('preset_id'), // "label_size" => "10x4", // "label_format" => "pdf", // "generate_invoice" => false, // "generate_packing_slip" => false, // "courier" => $courier_req, // "reference" => $reference, // 'delivery_instructions' => $request->input('delivery_instructions') ?? " ", // 'collection_date' => $collectionDateTime, // 'ship_from' => $ship_from, // 'ship_to' => $ship_to, // 'parcels' => $parcels, // ], // ]; // //return $requestBody; // // Make the API call // $client = new Client; // $response = $client->post('https://production.courierapi.co.uk/api/couriers/v1/' . $courier . '/create-label', [ // 'headers' => [ // // 'api-user' => env("COURIERAPI_USER"), // 'api-user' => "GCL Courier Accounts", // // 'api-token' => env("COURIERAPI_TOKEN"), // 'api-token' => "cwqpnhmjtrvbyafs", // 'Content-Type' => 'application/json', // ], // 'json' => $requestBody, // ]); // list($totalWeight, $totalQuantity) = $this->quoteService->calculateTotalWeightAndQuantity($parcels); // $selectedQuote = $this->quoteService->getSelectedQuote($request, $request->input('preset_id'), $request->input('courier')); // // Handle the API response // if ($response->getStatusCode() === 200) { // $responseData = $response->getBody()->getContents(); // $result = json_decode($responseData); // $vat_price = $selectedQuote['price']['total'] *auth()->user()->isVat ? (float)(auth()->user()->vatPercentage / 100) : 0;; // ///Saving a data of booking/lable in database // $booking = new Booking([ // "user_id" => Auth::User()->id, // "origin_phone" => $request->input('origin_contact_phone'), // "origin_email" => $request->input('origin_contact_email'), // "origin_name" => $request->input('origin_contact_name'), // "origin_company" => $request->input('origin_name'), // "origin_address" => $request->input('origin_address_1'), // "origin_city" => $request->input('origin_city'), // "origin_postal" => $request->input('origin_postal'), // "origin_country" => $request->input('origin_country'), // "destination_phone" => $request->input('ship_to_phone'), // "destination_email" => $request->input('ship_to_email'), // "destination_name" => $request->input('ship_to_reference'), // "destination_company" => $request->input('ship_to_name'), // "destination_address" => $request->input('ship_to_address_1'), // "destination_city" => $request->input('ship_to_city'), // "destination_postal" => $request->input('postal'), // "destination_country" => $request->input('country'), // 'total_weight' => $totalWeight, // 'total_items' => $totalQuantity, // 'vat_price' => $vat_price, // 'shipping_price' => $selectedQuote['price']['total'], // 'total_price' => $selectedQuote['price']['total'] + $vat_price, // 'service_code' => $selectedQuote['service_code'], // 'type' => $result->type, // 'tracking_codes' => $result->tracking_codes[0], // 'tracking_urls' => $result->tracking_urls[0], // 'uri' => $this->quoteService->downloadAndSavePdf($result->uri), // 'key' => $result->key, // 'tracking_request_id' => $result->tracking_request_id, // 'tracking_request_hash' => $result->tracking_request_hash, // 'label_size' => $result->label_size, // 'courier' => $result->courier, // 'dc_service_id' => $result->dc_service_id ?? null, // 'dc_request_id' => $result->dc_request_id ?? null, // ]); // $booking->save(); // return response()->json(json_decode($responseData)); // } else { // // Handle the API error response // $errorResponse = $response->getBody()->getContents(); // return response()->json(['error' => $response], $response->getStatusCode()); // } // } catch (Exception $e) { // return response()->json(['error' => $e->getMessage()], 400); // } // } public function generateQuoteSummary(Request $request) { // Retrieve session values which we generated in the generateQuotes function $parcels = $request->session()->get('parcels', []); $quotes = $request->session()->get('quotes', []); $service_code = $request->input('service_code'); $courier = $request->input('courier'); $selectedQuote = $this->quoteService->getSelectedQuote($request, $service_code, $courier); list($totalWeight, $totalQuantity) = $this->quoteService->calculateTotalWeightAndQuantity($parcels); // Check if parcels and quotes are empty or non-existent if (empty($parcels) || empty($quotes)) { // If parcels or quotes are empty, redirect back return redirect('/quotes')->with('error', 'Parcels or quotes are empty.'); } $presetId=$selectedQuote['service_code']; $courierName=$selectedQuote['courier']; $courierPrice=$selectedQuote['price']['total']; // If parcels and quotes are not empty, return the view return view('quotes.get-address', compact('parcels', 'totalWeight', 'totalQuantity', 'selectedQuote','presetId', 'courierName', 'courierPrice')); } public function getAddress(Request $request) { if (empty($request->session()->get('quote_input'))) { return redirect('/quotes'); } $dateTime = $request->input('datepicker'); $presetId = $request->input('preset_id'); $courierName = $request->input('courier'); $courierPrice = $request->input('courier_price'); // Parse the datetime input into a Carbon instance $carbonDateTime = Carbon::parse($dateTime); // Extract date and time components $date = $carbonDateTime->toDateString(); // Gets the date in Y-m-d format $time = $carbonDateTime->toTimeString(); // Gets the time in H:i:s format // Pass $date and $time to the view return view('quotes.get-address', compact('date', 'time', 'presetId', 'courierName', 'courierPrice')); } public function getPostCode($postcode) { // Initialize Guzzle client $client = new Client(); // Make the API request try { $response = $client->request('GET', 'https://api.postcodes.io/postcodes/' . $postcode); $postcodeData = json_decode($response->getBody(), true); // Process the postcode data as needed return response()->json($postcodeData); } catch (\Exception $e) { // Handle error response return response()->json(['error' => 'Failed to fetch postcode data'], 500); } } function generateHsCode($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charLength - 1)]; } return $randomString; } }