Example #1
1
 /**
  * @param      $string
  * @param null $path
  * @return string
  */
 public function parse($string, $path = null)
 {
     $headers = [];
     $parts = preg_split('/[\\n]*[-]{3}[\\n]/', $string, 3);
     if (count($parts) == 3) {
         $string = $parts[0] . "\n" . $parts[2];
         $headers = $this->yaml->parse($parts[1]);
     }
     $file = new SplFileInfo($path, '', '');
     $date = Carbon::createFromTimestamp($file->getMTime());
     $dateFormat = config('fizl-pages::date_format', 'm/d/Y g:ia');
     $headers['date_modified'] = $date->toDateTimeString();
     if (isset($headers['date'])) {
         try {
             $headers['date'] = Carbon::createFromFormat($dateFormat, $headers['date'])->toDateTimeString();
         } catch (\InvalidArgumentException $e) {
             $headers['date'] = $headers['date_modified'];
             //dd($e->getMessage());
         }
     } else {
         $headers['date'] = $headers['date_modified'];
     }
     $this->execute(new PushHeadersIntoCollectionCommand($headers, $this->headers));
     $viewPath = PageHelper::filePathToViewPath($path);
     $cacheKey = "{$viewPath}.headers";
     $this->cache->put($cacheKey, $headers);
     return $string;
 }
Example #2
0
 public function makefilename(Request $request)
 {
     $date = Carbon::createFromFormat('d/m/Y', $request['published_at']);
     $date = $date->format('Y-m-d');
     $filename = sprintf('%s-[%s]-%s.png', $date, implode(',', $request['tags']), $this->createSlug($request['heading']));
     return ['filename' => $filename];
 }
Example #3
0
 public static function formatDate($date)
 {
     $instance = Carbon::createFromFormat('Y-m-d', $date);
     setlocale(LC_TIME, 'fr_FR');
     $formatDate = $instance->formatLocalized('%d %B %Y');
     return $formatDate;
 }
Example #4
0
 /**
  * @return string
  */
 public function lastLogin()
 {
     if (!$this->last_login || $this->last_login == '0000-00-00 00:00:00') {
         return;
     }
     return Carbon::createFromFormat('Y-m-d H:i:s', $this->last_login)->diffForHumans();
 }
Example #5
0
 /**
  * Make timestamp
  * @param string $datetime
  * @param string $format
  * @return integer
  */
 public function makeTimeStamp($datetime, $format = 'full')
 {
     if (in_array($format, ['short', 'full'])) {
         $format = $this->getFormat($format);
     }
     return Carbon::createFromFormat($format, $datetime, $this->getTimeZone())->getTimestamp();
 }
 public function postLogin(LoginRequest $request)
 {
     if (!Auth::attempt(['email' => $request->get('email'), 'password' => $request->get('password')], true)) {
         session()->flash('errorMessages', ['You have entered an invalid email address or password.', 'Please try again.']);
         return back()->withInput();
     }
     $user = Auth::user();
     // if the user has a plant, set welcome message
     if (count($user->plants)) {
         $plant = $user->plants()->where('isHarvested', '=', false)->orderBy(DB::raw('RAND()'))->first();
         if ($plant) {
             // set welcome message to need water or need fertilizer if the plant needs it
             $lastTimeWatered = $plant->getLastTimeWatered();
             $lastTimeFertilized = $plant->getLastTimeFertilized();
             $random = round(rand(1, 2));
             if (!$lastTimeWatered && $plant->created_at->addDay() < Carbon::now()) {
                 $status = $plant->plantCharacter['need_water_phrase_' . $random];
             } elseif (!$lastTimeFertilized && $plant->created_at->addDay() < Carbon::now()) {
                 $status = $plant->plantCharacter['need_fertilizer_phrase_' . $random];
             } elseif ($lastTimeWatered && Carbon::createFromFormat('Y-m-d H:i:s', $lastTimeWatered->pivot->date)->addDay() < Carbon::now()) {
                 $status = $plant->plantCharacter['need_water_phrase_' . $random];
             } elseif ($lastTimeFertilized && Carbon::createFromFormat('Y-m-d H:i:s', $lastTimeFertilized->pivot->date)->addDay() < Carbon::now()) {
                 $status = $plant->plantCharacter['need_fertilizer_phrase_' . $random];
             } else {
                 $status = $plant->plantCharacter['welcome_phrase_' . $random];
             }
             session()->flash('message', $plant->plantCharacter->name . ': ' . $status);
         }
     }
     return redirect()->route('dashboard');
 }
 /**
  * Render yearly panel with navigation and chart
  * @param  string $envelopeId Envelope primary key
  * @param  string|null $date Date within the year to consider (default to current year)
  * @return Illuminate\View\View|\Illuminate\Contracts\View\Factory View
  */
 public function getYearly($envelopeId, $date = null)
 {
     $envelope = Auth::user()->envelopes()->findOrFail($envelopeId);
     $date = is_null($date) ? Carbon::today() : Carbon::createFromFormat('Y-m-d', $date);
     $data = ['envelope' => $envelope, 'date' => $date, 'prevYear' => $date->copy()->subYear(), 'nextYear' => $date->copy()->addYear(), 'chart' => LineChart::forge($envelope, $date, LineChart::PERIOD_YEAR)];
     return view('envelope.development.yearly', $data);
 }
    /**
     * Stores a new notification for the user.
     *
     * @param Request $request
     *
     * @return array
     */
    public function create(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'gcm_id'   => 'required|exists:users,gcm_id',
            'movie_id' => 'required|exists:movies,id',
            'date'     => 'required|date|after:today',
            'no_of_seats' => 'required_with_all:after_time,before_time|integer',
            'after_time' => 'required_with_all:no_of_seats,before_time|date_format:g\:i A',
            'before_time' => 'required_with_all:no_of_seats,after_time|date_format:g\:i A',
        ]);

        if ($validator->fails()) {
            return ['errors' => $validator->errors()->all(), 'status' => 'failed'];
        }

        $user = User::whereGcmId($request->get('gcm_id'))->firstOrFail();
        $movie = Movie::findOrFail($request->get('movie_id'));
        $date = Carbon::createFromFormat('Y-m-d', $request->get('date'))->toDateString();
        $numberOfSeats = $request->get('no_of_seats', 0);
        $afterTime = $numberOfSeats ? $request->get('after_time') : null;
        $beforeTime = $numberOfSeats ? $request->get('before_time') : null;

        if (!$movie->showtimes()->where('date', $date)->count()) {
            $user->notifications()->firstOrCreate([
                'movie_id' => $movie->id,
                'date'     => Carbon::createFromFormat('Y-m-d', $date)->toDateTimeString(),
                'sent'     => false,
                'no_of_seats' => $numberOfSeats,
                'after_time' => $afterTime,
                'before_time' => $beforeTime,
            ]);
        }

        return ['status' => 'success'];
    }
Example #9
0
 private function longestPath(&$tasks, &$trail = [])
 {
     if (empty($tasks)) {
         return 0;
     }
     $max = ['weight' => 0, 'trail' => []];
     foreach ($tasks as &$task) {
         if (!$task['from'] || !$task['to']) {
             continue;
         }
         $newTrail = $trail;
         $newTrail[] =& $task;
         $diff = Carbon::createFromFormat('Y-m-d', $task['from'])->diffInDays(Carbon::createFromFormat('Y-m-d', $task['to']));
         $weight = $diff + $this->longestPath($task['slaves'], $newTrail);
         if ($max['weight'] < $weight) {
             $max['weight'] = $weight;
             $max['trail'] = $newTrail;
         }
     }
     if (empty($trail)) {
         //At top level
         foreach ($max['trail'] as &$task) {
             $task['critical'] = true;
         }
     }
     foreach ($max['trail'] as &$task) {
         if (!in_array($task, $trail)) {
             $trail[] =& $task;
         }
     }
     return $max['weight'];
 }
 public function testWithDaysAndStartDate()
 {
     $startDate = Carbon::createFromFormat("Y-m-d", "2014-03-01");
     $request = new Shows(get_token(), $startDate, 25);
     $this->assertContains("25", (string) $request->getDays());
     $this->assertContains("2014-03-01", (string) $request->getStartDate());
 }
 /**
  * Store a newly created resource in storage.
  *
  * @param  Request  $request
  * @return Response
  */
 public function store(Request $request)
 {
     $path = config('enzo.uploads.comprovante_aporte.path');
     $data_aporte = Carbon::createFromFormat('d/m/Y', $request->data)->toDateString();
     // Prepara os dados para que seja feito o upload do arquivo
     $file = $request->file('comprovante');
     $extension = $file->getClientOriginalExtension();
     $newFilename = $request->investidor_id . '_' . str_replace(['.', ','], '', $request->valor) . '_' . $data_aporte . '_' . str_random(2) . '.' . $extension;
     // Cria o objeto com os dados do request
     $aporte = new AporteFinanceiro();
     $aporte->valor = $request->valor;
     $aporte->data = $data_aporte;
     $aporte->comprovante_path = $newFilename;
     $aporte->observacao = $request->observacao;
     $aporte->investidor_id = $request->investidor_id;
     $upload = new UploadFile();
     $retornoUpload = $upload->upload($path, $newFilename, $file);
     if ($retornoUpload['cod'] == 0) {
         return redirect()->back()->with('status', $retornoUpload['msg']);
     }
     // se deu certo o upload do comprovante, salva no banco o "aporte financeiro"
     try {
         $aporte->save();
     } catch (Exception $e) {
         $upload->deleteFile();
         //se deu erro ao salvar no banco, tem q apagar o arquivo q foi upado
         var_dump($e->getMessage());
         //@TODO confirmar se o catch interrompe a execuçao do codigo
     }
     return redirect()->route('aporte-financeiro.index')->with('status', "Aporte financeiro cadastrado com sucesso!");
 }
Example #12
0
 /**
  * Return a timestamp as DateTime object.
  *
  * @param  mixed  $value
  * @return \Carbon\Carbon
  */
 protected function asDateTime($value)
 {
     // \Log::debug('asDateTime: '.$value);
     // If this value is an integer, we will assume it is a UNIX timestamp's value
     // and format a Carbon object from this timestamp. This allows flexibility
     // when defining your date fields as they might be UNIX timestamps here.
     if (is_numeric($value)) {
         // \Log::debug('a');
         return Carbon::createFromTimestamp($value);
     } elseif (preg_match('/^(\\d{4})-(\\d{2})-(\\d{2})$/', $value)) {
         // \Log::debug('b');
         return Carbon::createFromFormat('Y-m-d', $value)->startOfDay();
     } elseif (preg_match('/^(\\d{2}):(\\d{2})(:(\\d{2}))?$/', $value)) {
         // \Log::debug('c');
         $value = Carbon::createFromFormat('H:i:s', $value);
     } elseif (!$value instanceof DateTime) {
         // \Log::debug('d');
         if (null === $value) {
             return $value;
         }
         $format = $this->getDateFormat();
         return Carbon::createFromFormat($format, $value);
     }
     return Carbon::instance($value);
 }
 private function calculateTimerTime($start, $finish)
 {
     $carbon_start = Carbon::createFromFormat('Y-m-d H:i:s', $start);
     $carbon_finish = Carbon::createFromFormat('Y-m-d H:i:s', $finish);
     $time = $carbon_finish->diff($carbon_start);
     return $time;
 }
 public function update(Request $request)
 {
     $rules = ['period_id' => 'required|exists:periods,id', 'name' => 'required|min:4|max:255', 'start' => 'required|date', 'end' => 'required|date'];
     $messages = ['period_id.exists' => 'El periodo indicado no existe.', 'name.required' => 'Es necesario asignar un nombre al periodo.', 'name.min' => 'Ingrese un nombre adecuado.', 'start.required' => 'Es necesario definir la fecha de inicio.', 'end.required' => 'Es necesario definir la fecha de fin.'];
     $v = Validator::make($request->all(), $rules, $messages);
     if ($v->fails()) {
         return ['success' => false, 'errors' => $v->getMessageBag()->toArray()];
     }
     // Getting the period that will be updated
     $period = Period::find($request->get('period_id'));
     $year = $period->school_year;
     // Custom validation
     $name = $request->get('name');
     $start = Carbon::createFromFormat("Y-m-d", $request->get('start'));
     $end = Carbon::createFromFormat("Y-m-d", $request->get('end'));
     if ($start < $year->start) {
         $errors['start'] = 'La fecha de inicio debe ser posterior al inicio del año lectivo.';
     }
     if ($end > $year->end) {
         $errors['end'] = 'La fecha de fin debe ser anterior al fin del año lectivo.';
     }
     if (isset($errors)) {
         return ['success' => false, 'errors' => $errors];
     }
     // Finally, saving the changes
     $period->name = $name;
     $period->start = $start;
     $period->end = $end;
     $period->save();
     return ['success' => true, 'name' => $period->name, 'start' => $period->start_format, 'end' => $period->end_format];
 }
Example #15
0
 public static function relative($string)
 {
     if (empty($string)) {
         return '';
     }
     return \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $string)->diffForHumans();
 }
Example #16
0
 public function days($startDate, $endDate)
 {
     $startDate = Carbon::createFromFormat('d/m/Y', $startDate);
     $endDate = Carbon::createFromFormat('d/m/Y', $endDate);
     $days = $startDate->diffInDays($endDate);
     return $days;
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  * @throws ImageFailedException
  * @throws \BB\Exceptions\FormValidationException
  */
 public function store()
 {
     $data = \Request::only(['user_id', 'category', 'description', 'amount', 'expense_date', 'file']);
     $this->expenseValidator->validate($data);
     if (\Input::file('file')) {
         try {
             $filePath = \Input::file('file')->getRealPath();
             $ext = \Input::file('file')->guessClientExtension();
             $mimeType = \Input::file('file')->getMimeType();
             $newFilename = \App::environment() . '/expenses/' . str_random() . '.' . $ext;
             Storage::put($newFilename, file_get_contents($filePath), 'public');
             $data['file'] = $newFilename;
         } catch (\Exception $e) {
             \Log::error($e);
             throw new ImageFailedException($e->getMessage());
         }
     }
     //Reformat from d/m/y to YYYY-MM-DD
     $data['expense_date'] = Carbon::createFromFormat('j/n/y', $data['expense_date']);
     if ($data['user_id'] != \Auth::user()->id) {
         throw new \BB\Exceptions\FormValidationException('You can only submit expenses for yourself', new \Illuminate\Support\MessageBag(['general' => 'You can only submit expenses for yourself']));
     }
     $expense = $this->expenseRepository->create($data);
     event(new NewExpenseSubmitted($expense));
     return \Response::json($expense, 201);
 }
 public function putEdit(Request $request)
 {
     if (!ACL::hasPermission('visitWellPhotos', 'edit')) {
         return redirect(route('visitWellPhotos'))->withErrors(['Você não pode editar fotos.']);
     }
     $this->validate($request, ['date' => 'required|max:10', 'title' => 'required|max:100', 'image' => 'image|mimes:jpeg,gif,png'], ['date.required' => 'Informe a data', 'date.max' => 'A data não pode passar de :max caracteres', 'title.required' => 'Informe o nome da turma ou o título da foto', 'title.max' => 'O nome da turma ou título da foto não pode passar de :max caracteres', 'image.image' => 'Envie um formato de imagem válida', 'image.mimes' => 'Formatos suportados: .jpg, .gif e .png']);
     $visitWellPhotos = VisitWellPhotos::find($request->visitWellPhotosId);
     $visitWellPhotos->date = Carbon::createFromFormat('d/m/Y', $request->date)->format('Y-m-d');
     $visitWellPhotos->title = $request->title;
     $visitWellPhotos->slug = str_slug($request->title, '-');
     if ($request->image) {
         //DELETE OLD IMAGE
         if ($request->currentImage != "") {
             if (File::exists($this->folder . $request->currentImage)) {
                 File::delete($this->folder . $request->currentImage);
             }
         }
         //IMAGE
         $extension = $request->image->getClientOriginalExtension();
         $nameImage = Carbon::now()->format('YmdHis') . "." . $extension;
         $image = Image::make($request->file('image'));
         if ($request->imageCropAreaW > 0 or $request->imageCropAreaH > 0 or $request->imagePositionX or $request->imagePositionY) {
             $image->crop($request->imageCropAreaW, $request->imageCropAreaH, $request->imagePositionX, $request->imagePositionY);
         }
         $image->resize($this->imageWidth, $this->imageHeight)->save($this->folder . $nameImage);
         $visitWellPhotos->image = $nameImage;
     }
     $visitWellPhotos->save();
     $success = "Foto editada com sucesso";
     return redirect(route('visitWellPhotos'))->with(compact('success'));
 }
Example #19
0
 public function testCopyEnsureMicrosAreCopied()
 {
     $micro = 254687;
     $dating = Carbon::createFromFormat('Y-m-d H:i:s.u', '2014-02-01 03:45:27.' . $micro);
     $dating2 = $dating->copy();
     $this->assertSame($micro, $dating2->micro);
 }
Example #20
0
 protected function processarDetalhe(array $detalhe)
 {
     $i = $this->i;
     $this->detalhe[$i] = new Detalhe($detalhe);
     $this->detalhe[$i]->numeroControle = Util::controle2array($this->rem(38, 62, $detalhe));
     $this->detalhe[$i]->numero = $this->rem(63, 70, $detalhe);
     $this->detalhe[$i]->nossoNumero = $this->rem(86, 93, $detalhe);
     $this->detalhe[$i]->nossoNumeroDigito = $this->rem(94, 94, $detalhe);
     $this->detalhe[$i]->numeroDocumento = $this->rem(117, 126, $detalhe);
     $this->detalhe[$i]->ocorrencia = $this->rem(109, 110, $detalhe);
     $this->detalhe[$i]->dataOcorrencia = $this->rem(111, 116, $detalhe);
     $this->detalhe[$i]->dataCredito = $this->rem(296, 301, $detalhe);
     $this->detalhe[$i]->dataVencimento = $this->rem(147, 152, $detalhe);
     $this->detalhe[$i]->confTituloBanco = $this->rem(127, 134, $detalhe);
     $this->detalhe[$i]->bancoCobrador = $this->rem(166, 168, $detalhe);
     $this->detalhe[$i]->agenciaCobradora = $this->rem(169, 172, $detalhe);
     $this->detalhe[$i]->agenciaCobradoraDigito = $this->rem(173, 173, $detalhe);
     $this->detalhe[$i]->especie = $this->rem(174, 175, $detalhe);
     $this->detalhe[$i]->valor = Util::nFloat($this->rem(153, 165, $detalhe) / 100);
     $this->detalhe[$i]->valorTarifa = Util::nFloat($this->rem(176, 188, $detalhe) / 100);
     $this->detalhe[$i]->valorIOF = Util::nFloat($this->rem(215, 227, $detalhe) / 100);
     $this->detalhe[$i]->valorAbatimento = Util::nFloat($this->rem(228, 240, $detalhe) / 100);
     $this->detalhe[$i]->valorDesconto = Util::nFloat($this->rem(241, 253, $detalhe) / 100);
     $this->detalhe[$i]->valorRecebido = Util::nFloat($this->rem(254, 266, $detalhe) / 100);
     $this->detalhe[$i]->valorMora = Util::nFloat($this->rem(267, 279, $detalhe) / 100);
     $this->detalhe[$i]->valorOutrosCreditos = Util::nFloat($this->rem(280, 292, $detalhe) / 100);
     $this->detalhe[$i]->valorComplementar = Util::nFloat($this->rem(312, 324, $detalhe) / 100);
     $this->detalhe[$i]->dda = $this->rem(293, 293, $detalhe);
     $this->detalhe[$i]->instrucaoCancelada = $this->rem(302, 305, $detalhe);
     $this->detalhe[$i]->dataComplementar = $this->rem(306, 311, $detalhe);
     $this->detalhe[$i]->sacadoNome = $this->rem(325, 354, $detalhe);
     $this->detalhe[$i]->motivosRejeicao = str_split($this->rem(378, 385, $detalhe), 2);
     $this->detalhe[$i]->liquidacaoCodigo = $this->rem(393, 394, $detalhe);
     $this->detalhe[$i]->liquidacaoNome = 'Desconhecido';
     $this->detalhe[$i]->ocorrenciaNome = $this->ocorrencias[$this->detalhe[$i]->get('ocorrencia', 'XX', true)];
     $this->detalhe[$i]->especieNome = $this->especies[$this->detalhe[$i]->get('especie', 'XX', true)];
     $this->detalhe[$i]->bancoCobradorNome = $this->bancos[$this->detalhe[$i]->get('bancoCobrador', 'XXX', true)];
     $this->detalhe[$i]->dataOcorrencia = $this->detalhe[$i]->get('dataOcorrencia', false, true) ? Carbon::createFromFormat('dmy', $this->detalhe[$i]->get('dataOcorrencia'))->setTime(0, 0, 0) : null;
     $this->detalhe[$i]->dataVencimento = $this->detalhe[$i]->get('dataVencimento', false, true) ? Carbon::createFromFormat('dmy', $this->detalhe[$i]->get('dataVencimento'))->setTime(0, 0, 0) : null;
     $this->detalhe[$i]->dataCredito = $this->detalhe[$i]->get('dataCredito', false, true) ? Carbon::createFromFormat('dmy', $this->detalhe[$i]->get('dataCredito'))->setTime(0, 0, 0) : null;
     $this->detalhe[$i]->dataComplementar = $this->detalhe[$i]->get('dataComplementar', false, true) ? Carbon::createFromFormat('dmy', $this->detalhe[$i]->get('dataComplementar'))->setTime(0, 0, 0) : null;
     if (in_array($this->detalhe[$i]->get('ocorrencia'), ['06', '07', '08', '10'])) {
         $this->detalhe[$i]->liquidacaoNome = $this->liquidacoes[$this->detalhe[$i]->get('liquidacaoCodigo', 'XX', true)];
         $this->totais['liquidados']++;
         $this->detalhe[$i]->setTipoOcorrencia(Detalhe::OCORRENCIA_LIQUIDADA);
     } elseif (in_array($this->detalhe[$i]->get('ocorrencia'), ['02', '64', '71', '73'])) {
         $this->totais['entradas']++;
         $this->detalhe[$i]->setTipoOcorrencia(Detalhe::OCORRENCIA_ENTRADA);
     } elseif (in_array($this->detalhe[$i]->get('ocorrencia'), ['05', '09', '32', '47', '59', '72'])) {
         $this->totais['baixados']++;
         $this->detalhe[$i]->setTipoOcorrencia(Detalhe::OCORRENCIA_BAIXADA);
     } elseif (in_array($this->detalhe[$i]->get('ocorrencia'), ['03', '15', '16', '60', '03'])) {
         $this->totais['erros']++;
         $this->detalhe[$i]->setErro('Desconhecido');
     } else {
         $this->totais['alterados']++;
         $this->detalhe[$i]->setTipoOcorrencia(Detalhe::OCORRENCIA_ALTERACAO);
     }
     $this->i++;
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $client = new Client();
     $end_point = 'http://api.serviceu.com/rest/events/occurrences?orgKey=b96cd642-acbb-4eb7-95a2-f18c0f01d5b1&format=json';
     $response = $client->get($end_point);
     $data = json_decode($response->getBody(true));
     $active_records = [];
     CalendarEvent::unguard();
     foreach ($data as $event) {
         array_push($active_records, $event->OccurrenceId);
         $record = CalendarEvent::withPast()->where('id', '=', $event->OccurrenceId)->first() ?: new CalendarEvent();
         $record->{'id'} = $event->OccurrenceId;
         $record->{'event_number'} = $event->EventId;
         $record->{'title'} = $event->Name;
         $record->{'starts_at'} = Carbon::createFromFormat('m/d/Y h:i:s A', $event->OccurrenceStartTime);
         $record->{'ends_at'} = Carbon::createFromFormat('m/d/Y h:i:s A', $event->OccurrenceEndTime);
         $record->{'location'} = $event->LocationName;
         $record->{'address'} = $event->LocationAddress;
         $record->{'address2'} = $event->LocationAddress2;
         $record->{'city'} = $event->LocationCity;
         $record->{'state'} = $event->LocationState;
         $record->{'zip'} = $event->LocationZip;
         $record->{'description'} = $event->Description;
         $record->{'contact'} = $event->ContactName;
         $record->{'contact_email'} = $event->ContactEmail;
         $record->{'contact_phone'} = $event->ContactPhone;
         $record->{'department'} = $event->DepartmentName;
         $record->save();
     }
     CalendarEvent::reguard();
     // Remove non-existing events
     CalendarEvent::withPast()->whereNotIn('id', $active_records)->delete();
     // Purge old events
     CalendarEvent::where('ends_at', '<', Carbon::now()->subMonth(2))->delete();
 }
Example #22
0
 public static function update($user)
 {
     if (!$user->can_fetch()) {
         return [];
     }
     $first_page = static::page(1, $user);
     $raw_items = $first_page->Data;
     for ($i = 2; $i <= $first_page->TotalPages; $i++) {
         $page = static::page($i, $user);
         foreach ($page->Data as $index => $item) {
             $raw_items[] = $item;
         }
     }
     $items = [];
     foreach ($raw_items as $key => $data) {
         if ($item = PastoralCare::find($data->ID)) {
             $item->type = $data->EntryType;
             $item->category = $data->Category;
             $item->description = $data->Details;
             $item->author = $data->Author;
             $item->date = Carbon::createFromFormat('d/m/Y', $data->DateOccurred)->format("Y-m-d H:i:s");
             $item->save();
         } else {
             $item = PastoralCare::updateOrCreate(array('pastoralcare_id' => $data->ID, 'type' => $data->EntryType, 'category' => $data->Category, 'description' => $data->Details, 'author' => $data->Author, 'date' => Carbon::createFromFormat('d/m/Y', $data->DateOccurred)->format("Y-m-d H:i:s")));
         }
         if (!$item->users->contains($user->user_id)) {
             $item->users()->attach($user->user_id);
         }
         $items[] = $item;
     }
     return $items;
 }
 public function createReservation(Request $request)
 {
     $room_info = $request['room_info'];
     $start_dt = Carbon::createFromFormat('d-m-Y', $request['start_dt'])->toDateString();
     $end_dt = Carbon::createFromFormat('d-m-Y', $request['end_dt'])->toDateString();
     $customer = Customer::firstOrCreate($request['customer']);
     $reservation = Reservation::create();
     $reservation->total_price = $room_info['total_price'];
     $reservation->occupancy = $request['occupancy'];
     $reservation->customer_id = $customer->id;
     $reservation->checkin = $start_dt;
     $reservation->checkout = $end_dt;
     $reservation->save();
     $date = $start_dt;
     while (strtotime($date) < strtotime($end_dt)) {
         $room_calendar = RoomCalendar::where('day', '=', $date)->where('room_type_id', '=', $room_info['id'])->first();
         $night = ReservationNight::create();
         $night->day = $date;
         $night->rate = $room_calendar->rate;
         $night->room_type_id = $room_info['id'];
         $night->reservation_id = $reservation->id;
         $room_calendar->availability--;
         $room_calendar->reservations++;
         $room_calendar->save();
         $night->save();
         $date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
     }
     $nights = $reservation->nights;
     $customer = $reservation->customer;
     return $reservation;
 }
Example #24
0
 public static function boot()
 {
     parent::boot();
     // Setup event bindings...
     Balance::saving(function ($balance) {
         $balance->user_id = Auth::id();
         return $balance;
     });
     $user_id = Auth::id();
     $balance = Balance::where('user_id', $user_id)->orderBy('id', 'DESC')->first();
     if (count($balance) > 0) {
         $date = Carbon::createFromFormat('Y-m-d H:i:s', $balance->created_at);
         if ($date->isToday()) {
             // Deixa como está.
         } else {
             // Cria o pro=imeiro registro
             $todayAmount = DB::table('transactions')->where('created_at', '>', date("Y-m-d") . " 00:00:00")->where('created_at', '<=', date('Y-m-d H:i:s'))->where('user_id', Auth::id())->where('done', 1)->sum('amount');
             $newAmount = $balance->amount + $todayAmount;
             // Cria um novo pro dia de hoje
             $balance = Balance::create(['amount' => $newAmount, 'user_id' => $user_id]);
         }
     } else {
         // Cria o pro=imeiro registro
         $amount = DB::table('transactions')->where('created_at', '<=', date('Y-m-d H:i:s'))->where('user_id', Auth::id())->where('done', 1)->sum('amount');
         $balance = Balance::create(['amount' => $amount, 'user_id' => $user_id]);
     }
 }
Example #25
0
 public function hours($startDate, $endDate)
 {
     $startDate = Carbon::createFromFormat('d/m/Y H:i', $startDate);
     $endDate = Carbon::createFromFormat('d/m/Y H:i', $endDate);
     $hours = $startDate->diffInHours($endDate);
     return $hours;
 }
Example #26
0
 public function end($formatted = false)
 {
     if ($this->end instanceof Carbon) {
         return $formatted ? $this->end->toFormattedDateString() : $this->end->toDateString();
     }
     return $formatted ? Carbon::createFromFormat('Y-m-d', $this->end)->toFormattedDateString() : $this->end;
 }
 protected function create()
 {
     $route = Helpers::routeinfo();
     /*
     		$event 			= Conference::where('slug', '=', $route->params['conference'])
     									->published()
     									->latest();
     */
     $events = Lookup::lookup('conferences', [$route->params['conference']], ['latest' => true, 'published' => true]);
     $event = $events[0];
     $options = Helpers::unserialize($event->options);
     $options['speakers'] = false;
     $options['sponsors'] = false;
     $options['partners'] = false;
     $options = Helpers::options($route, $route->params['conference']);
     $newEvent = Conference::create(['slug' => $route->params['conference'], 'conference' => $event->conference, 'city' => $event->city, 'state' => $event->state, 'start_date' => Carbon::createFromFormat('Y-m-d H:i:s', $event->start_date)->addYear(), 'end_date' => Carbon::createFromFormat('Y-m-d H:i:s', $event->end_date)->addYear(), 'timezone' => $event->timezone, 'coming' => 1, 'about' => $event->about, 'tags' => $event->tags, 'options' => Helpers::serialize($options), 'hero' => $event->hero, 'photo' => $event->photo, 'published' => Carbon::now()]);
     $newEvent = (object) $newEvent->toArray();
     $newAgendas = [];
     $agendas = Lookup::lookup('agendas', ['conference' => $event->id], ['published' => true]);
     if (is_array($agendas)) {
         foreach ($agendas as $agenda) {
             $agenda->conference_id = $newEvent->id;
             $agenda->timeslot = Carbon::createFromFormat('Y-m-d H:i:s', $agenda->timeslot)->addYear();
             $agenda->title = $agenda->type === 'breakout' || $agenda->type === 'session' ? 'Breakout Session' : ($agenda->type === 'break' ? $agenda->title : 'Keynote');
             $agenda->title_short = $agenda->type === 'breakout' || $agenda->type === 'session' ? 'Breakout Session' : ($agenda->type === 'break' ? $agenda->title : 'Keynote');
             $agenda->subtitle = null;
             $agenda->desc = null;
             $agenda->speakers = null;
             $agenda->published = Carbon::now();
             $newAgendas[] = Agenda::create((array) $agenda);
         }
     }
     $container = (object) ['event' => (object) $newEvent, 'agendas' => (object) $newAgendas];
     dd($newEvent);
 }
 /**
  * Display a listing of the resource.
  * GET /reports
  *
  * @return Response
  */
 public function index()
 {
     $reports = Report::orderBy('id', 'DESC')->get();
     echo "<pre>";
     print_r($reports);
     echo "</pre>";
     exit;
     $hoje = Carbon::now()->today();
     $ontem = Carbon::now()->yesterday();
     $anteontem = Carbon::now()->subDays(2);
     $reports->hoje = Report::where('created_at', '>=', $hoje)->orderBy('id', 'DESC')->get();
     $reports->ontem = Report::where('created_at', '=', $ontem)->orderBy('id', 'DESC')->get();
     $reports->anteontem = Report::where('created_at', '=', $anteontem)->orderBy('id', 'DESC')->get();
     $reports->anteriores = Report::where('created_at', '<', Carbon::now()->subDays(2))->orderBy('id', 'DESC')->get();
     if ($reports->hoje) {
         foreach ($reports->hoje as $report) {
             // Get HOUR:MINUTE from CREATED_AT
             $date = Carbon::createFromFormat('Y-m-d H:i:s', $report->created_at);
             $report->date = $date->hour . ':' . $date->minute;
         }
     }
     if ($reports->ontem) {
         foreach ($reports->ontem as $report) {
             // Get HOUR:MINUTE from CREATED_AT
             $date = Carbon::createFromFormat('Y-m-d H:i:s', $report->created_at);
             $report->date = $date->hour . ':' . $date->minute;
         }
     }
     return View::make('reports.index', compact('reports'));
 }
Example #29
0
 /**
  * Series constructor.
  *
  * @param $data
  */
 public function __construct($data)
 {
     $this->id = (int) $data->id;
     $this->language = (string) $data->Language;
     $this->name = (string) $data->SeriesName;
     $this->banner = (string) $data->banner;
     $this->overview = (string) $data->Overview;
     $this->firstAired = (string) $data->FirstAired !== '' ? Carbon::createFromFormat('Y-m-d', (string) $data->FirstAired)->toDateString() : null;
     $this->imdbId = (string) $data->IMDB_ID;
     if (isset($data->Actors)) {
         $this->actors = (array) TVDB::removeEmptyIndexes(explode('|', (string) $data->Actors));
     }
     $this->airsDayOfWeek = (string) $data->Airs_DayOfWeek;
     $this->airsTime = (string) $data->Airs_Time;
     $this->contentRating = (string) $data->ContentRating;
     if (isset($data->Genre)) {
         $this->genres = (array) TVDB::removeEmptyIndexes(explode('|', (string) $data->Genre));
     }
     $this->network = (string) $data->Network;
     $this->rating = (double) $data->Rating;
     $this->ratingCount = (int) $data->RatingCount;
     $this->runtime = (int) $data->Runtime;
     $this->status = (string) $data->Status;
     if (isset($data->added)) {
         //            $this->added = Carbon::createFromFormat('Y-m-d H:i:s', (string)$data->added)->toDateTimeString();
     }
     $this->fanArt = (string) $data->fanart;
     $this->lastUpdated = Carbon::createFromTimestamp((int) $data->lastupdated)->toDateTimeString();
     $this->poster = (string) $data->poster;
     $this->zap2itId = (string) $data->zap2it_id;
     if (isset($data->AliasNames)) {
         $this->aliasNames = (array) TVDB::removeEmptyIndexes(explode('|', (string) $data->AliasNames));
     }
 }
 public function project($url)
 {
     $project = Project::where('url_page', '=', $url)->get();
     $project = $project->first();
     $project->date = Carbon::createFromFormat('Y-m-d H:i:s', $project->date)->format('Y');
     return view('pages.project', compact('project'));
 }