Example #1
0
 /**
  * Function that saves an Institution.
  *
  * @return Response
  */
 public function saveInstitution()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('name' => 'required', 'id' => 'required', 'phone' => 'required', 'address' => 'required', 'lat' => 'required', 'lon' => 'required', 'creditLimit' => 'required', 'institutionId' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => 'No se envio la informacion completa!']);
     }
     // 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(['state' => 'No autorizado']);
     }
     // Get the credit value.
     $credit = Input::get('credit') ? true : false;
     $creditLimit = Input::get('creditLimit');
     // Reset creditLimit just in case.
     if (!$credit) {
         $creditLimit = 0;
     }
     // Get the institution.
     $institution = Institution::find(Input::get('institutionId'));
     if (!$institution) {
         $response['state'] = 'Error';
         $response['error'] = 'No existe una institucion con este numero de identifiacion!';
         return response()->json($response);
     }
     // Now get the location.
     $location = Location::find($institution->LocationId);
     // Update Institution.
     $institution->Name = Input::get('name');
     $institution->RUC = Input::get('id');
     $institution->Phone = Input::get('phone');
     $institution->Email = Input::get('email');
     $institution->Address = Input::get('address');
     $institution->Excempt = Input::get('excemption');
     $institution->Credit = $credit;
     $institution->CreditLimit = $creditLimit;
     // Save the Institution.
     $institution->save();
     // Update the location.
     $location->Name = 'Direccion de ' . Input::get('name');
     $location->Latitude = Input::get('lat');
     $location->Longitude = Input::get('lon');
     // Save the location.
     $location->save();
     return response()->json(['state' => 'Success']);
 }
 public function reject_payment($typeId, $id, $narration_id)
 {
     $user = Institution::find($id);
     return view('backend.institutions.payment_reject', compact('typeId', 'id', 'narration_id'));
 }
use App\Sale;
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>
 /**
  * Function that gets reservation information.
  *
  * @return Response
  */
 public function getReservationData()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('id' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => 'No se recibieron los datos necesarios!']);
     }
     // Check that user is part of authorized staff.
     if (Auth::user()->Type != 1) {
         $response['state'] = 'No Autorizado';
         $response['error'] = 'Usuario no autorizado!';
         return response()->json($response);
     }
     // Get user branch.
     $worker = Worker::find(Auth::user()->TypeId);
     $userBranch = $worker->BranchId;
     // Get the reservation.
     $reservation = Reservation::find(Input::get('id'));
     // Get the breakdown of the reservation.
     $reservationBreakdown = ReservationBreakdown::where('ReservationId', '=', $reservation->Id)->get();
     $reservationItems = array();
     foreach ($reservationBreakdown as $breakdown) {
         // Try getting the product.
         $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
         if (!$product) {
             // If it's not a product it's a service.
             $service = Service::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
             array_push($reservationItems, array('quantity' => $breakdown->Quantity, 'description' => $service->Description, 'price' => $service->Price));
         } else {
             array_push($reservationItems, array('quantity' => $breakdown->Quantity, 'note' => $product->Description, 'price' => $product->Price));
         }
     }
     // Get the client's or institution's information.
     $client;
     if ($reservation->CreditorId != 0) {
         if ($reservation->CreditorType != 1) {
             $temp = Institution::find($reservation->CreditorId);
             $client = array('Name' => $temp->Name, 'Address' => $temp->Address, 'Id' => $temp->RUC);
         } else {
             $temp = Client::find($reservation->CreditorId);
             $client = array('Name' => $temp->Name, 'Address' => $temp->Address, 'Id' => $temp->Id);
         }
     } else {
         $client = array('Name' => 'No asignado', 'Address' => 'No asignado', 'Id' => 'No asignado');
     }
     // Get configuration info.
     $config = Configuration::find(0);
     //  Now prepare all the information to be returned to user.
     $response['state'] = 'Success';
     $response['clientInfo'] = $client;
     $response['reservationInfo'] = array('Date' => date('Y-m-d', strtotime($reservation->Created)), 'Life' => $config->ReservationLife, 'ReservationId' => $reservation->Id, 'SubTotal' => $reservation->Value, 'Discount' => $reservation->Discount, 'Tax' => $reservation->Tax, 'Deposit' => $reservation->Deposit, 'Total' => $reservation->Value + $reservation->Tax - $reservation->Discount);
     $response['reservationItems'] = $reservationItems;
     // Return response.
     return response()->json($response);
 }
Example #5
0
 /**
  * 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);
 }
Example #6
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);
                             });
                         }
                     }
                 }
             }
         }
     }
 }
 /**
  * @param $id
  * @return \Illuminate\Http\RedirectResponse
  *
  */
 private function storeORUpdate(Request $request, Course $course)
 {
     $this->validate($request, ['institution' => 'required|integer', 'courseName' => 'required|max:64', 'description' => 'required|min:10', 'price' => 'numeric|required|min:0|max:9999', 'startDate' => 'required|date', 'duration' => 'required|min:0|max:480|integer', 'participantNum' => 'required|min:1|max:50|Integer']);
     $institution = Institution::find($request->institution);
     #TODO validate the institute here.
     #$this->validator->after(function($validator) {
     #    if ($this->somethingElseIsInvalid()) {
     #        $validator->errors()->add('field', 'Something is wrong with this field!');
     #    }
     #});
     $course->institution()->associate($institution);
     $course->courseName = $request->courseName;
     $course->description = $request->description;
     $course->price = $request->price;
     $course->startDate = $request->startDate;
     $course->duration = $request->duration;
     $course->participantNum = $request->participantNum;
     $course->user()->associate(Auth::user());
     if ($course->save()) {
         \Session::flash('flash_message', "Der Kurs wurde erfolgreich gespeichert");
         \Session::flash('flash_message_type', "success");
         return redirect()->action('CourseController@show', [$course->id]);
     } else {
         return Redirect::back()->withError("Der Kurs konnte leider nicht gespeichert werden.")->withInput();
     }
 }
        // Get the client.
        $client = Client::find($bill->CreditorId);
        if ($days > $client->CreditDays) {
            // Get any payments made to it.
            $paid = 0;
            $payments = CashReceipt::where('Type', '=', 2)->where('TypeId', '=', $bill->Id)->get();
            foreach ($payments as $payment) {
                $paid += $payment->Value;
            }
            $total = $bill->Value + $bill->Tax;
            $pending = $total - $paid;
            array_push($lateBills, array('Id' => $bill->Id, 'Total' => $total, 'Pending' => $pending, 'State' => 'Atrasado'));
        }
    } else {
        // Get the institution.
        $institution = Institution::find($bill->CreditorId);
        if ($days > $institution->CreditDays) {
            // Get any payments made to it.
            $paid = 0;
            $payments = CashReceipt::where('Type', '=', 2)->where('TypeId', '=', $bill->Id)->get();
            foreach ($payments as $payment) {
                $paid += $payment->Value;
            }
            $total = $bill->Value + $bill->Tax;
            $pending = $total - $paid;
            array_push($lateBills, array('Id' => $bill->Id, 'Total' => $total, 'Pending' => $pending, 'State' => 'Atrasado'));
        }
    }
}
?>
@foreach($lateBills as $bill)
Example #9
0
$currentNotification->save();
$permissions = json_decode(UserLevel::find(Auth::user()->UserLevel)->Permissions);
$debt = Sale::find($id);
$totalDebt = $debt->Value + $debt->Tax;
// Check to see if there have been any previous payments.
$pastPaymentTotal = 0;
$payments = CashReceipt::where('Type', '=', 2)->where('TypeId', '=', $debt->Id)->get();
foreach ($payments as $payment) {
    $pastPaymentTotal += $payment->Value;
}
$salebreakdown = SaleBreakdown::where('SaleId', '=', $debt->Id)->get();
$creditor = null;
if ($debt->CreditorType == 1) {
    $creditor = Client::find($debt->CreditorId);
} else {
    $creditor = Institution::find($debt->CreditorId);
}
$branchId = Worker::find(Auth::user()->TypeId)->BranchId;
$branch = Branch::find($branchId);
$subtotal = 0;
$regimen = json_decode($branch->DefaultExpenses)->regimen;
?>
<!DOCTYPE html>
<html lang="es">
    <head>
        <title>Eirene Systema Administrativo</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta charset="UTF-8">
        <meta name="csrf-token" content="{{{ Session::token() }}}">
        <link href="{{ URL::to('/') }}/css/bootstrap.min.css" rel="stylesheet">
 /**
  * Show the form for editing the specified resource.
  *
  * @param  int  $id
  * @return Response
  */
 public function edit(Request $request)
 {
     if ($request->ajax()) {
         return Institution::find($request->id);
     }
 }
 /**
  * Function that gets transaction Data.
  *
  * @return Response
  */
 public function transactionData()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('id' => 'required'));
     $response = array();
     if ($validator->fails()) {
         $response['state'] = 'Error';
         $response['error'] = 'La identification de la transaccion es necesaria!';
         return response()->json($response);
     }
     // Check that user is part of authorized staff.
     if (Auth::user()->Type != 1) {
         $response['state'] = 'No Autorizado';
         $response['error'] = 'Usuario no autorizado!';
         return response()->json($response);
     }
     // Get transaction Data.
     $transaction = CashboxTransaction::find(Input::get('id'));
     if (!$transaction) {
         $response['state'] = 'Fail';
         $response['error'] = 'Esta transaccion no existe!';
         return response()->json($response);
     }
     // Modify transaction Data.
     $transaction->DateTime = date('Y-m-d', strtotime($transaction->DateTime));
     // Get cashbox.
     $cashbox = Cashbox::find($transaction->CashboxId);
     // Get worker.
     $worker = Worker::find(User::find($cashbox->UserId)->TypeId);
     if ($transaction->Type == 1 || $transaction->Type == 7) {
         // Get sale.
         $sale = Sale::where('TransactionId', '=', $transaction->Id)->first();
         // Get items in sale.
         $items = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
         $itemsData = array();
         // Loop trough sales breakdown and extract products or services data.
         foreach ($items as $item) {
             $product = Stock::where('Code', '=', $item->Code)->where('BranchId', '=', $sale->BranchId)->first();
             if (!$product) {
                 $service = Service::where('Code', '=', $item->Code)->where('BranchId', '=', $sale->BranchId)->first();
                 array_push($itemsData, $service);
             } else {
                 array_push($itemsData, $product);
             }
         }
         // Now get client or institution information.
         $creditor = array('Name' => 'No Asignado.', 'Address' => 'No Asignado.', 'Id' => 'No Asignado');
         if ($sale->CreditorId != 0) {
             if ($sale->CreditorType == 1) {
                 $creditor = Client::find($sale->CreditorId);
             } else {
                 $creditor = Institution::find($sale->CreditorId);
             }
         }
         // Now return transaction data.
         $response['state'] = 'Success';
         $response['transaction'] = $transaction;
         $response['cashbox'] = $cashbox;
         $response['worker'] = $worker;
         $response['sale'] = $sale;
         $response['items'] = $items;
         $response['itemsData'] = $itemsData;
         $response['creditor'] = $creditor;
         return response()->json($response);
     } else {
         // Check if this is a payment for a provider bill.
         if ($transaction->Type == 2) {
             // Get the provider bill information.
             $providerBillPayment = ProviderBillPayment::where('TransactionId', '=', $transaction->Id)->first();
             // Get the provider bill and provider.
             $providerBill = ProviderBill::find($providerBillPayment->ProviderBillId);
             $provider = Provider::find($providerBill->ProviderId);
             // Get all debt from provider.
             $providerBills = ProviderBill::where('State', '=', 1)->where('ProviderId', '=', $provider->Id)->get();
             $totalDebt = 0;
             foreach ($providerBills as $bill) {
                 $totalDebt += $bill->Value;
             }
             // Get all payments.
             $providerBillPayments = ProviderBillPayment::where('ProviderBillId', '=', $providerBill->Id)->get();
             // Get name of worker that made each payment.
             foreach ($providerBillPayments as $payment) {
                 $tempTransaction = CashboxTransaction::find($payment->TransactionId);
                 $workerName = Worker::find(User::find(Cashbox::find($tempTransaction->CashboxId)->UserId)->TypeId)->Name;
                 $payment['Name'] = $workerName;
             }
             // Return what we have.
             $response['state'] = 'Success';
             $response['transaction'] = $transaction;
             $response['cashbox'] = $cashbox;
             $response['worker'] = $worker;
             $response['date'] = date('Y-m-d');
             $response['totalDebt'] = $totalDebt;
             $response['provider'] = $provider;
             $response['providerBill'] = $providerBill;
             $response['providerBillPayments'] = $providerBillPayments;
         } else {
             // No special information needed, just return what we have.
             $response['state'] = 'Success';
             $response['transaction'] = $transaction;
             $response['cashbox'] = $cashbox;
             $response['worker'] = $worker;
         }
         return response()->json($response);
     }
 }