public static function assignPrice($level_id, $transport_status, $reductionPrix = null) { $currentYear = \Auth::user()->schoolyears()->where('current', 1)->first(); if ($currentYear->type == 'Semis') { if (Carbon::now()->between($currentYear->startch1, $currentYear->endch2)) { if ($transport_status == 0) { $price = \Auth::user()->pricebills()->where('niveau', $level_id)->first(); if ($price->prix > 0 && is_null($reductionPrix)) { return $price->prix; } else { return $price->prix - $reductionPrix; } } else { if (Transport::where('user_id', \Auth::user()->id)->exists()) { $price = \Auth::user()->pricebills()->where('niveau', $level_id)->first(); if ($price->prix > 0 && is_null($reductionPrix)) { return $price->prix + Transport::where('user_id', \Auth::user()->id)->first()->somme; } else { return $price->prix + Transport::where('user_id', \Auth::user()->id)->first()->somme - $reductionPrix; } } } } } else { if (Carbon::now()->between($currentYear->startch1, $currentYear->endch3)) { if ($transport_status == 0) { $price = \Auth::user()->pricebills()->where('niveau', $level_id)->first(); if ($price->prix > 0 && is_null($reductionPrix)) { return $price->prix; } else { return $price->prix - $reductionPrix; } } else { if (Transport::where('user_id', \Auth::user()->id)->exists()) { $price = \Auth::user()->pricebills()->where('niveau', $level_id)->first(); if ($price->prix > 0 && is_null($reductionPrix)) { return $price->prix + Transport::where('user_id', \Auth::user()->id)->first()->somme; } else { return $price->prix + Transport::where('user_id', \Auth::user()->id)->first()->somme - $reductionPrix; } } } } } }
/** * Execute the console command. * * @return mixed */ public function handle() { // Get contracts that are still active. $contracts = Contract::where('State', '!=', 'used')->where('State', '!=', 'cancelled')->where('State', '!=', 'paid')->get(); foreach ($contracts as $contract) { // Check if we have visited this month. if ($contract->Visited) { // Check if we should reset this. if ($contract->QuotaInterval == 'mensuales') { if ('01' == date('d')) { $contract->Visited = false; $contract->save(); } } else { if ($contract->QuotaInterval == 'quincenales') { if ('01' == date('d')) { $contract->Visited = false; $contract->save(); } else { if ('16' == date('d')) { $contract->Visited = false; $contract->save(); } } } else { if (date('D') == 'Mon') { $contract->Visited = false; $contract->save(); } } } } // Check if we need to organize a visit for this contract. if (!$contract->Visited) { if ($contract->StartDate < date('Y-m-d')) { $visitDates = explode(',', $contract->PaymentDates); foreach ($visitDates as $date) { if ($date == date('d', strtotime("+3 days"))) { // Check if we already have a visit programmed for this contract. $transports = Transport::where('Type', '=', '8')->where('ReasonId', '=', $contract->Id)->where('Date', '=', date('Y-m-d', strtotime("+3 days")))->get(); if (count($transports) == 0) { // Get an appropriate vehicle for this. $vehicles = Vehicle::where('BranchId', '=', $contract->BranchId)->where('Repair', '=', false)->get(); $vehicle = null; foreach ($vehicles as $v) { if (!$vehicle) { $vehicle = $v; } // In this case the smaller the vehicle the more suitable it should be. // TODO: This could be improved. if ($v->Type < $vehicle->Type) { $vehicle = $v; } } if (!$vehicle) { // In this case we don't have a vehicle and the provider doesn't provide delivery so we must notify an administrator. $users = User::where('UserLevel', '=', 1)->get(); foreach ($users as $admin) { Notification::create(array('UserId' => $admin->Id, 'Created' => date('Y-m-d H:i:s'), 'Reason' => 'Aergia no fue capaz de organizar el cobro para el contrato ' . $contract->Code . '. Por favor revisar y organizar el cobro de la cuota de este contrato.', 'Url' => '/contract/' . $contract->Id, 'Seen' => false)); } } else { // Get location of client. $client = Client::find($contract->ClientId); $location = Location::find($client->LocationId); $transport = Transport::create(array('Date' => date('Y-m-d', strtotime("+3 day")), 'Time' => '00:00:00', 'VehicleId' => $vehicle->Id, 'DriverId' => 0, 'StartLatitude' => 0, 'StartLongitude' => 0, 'Journey' => '[]', 'EndLatitude' => $location->Latitude, 'EndLongitude' => $location->Longitude, 'EndAddress' => $client->Address, 'Distance' => 0, 'ReasonId' => $contract->Id, 'Type' => 8, 'State' => 2, 'Order' => 0, 'Depreciation' => 0)); // Inform creditor of when you shall collect payment. if ($client->Email != '') { Mail::send('emails.ai.contractReminder', ['contract' => $contract, 'transport' => $transport], function ($message) use($contract, $client) { $message->to($client->Email); $message->subject('Cobro de Cuota de Contrato: ' . $contract->Code); }); } } } } } } } // TODO: Not sure if I want to do something in these cases. switch ($contract->State) { case 'usedpending': break; case 'late': break; } } }
public function checktransport() { if (\Request::ajax()) { $trans = Transport::where('user_id', \Auth::user()->id)->exists(); $details = Transport::where('user_id', \Auth::user()->id)->first(); if ($trans && $details->somme !== '') { echo 'oui'; } } }
/** * Execute the console command. * * @return mixed */ public function handle() { // Let's get all credit sales that have not been paid yet. $creditSales = Sale::where('Credit', '=', true)->where('Cancelled', '=', false)->get(); // Check if any of them are due soon. $today = date('Y-m-d H:i:s'); foreach ($creditSales as $sale) { // Get the client or institution that made the credit purchase. $creditor = null; if ($sale->CreditorType == 1) { $creditor = Client::find($sale->CreditorId); } else { $creditor = Institution::find($sale->CreditorId); } // First check if the payment is late. if (date('Y-m-d H:i:s', strtotime($sale->Created) + $creditor->CreditDays * 86400) < $today) { // If it's past due for more than a month notify admins so they can deal with it. if (date('Y-m-d H:i:s', strtotime($sale->Created) + ($creditor->CreditDays + 30) * 86400) < $today) { // In this case we don't have a vehicle and the provider doesn't provide delivery so we must notify an administrator. $users = User::where('UserLevel', '=', 1)->get(); foreach ($users as $admin) { Notification::create(array('UserId' => $admin->Id, 'Created' => date('Y-m-d H:i:s'), 'Reason' => 'Aergia ha tratado de cobrar la venta de credito con factura: ' . $sale->Id . ', sin embargo no se ha registrado el pago de la factura y esta tiene mas de un mes de vencimiento. Aergia no seguira tratando de cobrar esta factura, por favor darle seguimiento al caso.', 'Url' => '/creditdue/' . $sale->Id, 'Seen' => false)); } } else { // Check to see if there is a transport request active to collect payment. $transport = Transport::where('Type', '=', 7)->where('ReasonId', '=', $sale->Id)->where('Date', '>', date('Y-m-d'))->get(); if (count($transport) == 0) { // Get a vehicle that can be used to go to charge creditor. $vehicles = Vehicle::where('BranchId', '=', $sale->BranchId)->where('Repair', '=', false)->get(); $vehicle = null; foreach ($vehicles as $v) { if (!$vehicle) { $vehicle = $v; } // In this case the smaller the vehicle the more suitable it should be. // TODO: This could be improved. if ($v->Type < $vehicle->Type) { $vehicle = $v; } } if (!$vehicle) { // In this case we don't have a vehicle to go charge creditor so we must notify an administrator. $users = User::where('UserLevel', '=', 1)->get(); foreach ($users as $admin) { Notification::create(array('UserId' => $admin->Id, 'Created' => date('Y-m-d H:i:s'), 'Reason' => 'Aergia no fue capaz de organizar el cobro de la factura: ' . $sale->Id . ' ya que no tuvo vehiculos disponibles para hacerlo. Por favor organizar el cobro de la factura.', 'Url' => '/creditdue/' . $sale->Id, 'Seen' => false)); } } else { // Get location of creditor. $location = Location::find($creditor->LocationId); $paymentCollection = Transport::create(array('Date' => date('Y-m-d', strtotime("+1 day")), 'Time' => '00:00:00', 'VehicleId' => $vehicle->Id, 'DriverId' => 0, 'StartLatitude' => 0, 'StartLongitude' => 0, 'Journey' => '[]', 'EndLatitude' => $location->Latitude, 'EndLongitude' => $location->Longitude, 'EndAddress' => $creditor->Address, 'Distance' => 0, 'ReasonId' => $sale->Id, 'Type' => 7, 'State' => 2, 'Order' => 0, 'Depreciation' => 0)); // Inform creditor of when you shall collect payment. if ($creditor->Email != '') { Mail::send('emails.ai.creditorReminder', ['sale' => $sale, 'creditor' => $creditor, 'transport' => $paymentCollection], function ($message) use($sale, $creditor) { $message->to($creditor->Email); $message->subject('Cobro Factura: ' . $sale->Id); }); } } } } } } }
use App\Client; use App\Institution; use App\CashReceipt; use App\Transport; use App\Branch; // Get the sale. $creditDue = Sale::find($sale['Id']); // Get the branch. $branch = Branch::find($creditDue->BranchId); // Get the creditor. $creditor = null; if ($sale->CreditorType == 1) { $creditor = Client::find($sale->CreditorId); } else { $creditor = Institution::find($sale->CreditorId); } // Get the transport request. $paymentCollection = Transport::find($transport['Id']); $payments = CashReceipt::where('Type', '=', 2)->where('TypeId', '=', $sale->Id)->get(); $totalDue = $creditDue->Value + $creditDue->Tax; foreach ($payments as $payment) { $totalDue -= $payment->Value; } ?> <p>{{ $creditor->Name }},</p> <p>Les enviamos el siguiente correo para dejarles saber que el {{ $transport->Date }} estaremos llegando a recoger el pago de la factura numero {{ $sale->Id }}. El total pendiente es de C$ {{ $totalDue }}.</p> <p>Si por algun motivo no podra pagar ese dia puede reprogramar nuestra visita respondiendo a este correo de la siguiente manera:</p> <p>Reprogramar:{{ date('Y-m-d', strtotime("+5 days")) }}</p> <p>Se despide cordialmente,</p> <p>Aergia AI (Inteligencia Artificial)</p> <p>{{ $branch->Name }}</p>
/** * Function that searches for past trips. * * @return Response */ public function searchVehicleTrips() { // Validate Input. $validator = Validator::make(Input::all(), array('vehicle' => 'required', 'start' => 'required', 'end' => 'required')); if ($validator->fails()) { return response()->json(['error' => 'Informacion incompleta!']); } // Check that user is part of authorized staff. if (Auth::user()->Type != 1) { // If they are unauthorized no point in returning anything. return response()->json(array()); } // Get trips. $start = date('Y-m-d', strtotime(Input::get('start'))); $end = date('Y-m-d', strtotime(Input::get('end'))); $trips = Transport::where('VehicleId', '=', Input::get('vehicle'))->where('Date', '>=', $start)->where('Date', '<=', $end)->where('State', '=', 1)->groupBy('Date')->orderBy('Order')->get(); $tripData = array(); foreach ($trips as $trip) { $driver = Worker::find($trip->DriverId); $reason = ''; switch ($trip->Type) { case 1: // Get sale breakdown. $breakdown = SaleBreakdown::find($trip->ReasonId); // Get product or service. $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $driver->BranchId)->first(); if ($product) { $reason = 'Venta de ' . $product->Description; } else { $service = Service::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $driver->BranchId)->first(); $reason = 'Venta de ' . $service->Description; } break; case 2: // Get sale. $sale = Sale::find($trip->ReasonId); // Get client or institution. if ($sale->CreditorType == 1) { if ($sale->CreditorId == 0) { $reason = 'Venta a cliente no definido'; } else { $client = Client::find($sale->CreditorId); $reason = 'Venta a ' . $client->Name; } } else { $institution = Institution::find($sale->CreditorId); $reason = 'Venta a ' . $institution->Name; } break; case 3: // Get order breakdown. $breakdown = OrderBreakdown::find('OrderId', '=', $trip->ReasonId); // Get product or service. $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $driver->BranchId)->first(); $reason = 'Produccion de ' . $product->Description; break; case 4: // Get order. $order = Order::find($trip->ReasonId); // Get client or institution. $client = Client::find($order->ClientId); if ($client->InstitutionId == 0) { $reason = 'Orden de Produccion de ' . $client->Name; } else { $institution = Institution::find($client->InstitutionId); $reason = 'Orden de Produccion de ' . $institution->Name; } break; case 5: // Get storage request. $request = StorageRequest::find($trip->ReasonId); $reason = $request->Reason; break; case 6: // Get visit. $visit = Visit::find($trip->ReasonId); $reason = 'Visita ' . $visit->Result; break; case 7: // Get credit bill. $creditBill = Sale::find($trip->ReasonId); $reason = 'Cobro de Facturo: ' . $creditBill->Id; break; case 8: // Contract Payment. $contract = Contract::find($trip->ReasonId); $reason = 'Cobro de Contrato: ' . $contract->Code; break; case 9: // Provider purchase. $aiOrder = AIOrder::find($trip->ReasonId); $reason = 'Compra automatica ' . $aiOrder->Id; break; case 10: $reason = 'Generado por usuario.'; break; } array_push($tripData, array('Id' => $trip->Id, 'Date' => $trip->Date, 'Driver' => $driver->Name, 'Reason' => $reason, 'Distance' => $trip->Distance, 'Journey' => json_decode($trip->Journey, true), 'StartLat' => $trip->StartLatitude, 'StartLon' => $trip->StartLongitude, 'EndLat' => $trip->EndLatitude, 'EndLon' => $trip->EndLongitude)); } $response['state'] = 'Success'; $response['trips'] = $tripData; return response()->json($response); }
public function price_bills_store(Request $request) { $trans = Transport::where('user_id', \Auth::user()->id)->first(); if ($trans) { $trans->somme = $request->somme; $trans->save(); } else { Transport::create(['somme' => $request->somme, 'user_id' => \Auth::user()->id]); } $niveau_id = $request->niveau; $price = $request->price; $user_id = \Auth::user()->id; $ann_scol = '2015-2016'; $checkPrice = PriceBill::where('user_id', $user_id)->where('niveau', $niveau_id)->where('ann_scol', $ann_scol)->where('school_year_id', $request->school_year)->first(); if ($checkPrice) { $checkPrice->prix = $price; $checkPrice->save(); } else { $priceBill = new PriceBill(); $priceBill->niveau = $niveau_id; $priceBill->prix = $price; $priceBill->ann_scol = $ann_scol; $priceBill->user_id = $user_id; $priceBill->school_year_id = $request->school_year; $priceBill->save(); } return redirect()->back()->with('success', 'Bien enregistré'); }
public function category(Request $request) { $validator = Validator::make($request->all(), ['age_de' => 'required|integer', 'age_a' => 'required|integer', 'prix' => 'required', 'categories' => 'required|integer'], ['age_de.integer' => "L'age De doit etre un nombre entier", 'age_a.integer' => "L'age A doit etre un nombre entier", 'prix.required' => "Le prix de Catégorie est requis", 'categories.required' => 'Vous devez choisir une Catégorie', 'categories.integer' => 'Vous devez choisir une Catégorie']); if ($validator->passes()) { $cat = CategoryBill::where('name', $request->categories)->where('user_id', \Auth::user()->id)->get(); $trans = Transport::where('user_id', \Auth::user()->id)->get(); if (!$trans->isEmpty()) { foreach ($trans as $t) { $t->somme = $request->somme; $t->save(); } } else { Transport::create(['somme' => $request->somme, 'user_id' => \Auth::user()->id]); } if (!$cat->isEmpty()) { foreach ($cat as $c) { $c->age_de = $request->age_de; $c->age_a = $request->age_a; $c->prix = $request->prix; $c->save(); } } else { $newcat = new CategoryBill(); $newcat->user_id = \Auth::user()->id; $newcat->name = $request->categories; $newcat->age_de = $request->age_de; $newcat->age_a = $request->age_a; $newcat->prix = $request->prix; $newcat->save(); } return redirect()->back()->with('success', 'Bien Enregistré dans la base de données'); } else { return redirect()->back()->withErrors($validator); } }
/** * Execute the console command. * * @return mixed */ public function handle() { // Get all transport requests for today group them by vehicle. $transportRequests = Transport::where('Date', '=', date('Y-m-d'))->where('State', '=', 2)->orderBy('VehicleId')->get(); if (count($transportRequests) > 0) { // Seperate all transport request of first vehicle. $vehicleId = 0; $selectedTransport = array(); $sortedByVehicle = array(); foreach ($transportRequests as $transport) { if ($vehicleId == 0) { $vehicleId = $transport->VehicleId; } if ($vehicleId != $transport->VehicleId) { array_push($sortedByVehicle, $selectedTransport); $selectedTransport = array(); $vehicleId = $transport->VehicleId; } else { array_push($selectedTransport, $transport); } } // Add final set to sortedByVehicle array. array_push($sortedByVehicle, $selectedTransport); $clusterArray = array(); foreach ($sortedByVehicle as $s) { // Get other available vehicles of selected vehicle type. $vehicle = Vehicle::find($s[0]->VehicleId); $vehicles = Vehicle::where('Type', '=', $vehicle->Type)->where('Repair', '=', false)->get(); // Check if we have more transport requests than vehicles. if (count($s) >= count($vehicles)) { // If we do go ahead with K-means algorithm. $kmean = array(); $used = array(); foreach ($vehicles as $v) { // Randomly select x amount of indexes from lat lon cluster array and add them to k object. array_push($kmean, array('VehicleId' => $v->Id, 'Mean' => $this->getRandomLocation($s, $used), 'Cluster' => array())); } // Now compare all lat lon points by distance to selected points and add them to closest point cluster. foreach ($s as $t) { $index = $this->getClosest($t, $kmean); array_push($kmean[$index]['Cluster'], $t); } // Start loop until no further changes are made. $changed = true; $limit = 500; while ($changed && $limit > 1) { $changed = false; // Update each mean in k object. foreach ($kmean as $i => $k) { $newMean = $this->calculateMean($k['Cluster']); if ($newMean['Lat'] != $k['Mean']['Lat'] || $newMean['Lat'] != $k['Mean']['Lat']) { $kmean[$i]['Mean'] = $newMean; $changed = true; } // Clean cluster array in each k-object. $kmean[$i]['Cluster'] = array(); } // Compare lat lon points by distance again. foreach ($s as $t) { $index = $this->getClosest($t, $kmean); array_push($kmean[$index]['Cluster'], $t); } // Emergency exit. $limit--; } // Now that this set has been organized update them in database. foreach ($kmean as $k) { foreach ($k['Cluster'] as $index => $t) { $t->Order = $index + 1; $t->VehicleId = $k['VehicleId']; print_r($t); $t->save(); } } } else { // TODO: This is here to improve transport selection when there is very little to do. echo 'less transport requests'; } } } }
/** * Execute the console command. * * @return mixed */ public function handle() { // Get providers. $providers = Provider::all(); // Get the branches. $branches = Branch::all(); // Loop through them and check which ones are set to auto order. foreach ($providers as $provider) { if ($provider->AIManaged) { foreach ($branches as $branch) { // Now let's get all the products for this provider. $products = Stock::where('BranchId', '=', $branch->Id)->where('ProviderId', '=', $provider->Id)->get(); $order = array(); foreach ($products as $product) { if ($product->Quantity <= $product->Minimum) { $order[$product->Code] = array('Code' => $product->Code, 'Description' => $product->Description, 'Exist' => $product->Quantity, 'Cost' => $product->Cost, 'Minimum' => $product->Minimum, 'Order' => 0, 'Average' => 0, 'Sold' => 0); } } // Get all the products sold in selected sample range. $today = date('Y-m-d H:i:s'); switch ($provider->SampleRange) { case '1week': $startDate = date('Y-m-d H:i:s', strtotime($today) - 604800); $sales = Sale::where('BranchId', '=', $branch->Id)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get(); foreach ($sales as $sale) { $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get(); foreach ($breakdown as $item) { if (array_key_exists($item->Code, $order)) { $order[$item->Code]['Sold'] += $item->Quantity; } } } // Now calculate average of each product. foreach ($order as $index => $product) { $order[$index]['Average'] = $product['Sold'] / 7; } break; case '2week': $startDate = date('Y-m-d H:i:s', strtotime($today) - 1209600); $sales = Sale::where('BranchId', '=', $branch->Id)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get(); foreach ($sales as $sale) { $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get(); foreach ($breakdown as $item) { if (array_key_exists($item->Code, $order)) { $order[$item->Code]['Sold'] += $item->Quantity; } } } // Now calculate average of each product. foreach ($order as $index => $product) { $order[$index]['Average'] = $product['Sold'] / 14; } break; case '1month': $startDate = date('Y-m-d H:i:s', strtotime($today) - 2419200); $sales = Sale::where('BranchId', '=', $branch->Id)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get(); foreach ($sales as $sale) { $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get(); foreach ($breakdown as $item) { if (array_key_exists($item->Code, $order)) { $order[$item->Code]['Sold'] += $item->Quantity; } } } // Now calculate average of each product. foreach ($order as $index => $product) { $order[$index]['Average'] = $product['Sold'] / 30; } break; case '3month': $startDate = date('Y-m-d H:i:s', strtotime($today) - 7257600); $sales = Sale::where('BranchId', '=', $branch->Id)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get(); foreach ($sales as $sale) { $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get(); foreach ($breakdown as $item) { if (array_key_exists($item->Code, $order)) { $order[$item->Code]['Sold'] += $item->Quantity; } } } // Now calculate average of each product. foreach ($order as $index => $product) { $order[$index]['Average'] = $product['Sold'] / 90; } break; case '1year': $startDate = date('Y-m-d H:i:s', strtotime($today) - 29030400); $sales = Sale::where('BranchId', '=', $branch->Id)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get(); foreach ($sales as $sale) { $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get(); foreach ($breakdown as $item) { if (array_key_exists($item->Code, $order)) { $order[$item->Code]['Sold'] += $item->Quantity; } } } // Now calculate average of each product. foreach ($order as $index => $product) { $order[$index]['Average'] = $product['Sold'] / 365; } break; } // Now calculate amount to order based on average, existence, minimum and order range. switch ($provider->OrderRange) { case '3day': foreach ($order as $index => $product) { $estimatedOrder = $product['Average'] * 3; // Order should be at least twice minimum required with existence influded. if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) { $estimatedOrder = $product['Minimum'] * 2; } $order[$index]['Order'] = ceil($estimatedOrder); } break; case '1week': foreach ($order as $index => $product) { $estimatedOrder = $product['Average'] * 7; // Order should be at least twice minimum required with existence influded. if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) { $estimatedOrder = $product['Minimum'] * 2; } $order[$index]['Order'] = ceil($estimatedOrder); } break; case '2week': foreach ($order as $index => $product) { $estimatedOrder = $product['Average'] * 14; // Order should be at least twice minimum required with existence influded. if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) { $estimatedOrder = $product['Minimum'] * 2; } $order[$index]['Order'] = ceil($estimatedOrder); } break; case '1month': foreach ($order as $index => $product) { $estimatedOrder = $product['Average'] * 30; // Order should be at least twice minimum required with existence influded. if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) { $estimatedOrder = $product['Minimum'] * 2; } $order[$index]['Order'] = ceil($estimatedOrder); } break; case '3month': foreach ($order as $index => $product) { $estimatedOrder = $product['Average'] * 90; // Order should be at least twice minimum required with existence influded. if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) { $estimatedOrder = $product['Minimum'] * 2; } $order[$index]['Order'] = ceil($estimatedOrder); } break; } // Check if we have recently made an order for this provider to fix order. $aiOrders = AIOrder::where('GenerationDate', '>', date('Y-m-d H:i:s', strtotime($today) - 259200))->where('Received', '=', false)->where('BranchId', '=', $branch->Id)->get(); foreach ($aiOrders as $o) { // Get breakdown and remove quantity from order. $breakdown = AIOrderBreakdown::where('AIOrderId', '=', $o->Id)->get(); foreach ($breakdown as $item) { if (array_key_exists($item->Code, $order)) { $order[$item->Code]['Order'] -= $item->Quantity; } } } // Check if we have anything to order. $sendOrder = false; foreach ($order as $item) { if ($item['Order'] > 0) { $sendOrder = true; } } if (!$sendOrder) { return 1; } // Generate Order. $aiOrder = AIOrder::create(array('GenerationDate' => date('Y-m-d H:i:s'), 'ConfirmationDate' => '0000-00-00 00:00:00', 'ProviderId' => $provider->Id, 'BranchId' => $branch->Id, 'Received' => false, 'EstimatedDelivery' => date('Y-m-d', strtotime("+3 days")))); foreach ($order as $item) { AIOrderBreakdown::create(array('AIOrderId' => $aiOrder->Id, 'Code' => $item['Code'], 'Quantity' => $item['Order'])); } $breakdown = AIOrderBreakdown::where('AIOrderId', '=', $aiOrder->Id)->get(); // Now if the provider has delivery send email with order. if ($provider->Delivery) { // Now check what method we will use to make order. if ($provider->Method == 'email') { try { Mail::send('emails.ai.makeOrder', ['order' => $aiOrder, 'breakdown' => $breakdown], function ($message) use($provider, $aiOrder) { $message->to($provider->Email); $message->subject('Orden de Compra: ' . $aiOrder->Id); }); } catch (\Exception $e) { // In this case we should let an administrator know that the email order failed. $users = User::where('UserLevel', '=', 1)->get(); foreach ($users as $admin) { Notification::create(array('UserId' => $admin->Id, 'Created' => date('Y-m-d H:i:s'), 'Reason' => 'Aergia no fue capaz de organizar un pedido via correo para ' . $provider->Name . '. Por favor revisar orden y organizar su compra.', 'Url' => '/ai/order/' . $aiOrder->Id, 'Seen' => false)); } } } else { if ($provider->Method == 'ai') { // TODO: Establish Contact via AI. } } } else { // If the provider doesn't have delivery program a trip to make purchase. $vehicles = Vehicle::where('BranchId', '=', $branch->Id)->where('Repair', '=', false)->get(); $vehicle = null; foreach ($vehicles as $v) { if (!$vehicle) { $vehicle = $v; } // In this case the bigger the vehicle the more suitable it should be. // TODO: This could be improved. if ($v->Type > $vehicle->Type) { $vehicle = $v; } } if (!$vehicle) { // In this case we don't have a vehicle and the provider doesn't provide delivery so we must notify an administrator. $users = User::where('UserLevel', '=', 1)->get(); foreach ($users as $admin) { Notification::create(array('UserId' => $admin->Id, 'Created' => date('Y-m-d H:i:s'), 'Reason' => 'Aergia no fue capaz de organizar un pedido a para ' . $provider->Name . '. Por favor revisar orden y organizar su compra.', 'Url' => '/ai/order/' . $aiOrder->Id, 'Seen' => false)); } } else { // Get location of provider. $location = Location::find($provider->LocationId); $transport = Transport::create(array('Date' => date('Y-m-d', strtotime("+1 day")), 'Time' => '00:00:00', 'VehicleId' => $vehicle->Id, 'DriverId' => 0, 'StartLatitude' => 0, 'StartLongitude' => 0, 'Journey' => '[]', 'EndLatitude' => $location->Latitude, 'EndLongitude' => $location->Longitude, 'EndAddress' => $provider->Address, 'Distance' => 0, 'ReasonId' => $aiOrder->Id, 'Type' => 9, 'State' => 2, 'Order' => 0, 'Depreciation' => 0)); // Update Estimated Delivery Date. $aiOrder->EstimatedDelivery = date('Y-m-d', strtotime("+1 day")); $aiOrder->save(); } } } } } }