search) { $this->searchQuery( $orders, $request->search, null, 'label' ); } // if (Session::has('orders.sort_col') and Session::has('orders.sort_way')) { // switch (Session::get('orders.sort_col')) { // case 'date': // $orders = $orders->orderBy('date', Session::get('orders.sort_way')); // break; // case 'status_id': // $orders = $orders->orderBy('status_id', Session::get('orders.sort_way')); // break; // case 'magasin_id': // $orders = $orders->select('orders.*'); // $orders = $orders->leftJoin('timeslots', 'timeslots.order_id', '=', 'orders.id'); // $orders = $orders->leftJoin('shops', 'timeslots.shop_id', '=', 'shops.id'); // $orders = $orders->orderBy('shops.id', Session::get('orders.sort_way')); // break; // case 'date_retrait': // $orders = $orders->select('orders.*'); // $orders = $orders->leftJoin('timeslots', 'timeslots.order_id', '=', 'orders.id'); // $orders = $orders->orderBy('timeslots.day', Session::get('orders.sort_way')); // $orders = $orders->orderBy('timeslots.time', Session::get('orders.sort_way')); // break; // case 'customer_id': // $orders = $orders->orderBy('customer_id', Session::get('orders.sort_way')); // break; // }//end switch // }//end if $this->sortQuery($orders); $searchFields = trans('Label'); $orders->orderBy('updated_at', 'DESC'); $orders = $orders->paginate(10); return view('back.orders.index', compact('orders', 'searchFields')); } /** * Met a jour le statut de validation d'une commande en annulé * * @param \App\Models\Order $order * @return \Illuminate\Http\RedirectResponse */ public function cancelOrder(Order $order) { $order->validation_status = ValidationStatus::cancelled(); $order->saveOrFail(); return back()->with('success', "La commande {$order->reference} a été annulée."); } /** * bo : page détail commande * * @param \App\Models\Order $order * @return \Illuminate\Contracts\View\View */ public function orderDetails(Order $order) { return view('back.orders.details', [ 'orderModel' => $order ]); } /** * orders that ship today * * @param SortOrders $request * @return \Illuminate\Contracts\View\View */ public function today(SortOrders $request) { $orders = $this->filterOrders($request); // Filter today. $today = CarbonImmutable::now()->startOfDay(); $orders = $orders->whereHas('timeslot', function ($q) use ($today) { $q->where('day', '=', $today->format('d/m/Y')); }); $orders = $orders->get(); return view('back.orders.index', compact('orders', 'today')); } /** * action de changement de statut vers l'avant * envoi de mails transctionnels * * @param string $reference Reference de la commande. * @return \Illuminate\Http\RedirectResponse */ public function changeStatus(string $reference) { $order = Order::where('reference', $reference)->first(); $order->status_id = $order->status_id + 1; $order->save(); // Send confirm mail. Mail::to($order->customer->email)->send(new OrderStatusMail($order)); return back()->with('success', "Changement de status enregistré pour la commande " . $order->reference . "."); } /** * @deprecated Supprimer cette méthode qui repose sur un modèle de donnée osolète. * ajout de produits à la commande * * @param string $orderReference * @param integer $productId * @param integer $quantity * @return \Illuminate\Http\RedirectResponse */ public function addProduct(string $orderReference, int $productId, int $quantity) { $product = Product::findOrFail($productId); $order = Order::where('reference', $orderReference)->first(); // FIXME: price_buy No longer available. $order->total = $order->total + (($product->price - $product->price_buy) * $quantity); $orderProduct = new OrdersProducts(); $orderProduct->product_id = $product->id; $orderProduct->order_id = $order->id; $orderProduct->quantity = $quantity; $orderProduct->save(); return redirect()->route('bo.orders')->with('success', "Le produit a été ajouté."); } /** * front * Storing order from sales tunnel * * @return \Illuminate\Http\RedirectResponse */ public function store() { // Save. Cart::instance('panier'); $order = new Order(); // Generate order ref. $order->reference = $this->generateOrderRef(); $order->date = Carbon::now(); $order->status_id = 1; $order->total = str_replace(',', '.', str_replace(' ', '', Cart::total())); $order->customer_id = Auth::user()->id; $order->save(); // Order_id. Cart::instance('panier'); $cart = Cart::content(); foreach ($cart as $cartItem) { $order_line = new OrderLine(); $order_line->order_id = $order->id; $order_line->product_id = $cartItem->model->id; $order_line->quantity = $cartItem->qty; // Gross unit price. $order_line->unit_price = $cartItem->model->priceHt; // Discount per unit. $order_line->unit_discount = $cartItem->model->discountAmount; // Tax rate for this line. $order_line->tax_rate = $cartItem->taxRate; // Tax amount par unit. $order_line->unit_tax = round( (($order_line->unit_price - $order_line->unit_discount) * ($order_line->tax_rate / 100)) * 100 ) / 100; // Discount amount for the line. $order_line->total_discount = $order_line->unit_discount * $order_line->quantity; // Gross amount for the line. $order_line->total_ht = ($order_line->unit_price - $order_line->unit_discount) * $order_line->quantity; // Tax amount for the line. $order_line->total_tax = $order_line->unit_tax * $order_line->quantity; // Total TTC avec remises de la ligne. $order_line->total_ttc = $order_line->total_ht + $order_line->total_tax; $order_line->save(); } //end foreach // Empty cart. Cart::destroy(); // Then redirect. return redirect()->route('order-tunnel.pick-slot', ['reference' => $order->reference]); } /** * generate order Reference * for a new order * * @return string */ public function generateOrderRef() { // Format : YYYYMMDDHHMM000. $now = Carbon::now(); // Count todays orders. $countorders = Order::whereDate('created_at', Carbon::today())->count(); // Add one. $countorders++; $ref = $now->isoFormat('YYYYMMDDHHmm') . str_pad($countorders, 3, "0", STR_PAD_LEFT); return $ref; } /** * front tunnel de commande étape 3 : choix de créneau * * @param string $reference * @return \Illuminate\Contracts\View\View */ public function timeSlotPick(string $reference) { $activestep = 3; if (config('theme.multi_relay')) { $shop = Shop::all(); } else { $shop = Shop::first(); } $availCreneaux = array(); $order = Order::where('reference', '=', $reference)->firstOrFail(); return view('sales.pick-slot', compact('activestep', 'availCreneaux', 'order', 'shop')); } /** * add timeslot by interval between start and end hour * * @param array $plage * @param integer $weekDay * @param CarbonImmutable $current * @param Shop $shop * @param CarbonImmutable $now * @param CarbonImmutable $today * @param CarbonInterval $delaiPrepa * @param CarbonInterval $interval * @param Carbon $currentTime * @param Carbon $endTime * @return array */ private function addCreneaux( array $plage, int $weekDay, CarbonImmutable $current, Shop $shop, CarbonImmutable $now, CarbonImmutable $today, CarbonInterval $delaiPrepa, CarbonInterval $interval, Carbon $currentTime, Carbon $endTime ) { $retArray = array(); do { $creneau = $currentTime->format('H:i'); $nbtakens = $shop->timeslots() ->where('day', $current->format('d/m/Y')) ->where('time', $creneau)->count(); if ($nbtakens >= $plage[$weekDay]['max_orders_per_interval']) { $isDispo = false; } else { $isDispo = true; } if ( $current->addHours($currentTime->format('H'))->addMinutes($currentTime->format('i')) < $now->add($delaiPrepa) ) { $isDispo = false; } // Attention si la date est passée (today mais avant maintenant) : pas de créneau. if ($current > $today || $currentTime >= $now) { $retArray[] = array($creneau, $isDispo); } $currentTime->add($interval); } while ($currentTime <= $endTime); return $retArray; } /** * give array of available crenaux * * @param integer $id * @return array */ public function getAvailableCreneauxByShop(int $id) { // Setting à stocker et réutiliser. $plage_days = Setting::where('key', 'order_withdrawal_period')->firstOrFail()->value; $shop = Shop::findOrFail($id); $timeslotSettings = $shop->timeslotSettings; // $timeslotSettings = TimeslotSetting::all(); // Fabriquons un tableau recap. $plage = array(); foreach ($timeslotSettings as $day) { $plage[$day->day_index] = array( 'morning_start' => $day->morning_start, 'morning_end' => $day->morning_end, 'afternoon_start' => $day->afternoon_start, 'afternoon_end' => $day->afternoon_end, 'interval' => $day->interval, 'min_order_preparation' => $day->min_order_preparation, 'max_orders_per_interval' => $day->max_orders_per_interval ); } // Génération des plages. // Start today. $today = CarbonImmutable::now()->startOfDay(); $weekDay = $today->weekday(); // Final boundary (permet de limiter la liste des jours d'exception). $finalday = $today->add($plage_days, 'day'); $now = CarbonImmutable::now(); // Jours exceptions. $noCollectDays = $shop->collectionExceptions() ->whereDate('date', '>', $now) ->whereDate('date', '<=', $finalday) ->orderBy('date')->get(); $delaiPrepa = CarbonInterval::createFromFormat('h:i', $plage[$weekDay]['min_order_preparation'] ?? '01:00'); $availCreneaux = array(); for ($i = 0; $i < $plage_days; $i++) { $current = $today->add($i, 'day'); $weekDay = $current->weekday(); $interval = CarbonInterval::createFromFormat('h:i', $plage[$weekDay]['interval'] ?? '00:15'); // Si c'est un jour exception skip. $skip = false; foreach ($noCollectDays as $not_today) { if ($current->isSameDay($not_today->date)) { $skip = true; } } if ($skip) { continue; } $availCreneaux[$current->format('d/m/Y')] = array(); // Matinée. if (!empty($plage[$weekDay]['morning_start'])) { $currentTime = Carbon::createFromTimeString($plage[$weekDay]['morning_start']); $endTime = Carbon::createFromTimeString($plage[$weekDay]['morning_end']); $morningCreneaux = $this->addCreneaux( $plage, $weekDay, $current, $shop, $now, $today, $delaiPrepa, $interval, $currentTime, $endTime ); $availCreneaux[$current->format('d/m/Y')] = array_merge( $availCreneaux[$current->format('d/m/Y')], $morningCreneaux ); } //end if // Aprem. if (!empty($plage[$weekDay]['afternoon_start'])) { $currentTime = Carbon::createFromTimeString($plage[$weekDay]['afternoon_start']); $endTime = Carbon::createFromTimeString($plage[$weekDay]['afternoon_end']); $afternoonCreneaux = $this->addCreneaux( $plage, $weekDay, $current, $shop, $now, $today, $delaiPrepa, $interval, $currentTime, $endTime ); $availCreneaux[$current->format('d/m/Y')] = array_merge( $availCreneaux[$current->format('d/m/Y')], $afternoonCreneaux ); } //end if } //end for return $availCreneaux; } /** * Call ajax pour le composant vue de timeslots. * * @param Request $request * @return array */ public function getAvailableCreneaux(Request $request) { return $this->getAvailableCreneauxByShop($request->id); } /** * front * enregistrement du créneau de collect * et validation de la commande * * @param Request $request * @return \Illuminate\Http\RedirectResponse */ public function setTimeSlot(Request $request) { $request->validate([ 'selectedmagasin' => 'required', 'selectedcreneau' => 'required', 'ok_cgv' => 'accepted', ]); $time_slot = Carbon::createFromFormat('d/m/Y-H:i', $request->selectedcreneau); $tsday = explode('-', $request->selectedcreneau)[0]; $tstime = explode('-', $request->selectedcreneau)[1]; $magasin_id = $request->selectedmagasin; $reference = $request->order_ref; $order = Order::where('reference', '=', $reference)->firstOrFail(); if ($order->status_id == 1) { // On ne traite l'enregistrement que pour les commandes en attente venant de l'étape de récap. // Save timeslot. $timeslot = Timeslot::firstOrNew(['order_id' => $order->id]); $timeslot->order_id = $order->id; $timeslot->magasin_id = $magasin_id; $timeslot->day = $tsday; $timeslot->time = $tstime; $timeslot->save(); // Save order status. $order->status_id = 3; $order->save(); // Send confirm mail. Mail::to($order->customer->email)->queue(new OrderConfirmMail($order)); // Envoi du mail de confirmation aux admins site. $toMailSetting = Setting::where('key', 'send_order_confirm_mail_to')->first(); if (empty($toMailSetting->value)) { $toMail = config('mail.from.address'); } else { $toMail = $toMailSetting->value; } Mail::to($toMail)->queue(new OrderConfirmAdminMail($order)); } //end if // Redirect to final confirmation. return redirect()->route('order-tunnel.confirm', ['reference' => $order->reference]); } /** * generate Order * Test method * * @param string $reference * @return void */ public function generateOrder(string $reference) { $order = Order::where('reference', '=', $reference)->with('lines')->firstOrFail(); $job = new CsvOrderWrite($order); $job->handle(); dd('end'); } /** * front * page de confirmation de commande * * @param string $reference * @return \Illuminate\Contracts\View\View */ public function confirmOrder(string $reference) { $activestep = 4; $idcommande = Session::get('idcommande'); $order = Order::where('reference', '=', $reference)->firstOrFail(); // 1 seul magasin en base pour le moment $shop = Shop::find($order->timeslot->shop->id); return view('sales.confirm', compact('activestep', 'order', 'shop')); } /** * bo * ajx : affichage d'infos sur un client * * @param integer $id * @param string|null $mode * @return \Illuminate\Contracts\View\View */ public function getCustomerInfo(int $id, string $mode = null) { $cust = Customer::findOrFail($id); if (!is_null($mode)) { if ($mode == "tippy") { return view('back.customer.tippy-card', compact('cust')); } if ($mode == "json") { return $cust->apiData; } return view('back.customer.info-card', compact('cust')); } return view('back.customer.info-popup', compact('cust')); } }