Exemplo n.º 1
0
 public static function addLocationFromIridiumMail($header, $messageBody)
 {
     $from = $header->sender[0]->mailbox . '@' . $header->sender[0]->host;
     $unixtime = (int) $header->udate;
     //echo 'u'.$unixtime.'u';
     //print_r($unixtime);
     $lat = getStringBetween($messageBody, 'Lat+', ' Lon');
     //Lon+13.493400 Alt
     $lon = getStringBetween($messageBody, 'Lon+', ' Alt');
     //        echo 'f**k';
     //        echo $from;
     //        echo $unixtime;
     //        echo $header->fromaddress;
     //        echo "\n";
     //
     //echo strpos($header->fromaddress, '@msg.iridium.com');
     if (strpos($header->fromaddress, '@msg.iridium.com') !== FALSE) {
         $sat_number = (int) str_replace('@msg.iridium.com', '', $header->fromaddress);
         $vehicle = Vehicle::where('sat_number', '=', $sat_number)->get();
         if (isset($vehicle[0])) {
             echo 'Vehicle: ' . $vehicle[0]->id . "\n";
             $vehicleLocation = new \App\VehicleLocation(array('lat' => $lat, 'lon' => $lon, 'vehicle_id' => $vehicle[0]->id, 'timestamp' => $unixtime, 'connection_type' => 'iridium'));
             $vehicleLocation->save();
             return true;
         } else {
             echo "The vehicle is not added to the database:" . $sat_number . "\n";
             return false;
         }
     }
     return false;
     //echo 'coord:'.$lat.','.$lon;
 }
Exemplo n.º 2
0
 /**
  * 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;
         }
     }
 }
Exemplo n.º 3
0
 public function getHomeView(Request $request)
 {
     $activeUser = $request->user();
     $usersVehicles = Vehicle::where('user_id', $activeUser->id)->orderBy('registration', 'asc')->get();
     return view('home')->with(['activeUser' => $activeUser, 'vehicles' => $usersVehicles]);
 }
Exemplo n.º 4
0
 /**
  * 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);
                             });
                         }
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 5
0
 /**
  * Display the specified resource.
  *
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function show($id)
 {
     $estimate = Estimate::findOrFail($id);
     $estimate_details = DB::table('estimate_details')->where('estimate_id', '=', $id)->get();
     $department = Department::where('id', '=', $estimate->department)->firstOrFail();
     $customer = Customer::where('id', '=', $estimate->customer_id)->firstOrFail();
     $vehicle = Vehicle::where('id', '=', $estimate->vehicle_id)->firstOrFail();
     return view('estimates.single-estimate', compact('estimate', 'estimate_details', 'department', 'customer', 'vehicle'));
 }
Exemplo n.º 6
0
 public function show($id)
 {
     $vehicle = \App\Vehicle::where('id', $id)->take(1)->get();
     return response()->json($vehicle);
 }
Exemplo n.º 7
0
 /**
  * Function that locates vehicles.
  *
  * @return Response
  */
 public function locateVehicle()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('vehicle' => '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 vehicle or vehicles.
     $branchId = Worker::find(Auth::user()->TypeId)->BranchId;
     $vehicle = array();
     if (Input::get('vehicle') == 0) {
         $vehicle = Vehicle::where('BranchId', '=', $branchId)->get();
     } else {
         $vehicle = Vehicle::where('Id', '=', Input::get('vehicle'))->get();
     }
     $response['state'] = 'Success';
     $response['vehicle'] = $vehicle;
     return response()->json($response);
 }
Exemplo n.º 8
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index(Request $request)
 {
     $activeUser = $request->user();
     $usersVehicles = Vehicle::where('user_id', $activeUser->id)->orderBy('registration', 'asc')->get();
     return response()->json($usersVehicles);
 }
Exemplo n.º 9
0
 public function updateVehiclePosition(Request $request)
 {
     $all = $request->all();
     $Vehicle = Vehicle::where('user_id', '=', JWTAuth::parseToken()->toUser()->id)->first();
     $lastTracked = VehicleLocation::where('vehicle_id', $Vehicle->id)->orderBy('timestamp', 'desc')->first();
     if (abs($lastTracked->lat - $all['position']["latitude"]) == 0 && abs($lastTracked->lon - $all['position']["longitude"]) == 0) {
         $lastTracked->updated_at = date('Y-m-d H:i:s', time());
         $lastTracked->timestamp = time();
         $lastTracked->save();
     } else {
     }
     $vehicleLocation = new \App\VehicleLocation(array('lat' => $all['position']["latitude"], 'lon' => $all['position']['longitude'], 'vehicle_id' => $Vehicle->id, 'timestamp' => time(), 'connection_type' => 'spotter_app'));
     $vehicleLocation->save();
     $Vehicle->updated_at = date('Y-m-d H:i:s', time());
     $Vehicle->save();
     //echo $vehicleLocation->id;
     //$result['vessels'] = $vehicles->toArray();
     //return $result;
     return $Vehicle;
 }
Exemplo n.º 10
0
 /**
  * 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';
             }
         }
     }
 }
Exemplo n.º 11
0
 /**
  * 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();
                     }
                 }
             }
         }
     }
 }