Process stored/updated booking.

@param \Illuminate\Foundation\Http\FormRequest $request
@param \Cortex\Bookings\Models\ServiceBooking  $serviceBooking

@return int
517327
protected function process(FormRequest $request, ServiceBooking $serviceBooking): int
    {
        // Prepare required input fields
        $data = $request->validated();

        // Save booking
        $serviceBooking->fill($data)->save();

        return $serviceBooking->getKey();
    }
1035010
public function transform($events, $eventsCount, $page, $maxPerPage)
    {
        $pageCount = count($events);
        $eventsCollection = new EventCollectionObjectRepresentation(
            (int) $page,
            (int) $maxPerPage,
            (int) $numberOfPages = ceil($eventsCount/$maxPerPage),
            (int) $eventsCount,
            $this->calculateLinks($page, $numberOfPages)
        );
        foreach ($events as $event) {
            $eventsCollection->addEvent(new EventObjectRepresentation($event));
        }

        $response = new Response(
            $this->serializer->serialize(
                [
                    $eventsCollection
                ], 'xml'),
            $this->getHttpStatusCode($pageCount)
        );

        $response->headers->set('Content-type', 'text/xml');
        $response->setCharset('utf-8');

        // set infinite cache if page is complete
        if ($maxPerPage === $pageCount) {
            $response
                ->setMaxAge(60 * 60 * 24 * 365)
                ->setSharedMaxAge(60 * 60 * 24 * 365);
        }

        return $response;
    }
820238
protected function process(FormRequest $request, Service $service)
    {
        // Prepare required input fields
        $data = $request->validated();

        ! $request->hasFile('profile_picture')
        || $service->addMediaFromRequest('profile_picture')
                  ->sanitizingFileName(function ($fileName) {
                      return md5($fileName).'.'.pathinfo($fileName, PATHINFO_EXTENSION);
                  })
                  ->toMediaCollection('profile_picture', config('cortex.auth.media.disk'));

        ! $request->hasFile('cover_photo')
        || $service->addMediaFromRequest('cover_photo')
                  ->sanitizingFileName(function ($fileName) {
                      return md5($fileName).'.'.pathinfo($fileName, PATHINFO_EXTENSION);
                  })
                  ->toMediaCollection('cover_photo', config('cortex.auth.media.disk'));

        // Save service
        $service->fill($data)->save();

        [$existingRates, $newRates] = collect($data['rates'])->partition(function ($rate) {
            return isset($rate['id']);
        });

        if (array_get($data, 'rates')) {
            $service->rates()->createMany($newRates->toArray());
            app('cortex.bookings.service_rate')->findMany($existingRates->pluck('id'))->map(function (ServiceRate $rate) use ($existingRates) {
                $rate->update($existingRates->where('id', $rate->id)->first());
            });
        }

        [$existingAvailabilities, $newAvailabilities] = collect($data['availabilities'])->partition(function ($availability) {
            return isset($availability['id']);
        });

        if (array_get($data, 'availabilities')) {
            $service->availabilities()->createMany($newAvailabilities->toArray());
            app('cortex.bookings.service_availability')->findMany($existingAvailabilities->pluck('id'))->map(function (ServiceAvailability $availability) use ($existingAvailabilities) {
                $availability->update($existingAvailabilities->where('id', $availability->id)->first());
            });
        }

        return intend([
            'url' => route('adminarea.services.index'),
            'with' => ['success' => trans('cortex/foundation::messages.resource_saved', ['resource' => trans('cortex/bookings::common.service'), 'identifier' => $service->name])],
        ]);
    }
1111192
protected function form(Event $event, EventBooking $eventBooking)
    {
        $tickets = $event->tickets->pluck('name', 'id');
        $customers = app('rinvex.contacts.contact')->all()->pluck('full_name', 'id');

        return view('cortex/bookings::adminarea.pages.event_booking', compact('event', 'eventBooking', 'tickets', 'customers'));
    }
476661
public function update(Request $request, $entity, $id, $child = null, $record = null)
    {
        if (!$record && !$child && ($entityObject = Entity::fromYamlFile($entity))) {
            // Get the record from the database, or fail if it is not found
            $entityClass = $entityObject->class;
            $recordObject = $entityClass::findOrFail($id);
        } elseif (($parentEntity = Entity::fromYamlFile($entity)) && ($entityObject = Entity::fromYamlFile($child))) {
            // Get parent's record
            $parentRecord = $parentEntity->class::findOrFail($id);

            // Get the record from the database, or fail if it is not found
            $entityClass = $entityObject->class;
            $recordObject = $entityClass::findOrFail($record);
        } else {
            abort(404);
        }

        // Get validation from entity rules and validate
        $this->validate($request, $this->validationRules($entityObject->fields, true));

        // If data is validated and everything seems good, lets update the record
        foreach ($entityObject->fields as $field => $options) {
            $type = ucwords($options['type']);
            $className = 'Jaimeeee\\Panel\\Fields\\'.$type.'\\'.$type.'Field';

            if (!isset($className::$ignore) || !$className::$ignore) {
                $recordObject->$field = $request->input($field);
            }

            // Lets see if the call method exists, and if it does, we should trust the field ¯\_(ツ)_/¯
            if (method_exists($className, 'call')) {
                $className::call($request, $recordObject, $field, $options);
            }
        }

        // Edit slug
        if (isset($entityObject->slug['field']) && $entityObject->slug['field'] &&
            isset($entityObject->slug['column']) && $entityObject->slug['column']) {
            $field = $entityObject->slug['field'];
            $column = $entityObject->slug['column'];

            $recordObject->$column = str_slug($recordObject->$field,
                                            isset($entityObject->slug['separator']) ? $entityObject->slug['separator'] : '-');
        }

        $recordObject->save();

        // Upload single images
        // $this->uploadImages($request, $recordObject, $entityObject);

        if (isset($parentRecord) && $parentRecord) {
            return redirect(config('panel.url').'/'.$parentEntity->url.'/'.$parentRecord->id.'/'.$entityObject->url.'?updated=1');
        } else {
            return redirect(config('panel.url').'/'.$entityObject->url.'?updated=1');
        }
    }
398938
public function process($query, $format = null, $timeout = 6000, $pagination = true)
    {
        $this->timeout = $timeout;
        $factory = new RequestProcessorFactory();
        $processor = $factory->create(gettype($query));
        $request = $processor->convertToObjectRequest($query);
        $validation = $this->validate($request);
        if ($validation->count() === 0) {
            $result = $this->callApi($request, $format);
            $pagination_total_result_le_pagination_item_per_page = false;
            if (isset($result->pagination)) {
                if ($result->pagination->total_result <= $result->pagination->items_per_page) {
                    $pagination_total_result_le_pagination_item_per_page = true;
                }
            }
            if ($pagination !== false ||
                $pagination_total_result_le_pagination_item_per_page) {
                return $result;
            } else {
                return $this->deletePagination($request, $format, $result);
            }
        } else {
            return $validation;
        }
    }
1357487
@Transactional
    public static ServiceManagementRecord updateServiceManagementRecord(EntityManager em, ServiceManagementRecord record) {
        SystemAssert.requireArgument(em != null, "Entity manager can not be null.");
        SystemAssert.requireArgument(record != null, "ServiceManagementRecord cannot be null.");

        TypedQuery<ServiceManagementRecord> query = em.createNamedQuery("ServiceManagementRecord.findByService", ServiceManagementRecord.class);

        query.setParameter("service", record.getService());
        try {
            ServiceManagementRecord oldRecord = query.getSingleResult();

            oldRecord.setEnabled(record.isEnabled());
            return em.merge(oldRecord);
        } catch (NoResultException ex) {
            return em.merge(record);
        }
    }
63450
protected function applyBookingInfoUpdated(AbstractBookingInfoUpdated $bookingInfoUpdated)
    {
        $document = $this->loadDocumentFromRepository($bookingInfoUpdated);

        $offerLd = $document->getBody();

        $offerLd->bookingInfo = $bookingInfoUpdated->getBookingInfo()->toJsonLd();

        return $document->withBody($offerLd);
    }
549804
public function postUpdate(ModelConfigurationInterface $model, Request $request, $id)
    {
        /** @var FormInterface $editForm */
        $editForm = $model->fireEdit($id);
        $item = $editForm->getModel();

        if (is_null($item) || ! $model->isEditable($item)) {
            abort(404);
        }

        $nextAction = $request->input('next_action');

        $backUrl = $this->getBackUrl($request);

        if ($editForm instanceof FormInterface) {
            try {
                $editForm->validateForm($request, $model);

                if ($editForm->saveForm($request, $model) === false) {
                    return redirect()->back()->with([
                        '_redirectBack'       => $backUrl,
                        'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
                    ]);
                }
            } catch (ValidationException $exception) {
                return redirect()->back()
                    ->withErrors($exception->validator)
                    ->withInput()
                    ->with([
                        '_redirectBack'       => $backUrl,
                        'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
                    ]);
            }
        }

        $redirectPolicy = $model->getRedirect();

        if ($nextAction == 'save_and_continue') {
            $response = redirect()->back()->with([
                '_redirectBack'       => $backUrl,
                'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
            ]);

            if ($redirectPolicy->get('edit') == 'display') {
                $response = redirect()->to(
                    $model->getDisplayUrl()
                )->with([
                    '_redirectBack'       => $backUrl,
                    'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
                ]);
            }
        } elseif ($nextAction == 'save_and_create') {
            $response = redirect()->to($model->getCreateUrl($request->except([
                '_redirectBack',
                '_token',
                'url',
                'next_action',
            ])))->with([
                '_redirectBack'       => $backUrl,
                'sleeping_owl_tab_id' => $request->get('sleeping_owl_tab_id') ?: null,
            ]);
        } else {
            $response = redirect()->to($request->input('_redirectBack', $model->getDisplayUrl()));
        }

        return $response->with('success_message', $model->getMessageOnUpdate());
    }
1263798
function(eventData) {

    utils.doCallback('showBookingPage', eventData);

    var template = require('./templates/booking-page.html');

    var dateFormat = getConfig().ui.booking_date_format || moment.localeData().longDateFormat('LL');
    var timeFormat = getConfig().ui.booking_time_format || moment.localeData().longDateFormat('LT');
    var allocatedResource = eventData.resources ? eventData.resources[0].name : false;

    bookingPageTarget = $(template.render({
      chosenDate:               formatTimestamp(eventData.start, dateFormat),
      chosenTime:               formatTimestamp(eventData.start, timeFormat) + ' - ' + formatTimestamp(eventData.end, timeFormat),
      allocatedResourcePrefix:  getConfig().ui.localization.allocated_resource_prefix,
      allocatedResource:        allocatedResource,
      closeIcon:                require('!svg-inline!./assets/close-icon.svg'),
      checkmarkIcon:            require('!svg-inline!./assets/checkmark-icon.svg'),
      loadingIcon:              require('!svg-inline!./assets/loading-spinner.svg'),
      errorIcon:                require('!svg-inline!./assets/error-icon.svg'),
      submitText:               getConfig().ui.localization.submit_button,
      successMessage:           interpolate.sprintf(getConfig().ui.localization.success_message, '<span class="booked-email"></span>')
    }));

    var formFields = bookingPageTarget.find('.bookingjs-form-fields');
    $(formFields).append(renderCustomerFields());
    
    var form = bookingPageTarget.children('.bookingjs-form');

    bookingPageTarget.children('.bookingjs-bookpage-close').click(function(e) {
      e.preventDefault();
      var bookingHasBeenCreated = $(form).hasClass('success');
      if (bookingHasBeenCreated) getAvailability();
      hideBookingPage();
    });

    if (eventData.resources) {
      utils.logDebug(['Available resources for chosen timeslot:', eventData.resources]);
    }

    form.find('.bookingjs-form-input').on('input', function() {
      var field = $(this).closest('.bookingjs-form-field');
      if (this.value) field.addClass('bookingjs-form-field--dirty');
      else field.removeClass('bookingjs-form-field--dirty');
    });

    form.submit(function(e) {
      submitBookingForm(this, e, eventData);
    });

    $(rootTarget).on('customer-timezone-changed', function () {
      if (!bookingPageTarget) return
      $('.bookingjs-bookpage-date').text(formatTimestamp(eventData.start, dateFormat));
      $('.bookingjs-bookpage-time').text(formatTimestamp(eventData.start, timeFormat) + ' - ' + formatTimestamp(eventData.end, timeFormat));
    });

    $(document).on('keyup', function(e) {
      // escape key maps to keycode `27`
      if (e.keyCode === 27) { hideBookingPage(); }
    });

    rootTarget.append(bookingPageTarget);

    setTimeout(function(){
      bookingPageTarget.addClass('show');
    }, 100);

  }
765666
private function persistDocument(Request $request, $formType, $document, $language)
    {
        $data = $request->request->all();

        if ($request->query->has('parentId')) {
            $data['parent'] = $request->query->get('parentId');
        }

        $form = $this->createForm(
            $formType,
            $document,
            [
                // disable csrf protection, since we can't produce a token, because the form is cached on the client
                'csrf_protection' => false,
                'webspace_key' => $this->getWebspace($request),
            ]
        );
        $form->submit($data, false);

        if (array_key_exists('author', $data) && null === $data['author']) {
            $document->setAuthor(null);
        }

        if (!$form->isValid()) {
            throw new InvalidFormException($form);
        }

        $this->getDocumentManager()->persist(
            $document,
            $language,
            [
                'user' => $this->getUser()->getId(),
                'clear_missing_content' => false,
            ]
        );
    }
533360
public function transferir(
        Request $request,
        AtendimentoService $atendimentoService,
        ServicoService $servicoService,
        Atendimento $atendimento,
        TranslatorInterface $translator
    ) {
        $envelope = new Envelope();
        
        $usuario = $this->getUser();
        $unidade = $usuario->getLotacao()->getUnidade();

        $this->checkAtendimento($unidade, $atendimento, $translator);

        $data = json_decode($request->getContent(), true);

        $transferirForm = $this->createTransferirForm($request, $servicoService);
        $transferirForm->submit($data);

        if (!$transferirForm->isValid()) {
            throw new Exception($translator->trans('error.invalid_form', [], self::DOMAIN));
        }
        
        $servicoUnidade = $transferirForm->get('servico')->getData();
        $prioridade     = $transferirForm->get('prioridade')->getData();

        $atendimentoService->transferir(
            $atendimento,
            $unidade,
            $servicoUnidade->getServico(),
            $prioridade
        );

        return $this->json($envelope);
    }
64724
protected function handlePaginationRequest($request, $model, $total = null)
    {
        $page = $request->pageNumber;
        $perPage = $request->pageSize;
        if (!$total) {
            $total = $model->count();
        }
        $results = $model->forPage($page, $perPage)->get(array('*'));
        $paginator = new LengthAwarePaginator($results, $total, $perPage, $page, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => 'page[number]'
        ]);
        $paginator->appends('page[size]', $perPage);
        if (!empty($request->filter)) {
            foreach ($request->filter as $key=>$value) {
                $paginator->appends($key, $value);
            }
        }
        if (!empty($request->sort)) {
            $paginator->appends('sort', implode(',', $request->sort));
        }

        return $paginator;
    }
1085655
public function process(FormInterface $form, Request $request)
    {
        if ($request->isMethod('POST')) {
            $form->submit($request);
            if ($form->isValid()) {
                $this->bannerManager->add($form->getData());

                return true;
            }
        }

        return false;
    }
1271250
protected function callRaw(ServiceRequestInterface $request)
    {
        $url = rtrim($request->getLocation(), '/') . '/' . $request->getMethod();

        $httpMethod = $this->determineHttpMethod($request);

        $options = $this->prepareGuzzleOptions($request, $httpMethod);

        $this->beforeGuzzleCall($options);

        try {

            $response = $this->client->request($httpMethod, $url, $options);

        } catch (Exception $e) {

            // throw as CouldNotConnect if it is a guzzle error
            // or rethrow if unexpected

            if ($this->isGuzzleException($e)) {

                throw new CouldNotConnectException($e->getMessage(), $e->getCode(), $e);
            }

            throw $e;
        }

        $this->afterGuzzleCall($response);

        $this->responseInformation->setStatusCode( $response->getStatusCode() );
        $this->responseInformation->setMessage( $response->getReasonPhrase() );
        $this->responseInformation->setHeaders( $response->getHeaders() );

        $responseBody = $response->getBody()->getContents();

        event(
            new RestCallCompleted(
                $url,
                isset($options['form_params'])
                    ?   $options['form_params']
                    :   (isset($options['query'])
                            ?   $options['query']
                            :   []),
                ($this->sendResponseToEvent) ? $responseBody : null
            )
        );

        return $responseBody;
    }
350349
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        /* @var ValidatorInterface $validator */
        $serviceHandler = $request->getAttribute(RouterMiddleware::ATTRIBUTE);
        $serviceData    = $request->getAttribute(PackerMiddleware::ATTRIBUTE_DATA);
        $validator      = App::getBean(ServiceValidator::class);

        list($className, $validatorKey) = $serviceHandler;
        $collector = ValidatorCollector::getCollector();
        if (isset($collector[$className][$validatorKey]['validator'])) {
            $validators = $collector[$className][$validatorKey]['validator'];
            $validator->validate($validators, $serviceHandler, $serviceData);
        }

        return $handler->handle($request);
    }
74956
public function update($menu = null, $model, FormRequest $request)
    {
        $data = $request->all();
        $data['parent_id'] = $data['parent_id'] ?: null;
        $data['page_id'] = $data['page_id'] ?: null;
        $this->repository->update($data);

        return $this->redirect($request, $model);
    }