Пример #1
0
 /**
  * Handle the event.
  *
  * @param  Events  $event
  * @return void
  */
 public function handle(NotifiableEvent $event)
 {
     $notification = Notification::create($event->getData());
     $notification->notifiable()->associate($event->getNotifiable());
     $notification->save();
     $event->getUser()->notifications()->save($notification);
 }
Пример #2
0
 /**
  * Create new notification.
  *
  * @param CreateNotificationRequest $request
  * @return mixed
  */
 public function create(CreateNotificationRequest $request)
 {
     Notification::create(['title' => $request->get('title'), 'message' => $request->get('message'), 'notification_type_id' => NotificationType::where('type', $request->get('type'))->first()->id, 'targeted_user_id' => TargetedUser::first()->id]);
     $response = new AjaxResponse();
     $response->setSuccessMessage(trans('notifications.notification_created'));
     return response($response->get())->header('Content-Type', 'application/json');
 }
Пример #3
0
 public function editPost($id, EditPostRequest $request)
 {
     $post = Post::findOrFail($id);
     $post->update(['post' => $request->input('post'), 'editor_id' => \Auth::id(), 'editor_name' => \Auth::user()->name, 'was_edited' => 1, 'edit_reason' => $request->input('edit_reason')]);
     Notification::create(['not_title' => 'Kliknij i przejdź do posta, aby sprawdzić szczegóły', 'not_body' => 'Twój post w artykule został edytowany', 'not_status' => 5, 'not_from_user_name' => \Auth::user()->name, 'user_id' => $post->user['id'], 'not_route' => '' . $request->input('take_uri') . '#post' . $id . '']);
     flash()->success('Udało Ci się edytować post o ID <b>' . $id . '</b>!');
     return redirect('/admin/article/' . $request->input('take_article_id') . '');
 }
Пример #4
0
 /**
  * Store a newly created resource in storage.
  *
  * @param  Request  $request
  * @return Response
  */
 public function store(Request $request)
 {
     $v = Validator::make($request->all(), ['title' => 'required', 'body' => 'required', 'will_be' => 'required']);
     if ($v->fails()) {
         return redirect()->back()->withErrors($v->errors());
     }
     $notification = Notification::create($request->all());
     return Redirect::to('admin/notifications');
 }
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     Model::unguard();
     $this->call('UsersTableSeeder');
     DB::table('package')->delete();
     \App\Package::create(['name' => 'hoc', 'content' => 'hoc hanh']);
     DB::table('notification')->delete();
     \App\Notification::create(['title' => 'hoc bong abc', 'content' => 'hoc hanh', 'package_id' => 1]);
     // Add calls to Seeders here
 }
Пример #6
0
 public function update($id)
 {
     // save updated
     $record = $this->records->find($id);
     if (!$record) {
         Notification::create(Input::all());
         return $this->respond($record);
     }
     $record->fill(Input::all())->save();
     return $this->respond($record);
 }
Пример #7
0
 /**
  * Execute the console command. TODO: This could probably be better? Ok for now though, it works:)
  *
  * @return mixed
  */
 public function handle()
 {
     try {
         $this->ping("google.com");
     } catch (\Exception $e) {
         // If we can't ping google I'll assume we're offline, so let's notify admins.
         $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 detectado de que no tiene conexion a internet, por favor restablecer la conexion para que el sistema pueda mantener su correcto funcionamiento!', 'Url' => '#', 'Seen' => false));
         }
     }
 }
 /**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function store(Request $request)
 {
     try {
         $inputs = $request->all();
         unset($inputs['_token']);
         $device_tokens = Customer::where('platform', 'A')->lists('device_token');
         $is_sent = PnS::sendPnsToAndroidDevices($device_tokens, $inputs['body']);
         if ($is_sent) {
             $inputs['user_id'] = Auth::id();
             Notification::create($inputs);
         }
         return redirect()->to('/crm/notification/')->withMessage(Generate::success_message('Success', 'Sent Successfully'));
     } catch (Exception $e) {
         return redirect()->to('/crm/notification/')->withMessage(Generate::error_message('Failed', $e->getMessage()));
     }
 }
 public function accept()
 {
     $oMate = Mate::where('from_user_id', Input::get('from_user_id'))->where('status', Mate::MATE_STATUS_ADDED_BY_USER)->orWhere('status', Mate::MATE_STATUS_ADDED_BY_ADMIN)->first();
     $oMate->update(['status' => Mate::MATE_STATUS_ACCEPTED_BY_USER]);
     if ($oMate) {
         $aMate = $oMate->toArray();
         $aUpdate = Update::create(['user_id' => Session::get('user')['id'], 'update_type' => Update::UPDATE_TYPE_MATE, 'status' => Update::UPDATE_STATUS_ACTIVE]);
         $aNotification = Notification::create(['from_user_id' => $aMate['to_user_id'], 'to_user_id' => $aMate['from_user_id'], 'notification_type' => Notification::NOTIFICATION_TYPE_MATE_ACCEPTED_REQUEST_BY_USER, 'status' => Notification::NOTIFICATION_STATUS_ACTIVE, 'mate_id' => $aMate['id']]);
         if ($aUpdate) {
             return response()->json(['status' => true, 'message' => "Successfully accepted", 'mate' => json_encode($aMate)]);
         } else {
             return response()->json(['status' => false, 'message' => "Something went wrong. Please try again"]);
         }
     } else {
         return response()->json(['status' => false, 'message' => "Something went wrong. Please try again"]);
     }
 }
Пример #10
0
 public function run()
 {
     DB::table('notifications')->delete();
     Notification::create(['user_id' => 3, 'loan_id' => 1, 'notification_type' => 'comment', 'task' => 'You have a message']);
     Notification::create(['user_id' => 3, 'loan_id' => 2, 'notification_type' => 'report', 'report_id' => 1, 'task' => 'Confirm Activity Detail Report']);
     Notification::create(['user_id' => 3, 'loan_id' => 1, 'report_id' => 2, 'notification_type' => 'report', 'task' => 'Confirm Customer Budget Report']);
     Notification::create(['user_id' => 3, 'loan_id' => 2, 'report_id' => 3, 'notification_type' => 'report', 'task' => 'Confirm Account Reconciliation Report']);
     Notification::create(['user_id' => 3, 'loan_id' => 1, 'report_id' => 9, 'notification_type' => 'report', 'task' => 'Confirm Crop Mix Report']);
     Notification::create(['user_id' => 4, 'loan_id' => 1, 'notification_type' => 'report', 'report_id' => 1, 'task' => 'Confirm Activity Detail Report']);
     Notification::create(['user_id' => 4, 'loan_id' => 1, 'report_id' => 2, 'notification_type' => 'report', 'task' => 'Confirm Customer Budget Report']);
     Notification::create(['user_id' => 4, 'loan_id' => 1, 'report_id' => 3, 'notification_type' => 'report', 'task' => 'Confirm Account Reconciliation Report']);
     Notification::create(['user_id' => 4, 'loan_id' => 1, 'report_id' => 9, 'notification_type' => 'report', 'task' => 'Confirm Crop Mix Report']);
     Notification::create(['user_id' => 3, 'loan_id' => 1, 'notification_type' => 'vote', 'task' => 'Review Loan: Tony Stark - Glass Towers']);
     Notification::create(['user_id' => 3, 'loan_id' => 2, 'notification_type' => 'vote', 'task' => 'Review Loan: Clint Barton - Nested Row']);
     Notification::create(['user_id' => 3, 'notification_type' => 'office', 'task' => 'Staff Meeting on Wednesday, Dec. 10, 2014', 'status' => 'acknowledged']);
     Notification::create(['user_id' => 4, 'notification_type' => 'office', 'task' => 'Review Site']);
     Notification::create(['user_id' => 4, 'notification_type' => 'office', 'task' => 'Report Progress']);
     Notification::create(['user_id' => 4, 'notification_type' => 'office', 'task' => 'Enjoy life!']);
 }
 public function store(Requests\NotifyRequest $request)
 {
     //how to fetch all input and fetch each individual
     //Notification::create($request->all());
     //$input = Request::all();
     //$input = Request::get('title');
     //$input['date'] = ('date');
     //Store the form created
     //Notification::create($input);
     //Using auth
     //$notification = new Notification($request->all());
     //Auth::user()->articles()->save($article);
     //session()->flash('flash_message', 'Your notification has been saved');
     //session()->flash('flash_message_important', 'true');
     //validation
     //Inline to make cleaner
     Notification::create($request->all());
     flash('Notification is created');
     return redirect('notifies');
     //return $input;
 }
Пример #12
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     // Get all calendar entries that are due in two hours.
     $now = date('Y-m-d H:i:s');
     $events = Calendar::where('Reminded', '=', false)->where('Start', '<=', date('Y-m-d H:i:s', strtotime($now) + 7200))->get();
     // Now remind each user.
     foreach ($events as $event) {
         $user = User::where('TypeId', '=', $event->WorkerId)->first();
         $notification = Notification::create(array('UserId' => $user->Id, 'Created' => $now, 'Reason' => 'Recordatorio de Evento: ' . $event->Title, 'Url' => '/calendar/' . $event->Id, 'Seen' => false));
         // Update event.
         $event->Reminded = true;
         $event->save();
         // Now check if this event should be rescheduled.
         switch ($event->Type) {
             case 2:
                 // Add event next week.
                 Calendar::create(array('Start' => date('Y-m-d H:i:s', strtotime($event->Start) + 604800), 'End' => date('Y-m-d H:i:s', strtotime($event->End) + 604800), 'WorkerId' => $event->WorkerId, 'Title' => $event->Title, 'AllDay' => $event->AllDay, 'Type' => $event->Type));
                 break;
             case 3:
                 // Add event next Month.
                 Calendar::create(array('Start' => date('Y-m-d H:i:s', strtotime($event->Start) + 2419200), 'End' => date('Y-m-d H:i:s', strtotime($event->End) + 2419200), 'WorkerId' => $event->WorkerId, 'Title' => $event->Title, 'AllDay' => $event->AllDay, 'Type' => $event->Type));
                 break;
             case 4:
                 // Add event next Year.
                 Calendar::create(array('Start' => date('Y-m-d H:i:s', strtotime($event->Start) + 29030400), 'End' => date('Y-m-d H:i:s', strtotime($event->End) + 29030400), 'WorkerId' => $event->WorkerId, 'Title' => $event->Title, 'AllDay' => $event->AllDay, 'Type' => $event->Type));
                 break;
         }
     }
     // Check for provider payments.
     $events = Calendar::where('Type', '=', 5)->where('Start', '<=', date('Y-m-d H:i:s', strtotime($now) + 172800))->get();
     // Now remind each user.
     foreach ($events as $event) {
         $user = User::where('TypeId', '=', $event->WorkerId)->first();
         $notification = Notification::create(array('UserId' => $user->Id, 'Created' => $now, 'Reason' => 'Dentro de dos dias se deberia pagar: ' . $event->Title, 'Url' => '/calendar/' . $event->Id, 'Seen' => false));
         // Update event.
         $event->Reminded = true;
         $event->save();
     }
 }
Пример #13
0
 /**
  * 更新消息
  *
  * @return void
  */
 public function store()
 {
     // get params & validate
     $id = Request::get('id');
     $message = Request::get('message');
     $durationAt = Request::get('duration_at');
     $state = Request::get('state');
     $redirectUrl = Request::get('_redirect_url');
     $rules = ['message' => 'required|max:500', 'duration_at' => 'required|date', 'state' => 'required|in:0,1'];
     $validator = Validator::make(Request::all(), $rules);
     if ($validator->fails()) {
         return Redirect::to($redirectUrl)->with('error', '保存失败~');
     }
     // save
     $data = ['message' => $message, 'duration_at' => $durationAt, 'state' => $state];
     if ($id) {
         Notification::where('id', $id)->update($data);
     } else {
         Notification::create($data);
     }
     // redirect
     return Redirect::to($redirectUrl)->with('success', '保存成功~');
 }
Пример #14
0
 /**
  * Handle the event.
  *
  * @param  BookHasCreated  $event
  * @return void
  */
 public function handle(BookHasCreated $event)
 {
     //
     Notification::create(['user_id' => \Auth::id(), 'text' => $event->text, 'url' => $event->url, 'created_on' => Carbon::now(), 'unread' => $event->unread, 'barcode' => $event->barcode]);
 }
 /**
  * Insert Notification
  * @param $senderId
  * @param $receiverId
  * @param $type
  * @param $message
  * @param $itemId
  * @return bool|mixed
  */
 public function insertNotification($senderId, $receiverId, $type, $message, $itemId)
 {
     $notification = Notification::create(['sender_id' => $senderId, 'receiver_id' => $receiverId, 'message' => $message, 'item_id' => $itemId, 'type' => $type]);
     return $notification->id;
 }
Пример #16
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;
         }
     }
 }
Пример #17
0
 /**
  * Function that requests discount.
  *
  * @return Response
  */
 public function requestDiscount()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('discount' => 'required', 'reason' => 'required'));
     $response = array();
     if ($validator->fails()) {
         $response['state'] = 'Error';
         $response['error'] = 'Informacion incompleta!';
         return response()->json($response);
     }
     // 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 worker.
     $worker = Worker::find(Auth::user()->TypeId);
     // Create Request.
     $request = Request::create(array('Amount' => Input::get('discount'), 'Reason' => Input::get('reason'), 'RequestBy' => Auth::user()->Id, 'State' => 'pending', 'GrantedBy' => 0, 'Used' => false));
     // Get admins and notify them.
     $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' => $worker->Name . ' ha solicitado permiso para dar un descuento del ' . $request->Amount . '% en una venta.', 'Url' => '/sales/discountRequest/' . $request->Id, 'Seen' => false));
     }
     $response['state'] = 'Success';
     $response['request'] = $request;
     return response()->json($response);
 }
Пример #18
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();
                     }
                 }
             }
         }
     }
 }
Пример #19
0
 /**
  * Function that withdraws from stock specified materials and creates withdrawal order.
  *
  * @return Response
  */
 public function withdrawal()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('code' => 'required', 'stage' => 'required', 'storageMaterials' => 'required'));
     if ($validator->fails()) {
         // All input should always be provided so just return blank.
         return response()->json(array());
     }
     // 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());
     }
     // First get current stage.
     $item = Production::find(Input::get('code'));
     $stage = $item->currentStage();
     // Extract the used materials thus far.
     $usedMaterials = json_decode($stage->Materials, true);
     $newMaterials = json_decode(Input::get('storageMaterials'), true);
     // Add new materials to used materials.
     foreach ($newMaterials as $newMaterial => $newValue) {
         $found = false;
         foreach ($usedMaterials as $usedMaterial => $usedValue) {
             if ($newMaterial == $usedMaterial) {
                 $found = true;
                 $usedMaterials[$usedMaterial] += $newValue;
             }
         }
         if (!$found) {
             $usedMaterials[$newMaterial] = $newValue;
         }
     }
     // Save stage with new materials.
     $stage->Materials = json_encode($usedMaterials);
     $stage->save();
     // Get the production expense.
     $expense = $item->currentExpense();
     // If this item has a grip fuse materials.
     $estimatedMaterials = json_decode($expense->Materials);
     if ($item->Grip) {
         $gripMaterials = json_decode($expense->GripMaterial);
         $found = false;
         foreach ($gripMaterials as $gripMaterial => $gripQuantity) {
             foreach ($estimatedMaterials as $material => $quantity) {
                 // If the material is already in the used Materials just add extra quantity.
                 if ($material == $gripMaterial) {
                     $found = true;
                     $quantity += $gripQuantity;
                 }
             }
             // If the grip material isn't in used Materials add it.
             $estimatedMaterials[$gripMaterial] = $gripQuantity;
         }
     }
     $response['estimated'] = $estimatedMaterials;
     $response['used'] = $usedMaterials;
     // Now compare both estimated materials with used materials.
     $notified = false;
     foreach ($usedMaterials as $usedMaterial => $usedValue) {
         $found = false;
         foreach ($estimatedMaterials as $material => $value) {
             if ($usedMaterial == $material) {
                 $found = true;
                 if ($usedValue > $value && !$notified) {
                     $notified = true;
                     // Prepare to notify admins.
                     // Admins are UserLevel 1
                     $admins = User::where('UserLevel', '=', 1)->get();
                     $reason = "Se ha agregado un material inusual en la produccion del ataud {$item->Id}" . " en la etapa " . Input::get('stage');
                     // Now send notifications to admins.
                     foreach ($admins as $admin) {
                         Notification::create(array('UserId' => $admin->Id, 'Reason' => $reason, 'Url' => '/storage/production/' . $item->Id . '/stage/' . Input::get('stage'), 'Seen' => false));
                     }
                 }
             }
         }
         if (!$found && !$notified) {
             $notified = true;
             // Prepare to notify admins.
             // Admins are UserLevel 1
             $admins = User::where('UserLevel', '=', 1)->get();
             $reason = "Se ha agregado un material inusual en la produccion del ataud {$item->Id}" . " en la etapa " . Input::get('stage');
             // Now send notifications to admins.
             foreach ($admins as $admin) {
                 Notification::create(array('UserId' => $admin->Id, 'Reason' => $reason, 'Url' => '/storage/production/' . $item->Id . '/stage/' . Input::get('stage'), 'Seen' => false));
             }
         }
     }
     // Now take from stock.
     foreach ($newMaterials as $material => $value) {
         $stockItem = Stock::where('Code', '=', $material)->where('BranchId', '=', 2)->first();
         $stockItem->Quantity -= $value;
         $stockItem->save();
     }
     //Now create storage request.
     $reason = Input::get('reason');
     if ($reason == '') {
         $reason = 'Retiro de materiales para etapa ' . Input::get('stage') . ' de Ataud ' . Input::get('code');
     }
     $storageRequest = StorageRequest::create(array('Date' => date('Y-m-d'), 'WorkerId' => $stage->WorkerId, 'ProductionId' => $item->Id, 'Materials' => json_encode($newMaterials), 'Reason' => $reason));
     $response['id'] = $storageRequest->Id;
     // Return suggestions.
     return response()->json($response);
 }
Пример #20
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store(Request $request, NotificationRequest $notificationRequest)
 {
     //
     $fields = $request->except(['optionsRadios', 'email']);
     if ($request->get('email') == 1) {
         if (strcmp($request->get('optionsRadios'), "users") == 0) {
             $user_id = $request->get('user_id');
             $user = User::findOrFail($user_id);
             Mail::send('emails.notification', ['user' => $user, 'fields' => $fields], function ($m) use($user, $fields) {
                 $m->to($user->email)->subject('Usted tiene una nueva notificación ' . $fields['title']);
             });
         } else {
             $role_id = $request->get('role_id');
             $role = Sentinel::findRoleById($role_id);
             $users = $role->users()->with('roles')->get();
             foreach ($users as $user) {
                 Mail::send('emails.notification', ['user' => $user, 'fields' => $fields], function ($m) use($user, $fields) {
                     $m->to($user->email)->subject('Usted tiene una nueva notificación ' . $fields['title']);
                 });
             }
         }
     }
     $notification = Notification::create($fields);
     return \Redirect::to('notifications')->withSuccess('La notificación se ha sido añadido.');
 }
 public function run()
 {
     DB::table('notifications')->delete();
     Notification::create(['name' => 'Deployer', 'channel' => '#testing', 'icon' => ':ghost:', 'webhook' => 'https://hooks.slack.com/services/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', 'project_id' => 1]);
 }
Пример #22
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);
                             });
                         }
                     }
                 }
             }
         }
     }
 }
Пример #23
0
 /**
  * Function that creates a new provider.
  *
  * @return Response
  */
 public function createProvider()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('name' => 'required', 'number' => 'required', 'email' => 'required', 'ruc' => 'required', 'web' => 'required', 'retainer' => 'required'));
     $response = array();
     if ($validator->fails()) {
         $response['state'] = 'Error';
         $response['error'] = 'Informacion incompleta!';
         return response()->json($response);
     }
     // 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 the worker.
     $worker = Worker::find(Auth::user()->TypeId);
     // Create the provider.
     $provider = Provider::create(array('Name' => Input::get('name'), 'Phone' => Input::get('number'), 'Email' => Input::get('email'), 'RUC' => Input::get('ruc'), 'Web' => Input::get('web'), 'Retainer' => Input::get('retainer')));
     // Prepare to notify admins.
     // Admins are UserLevel 1
     $admins = User::where('UserLevel', '=', 1)->get();
     // Now send notifications to admins.
     foreach ($admins as $admin) {
         $reason = "Se ha creado un nuevo proveedor: " . Input::get('name') . " El proveedor fue creado por {$worker->Name}.";
         Notification::create(array('UserId' => $admin->Id, 'Reason' => $reason, 'Url' => '/bills/provider/' . $provider->Id, 'Seen' => false));
     }
     // Get updated list of providers.
     $providers = Provider::all();
     $response['state'] = 'Success';
     $response['providers'] = $providers;
     // Return result.
     return response()->json($response);
 }
Пример #24
0
 public function updateAppel($id, UpdateAppelRequest $request)
 {
     $appel = Appelation::findOrFail($id);
     if ($request->input('app_status') == 2) {
         $appel->update(['app_status' => $request->input('app_status')]);
         Notification::create(['not_title' => 'Kliknij i przejdź do panelu apelacji, aby sprawdzić szczegóły', 'not_body' => 'Twoja apelacja została pozytywnie rozpatrzona', 'not_status' => 2, 'not_from_user_name' => \Auth::user()->name, 'user_id' => $appel->user['id'], 'not_route' => '/appelpanel']);
         flash()->success('Apelacja została pozytywnie rozpatrzona, dokończ sprawy z nią związane.');
         return redirect('/admin/appelations');
     } elseif ($request->input('app_status') == 1) {
         $appel->update(['app_status' => $request->input('app_status'), 'app_reason' => $request->input('app_reason')]);
         Notification::create(['not_title' => 'Kliknij i przejdź do panelu apelacji, aby sprawdzić szczegóły', 'not_body' => 'Twoja apelacja została negatywnie rozpatrzona', 'not_status' => 2, 'not_from_user_name' => \Auth::user()->name, 'user_id' => $appel->user['id'], 'not_route' => '/appelpanel']);
         flash()->success('Udało Ci się odrzucić apelację, tworzący dostał odpowiedź zwrotną wraz z powodem odrzucenia.');
         return redirect('/admin/appelations');
     }
 }
 function create(Request $request)
 {
     if (Session::has('user')) {
         //Check the type of comment type to determine what id is to be inserted [photo_id, character_id, family_id, specy_id, post_id, mate_id]
         $iFromType = Input::get('comment-from-type');
         $iFromWhereID = null;
         $iCommentPhotoID = 0;
         $aComment = [];
         switch ($iFromType) {
             case Comment::COMMENT_FROM_TYPE_USER:
                 $iFromWhereID = "user_id";
                 break;
             case Comment::COMMENT_FROM_TYPE_CHARACTER:
                 $iFromWhereID = "character_id";
                 break;
             case Comment::COMMENT_FROM_TYPE_FAMILY:
                 $iFromWhereID = "family_id";
                 break;
             case Comment::COMMENT_FROM_TYPE_SPECY:
                 $iFromWhereID = "specy_id";
                 break;
             case Comment::COMMENT_FROM_TYPE_PHOTO:
                 $iFromWhereID = "photo_id";
                 break;
             case Comment::COMMENT_FROM_TYPE_POST:
                 $iFromWhereID = "post_id";
                 break;
             case Comment::COMMENT_FROM_TYPE_MATE:
                 $iFromWhereID = "mate_id";
                 break;
         }
         $oComment = Comment::create(['from_user_id' => Session::get('user')['id'], 'to_user_id' => Input::get('comment-to-user-id'), 'comment_text' => Input::get('comment-text'), 'status' => Comment::COMMENT_STATUS_DEFAULT, 'comment_type' => $request->file('comment-photo') != null ? Comment::COMMENT_TYPE_PHOTO : Comment::COMMENT_TYPE_TEXT, 'comment_from_type' => Input::get('comment-from-type'), $iFromWhereID => Input::get('comment-from-id'), 'comment_photo_id' => $iCommentPhotoID]);
         //Check if there's a file
         if ($request->file('comment-photo') != null) {
             $sInputImageName = str_replace(' ', '_', Input::get('comment-to-user-id') . '_' . $request->file('comment-photo')->getClientOriginalName());
             $sImageName = rand(1, 1000000) . '_' . Session::get('user')['id'] . '_' . $sInputImageName;
             $request->file('comment-photo')->move(base_path() . '/public/' . Photo::PHOTO_LINK_COMMENT, $sImageName);
             $oPhoto = Photo::create(['user_id' => Session::get('user')['id'], 'photo_type' => Photo::PHOTO_TYPE_COMMENT, 'photo_link' => Photo::PHOTO_LINK_COMMENT . $sImageName, 'status' => Photo::PHOTO_STATUS_DEFAULT]);
             $iCommentPhotoID = $oPhoto->toArray()['id'];
             if ($oPhoto) {
                 Comment::where('id', $oComment->toArray()['id'])->update(['comment_photo_id' => $iCommentPhotoID]);
             }
         }
         if ($oComment) {
             $aComment = Comment::where('id', $oComment->toArray()['id'])->first()->toArray();
             $aNotification = Notification::create(['from_user_id' => Session::get('user')['id'], 'to_user_id' => Input::get('comment-to-user-id'), 'notification_type' => Notification::NOTIFICATION_TYPE_COMMENT, 'status' => Notification::NOTIFICATION_STATUS_ACTIVE, 'comment_id' => $aComment['id']]);
             Update::create(['user_id' => Session::get('user')['id'], 'update_type' => Update::UPDATE_TYPE_COMMENT, 'comment_id' => $aComment['id'], 'status' => Update::UPDATE_STATUS_ACTIVE]);
             //FOR DISPLAY
             $aComment['from_user'] = User::where('id', Session::get('user')['id'])->first()->toArray();
             $aComment['photo_comment'] = $aComment['comment_photo_id'] > 0 ? Photo::where('id', $aComment['comment_photo_id'])->first()->toArray() : [];
         }
         $view = view('users.comments.partials.partial-comment-owner')->with('aComment', $aComment);
         if ($aComment) {
             return response()->json(['status' => true, 'message' => "Successfully submitted comment", 'view' => (string) $view]);
         } else {
             return response()->json(['status' => false, 'message' => "Something went wrong. Please try again"]);
         }
     }
 }
Пример #26
0
 /**
  * Function that adds a loan to defined worker.
  *
  * @return Response
  */
 public function requestLoan()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('worker' => 'required', 'formData' => 'required'));
     if ($validator->fails()) {
         // No reason why staffId and dayType would not be provided so return nothing.
         return response()->json(array());
     }
     // 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());
     }
     // Create request.
     $request = Request::create(array('Amount' => Input::get('formData')['plsamounts'], 'Reason' => Input::get('formData')['plsReasons'], 'RequestBy' => Auth::user()->Id, 'State' => 'pending', 'GrantedBy' => 0, 'Used' => false, 'Created' => date('Y-m-d H:i:s')));
     // Notify admins.
     $worker = Worker::find(Auth::user()->TypeId);
     $loanTo = Worker::where('Cedula', '=', Input::get('worker'))->first();
     $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' => $worker->Name . ' ha solicitado permiso para prestar dinero a ' . $loanTo->Name . '.', 'Url' => '/requestLoan/' . $request->Id, 'Seen' => false));
     }
     $response['state'] = 'Success';
     $response['message'] = 'La solicitud fue realizada exitosamente! Recibiras una notificacion cuando haya respuesta de algun administrador.';
     return response()->json($response);
 }
Пример #27
0
 /**
  * Function that requests permission to authorized users to make a withdrawal.
  *
  * @return Response
  */
 public function othersRequest()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('amount' => 'required', 'reason' => 'required'));
     $response = array();
     if ($validator->fails()) {
         $response['state'] = 'Error';
         $response['error'] = 'No se envio la informacion completa para realizar esta operacion!';
         return response()->json($response);
     }
     // Check that user is part of authorized staff.
     if (Auth::user()->Type != 1) {
         $response['state'] = 'No autorizado';
         $response['error'] = 'El usuario no esta autorizado para realizar esta operacion!';
         return response()->json($response);
     }
     // Check that cashbox is open.
     $cashbox = Cashbox::where('UserId', '=', Auth::user()->Id)->where('Close', '=', NULL)->first();
     if (!$cashbox) {
         $response['state'] = 'Error';
         $response['error'] = 'La caja no esta abierta, por lo tanto no se puede solicitar el retiro!';
         return response()->json($response);
     }
     // Generate Request.
     $request = Request::create(array('RequestBy' => Auth::user()->Id, 'State' => 'pending', 'GrantedBy' => 0, 'Used' => false, 'Amount' => Input::get('amount'), 'Reason' => Input::get('reason')));
     // Get users that have permission to withdraw money from cashbox.
     /*$canWithdraw = array();
             $levels = UserLevel::all();
             foreach($levels as $level) {
                 $permissions = json_decode($level->Permissions);
                 if($permissions->cashbox->withdraw) {
                     array_push($canWithdraw, array($permissions->role => $level->Id));
                 }
             }
     
             // Get info on worker that is making request.
             $worker = Worker::find(Auth::user()->TypeId);
     
             // Send notifications to all users that are admins or are within same branch.
             foreach($canWithdraw as $role => $id) {
                 $users = User::where('UserLevel', '=', $id)->get();
                 foreach($users as $user) {
                     if($role == 'admin') {
                         Notification::create(array('UserId' => $user->Id,
                                                     'Created' => date('Y-m-d H:i:s'),
                                                     'Reason' => $worker->Name.' ha solicitado permiso para retirar dinero de la caja para otros gastos.',
                                                     'Url' => '/request/'.$request->Id,
                                                     'Seen' => false));
                     } else {
                         $workerWithPermission = Worker::find($user->TypeId);
                         if($workerWithPermission->BranchId == $worker->BranchId) {
                             Notification::create(array('UserId' => $user->Id,
                                                     'Created' => date('Y-m-d H:i:s'),
                                                     'Reason' => $worker->Name.' ha solicitado permiso para retirar dinero de la caja para otros gastos.',
                                                     'Url' => '/request/'.$request->Id,
                                                     'Seen' => false));
                         }
                     }
                 }
             }*/
     // Get info on worker that is making request.
     $worker = Worker::find(Auth::user()->TypeId);
     $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' => $worker->Name . ' ha solicitado permiso para retirar dinero de la caja.', 'Url' => '/request/' . $request->Id, 'Seen' => false));
     }
     // Get the total amount of cash that the cashbox was opened with.
     $initial = 0;
     $cash = 0;
     foreach (json_decode($cashbox->Open) as $bill => $amount) {
         if ($bill != 'dollar') {
             $cash += $bill * $amount;
         } else {
             $cash += Configuration::find(0)->Dollar * $amount;
         }
     }
     $initial = $cash;
     // Now get all transactions.
     $transactions = CashboxTransaction::where('CashboxId', '=', $cashbox->Id)->get();
     // Go through transactions to get total of all kind of transactions.
     $card = 0;
     $providers = 0;
     $staff = 0;
     $others = 0;
     $withdrawals = 0;
     $refunds = 0;
     $sales = 0;
     foreach ($transactions as $transaction) {
         switch ($transaction->Type) {
             case 1:
                 $sales += $transaction->Amount;
                 // Check if a credit card was used for sale.
                 if (Sale::where('TransactionId', '=', $transaction->Id)->first()->Card) {
                     $card += $transaction->Amount;
                 } else {
                     $cash += $transaction->Amount;
                 }
                 break;
             case 2:
                 $providers += $transaction->Amount;
                 break;
             case 3:
                 $staff += $transaction->Amount;
                 break;
             case 4:
                 $others += $transaction->Amount;
                 break;
             case 5:
                 $withdrawals += $transaction->Amount;
                 break;
             case 6:
                 $refunds += $transaction->Amount;
                 break;
                 // Contract Payments.
             // Contract Payments.
             case 7:
                 $sales += $transaction->Amount;
                 break;
                 // Credit sales.
             // Credit sales.
             case 8:
                 $sales += $transaction->Amount;
                 break;
                 // Deposits for reservations.
             // Deposits for reservations.
             case 9:
                 $sales += $transaction->Amount;
                 break;
         }
     }
     $cash = $cash + $refunds - $providers - $withdrawals - $others;
     $total = $initial + $sales + $refunds - $providers - $staff - $withdrawals - $others;
     // Inform user operation was completed succesfully.
     $response['state'] = 'Success';
     $response['total'] = $total;
     $response['cash'] = $cash;
     $response['card'] = $card;
     $response['providers'] = $providers;
     $response['staff'] = $staff;
     $response['others'] = $others;
     $response['withdrawals'] = $withdrawals;
     $response['refunds'] = $refunds;
     $response['sales'] = $sales;
     $response['request'] = $request;
     return response()->json($response);
 }