610 lines
20 KiB
PHP
610 lines
20 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Bo;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\Order;
|
|
use App\Models\OrderLine;
|
|
use App\Models\OrdersProducts;
|
|
use App\Models\Product;
|
|
use App\Models\Timeslot;
|
|
use App\Models\Magasin;
|
|
use App\Http\Requests\SortOrders;
|
|
use Illuminate\Support\Facades\Mail;
|
|
use App\Mail\OrderStatusMail;
|
|
use App\Mail\OrderConfirmMail;
|
|
use App\Mail\OrderConfirmAdminMail;
|
|
use App\Jobs\CsvOrderWrite;
|
|
use App\Models\Customers;
|
|
use App\Models\Setting;
|
|
use Carbon\Carbon;
|
|
use Carbon\CarbonImmutable;
|
|
use Carbon\CarbonInterval;
|
|
use Gloudemans\Shoppingcart\Facades\Cart;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Session;
|
|
|
|
class OrdersController extends Controller
|
|
{
|
|
/**
|
|
* Display a listing of the resource.
|
|
*
|
|
* @param \App\Http\Requests\SortOrders $request
|
|
* @return \Illuminate\Contracts\View\View
|
|
*/
|
|
public function index(SortOrders $request)
|
|
{
|
|
$orders = $this->filterOrders($request);
|
|
|
|
$orders = $orders->paginate(10);
|
|
|
|
return view('bo.orders.index', compact('orders'));
|
|
}
|
|
|
|
/**
|
|
* 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('bo.orders.index', compact('orders', 'today'));
|
|
}
|
|
|
|
/**
|
|
* Filter orders
|
|
*
|
|
* @param Request $request
|
|
* @return \Illuminate\Database\Eloquent\Builder
|
|
*/
|
|
protected function filterOrders(Request $request)
|
|
{
|
|
$orders = Order::query();
|
|
|
|
|
|
if ($request->rst) {
|
|
Session::remove('orders.sort_col');
|
|
Session::remove('orders.sort_way');
|
|
}
|
|
if ($request->sort_col) {
|
|
Session::put('orders.sort_col', $request->sort_col);
|
|
Session::save();
|
|
}
|
|
if ($request->sort_way) {
|
|
Session::put('orders.sort_way', $request->sort_way);
|
|
Session::save();
|
|
}
|
|
|
|
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('magasins', 'timeslots.magasin_id', '=', 'magasins.id');
|
|
$orders = $orders->orderBy('magasins.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
|
|
|
|
return $orders;
|
|
}
|
|
|
|
/**
|
|
* 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 . ".");
|
|
}
|
|
|
|
/**
|
|
* mise au statut annulé d'une commande
|
|
*
|
|
* @param string $reference
|
|
* @return \Illuminate\Http\RedirectResponse
|
|
*/
|
|
public function cancelOrder(string $reference)
|
|
{
|
|
$order = Order::where('reference', $reference)->first();
|
|
$order->status_id = 7;
|
|
$order->save();
|
|
|
|
return back()->with('success', "La commande " . $order->reference . " à été annulée.");
|
|
}
|
|
|
|
/**
|
|
* @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();
|
|
|
|
$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 à été ajouté.");
|
|
}
|
|
|
|
/**
|
|
* front
|
|
* récap panier du tunnel de commande
|
|
*
|
|
* @return \Illuminate\Contracts\View\View
|
|
*/
|
|
public function recapOrder()
|
|
{
|
|
$activestep = 2;
|
|
Cart::instance('panier');
|
|
$cart = Cart::content();
|
|
|
|
$cartInfos = array(
|
|
"totalTTC" => Cart::total(),
|
|
// Total des taxes.
|
|
'totalTVA' => Cart::tax(),
|
|
// Total sans les taxes.
|
|
'totalHT' => Cart::subtotal(),
|
|
// Poids total des items.
|
|
'totalweight' => Cart::weight(),
|
|
// Total avant taxes et remises.
|
|
'totalHTbefore' => Cart::priceTotal(),
|
|
// Total des remises.
|
|
'totaldiscount' => Cart::discount(),
|
|
// Nb de produits dans le cart.
|
|
'countItems' => Cart::count(),
|
|
);
|
|
|
|
return view('sales.recap', compact('activestep', 'cart', 'cartInfos'));
|
|
}
|
|
|
|
/**
|
|
* 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('sales.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')) {
|
|
$magasin = Magasin::all();
|
|
} else {
|
|
$magasin = Magasin::first();
|
|
}
|
|
|
|
$availCreneaux = array();
|
|
$order = Order::where('reference', '=', $reference)->firstOrFail();
|
|
|
|
return view('sales.pick-slot', compact('activestep', 'availCreneaux', 'order', 'magasin'));
|
|
}
|
|
|
|
/**
|
|
* add timeslot by interval between start and end hour
|
|
*
|
|
* @param array $plage
|
|
* @param integer $weekDay
|
|
* @param CarbonImmutable $current
|
|
* @param Magasin $magasin
|
|
* @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,
|
|
Magasin $magasin,
|
|
CarbonImmutable $now,
|
|
CarbonImmutable $today,
|
|
CarbonInterval $delaiPrepa,
|
|
CarbonInterval $interval,
|
|
Carbon $currentTime,
|
|
Carbon $endTime
|
|
) {
|
|
$retArray = array();
|
|
do {
|
|
$creneau = $currentTime->format('H:i');
|
|
$nbtakens = $magasin->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;
|
|
|
|
$magasin = Magasin::findOrFail($id);
|
|
$timeslotSettings = $magasin->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 = $magasin->collecteExceptions()
|
|
->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,
|
|
$magasin,
|
|
$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,
|
|
$magasin,
|
|
$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));
|
|
|
|
// Export commande.
|
|
if (config('bosettings.regate_orders')) {
|
|
CsvOrderWrite::dispatch($order);
|
|
}
|
|
}//end if
|
|
|
|
// Redirect to final confirmation.
|
|
return redirect()->route('sales.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
|
|
$magasin = Magasin::find($order->timeslot->magasin->id);
|
|
|
|
return view('sales.confirm', compact('activestep', 'order', 'magasin'));
|
|
}
|
|
|
|
/**
|
|
* 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 = Customers::findOrFail($id);
|
|
if (!is_null($mode)) {
|
|
if ($mode == "tippy") {
|
|
return view('bo.customer.tippy-card', compact('cust'));
|
|
}
|
|
if ($mode == "json") {
|
|
return $cust->apiData;
|
|
}
|
|
return view('bo.customer.info-card', compact('cust'));
|
|
}
|
|
return view('bo.customer.info-popup', compact('cust'));
|
|
}
|
|
|
|
/**
|
|
* bo : page détail commande
|
|
*
|
|
* @param string $reference
|
|
* @return \Illuminate\Contracts\View\View
|
|
*/
|
|
public function orderDetail(string $reference)
|
|
{
|
|
$order = Order::where('reference', '=', $reference)->firstOrFail();
|
|
return view('bo.orders.detail', compact('order'));
|
|
}
|
|
}
|