* Summit Registration Model/Endpoints

Doc

https://docs.google.com/document/d/1gOAceevwutF3QHYWD0_6aESQMZEiIz3YVBVXlyUuRy8

* Summit Registration External Feed

https://docs.google.com/document/d/1_2QZUK--A350jxh2USKBtVtisKrrcUcVjdKnbcZ7-4M/edit#

* Multi Stripe Config

* Added stripe payment configuration per summit
* Added webhook automatic creation
* Added CRUD endpoints for payment profiles per summit

GET api/v1/summits/{id}/payment-gateway-profiles

filters

active ['==']
application_type ['=@', '==']

scopes

summits/read/all
summits/payment-gateway-profiles/read

POST  api/v1/summits/{id}/payment-gateway-profiles

payload

'active'               => 'sometimes|boolean',
'application_type'     => 'sometimes|string|in:Registration,BookableRooms'
'provider'             => 'required|string|in:Stripe',
'test_mode_enabled'    => 'required|boolean',
'live_secret_key'      => 'sometimes|string',
'live_publishable_key' => 'required_with:live_secret_key|string',
'test_secret_key'      => 'sometimes|string',
'test_publishable_key' => 'required_with:test_secret_key|string'

scopes

summits/write
summits/payment-gateway-profiles/write

GET  api/v1/summits/{id}/payment-gateway-profiles/{payment_profile_id}

scopes

summits/read/all
summits/payment-gateway-profiles/read

PUT api/v1/summits/{id}/payment-gateway-profiles/{payment_profile_id}

payload

'active'               => 'sometimes|boolean',
'application_type'     => 'sometimes|string|in:Registration,BookableRooms'
'provider'             => 'required|string|in:Stripe',
'test_mode_enabled'    => 'required|boolean',
'live_secret_key'      => 'sometimes|string',
'live_publishable_key' => 'required_with:live_secret_key|string',
'test_secret_key'      => 'sometimes|string',
'test_publishable_key' => 'required_with:test_secret_key|string'

scopes

summits/payment-gateway-profiles/write
summits/write

DELETE api/v1/summits/{id}/payment-gateway-profiles/{payment_profile_id}

scopes

summits/payment-gateway-profiles/write
summits/write

Stripe Webhooks

default webhook

(SECRET set per application under .env, should be created previously on stripe default account)

POST api/public/v1/summits/all/payments/{application_name}/confirm

where application_name could be Registration or BookableRooms

otherwise if a stripe account is set per summit, when the profile gets activated
a webhook will be automatically be created using following url

POST api/public/v1/summits/{id}/payments/{application_name}/confirm

* Email API Integration

* moved all blade templates to mail api ( DB Seeding)
* defined email events flows per summmit
* created endpoint to set up templates per email events on each flow

PUT /api/v1/summits/{id}/email-flows-events/{event_id}

payload

email_template_identifier: string

* added endpoint to get all email events per summit

GET /api/v1/summits/{id}/email-flows-events

* added endpoint to get email event per summit/id

GET /api/v1/summits/{id}/email-flows-events/{event_id}

Summit Documents endpoints

add summit document

POST /api/v1/summits/{id}/summit-documents

payload

file (mandatory|file stream)
label ( mandatory|string)
name ( mandatory|string)
description (optional|string)

get all summit documents

GET /api/v1/summits/{id}/summit-documents

get by id

GET /api/v1/summits/{id}/summit-documents/{document_id}

update

PUT GET /api/v1/summits/{id}/summit-documents/{document_id}

file (optional|file stream)
label (optional|string)
name (optional|string)
description (optional|string)

delete

DELETE GET /api/v1/summits/{id}/summit-documents/{document_id}

add event type to doc

PUT /api/v1/summits/{id}/summit-documents/{document_id}/event-types/{event_type_id}

delete event type from doc

DELETE /api/v1/summits/{id}/summit-documents/{document_id}/event-types/{event_type_id}

add document to event type

PUT /api/v1/summits/{id}/event-types/{event_type_id}/summit-documents/{document_id}

delete document from event type

DELETE /api/v1/summits/{id}/event-types/{event_type_id}/summit-documents/{document_id}

Updated Summit events to support streaming url, meeting_url and etherpad link

* Summit Registration - Invite only

Summit Administrator Permission Groups

GET /api/v1/summit-administrator-groups

filter

* title
* member_first_name
* member_last_name
* member_full_name
* member_email
* summit_id
* member_id

ordering

id
title

scopes

%s/summit-administrator-groups/read

/api/v1/summit-administrator-groups/{group_id}

scopes

%s/summit-administrator-groups/read

POST /api/v1/summit-administrator-groups

title
summits
members

scopes

%s/summit-administrator-groups/write

PUT /api/v1/summit-administrator-groups/{group_id}

title
summits
members

scopes

%s/summit-administrator-groups/write

DELETE /api/v1/summit-administrator-groups/{group_id}

scopes

%s/summit-administrator-groups/write

PUT /api/v1/summit-administrator-groups/{group_id}/members/{member_id}

DELETE /api/v1/summit-administrator-groups/{group_id}/members/{member_id}

PUT /api/v1/summit-administrator-groups/{group_id}/summits/{summit_id}

DELETE /api/v1/summit-administrator-groups/{group_id}/summits/{summit_id}

Room Metrics

PUT /api/v1/summits/{id}/members/{member_id}/schedule/{event_id}/enter

Scopes

%s/me/summits/events/enter

PUT /api/v1/summits/{id}/members/{member_id}/schedule/{event_id}/leave

%s/me/summits/events/leave

update summit_event serializer

new fields

total_attendance_count
current_attendance_count
attendance
current_attendance

Added new Speakers Endpoints

GET /api/v1/summits/{id}/speakers/on-schedule

retrieves all speakers on summit schedule

filters

'first_name' => ['=@', '=='],
'last_name'  => ['=@', '=='],
'email'      => ['=@', '=='],
'id'         => ['=='],
'full_name'  => ['=@', '=='],
'start_date' => ['>', '<', '<=', '>=', '=='],
'end_date'   => ['>', '<', '<=', '>=', '=='],

Summit Events Image

POST /api/v1/summits/{id}/events/{event_id}/image
DELETE /api/v1/summits/{id}/events/{event_id}/image

Speakers Image Big Pic

POST /api/v1/speakers/{speaker_id}/big-photo
DELETE /api/v1/speakers/{speaker_id}/big-photo

CFP - multiple summits

Presentation Materials - Media Uploads

New Endpoints

GET api/v1/summit-media-file-types

filter
'name' => ['=@', '==']

order

id, name

POST api/v1/summit-media-file-types

payload

'name'  => 'required|string|max:255',
'description'  => 'sometimes|string|max:255',
'allowed_extensions' => 'required|string_array',

GET api/v1/summit-media-file-types/{id}

PUT api/v1/summit-media-file-types/{id}

payload

'name'  => 'sometimes|string|max:255',
'description'  => 'sometimes|string|max:255',
'allowed_extensions' => 'required|string_array',

DELETE api/v1/summit-media-file-types/{id}

GET api/v1/summits/{id}/media-upload-types

POST

payload

'name' => 'required|string|max:255',
'description' => 'sometimes|string|max:255',
'is_mandatory' => 'required|boolean',
'max_size' => 'required|int|megabyte_aligned',
'private_storage_type' => 'required|string|in:None,DropBox,Swift,Local',
'public_storage_type' => 'required|string|in:None,DropBox,Swift,Local'
'type_id' => 'required|int',
'presentation_types' => 'sometimes|int_array',

GET api/v1/summits/{id}/media-upload-types/{media_upload_type_id}

PUT api/v1/summits/{id}/media-upload-types/{media_upload_type_id}

payload

'name' => 'sometimes|string|max:255',
'description' => 'sometimes|string|max:255',
'is_mandatory' => 'sometimes|boolean',
'max_size' => 'sometimes|int|megabyte_aligned',
'private_storage_type' => 'sometimes|string|in:None,DropBox,Swift,Local',
'public_storage_type' => 'sometimes|string|in:None,DropBox,Swift,Local'
'type_id' => 'sometimes|int',
'presentation_types' => 'sometimes|int_array',

DELETE api/v1/summits/{id}/media-upload-types/{media_upload_type_id}

PUT api/v1/summits/{id}/media-upload-types/{media_upload_type_id}/presentation-types/{event_type_id}

DELETE api/v1/summits/{id}/media-upload-types/{media_upload_type_id}/presentation-types/{event_type_id}

GET api/v1/summits/{id}/presentations/{presentation_id}/media-uploads

POST api/v1/summits/{id}/presentations/{presentation_id}/media-uploads

payload multiform

file

media_upload_type_id

GET api/v1/summits/{id}/presentations/{presentation_id}/media-uploads/{media_upload_id}

PUT api/v1/summits/{id}/presentations/{presentation_id}/media-uploads/{media_upload_id}

payload multiform

file

DELETE api/v1/summits/{id}/presentations/{presentation_id}/media-uploads/{media_upload_id}

POST /api/v1/summits/{id}/media-upload-types/all/clone/{to_summit_id}

Summit Invitation Only endpoints V2

CRUD invitations

Change-Id: Ia23c247a59c3810f2a738265efdd890fe6f59dfb
Signed-off-by: smarcet <smarcet@gmail.com>
This commit is contained in:
smarcet 2019-07-30 00:16:56 -03:00
parent 688b8fad1c
commit 39e3c8e333
692 changed files with 65145 additions and 8256 deletions

View File

@ -1,5 +1,6 @@
APP_ENV=local
APP_DEBUG=true
APP_DEBUG_EMAIL=
APP_KEY=SomeRandomString
APP_URL=http://localhost
APP_SCOPE_BASE_REALM=http://localhost
@ -28,7 +29,9 @@ SESSION_DRIVER=redis
SESSION_COOKIE_DOMAIN=
SESSION_COOKIE_SECURE=false
QUEUE_DRIVER=sync
QUEUE_DRIVER=database
QUEUE_CONN=
QUEUE_DATABASE=
MAIL_DRIVER=sendgrid
SENDGRID_API_KEY='YOUR_SENDGRID_API_KEY'
@ -51,7 +54,7 @@ API_RESPONSE_CACHE_LIFETIME=600
LOG_EMAIL_TO=smarcet@gmail.com
LOG_EMAIL_FROM=smarcet@gmail.com
LOG_LEVEL=info
LOG_LEVEL=debug
EVENTBRITE_OAUTH2_PERSONAL_TOKEN=
SS_ENCRYPT_KEY=
@ -69,15 +72,99 @@ SCP_REMOTE_BASE_PATH=/tmp
GOOGLE_GEO_CODING_API_KEY=
# swift configuration
CLOUD_STORAGE_BASE_URL=
CLOUD_STORAGE_ASSETS_CONTAINER=
CLOUD_STORAGE_IMAGES_CONTAINER=
CLOUD_STORAGE_AUTH_URL=
CLOUD_STORAGE_USERNAME=
CLOUD_STORAGE_APIKEY=
CLOUD_STORAGE_PROJECT_NAME=
CLOUD_STORAGE_REGION=
CLOUD_STORAGE_ASSETS_CONTAINER=
CLOUD_STORAGE_IMAGES_CONTAINER=
CLOUD_STORAGE_MEDIA_UPLOADS_CONTAINER=
# enable/disable cal sync background task
ENABLE_CAL_SYNC=true
# enable/disable bookable rooms reservation revocation task
ENABLE_BOOKABLE_ROOMS_RESERVATION_REVOCATION=false
ENABLE_BOOKABLE_ROOMS_RESERVATION_REVOCATION=false
MAIL_FROM_NAME=
MAIL_FROM_EMAIL=
#stripe
STRIPE_BOOKING_PRIVATE_KEY=
STRIPE_BOOKING_ENDPOINT_SECRET=
STRIPE_REGISTRATION_PRIVATE_KEY=
STRIPE_REGISTRATION_ENDPOINT_SECRET=
#registration
REGISTRATION_SERVICE_OAUTH2_CLIENT_ID=
REGISTRATION_SERVICE_OAUTH2_CLIENT_SECRET=
REGISTRATION_SERVICE_OAUTH2_SCOPES=
REGISTRATION_DASHBOARD_OAUTH2_CLIENT_ID=
REGISTRATION_FROM_EMAIL=
REGISTRATION_DASHBOARD_BASE_URL=
REGISTRATION_DASHBOARD_BACK_URL=%s/a/orders
REGISTRATION_DASHBOARD_INVITATION_FORM_URL=%s/a/invitations/%s
REGISTRATION_DASHBOARD_ATTENDEE_EDIT_FORM_URL=%s/a/guests/%s
REGISTRATION_REMINDER_EMAIL_DAYS_INTERVAL=7
REGISTRATION_SUPPORT_EMAIL=
#IDP
# CHECK /.well-known/openid-configuration at idp
IDP_BASE_URI=
IDP_AUTHORIZATION_ENDPOINT=
IDP_TOKEN_ENDPOINT=
IDP_INTROSPECTION_ENDPOINT=
IDP_USERINFO_ENDPOINT=
REGISTRATION_VALIDATE_TICKET_TYPE_REMOVAL=true
# default stripe config
# if not set at summit level this will be used ( if set by default)
# *_WEBHOOK_SECRET variables should be populated by manually created webhooks at set stripe account
# and should be pointed to $API_BASE_URL/api/public/v1/summits/all/payments/Registration/confirm
# and set to attended following events types
# * payment_intent.payment_failed
# payment_intent.succeeded
REGISTRATION_DEFAULT_PAYMENT_PROVIDER=Stripe
REGISTRATION_DEFAULT_STRIPE_TEST_MODE=
REGISTRATION_DEFAULT_LIVE_STRIPE_PRIVATE_KEY=
REGISTRATION_DEFAULT_LIVE_STRIPE_PUBLISHABLE_KEY=
REGISTRATION_DEFAULT_LIVE_WEBHOOK_SECRET=
REGISTRATION_DEFAULT_TEST_STRIPE_PRIVATE_KEY=
REGISTRATION_DEFAULT_TEST_STRIPE_PUBLISHABLE_KEY=
REGISTRATION_DEFAULT_TEST_WEBHOOK_SECRET=
BOOKABLE_ROOMS_DEFAULT_PAYMENT_PROVIDER=Stripe
BOOKABLE_ROOMS_DEFAULT_STRIPE_TEST_MODE=
BOOKABLE_ROOMS_DEFAULT_LIVE_STRIPE_PRIVATE_KEY=
BOOKABLE_ROOMS_DEFAULT_LIVE_STRIPE_PUBLISHABLE_KEY=
BOOKABLE_ROOMS_DEFAULT_LIVE_WEBHOOK_SECRET=
BOOKABLE_ROOMS_DEFAULT_TEST_STRIPE_PRIVATE_KEY=
BOOKABLE_ROOMS_DEFAULT_TEST_STRIPE_PUBLISHABLE_KEY=
BOOKABLE_ROOMS_DEFAULT_TEST_WEBHOOK_SECRET=
MAIL_API_BASE_URL=
MAIL_API_OAUTH2_CLIENT_ID=
MAIL_API_OAUTH2_CLIENT_SECRET=
MAIL_API_OAUTH2_CLIENT_SCOPES=
CFP_APP_BASE_URL=
CFP_SUPPORT_EMAIL=
## RABBIT MQ
RABBITMQ_EXCHANGE_NAME=databus-exchange
RABBITMQ_HOST=
RABBITMQ_PORT=5671
RABBITMQ_VHOST=databus
RABBITMQ_LOGIN=admin
RABBITMQ_PASSWORD=1qaz2wsx
RABBITMQ_QUEUE=default
RABBITMQ_SSL=true
RABBITMQ_SSL_CAFILE=/certs/rabbit/ca-osf.pem
RABBITMQ_SSL_LOCALCERT=/certs/rabbit/client-cert-osf.pem
RABBITMQ_SSL_LOCALKEY=/certs/rabbit/client-key-osf.pem
RABBITMQ_SSL_VERIFY_PEER=false
DROPBOX_ACCESS_TOKEN=

1
.gitignore vendored
View File

@ -27,3 +27,4 @@ storage/*
routes.txt
/storage/logs/
/ss.sql
phpunit.xml

View File

@ -11,6 +11,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Support\Facades\Log;
use libs\utils\JsonUtils;
use models\oauth2\IResourceServerContext;
use models\utils\IEntity;
@ -123,7 +125,7 @@ abstract class AbstractSerializer implements IModelSerializer
return array_merge(array($class_name), $parents);
}
const BoolType = 'json_boolean';
const BoolType = 'json_boolean';
const EpochType = 'datetime_epoch';
const StringType = 'json_string';
const IntType = 'json_int';
@ -191,40 +193,40 @@ abstract class AbstractSerializer implements IModelSerializer
switch(strtolower($mapping[1]))
{
case 'datetime_epoch':
{
if(!is_null($value)) {
$value = $value->getTimestamp();
}
{
if(!is_null($value)) {
$value = $value->getTimestamp();
}
}
break;
case 'json_string':
{
$value = JsonUtils::toJsonString($value);
}
{
$value = JsonUtils::toJsonString($value);
}
break;
case 'json_boolean':
{
$value = JsonUtils::toJsonBoolean($value);
}
{
$value = JsonUtils::toJsonBoolean($value);
}
break;
case 'json_int':
{
$value = JsonUtils::toJsonInt($value);
}
{
$value = JsonUtils::toJsonInt($value);
}
break;
case 'json_float':
{
$value = JsonUtils::toJsonFloat($value);
}
{
$value = JsonUtils::toJsonFloat($value);
}
break;
case 'json_obfuscated_email':
{
$value = JsonUtils::toObfuscatedEmail($value);
}
{
$value = JsonUtils::toObfuscatedEmail($value);
}
case 'json_url':{
$value = JsonUtils::encodeUrl($value);
}
break;
break;
}
}
$new_values[$mapping[0]] = $value;
@ -259,12 +261,16 @@ abstract class AbstractSerializer implements IModelSerializer
* @param string $expand
* @return string
*/
protected static function getExpandForPrefix(string $prefix, string $expand):string{
protected static function getExpandForPrefix(string $prefix, string $expand):string {
Log::debug(sprintf("AbstractSerializer::getExpandForPrefix prefix %s expand %s", $prefix, $expand));
$prefix_expand = [];
foreach(explode(',', $expand) as $e){
if(strstr($e, $prefix.".")!==false)
$prefix_expand[] = str_replace($prefix.".","", $e);
}
return implode(',', $prefix_expand);
}
}

View File

@ -86,7 +86,7 @@ abstract class JsonUtils
public static function toJsonFloat($value)
{
if(empty($value)) return 0.00;
return floatval(number_format(floatval($value),2));
return floatval($value);
}
/**

View File

@ -0,0 +1,84 @@
<?php namespace App\Console\Commands;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Services\Model\ISummitOrderService;
use Illuminate\Support\Facades\Config;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Exception;
/**
* Class RegistrationSummitOrderReminderEmailCommand
* @package App\Console\Commands
*/
class RegistrationSummitOrderReminderEmailCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'summit:registration-order-reminder-action-email';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'summit:registration-order-reminder-action-email';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Process all Order without Action';
/**
* @var ISummitOrderService
*/
private $order_service;
/**
* RegistrationSummitOrderRevocationCommand constructor.
* @param ISummitOrderService $order_service
*/
public function __construct(ISummitOrderService $order_service)
{
parent::__construct();
$this->order_service = $order_service;
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
try {
$this->info("processing summit orders without action");
$start = time();
Log::debug("RegistrationSummitOrderReminderEmailCommand::handle");
$this->order_service->processAllOrderReminder();
$end = time();
$delta = $end - $start;
$this->info(sprintf("execution call %s seconds", $delta));
}
catch (Exception $ex) {
Log::error($ex);
}
}
}

View File

@ -0,0 +1,102 @@
<?php namespace App\Console\Commands;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Services\Model\ISummitOrderService;
use Illuminate\Support\Facades\Config;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Exception;
/**
* Class RegistrationSummitOrderRevocationCommand
* @package App\Console\Commands
*/
class RegistrationSummitOrderRevocationCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'summit:order-reservation-revocation';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'summit:order-reservation-revocation';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Revokes all reserved orders after N minutes without action';
/**
* @var ISummitOrderService
*/
private $order_service;
/**
* RegistrationSummitOrderRevocationCommand constructor.
* @param ISummitOrderService $order_service
*/
public function __construct(ISummitOrderService $order_service)
{
parent::__construct();
$this->order_service = $order_service;
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$enabled = Config::get("registration.enable_orders_reservation_revocation", true);
if (!$enabled) {
$this->info("task is not enabled!");
return false;
}
try {
$this->info("processing summit orders reservations");
$start = time();
$lifetime = intval(Config::get("registration.reservation_lifetime", 30));
Log::info(sprintf("RegistrationSummitOrderRevocationCommand: using lifetime of %s ", $lifetime));
Log::info("RegistrationSummitOrderRevocationCommand: invoking revokeReservedOrdersOlderThanNMinutes");
$this->order_service->revokeReservedOrdersOlderThanNMinutes($lifetime);
$end = time();
$delta = $end - $start;
$this->info(sprintf("execution call %s seconds", $delta));
$start = time();
Log::info("RegistrationSummitOrderRevocationCommand: invoking confirmOrdersOlderThanNMinutes");
$this->order_service->confirmOrdersOlderThanNMinutes($lifetime);
$end = time();
$delta = $end - $start;
$this->info(sprintf("execution call %s seconds", $delta));
} catch (Exception $ex) {
Log::error($ex);
}
}
}

View File

@ -0,0 +1,98 @@
<?php namespace App\Console\Commands;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use services\model\ISummitService;
use Exception;
/**
* Class SummitForwardXDays
* @package App\Console\Commands
*/
class SummitForwardXDays extends Command
{
/**
* @var ISummitService
*/
private $service;
/**
* The console command name.
*
* @var string
*/
protected $name = 'summit:forward-x-days';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'summit:forward-x-days {summit_id} {days} {--negative} {--check-ended}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Advance a summit forward by x days';
/**
* @var ISummitService
*/
private $summit_service;
/**
* SummitEventSetAvgRateProcessor constructor.
* @param ISummitService $summit_service
*/
public function __construct(ISummitService $summit_service)
{
parent::__construct();
$this->summit_service = $summit_service;
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
try {
$summit_id = $this->argument('summit_id');
if(empty($summit_id))
throw new \InvalidArgumentException("summit_id is required");
$days = $this->argument('days');
if(empty($days))
throw new \InvalidArgumentException("days is required");
$negative = $this->option('negative');
$check_summit_ends = $this->option('check-ended');
$this->info("processing SummitForwardXDays");
$start = time();
$days = intval($days);
$this->summit_service->advanceSummit(intval($summit_id), $days, $negative, $check_summit_ends);
$end = time();
$delta = $end - $start;
$this->info(sprintf("execution call %s seconds", $delta));
}
catch (Exception $ex) {
Log::warning($ex);
}
}
}

View File

@ -11,15 +11,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Repositories\ISummitRoomReservationRepository;
use App\Services\Model\ILocationService;
use Illuminate\Support\Facades\Log;
use libs\utils\ITransactionService;
use models\summit\SummitRoomReservation;
use models\utils\SilverstripeBaseModel;
use utils\Filter;
use utils\FilterElement;
use utils\PagingInfo;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Exception;

View File

@ -11,10 +11,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Console\Commands\SummitEventSetAvgRateProcessor;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\App;
use models\summit\CalendarSync\CalendarSyncInfo;
/**
* Class Kernel
@ -37,6 +36,9 @@ class Kernel extends ConsoleKernel
\App\Console\Commands\SummitRoomReservationRevocationCommand::class,
\App\Console\Commands\ExternalScheduleFeedIngestionCommand::class,
\App\Console\Commands\SummitEventSetAvgRateProcessor::class,
\App\Console\Commands\RegistrationSummitOrderRevocationCommand::class,
\App\Console\Commands\RegistrationSummitOrderReminderEmailCommand::class,
\App\Console\Commands\SummitForwardXDays::class,
];
/**
@ -49,6 +51,8 @@ class Kernel extends ConsoleKernel
{
// regenerate available summits cache
$env = App::environment();
$schedule->command('summit:json-generator')->everyFiveMinutes()->withoutOverlapping();
// list of available summits
@ -79,5 +83,18 @@ class Kernel extends ConsoleKernel
// AVG schedule feedback rate
$schedule->command("summit:feedback-avg-rate-processor")->everyFifteenMinutes()->withoutOverlapping();
// registration orders
$schedule->command('summit:order-reservation-revocation')->everyFiveMinutes()->withoutOverlapping();
// reminder emails
$schedule->command('summit:registration-order-reminder-action-email')->everyThirtyMinutes()->timezone(new \DateTimeZone('UTC'))->withoutOverlapping();
// production YOCO (13) advance AT 0700 AM ( 12:00 AM PST)
if ($env == 'production') {
$schedule->command("summit:forward-x-days", [13, 2, '--check-ended'])->dailyAt("07:00")->timezone('UTC')->withoutOverlapping();
}
}
}

45
app/Events/NewMember.php Normal file
View File

@ -0,0 +1,45 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Queue\SerializesModels;
/**
* Class NewMember
* @package App\Events
*/
final class NewMember
{
use SerializesModels;
/**
* @var int
*/
private $member_id;
/**
* NewMember constructor.
* @param int $member_id
*/
public function __construct(int $member_id)
{
$this->member_id = $member_id;
}
/**
* @return int
*/
public function getMemberId(): int
{
return $this->member_id;
}
}

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class CreatedSummitRegistrationOrder
* @package App\Events
*/
final class CreatedSummitRegistrationOrder extends SummitRegistrationOrderAction
{
}

View File

@ -0,0 +1,76 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class OrderDeleted
* @package App\Events
*/
class OrderDeleted extends SummitRegistrationOrderAction
{
/**
* @var array
*/
private $tickets_to_return;
/**
* @var array
*/
private $promo_codes_to_return;
/**
* @var int
*/
private $summit_id;
/**
* OrderDeleted constructor.
* @param int $order_id
* @param int $summit_id
* @param array $tickets_to_return
* @param array $promo_codes_to_return
*/
public function __construct(int $order_id, int $summit_id, array $tickets_to_return, array $promo_codes_to_return)
{
parent::__construct($order_id);
$this->summit_id = $summit_id;
$this->tickets_to_return = $tickets_to_return;
$this->promo_codes_to_return = $promo_codes_to_return;
}
/**
* @return array
*/
public function getTicketsToReturn(): array
{
return $this->tickets_to_return;
}
/**
* @return array
*/
public function getPromoCodesToReturn(): array
{
return $this->promo_codes_to_return;
}
/**
* @return int
*/
public function getSummitId(): int
{
return $this->summit_id;
}
}

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class PaymentSummitRegistrationOrderConfirmed
* @package App\Events
*/
final class PaymentSummitRegistrationOrderConfirmed extends SummitRegistrationOrderAction
{
}

View File

@ -0,0 +1,45 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class RequestedSummitAttendeeTicketRefund
* @package App\Events
*/
class RequestedSummitAttendeeTicketRefund extends SummitAttendeeTicketAction
{
/**
* @var int
*/
private $days_before_event_starts;
/**
* RequestedSummitAttendeeTicketRefund constructor.
* @param int $order_id
* @param int $days_before_event_starts
*/
public function __construct(int $order_id, int $days_before_event_starts)
{
parent::__construct($order_id);
$this->days_before_event_starts = $days_before_event_starts;
}
/**
* @return int
*/
public function getDaysBeforeEventStarts(): int
{
return $this->days_before_event_starts;
}
}

View File

@ -0,0 +1,45 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class RequestedSummitOrderRefund
* @package App\Events
*/
final class RequestedSummitOrderRefund extends SummitRegistrationOrderAction
{
/**
* @var int
*/
private $days_before_event_starts;
/**
* RequestedSummitOrderRefund constructor.
* @param int $order_id
* @param int $days_before_event_starts
*/
public function __construct(int $order_id, int $days_before_event_starts)
{
parent::__construct($order_id);
$this->days_before_event_starts = $days_before_event_starts;
}
/**
* @return int
*/
public function getDaysBeforeEventStarts(): int
{
return $this->days_before_event_starts;
}
}

View File

@ -0,0 +1,44 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Queue\SerializesModels;
/**
* Class SummitAttendeeTicketAction
* @package App\Events
*/
abstract class SummitAttendeeTicketAction
{
use SerializesModels;
/**
* @var int
*/
private $ticket_id;
/**
* BookableRoomReservationAction constructor.
* @param int $order_id
*/
public function __construct(int $ticket_id)
{
$this->ticket_id = $ticket_id;
}
/**
* @return int
*/
public function getTicketId(): int
{
return $this->ticket_id;
}
}

View File

@ -0,0 +1,59 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class SummitAttendeeTicketRefundAccepted
* @package App\Events
*/
final class SummitAttendeeTicketRefundAccepted extends SummitAttendeeTicketAction
{
/**
* @var array
*/
private $tickets_to_return;
/**
* @var array
*/
private $promo_codes_to_return;
/**
* SummitAttendeeTicketRefundAccepted constructor.
* @param int $ticket_id
* @param array $tickets_to_return
* @param array $promo_codes_to_return
*/
public function __construct(int $ticket_id, array $tickets_to_return, array $promo_codes_to_return)
{
parent::__construct($ticket_id);
$this->tickets_to_return = $tickets_to_return;
$this->promo_codes_to_return = $promo_codes_to_return;
}
/**
* @return array
*/
public function getTicketsToReturn(): array
{
return $this->tickets_to_return;
}
/**
* @return array
*/
public function getPromoCodesToReturn(): array
{
return $this->promo_codes_to_return;
}
}

View File

@ -0,0 +1,79 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class SummitOrderCanceled
* @package App\Events
*/
final class SummitOrderCanceled extends SummitRegistrationOrderAction
{
/**
* @var array
*/
private $tickets_to_return;
/**
* @var array
*/
private $promo_codes_to_return;
/**
* @var bool
*/
private $send_email;
/**
* SummitOrderCanceled constructor.
* @param int $order_id
* @param bool $send_email
* @param array $tickets_to_return
* @param array $promo_codes_to_return
*/
public function __construct(int $order_id, bool $send_email, array $tickets_to_return, array $promo_codes_to_return)
{
parent::__construct($order_id);
$this->send_email = $send_email;
$this->tickets_to_return = $tickets_to_return;
$this->promo_codes_to_return = $promo_codes_to_return;
}
/**
* @return bool
*/
public function shouldSendEmail(): bool
{
return $this->send_email;
}
/**
* @return array
*/
public function getTicketsToReturn(): array
{
return $this->tickets_to_return;
}
/**
* @return array
*/
public function getPromoCodesToReturn(): array
{
return $this->promo_codes_to_return;
}
}

View File

@ -0,0 +1,59 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class SummitOrderRefundAccepted
* @package App\Events
*/
class SummitOrderRefundAccepted extends SummitRegistrationOrderAction
{
/**
* @var array
*/
private $tickets_to_return;
/**
* @var array
*/
private $promo_codes_to_return;
/**
* SummitOrderRefundAccepted constructor.
* @param int $order_id
* @param array $tickets_to_return
* @param array $promo_codes_to_return
*/
public function __construct(int $order_id, array $tickets_to_return, array $promo_codes_to_return)
{
parent::__construct($order_id);
$this->promo_codes_to_return = $promo_codes_to_return;
$this->tickets_to_return = $tickets_to_return;
}
/**
* @return array
*/
public function getTicketsToReturn(): array
{
return $this->tickets_to_return;
}
/**
* @return array
*/
public function getPromoCodesToReturn(): array
{
return $this->promo_codes_to_return;
}
}

View File

@ -0,0 +1,44 @@
<?php namespace App\Events;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Queue\SerializesModels;
/**
* Class SummitRegistrationOrderAction
* @package App\Events
*/
abstract class SummitRegistrationOrderAction
{
use SerializesModels;
/**
* @var int
*/
private $order_id;
/**
* BookableRoomReservationAction constructor.
* @param int $order_id
*/
public function __construct(int $order_id)
{
$this->order_id = $order_id;
}
/**
* @return int
*/
public function getOrderId(): int
{
return $this->order_id;
}
}

View File

@ -1,14 +1,27 @@
<?php
namespace App\Exceptions;
<?php namespace App\Exceptions;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Predis\Connection\ConnectionException as RedisConnectionException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
/**
* Class Handler
* @package App\Exceptions
*/
class Handler extends ExceptionHandler
{
/**
@ -21,6 +34,7 @@ class Handler extends ExceptionHandler
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
RedisConnectionException::class,
];
/**

View File

@ -11,122 +11,102 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Services\Model\ICompanyService;
use models\main\ICompanyRepository;
use models\oauth2\IResourceServerContext;
use utils\Filter;
use utils\FilterParser;
use utils\FilterParserException;
use utils\OrderParser;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Log;
use utils\PagingInfo;
use models\exceptions\EntityNotFoundException;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
use models\exceptions\ValidationException;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
/**
* Class OAuth2CompaniesApiController
* @package App\Http\Controllers
*/
final class OAuth2CompaniesApiController extends OAuth2ProtectedController
{
/**
* OAuth2MembersApiController constructor.
* @var ICompanyService
*/
private $service;
/**
* OAuth2CompaniesApiController constructor.
* @param ICompanyRepository $company_repository
* @param IResourceServerContext $resource_server_context
* @param ICompanyService $service
*/
public function __construct
(
ICompanyRepository $company_repository,
IResourceServerContext $resource_server_context
IResourceServerContext $resource_server_context,
ICompanyService $service
)
{
parent::__construct($resource_server_context);
$this->repository = $company_repository;
$this->service = $service;
}
public function getAll(){
use ParametrizedGetAll;
$values = Input::all();
/**
* @return mixed
*/
public function getAllCompanies(){
$rules = array
(
'page' => 'integer|min:1',
'per_page' => 'required_with:page|integer|min:5|max:100',
);
try {
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
// default values
$page = 1;
$per_page = 5;
if (Input::has('page')) {
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
$filter = null;
if (Input::has('filter')) {
$filter = FilterParser::parse(Input::get('filter'), array
(
return $this->_getAll(
function(){
return [
'name' => ['=@', '=='],
));
}
$order = null;
if (Input::has('order'))
];
},
function(){
return [
'name' => 'sometimes|string',
];
},
function()
{
$order = OrderParser::parse(Input::get('order'), array
(
return [
'name',
'id',
));
];
},
function($filter){
return $filter;
},
function(){
return SerializerRegistry::SerializerType_Public;
}
if(is_null($filter)) $filter = new Filter();
$data = $this->repository->getAllByPage(new PagingInfo($page, $per_page), $filter, $order);
$fields = Request::input('fields', '');
$fields = !empty($fields) ? explode(',', $fields) : [];
$relations = Request::input('relations', '');
$relations = !empty($relations) ? explode(',', $relations) : [];
return $this->ok
(
$data->toArray
(
Request::input('expand', ''),
$fields,
$relations
)
);
}
catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch(FilterParserException $ex3){
Log::warning($ex3);
return $this->error412($ex3->getMessages());
}
catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
);
}
use AddEntity;
/**
* @param array $payload
* @return array
*/
function getAddValidationRules(array $payload): array
{
return [
'name' => 'required|string',
'description' => 'nullable|string',
'url' => 'nullable|url',
'industry' => 'nullable|string',
'city' => 'nullable|string',
'state' => 'nullable|string',
'country' => 'nullable|string',
];
}
/**
* @param array $payload
* @return IEntity
* @throws ValidationException
*/
protected function addEntity(array $payload): IEntity
{
return $this->service->addCompany($payload);
}
}

View File

@ -28,7 +28,7 @@ use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Log;
use utils\PagingInfo;
use utils\PagingResponse;
use Exception;
/**
* Class OAuth2MembersApiController
* @package App\Http\Controllers
@ -63,6 +63,9 @@ final class OAuth2MembersApiController extends OAuth2ProtectedController
*/
public function getAll(){
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error404();
$values = Input::all();
$rules = [
@ -152,7 +155,9 @@ final class OAuth2MembersApiController extends OAuth2ProtectedController
(
Request::input('expand', ''),
$fields,
$relations
$relations,
[],
$current_member->isAdmin() ? SerializerRegistry::SerializerType_Admin : SerializerRegistry::SerializerType_Public
)
);
}

View File

@ -0,0 +1,269 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Exceptions\HTTP403ForbiddenException;
use App\Models\Foundation\Main\Repositories\ISummitAdministratorPermissionGroupRepository;
use App\ModelSerializers\ISummitAttendeeTicketSerializerTypes;
use App\Services\Model\ISummitAdministratorPermissionGroupService;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\IOrderConstants;
use models\utils\IEntity;
use Exception;
use ModelSerializers\SerializerRegistry;
use utils\Filter;
use utils\FilterElement;
/**
* Class OAuth2SummitAdministratorPermissionGroupApiController
* @package App\Http\Controllers
*/
class OAuth2SummitAdministratorPermissionGroupApiController
extends OAuth2ProtectedController
{
/**
* @var ISummitAdministratorPermissionGroupService
*/
private $service;
/**
* OAuth2SummitAdministratorPermissionGroupApiController constructor.
* @param ISummitAdministratorPermissionGroupService $service
* @param ISummitAdministratorPermissionGroupRepository $repository
* @param IResourceServerContext $resource_server_context
*/
public function __construct
(
ISummitAdministratorPermissionGroupService $service,
ISummitAdministratorPermissionGroupRepository $repository,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->service = $service;
$this->repository = $repository;
}
use ParametrizedGetAll;
use AddEntity;
use DeleteEntity;
use UpdateEntity;
use GetEntity;
function getAll()
{
return $this->_getAll(
function () {
return [
'title' => ['=@', '=='],
'member_first_name' => ['=@', '=='],
'member_last_name' => ['=@', '=='],
'member_full_name' => ['=@', '=='],
'member_email' => ['=@', '=='],
'summit_id' => ['=='],
'member_id' => ['=='],
];
},
function () {
return [
'title' => 'sometimes|string',
'member_first_name' => 'sometimes|string',
'member_last_name' => 'sometimes|string',
'member_full_name' => 'sometimes|string',
'member_email' => 'sometimes|string',
'summit_id' => 'sometimes|integer',
'member_id' => 'sometimes|integer',
];
},
function () {
return [
'id',
'title',
];
},
function ($filter) {
return $filter;
},
function () {
return SerializerRegistry::SerializerType_Public;
}
);
}
/**
* @inheritDoc
*/
function getAddValidationRules(array $payload): array
{
return [
'title' => 'required|string',
'summits' => 'required|int_array',
'members' => 'required|int_array',
];
}
/**
* @inheritDoc
*/
protected function addEntity(array $payload): IEntity
{
return $this->service->create($payload);
}
/**
* @inheritDoc
*/
protected function deleteEntity(int $id): void
{
$this->service->delete($id);
}
/**
* @inheritDoc
*/
protected function getEntity(int $id): IEntity
{
return $this->repository->getById($id);
}
/**
* @inheritDoc
*/
function getUpdateValidationRules(array $payload): array
{
return [
'title' => 'sometimes|string',
'summits' => 'sometimes|int_array',
'members' => 'sometimes|int_array',
];
}
/**
* @inheritDoc
*/
protected function updateEntity($id, array $payload): IEntity
{
return $this->service->update($id, $payload);
}
public function addMember($id, $member_id)
{
try {
$group = $this->repository->getById($id);
if (is_null($group))
throw new EntityNotFoundException();
$group = $this->service->addMemberTo($group, $member_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($group)->serialize());
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412(array($ex->getMessage()));
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\HTTP401UnauthorizedException $ex) {
Log::warning($ex);
return $this->error401();
} catch (HTTP403ForbiddenException $ex) {
Log::warning($ex);
return $this->error403();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function removeMember($id, $member_id)
{
try {
$group = $this->repository->getById($id);
if (is_null($group))
throw new EntityNotFoundException();
$group = $this->service->removeMemberFrom($group, $member_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($group)->serialize());
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412(array($ex->getMessage()));
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\HTTP401UnauthorizedException $ex) {
Log::warning($ex);
return $this->error401();
} catch (HTTP403ForbiddenException $ex) {
Log::warning($ex);
return $this->error403();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function addSummit($id, $summit_id)
{
try {
$group = $this->repository->getById($id);
if (is_null($group))
throw new EntityNotFoundException();
$group = $this->service->addSummitTo($group, $summit_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($group)->serialize());
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412(array($ex->getMessage()));
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\HTTP401UnauthorizedException $ex) {
Log::warning($ex);
return $this->error401();
} catch (HTTP403ForbiddenException $ex) {
Log::warning($ex);
return $this->error403();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function removeSummit($id, $summit_id)
{
try {
$group = $this->repository->getById($id);
if (is_null($group))
throw new EntityNotFoundException();
$group = $this->service->removeSummitFrom($group, $summit_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($group)->serialize());
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412(array($ex->getMessage()));
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\HTTP401UnauthorizedException $ex) {
Log::warning($ex);
return $this->error401();
} catch (HTTP403ForbiddenException $ex) {
Log::warning($ex);
return $this->error403();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,67 @@
<?php
namespace App\Http\Controllers;
use models\summit\IPaymentConstants;
use models\summit\PaymentGatewayProfile;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class PaymentGatewayProfileValidationRulesFactory
* @package App\Http\Controllers
*/
final class PaymentGatewayProfileValidationRulesFactory
{
/**
* @param array $data
* @param bool $update
* @return array
*/
public static function build(array $data, $update = false){
if($update){
$rules = [
'active' => 'sometimes|boolean',
'application_type' => 'sometimes|string|in:'.implode(',',IPaymentConstants::ValidApplicationTypes),
'provider' => 'required|string|in:'.implode(',',IPaymentConstants::ValidProviderTypes),
];
if(isset($data['provider']) && $data['provider'] == IPaymentConstants::ProviderStripe){
$rules = array_merge($rules, [
'test_mode_enabled' => 'required|boolean',
'live_secret_key' => 'sometimes|string',
'live_publishable_key' => 'required_with:live_secret_key|string',
'test_secret_key' => 'required_with:test_mode_enabled|string',
'test_publishable_key' => 'required_with:test_secret_key|string',
]);
}
return $rules;
}
$rules = [
'active' => 'required|boolean',
'application_type' => 'required|string|in:'.implode(',',IPaymentConstants::ValidApplicationTypes),
'provider' => 'required|string|in:'.implode(',',IPaymentConstants::ValidProviderTypes),
];
if(isset($data['provider']) && $data['provider'] == IPaymentConstants::ProviderStripe){
$rules = array_merge($rules, [
'test_mode_enabled' => 'required|boolean',
'live_secret_key' => 'sometimes|string',
'live_publishable_key' => 'required_with:live_secret_key|string',
'test_secret_key' => 'required_with:test_mode_enabled|string',
'test_publishable_key' => 'required_with:test_secret_key|string',
]);
}
return $rules;
}
}

View File

@ -0,0 +1,43 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class AccessLevelTypeValidationRulesFactory
* @package App\Http\Controllers
*/
final class AccessLevelTypeValidationRulesFactory
{
/**
* @param array $data
* @param bool $update
* @return array
*/
public static function build(array $data, $update = false){
if($update){
return [
'name' => 'sometimes|string',
'description' => 'sometimes|string',
'template_content' => 'sometimes|string',
'is_default' => 'sometimes|boolean',
];
}
return [
'name' => 'required|string',
'description' => 'sometimes|string',
'template_content' => 'nullable|string',
'is_default' => 'required|boolean',
];
}
}

View File

@ -13,8 +13,11 @@
**/
use App\Models\Foundation\Summit\PromoCodes\PromoCodesConstants;
use models\exceptions\ValidationException;
use models\summit\MemberSummitRegistrationDiscountCode;
use models\summit\MemberSummitRegistrationPromoCode;
use models\summit\SpeakerSummitRegistrationDiscountCode;
use models\summit\SpeakerSummitRegistrationPromoCode;
use models\summit\SponsorSummitRegistrationDiscountCode;
use models\summit\SponsorSummitRegistrationPromoCode;
/**
* Class PromoCodesValidationRulesFactory
@ -24,10 +27,11 @@ final class PromoCodesValidationRulesFactory
{
/**
* @param array $data
* @param bool $update
* @return array
* @throws ValidationException
*/
public static function build(array $data){
public static function build(array $data, $update = false){
if(!isset($data['class_name']))
throw new ValidationException("class_name parameter is mandatory");
@ -44,10 +48,20 @@ final class PromoCodesValidationRulesFactory
}
$base_rules = [
'code' => 'required|string',
'code' => $update ? 'sometimes|string|max:255' : 'required|string|max:255',
'quantity_available' => 'sometimes|integer|min:0',
'valid_since_date' => 'nullable|date_format:U',
'valid_until_date' => 'nullable|required_with:valid_since_date|date_format:U|after:valid_since_date',
'badge_type_id' => 'nullable|integer',
'allowed_ticket_types' => 'sometimes|int_array',
'badge_features' => 'sometimes|int_array',
];
$specific_rules = [];
$discount_code_rules = [
'amount' => 'sometimes|numeric|min:0',
'rate' => 'sometimes|numeric|min:0',
];
switch ($class_name){
case MemberSummitRegistrationPromoCode::ClassName:{
@ -55,7 +69,7 @@ final class PromoCodesValidationRulesFactory
'first_name' => 'required_without:owner_id|string',
'last_name' => 'required_without:owner_id|string',
'email' => 'required_without:owner_id|email|max:254',
'type' => 'required|string|in:'.join(",",MemberSummitRegistrationPromoCode::$valid_type_values),
'type' => 'required|string|in:'.join(",", PromoCodesConstants::MemberSummitRegistrationPromoCodeTypes),
'owner_id' => 'required_without:first_name,last_name,email|integer'
];
}
@ -63,7 +77,7 @@ final class PromoCodesValidationRulesFactory
case SpeakerSummitRegistrationPromoCode::ClassName:
{
$specific_rules = [
'type' => 'required|string|in:'.join(",",SpeakerSummitRegistrationPromoCode::$valid_type_values),
'type' => 'required|string|in:'.join(",", PromoCodesConstants::SpeakerSummitRegistrationPromoCodeTypes),
'speaker_id' => 'required|integer'
];
}
@ -75,6 +89,35 @@ final class PromoCodesValidationRulesFactory
];
}
break;
case MemberSummitRegistrationDiscountCode::ClassName:
{
$specific_rules = array_merge([
'first_name' => 'required_without:owner_id|string',
'last_name' => 'required_without:owner_id|string',
'email' => 'required_without:owner_id|email|max:254',
'type' => 'required|string|in:'.join(",", PromoCodesConstants::MemberSummitRegistrationPromoCodeTypes),
'owner_id' => 'required_without:first_name,last_name,email|integer',
], $discount_code_rules);
}
break;
case SpeakerSummitRegistrationDiscountCode::ClassName:
{
$specific_rules = array_merge([
'type' => 'required|string|in:'.join(",", PromoCodesConstants::SpeakerSummitRegistrationPromoCodeTypes),
'speaker_id' => 'required|integer',
'amount' => 'sometimes|required_without:rate',
'rate' => 'sometimes|required_without:amount',
], $discount_code_rules);
}
break;
case SponsorSummitRegistrationDiscountCode::ClassName:
{
$specific_rules = array_merge([
'sponsor_id' => 'required|integer'
],$discount_code_rules);
}
break;
}
return array_merge($base_rules, $specific_rules);

View File

@ -1,6 +1,6 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2018 OpenStack Foundation
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -13,29 +13,29 @@
**/
/**
* Class SummitTicketTypeValidationRulesFactory
* Class SummitBadgeFeatureTypeValidationRulesFactory
* @package App\Http\Controllers
*/
final class SummitTicketTypeValidationRulesFactory
final class SummitBadgeFeatureTypeValidationRulesFactory
{
/**
* @param array $data
* @param bool $update
* @return array
*/
public static function build(array $data, $update = false){
if($update){
return [
'name' => 'sometimes|string',
'name' => 'sometimes|string',
'description' => 'sometimes|string',
'external_id' => 'sometimes|string|max:255',
'template_content' => 'nullable|string',
];
}
return [
'name' => 'required|string',
'name' => 'required|string',
'description' => 'sometimes|string',
'external_id' => 'required|string|max:255',
'template_content' => 'nullable|string',
];
}
}

View File

@ -0,0 +1,43 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class SummitBadgeTypeValidationRulesFactory
* @package App\Http\Controllers
*/
final class SummitBadgeTypeValidationRulesFactory
{
/**
* @param array $data
* @param bool $update
* @return array
*/
public static function build(array $data, $update = false){
if($update){
return [
'name' => 'sometimes|string',
'description' => 'sometimes|string',
'template_content' => 'nullable|string',
'is_default' => 'sometimes|boolean',
];
}
return [
'name' => 'required|string',
'description' => 'required|string',
'template_content' => 'nullable|string',
'is_default' => 'required|boolean',
];
}
}

View File

@ -0,0 +1,51 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use models\summit\SummitOrderExtraQuestionTypeConstants;
/**
* Class SummitOrderExtraQuestionTypeValidationRulesFactory
* @package App\Http\Controllers
*/
final class SummitOrderExtraQuestionTypeValidationRulesFactory
{
/**
* @param array $data
* @param bool $update
* @return array
*/
public static function build(array $data, $update = false){
if($update){
return [
'name' => 'sometimes|string',
'type' => 'sometimes|string|in:'.implode(",", SummitOrderExtraQuestionTypeConstants::ValidQuestionTypes),
'label' => 'sometimes|string',
'mandatory' => 'sometimes|boolean',
'usage' => 'sometimes|string|in:'.implode(",", SummitOrderExtraQuestionTypeConstants::ValidQuestionUsages),
'printable' => 'sometimes|boolean',
'placeholder' => 'sometimes|string',
'order' => 'sometimes|integer|min:1',
];
}
return [
'name' => 'required|string',
'type' => 'required|string|in:'.implode(",", SummitOrderExtraQuestionTypeConstants::ValidQuestionTypes),
'label' => 'required|string',
'mandatory' => 'required|boolean',
'usage' => 'required|string|in:'.implode(",", SummitOrderExtraQuestionTypeConstants::ValidQuestionUsages),
'printable' => 'sometimes|boolean',
'placeholder' => 'sometimes|string',
];
}
}

View File

@ -0,0 +1,41 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class SummitRefundPolicyTypeValidationRulesFactory
* @package App\Http\Controllers
*/
final class SummitRefundPolicyTypeValidationRulesFactory
{
/**
* @param array $data
* @param bool $update
* @return array
*/
public static function build(array $data, $update = false){
if($update){
return [
'name' => 'sometimes|string',
'refund_rate' => 'sometimes|numeric|min:0|max:100',
'until_x_days_before_event_starts' => 'sometimes|integer|min:1',
];
}
return [
'name' => 'required|string',
'refund_rate' => 'required|numeric|min:0|max:100',
'until_x_days_before_event_starts' => 'required|integer|min:1',
];
}
}

View File

@ -0,0 +1,55 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2018 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class SummitTicketTypeValidationRulesFactory
* @package App\Http\Controllers
*/
final class SummitTicketTypeValidationRulesFactory
{
/**
* @param array $data
* @return array
*/
public static function build(array $data, $update = false){
if($update){
return [
'name' => 'sometimes|string',
'description' => 'sometimes|string',
'badge_type_id' => 'sometimes|integer',
'external_id' => 'sometimes|string|max:255',
'currency' => 'sometimes|string|currency_iso',
'quantity_2_sell' => 'sometimes|integer|greater_than:0',
'max_quantity_per_order' => 'sometimes|integer',
'sales_start_date' => 'nullable|date_format:U',
'sales_end_date' => 'nullable:sales_start_date|date_format:U|after:sales_start_date',
'cost' => 'sometimes|numeric|greater_than_or_equal:0',
];
}
return [
'name' => 'required|string',
'cost' => 'sometimes|numeric|greater_than_or_equal:0',
'currency' => 'required_with:cost|string|currency_iso',
'quantity_2_sell' => 'sometimes|integer|greater_than:0',
'max_quantity_per_order' => 'sometimes|integer',
'sales_start_date' => 'nullable|date_format:U',
'sales_end_date' => 'nullable:sales_start_date|date_format:U|after:sales_start_date',
'description' => 'sometimes|string',
'external_id' => 'sometimes|string|max:255',
'badge_type_id' => 'sometimes|integer',
];
}
}

View File

@ -0,0 +1,41 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class TaxTypeValidationRulesFactory
* @package App\Http\Controllers
*/
final class TaxTypeValidationRulesFactory
{
/**
* @param array $data
* @param bool $update
* @return array
*/
public static function build(array $data, $update = false){
if($update){
return [
'name' => 'sometimes|string',
'tax_id' => 'sometimes|string',
'rate' => 'sometimes|numeric|greater_than:0'
];
}
return [
'name' => 'required|string',
'tax_id' => 'sometimes|string',
'rate' => 'required|numeric|greater_than:0'
];
}
}

View File

@ -0,0 +1,41 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class SponsorValidationRulesFactory
* @package App\Http\Controllers
*/
final class SponsorValidationRulesFactory
{
/**
* @param array $data
* @param bool $update
* @return array
*/
public static function build(array $data, $update = false){
if($update){
return [
'company_id' => 'sometimes|integer',
'sponsorship_id' => 'sometimes|integer',
'order' => 'sometimes|integer|min:1',
];
}
return [
'company_id' => 'required|integer',
'sponsorship_id' => 'required|integer',
];
}
}

View File

@ -0,0 +1,45 @@
<?php namespace App\Http\Controllers;
use models\summit\ISponsorshipTypeConstants;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class SponsorshipTypeValidationRulesFactory
* @package App\Http\Controllers
*/
final class SponsorshipTypeValidationRulesFactory
{
/**
* @param array $data
* @param bool $update
* @return array
*/
public static function build(array $data, $update = false){
if($update){
return [
'name' => 'sometimes|string',
'label' => 'sometimes|string',
'size' => 'sometimes|string|in:'.implode(",", ISponsorshipTypeConstants::AllowedSizes),
'order' => 'sometimes|integer|min:1',
];
}
return [
'name' => 'required|string',
'label' => 'required|string',
'size' => 'required|string|in:'.implode(",", ISponsorshipTypeConstants::AllowedSizes),
];
}
}

View File

@ -11,113 +11,141 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use models\summit\Summit;
use App\Models\Foundation\Summit\ISummitExternalScheduleFeedType;
use App\Models\Foundation\Summit\Registration\ISummitExternalRegistrationFeedType;
/**
* Class SummitValidationRulesFactory
* @package App\Http\Controllers
*/
final class SummitValidationRulesFactory
{
public static function build(array $data, $update = false){
public static function build(array $data, $update = false)
{
if($update){
if ($update) {
return [
'name' => 'sometimes|string|max:50',
'start_date' => 'sometimes|date_format:U',
'end_date' => 'required_with:start_date|date_format:U|after_or_equal:start_date',
'registration_begin_date' => 'nullable|date_format:U',
'registration_end_date' => 'nullable|required_with:registration_begin_date|date_format:U|after_or_equal:registration_begin_date',
'name' => 'sometimes|string|max:50',
'start_date' => 'sometimes|date_format:U',
'end_date' => 'required_with:start_date|date_format:U|after_or_equal:start_date',
'registration_begin_date' => 'nullable|date_format:U',
'registration_end_date' => 'nullable|required_with:registration_begin_date|date_format:U|after_or_equal:registration_begin_date',
'start_showing_venues_date' => 'nullable|date_format:U|before_or_equal:start_date',
'schedule_start_date' => 'nullable|date_format:U|after_or_equal:start_date|before_or_equal:end_date',
'active' => 'sometimes|boolean',
'dates_label' => 'sometimes|string',
'time_zone_id' => 'sometimes|timezone',
'external_summit_id' => 'sometimes|string',
'available_on_api' => 'sometimes|boolean',
'calendar_sync_name' => 'sometimes|string|max:255',
'calendar_sync_desc' => 'sometimes|string',
'link' => 'sometimes|url',
'registration_link' => 'sometimes|url',
'max_submission_allowed_per_user' => 'sometimes|integer|min:1',
'secondary_registration_link' => 'sometimes|url',
'secondary_registration_label' => 'sometimes|string',
'slug' => 'nullable|string',
'meeting_room_booking_start_time' => 'nullable|date_format:U',
'meeting_room_booking_end_time' => 'nullable|required_with:meeting_room_booking_start_time|date_format:U|after_or_equal:meeting_room_booking_start_time',
'schedule_start_date' => 'nullable|date_format:U|after_or_equal:start_date|before_or_equal:end_date',
'active' => 'sometimes|boolean',
'dates_label' => 'sometimes|string',
'time_zone_id' => 'sometimes|timezone',
'available_on_api' => 'sometimes|boolean',
'calendar_sync_name' => 'sometimes|string|max:255',
'calendar_sync_desc' => 'sometimes|string',
'link' => 'sometimes|url',
'registration_link' => 'sometimes|url',
'max_submission_allowed_per_user' => 'sometimes|integer|min:1',
'secondary_registration_link' => 'sometimes|url',
'secondary_registration_label' => 'sometimes|string',
'slug' => 'required|string',
'meeting_room_booking_start_time' => 'nullable|date_format:U',
'meeting_room_booking_end_time' => 'nullable|required_with:meeting_room_booking_start_time|date_format:U|after_or_equal:meeting_room_booking_start_time',
'meeting_room_booking_slot_length' => 'nullable|integer',
'meeting_room_booking_max_allowed' => 'nullable|integer|min:1',
'api_feed_type' => sprintf('nullable|in:%s',implode(',', Summit::$valid_feed_types)),
'api_feed_url' => 'nullable|string|url|required_with:api_feed_type',
'api_feed_key' => 'nullable|string|required_with:api_feed_type',
'begin_allow_booking_date' => 'nullable|date_format:U',
'end_allow_booking_date' => 'nullable|required_with:begin_allow_booking_date|date_format:U|after_or_equal:begin_allow_booking_date',
'api_feed_type' => sprintf('nullable|in:%s', implode(',', ISummitExternalScheduleFeedType::ValidFeedTypes)),
'api_feed_url' => 'nullable|string|url|required_with:api_feed_type',
'api_feed_key' => 'nullable|string|required_with:api_feed_type',
'begin_allow_booking_date' => 'nullable|date_format:U',
'end_allow_booking_date' => 'nullable|required_with:begin_allow_booking_date|date_format:U|after_or_equal:begin_allow_booking_date',
'reassign_ticket_till_date' => 'nullable|date_format:U',
'registration_disclaimer_content' => 'nullable|string',
'registration_disclaimer_mandatory' => 'nullable|boolean',
'registration_reminder_email_days_interval' => 'nullable|integer|min:1',
'external_summit_id' => 'nullable|string',
'external_registration_feed_type' => sprintf('nullable|in:%s', implode(',', ISummitExternalRegistrationFeedType::ValidFeedTypes)),
'external_registration_feed_api_key' => 'nullable|string|required_with:external_registration_feed_type',
// schedule
'schedule_default_page_url' => 'nullable|url',
'schedule_default_event_detail_url' => 'nullable|url',
'schedule_og_site_name' => 'nullable|string',
'schedule_og_image_url' => 'nullable|url',
'schedule_og_image_secure_url' => 'nullable|url',
'schedule_og_image_width' => 'nullable|integer',
'schedule_og_image_height' => 'nullable|integer',
'schedule_facebook_app_id' => 'nullable|string',
'schedule_ios_app_name' => 'nullable|string',
'schedule_ios_app_store_id' => 'nullable|string',
'schedule_ios_app_custom_schema' => 'nullable|string',
'schedule_android_app_name' => 'nullable|string',
'schedule_android_app_package' => 'nullable|string',
'schedule_android_custom_schema' => 'nullable|string',
'schedule_twitter_app_name' => 'nullable|string',
'schedule_twitter_text' => 'nullable|string',
'schedule_default_page_url' => 'nullable|url',
'schedule_default_event_detail_url' => 'nullable|url',
'schedule_og_site_name' => 'nullable|string',
'schedule_og_image_url' => 'nullable|url',
'schedule_og_image_secure_url' => 'nullable|url',
'schedule_og_image_width' => 'nullable|integer',
'schedule_og_image_height' => 'nullable|integer',
'schedule_facebook_app_id' => 'nullable|string',
'schedule_ios_app_name' => 'nullable|string',
'schedule_ios_app_store_id' => 'nullable|string',
'schedule_ios_app_custom_schema' => 'nullable|string',
'schedule_android_app_name' => 'nullable|string',
'schedule_android_app_package' => 'nullable|string',
'schedule_android_custom_schema' => 'nullable|string',
'schedule_twitter_app_name' => 'nullable|string',
'schedule_twitter_text' => 'nullable|string',
'default_page_url' => 'nullable|url',
'speaker_confirmation_default_page_url' => 'nullable|url',
'virtual_site_url' => 'nullable|url',
'marketing_site_url' => 'nullable|url',
'virtual_site_oauth2_client_id' => 'nullable|string',
'marketing_site_oauth2_client_id' => 'nullable|string',
'support_email' => 'nullable|email',
];
}
return [
'name' => 'required|string|max:50',
'start_date' => 'required|date_format:U',
'end_date' => 'required_with:start_date|date_format:U|after_or_equal:start_date',
'registration_begin_date' => 'nullable|date_format:U',
'registration_end_date' => 'nullable|required_with:registration_begin_date|date_format:U|after_or_equal:registration_begin_date',
'start_showing_venues_date' => 'nullable|date_format:U|before_or_equal:start_date',
'schedule_start_date' => 'nullable|date_format:U|after_or_equal:start_date|before_or_equal:end_date',
'active' => 'sometimes|boolean',
'dates_label' => 'sometimes|string',
'time_zone_id' => 'required|timezone',
'external_summit_id' => 'nullable|string',
'available_on_api' => 'sometimes|boolean',
'calendar_sync_name' => 'sometimes|string|max:255',
'calendar_sync_desc' => 'sometimes|string',
'link' => 'sometimes|url',
'registration_link' => 'sometimes|url',
'max_submission_allowed_per_user' => 'sometimes|integer|min:1',
'secondary_registration_link' => 'sometimes|url',
'secondary_registration_label' => 'sometimes|string',
'slug' => 'nullable|string',
'meeting_room_booking_start_time' => 'nullable|date_format:U',
'meeting_room_booking_end_time' => 'nullable|required_with:meeting_room_booking_start_time|date_format:U|after_or_equal:meeting_room_booking_start_time',
'meeting_room_booking_slot_length' => 'nullable|integer',
'meeting_room_booking_max_allowed' => 'nullable|integer|min:1',
'api_feed_type' => sprintf('nullable|in:%s',implode(',', Summit::$valid_feed_types)),
'api_feed_url' => 'nullable|string|url|required_with:api_feed_type',
'api_feed_key' => 'nullable|string|required_with:api_feed_type',
'begin_allow_booking_date' => 'nullable|date_format:U',
'end_allow_booking_date' => 'nullable|required_with:begin_allow_booking_date|date_format:U|after_or_equal:begin_allow_booking_date',
'name' => 'required|string|max:50',
'start_date' => 'required|date_format:U',
'end_date' => 'required_with:start_date|date_format:U|after_or_equal:start_date',
'registration_begin_date' => 'nullable|date_format:U',
'registration_end_date' => 'nullable|required_with:registration_begin_date|date_format:U|after_or_equal:registration_begin_date',
'start_showing_venues_date' => 'nullable|date_format:U|before_or_equal:start_date',
'schedule_start_date' => 'nullable|date_format:U|after_or_equal:start_date|before_or_equal:end_date',
'active' => 'sometimes|boolean',
'dates_label' => 'sometimes|string',
'time_zone_id' => 'required|timezone',
'available_on_api' => 'sometimes|boolean',
'calendar_sync_name' => 'sometimes|string|max:255',
'calendar_sync_desc' => 'sometimes|string',
'link' => 'sometimes|url',
'registration_link' => 'sometimes|url',
'max_submission_allowed_per_user' => 'sometimes|integer|min:1',
'secondary_registration_link' => 'sometimes|url',
'secondary_registration_label' => 'sometimes|string',
'slug' => 'required|string',
'meeting_room_booking_start_time' => 'nullable|date_format:U',
'meeting_room_booking_end_time' => 'nullable|required_with:meeting_room_booking_start_time|date_format:U|after_or_equal:meeting_room_booking_start_time',
'meeting_room_booking_slot_length' => 'nullable|integer',
'meeting_room_booking_max_allowed' => 'nullable|integer|min:1',
'api_feed_type' => sprintf('nullable|in:%s', implode(',', ISummitExternalScheduleFeedType::ValidFeedTypes)),
'api_feed_url' => 'nullable|string|url|required_with:api_feed_type',
'api_feed_key' => 'nullable|string|required_with:api_feed_type',
'begin_allow_booking_date' => 'nullable|date_format:U',
'end_allow_booking_date' => 'nullable|required_with:begin_allow_booking_date|date_format:U|after_or_equal:begin_allow_booking_date',
'reassign_ticket_till_date' => 'nullable|date_format:U',
'registration_disclaimer_content' => 'nullable|string',
'registration_disclaimer_mandatory' => 'nullable|boolean',
'registration_reminder_email_days_interval' => 'nullable|integer|min:1',
'external_summit_id' => 'nullable|string',
'external_registration_feed_type' => sprintf('nullable|in:%s', implode(',', ISummitExternalRegistrationFeedType::ValidFeedTypes)),
'external_registration_feed_api_key' => 'nullable|string|required_with:external_registration_feed_type',
// schedule
'schedule_default_page_url' => 'nullable|url',
'schedule_default_event_detail_url' => 'nullable|url',
'schedule_og_site_name' => 'nullable|string',
'schedule_og_image_url' => 'nullable|url',
'schedule_og_image_secure_url' => 'nullable|url',
'schedule_og_image_width' => 'nullable|integer',
'schedule_og_image_height' => 'nullable|integer',
'schedule_facebook_app_id' => 'nullable|string',
'schedule_ios_app_name' => 'nullable|string',
'schedule_ios_app_store_id' => 'nullable|string',
'schedule_ios_app_custom_schema' => 'nullable|string',
'schedule_android_app_name' => 'nullable|string',
'schedule_android_app_package' => 'nullable|string',
'schedule_android_custom_schema' => 'nullable|string',
'schedule_twitter_app_name' => 'nullable|string',
'schedule_twitter_text' => 'nullable|string',
'schedule_default_page_url' => 'nullable|url',
'schedule_default_event_detail_url' => 'nullable|url',
'schedule_og_site_name' => 'nullable|string',
'schedule_og_image_url' => 'nullable|url',
'schedule_og_image_secure_url' => 'nullable|url',
'schedule_og_image_width' => 'nullable|integer',
'schedule_og_image_height' => 'nullable|integer',
'schedule_facebook_app_id' => 'nullable|string',
'schedule_ios_app_name' => 'nullable|string',
'schedule_ios_app_store_id' => 'nullable|string',
'schedule_ios_app_custom_schema' => 'nullable|string',
'schedule_android_app_name' => 'nullable|string',
'schedule_android_app_package' => 'nullable|string',
'schedule_android_custom_schema' => 'nullable|string',
'schedule_twitter_app_name' => 'nullable|string',
'schedule_twitter_text' => 'nullable|string',
'default_page_url' => 'nullable|url',
'speaker_confirmation_default_page_url' => 'nullable|url',
'virtual_site_url' => 'nullable|url',
'marketing_site_url' => 'nullable|url',
'virtual_site_oauth2_client_id' => 'nullable|string',
'marketing_site_oauth2_client_id' => 'nullable|string',
'support_email' => 'nullable|email',
];
}
}

View File

@ -0,0 +1,171 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Repositories\IPaymentGatewayProfileRepository;
use App\Services\Model\IPaymentGatewayProfileService;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use models\summit\Summit;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
/**
* Class OAuth2PaymentGatewayProfileApiController
* @package App\Http\Controller
*/
final class OAuth2PaymentGatewayProfileApiController extends OAuth2ProtectedController
{
/**
* @var IPaymentGatewayProfileService
*/
private $service;
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* OAuth2PaymentGatewayProfileApiController constructor.
* @param IPaymentGatewayProfileRepository $repository
* @param ISummitRepository $summit_repository
* @param IPaymentGatewayProfileService $service
* @param IResourceServerContext $resource_server_context
*/
public function __construct
(
IPaymentGatewayProfileRepository $repository,
ISummitRepository $summit_repository,
IPaymentGatewayProfileService $service,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->repository = $repository;
$this->summit_repository = $summit_repository;
$this->service = $service;
}
use GetAllBySummit;
use GetSummitChildElementById;
use AddSummitChildElement;
use UpdateSummitChildElement;
use DeleteSummitChildElement;
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @inheritDoc
*/
protected function addChild(Summit $summit, array $payload): IEntity
{
return $this->service->addPaymentProfile($summit, $payload);
}
/**
* @inheritDoc
*/
function getAddValidationRules(array $payload): array
{
return PaymentGatewayProfileValidationRulesFactory::build($payload, false);
}
/**
* @inheritDoc
*/
protected function deleteChild(Summit $summit, $child_id): void
{
$this->service->deletePaymentProfile($summit, $child_id);
}
/**
* @inheritDoc
*/
protected function getChildFromSummit(Summit $summit, $child_id): ?IEntity
{
return $summit->getPaymentProfileById($child_id);
}
/**
* @inheritDoc
*/
function getUpdateValidationRules(array $payload): array
{
return PaymentGatewayProfileValidationRulesFactory::build($payload, true);
}
/**
* @inheritDoc
*/
protected function updateChild(Summit $summit, int $child_id, array $payload): IEntity
{
return $this->service->updatePaymentProfile($summit, $child_id, $payload);
}
/**
* @return array
*/
protected function getFilterRules():array
{
return [
'application_type' => ['=@', '=='],
'active' => ['=='],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [
'application_type' => 'sometimes|required|string',
'active' => 'sometimes|required|boolean',
];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [
'id',
'application_type',
];
}
protected function serializerType():string{
return SerializerRegistry::SerializerType_Private;
}
protected function addSerializerType():string{
return SerializerRegistry::SerializerType_Private;
}
protected function updateSerializerType():string{
return SerializerRegistry::SerializerType_Private;
}
public function getChildSerializer(){
return SerializerRegistry::SerializerType_Private;
}
}

View File

@ -11,14 +11,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Utils\FileTypes;
use App\Http\Utils\MultipartFormDataCleaner;
use libs\utils\HTMLCleaner;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\main\IMemberRepository;
use models\main\Member;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitEventRepository;
use models\summit\ISummitRepository;
@ -32,7 +30,6 @@ use models\summit\Presentation;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
use services\model\IPresentationService;
use utils\ParseMultiPartFormDataInputStream;
/**
* Class OAuth2PresentationApiController
* @package App\Http\Controllers
@ -131,7 +128,7 @@ final class OAuth2PresentationApiController extends OAuth2ProtectedController
if (is_null($presentation)) return $this->error404();
$video = $presentation-getVideoBy($video_id);
$video = $presentation->getVideoBy($video_id);
if (is_null($video)) return $this->error404();
@ -350,7 +347,7 @@ final class OAuth2PresentationApiController extends OAuth2ProtectedController
$presentation = $this->presentation_service->submitPresentation($summit, $current_member, HTMLCleaner::cleanData($data, $fields));
return $this->created(SerializerRegistry::getInstance()->getSerializer($presentation)->serialize());
return $this->created(SerializerRegistry::getInstance()->getSerializer($presentation)->serialize(Request::input('expand', '')));
}
catch (EntityNotFoundException $ex1)
{
@ -426,7 +423,7 @@ final class OAuth2PresentationApiController extends OAuth2ProtectedController
HTMLCleaner::cleanData($data, $fields)
);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($presentation)->serialize());
return $this->updated(SerializerRegistry::getInstance()->getSerializer($presentation)->serialize(Request::input('expand', '')));
}
catch (EntityNotFoundException $ex1)
{
@ -466,7 +463,7 @@ final class OAuth2PresentationApiController extends OAuth2ProtectedController
$current_member
);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($presentation)->serialize());
return $this->updated(SerializerRegistry::getInstance()->getSerializer($presentation)->serialize(Request::input('expand', '')));
}
catch (EntityNotFoundException $ex1)
{
@ -532,7 +529,7 @@ final class OAuth2PresentationApiController extends OAuth2ProtectedController
if (is_null($presentation)) return $this->error404();
$slides = $presentation-getSlides();
$slides = $presentation->getSlides();
$items = [];
foreach($slides as $i)
@ -573,7 +570,7 @@ final class OAuth2PresentationApiController extends OAuth2ProtectedController
if (is_null($presentation)) return $this->error404();
$slide = $presentation-getSlideBy($slide_id);
$slide = $presentation->getSlideBy($slide_id);
if (is_null($slide)) return $this->error404();
@ -794,7 +791,7 @@ final class OAuth2PresentationApiController extends OAuth2ProtectedController
if (is_null($presentation)) return $this->error404();
$links = $presentation-getLinks();
$links = $presentation->getLinks();
$items = [];
foreach($links as $i)
@ -835,7 +832,7 @@ final class OAuth2PresentationApiController extends OAuth2ProtectedController
if (is_null($presentation)) return $this->error404();
$link = $presentation-getLinkBy($link_id);
$link = $presentation->getLinkBy($link_id);
if (is_null($link)) return $this->error404();
@ -1000,4 +997,260 @@ final class OAuth2PresentationApiController extends OAuth2ProtectedController
return $this->error500($ex);
}
}
// MediaUploads
/**
* @param $summit_id
* @param $presentation_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getPresentationMediaUploads($summit_id, $presentation_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$presentation = $this->presentation_repository->getById($presentation_id);
if (is_null($presentation) || !$presentation instanceof Presentation) return $this->error404();
$mediaUploads = $presentation->getMediaUploads();
$items = [];
foreach($mediaUploads as $i)
{
if($i instanceof IEntity)
{
$i = SerializerRegistry::getInstance()->getSerializer($i)->serialize();
}
$items[] = $i;
}
return $this->ok($items);
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $presentation_id
* @param $media_upload_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getPresentationMediaUpload($summit_id, $presentation_id, $media_upload_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$presentation = $this->presentation_repository->getById($presentation_id);
if (is_null($presentation) || !$presentation instanceof Presentation) return $this->error404();
$mediaUpload = $presentation->getMediaUploadBy($media_upload_id);
if (is_null($mediaUpload)) return $this->error404();
return $this->ok(SerializerRegistry::getInstance()->getSerializer($mediaUpload)->serialize());
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param LaravelRequest $request
* @param $summit_id
* @param $presentation_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function addPresentationMediaUpload(LaravelRequest $request, $summit_id, $presentation_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$serializeType = SerializerRegistry::SerializerType_Private;
if(!$current_member->isAdmin()){
$serializeType = SerializerRegistry::SerializerType_Public;
// check if we could edit presentation
$presentation = $summit->getEvent($presentation_id);
if(is_null($presentation) || !$presentation instanceof Presentation)
return $this->error404();
if(!$current_member->hasSpeaker() || !$presentation->canEdit($current_member->getSpeaker()))
return $this->error403();
}
$data = $request->all();
$rules = [
'media_upload_type_id' => 'required|integer',
];
// Creates a Validator instance and validates the data.
$validation = Validator::make($data, $rules);
if ($validation->fails()) {
$ex = new ValidationException;
$ex->setMessages($validation->messages()->toArray());
throw $ex;
}
$mediaUpload = $this->presentation_service->addMediaUploadTo
(
$request,
$summit,
intval($presentation_id),
$data
);
$fields = Request::input('fields', '');
$relations = Request::input('relations', '');
$relations = !empty($relations) ? explode(',', $relations) : [];
$fields = !empty($fields) ? explode(',', $fields) : [];
return $this->created(SerializerRegistry::getInstance()->getSerializer
(
$mediaUpload, $serializeType)
->serialize
(
Request::input('expand', ''),
$fields,
$relations
)
);
}
catch (EntityNotFoundException $ex1)
{
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param LaravelRequest $request
* @param $summit_id
* @param $presentation_id
* @param $media_upload_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function updatePresentationMediaUpload(LaravelRequest $request, $summit_id, $presentation_id, $media_upload_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$serializeType = SerializerRegistry::SerializerType_Private;
if(!$current_member->isAdmin()){
$serializeType = SerializerRegistry::SerializerType_Public;
// check if we could edit presentation
$presentation = $summit->getEvent($presentation_id);
if(is_null($presentation) || !$presentation instanceof Presentation)
return $this->error404();
if(!$current_member->hasSpeaker() || !$presentation->canEdit($current_member->getSpeaker()))
return $this->error403();
}
$mediaUpload = $this->presentation_service->updateMediaUploadFrom
(
$request,
$summit,
intval($presentation_id),
intval($media_upload_id)
);
$fields = Request::input('fields', '');
$relations = Request::input('relations', '');
$relations = !empty($relations) ? explode(',', $relations) : [];
$fields = !empty($fields) ? explode(',', $fields) : [];
return $this->updated(SerializerRegistry::getInstance()->getSerializer
(
$mediaUpload, $serializeType)
->serialize
(
Request::input('expand', ''),
$fields,
$relations
)
);
}
catch (EntityNotFoundException $ex1)
{
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $presentation_id
* @param $media_upload_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function deletePresentationMediaUpload($summit_id, $presentation_id, $media_upload_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$this->presentation_service->deleteMediaUpload($summit, intval($presentation_id), intval($media_upload_id));
return $this->deleted();
}
catch (EntityNotFoundException $ex1)
{
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,225 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Repositories\ISponsorshipTypeRepository;
use App\Services\Model\ISponsorshipTypeService;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use ModelSerializers\SerializerRegistry;
use Exception;
/**
* Class OAuth2SponsorshipTypeApiController
* @package App\Http\Controllers
*/
final class OAuth2SponsorshipTypeApiController extends OAuth2ProtectedController
{
/**
* @var ISponsorshipTypeService
*/
private $service;
/**
* OAuth2SponsorshipTypeApiController constructor.
* @param ISponsorshipTypeRepository $repository
* @param ISummitRepository $summit_repository
* @param ISponsorshipTypeService $service
* @param IResourceServerContext $resource_server_context
*/
public function __construct
(
ISponsorshipTypeRepository $repository,
ISummitRepository $summit_repository,
ISponsorshipTypeService $service,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->repository = $repository;
$this->summit_repository = $summit_repository;
$this->service = $service;
}
use GetAll;
/**
* @return array
*/
protected function getFilterRules(): array
{
return [
'name' => ['==', '=@'],
'label' => ['==', '=@'],
'size' => ['==', '=@'],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules(): array
{
return [
'name' => 'sometimes|required|string',
'label' => 'sometimes|required|string',
'size' => 'sometimes|required|string',
];
}
/**
* @return array
*/
protected function getOrderRules(): array
{
return [
'id',
'name',
'order',
'label',
'size',
];
}
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function add()
{
try {
if (!Request::isJson()) return $this->error400();
$data = Input::json();
$payload = $data->all();
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, SponsorshipTypeValidationRulesFactory::build($payload));
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$sponsorship_type = $this->service->addSponsorShipType($payload);
return $this->created(SerializerRegistry::getInstance()->getSerializer($sponsorship_type)->serialize());
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function get($id)
{
try {
$sponsorship_type = $this->repository->getById($id);
if(is_null($sponsorship_type))
return $this->error404();
return $this->ok(SerializerRegistry::getInstance()->getSerializer($sponsorship_type)->serialize( Request::input('expand', '')));
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function update($id)
{
try {
if (!Request::isJson()) return $this->error400();
$data = Input::json();
$payload = $data->all();
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, SponsorshipTypeValidationRulesFactory::build($payload, true));
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$sponsorship_type = $this->service->updateSponsorShipType($id, $payload);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($sponsorship_type)->serialize());
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function delete($id)
{
try {
$this->service->deleteSponsorShipType($id);
return $this->deleted();
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,181 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Repositories\ISummitAccessLevelTypeRepository;
use App\Services\Model\ISummitAccessLevelTypeService;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use models\summit\Summit;
use models\utils\IBaseRepository;
use models\utils\IEntity;
/**
* Class OAuth2SummitAccessLevelTypeApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitAccessLevelTypeApiController
extends OAuth2ProtectedController
{
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* @var ISummitAccessLevelTypeService
*/
private $service;
use GetAllBySummit;
use GetSummitChildElementById;
use AddSummitChildElement;
use UpdateSummitChildElement;
use DeleteSummitChildElement;
/**
* @return array
*/
protected function getFilterRules():array
{
return [
'name' => ['=@', '=='],
'is_default' => [ '=='],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [
'name' => 'sometimes|required|string',
'is_default' => 'sometimes|required|boolean',
];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [
'id',
'name',
];
}
public function __construct
(
ISummitAccessLevelTypeRepository $repository,
ISummitRepository $summit_repository,
ISummitAccessLevelTypeService $service,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->repository = $repository;
$this->summit_repository = $summit_repository;
$this->service = $service;
}
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @return IResourceServerContext
*/
protected function getResourceServerContext(): IResourceServerContext
{
return $this->resource_server_context;
}
/**
* @return IBaseRepository
*/
protected function getRepository(): IBaseRepository
{
return $this->repository;
}
/**
* @param array $payload
* @return array
*/
protected function getAddValidationRules(array $payload): array
{
return AccessLevelTypeValidationRulesFactory::build($payload);
}
/**
* @param Summit $summit
* @param array $payload
* @return IEntity
* @throws EntityNotFoundException
* @throws ValidationException
*/
protected function addChild(Summit $summit, array $payload): IEntity
{
return $this->service->addAccessLevelType($summit, $payload);
}
/**
* @param Summit $summit
* @param $child_id
* @return IEntity|null
*/
protected function getChildFromSummit(Summit $summit, $child_id): ?IEntity
{
return $summit->getBadgeAccessLevelTypeById($child_id);
}
/**
* @param array $payload
* @return array
*/
function getUpdateValidationRules(array $payload): array
{
return AccessLevelTypeValidationRulesFactory::build($payload, true);
}
/**
* @param Summit $summit
* @param int $child_id
* @param array $payload
* @return IEntity
* @throws EntityNotFoundException
* @throws ValidationException
*/
protected function updateChild(Summit $summit, int $child_id, array $payload): IEntity
{
return $this->service->updateAccessLevelType($summit, $child_id, $payload);
}
/**
* @param Summit $summit
* @param $child_id
* @throws EntityNotFoundException
*/
protected function deleteChild(Summit $summit, $child_id): void
{
$this->service->deleteAccessLevelType($summit, $child_id);
}
}

View File

@ -11,7 +11,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Exceptions\HTTP403ForbiddenException;
use App\Models\Foundation\Main\IGroup;
use App\Models\Foundation\Summit\Registration\IBuildDefaultPaymentGatewayProfileStrategy;
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
@ -19,6 +22,7 @@ use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\main\SummitAdministratorPermissionGroup;
use models\oauth2\IResourceServerContext;
use models\summit\ConfirmationExternalOrderRequest;
use models\summit\IEventFeedbackRepository;
@ -28,8 +32,13 @@ use models\summit\ISummitRepository;
use ModelSerializers\ISerializerTypeSelector;
use ModelSerializers\SerializerRegistry;
use services\model\ISummitService;
use utils\PagingResponse;
use utils\Filter;
use utils\FilterElement;
use utils\Order;
use utils\OrderElement;
use Illuminate\Http\Request as LaravelRequest;
/**
* Class OAuth2SummitApiController
* @package App\Http\Controllers
@ -37,6 +46,11 @@ use Illuminate\Http\Request as LaravelRequest;
final class OAuth2SummitApiController extends OAuth2ProtectedController
{
/**
* @var IBuildDefaultPaymentGatewayProfileStrategy
*/
private $build_default_payment_gateway_profile_strategy;
/**
* @var ISummitService
*/
@ -70,6 +84,7 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
* @param IEventFeedbackRepository $event_feedback_repository
* @param ISummitService $summit_service
* @param ISerializerTypeSelector $serializer_type_selector
* @param IBuildDefaultPaymentGatewayProfileStrategy $build_default_payment_gateway_profile_strategy
* @param IResourceServerContext $resource_server_context
*/
public function __construct
@ -80,89 +95,185 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
IEventFeedbackRepository $event_feedback_repository,
ISummitService $summit_service,
ISerializerTypeSelector $serializer_type_selector,
IBuildDefaultPaymentGatewayProfileStrategy $build_default_payment_gateway_profile_strategy,
IResourceServerContext $resource_server_context
) {
)
{
parent::__construct($resource_server_context);
$this->repository = $summit_repository;
$this->speaker_repository = $speaker_repository;
$this->event_repository = $event_repository;
$this->repository = $summit_repository;
$this->speaker_repository = $speaker_repository;
$this->event_repository = $event_repository;
$this->event_feedback_repository = $event_feedback_repository;
$this->serializer_type_selector = $serializer_type_selector;
$this->summit_service = $summit_service;
$this->serializer_type_selector = $serializer_type_selector;
$this->build_default_payment_gateway_profile_strategy = $build_default_payment_gateway_profile_strategy;
$this->summit_service = $summit_service;
}
use ParametrizedGetAll;
/**
* @return mixed
*/
public function getSummits()
{
try {
$current_member = $this->resource_server_context->getCurrentUser();
$expand = Request::input('expand', '');
$fields = Request::input('fields', '');
$relations = Request::input('relations', '');
$relations = !empty($relations) ? explode(',', $relations) : [];
$fields = !empty($fields) ? explode(',', $fields) : [];
$summits = [];
foreach($this->repository->getAvailables() as $summit){
$summits[] = SerializerRegistry::getInstance()->getSerializer($summit)->serialize($expand, $fields, $relations);
}
$response = new PagingResponse
(
count($summits),
count($summits),
1,
1,
$summits
);
return $this->ok($response->toArray());
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
if (!is_null($current_member) && !$current_member->isAdmin() && $current_member->isSummitAdmin() && !$current_member->hasAllowedSummits()) {
return $this->error403(['message' => sprintf("Member %s has not permission for any Summit", $current_member->getId())]);
}
return $this->_getAll(
function () {
return [
'name' => ['=@', '=='],
'start_date' => ['==', '<', '>', '<=', '>='],
'end_date' => ['==', '<', '>', '<=', '>='],
'registration_begin_date' => ['==', '<', '>', '<=', '>='],
'registration_end_date' => ['==', '<', '>', '<=', '>='],
'ticket_types_count' => ['==', '<', '>', '<=', '>=', '<>'],
];
},
function () {
return [
'name' => 'sometimes|required|string',
'start_date' => 'sometimes|required|date_format:U',
'end_date' => 'sometimes|required_with:start_date|date_format:U|after:start_date',
'registration_begin_date' => 'sometimes|required|date_format:U',
'registration_end_date' => 'sometimes|required_with:start_date|date_format:U|after:registration_begin_date',
'ticket_types_count' => 'sometimes|required|integer'
];
},
function () {
return [
'id',
'name',
'begin_date',
'registration_begin_date'
];
},
function ($filter) use ($current_member) {
if ($filter instanceof Filter) {
$filter->addFilterCondition(FilterElement::makeEqual('available_on_api', '1'));
if (!is_null($current_member) && !$current_member->isAdmin() && $current_member->isSummitAdmin()) {
// filter only the ones that we are allowed to see
$filter->addFilterCondition
(
FilterElement::makeEqual
(
'summit_id',
$current_member->getAllAllowedSummitsIds(),
"OR"
)
);
}
}
return $filter;
},
function () {
return $this->serializer_type_selector->getSerializerType();
},
function () {
return new Order([
OrderElement::buildAscFor("begin_date"),
]);
},
function () {
return PHP_INT_MAX;
},
null,
[
'build_default_payment_gateway_profile_strategy' => $this->build_default_payment_gateway_profile_strategy
]
);
}
/**
* @return mixed
*/
public function getAllSummits(){
try {
public function getAllSummits()
{
$expand = Request::input('expand', '');
$fields = Request::input('fields', '');
$relations = Request::input('relations', '');
$current_member = $this->resource_server_context->getCurrentUser();
$relations = !empty($relations) ? explode(',', $relations) : [];
$fields = !empty($fields) ? explode(',', $fields) : [];
if (!is_null($current_member) && !$current_member->isAdmin() && $current_member->isSummitAdmin() && !$current_member->hasAllowedSummits()) {
return $this->error403(['message' => sprintf("Member %s has not permission for any Summit", $current_member->getId())]);
}
$summits = [];
return $this->_getAll(
function () {
return [
'name' => ['=@', '=='],
'start_date' => ['==', '<', '>', '=>', '>='],
'end_date' => ['==', '<', '>', '=>', '>='],
'registration_begin_date' => ['==', '<', '>', '=>', '>='],
'registration_end_date' => ['==', '<', '>', '=>', '>='],
'ticket_types_count' => ['==', '<', '>', '=>', '>=', '<>'],
'submission_begin_date' => ['==', '<', '>', '=>', '>='],
'submission_end_date' => ['==', '<', '>', '=>', '>='],
'selection_plan_enabled' => ['=='],
];
},
function () {
return [
'name' => 'sometimes|required|string',
'start_date' => 'sometimes|required|date_format:U',
'end_date' => 'sometimes|required_with:start_date|date_format:U|after:start_date',
'registration_begin_date' => 'sometimes|required|date_format:U',
'registration_end_date' => 'sometimes|required_with:start_date|date_format:U|after:registration_begin_date',
'ticket_types_count' => 'sometimes|required|integer',
'submission_begin_date' => 'sometimes|required|date_format:U',
'submission_end_date' => 'sometimes|required_with:submission_begin_date|date_format:U',
'selection_plan_enabled' => 'sometimes|required|boolean',
];
},
function () {
return [
'id',
'name',
'start_date',
'registration_begin_date'
];
},
function ($filter) use ($current_member) {
if ($filter instanceof Filter) {
if (!is_null($current_member) && !$current_member->isAdmin() && $current_member->isSummitAdmin()) {
// filter only the ones that we are allowed to see
$filter->addFilterCondition
(
FilterElement::makeEqual
(
'summit_id',
$current_member->getAllAllowedSummitsIds(),
"OR"
foreach($this->repository->getAllOrderedByBeginDate()as $summit){
$summits[] = SerializerRegistry::getInstance()->getSerializer($summit)->serialize($expand, $fields, $relations);
)
);
}
}
return $filter;
},
function () {
return $this->serializer_type_selector->getSerializerType();
}
$response = new PagingResponse
(
count($summits),
count($summits),
1,
1,
$summits
);
return $this->ok($response->toArray());
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
,
function () {
return new Order([
OrderElement::buildAscFor("begin_date"),
]);
},
function () {
return PHP_INT_MAX;
},
null,
[
'build_default_payment_gateway_profile_strategy' => $this->build_default_payment_gateway_profile_strategy
]
);
}
/**
@ -175,22 +286,29 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (!is_null($current_member) && !$current_member->isAdmin() && !$current_member->hasPermissionForOnGroup($summit, IGroup::SummitAdministrators))
return $this->error403(['message' => sprintf("Member %s has not permission for this Summit", $current_member->getId())]);
$serializer_type = $this->serializer_type_selector->getSerializerType();
return $this->ok(SerializerRegistry::getInstance()->getSerializer($summit, $serializer_type)->serialize($expand));
}
catch(HTTP403ForbiddenException $ex1){
return $this->ok
(
SerializerRegistry::getInstance()
->getSerializer($summit, $serializer_type)
->serialize($expand, [], [], [
'build_default_payment_gateway_profile_strategy' => $this->build_default_payment_gateway_profile_strategy
])
);
} catch (HTTP403ForbiddenException $ex1) {
Log::warning($ex1);
return $this->error403();
}
catch (Exception $ex) {
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return mixed
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getAllCurrentSummit()
{
@ -199,36 +317,62 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
try {
$summit = $this->repository->getCurrent();
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (!is_null($current_member) && !$current_member->isAdmin() && !$current_member->hasPermissionForOnGroup($summit, IGroup::SummitAdministrators))
return $this->error403(['message' => sprintf("Member %s has not permission for this Summit", $current_member->getId())]);
$serializer_type = $this->serializer_type_selector->getSerializerType();
return $this->ok(SerializerRegistry::getInstance()->getSerializer($summit, $serializer_type)->serialize($expand));
}
catch(HTTP403ForbiddenException $ex1){
return $this->ok
(
SerializerRegistry::getInstance()
->getSerializer($summit, $serializer_type)
->serialize($expand, [], [], [
'build_default_payment_gateway_profile_strategy' => $this->build_default_payment_gateway_profile_strategy
])
);
} catch (HTTP403ForbiddenException $ex1) {
Log::warning($ex1);
return $this->error403();
}
catch (Exception $ex) {
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function getAllSummitByIdOrSlug($id){
/**
* @param $id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getAllSummitByIdOrSlug($id)
{
$expand = Request::input('expand', '');
try {
$summit = $this->repository->getById(intval($id));
if(is_null($summit))
if (is_null($summit))
$summit = $this->repository->getBySlug(trim($id));
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (!is_null($current_member) && !$current_member->isAdmin() && !$current_member->hasPermissionForOnGroup($summit, IGroup::SummitAdministrators))
return $this->error403(['message' => sprintf("Member %s has not permission for this Summit", $current_member->getId())]);
$serializer_type = $this->serializer_type_selector->getSerializerType();
return $this->ok(SerializerRegistry::getInstance()->getSerializer($summit, $serializer_type)->serialize($expand));
}
catch(HTTP403ForbiddenException $ex1){
return $this->ok
(
SerializerRegistry::getInstance()
->getSerializer($summit, $serializer_type)
->serialize($expand, [], [],
[
'build_default_payment_gateway_profile_strategy' => $this->build_default_payment_gateway_profile_strategy
])
);
} catch (HTTP403ForbiddenException $ex1) {
Log::warning($ex1);
return $this->error403();
}
catch (Exception $ex) {
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
@ -237,15 +381,19 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
/**
* @return mixed
*/
public function addSummit(){
public function addSummit()
{
try {
if(!Request::isJson()) return $this->error400();
if (!Request::isJson()) return $this->error400();
$payload = Input::json()->all();
$rules = SummitValidationRulesFactory::build($payload);
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, $rules);
$validation = Validator::make($payload, $rules, $messages = [
'slug.required' => 'A Slug is required.',
'schedule_start_date.before_or_equal' => 'Show on schedule page needs to be after the start of the Show And Before of the Show End.',
]);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
@ -259,17 +407,13 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
$summit = $this->summit_service->addSummit($payload);
$serializer_type = $this->serializer_type_selector->getSerializerType();
return $this->created(SerializerRegistry::getInstance()->getSerializer($summit, $serializer_type)->serialize());
}
catch (ValidationException $ex1) {
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412([$ex1->getMessage()]);
}
catch(EntityNotFoundException $ex2)
{
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(['message'=> $ex2->getMessage()]);
}
catch (Exception $ex) {
return $this->error404(['message' => $ex2->getMessage()]);
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
@ -279,10 +423,11 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
* @param $summit_id
* @return mixed
*/
public function updateSummit($summit_id){
public function updateSummit($summit_id)
{
try {
if(!Request::isJson()) return $this->error400();
if (!Request::isJson()) return $this->error400();
$payload = Input::json()->all();
$rules = SummitValidationRulesFactory::build($payload, true);
@ -298,20 +443,23 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
);
}
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (!is_null($current_member) && !$current_member->isAdmin() && !$current_member->hasPermissionForOnGroup($summit, IGroup::SummitAdministrators))
return $this->error403(['message' => sprintf("Member %s has not permission for this Summit", $current_member->getId())]);
$summit = $this->summit_service->updateSummit($summit_id, $payload);
$serializer_type = $this->serializer_type_selector->getSerializerType();
return $this->updated(SerializerRegistry::getInstance()->getSerializer($summit, $serializer_type)->serialize());
}
catch (ValidationException $ex1) {
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412([$ex1->getMessage()]);
}
catch(EntityNotFoundException $ex2)
{
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(['message'=> $ex2->getMessage()]);
}
catch (Exception $ex) {
return $this->error404(['message' => $ex2->getMessage()]);
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
@ -321,23 +469,20 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
* @param $summit_id
* @return mixed
*/
public function deleteSummit($summit_id){
public function deleteSummit($summit_id)
{
try {
$this->summit_service->deleteSummit($summit_id);
return $this->deleted();
}
catch (ValidationException $ex1) {
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412([$ex1->getMessage()]);
}
catch(EntityNotFoundException $ex2)
{
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(['message'=> $ex2->getMessage()]);
}
catch (Exception $ex) {
return $this->error404(['message' => $ex2->getMessage()]);
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
@ -354,40 +499,37 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
$current_member_id = is_null($current_member)? null : $current_member->getId();
$current_member = $this->resource_server_context->getCurrentUser();
$current_member_id = is_null($current_member) ? null : $current_member->getId();
$last_event_id = Request::input('last_event_id', null);
$from_date = Request::input('from_date', null);
$limit = Request::input('limit', 25);
$from_date = Request::input('from_date', null);
$limit = Request::input('limit', 25);
$rules = [
'last_event_id' => 'sometimes|required|integer',
'from_date' => 'sometimes|required|integer',
'limit' => 'sometimes|required|integer',
'from_date' => 'sometimes|required|integer',
'limit' => 'sometimes|required|integer',
];
$data = [];
if (!is_null($last_event_id))
{
if (!is_null($last_event_id)) {
$data['last_event_id'] = $last_event_id;
}
if (!is_null($from_date))
{
if (!is_null($from_date)) {
$data['from_date'] = $from_date;
}
if(!is_null($limit)){
if (!is_null($limit)) {
$data['limit'] = $limit;
}
// Creates a Validator instance and validates the data.
$validation = Validator::make($data, $rules);
if ($validation->fails())
{
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
@ -396,8 +538,7 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
);
}
if (!is_null($from_date))
{
if (!is_null($from_date)) {
$from_date = new \DateTime("@$from_date", new \DateTimeZone("UTC"));
}
@ -421,9 +562,7 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
)*/
$list
);
}
catch (Exception $ex)
{
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
@ -434,22 +573,20 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
* @param $external_order_id
* @return mixed
*/
public function getExternalOrder($summit_id, $external_order_id){
public function getExternalOrder($summit_id, $external_order_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$order = $this->summit_service->getExternalOrder($summit, $external_order_id);
return $this->ok($order);
}
catch (EntityNotFoundException $ex1) {
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404(array('message' => $ex1->getMessage()));
}
catch (ValidationException $ex2) {
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (Exception $ex) {
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
@ -461,7 +598,8 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
* @param $external_attendee_id
* @return mixed
*/
public function confirmExternalOrderAttendee($summit_id, $external_order_id, $external_attendee_id){
public function confirmExternalOrderAttendee($summit_id, $external_order_id, $external_attendee_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
@ -480,31 +618,36 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
);
return $this->ok(SerializerRegistry::getInstance()->getSerializer($attendee)->serialize());
}
catch (EntityNotFoundException $ex1) {
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404(array('message' => $ex1->getMessage()));
}
catch (ValidationException $ex2) {
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (\HTTP401UnauthorizedException $ex3) {
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
return $this->error401();
}
catch (Exception $ex) {
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->repository;
}
/**
* @param LaravelRequest $request
* @param $summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function addSummitLogo(LaravelRequest $request, $summit_id){
public function addSummitLogo(LaravelRequest $request, $summit_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
@ -515,6 +658,10 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
return $this->error412(array('file param not set!'));
}
$current_member = $this->resource_server_context->getCurrentUser();
if (!is_null($current_member) && !$current_member->isAdmin() && !$current_member->hasPermissionForOnGroup($summit, IGroup::SummitAdministrators))
return $this->error403(['message' => sprintf("Member %s has not permission for this Summit", $current_member->getId())]);
$photo = $this->summit_service->addSummitLogo($summit_id, $file);
return $this->created(SerializerRegistry::getInstance()->getSerializer($photo)->serialize());
@ -538,12 +685,17 @@ final class OAuth2SummitApiController extends OAuth2ProtectedController
* @param $summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function deleteSummitLogo($summit_id){
public function deleteSummitLogo($summit_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (!is_null($current_member) && !$current_member->isAdmin() && !$current_member->hasPermissionForOnGroup($summit, IGroup::SummitAdministrators))
return $this->error403(['message' => sprintf("Member %s has not permission for this Summit", $current_member->getId())]);
$this->summit_service->deleteSummitLogo($summit_id);
return $this->deleted();

View File

@ -12,21 +12,25 @@
* limitations under the License.
**/
use App\Services\Model\IAttendeeService;
use App\Services\Model\ISummitOrderService;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\main\IMemberRepository;
use models\main\Member;
use models\oauth2\IResourceServerContext;
use models\summit\IEventFeedbackRepository;
use models\summit\ISpeakerRepository;
use models\summit\ISummitAttendeeRepository;
use models\summit\ISummitEventRepository;
use models\summit\ISummitRepository;
use models\summit\SummitAttendee;
use ModelSerializers\SerializerRegistry;
use services\model\ISummitService;
use utils\Filter;
use utils\FilterElement;
use utils\FilterParser;
use utils\OrderParser;
use Illuminate\Support\Facades\Input;
@ -38,6 +42,8 @@ use utils\PagingInfo;
*/
final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
{
use GetAndValidateJsonPayload;
/**
* @var ISummitService
*/
@ -64,15 +70,23 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
private $event_feedback_repository;
/**
* @var ISummitAttendeeRepository
* @var ISummitRepository
*/
private $attendee_repository;
private $summit_repository;
/**
* @var IMemberRepository
*/
private $member_repository;
/**
* @var ISummitOrderService
*/
private $summit_order_service;
use ParametrizedGetAll;
/**
* OAuth2SummitAttendeesApiController constructor.
* @param ISummitAttendeeRepository $attendee_repository
@ -83,6 +97,7 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
* @param IMemberRepository $member_repository
* @param ISummitService $summit_service
* @param IAttendeeService $attendee_service
* @param ISummitOrderService $summit_order_service
* @param IResourceServerContext $resource_server_context
*/
public function __construct
@ -95,17 +110,19 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
IMemberRepository $member_repository,
ISummitService $summit_service,
IAttendeeService $attendee_service,
ISummitOrderService $summit_order_service,
IResourceServerContext $resource_server_context
) {
parent::__construct($resource_server_context);
$this->attendee_repository = $attendee_repository;
$this->repository = $summit_repository;
$this->summit_repository = $summit_repository;
$this->repository = $attendee_repository;
$this->speaker_repository = $speaker_repository;
$this->event_repository = $event_repository;
$this->event_feedback_repository = $event_feedback_repository;
$this->member_repository = $member_repository;
$this->summit_service = $summit_service;
$this->attendee_service = $attendee_service;
$this->summit_order_service = $summit_order_service;
}
/**
@ -121,7 +138,7 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$type = CheckAttendeeStrategyFactory::Me;
@ -150,10 +167,10 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = $this->attendee_repository->getById($attendee_id);
$attendee = $this->repository->getById($attendee_id);
if(is_null($attendee)) return $this->error404();
return $this->ok
@ -189,7 +206,7 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = CheckAttendeeStrategyFactory::build(CheckAttendeeStrategyFactory::Own, $this->resource_server_context)->check($attendee_id, $summit);
@ -225,7 +242,7 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = CheckAttendeeStrategyFactory::build(CheckAttendeeStrategyFactory::Own, $this->resource_server_context)->check($attendee_id, $summit);
@ -238,7 +255,7 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
return $this->error412($ex1->getMessages());
}
catch (EntityNotFoundException $ex2)
{
@ -267,7 +284,7 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = CheckAttendeeStrategyFactory::build(CheckAttendeeStrategyFactory::Own, $this->resource_server_context)->check($attendee_id, $summit);
@ -281,7 +298,7 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
return $this->error412($ex1->getMessages());
}
catch (EntityNotFoundException $ex2)
{
@ -309,7 +326,7 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
public function deleteEventRSVP($summit_id, $attendee_id, $event_id){
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$event = $summit->getScheduleEvent(intval($event_id));
@ -329,7 +346,7 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
return $this->error412($ex1->getMessages());
}
catch (EntityNotFoundException $ex2)
{
@ -353,94 +370,114 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
*/
public function getAttendeesBySummit($summit_id){
$values = Input::all();
$rules = [
'page' => 'integer|min:1',
'per_page' => 'required_with:page|integer|min:5|max:100',
];
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
// default values
$page = 1;
$per_page = 5;
if (Input::has('page')) {
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
$filter = null;
if (Input::has('filter')) {
$filter = FilterParser::parse(Input::get('filter'), [
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
return $this->_getAll(
function(){
return [
'first_name' => ['=@', '=='],
'last_name' => ['=@', '=='],
'full_name' => ['=@', '=='],
'company' => ['=@', '=='],
'email' => ['=@', '=='],
'external_order_id' => ['=@', '=='],
'external_attendee_id' => ['=@', '=='],
]);
}
$order = null;
if (Input::has('order'))
];
},
function(){
return [
'first_name' => 'sometimes|string',
'last_name' => 'sometimes|string',
'full_name' => 'sometimes|string',
'company' => 'sometimes|string',
'email' => 'sometimes|string',
'external_order_id' => 'sometimes|string',
'external_attendee_id' => 'sometimes|string',
];
},
function()
{
$order = OrderParser::parse(Input::get('order'), [
return [
'first_name',
'last_name',
'company',
'id',
'external_order_id',
];
},
function($filter) use($summit){
if($filter instanceof Filter){
$filter->addFilterCondition(FilterElement::makeEqual('summit_id', $summit->getId()));
}
return $filter;
},
function(){
return SerializerRegistry::SerializerType_Private;
}
);
}
/**
* @param $summit_id
* @return mixed
*/
public function getAttendeesBySummitCSV($summit_id){
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
return $this->_getAllCSV(
function(){
return [
'first_name' => ['=@', '=='],
'last_name' => ['=@', '=='],
'full_name' => ['=@', '=='],
'email' => ['=@', '=='],
'external_order_id' => ['=@', '=='],
'company' => ['=@', '=='],
'external_attendee_id' => ['=@', '=='],
];
},
function(){
return [
'first_name' => 'sometimes|string',
'last_name' => 'sometimes|string',
'full_name' => 'sometimes|string',
'email' => 'sometimes|string',
'external_order_id' => 'sometimes|string',
'external_attendee_id' => 'sometimes|string',
'company' => 'sometimes|string',
];
},
function()
{
return [
'first_name',
'last_name',
'id',
'external_order_id',
]);
}
if(is_null($filter)) $filter = new Filter();
$data = $this->attendee_repository->getBySummit($summit, new PagingInfo($page, $per_page), $filter, $order);
return $this->ok
(
$data->toArray
(
Request::input('expand', ''),
[],
[],
[ 'serializer_type' => SerializerRegistry::SerializerType_Private ]
)
);
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch(\HTTP401UnauthorizedException $ex3)
{
Log::warning($ex3);
return $this->error401();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
'company',
];
},
function($filter) use($summit){
if($filter instanceof Filter){
$filter->addFilterCondition(FilterElement::makeEqual('summit_id', $summit->getId()));
}
return $filter;
},
function(){
return SerializerRegistry::SerializerType_CSV;
},
function(){
return [];
},
function(){
return [];
},
'attendees-'
);
}
/**
@ -452,15 +489,19 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
if(!Request::isJson()) return $this->error400();
$data = Input::json();
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$rules = [
'member_id' => 'required|integer',
'shared_contact_info' => 'sometimes|boolean',
'summit_hall_checked_in' => 'sometimes|boolean',
'summit_hall_checked_in_date' => 'sometimes|date_format:U',
'first_name' => 'required_without:member_id|string|max:255',
'surname' => 'required_without:member_id|string|max:255',
'company' => 'sometimes|string|max:255',
'email' => 'required_without:member_id|string|max:255|email',
'member_id' => 'required_without_all:email|integer',
'extra_questions' => 'sometimes|order_extra_question_dto_array',
];
// Creates a Validator instance and validates the data.
@ -481,7 +522,7 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
return $this->error412($ex1->getMessages());
}
catch(EntityNotFoundException $ex2)
{
@ -503,10 +544,10 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
{
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = $this->attendee_repository->getById($attendee_id);
$attendee = $this->repository->getById($attendee_id);
if(is_null($attendee)) return $this->error404();
$this->attendee_service->deleteAttendee($summit, $attendee->getIdentifier());
@ -534,17 +575,23 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
if(!Request::isJson()) return $this->error400();
$data = Input::json();
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = $this->attendee_repository->getById($attendee_id);
$attendee = $this->repository->getById($attendee_id);
if(is_null($attendee)) return $this->error404();
$rules = [
'member_id' => 'required|integer',
'shared_contact_info' => 'sometimes|boolean',
'summit_hall_checked_in' => 'sometimes|boolean',
'summit_hall_checked_in_date' => 'sometimes|date_format:U',
'disclaimer_accepted_date' => 'sometimes|date_format:U',
'first_name' => 'required_without:member_id|string|max:255',
'surname' => 'required_without:member_id|string|max:255',
'company' => 'sometimes|string|max:255',
'email' => 'required_without:member_id|string|max:255|email',
'member_id' => 'required_without_all:first_name,surname,email|integer',
'extra_questions' => 'sometimes|order_extra_question_dto_array',
];
// Creates a Validator instance and validates the data.
@ -565,7 +612,7 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
return $this->error412($ex1->getMessages());
}
catch(EntityNotFoundException $ex2)
{
@ -588,20 +635,22 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
if(!Request::isJson()) return $this->error400();
$data = Input::json();
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = $this->attendee_repository->getById($attendee_id);
if(is_null($attendee)) return $this->error404();
$attendee = $this->repository->getById($attendee_id);
if(is_null($attendee) || !$attendee instanceof SummitAttendee) return $this->error404();
$rules = [
'ticket_type_id' => 'required|integer',
'external_order_id' => 'required|string',
'external_attendee_id' => 'required|string',
'promo_code' => 'nullable|string',
'external_order_id' => 'nullable|string',
'external_attendee_id' => 'nullable|string',
];
$payload = $data->all();
// Creates a Validator instance and validates the data.
$validation = Validator::make($data->all(), $rules);
$validation = Validator::make($payload, $rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
@ -612,13 +661,21 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
);
}
$ticket = $this->attendee_service->addAttendeeTicket($attendee, $data->all());
$payload['owner_email'] = $attendee->getEmail();
$payload['owner_first_name'] = $attendee->getFirstName();
$payload['owner_last_name'] = $attendee->getSurname();
$payload['owner_company'] = $attendee->getCompanyName();
if($attendee->hasMember())
$payload['owner_id'] = $attendee->getMemberId();
$ticket = $this->summit_order_service->createOrderSingleTicket($summit, $payload);
return $this->created(SerializerRegistry::getInstance()->getSerializer($ticket)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
return $this->error412($ex1->getMessages());
}
catch(EntityNotFoundException $ex2)
{
@ -639,10 +696,10 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
*/
public function deleteAttendeeTicket($summit_id, $attendee_id, $ticket_id){
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = $this->attendee_repository->getById($attendee_id);
$attendee = $this->repository->getById($attendee_id);
if(is_null($attendee)) return $this->error404();
$ticket = $this->attendee_service->deleteAttendeeTicket($attendee, $ticket_id);
@ -651,7 +708,7 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
return $this->error412($ex1->getMessages());
}
catch(EntityNotFoundException $ex2)
{
@ -671,25 +728,25 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
* @param $other_member_id
* @return mixed
*/
public function reassignAttendeeTicket($summit_id, $attendee_id, $ticket_id, $other_member_id){
public function reassignAttendeeTicketByMember($summit_id, $attendee_id, $ticket_id, $other_member_id){
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = $this->attendee_repository->getById($attendee_id);
if(is_null($attendee)) return $this->error404();
$attendee = $this->repository->getById($attendee_id);
if(is_null($attendee) || !$attendee instanceof SummitAttendee) return $this->error404();
$other_member = $this->member_repository->getById($other_member_id);
if(is_null($other_member)) return $this->error404();
if(is_null($other_member) || !$other_member instanceof Member) return $this->error404();
$ticket = $this->attendee_service->reassignAttendeeTicket($summit, $attendee, $other_member, $ticket_id);
$ticket = $this->attendee_service->reassignAttendeeTicketByMember($summit, $attendee, $other_member, intval($ticket_id));
return $this->updated(SerializerRegistry::getInstance()->getSerializer($ticket)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
return $this->error412($ex1->getMessages());
}
catch(EntityNotFoundException $ex2)
{
@ -701,4 +758,53 @@ final class OAuth2SummitAttendeesApiController extends OAuth2ProtectedController
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $attendee_id
* @param $ticket_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function reassignAttendeeTicket($summit_id, $attendee_id, $ticket_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$attendee = $this->repository->getById($attendee_id);
if(is_null($attendee) || !$attendee instanceof SummitAttendee) return $this->error404();
$payload = $this->getJsonPayload([
'attendee_first_name' => 'nullable|string|max:255',
'attendee_last_name' => 'nullable|string|max:255',
'attendee_email' => 'required|string|max:255|email',
'attendee_company' => 'nullable|string|max:255',
'extra_questions' => 'sometimes|order_extra_question_dto_array'
]);
$ticket = $this->attendee_service->reassignAttendeeTicket($summit, $attendee, intval($ticket_id), $payload);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($ticket)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412($ex1->getMessages());
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
}

View File

@ -0,0 +1,181 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Repositories\ISummitBadgeFeatureTypeRepository;
use App\Services\Model\ISummitBadgeFeatureTypeService;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use models\summit\Summit;
use models\utils\IBaseRepository;
use models\utils\IEntity;
/**
* Class OAuth2SummitBadgeFeatureTypeApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitBadgeFeatureTypeApiController
extends OAuth2ProtectedController
{
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* @var ISummitBadgeFeatureTypeService
*/
private $service;
/**
* OAuth2SummitBadgeFeatureTypeApiController constructor.
* @param ISummitBadgeFeatureTypeRepository $repository
* @param ISummitRepository $summit_repository
* @param ISummitBadgeFeatureTypeService $service
* @param IResourceServerContext $resource_server_context
*/
public function __construct
(
ISummitBadgeFeatureTypeRepository $repository,
ISummitRepository $summit_repository,
ISummitBadgeFeatureTypeService $service,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->repository = $repository;
$this->summit_repository = $summit_repository;
$this->service = $service;
}
/**
* @return array
*/
protected function getFilterRules():array
{
return [
'name' => ['=@', '=='],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [
'name' => 'sometimes|required|string',
];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [
'id',
'name',
];
}
use GetAllBySummit;
use GetSummitChildElementById;
use AddSummitChildElement;
use UpdateSummitChildElement;
use DeleteSummitChildElement;
/**
* @param array $payload
* @return array
*/
function getAddValidationRules(array $payload): array
{
return SummitBadgeFeatureTypeValidationRulesFactory::build($payload);
}
/**
* @param Summit $summit
* @param array $payload
* @return IEntity
*/
protected function addChild(Summit $summit, array $payload): IEntity
{
return $this->service->addBadgeFeatureType($summit, $payload);
}
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @return IResourceServerContext
*/
protected function getResourceServerContext(): IResourceServerContext
{
return $this->resource_server_context;
}
/**
* @return IBaseRepository
*/
protected function getRepository(): IBaseRepository
{
return $this->repository;
}
/**
* @param Summit $summit
* @param $child_id
* @return void
*/
protected function deleteChild(Summit $summit, $child_id): void
{
$this->service->deleteBadgeFeatureType($summit, $child_id);
}
/**
* @param Summit $summit
* @param $child_id
* @return IEntity|null
*/
protected function getChildFromSummit(Summit $summit,$child_id): ?IEntity
{
return $summit->getFeatureTypeById($child_id);
}
/**
* @param array $payload
* @return array
*/
function getUpdateValidationRules(array $payload): array
{
return SummitBadgeFeatureTypeValidationRulesFactory::build($payload, true);
}
/**
* @param Summit $summit
* @param int $child_id
* @param array $payload
* @return IEntity
*/
protected function updateChild(Summit $summit, int $child_id, array $payload): IEntity
{
return $this->service->updateBadgeFeatureType($summit, $child_id, $payload);
}
}

View File

@ -0,0 +1,330 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Exceptions\HTTP403ForbiddenException;
use App\Http\Utils\EpochCellFormatter;
use App\Services\Model\ISponsorBadgeScanService;
use Illuminate\Support\Facades\Input;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\ISponsorBadgeScanRepository;
use models\summit\ISummitRepository;
use models\summit\Summit;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
use utils\Filter;
use utils\FilterElement;
/**
* Class OAuth2SummitBadgeScanApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitBadgeScanApiController
extends OAuth2ProtectedController
{
/**
* @var ISponsorBadgeScanService
*/
private $service;
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* OAuth2SummitBadgeScanApiController constructor.
* @param ISponsorBadgeScanRepository $repository
* @param ISummitRepository $summit_repository
* @param IResourceServerContext $resource_server_context
* @param ISponsorBadgeScanService $service
*/
public function __construct
(
ISponsorBadgeScanRepository $repository,
ISummitRepository $summit_repository,
IResourceServerContext $resource_server_context,
ISponsorBadgeScanService $service
)
{
parent::__construct($resource_server_context);
$this->repository = $repository;
$this->summit_repository = $summit_repository;
$this->service = $service;
}
use AddSummitChildElement;
/**
* @param array $payload
* @return array
*/
function getAddValidationRules(array $payload): array
{
return [
'qr_code' => 'required|string',
'scan_date' => 'required|date_format:U',
];
}
/**
* @param Summit $summit
* @param array $payload
* @return IEntity
*/
protected function addChild(Summit $summit, array $payload): IEntity
{
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) throw new HTTP403ForbiddenException();
return $this->service->addBadgeScan($summit, $current_member, $payload);
}
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
// traits
use ParametrizedGetAll;
/**
* @param $summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getAllMyBadgeScans($summit_id){
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
return $this->_getAll(
function(){
return [
'attendee_first_name' => ['=@', '=='],
'attendee_last_name' => ['=@', '=='],
'attendee_full_name' => ['=@', '=='],
'attendee_email' => ['=@', '=='],
'ticket_number' => ['=@', '=='],
'order_number' => ['=@', '=='],
];
},
function(){
return [
'attendee_first_name' => 'sometimes|string',
'attendee_last_name' => 'sometimes|string',
'attendee_full_name' => 'sometimes|string',
'attendee_email' => 'sometimes|string',
'ticket_number' => 'sometimes|string',
'order_number' => 'sometimes|string',
];
},
function()
{
return [
'id',
'scan_date'
];
},
function($filter) use($summit, $current_member){
if($filter instanceof Filter){
$filter->addFilterCondition(FilterElement::makeEqual('summit_id', $summit->getId()));
$filter->addFilterCondition(FilterElement::makeEqual('user_id', $current_member->getId()));
}
return $filter;
},
function(){
return SerializerRegistry::SerializerType_Public;
}
);
}
/**
* @param $summit_id
* @return mixed
*/
public function getAllBySummit($summit_id){
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$sponsor = null;
if(!$current_member->isAdmin()){
$sponsor = $current_member->getSponsorBySummit($summit);
if(is_null($sponsor)){
return $this->error403();
}
}
return $this->_getAll(
function(){
return [
'attendee_first_name' => ['=@', '=='],
'attendee_last_name' => ['=@', '=='],
'attendee_full_name' => ['=@', '=='],
'attendee_email' => ['=@', '=='],
'ticket_number' => ['=@', '=='],
'order_number' => ['=@', '=='],
'sponsor_id' => ['=='],
'attendee_company' => ['=@', '=='],
];
},
function(){
return [
'attendee_first_name' => 'sometimes|string',
'attendee_last_name' => 'sometimes|string',
'attendee_full_name' => 'sometimes|string',
'attendee_email' => 'sometimes|string',
'ticket_number' => 'sometimes|string',
'order_number' => 'sometimes|string',
'sponsor_id' => 'sometimes|integer',
'attendee_company' => 'sometimes|string',
];
},
function()
{
return [
'id',
'attendee_full_name',
'attendee_email',
'attendee_first_name',
'attendee_last_name',
'attendee_company',
'scan_date'
];
},
function($filter) use($summit, $sponsor){
if($filter instanceof Filter){
$filter->addFilterCondition(FilterElement::makeEqual('summit_id', $summit->getId()));
if(!is_null($sponsor)){
$filter->addFilterCondition(FilterElement::makeEqual('sponsor_id', $sponsor->getId()));
}
}
return $filter;
},
function(){
return SerializerRegistry::SerializerType_Public;
}
);
}
/**
* @param $summit_id
* @return mixed
*/
public function getAllBySummitCSV($summit_id){
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$sponsor = null;
if(!$current_member->isAdmin()){
$sponsor = $current_member->getSponsorBySummit($summit);
if(is_null($sponsor)){
return $this->error403();
}
}
return $this->_getAllCSV(
function(){
return [
'attendee_first_name' => ['=@', '=='],
'attendee_last_name' => ['=@', '=='],
'attendee_full_name' => ['=@', '=='],
'attendee_email' => ['=@', '=='],
'ticket_number' => ['=@', '=='],
'order_number' => ['=@', '=='],
'sponsor_id' => ['=='],
'attendee_company' => ['=@', '=='],
];
},
function(){
return [
'attendee_first_name' => 'sometimes|string',
'attendee_last_name' => 'sometimes|string',
'attendee_full_name' => 'sometimes|string',
'attendee_email' => 'sometimes|string',
'ticket_number' => 'sometimes|string',
'order_number' => 'sometimes|string',
'sponsor_id' => 'sometimes|integer',
'attendee_company' => 'sometimes|string',
];
},
function()
{
return [
'id',
'attendee_full_name',
'attendee_email',
'attendee_first_name',
'attendee_last_name',
'attendee_company',
'scan_date'
];
},
function($filter) use($summit, $sponsor){
if($filter instanceof Filter){
$filter->addFilterCondition(FilterElement::makeEqual('summit_id', $summit->getId()));
if(!is_null($sponsor)){
$filter->addFilterCondition(FilterElement::makeEqual('sponsor_id', $sponsor->getId()));
}
}
return $filter;
},
function(){
return SerializerRegistry::SerializerType_CSV;
},
function(){
return [
'scan_date' => new EpochCellFormatter(),
];
},
function(){
$allowed_columns = [
'scan_date',
'qr_code',
'sponsor_id',
'user_id',
'badge_id',
'attendee_first_name',
'attendee_last_name',
'attendee_email',
'attendee_company'
];
$columns_param = Input::get("columns", "");
$columns = [];
if(!empty($columns_param))
$columns = explode(',', $columns_param);
$diff = array_diff($columns, $allowed_columns);
if(count($diff) > 0){
throw new ValidationException(sprintf("columns %s are not allowed!", implode(",", $diff)));
}
if(empty($columns))
$columns = $allowed_columns;
return $columns;
},
'attendees-badge-scans-'
);
}
}

View File

@ -0,0 +1,301 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Repositories\ISummitBadgeTypeRepository;
use App\Services\Model\ISummitBadgeTypeService;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use models\summit\Summit;
use models\utils\IBaseRepository;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
use Exception;
/**
* Class OAuth2SummitBadgeTypeApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitBadgeTypeApiController extends OAuth2ProtectedController
{
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* @var ISummitBadgeTypeService
*/
private $service;
/**
* OAuth2SummitBadgeFeatureTypeApiController constructor.
* @param ISummitBadgeTypeRepository $repository
* @param ISummitRepository $summit_repository
* @param ISummitBadgeTypeService $service
* @param IResourceServerContext $resource_server_context
*/
public function __construct
(
ISummitBadgeTypeRepository $repository,
ISummitRepository $summit_repository,
ISummitBadgeTypeService $service,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->repository = $repository;
$this->summit_repository = $summit_repository;
$this->service = $service;
}
/**
* @return array
*/
protected function getFilterRules():array
{
return [
'name' => ['=@', '=='],
'is_default' => [ '=='],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [
'name' => 'sometimes|required|string',
'is_default' => 'sometimes|required|boolean',
];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [
'id',
'name',
];
}
use GetAllBySummit;
use GetSummitChildElementById;
use AddSummitChildElement;
use UpdateSummitChildElement;
use DeleteSummitChildElement;
/**
* @param array $payload
* @return array
*/
function getAddValidationRules(array $payload): array
{
return SummitBadgeTypeValidationRulesFactory::build($payload);
}
/**
* @param Summit $summit
* @param array $payload
* @return IEntity
*/
protected function addChild(Summit $summit, array $payload): IEntity
{
return $this->service->addBadgeType($summit, $payload);
}
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @return IResourceServerContext
*/
protected function getResourceServerContext(): IResourceServerContext
{
return $this->resource_server_context;
}
/**
* @return IBaseRepository
*/
protected function getRepository(): IBaseRepository
{
return $this->repository;
}
/**
* @param Summit $summit
* @param $child_id
* @return void
*/
protected function deleteChild(Summit $summit, $child_id): void
{
$this->service->deleteBadgeType($summit, $child_id);
}
protected function getChildFromSummit(Summit $summit, $child_id): ?IEntity
{
return $summit->getBadgeTypeById($child_id);
}
/**
* @param array $payload
* @return array
*/
function getUpdateValidationRules(array $payload): array
{
return SummitBadgeTypeValidationRulesFactory::build($payload, true);
}
/**
* @param Summit $summit
* @param int $child_id
* @param array $payload
* @return IEntity
*/
protected function updateChild(Summit $summit, int $child_id, array $payload): IEntity
{
return $this->service->updateBadgeType($summit, $child_id, $payload);
}
/**
* @param $summit_id
* @param $badge_type_id
* @param $access_level_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function addAccessLevelToBadgeType($summit_id, $badge_type_id, $access_level_id){
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$child = $this->service->addAccessLevelToBadgeType($summit, $badge_type_id, $access_level_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($child)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $badge_type_id
* @param $access_level_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function removeAccessLevelFromBadgeType($summit_id, $badge_type_id, $access_level_id){
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$child = $this->service->removeAccessLevelFromBadgeType($summit, $badge_type_id, $access_level_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($child)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $badge_type_id
* @param $feature_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function addFeatureToBadgeType($summit_id, $badge_type_id, $feature_id){
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$child = $this->service->addFeatureToBadgeType($summit, $badge_type_id, $feature_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($child)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $badge_type_id
* @param $feature_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function removeFeatureFromBadgeType($summit_id, $badge_type_id, $feature_id){
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$child = $this->service->removeFeatureFromBadgeType($summit, $badge_type_id, $feature_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($child)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,166 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Repositories\ISummitAttendeeBadgeRepository;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use ModelSerializers\SerializerRegistry;
use utils\Filter;
use utils\FilterElement;
/**
* Class OAuth2SummitBadgesApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitBadgesApiController extends OAuth2ProtectedController
{
/**
* @var ISummitRepository
*/
private $summit_repository;
// traits
use ParametrizedGetAll;
public function __construct
(
ISummitAttendeeBadgeRepository $repository,
ISummitRepository $summit_repository,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->repository = $repository;
$this->summit_repository = $summit_repository;
}
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @param $summit_id
* @return mixed
*/
public function getAllBySummit($summit_id){
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
return $this->_getAll(
function(){
return [
'owner_first_name' => ['=@', '=='],
'owner_last_name' => ['=@', '=='],
'owner_full_name' => ['=@', '=='],
'owner_email' => ['=@', '=='],
'ticket_number' => ['=@', '=='],
'order_number' => ['=@', '=='],
];
},
function(){
return [
'owner_first_name' => 'sometimes|string',
'owner_last_name' => 'sometimes|string',
'owner_full_name' => 'sometimes|string',
'owner_email' => 'sometimes|string',
'ticket_number' => 'sometimes|string',
'order_number' => 'sometimes|string',
];
},
function()
{
return [
'id',
'ticket_number',
'order_number',
'created'
];
},
function($filter) use($summit){
if($filter instanceof Filter){
$filter->addFilterCondition(FilterElement::makeEqual('summit_id', $summit->getId()));
}
return $filter;
},
function(){
return SerializerRegistry::SerializerType_Private;
}
);
}
/**
* @param $summit_id
* @return mixed
*/
public function getAllBySummitCSV($summit_id){
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
return $this->_getAllCSV(
function(){
return [
'owner_first_name' => ['=@', '=='],
'owner_last_name' => ['=@', '=='],
'owner_full_name' => ['=@', '=='],
'owner_email' => ['=@', '=='],
'ticket_number' => ['=@', '=='],
'order_number' => ['=@', '=='],
];
},
function(){
return [
'owner_first_name' => 'sometimes|string',
'owner_last_name' => 'sometimes|string',
'owner_full_name' => 'sometimes|string',
'owner_email' => 'sometimes|string',
'ticket_number' => 'sometimes|string',
'order_number' => 'sometimes|string',
];
},
function()
{
return [
'id',
'ticket_number',
'order_number',
'created'
];
},
function($filter) use($summit){
if($filter instanceof Filter){
$filter->addFilterCondition(FilterElement::makeEqual('summit_id', $summit->getId()));
}
return $filter;
},
function(){
return SerializerRegistry::SerializerType_Private;
},
function(){
return [];
},
function(){
return [];
},
'attendees-badges-'
);
}
}

View File

@ -0,0 +1,330 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Repositories\ISummitDocumentRepository;
use App\Services\Model\ISummitDocumentService;
use Illuminate\Http\Request as LaravelRequest;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use libs\utils\HTMLCleaner;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use models\summit\Summit;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
/**
* Class OAuth2SummitDocumentsApiController
* @package App\Http\Controllers
*/
class OAuth2SummitDocumentsApiController extends OAuth2ProtectedController
{
// traits
use GetAllBySummit;
use GetSummitChildElementById;
use DeleteSummitChildElement;
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* @var ISummitDocumentService
*/
private $service;
/**
* OAuth2SummitDocumentsApiController constructor.
* @param ISummitDocumentRepository $repository
* @param ISummitRepository $summit_repository
* @param ISummitDocumentService $service
* @param IResourceServerContext $resource_server_context
*/
public function __construct
(
ISummitDocumentRepository $repository,
ISummitRepository $summit_repository,
ISummitDocumentService $service,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->repository = $repository;
$this->summit_repository = $summit_repository;
$this->service = $service;
}
/**
* @param LaravelRequest $request
* @param $summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function add(LaravelRequest $request, $summit_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$payload = $request->all();
$rules = [
'file' => 'required',
'name' => 'required|string:512',
'label' => 'required|string:512',
'description' => 'nullable|string',
'event_types' => 'sometimes|int_array',
];
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, $rules);
if ($validation->fails()) {
$ex = new ValidationException;
$ex->setMessages($validation->messages()->toArray());
throw $ex;
}
$fields = [
'name',
'description',
'label',
];
$document = $this->service->addSummitDocument
(
$summit,
HTMLCleaner::cleanData($payload, $fields)
);
return $this->created(SerializerRegistry::getInstance()->getSerializer($document)->serialize());
}
catch (EntityNotFoundException $ex1)
{
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (\Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param LaravelRequest $request
* @param $summit_id
* @param $document_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function update(LaravelRequest $request, $summit_id, $document_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$payload = $request->all();
$rules = [
'file' => 'sometimes',
'name' => 'nullable|string:512',
'label' => 'nullable|string:512',
'description' => 'nullable|string',
'event_types' => 'sometimes|int_array',
];
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, $rules);
if ($validation->fails()) {
$ex = new ValidationException;
$ex->setMessages($validation->messages()->toArray());
throw $ex;
}
$fields = [
'name',
'description',
'label',
];
$document = $this->service->updateSummitDocument
(
$summit,
$document_id,
HTMLCleaner::cleanData($payload, $fields)
);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($document)->serialize());
}
catch (EntityNotFoundException $ex1)
{
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (\Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @inheritDoc
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @inheritDoc
*/
protected function deleteChild(Summit $summit, $child_id): void
{
$this->service->deleteSummitDocument($summit, $child_id);
}
/**
* @inheritDoc
*/
protected function getChildFromSummit(Summit $summit, $child_id): ?IEntity
{
return $summit->getSummitDocumentById($child_id);
}
/**
* @return array
*/
protected function getFilterRules():array
{
return [
'name' => ['=@', '=='],
'description' => ['=@', '=='],
'label' => ['=@', '=='],
'event_type' => ['=@', '=='],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [
'name' => 'sometimes|required|string',
'description' => 'sometimes|required|string',
'label' => 'sometimes|required|string',
'event_type' => 'sometimes|required|string',
];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [
'id',
'name',
'label',
];
}
/**
* @param $summit_id
* @param $document_id
* @param $event_type_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function addEventType($summit_id, $document_id, $event_type_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$document = $this->service->addEventTypeToSummitDocument
(
$summit,
$document_id,
$event_type_id
);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($document)->serialize());
}
catch (EntityNotFoundException $ex1)
{
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (\Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $document_id
* @param $event_type_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function removeEventType($summit_id, $document_id, $event_type_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$document = $this->service->removeEventTypeFromSummitDocument
(
$summit,
$document_id,
$event_type_id
);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($document)->serialize());
}
catch (EntityNotFoundException $ex1)
{
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (\Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,143 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Repositories\ISummitEmailEventFlowRepository;
use App\Services\Model\ISummitEmailEventFlowService;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use models\summit\Summit;
use models\utils\IEntity;
/**
* Class OAuth2SummitEmailEventFlowApiController
* @package App\Http\Controllers
*/
class OAuth2SummitEmailEventFlowApiController extends OAuth2ProtectedController
{
// traits
use ParametrizedGetAll;
use UpdateSummitChildElement;
use GetAllBySummit;
use GetSummitChildElementById;
use DeleteSummitChildElement;
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* @var ISummitEmailEventFlowService
*/
private $service;
/**
* OAuth2SummitEmailEventFlowApiController constructor.
* @param ISummitEmailEventFlowRepository $repository
* @param ISummitRepository $summit_repository
* @param ISummitEmailEventFlowService $service
* @param IResourceServerContext $resource_server_context
*/
public function __construct
(
ISummitEmailEventFlowRepository $repository,
ISummitRepository $summit_repository,
ISummitEmailEventFlowService $service,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->repository = $repository;
$this->summit_repository = $summit_repository;
$this->service = $service;
}
/**
* @inheritDoc
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @inheritDoc
*/
function getUpdateValidationRules(array $payload): array
{
return [
'email_template_identifier' => 'sometimes|required|string',
];
}
/**
* @inheritDoc
*/
protected function updateChild(Summit $summit, int $child_id, array $payload): IEntity
{
return $this->service->updateEmailEventFlow($summit, $child_id, $payload);
}
/**
* @inheritDoc
*/
protected function getChildFromSummit(Summit $summit, $child_id): ?IEntity
{
return $summit->getEmailEventById($child_id);
}
/**
* @return array
*/
protected function getFilterRules():array
{
return [
'email_template_identifier' => ['=@', '=='],
'event_type_name' => ['=@', '=='],
'flow_name' => ['=@', '=='],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [
'email_template_identifier' => 'sometimes|required|string',
'event_type_name' => 'sometimes|required|string',
'flow_name' => 'sometimes|required|string',
];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [
'id',
'email_template_identifier',
];
}
/**
* @param Summit $summit
* @param $child_id
* @throws \models\exceptions\EntityNotFoundException
*/
protected function deleteChild(Summit $summit, $child_id): void
{
$this->service->deleteEmailEventFlow($summit, $child_id);
}
}

View File

@ -435,6 +435,9 @@ final class OAuth2SummitEventsApiController extends OAuth2ProtectedController
'end_date' => 'sometimes|required_with:start_date|date_format:U|after:start_date',
'track_id' => 'required|integer',
'rsvp_link' => 'sometimes|url',
'streaming_url' => 'sometimes|url',
'etherpad_link' => 'sometimes|url',
'meeting_url' => 'sometimes|url',
'rsvp_template_id' => 'sometimes|integer',
'rsvp_max_user_number' => 'required_with:rsvp_template_id|integer|min:0',
'rsvp_max_user_wait_list_number' => 'required_with:rsvp_template_id|integer|min:0',
@ -451,6 +454,7 @@ final class OAuth2SummitEventsApiController extends OAuth2ProtectedController
'moderator_speaker_id' => 'sometimes|integer',
// group event
'groups' => 'sometimes|int_array',
'selection_plan_id' => 'sometimes|integer',
];
// Creates a Validator instance and validates the data.
@ -512,6 +516,9 @@ final class OAuth2SummitEventsApiController extends OAuth2ProtectedController
'title' => 'sometimes|string|max:255',
'description' => 'sometimes|string|max:1100',
'rsvp_link' => 'sometimes|url',
'streaming_url' => 'sometimes|url',
'etherpad_link' => 'sometimes|url',
'meeting_url' => 'sometimes|url',
'rsvp_template_id' => 'sometimes|integer',
'rsvp_max_user_number' => 'required_with:rsvp_template_id|integer|min:0',
'rsvp_max_user_wait_list_number' => 'required_with:rsvp_template_id|integer|min:0',
@ -533,7 +540,8 @@ final class OAuth2SummitEventsApiController extends OAuth2ProtectedController
'moderator_speaker_id' => 'sometimes|integer',
// group event
'groups' => 'sometimes|int_array',
'occupancy' => 'sometimes|in:EMPTY,25%,50%,75%,FULL'
'occupancy' => 'sometimes|in:EMPTY,25%,50%,75%,FULL',
'selection_plan_id' => 'sometimes|integer',
];
// Creates a Validator instance and validates the data.
@ -1296,4 +1304,58 @@ final class OAuth2SummitEventsApiController extends OAuth2ProtectedController
}
}
public function addEventImage(LaravelRequest $request, $summit_id, $event_id){
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$file = $request->file('file');
if (is_null($file)) {
return $this->error412(array('file param not set!'));
}
$image = $this->service->addEventImage($summit, $event_id, $file);
return $this->created(SerializerRegistry::getInstance()->getSerializer($image)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function deleteEventImage($summit_id, $event_id) {
try {
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$this->service->removeEventImage($summit, $event_id);
return $this->deleted();
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -17,7 +17,6 @@ use App\Models\Foundation\Summit\Locations\SummitLocationConstants;
use App\Models\Foundation\Summit\Repositories\ISummitLocationBannerRepository;
use App\Models\Foundation\Summit\Repositories\ISummitLocationRepository;
use App\Models\Foundation\Summit\Repositories\ISummitRoomReservationRepository;
use App\Services\Apis\IPaymentGatewayAPI;
use App\Services\Model\ILocationService;
use Exception;
use Illuminate\Http\Request as LaravelRequest;
@ -95,11 +94,6 @@ final class OAuth2SummitLocationsApiController extends OAuth2ProtectedController
*/
private $location_banners_repository;
/**
* @var IPaymentGatewayAPI
*/
private $payment_gateway;
/**
* @var ISummitRoomReservationRepository
*/
@ -117,7 +111,6 @@ final class OAuth2SummitLocationsApiController extends OAuth2ProtectedController
* @param ISummitRoomReservationRepository $reservation_repository
* @param ISummitService $summit_service
* @param ILocationService $location_service
* @param IPaymentGatewayAPI $payment_gateway
* @param IResourceServerContext $resource_server_context
*/
public function __construct
@ -132,7 +125,6 @@ final class OAuth2SummitLocationsApiController extends OAuth2ProtectedController
ISummitRoomReservationRepository $reservation_repository,
ISummitService $summit_service,
ILocationService $location_service,
IPaymentGatewayAPI $payment_gateway,
IResourceServerContext $resource_server_context
) {
parent::__construct($resource_server_context);
@ -145,7 +137,6 @@ final class OAuth2SummitLocationsApiController extends OAuth2ProtectedController
$this->location_banners_repository = $location_banners_repository;
$this->location_service = $location_service;
$this->summit_service = $summit_service;
$this->payment_gateway = $payment_gateway;
$this->reservation_repository = $reservation_repository;
}

View File

@ -0,0 +1,142 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Repositories\ISummitMediaFileTypeRepository;
use App\Services\Model\ISummitMediaFileTypeService;
use models\oauth2\IResourceServerContext;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
/**
* Class OAuth2SummitMediaFileTypeApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitMediaFileTypeApiController extends OAuth2ProtectedController
{
use AddEntity;
use UpdateEntity;
use DeleteEntity;
use GetEntity;
use ParametrizedGetAll;
/**
* @var ISummitMediaFileTypeService
*/
private $service;
/**
* OAuth2SummitMediaFileTypeApiController constructor.
* @param ISummitMediaFileTypeService $service
* @param ISummitMediaFileTypeRepository $repository
* @param IResourceServerContext $resource_server_context
*/
public function __construct
(
ISummitMediaFileTypeService $service,
ISummitMediaFileTypeRepository $repository,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->service = $service;
$this->repository = $repository;
}
/**
* @inheritDoc
*/
function getAddValidationRules(array $payload): array
{
return [
'name' => 'required|string|max:255',
'description' => 'sometimes|string|max:255',
'allowed_extensions'=> 'required|string_array',
];
}
/**
* @inheritDoc
*/
protected function addEntity(array $payload): IEntity
{
return $this->service->add($payload);
}
/**
* @inheritDoc
*/
protected function deleteEntity(int $id): void
{
$this->service->delete($id);
}
/**
* @inheritDoc
*/
protected function getEntity(int $id): IEntity
{
return $this->repository->getById($id);
}
/**
* @inheritDoc
*/
function getUpdateValidationRules(array $payload): array
{
return [
'name' => 'sometimes|string|max:255',
'description' => 'sometimes|string|max:255',
'allowed_extensions'=> 'required|string_array',
];
}
/**
* @inheritDoc
*/
protected function updateEntity($id, array $payload): IEntity
{
return $this->service->update($id, $payload);
}
public function getAll(){
return $this->_getAll(
function(){
return [
'name' => ['=@', '=='],
];
},
function(){
return [
'name' => 'sometimes|string',
];
},
function()
{
return [
'name',
'id',
];
},
function($filter){
return $filter;
},
function(){
return SerializerRegistry::SerializerType_Public;
}
);
}
}

View File

@ -0,0 +1,297 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Exceptions\HTTP403ForbiddenException;
use App\Models\Foundation\Summit\Repositories\ISummitMediaUploadTypeRepository;
use App\Models\Utils\IStorageTypesConstants;
use App\Services\Model\ISummitMediaUploadTypeService;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use models\summit\Summit;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
use Exception;
/**
* Class OAuth2SummitMediaUploadTypeApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitMediaUploadTypeApiController extends OAuth2ProtectedController
{
use GetAllBySummit;
use AddSummitChildElement;
use UpdateSummitChildElement;
use DeleteSummitChildElement;
use GetSummitChildElementById;
/**
* @var ISummitMediaUploadTypeService
*/
private $service;
/**
* @var ISummitRepository
*/
private $summit_repository;
public function __construct
(
ISummitMediaUploadTypeRepository $repository,
ISummitRepository $summit_repository,
ISummitMediaUploadTypeService $service,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->service = $service;
$this->summit_repository = $summit_repository;
$this->repository = $repository;
}
/**
* @return array
*/
protected function getFilterRules():array
{
return [
'name' => ['=@', '=='],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [
'name' => 'sometimes|required|string',
];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [
'id',
'name',
];
}
/**
* @inheritDoc
*/
protected function addChild(Summit $summit, array $payload): IEntity
{
return $this->service->add($summit, $payload);
}
/**
* @inheritDoc
*/
function getAddValidationRules(array $payload): array
{
return [
'name' => 'required|string|max:255',
'description' => 'sometimes|string|max:255',
'is_mandatory' => 'required|boolean',
'max_size' => 'required|int|megabyte_aligned',
'private_storage_type' => 'required|string|in:'.implode(",", IStorageTypesConstants::ValidTypes),
'public_storage_type' => 'required|string|in:'.implode(",", IStorageTypesConstants::ValidTypes),
'type_id' => 'required|int',
'presentation_types' => 'sometimes|int_array',
];
}
/**
* @inheritDoc
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @inheritDoc
*/
protected function deleteChild(Summit $summit, $child_id): void
{
$this->service->delete($summit, $child_id);
}
/**
* @inheritDoc
*/
protected function getChildFromSummit(Summit $summit, $child_id): ?IEntity
{
return $summit->getMediaUploadTypeById($child_id);
}
/**
* @inheritDoc
*/
function getUpdateValidationRules(array $payload): array
{
return [
'name' => 'sometimes|string|max:255',
'description' => 'sometimes|string|max:255',
'is_mandatory' => 'sometimes|boolean',
// KB
'max_size' => 'sometimes|int|megabyte_aligned',
'private_storage_type' => 'sometimes|string|in:'.implode(",", IStorageTypesConstants::ValidTypes),
'public_storage_type' => 'sometimes|string|in:'.implode(",", IStorageTypesConstants::ValidTypes),
'type_id' => 'sometimes|int',
'presentation_types' => 'sometimes|int_array',
];
}
/**
* @inheritDoc
*/
protected function updateChild(Summit $summit, int $child_id, array $payload): IEntity
{
return $this->service->update($summit, $child_id, $payload);
}
/**
* @param $summit_id
* @param $media_upload_type_id
* @param $presentation_type_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function addToPresentationType($summit_id, $media_upload_type_id, $presentation_type_id){
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$presentation_type = $this->service->addToPresentationType($summit, intval($media_upload_type_id), intval($presentation_type_id));
return $this->updated(SerializerRegistry::getInstance()->getSerializer
(
$presentation_type
)->serialize());
}
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412(array($ex->getMessage()));
}
catch(EntityNotFoundException $ex)
{
Log::warning($ex);
return $this->error404(array('message'=> $ex->getMessage()));
}
catch (\HTTP401UnauthorizedException $ex) {
Log::warning($ex);
return $this->error401();
}
catch (HTTP403ForbiddenException $ex) {
Log::warning($ex);
return $this->error403();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $media_upload_type_id
* @param $presentation_type_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function deleteFromPresentationType($summit_id, $media_upload_type_id, $presentation_type_id){
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$presentation_type = $this->service->deleteFromPresentationType($summit, intval($media_upload_type_id), intval($presentation_type_id));
return $this->updated(SerializerRegistry::getInstance()->getSerializer
(
$presentation_type
)->serialize());
}
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412(array($ex->getMessage()));
}
catch(EntityNotFoundException $ex)
{
Log::warning($ex);
return $this->error404(array('message'=> $ex->getMessage()));
}
catch (\HTTP401UnauthorizedException $ex) {
Log::warning($ex);
return $this->error401();
}
catch (HTTP403ForbiddenException $ex) {
Log::warning($ex);
return $this->error403();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $to_summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function cloneMediaUploadTypes($summit_id, $to_summit_id){
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$to_summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($to_summit_id);
if (is_null($to_summit)) return $this->error404();
$to_summit = $this->service->cloneMediaUploadTypes($summit, $to_summit);
return $this->created(
SerializerRegistry::getInstance()->getSerializer
(
$to_summit
)->serialize()
);
}
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412(array($ex->getMessage()));
}
catch(EntityNotFoundException $ex)
{
Log::warning($ex);
return $this->error404(array('message'=> $ex->getMessage()));
}
catch (\HTTP401UnauthorizedException $ex) {
Log::warning($ex);
return $this->error401();
}
catch (HTTP403ForbiddenException $ex) {
Log::warning($ex);
return $this->error403();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -947,4 +947,82 @@ final class OAuth2SummitMembersApiController extends OAuth2ProtectedController
}
}
/**
* @param $summit_id
* @param $member_id
* @param $event_id
* @return mixed
*/
public function enterToEvent($summit_id, $member_id, $event_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$event = $this->summit_service->enterTo($summit, $current_member, intval($event_id));
return $this->updated(SerializerRegistry::getInstance()->getSerializer($event)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch(\HTTP401UnauthorizedException $ex3)
{
Log::warning($ex3);
return $this->error401();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $member_id
* @param $event_id
* @return mixed
*/
public function leaveFromEvent($summit_id, $member_id, $event_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$event = $this->summit_service->leaveFrom($summit, $current_member, intval($event_id));
return $this->updated(SerializerRegistry::getInstance()->getSerializer($event)->serialize());
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch(\HTTP401UnauthorizedException $ex3)
{
Log::warning($ex3);
return $this->error401();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,320 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Repositories\ISummitOrderExtraQuestionTypeRepository;
use App\Services\Model\ISummitOrderExtraQuestionTypeService;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use models\summit\Summit;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
use Exception;
/**
* Class OAuth2SummitOrderExtraQuestionTypeApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitOrderExtraQuestionTypeApiController
extends OAuth2ProtectedController
{
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* @var ISummitOrderExtraQuestionTypeService
*/
private $service;
/**
* OAuth2SummitSponsorApiController constructor.
* @param ISummitOrderExtraQuestionTypeRepository $repository
* @param ISummitRepository $summit_repository
* @param ISummitOrderExtraQuestionTypeService $service
* @param IResourceServerContext $resource_server_context
*/
public function __construct
(
ISummitOrderExtraQuestionTypeRepository $repository,
ISummitRepository $summit_repository,
ISummitOrderExtraQuestionTypeService $service,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->summit_repository = $summit_repository;
$this->service = $service;
$this->repository = $repository;
}
use GetAllBySummit;
use GetSummitChildElementById;
use AddSummitChildElement;
use UpdateSummitChildElement;
use DeleteSummitChildElement;
/**
* @param $summit_id
* @return mixed
*/
public function getMetadata($summit_id){
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
return $this->ok
(
$this->repository->getQuestionsMetadata($summit)
);
}
/**
* @return array
*/
protected function getFilterRules():array{
return [
'name' => ['==', '=@'],
'type' => ['==', '=@'],
'usage' => ['==', '=@'],
'label' => ['==', '=@'],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [
'name' => 'sometimes|required|string',
'type' => 'sometimes|required|string',
'usage' => 'sometimes|required|string',
'label' => 'sometimes|required|string',
];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [
'id',
'name',
'label',
'order',
];
}
/**
* @param array $payload
* @return array
*/
function getAddValidationRules(array $payload): array
{
return SummitOrderExtraQuestionTypeValidationRulesFactory::build($payload);
}
/**
* @param Summit $summit
* @param array $payload
* @return IEntity
* @throws EntityNotFoundException
* @throws ValidationException
*/
protected function addChild(Summit $summit, array $payload): IEntity
{
return $this->service->addOrderExtraQuestion($summit, $payload);
}
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @param Summit $summit
* @param $child_id
* @throws EntityNotFoundException
* @throws ValidationException
*/
protected function deleteChild(Summit $summit, $child_id): void
{
$this->service->deleteOrderExtraQuestion($summit, $child_id);
}
protected function getChildFromSummit(Summit $summit, $child_id): ?IEntity
{
return $summit->getOrderExtraQuestionById($child_id);
}
/**
* @param array $payload
* @return array
*/
function getUpdateValidationRules(array $payload): array
{
return SummitOrderExtraQuestionTypeValidationRulesFactory::build($payload, true);
}
/**
* @param Summit $summit
* @param int $child_id
* @param array $payload
* @return IEntity
* @throws \models\exceptions\EntityNotFoundException
* @throws \models\exceptions\ValidationException
*/
protected function updateChild(Summit $summit, int $child_id, array $payload): IEntity
{
return $this->service->updateOrderExtraQuestion($summit, $child_id, $payload);
}
/**
* @param $summit_id
* @param $question_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function addQuestionValue($summit_id, $question_id){
try {
if(!Request::isJson()) return $this->error400();
$data = Input::json();
$payload = $data->all();
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, [
'label' => 'sometimes|string',
'value' => 'required|string',
]);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$value = $this->service->addOrderExtraQuestionValue($summit, $question_id, $payload);
return $this->created(SerializerRegistry::getInstance()->getSerializer($value)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $question_id
* @param $value_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function updateQuestionValue($summit_id, $question_id, $value_id){
try {
if(!Request::isJson()) return $this->error400();
$data = Input::json();
$payload = $data->all();
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, [
'label' => 'sometimes|string',
'value' => 'sometimes|string',
'order' => 'sometimes|integer|min:1'
]);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$value = $this->service->updateOrderExtraQuestionValue($summit, $question_id, $value_id, $payload);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($value)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $question_id
* @param $value_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function deleteQuestionValue($summit_id, $question_id, $value_id){
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$this->service->deleteOrderExtraQuestionValue($summit, $question_id, $value_id);
return $this->deleted();
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -26,12 +26,12 @@ use models\summit\ISummitRepository;
use ModelSerializers\SerializerRegistry;
use services\model\ISummitPromoCodeService;
use utils\Filter;
use utils\FilterElement;
use utils\FilterParser;
use utils\OrderParser;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use utils\PagingInfo;
use Exception;
/**
* Class OAuth2SummitPromoCodesApiController
* @package App\Http\Controllers
@ -417,7 +417,7 @@ final class OAuth2SummitPromoCodesApiController extends OAuth2ProtectedControlle
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$rules = PromoCodesValidationRulesFactory::build($data->all());
$rules = PromoCodesValidationRulesFactory::build($data->all(), true);
// Creates a Validator instance and validates the data.
$validation = Validator::make($data->all(), $rules);
@ -430,7 +430,7 @@ final class OAuth2SummitPromoCodesApiController extends OAuth2ProtectedControlle
);
}
$promo_code = $this->promo_code_service->updatePromoCode($summit, $promo_code_id, $data->all(), $this->resource_server_context->getCurrentUser());
$promo_code = $this->promo_code_service->updatePromoCode($summit, intval($promo_code_id), $data->all(), $this->resource_server_context->getCurrentUser());
return $this->updated(SerializerRegistry::getInstance()->getSerializer($promo_code)->serialize());
@ -458,7 +458,7 @@ final class OAuth2SummitPromoCodesApiController extends OAuth2ProtectedControlle
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$this->promo_code_service->deletePromoCode($summit, $promo_code_id);
$this->promo_code_service->deletePromoCode($summit, intval($promo_code_id));
return $this->deleted();
} catch (ValidationException $ex1) {
@ -483,8 +483,8 @@ final class OAuth2SummitPromoCodesApiController extends OAuth2ProtectedControlle
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$mail_request = $this->promo_code_service->sendPromoCodeMail($summit, $promo_code_id);
return $this->created($mail_request->getId());
$this->promo_code_service->sendPromoCodeMail($summit, intval($promo_code_id));
return $this->ok();
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
@ -507,7 +507,7 @@ final class OAuth2SummitPromoCodesApiController extends OAuth2ProtectedControlle
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$promo_code = $summit->getPromoCodeById($promo_code_id);
$promo_code = $summit->getPromoCodeById(intval($promo_code_id));
if(is_null($promo_code))
return $this->error404();
return $this->ok(SerializerRegistry::getInstance()->getSerializer($promo_code)->serialize( Request::input('expand', '')));
@ -523,4 +523,125 @@ final class OAuth2SummitPromoCodesApiController extends OAuth2ProtectedControlle
}
}
/**
* @param $summit_id
* @param $promo_code_id
* @param $badge_feature_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function addBadgeFeatureToPromoCode($summit_id, $promo_code_id, $badge_feature_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$promo_code = $this->promo_code_service->addPromoCodeBadgeFeature($summit, intval($promo_code_id), intval($badge_feature_id));
return $this->updated(SerializerRegistry::getInstance()->getSerializer($promo_code)->serialize( Request::input('expand', '')));
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $promo_code_id
* @param $badge_feature_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function removeBadgeFeatureFromPromoCode($summit_id, $promo_code_id, $badge_feature_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$promo_code = $this->promo_code_service->removePromoCodeBadgeFeature($summit, intval($promo_code_id), intval($badge_feature_id));
return $this->updated(SerializerRegistry::getInstance()->getSerializer($promo_code)->serialize( Request::input('expand', '')));
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $promo_code_id
* @param $ticket_type_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function addTicketTypeToPromoCode($summit_id, $promo_code_id, $ticket_type_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$payload = [];
if (Request::isJson()) {
$data = Input::json();
$payload = $data->all();
$discount_code_rules = [
'amount' => 'sometimes|required_without:rate|numeric|min:0',
'rate' => 'sometimes|required_without:amount|numeric|min:0',
];
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, $discount_code_rules);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
}
$promo_code = $this->promo_code_service->addPromoCodeTicketTypeRule($summit, intval($promo_code_id), intval($ticket_type_id), $payload);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($promo_code)->serialize( Request::input('expand', '')));
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $promo_code_id
* @param $ticket_type_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function removeTicketTypeFromPromoCode($summit_id, $promo_code_id, $ticket_type_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$promo_code = $this->promo_code_service->removePromoCodeTicketTypeRule($summit, intval($promo_code_id), intval($ticket_type_id));
return $this->updated(SerializerRegistry::getInstance()->getSerializer($promo_code)->serialize( Request::input('expand', '')));
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,161 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Repositories\ISummitRefundPolicyTypeRepository;
use App\Services\Model\ISummitRefundPolicyTypeService;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use models\summit\Summit;
use models\utils\IEntity;
/**
* Class OAuth2SummitRefundPolicyTypeApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitRefundPolicyTypeApiController extends OAuth2ProtectedController
{
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* @var ISummitRefundPolicyTypeService
*/
private $service;
/**
* OAuth2SummitSponsorApiController constructor.
* @param ISummitRefundPolicyTypeRepository $repository
* @param ISummitRepository $summit_repository
* @param ISummitRefundPolicyTypeService $service
* @param IResourceServerContext $resource_server_context
*/
public function __construct
(
ISummitRefundPolicyTypeRepository $repository,
ISummitRepository $summit_repository,
ISummitRefundPolicyTypeService $service,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->summit_repository = $summit_repository;
$this->service = $service;
$this->repository = $repository;
}
use GetAllBySummit;
use GetSummitChildElementById;
use AddSummitChildElement;
use UpdateSummitChildElement;
use DeleteSummitChildElement;
/**
* @param array $payload
* @return array
*/
function getAddValidationRules(array $payload): array
{
return SummitRefundPolicyTypeValidationRulesFactory::build($payload);
}
/**
* @param array $payload
* @return array
*/
function getUpdateValidationRules(array $payload): array
{
return SummitRefundPolicyTypeValidationRulesFactory::build($payload, true);
}
/**
* @return array
*/
protected function getFilterRules():array
{
return [
'name' => ['=@', '=='],
'until_x_days_before_event_starts' => ['>=', '==', '>', '>=', '<', '<='],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [
'name' => 'sometimes|required|string',
];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [
'id',
'name',
'until_x_days_before_event_starts',
];
}
/**
* @param Summit $summit
* @param array $payload
* @return IEntity
* @throws \models\exceptions\EntityNotFoundException
* @throws \models\exceptions\ValidationException
*/
protected function addChild(Summit $summit, array $payload): IEntity
{
return $this->service->addPolicy($summit, $payload);
}
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @param Summit $summit
* @param $child_id
* @return void
*/
protected function deleteChild(Summit $summit, $child_id): void
{
$this->service->deletePolicy($summit, $child_id);
}
protected function getChildFromSummit(Summit $summit, $child_id): ?IEntity
{
return $summit->getRefundPolicyById($child_id);
}
/**
* @param Summit $summit
* @param int $child_id
* @param array $payload
* @return IEntity
*/
protected function updateChild(Summit $summit, int $child_id, array $payload): IEntity
{
return $this->service->updatePolicy($summit, $child_id, $payload);
}
}

View File

@ -0,0 +1,474 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Utils\BooleanCellFormatter;
use App\Http\Utils\EpochCellFormatter;
use App\Jobs\Emails\Registration\Invitations\InviteSummitRegistrationEmail;
use App\Jobs\Emails\Registration\Invitations\ReInviteSummitRegistrationEmail;
use App\Models\Foundation\Summit\Repositories\ISummitRegistrationInvitationRepository;
use App\Services\Model\ISummitRegistrationInvitationService;
use Illuminate\Http\Request as LaravelRequest;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use models\summit\Summit;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
use utils\Filter;
use utils\FilterElement;
use utils\FilterParser;
/**
* Class OAuth2SummitRegistrationInvitationApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitRegistrationInvitationApiController extends OAuth2ProtectedController
{
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* @var ISummitRegistrationInvitationService
*/
private $service;
/**
* OAuth2SummitRegistrationInvitationApiController constructor.
* @param ISummitRepository $summit_repository
* @param ISummitRegistrationInvitationRepository $repository
* @param ISummitRegistrationInvitationService $service
* @param IResourceServerContext $resource_server_context
*/
public function __construct
(
ISummitRepository $summit_repository,
ISummitRegistrationInvitationRepository $repository,
ISummitRegistrationInvitationService $service,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->repository = $repository;
$this->summit_repository = $summit_repository;
$this->service = $service;
}
/**
* @param LaravelRequest $request
* @param $summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function ingestInvitations(LaravelRequest $request, $summit_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$file = $request->file('file');
if (is_null($file)) {
return $this->error412(array('file param not set!'));
}
$this->service->importInvitationData($summit, $file);
return $this->ok();
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
return $this->error401();
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $token
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getInvitationByToken($token){
try {
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$invitation = $this->service->getInvitationByToken($current_member, $token);
return $this->ok(SerializerRegistry::getInstance()->getSerializer($invitation)->serialize(Request::input('expand', '')));
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
return $this->error401();
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $email
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getByEmail($summit_id, $email){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$invitation = $this->service->getInvitationByEmail($summit,$email);
if(is_null($invitation))
throw new EntityNotFoundException();
return $this->ok(SerializerRegistry::getInstance()->getSerializer($invitation)->serialize(Request::input('expand', '')));
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
return $this->error401();
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
// traits
use ParametrizedGetAll;
use GetSummitChildElementById;
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @inheritDoc
*/
protected function getChildFromSummit(Summit $summit, $child_id): ?IEntity
{
return $summit->getSummitRegistrationInvitationById($child_id);
}
/**
* @param $summit_id
* @return mixed
*/
public function getAllBySummit($summit_id){
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
return $this->_getAll(
function(){
return [
'email' => ['=@', '=='],
'first_name' => ['=@', '=='],
'last_name' => ['=@', '=='],
'is_accepted' => ['=='],
'is_sent' => ['=='],
];
},
function(){
return [
'email' => 'sometimes|required|string',
'first_name' => 'sometimes|required|string',
'last_name' => 'sometimes|required|string',
'is_accepted' => 'sometimes|required|string|in:true,false',
'is_sent' => 'sometimes|required|string|in:true,false',
];
},
function()
{
return [
'id',
'email',
];
},
function($filter) use($summit){
if($filter instanceof Filter){
$filter->addFilterCondition(FilterElement::makeEqual('summit_id', $summit->getId()));
}
return $filter;
},
function(){
return SerializerRegistry::SerializerType_Public;
}
);
}
/**
* @param $summit_id
* @return mixed
*/
public function getAllBySummitCSV($summit_id){
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
return $this->_getAllCSV(
function(){
return [
'email' => ['=@', '=='],
'first_name' => ['=@', '=='],
'last_name' => ['=@', '=='],
'is_accepted' => ['=='],
'is_sent' => ['=='],
];
},
function(){
return [
'email' => 'sometimes|required|string',
'first_name' => 'sometimes|required|string',
'last_name' => 'sometimes|required|string',
'is_accepted' => 'sometimes|required|string|in:true,false',
'is_sent' => 'sometimes|required|string|in:true,false',
];
},
function()
{
return [
'id',
'email',
];
},
function($filter) use($summit){
if($filter instanceof Filter){
$filter->addFilterCondition(FilterElement::makeEqual('summit_id', $summit->getId()));
}
return $filter;
},
function(){
return SerializerRegistry::SerializerType_CSV;
},
function(){
return [
'accepted_date' => new EpochCellFormatter(),
'is_accepted' => new BooleanCellFormatter(),
'is_sent' => new BooleanCellFormatter(),
];
},
function(){
$allowed_columns = [
'id',
'email',
'first_name',
'last_name',
'member_id',
'order_id',
'summit_id',
'accepted_date',
'is_accepted',
'is_sent',
];
$columns_param = Input::get("columns", "");
$columns = [];
if(!empty($columns_param))
$columns = explode(',', $columns_param);
$diff = array_diff($columns, $allowed_columns);
if(count($diff) > 0){
throw new ValidationException(sprintf("columns %s are not allowed!", implode(",", $diff)));
}
if(empty($columns))
$columns = $allowed_columns;
return $columns;
},
'summit-registration-invitations-'
);
}
use DeleteSummitChildElement;
/**
* @inheritDoc
*/
protected function deleteChild(Summit $summit, $child_id): void
{
$this->service->delete($summit, $child_id);
}
use AddSummitChildElement;
/**
* @inheritDoc
*/
protected function addChild(Summit $summit, array $payload): IEntity
{
return $this->service->add($summit, $payload);
}
/**
* @inheritDoc
*/
function getAddValidationRules(array $payload): array
{
return [
'email' => 'required|email|max:255',
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
];
}
use UpdateSummitChildElement;
/**
* @inheritDoc
*/
function getUpdateValidationRules(array $payload): array
{
return [
'email' => 'sometimes|email|max:255',
'first_name' => 'sometimes|string|max:255',
'last_name' => 'sometimes|string|max:255',
];
}
/**
* @inheritDoc
*/
protected function updateChild(Summit $summit, int $child_id, array $payload): IEntity
{
return $this->service->update($summit, $child_id, $payload);
}
/**
* @param $summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function deleteAll($summit_id){
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$this->service->deleteAll($summit);
return $this->deleted();
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
return $this->error401();
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function send($summit_id){
try {
if(!Request::isJson()) return $this->error400();
$data = Input::json();
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$payload = $data->all();
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, [
'email_flow_event' => 'required|string|in:'.join(',', [
InviteSummitRegistrationEmail::EVENT_SLUG,
ReInviteSummitRegistrationEmail::EVENT_SLUG,
]),
'invitations_ids' => 'sometimes|int_array',
]);
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$filter = null;
if (Input::has('filter')) {
$filter = FilterParser::parse(Input::get('filter'), [
'is_accepted' => ['=='],
'is_sent' => ['=='],
]);
}
if (is_null($filter))
$filter = new Filter();
$filter->validate([
'is_accepted' => 'sometimes|required|string|in:true,false',
'is_sent' => 'sometimes|required|string|in:true,false',
]);
$this->service->triggerSend($summit, $payload, Input::get('filter'));
return $this->ok();
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
return $this->error401();
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -73,14 +73,14 @@ final class OAuth2SummitSelectionPlansApiController extends OAuth2ProtectedContr
return $this->ok(SerializerRegistry::getInstance()->getSerializer($selection_plan)->serialize(Request::input('expand', '')));
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412([$ex1->getMessage()]);
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
}
catch(EntityNotFoundException $ex2)
catch(EntityNotFoundException $ex)
{
Log::warning($ex2);
return $this->error404(['message'=> $ex2->getMessage()]);
Log::warning($ex);
return $this->error404($ex->getMessage());
}
catch (Exception $ex) {
Log::error($ex);
@ -119,14 +119,14 @@ final class OAuth2SummitSelectionPlansApiController extends OAuth2ProtectedContr
return $this->updated(SerializerRegistry::getInstance()->getSerializer($selection_plan)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412([$ex1->getMessage()]);
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
}
catch(EntityNotFoundException $ex2)
catch(EntityNotFoundException $ex)
{
Log::warning($ex2);
return $this->error404(['message'=> $ex2->getMessage()]);
Log::warning($ex);
return $this->error404($ex->getMessage());
}
catch (Exception $ex) {
Log::error($ex);
@ -164,14 +164,14 @@ final class OAuth2SummitSelectionPlansApiController extends OAuth2ProtectedContr
return $this->created(SerializerRegistry::getInstance()->getSerializer($selection_plan)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412([$ex1->getMessage()]);
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
}
catch(EntityNotFoundException $ex2)
catch(EntityNotFoundException $ex)
{
Log::warning($ex2);
return $this->error404(['message'=> $ex2->getMessage()]);
Log::warning($ex);
return $this->error404($ex->getMessage());
}
catch (Exception $ex) {
Log::error($ex);
@ -194,14 +194,14 @@ final class OAuth2SummitSelectionPlansApiController extends OAuth2ProtectedContr
return $this->deleted();
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412([$ex1->getMessage()]);
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
}
catch(EntityNotFoundException $ex2)
catch(EntityNotFoundException $ex)
{
Log::warning($ex2);
return $this->error404(['message'=> $ex2->getMessage()]);
Log::warning($ex);
return $this->error404($ex->getMessage());
}
catch (Exception $ex) {
Log::error($ex);
@ -225,14 +225,14 @@ final class OAuth2SummitSelectionPlansApiController extends OAuth2ProtectedContr
return $this->deleted();
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412([$ex1->getMessage()]);
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
}
catch(EntityNotFoundException $ex2)
catch(EntityNotFoundException $ex)
{
Log::warning($ex2);
return $this->error404(['message'=> $ex2->getMessage()]);
Log::warning($ex);
return $this->error404($ex->getMessage());
}
catch (Exception $ex) {
Log::error($ex);
@ -256,14 +256,14 @@ final class OAuth2SummitSelectionPlansApiController extends OAuth2ProtectedContr
return $this->deleted();
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412([$ex1->getMessage()]);
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
}
catch(EntityNotFoundException $ex2)
catch(EntityNotFoundException $ex)
{
Log::warning($ex2);
return $this->error404(['message'=> $ex2->getMessage()]);
Log::warning($ex);
return $this->error404($ex->getMessage());
}
catch (Exception $ex) {
Log::error($ex);
@ -272,26 +272,30 @@ final class OAuth2SummitSelectionPlansApiController extends OAuth2ProtectedContr
}
/**
* @param string $status
* @return mixed
* @param $summit_id
* @param $status
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getCurrentSelectionPlanByStatus($status){
public function getCurrentSelectionPlanByStatus($summit_id, $status){
try {
$selection_plan = $this->selection_plan_service->getCurrentSelectionPlanByStatus($status);
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$selection_plan = $this->selection_plan_service->getCurrentSelectionPlanByStatus($summit, $status);
if (is_null($selection_plan)) return $this->error404();
return $this->ok(SerializerRegistry::getInstance()->getSerializer($selection_plan)->serialize(Request::input('expand', '')));
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412([$ex1->getMessage()]);
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
}
catch(EntityNotFoundException $ex2)
catch(EntityNotFoundException $ex)
{
Log::warning($ex2);
return $this->error404(['message'=> $ex2->getMessage()]);
Log::warning($ex);
return $this->error404($ex->getMessage());
}
catch (Exception $ex) {
Log::error($ex);

View File

@ -31,10 +31,6 @@ use ModelSerializers\ISerializerTypeSelector;
use ModelSerializers\SerializerRegistry;
use services\model\ISpeakerService;
use services\model\ISummitService;
use utils\Filter;
use utils\FilterElement;
use utils\FilterParser;
use utils\OrderParser;
use utils\PagingInfo;
use Illuminate\Http\Request as LaravelRequest;
use utils\PagingResponse;
@ -191,6 +187,72 @@ final class OAuth2SummitSpeakersApiController extends OAuth2ProtectedController
);
}
/**
* @param $summit_id
* @return mixed
*/
public function getSpeakersOnSchedule($summit_id)
{
$summit = SummitFinderStrategyFactory::build($this->getRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
return $this->_getAll(
function(){
return [
'first_name' => ['=@', '=='],
'last_name' => ['=@', '=='],
'email' => ['=@', '=='],
'id' => ['=='],
'full_name' => ['=@', '=='],
'event_start_date' => ['>', '<', '<=', '>=', '=='],
'event_end_date' => ['>', '<', '<=', '>=', '=='],
];
},
function(){
return [
'first_name' => 'sometimes|string',
'last_name' => 'sometimes|string',
'email' => 'sometimes|string',
'id' => 'sometimes|integer',
'full_name' => 'sometimes|string',
'event_start_date' => 'sometimes|date_format:U',
'event_end_date' => 'sometimes|date_format:U',
];
},
function()
{
return [
'first_name',
'last_name',
'id',
'email',
];
},
function($filter) use($summit){
return $filter;
},
function(){
return $this->serializer_type_selector->getSerializerType();
},
null,
null,
function ($page, $per_page, $filter, $order, $applyExtraFilters) use($summit) {
return $this->speaker_repository->getSpeakersBySummitAndOnSchedule
(
$summit,
new PagingInfo($page, $per_page),
call_user_func($applyExtraFilters, $filter),
$order
);
},
[
'summit_id' => $summit_id,
'published' => true,
'summit' => $summit
]
);
}
/**
* get all speakers without summit
* @return mixed
@ -500,7 +562,7 @@ final class OAuth2SummitSpeakersApiController extends OAuth2ProtectedController
'irc' => 'sometimes|string|max:50',
'twitter' => 'sometimes|string|max:50',
'member_id' => 'sometimes|integer',
'email' => 'sometimes|email:rfc,dns|max:50',
'email' => 'sometimes|email:rfc|max:50',
'on_site_phone' => 'sometimes|string|max:50',
'registered' => 'sometimes|boolean',
'is_confirmed' => 'sometimes|boolean',
@ -579,7 +641,7 @@ final class OAuth2SummitSpeakersApiController extends OAuth2ProtectedController
'irc' => 'sometimes|string|max:50',
'twitter' => 'sometimes|string|max:50',
'member_id' => 'sometimes|integer',
'email' => 'sometimes|email:rfc,dns|max:50',
'email' => 'sometimes|email:rfc|max:50',
'on_site_phone' => 'sometimes|string|max:50',
'registered' => 'sometimes|boolean',
'is_confirmed' => 'sometimes|boolean',
@ -655,50 +717,6 @@ final class OAuth2SummitSpeakersApiController extends OAuth2ProtectedController
}
}
/**
* @param LaravelRequest $request
* @param $speaker_id
* @return mixed
*/
public function addSpeakerPhoto(LaravelRequest $request, $speaker_id)
{
try {
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$speaker = $this->speaker_repository->getById($speaker_id);
if (is_null($speaker)) return $this->error404();
if(!$speaker->canBeEditedBy($current_member)){
return $this->error403();
}
$file = $request->file('file');
if (is_null($file)) {
return $this->error412(array('file param not set!'));
}
$photo = $this->service->addSpeakerPhoto($speaker_id, $file);
return $this->created(SerializerRegistry::getInstance()->getSerializer($photo)->serialize());
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
return $this->error401();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $speaker_from_id
* @param $speaker_to_id
@ -752,7 +770,7 @@ final class OAuth2SummitSpeakersApiController extends OAuth2ProtectedController
'irc' => 'sometimes|string|max:50',
'twitter' => 'sometimes|string|max:50',
'member_id' => 'sometimes|integer',
'email' => 'sometimes|email:rfc,dns|max:50',
'email' => 'sometimes|email:rfc|max:50',
'funded_travel' => 'sometimes|boolean',
'willing_to_travel' => 'sometimes|boolean',
'willing_to_present_video' => 'sometimes|boolean',
@ -767,6 +785,8 @@ final class OAuth2SummitSpeakersApiController extends OAuth2ProtectedController
'organizational_roles' => 'sometimes|int_array',
'other_organizational_rol' => 'sometimes|string|max:255',
'active_involvements' => 'sometimes|int_array',
'company' => 'sometimes|string|max:255',
'phone_number' => 'sometimes|string|max:255',
];
// Creates a Validator instance and validates the data.
@ -831,7 +851,7 @@ final class OAuth2SummitSpeakersApiController extends OAuth2ProtectedController
'irc' => 'sometimes|string|max:50',
'twitter' => 'sometimes|string|max:50',
'member_id' => 'sometimes|integer',
'email' => 'sometimes|email:rfc,dns|max:50',
'email' => 'sometimes|email:rfc|max:50',
'available_for_bureau' => 'sometimes|boolean',
'funded_travel' => 'sometimes|boolean',
'willing_to_travel' => 'sometimes|boolean',
@ -846,6 +866,8 @@ final class OAuth2SummitSpeakersApiController extends OAuth2ProtectedController
'organizational_roles' => 'sometimes|int_array',
'other_organizational_rol' => 'sometimes|string|max:255',
'active_involvements' => 'sometimes|int_array',
'company' => 'sometimes|string|max:255',
'phone_number' => 'sometimes|string|max:255',
];
// Creates a Validator instance and validates the data.
@ -1214,4 +1236,149 @@ final class OAuth2SummitSpeakersApiController extends OAuth2ProtectedController
}
}
/**
* @param LaravelRequest $request
* @param $speaker_id
* @return mixed
*/
public function addSpeakerPhoto(LaravelRequest $request, $speaker_id)
{
try {
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$speaker = $this->speaker_repository->getById($speaker_id);
if (is_null($speaker)) return $this->error404();
if(!$speaker->canBeEditedBy($current_member)){
return $this->error403();
}
$file = $request->file('file');
if (is_null($file)) {
return $this->error412(array('file param not set!'));
}
$photo = $this->service->addSpeakerPhoto($speaker_id, $file);
return $this->created(SerializerRegistry::getInstance()->getSerializer($photo)->serialize());
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
return $this->error401();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function deleteSpeakerPhoto($speaker_id){
try {
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$speaker = $this->speaker_repository->getById($speaker_id);
if (is_null($speaker)) return $this->error404();
if(!$speaker->canBeEditedBy($current_member)){
return $this->error403();
}
$this->service->deleteSpeakerPhoto($speaker_id);
return $this->deleted();
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
return $this->error401();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function addSpeakerBigPhoto(LaravelRequest $request, $speaker_id){
try {
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$speaker = $this->speaker_repository->getById($speaker_id);
if (is_null($speaker)) return $this->error404();
if(!$speaker->canBeEditedBy($current_member)){
return $this->error403();
}
$file = $request->file('file');
if (is_null($file)) {
return $this->error412(array('file param not set!'));
}
$photo = $this->service->addSpeakerBigPhoto($speaker_id, $file);
return $this->created(SerializerRegistry::getInstance()->getSerializer($photo)->serialize());
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
return $this->error401();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
public function deleteSpeakerBigPhoto($speaker_id){
try {
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$speaker = $this->speaker_repository->getById($speaker_id);
if (is_null($speaker)) return $this->error404();
if(!$speaker->canBeEditedBy($current_member)){
return $this->error403();
}
$this->service->deleteSpeakerBigPhoto($speaker_id);
return $this->deleted();
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
return $this->error401();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -412,8 +412,8 @@ final class OAuth2SummitSpeakersAssistanceApiController extends OAuth2ProtectedC
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$mail_request = $this->service->sendSpeakerSummitAssistanceAnnouncementMail($summit, $assistance_id);
return $this->created($mail_request->getId());
$this->service->sendSpeakerSummitAssistanceAnnouncementMail($summit, $assistance_id);
return $this->created();
} catch (ValidationException $ex1) {
Log::warning($ex1);

View File

@ -0,0 +1,224 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Repositories\ISponsorRepository;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use models\summit\Summit;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
use services\model\ISummitSponsorService;
/**
* Class OAuth2SummitSponsorApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitSponsorApiController extends OAuth2ProtectedController
{
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* @var ISummitSponsorService
*/
private $service;
/**
* OAuth2SummitSponsorApiController constructor.
* @param ISponsorRepository $repository
* @param ISummitRepository $summit_repository
* @param ISummitSponsorService $service
* @param IResourceServerContext $resource_server_context
*/
public function __construct
(
ISponsorRepository $repository,
ISummitRepository $summit_repository,
ISummitSponsorService $service,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->summit_repository = $summit_repository;
$this->service = $service;
$this->repository = $repository;
}
/**
* @return array
*/
protected function getFilterRules():array{
return [
'company_name' => ['==', '=@'],
'sponsorship_name' => ['==', '=@'],
'sponsorship_size' => ['==', '=@'],
'badge_scans_count' => ['==', '<','>','<=','>=','<>'],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [
'company_name' => 'sometimes|required|string',
'sponsorship_name' => 'sometimes|required|string',
'sponsorship_size' => 'sometimes|required|string',
'badge_scans_count' => 'sometimes|required|integer',
];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [
'id',
'order',
];
}
use GetAllBySummit;
use GetSummitChildElementById;
use AddSummitChildElement;
use UpdateSummitChildElement;
use DeleteSummitChildElement;
/**
* @param array $payload
* @return array
*/
function getAddValidationRules(array $payload): array
{
return SponsorValidationRulesFactory::build($payload);
}
/**
* @param Summit $summit
* @param array $payload
* @return IEntity
*/
protected function addChild(Summit $summit, array $payload): IEntity
{
return $this->service->addSponsor($summit, $payload);
}
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @param Summit $summit
* @param $child_id
* @return void
*/
protected function deleteChild(Summit $summit, $child_id): void
{
$this->service->deleteSponsor($summit, $child_id);
}
protected function getChildFromSummit(Summit $summit, $child_id): ?IEntity
{
return $summit->getSummitSponsorById($child_id);
}
/**
* @param array $payload
* @return array
*/
function getUpdateValidationRules(array $payload): array
{
return SponsorValidationRulesFactory::build($payload, true);
}
/**
* @param Summit $summit
* @param int $child_id
* @param array $payload
* @return IEntity
*/
protected function updateChild(Summit $summit, int $child_id, array $payload): IEntity
{
return $this->service->updateSponsor($summit, $child_id, $payload);
}
/**
* @param $summit_id
* @param $sponsor_id
* @param $member_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function addSponsorUser($summit_id, $sponsor_id, $member_id){
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$sponsor = $this->service->addSponsorUser($summit, $sponsor_id, $member_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($sponsor)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $sponsor_id
* @param $member_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function removeSponsorUser($summit_id, $sponsor_id, $member_id){
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$sponsor = $this->service->removeSponsorUser($summit, $sponsor_id, $member_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($sponsor)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,220 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Repositories\ISummitTaxTypeRepository;
use App\Services\Model\ISummitTaxTypeService;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use models\summit\Summit;
use models\utils\IBaseRepository;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
use Illuminate\Support\Facades\Log;
use Exception;
/**
* Class OAuth2SummitTaxTypeApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitTaxTypeApiController extends OAuth2ProtectedController
{
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* @var ISummitTaxTypeService
*/
private $service;
use GetAllBySummit;
use GetSummitChildElementById;
use AddSummitChildElement;
use UpdateSummitChildElement;
use DeleteSummitChildElement;
/**
* @return array
*/
protected function getFilterRules():array
{
return [
'name' => ['=@', '=='],
];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [
'name' => 'sometimes|required|string',
];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [
'id',
'name',
];
}
public function __construct
(
ISummitTaxTypeRepository $repository,
ISummitRepository $summit_repository,
ISummitTaxTypeService $service,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->repository = $repository;
$this->summit_repository = $summit_repository;
$this->service = $service;
}
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @param array $payload
* @return array
*/
protected function getAddValidationRules(array $payload): array
{
return TaxTypeValidationRulesFactory::build($payload);
}
/**
* @param Summit $summit
* @param array $payload
* @return IEntity
* @throws EntityNotFoundException
* @throws ValidationException
*/
protected function addChild(Summit $summit, array $payload): IEntity
{
return $this->service->addTaxType($summit, $payload);
}
protected function getChildFromSummit(Summit $summit, $child_id): ?IEntity
{
return $summit->getTaxTypeById($child_id);
}
/**
* @param array $payload
* @return array
*/
function getUpdateValidationRules(array $payload): array
{
return TaxTypeValidationRulesFactory::build($payload, true);
}
/**
* @param Summit $summit
* @param int $child_id
* @param array $payload
* @return IEntity
* @throws EntityNotFoundException
* @throws ValidationException
*/
protected function updateChild(Summit $summit, int $child_id, array $payload): IEntity
{
return $this->service->updateTaxType($summit, $child_id, $payload);
}
/**
* @param Summit $summit
* @param $child_id
* @throws EntityNotFoundException
*/
protected function deleteChild(Summit $summit, $child_id): void
{
$this->service->deleteTaxType($summit, $child_id);
}
/**
* @param $summit_id
* @param $tax_id
* @param $ticket_type_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function addTaxToTicketType($summit_id, $tax_id, $ticket_type_id){
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$child = $this->service->addTaxTypeToTicketType($summit, $tax_id, $ticket_type_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($child)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $tax_id
* @param $ticket_type_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function removeTaxFromTicketType($summit_id, $tax_id, $ticket_type_id){
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$child = $this->service->removeTaxTypeFromTicketType($summit, $tax_id, $ticket_type_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($child)->serialize());
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,693 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Utils\EpochCellFormatter;
use App\Jobs\IngestSummitExternalRegistrationData;
use App\ModelSerializers\ISummitAttendeeTicketSerializerTypes;
use App\Services\Model\ISummitOrderService;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\oauth2\IResourceServerContext;
use models\summit\IOrderConstants;
use models\summit\ISummitAttendeeTicketRepository;
use models\summit\ISummitRepository;
use models\summit\Summit;
use models\summit\SummitAttendeeTicket;
use models\summit\SummitOrderExtraQuestionTypeConstants;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
use utils\Filter;
use utils\FilterElement;
use Illuminate\Http\Request as LaravelRequest;
/**
* Class OAuth2SummitTicketApiController
* @package App\Http\Controllers
*/
final class OAuth2SummitTicketApiController extends OAuth2ProtectedController
{
use GetSummitChildElementById;
use ParametrizedGetAll;
use GetAndValidateJsonPayload;
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* @var ISummitOrderService
*/
private $service;
/**
* OAuth2SummitTicketApiController constructor.
* @param ISummitRepository $summit_repository
* @param ISummitAttendeeTicketRepository $repository
* @param ISummitOrderService $service
* @param IResourceServerContext $resource_server_context
*/
public function __construct
(
ISummitRepository $summit_repository,
ISummitAttendeeTicketRepository $repository,
ISummitOrderService $service,
IResourceServerContext $resource_server_context
)
{
parent::__construct($resource_server_context);
$this->repository = $repository;
$this->summit_repository = $summit_repository;
$this->service = $service;
}
/**
* @param $summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getAllBySummit($summit_id){
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
return $this->_getAll(
function(){
return [
'number' => ['=@', '=='],
'order_number' => ['=@', '=='],
'owner_name' => ['=@', '=='],
'owner_first_name' => ['=@', '=='],
'owner_last_name' => ['=@', '=='],
'owner_email' => ['=@', '=='],
'owner_company' => ['=@', '=='],
'summit_id' => ['=='],
'owner_id' => ['=='],
'order_id' => ['=='],
'status' => ['==','<>'],
];
},
function(){
return [
'status' => sprintf('sometimes|in:%s',implode(',', IOrderConstants::ValidStatus)),
'number' => 'sometimes|string',
'order_number' => 'sometimes|string',
'owner_name' => 'sometimes|string',
'owner_first_name' => 'sometimes|string',
'owner_last_name' => 'sometimes|string',
'owner_email' => 'sometimes|string',
'owner_company' => 'sometimes|string',
'summit_id' => 'sometimes|integer',
'owner_id' => 'sometimes|integer',
'order_id' => 'sometimes|integer',
];
},
function()
{
return [
'id',
'number',
'status',
];
},
function($filter) use($summit){
if($filter instanceof Filter){
$filter->addFilterCondition(FilterElement::makeEqual('summit_id', $summit->getId()));
}
return $filter;
},
function(){
return ISummitAttendeeTicketSerializerTypes::AdminType;
}
);
}
/**
* @param $summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getAllBySummitCSV($summit_id){
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
return $this->_getAllCSV(
function(){
return [
'number' => ['=@', '=='],
'order_number' => ['=@', '=='],
'owner_name' => ['=@', '=='],
'owner_first_name' => ['=@', '=='],
'owner_last_name' => ['=@', '=='],
'owner_email' => ['=@', '=='],
'owner_company' => ['=@', '=='],
'summit_id' => ['=='],
'owner_id' => ['=='],
'order_id' => ['=='],
'status' => ['=='],
];
},
function(){
return [
'status' => sprintf('sometimes|in:%s',implode(',', IOrderConstants::ValidStatus)),
'number' => 'sometimes|string',
'order_number' => 'sometimes|string',
'owner_name' => 'sometimes|string',
'owner_first_name' => 'sometimes|string',
'owner_last_name' => 'sometimes|string',
'owner_email' => 'sometimes|string',
'owner_company' => 'sometimes|string',
'summit_id' => 'sometimes|integer',
'owner_id' => 'sometimes|integer',
'order_id' => 'sometimes|integer',
];
},
function()
{
return [
'id',
'number',
'status',
];
},
function($filter) use($summit){
if($filter instanceof Filter){
$filter->addFilterCondition(FilterElement::makeEqual('summit_id', $summit->getId()));
}
return $filter;
},
function(){
return SerializerRegistry::SerializerType_CSV;
},
function(){
return [
'created' => new EpochCellFormatter(),
'last_edited' => new EpochCellFormatter(),
'bought_date' => new EpochCellFormatter(),
];
},
function() use($summit){
$allowed_columns = [
'id',
'created',
'last_edited',
'number',
'status',
'attendee_id',
'attendee_first_name',
'attendee_last_name',
'attendee_email',
'attendee_company',
'external_order_id',
'external_attendee_id',
'bought_date',
'ticket_type_id',
'ticket_type_name',
'order_id',
'badge_id',
'promo_code_id',
'promo_code',
'raw_cost',
'final_amount',
'discount',
'refunded_amount',
'currency',
'badge_type_id',
'badge_type_name',
];
foreach ($summit->getBadgeFeaturesTypes() as $featuresType){
$allowed_columns[] = $featuresType->getName();
}
foreach ($summit->getOrderExtraQuestionsByUsage(SummitOrderExtraQuestionTypeConstants::TicketQuestionUsage) as $question){
$allowed_columns[] = $question->getLabel();
}
$columns_param = Input::get("columns", "");
$columns = [];
if(!empty($columns_param))
$columns = explode(',', $columns_param);
$diff = array_diff($columns, $allowed_columns);
if(count($diff) > 0){
throw new ValidationException(sprintf("columns %s are not allowed!", implode(",", $diff)));
}
if(empty($columns))
$columns = $allowed_columns;
return $columns;
},
sprintf('tickets-%s-', $summit_id),
[
'features_types' => $summit->getBadgeFeaturesTypes(),
'ticket_questions' => $summit->getOrderExtraQuestionsByUsage(SummitOrderExtraQuestionTypeConstants::TicketQuestionUsage)
]
);
}
/**
* @param $summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function ingestExternalTicketData($summit_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$payload = $this->getJsonPayload([
'email_to' => 'nullable|email',
]);
$this->service->ingestExternalTicketData($summit, $payload);
return $this->ok();
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
return $this->error401();
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getImportTicketDataTemplate($summit_id){
try {
/**
* id
* number
* attendee_email ( mandatory if id and number are missing)
* attendee_first_name (optional)
* attendee_last_name (optional)
* attendee_company (optional)
* ticket_type_name ( mandatory if id and number are missing)
* ticket_type_id ( mandatory if id and number are missing)
* badge_type_id (optional)
* badge_type_name (optional)
* badge_features (optional)
*/
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$row = [
'id' => '',
'number' => '',
'attendee_email' => '',
'attendee_first_name' => '',
'attendee_last_name' => '',
'attendee_company' => '',
'ticket_type_name' => '',
'ticket_type_id' => '',
'badge_type_id' => '',
'badge_type_name' => '',
];
// badge features for summit
foreach ($summit->getBadgeFeaturesTypes() as $featuresType){
$row[$featuresType->getName()] = '' ;
}
$template = [
$row
];
return $this->export
(
'csv',
'ticket-data-import-template',
$template,
[],
[]
);
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
return $this->error401();
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param LaravelRequest $request
* @param $summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function importTicketData(LaravelRequest $request, $summit_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$file = $request->file('file');
if (is_null($file)) {
return $this->error412(array('file param not set!'));
}
$this->service->importTicketData($summit, $file);
return $this->ok();
} catch (EntityNotFoundException $ex1) {
Log::warning($ex1);
return $this->error404();
} catch (ValidationException $ex2) {
Log::warning($ex2);
return $this->error412(array($ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
return $this->error401();
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @return mixed
*/
public function getAllMyTickets(){
$owner = $this->getResourceServerContext()->getCurrentUser();
return $this->_getAll(
function(){
return [
'number' => ['=@', '=='],
'order_number' => ['=@', '=='],
'summit_id' => ['=='],
'order_id' => ['=='],
'status' => ['==','<>'],
];
},
function(){
return [
'number' => 'sometimes|string',
'order_number' => 'sometimes|string',
'summit_id' => 'sometimes|integer',
'order_id' => 'sometimes|integer',
'status' => sprintf('sometimes|in:%s',implode(',', IOrderConstants::ValidStatus)),
];
},
function()
{
return [
'id',
'number',
'status',
];
},
function($filter) use($owner){
if($filter instanceof Filter){
$filter->addFilterCondition(FilterElement::makeEqual('member_id', $owner->getId()));
}
return $filter;
},
function(){
return ISummitAttendeeTicketSerializerTypes::AdminType;
}
);
}
/**
* @return ISummitRepository
*/
protected function getSummitRepository(): ISummitRepository
{
return $this->summit_repository;
}
/**
* @param Summit $summit
* @param $child_id
* @return IEntity|null
* @throws \Exception
*/
protected function getChildFromSummit(Summit $summit, $child_id): ?IEntity
{
return $this->service->getTicket($summit, $child_id);
}
/**
* @param $summit_id
* @param $ticket_id
* @return mixed
*/
public function refundTicket($summit_id, $ticket_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$payload = $this->getJsonPayload([
'amount' => 'required|numeric|greater_than:0',
]);
$ticket = $this->service->refundTicket($summit, $ticket_id, floatval($payload['amount']));
return $this->updated(SerializerRegistry::getInstance()->getSerializer($ticket)->serialize( Request::input('expand', '')));
}
catch(\InvalidArgumentException $ex){
Log::warning($ex);
return $this->error400();
}
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $ticket_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getAttendeeBadge($summit_id, $ticket_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$ticket = is_int($ticket_id) ? $this->repository->getById(intval($ticket_id)) : $this->repository->getByNumber($ticket_id);
if(is_null($ticket) || !$ticket instanceof SummitAttendeeTicket) return $this->error404();;
if($ticket->getOrder()->getSummitId() != $summit->getId()) return $this->error404();
if(!$ticket->hasBadge()) return $this->error404();
return $this->ok(SerializerRegistry::getInstance()->getSerializer($ticket->getBadge())->serialize( Request::input('expand', '')));
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $ticket_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function createAttendeeBadge($summit_id, $ticket_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$payload = $this->getJsonPayload([
'badge_type_id' => 'sometimes|integer',
'features' => 'sometimes|int_array',
]);
$badge = $this->service->createBadge($summit, $ticket_id, $payload);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($badge)->serialize( Request::input('expand', '')));
}
catch(\InvalidArgumentException $ex){
Log::warning($ex);
return $this->error400();
}
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $ticket_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function deleteAttendeeBadge($summit_id, $ticket_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$this->service->deleteBadge($summit, $ticket_id);
return $this->deleted();
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $ticket_id
* @param $type_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function updateAttendeeBadgeType($summit_id, $ticket_id, $type_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$badge = $this->service->updateBadgeType($summit, $ticket_id, $type_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($badge)->serialize( Request::input('expand', '')));
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $ticket_id
* @param $feature_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function addAttendeeBadgeFeature($summit_id, $ticket_id, $feature_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$badge = $this->service->addAttendeeBadgeFeature($summit, $ticket_id, $feature_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($badge)->serialize( Request::input('expand', '')));
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $ticket_id
* @param $feature_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function removeAttendeeBadgeFeature($summit_id, $ticket_id, $feature_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$badge = $this->service->removeAttendeeBadgeFeature($summit, $ticket_id, $feature_id);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($badge)->serialize( Request::input('expand', '')));
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $ticket_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function printAttendeeBadge($summit_id, $ticket_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();
if (is_null($current_member)) return $this->error403();
$badge = $this->service->printAttendeeBadge($summit, $ticket_id, $current_member);
return $this->updated
(
SerializerRegistry::getInstance()->getSerializer($badge)->serialize( Request::input('expand', ''))
);
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -439,6 +439,7 @@ final class OAuth2SummitTracksApiController extends OAuth2ProtectedController
'name' => 'required|string|max:50',
'description' => 'required|string|max:500',
'code' => 'sometimes|string|max:5',
'color' => 'sometimes|hex_color|max:50',
'session_count' => 'sometimes|integer',
'alternate_count' => 'sometimes|integer',
'lightning_count' => 'sometimes|integer',
@ -537,6 +538,7 @@ final class OAuth2SummitTracksApiController extends OAuth2ProtectedController
$rules = [
'name' => 'sometimes|string|max:50',
'description' => 'sometimes|string|max:500',
'color' => 'sometimes|hex_color|max:50',
'code' => 'sometimes|string|max:5',
'session_count' => 'sometimes|integer',
'alternate_count' => 'sometimes|integer',

View File

@ -494,4 +494,80 @@ final class OAuth2SummitsEventTypesApiController extends OAuth2ProtectedControll
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $event_type_id
* @param $document_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function addSummitDocument($summit_id, $event_type_id, $document_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$document = $this->event_type_service->addSummitDocumentToEventType
(
$summit,
$event_type_id,
$document_id
);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($document)->serialize());
}
catch (EntityNotFoundException $ex1)
{
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (\Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $event_type_id
* @param $document_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function removeSummitDocument($summit_id, $event_type_id, $document_id){
try {
$summit = SummitFinderStrategyFactory::build($this->summit_repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$document = $this->event_type_service->removeSummitDocumentFromEventType
(
$summit,
$event_type_id,
$document_id
);
return $this->updated(SerializerRegistry::getInstance()->getSerializer($document)->serialize());
}
catch (EntityNotFoundException $ex1)
{
Log::warning($ex1);
return $this->error404();
}
catch (ValidationException $ex2)
{
Log::warning($ex2);
return $this->error412($ex2->getMessages());
}
catch (\Exception $ex)
{
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -12,6 +12,7 @@
* limitations under the License.
**/
use App\Http\Utils\FilterAvailableSummitsStrategy;
use function GuzzleHttp\Psr7\str;
use models\oauth2\IResourceServerContext;
use models\summit\ISummitRepository;
use models\summit\Summit;
@ -54,10 +55,8 @@ class CurrentSummitFinderStrategy implements ISummitFinderStrategy
public function find($summit_id)
{
$summit = $summit_id === 'current' ? $this->repository->getCurrent() : $this->repository->getById(intval($summit_id));
if(is_null($summit)) return null;
$show_all = FilterAvailableSummitsStrategy::shouldReturnAllSummits($this->resource_server_ctx);
if($show_all) return $summit;
if(!$summit->isAvailableOnApi()) return null;
if(is_null($summit))
$summit = $this->repository->getBySlug(strval($summit_id));
return $summit;
}
}

View File

@ -30,7 +30,7 @@ class RetrieveAllUnPublishedSummitEventsStrategy extends RetrieveAllSummitEvents
protected function getValidFilters()
{
$valid_filters = parent::getValidFilters();
$valid_filters['published'] = ['=='];
$valid_filters['published'] = ['=='];
return $valid_filters;
}

View File

@ -141,6 +141,7 @@ abstract class RetrieveSummitEventsStrategy
'speaker_email' => ['=@', '=='],
'selection_status' => ['=='],
'id' => ['=='],
'selection_plan_id' => ['=='],
];
}
@ -164,6 +165,7 @@ abstract class RetrieveSummitEventsStrategy
'speaker_id' => 'sometimes|integer',
'location_id' => 'sometimes|integer',
'id' => 'sometimes|integer',
'selection_plan_id' => 'sometimes|integer',
];
}
}

View File

@ -0,0 +1,102 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Exceptions\HTTP403ForbiddenException;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
use Exception;
/**
* Trait AddEntity
* @package App\Http\Controllers
*/
trait AddEntity
{
use BaseAPI;
/**
* @param array $payload
* @return array
*/
abstract function getAddValidationRules(array $payload): array;
/**
* @param array $payload
* @return IEntity
*/
abstract protected function addEntity(array $payload):IEntity;
/**
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function add(){
try {
if(!Request::isJson()) return $this->error400();
$data = Input::json();
$payload = $data->all();
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, $this->getAddValidationRules($payload));
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$fields = Request::input('fields', '');
$relations = Request::input('relations', '');
$relations = !empty($relations) ? explode(',', $relations) : [];
$fields = !empty($fields) ? explode(',', $fields) : [];
$entity = $this->addEntity($payload);
return $this->created(SerializerRegistry::getInstance()->getSerializer($entity)->serialize
(
Request::input('expand', ''),
$fields,
$relations
));
}
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412(array($ex->getMessage()));
}
catch(EntityNotFoundException $ex)
{
Log::warning($ex);
return $this->error404(array('message'=> $ex->getMessage()));
}
catch (\HTTP401UnauthorizedException $ex) {
Log::warning($ex);
return $this->error401();
}
catch (HTTP403ForbiddenException $ex) {
Log::warning($ex);
return $this->error403();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,115 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Exceptions\HTTP403ForbiddenException;
use models\summit\Summit;
use models\utils\IEntity;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use ModelSerializers\SerializerRegistry;
use Exception;
/**
* Trait AddSummitChildElement
* @package App\Http\Controllers
*/
trait AddSummitChildElement
{
use BaseSummitAPI;
/**
* @param Summit $summit
* @param array $payload
* @return IEntity
*/
abstract protected function addChild(Summit $summit, array $payload):IEntity;
/**
* @param array $payload
* @return array
*/
abstract function getAddValidationRules(array $payload): array;
protected function addSerializerType():string{
return SerializerRegistry::SerializerType_Public;
}
/**
* @param $summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function add($summit_id){
try {
if(!Request::isJson()) return $this->error400();
$data = Input::json();
$payload = $data->all();
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, $this->getAddValidationRules($payload));
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$child = $this->addChild($summit, $payload);
$fields = Request::input('fields', '');
$relations = Request::input('relations', '');
$relations = !empty($relations) ? explode(',', $relations) : [];
$fields = !empty($fields) ? explode(',', $fields) : [];
return $this->created(SerializerRegistry::getInstance()->getSerializer
(
$child,
$this->addSerializerType()
)->serialize(
Request::input('expand', ''),
$fields,
$relations
));
}
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412(array($ex->getMessage()));
}
catch(EntityNotFoundException $ex)
{
Log::warning($ex);
return $this->error404(array('message'=> $ex->getMessage()));
}
catch (\HTTP401UnauthorizedException $ex) {
Log::warning($ex);
return $this->error401();
}
catch (HTTP403ForbiddenException $ex) {
Log::warning($ex);
return $this->error403();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -1,6 +1,6 @@
<?php namespace App\Http\Utils;
<?php namespace App\Http\Controllers;
/**
* Copyright 2018 OpenStack Foundation
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -11,20 +11,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use models\main\File;
use Exception;
use models\summit\ISummitRepository;
/**
* Interface IBucket
* @package App\Http\Utils
* Trait BaseSummitAPI
* @package App\Http\Controllers
*/
interface IBucket
trait BaseSummitAPI
{
use BaseAPI;
/**
* @param File $f
* @param string $local_path
* @return object
* @throws Exception
* @return ISummitRepository
*/
public function put(File $f, $local_path);
abstract protected function getSummitRepository():ISummitRepository;
}

View File

@ -0,0 +1,59 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Exceptions\HTTP403ForbiddenException;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
/**
* Trait DeleteEntity
* @package App\Http\Controllers
*/
trait DeleteEntity
{
use BaseAPI;
/**
* @param int $id
*/
abstract protected function deleteEntity(int $id): void;
/**
* @param $id
* @return mixed
*/
public function delete($id)
{
try {
$this->deleteEntity($id);
return $this->deleted();
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412(array($ex->getMessage()));
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\HTTP401UnauthorizedException $ex) {
Log::warning($ex);
return $this->error401();
} catch (HTTP403ForbiddenException $ex) {
Log::warning($ex);
return $this->error403();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,59 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use models\summit\Summit;
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use Exception;
/**
* Trait DeleteSummitChildElement
* @package App\Http\Controllers
*/
trait DeleteSummitChildElement
{
use BaseSummitAPI;
/**
* @param Summit $summit
* @param $child_id
* @return void
*/
abstract protected function deleteChild(Summit $summit, $child_id):void;
/**
* @param $summit_id
* @param $child_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function delete($summit_id, $child_id){
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$this->deleteChild($summit, $child_id);
return $this->deleted();
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,146 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use ModelSerializers\SerializerRegistry;
use utils\Filter;
use utils\FilterParser;
use utils\OrderParser;
use utils\PagingInfo;
use App\Http\Utils\PagingConstants;
use Exception;
/**
* Trait GetAll
* @package App\Http\Controllers
*/
trait GetAll
{
use BaseSummitAPI;
/**
* @return array
*/
protected function getFilterRules():array{
return [];
}
/**
* @return array
*/
protected function getFilterValidatorRules():array{
return [];
}
/**
* @return array
*/
protected function getOrderRules():array{
return [];
}
protected function applyExtraFilters(Filter $filter):Filter {
return $filter;
}
protected function serializerType():string{
return SerializerRegistry::SerializerType_Public;
}
/**
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getAll(){
$values = Input::all();
$rules = [
'page' => 'integer|min:1',
'per_page' => sprintf('required_with:page|integer|min:%s|max:%s', PagingConstants::MinPageSize, PagingConstants::MaxPageSize),
];
try {
$validation = Validator::make($values, $rules);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
// default values
$page = 1;
$per_page = PagingConstants::DefaultPageSize;;
if (Input::has('page')) {
$page = intval(Input::get('page'));
$per_page = intval(Input::get('per_page'));
}
$filter = null;
if (Input::has('filter')) {
$filter = FilterParser::parse(Input::get('filter'), $this->getFilterRules());
}
if(is_null($filter)) $filter = new Filter();
$filter_validator_rules = $this->getFilterValidatorRules();
if(count($filter_validator_rules)) {
$filter->validate($filter_validator_rules);
}
$order = null;
if (Input::has('order'))
{
$order = OrderParser::parse(Input::get('order'), $this->getOrderRules());
}
$data = $this->getRepository()->getAllByPage(new PagingInfo($page, $per_page), $this->applyExtraFilters($filter), $order);
return $this->ok
(
$data->toArray
(
Request::input('expand', ''),
[],
[],
[ 'serializer_type' => $this->serializerType() ],
$this->serializerType()
)
);
}
catch (ValidationException $ex1)
{
Log::warning($ex1);
return $this->error412(array( $ex1->getMessage()));
}
catch (EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
}
catch(\HTTP401UnauthorizedException $ex3)
{
Log::warning($ex3);
return $this->error401();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,49 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use utils\Filter;
use utils\FilterElement;
/**
* Trait GetAllBySummit
* @package App\Http\Controllers
*/
trait GetAllBySummit
{
use GetAll;
/**
* @var mixed
*/
protected $summit_id;
/**
* @param Filter $filter
* @return Filter
*/
protected function applyExtraFilters(Filter $filter):Filter {
$filter->addFilterCondition(FilterElement::makeEqual("summit_id", intval($this->summit_id)));
return $filter;
}
/**
* @param $summit_id
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function getAllBySummit($summit_id){
$this->summit_id = $summit_id;
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($this->summit_id);
if (is_null($summit)) return $this->error404();
return $this->getAll();
}
}

View File

@ -0,0 +1,73 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Exceptions\HTTP403ForbiddenException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
/**
* Trait GetEntity
* @package App\Http\Controllers
*/
trait GetEntity
{
use BaseAPI;
/**
* @param int $id
* @return IEntity
*/
abstract protected function getEntity(int $id): IEntity;
/**
* @param $id
* @return mixed
*/
public function get($id)
{
try {
$entity = $this->getEntity($id);
$fields = Request::input('fields', '');
$relations = Request::input('relations', '');
$relations = !empty($relations) ? explode(',', $relations) : [];
$fields = !empty($fields) ? explode(',', $fields) : [];
return $this->ok(SerializerRegistry::getInstance()->getSerializer($entity)->serialize(
Request::input('expand', ''),
$fields,
$relations
));
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412(array($ex->getMessage()));
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\HTTP401UnauthorizedException $ex) {
Log::warning($ex);
return $this->error401();
} catch (HTTP403ForbiddenException $ex) {
Log::warning($ex);
return $this->error403();
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,69 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\summit\Summit;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
use Exception;
/**
* Trait GetSummitChildElementById
* @package App\Http\Controllers
*/
trait GetSummitChildElementById
{
use BaseSummitAPI;
/**
* @param Summit $summit
* @param $child_id
* @return IEntity|null
*/
abstract protected function getChildFromSummit(Summit $summit, $child_id):?IEntity;
/**
* @return string
*/
public function getChildSerializer(){
return SerializerRegistry::SerializerType_Public;
}
/**
* @param $summit_id
* @param $child_id
* @return mixed
*/
public function get($summit_id, $child_id)
{
try {
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$child = $this->getChildFromSummit($summit, $child_id);
if(is_null($child))
return $this->error404();
return $this->ok(SerializerRegistry::getInstance()->getSerializer($child, $this->getChildSerializer())->serialize( Request::input('expand', '')));
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412($ex1->getMessages());
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(['message' => $ex2->getMessage()]);
} catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -12,6 +12,7 @@
* limitations under the License.
**/
use App\Http\Exceptions\HTTP403ForbiddenException;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
@ -166,16 +167,24 @@ trait ParametrizedGetAll
call_user_func($serializerType)
)
);
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
}
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
}
catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
}
catch (\HTTP401UnauthorizedException $ex) {
Log::warning($ex);
return $this->error401();
} catch (Exception $ex) {
}
catch(HTTP403ForbiddenException $ex){
Log::warning($ex);
return $this->error403();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
@ -297,14 +306,14 @@ trait ParametrizedGetAll
call_user_func($getFormatters),
call_user_func($getColumns)
);
} catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412($ex1->getMessages());
} catch (EntityNotFoundException $ex2) {
Log::warning($ex2);
return $this->error404(array('message' => $ex2->getMessage()));
} catch (\HTTP401UnauthorizedException $ex3) {
Log::warning($ex3);
} catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412($ex->getMessages());
} catch (EntityNotFoundException $ex) {
Log::warning($ex);
return $this->error404(array('message' => $ex->getMessage()));
} catch (\HTTP401UnauthorizedException $ex) {
Log::warning($ex);
return $this->error401();
} catch (Exception $ex) {
Log::error($ex);

View File

@ -405,7 +405,7 @@ trait SummitBookableVenueRoomApi
* @param $room_id
* @return mixed
*/
public function getBookableVenueRoom($summit_id, $venue_id, $room_id){
public function getBookableVenueRoomByVenue($summit_id, $venue_id, $room_id){
try {
$expand = Request::input('expand', '');
@ -415,7 +415,7 @@ trait SummitBookableVenueRoomApi
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$venue = $summit->getLocation($venue_id);
$venue = $summit->getLocation(intval($venue_id));
if (is_null($venue)) {
return $this->error404();
@ -425,7 +425,7 @@ trait SummitBookableVenueRoomApi
return $this->error404();
}
$room = $venue->getRoom($room_id);
$room = $venue->getRoom(intval($room_id));
if (is_null($room) || !$room instanceof SummitBookableVenueRoom) {
return $this->error404();
@ -448,6 +448,45 @@ trait SummitBookableVenueRoomApi
}
}
/**
* @param $summit_id
* @param $venue_id
* @param $room_id
* @return mixed
*/
public function getBookableVenueRoom($summit_id, $room_id){
try {
$expand = Request::input('expand', '');
$relations = Request::input('relations', '');
$relations = !empty($relations) ? explode(',', $relations) : [];
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
if (is_null($summit)) return $this->error404();
$room = $summit->getLocation(intval($room_id));
if (is_null($room) || !$room instanceof SummitBookableVenueRoom) {
return $this->error404();
}
return $this->ok(SerializerRegistry::getInstance()->getSerializer($room)->serialize($expand,[], $relations));
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
/**
* @param $summit_id
* @param $room_id
@ -668,31 +707,6 @@ trait SummitBookableVenueRoomApi
}
}
/**
* @param LaravelRequest $request
* @return mixed
*/
public function confirmBookableVenueRoomReservation(LaravelRequest $request){
if(!Request::isJson())
return $this->error400();
try {
$response = $this->payment_gateway->processCallback($request);
$this->location_service->processBookableRoomPayment($response);
return $this->ok();
}
catch(EntityNotFoundException $ex){
Log::warning($ex);
return $this->error400(["error" => 'payload error']);
}
catch (Exception $ex){
Log::error($ex);
return $this->error400(["error" => 'payload error']);
}
return $this->error400(["error" => 'invalid event type']);
}
/**
* @param $summit_id
* @param $venue_id

View File

@ -0,0 +1,105 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Exceptions\HTTP403ForbiddenException;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\utils\IEntity;
use ModelSerializers\SerializerRegistry;
/**
* Trait UpdateEntity
* @package App\Http\Controllers
*/
trait UpdateEntity
{
use BaseAPI;
/**
* @param array $payload
* @return array
*/
abstract function getUpdateValidationRules(array $payload): array;
/**
* @param $id
* @param array $payload
* @return IEntity
*/
abstract protected function updateEntity($id, array $payload):IEntity;
/**
* @param $id
* @return mixed
*/
public function update($id){
try {
if(!Request::isJson()) return $this->error400();
$data = Input::json();
$payload = $data->all();
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, $this->getUpdateValidationRules($payload));
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$entity = $this->updateEntity($id, $payload);
$fields = Request::input('fields', '');
$relations = Request::input('relations', '');
$relations = !empty($relations) ? explode(',', $relations) : [];
$fields = !empty($fields) ? explode(',', $fields) : [];
return $this->updated(SerializerRegistry::getInstance()->getSerializer($entity)->serialize
(
Request::input('expand', ''),
$fields,
$relations
));
}
catch (ValidationException $ex) {
Log::warning($ex);
return $this->error412(array($ex->getMessage()));
}
catch(EntityNotFoundException $ex)
{
Log::warning($ex);
return $this->error404(array('message'=> $ex->getMessage()));
}
catch (\HTTP401UnauthorizedException $ex) {
Log::warning($ex);
return $this->error401();
}
catch (HTTP403ForbiddenException $ex) {
Log::warning($ex);
return $this->error403();
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -0,0 +1,110 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use models\summit\Summit;
use models\utils\IEntity;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Validator;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use ModelSerializers\SerializerRegistry;
use Exception;
/**
* Trait UpdateSummitChildElement
* @package App\Http\Controllers
*/
trait UpdateSummitChildElement
{
use BaseSummitAPI;
protected function updateSerializerType():string{
return SerializerRegistry::SerializerType_Public;
}
/**
* @param array $payload
* @return array
*/
abstract function getUpdateValidationRules(array $payload): array;
/**
* @param Summit $summit
* @param int $child_id
* @param array $payload
* @return IEntity
*/
abstract protected function updateChild(Summit $summit,int $child_id, array $payload):IEntity;
/**
* @param $summit_id
* @param $child_id
* @return mixed
*/
public function update($summit_id, $child_id){
try {
if(!Request::isJson()) return $this->error400();
$data = Input::json();
$summit = SummitFinderStrategyFactory::build($this->getSummitRepository(), $this->getResourceServerContext())->find($summit_id);
if (is_null($summit)) return $this->error404();
$payload = $data->all();
// Creates a Validator instance and validates the data.
$validation = Validator::make($payload, $this->getUpdateValidationRules($payload));
if ($validation->fails()) {
$messages = $validation->messages()->toArray();
return $this->error412
(
$messages
);
}
$child = $this->updateChild($summit, $child_id, $payload);
$fields = Request::input('fields', '');
$relations = Request::input('relations', '');
$relations = !empty($relations) ? explode(',', $relations) : [];
$fields = !empty($fields) ? explode(',', $fields) : [];
return $this->updated(SerializerRegistry::getInstance()->getSerializer
(
$child,
$this->updateSerializerType()
)->serialize(
Request::input('expand', ''),
$fields,
$relations
));
}
catch (ValidationException $ex1) {
Log::warning($ex1);
return $this->error412(array($ex1->getMessage()));
}
catch(EntityNotFoundException $ex2)
{
Log::warning($ex2);
return $this->error404(array('message'=> $ex2->getMessage()));
}
catch (Exception $ex) {
Log::error($ex);
return $this->error500($ex);
}
}
}

View File

@ -23,8 +23,6 @@ use Illuminate\Support\Facades\Response;
abstract class JsonController extends Controller
{
protected $log_service;
public function __construct()
{
}
@ -76,7 +74,8 @@ abstract class JsonController extends Controller
*/
protected function ok($data = 'ok')
{
$res = Response::json($data, 200);
$res = $this->response2XX(200, $data);
//jsonp
if (Input::has('callback')) {
$res->setCallback(Input::get('callback'));
@ -92,19 +91,33 @@ abstract class JsonController extends Controller
protected function error404($data = ['message' => 'Entity Not Found'])
{
if(!is_array($data)){
$data = ['message' => $data];
}
return Response::json($data, 404);
}
protected function error403($data = ['message' => 'Forbidden'])
{
if(!is_array($data)){
$data = ['message' => $data];
}
return Response::json($data, 403);
}
protected function error401($data = ['message' => 'You don\'t have access to this item through the API.'])
{
if(!is_array($data)){
$data = ['message' => $data];
}
return Response::json($data, 401);
}
protected function response2XX($code = 200, $data = '')
{
return Response::json($data, $code);
}
/**
* {
* "message": "Validation Failed",
@ -121,6 +134,9 @@ abstract class JsonController extends Controller
*/
protected function error412($messages)
{
if(!is_array($messages)){
$messages = [$messages];
}
return Response::json(array('message' => 'Validation Failed', 'errors' => $messages), 412);
}
@ -145,12 +161,13 @@ abstract class JsonController extends Controller
* @param array $columns
* @return \Illuminate\Http\Response
*/
private function csv($filename, array $items, array $formatters = [], $field_separator = ",", $mime_type = 'application/vnd.ms-excel', array $columns = []){
protected function csv($filename, array $items, array $formatters = [], $field_separator = ",", $mime_type = 'application/vnd.ms-excel', array $columns = []){
$headers = [
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-type' => $mime_type,
'Content-Transfer-Encoding' => 'binary',
'Content-Disposition' => 'attachment; filename='.$filename.".csv",
'Last-Modified: ' => gmdate('D, d M Y H:i:s').' GMT',
'Expires' => '0',
'Pragma' => 'public',
];
@ -175,4 +192,23 @@ abstract class JsonController extends Controller
$headers
);
}
/**
* @param string $filename
* @param string $content
* @return \Illuminate\Http\Response
*/
protected function pdf(string $filename, string $content){
$headers = [
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-type' => "application/pdf",
'Content-Transfer-Encoding' => 'binary',
'Content-Disposition' => 'attachment; filename='.basename($filename),
'Expires' => '0',
'Last-Modified: ' => gmdate('D, d M Y H:i:s').' GMT',
'Pragma' => 'public',
];
return Response::make($content, 200, $headers);
}
}

View File

@ -54,4 +54,5 @@ abstract class OAuth2ProtectedController extends JsonController
{
return $this->repository;
}
}

View File

@ -0,0 +1,196 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2020 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\Foundation\Summit\Registration\IBuildDefaultPaymentGatewayProfileStrategy;
use App\Services\Model\ILocationService;
use App\Services\Model\IProcessPaymentService;
use App\Services\Model\ISummitOrderService;
use Illuminate\Http\Request as LaravelRequest;
use models\oauth2\IResourceServerContext;
use models\summit\IPaymentConstants;
use models\summit\ISummitRepository;
use Illuminate\Support\Facades\Log;
use models\summit\Summit;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use Exception;
/**
* Class PaymentGatewayWebHookController
* @package App\Http\Controllers
*/
final class PaymentGatewayWebHookController extends JsonController
{
/**
* @var ISummitRepository
*/
private $summit_repository;
/**
* @var IResourceServerContext
*/
private $resource_server_context;
/**
* @var ILocationService
*/
private $location_service;
/**
* @var ISummitOrderService
*/
private $order_service;
/**
* @var IBuildDefaultPaymentGatewayProfileStrategy
*/
private $default_payment_gateway_strategy;
/**
* PaymentGatewayWebHookController constructor.
* @param ISummitRepository $summit_repository
* @param IResourceServerContext $resource_server_context
* @param ILocationService $location_service
* @param ISummitOrderService $order_service
* @param IBuildDefaultPaymentGatewayProfileStrategy $default_payment_gateway_strategy
*/
public function __construct
(
ISummitRepository $summit_repository,
IResourceServerContext $resource_server_context,
ILocationService $location_service,
ISummitOrderService $order_service,
IBuildDefaultPaymentGatewayProfileStrategy $default_payment_gateway_strategy
)
{
$this->summit_repository = $summit_repository;
$this->resource_server_context = $resource_server_context;
$this->location_service = $location_service;
$this->order_service = $order_service;
$this->default_payment_gateway_strategy = $default_payment_gateway_strategy;;
}
/**
* @param string $application_type
* @return IProcessPaymentService|null
*/
private function getProcessPaymentService(string $application_type):?IProcessPaymentService {
if($application_type == IPaymentConstants::ApplicationTypeRegistration)
return $this->order_service;
if($application_type == IPaymentConstants::ApplicationTypeBookableRooms)
return $this->location_service;
return null;
}
/**
* @param $application_type
* @param LaravelRequest $request
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function genericConfirm($application_type, LaravelRequest $request){
try {
Log::debug(sprintf("PaymentGatewayWebHookController::genericConfirm application_type %s ", $application_type));
// get api
$paymentGatewayApi = $this->default_payment_gateway_strategy->build($application_type);
if(is_null($paymentGatewayApi)) {
Log::debug(sprintf("PaymentGatewayWebHookController::genericConfirm application_type %s profile payment not found.", $application_type));
return $this->error412([sprintf("application_type %s profile payment not found.", $application_type)]);
}
$service = $this->getProcessPaymentService($application_type);
if(is_null($service)) {
Log::debug(sprintf("PaymentGatewayWebHookController::genericConfirm application_type %s service not found.", $application_type));
return $this->error412([sprintf("application_type %s service not found.", $application_type)]);
}
$service->processPayment($paymentGatewayApi->buildPaymentGatewayApi()->processCallback($request));
return $this->ok();
}
catch(EntityNotFoundException $ex){
Log::warning($ex);
return $this->response2XX(208, ['error' => 'already reported']);
}
catch(ValidationException $ex){
Log::warning($ex);
return $this->error412(["error" => 'payload error']);
}
catch (Exception $ex){
Log::error($ex);
return $this->error400(["error" => 'payload error']);
}
return $this->error400(["error" => 'invalid event type']);
}
/**
* @param $summit_id
* @param $application_type
* @param LaravelRequest $request
* @return \Illuminate\Http\JsonResponse|mixed
*/
public function confirm($summit_id, $application_type, LaravelRequest $request){
try {
Log::debug(sprintf("PaymentGatewayWebHookController::confirm summit %s application_type %s ", $summit_id, $application_type));
// get current summit
$summit = SummitFinderStrategyFactory::build
(
$this->summit_repository,
$this->resource_server_context
)->find($summit_id);
if (is_null($summit) || !$summit instanceof Summit){
Log::debug(sprintf("PaymentGatewayWebHookController::confirm summit %s not found.", $summit_id));
return $this->error412([sprintf("application_type %s summit not found.", $application_type)]);
}
// get api
$paymentGatewayApi = $summit->getPaymentGateWayPerApp($application_type, $this->default_payment_gateway_strategy);
if(is_null($paymentGatewayApi)) {
Log::debug(sprintf("PaymentGatewayWebHookController::confirm summit %s profile payment not found.", $summit_id));
return $this->error412([sprintf("application_type %s summit not found.", $application_type)]);
}
$service = $this->getProcessPaymentService($application_type);
if(is_null($service)) {
Log::debug(sprintf("PaymentGatewayWebHookController::confirm summit %s service not found.", $summit_id));
return $this->error412([sprintf("application_type %s service not found.", $application_type)]);
}
$service->processPayment($paymentGatewayApi->processCallback($request), $summit);
return $this->ok();
}
catch(EntityNotFoundException $ex){
Log::warning($ex);
return $this->response2XX(208, ['error' => 'already reported']);
}
catch(ValidationException $ex){
Log::warning($ex);
return $this->error412(["error" => 'payload error']);
}
catch (Exception $ex){
Log::error($ex);
return $this->error400(["error" => 'payload error']);
}
return $this->error400(["error" => 'invalid event type']);
}
}

View File

@ -1,16 +1,16 @@
<?php namespace App\Http\Middleware;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Closure;
use libs\utils\ICacheService;
@ -24,491 +24,485 @@ use Illuminate\Support\Facades\Config;
use libs\utils\RequestUtils;
/**
*
* @package App\Http\Middleware\
* Implementation of http://www.w3.org/TR/cors/
*/
*
* @package App\Http\Middleware\
* Implementation of http://www.w3.org/TR/cors/
*/
class CORSMiddleware
{
const CORS_IP_BLACKLIST_PREFIX = 'CORS_IP_BLACKLIST_PREFIX:';
const CORS_IP_BLACKLIST_PREFIX = 'CORS_IP_BLACKLIST_PREFIX:';
private $headers = [];
private $headers = [];
/**
* A header is said to be a simple header if the header field name is an ASCII case-insensitive match for Accept,
* Accept-Language, or Content-Language or if it is an ASCII case-insensitive match for Content-Type and the header
* field value media type (excluding parameters) is an ASCII case-insensitive match for
* application/x-www-form-urlencoded, multipart/form-data, or text/plain.
*/
/**
* A header is said to be a simple header if the header field name is an ASCII case-insensitive match for Accept,
* Accept-Language, or Content-Language or if it is an ASCII case-insensitive match for Content-Type and the header
* field value media type (excluding parameters) is an ASCII case-insensitive match for
* application/x-www-form-urlencoded, multipart/form-data, or text/plain.
*/
protected static $simple_headers = [
'accept',
'accept-language',
'content-language',
'origin',
];
protected static $simple_content_header_values = [
'application/x-www-form-urlencode',
'multipart/form-data',
'text/plain'
protected static $simple_headers = [
'accept',
'accept-language',
'content-language',
'origin',
];
/**
* A method is said to be a simple method if it is a case-sensitive match for one of the following:
* - GET
* - HEAD
* - POST
*/
protected static $simple_http_methods = array('GET', 'HEAD', 'POST');
protected static $simple_content_header_values = [
'application/x-www-form-urlencode',
'multipart/form-data',
'text/plain'
];
const DefaultAllowedHeaders = 'origin, content-type, accept, authorization, x-requested-with';
const DefaultAllowedMethods = 'GET, POST, OPTIONS, PUT, DELETE';
/**
* A method is said to be a simple method if it is a case-sensitive match for one of the following:
* - GET
* - HEAD
* - POST
*/
protected static $simple_http_methods = array('GET', 'HEAD', 'POST');
/**
* @var
*/
private $redis;
const DefaultAllowedHeaders = 'origin, content-type, accept, authorization, x-requested-with';
const DefaultAllowedMethods = 'GET, POST, OPTIONS, PUT, DELETE';
/**
* @var IApiEndpointRepository
*/
private $endpoint_repository;
/**
* @var
*/
private $redis;
/**
* @var IApiEndpoint;
*/
private $current_endpoint = null;
/**
* @var IApiEndpointRepository
*/
private $endpoint_repository;
/**
* @var IApiEndpoint;
*/
private $current_endpoint = null;
private $allowed_headers;
private $allowed_methods;
private $allowed_headers;
private $allowed_methods;
/**
* @var ICacheService
*/
private $cache_service;
/**
* @var ICacheService
*/
private $cache_service;
/**
* CORSMiddleware constructor.
* @param IApiEndpointRepository $endpoint_repository
* @param ICacheService $cache_service
*/
public function __construct(IApiEndpointRepository $endpoint_repository, ICacheService $cache_service)
{
$this->endpoint_repository = $endpoint_repository;
$this->cache_service = $cache_service;
$this->allowed_headers = Config::get('cors.allowed_headers', self::DefaultAllowedHeaders);
$this->allowed_methods = Config::get('cors.allowed_methods', self::DefaultAllowedMethods);
}
public function __construct(IApiEndpointRepository $endpoint_repository, ICacheService $cache_service)
{
$this->endpoint_repository = $endpoint_repository;
$this->cache_service = $cache_service;
$this->allowed_headers = Config::get('cors.allowed_headers', self::DefaultAllowedHeaders);
$this->allowed_methods = Config::get('cors.allowed_methods', self::DefaultAllowedMethods);
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($response = $this->preProcess($request))
{
return $response;
}
//normal processing
$response = $next($request);
$this->postProcess($request, $response);
return $response;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($response = $this->preProcess($request))
{
return $response;
}
//normal processing
$response = $next($request);
$this->postProcess($request, $response);
return $response;
}
private function generatePreflightCacheKey($request)
{
$cache_id = 'pre-flight-'. $request->getClientIp(). '-' . $request->getRequestUri(). '-' . $request->getMethod();
return $cache_id;
}
private function generatePreflightCacheKey($request)
{
$cache_id = 'pre-flight-'. $request->getClientIp(). '-' . $request->getRequestUri(). '-' . $request->getMethod();
return $cache_id;
}
/**
* @param Request $request
* @return Response
*/
public function preProcess(Request $request)
{
$actual_request = false;
/**
* @param Request $request
* @return Response
*/
public function preProcess(Request $request)
{
$actual_request = false;
if ($this->isValidCORSRequest($request))
{
if (!$this->testOriginHeaderScrutiny($request))
{
$response = new Response();
$response->setStatusCode(403);
return $response;
}
/* Step 01 : Determine the type of the incoming request */
$type = $this->getRequestType($request);
/* Step 02 : Process request according to is type */
switch($type)
{
case CORSRequestPreflightType::REQUEST_FOR_PREFLIGHT:
{
// HTTP request send by client to preflight a further 'Complex' request
// sets the original method on request in order to be able to find the
// correct route
$real_method = $request->headers->get('Access-Control-Request-Method');
$request->setMethod($real_method);
if ($this->isValidCORSRequest($request))
{
/* Step 01 : Determine the type of the incoming request */
$type = $this->getRequestType($request);
/* Step 02 : Process request according to is type */
switch($type)
{
case CORSRequestPreflightType::REQUEST_FOR_PREFLIGHT:
{
// HTTP request send by client to preflight a further 'Complex' request
// sets the original method on request in order to be able to find the
// correct route
$real_method = $request->headers->get('Access-Control-Request-Method');
$request->setMethod($real_method);
$route_path = RequestUtils::getCurrentRoutePath($request);
if (!$route_path || !$this->checkEndPoint($route_path, $real_method))
{
$response = new Response();
$response->setStatusCode(403);
return $response;
}
// ----Step 2b: Store pre-flight request data in the Cache to keep (mark) the request as correctly followed the request pre-flight process
$data = new CORSRequestPreflightData($request, $this->current_endpoint->isAllowCredentials());
$cache_id = $this->generatePreflightCacheKey($request);
$this->cache_service->storeHash($cache_id, $data->toArray(), CORSRequestPreflightData::$cache_lifetime);
// ----Step 2c: Return corresponding response - This part should be customized with application specific constraints.....
return $this->makePreflightResponse($request);
}
break;
case CORSRequestPreflightType::COMPLEX_REQUEST:
{
$cache_id = $this->generatePreflightCacheKey($request);
// ----Step 2a: Check if the current request has an entry into the preflighted requests Cache
$data = $this->cache_service->getHash($cache_id, CORSRequestPreflightData::$cache_attributes);
if (!count($data))
{
// there wasnt preflight so just regular processing
return null;
}
// ----Step 2b: Check that pre-flight information declared during the pre-flight request match the current request on key information
$match = false;
// ------Start with comparison of "Origin" HTTP header (according to utility method impl. used to retrieve header reference cannot be null)...
if ($request->headers->get('Origin') === $data['origin'])
{
// ------Continue with HTTP method...
if ($request->getMethod() === $data['expected_method'])
{
// ------Finish with custom HTTP headers (use an method to avoid manual iteration on collection to increase the speed)...
$x_headers = self::getCustomHeaders($request);
$x_headers_pre = explode(',', $data['expected_custom_headers']);
sort($x_headers);
sort($x_headers_pre);
if (count(array_diff($x_headers, $x_headers_pre)) === 0)
{
$match = true;
}
}
}
if (!$match)
{
$response = new Response();
$response->setStatusCode(403);
return $response;
}
$actual_request = true;
}
break;
case CORSRequestPreflightType::SIMPLE_REQUEST:
{
// origins, do not set any additional headers and terminate this set of steps.
if (!$this->isAllowedOrigin($request)) {
$response = new Response();
$response->setStatusCode(403);
$route_path = RequestUtils::getCurrentRoutePath($request);
if (!$route_path || !$this->checkEndPoint($route_path, $real_method))
{
$response = new Response();
$response->setStatusCode(403);
return $response;
}
// ----Step 2b: Store pre-flight request data in the Cache to keep (mark) the request as correctly followed the request pre-flight process
$data = new CORSRequestPreflightData($request, $this->current_endpoint->isAllowCredentials());
$cache_id = $this->generatePreflightCacheKey($request);
$this->cache_service->storeHash($cache_id, $data->toArray(), CORSRequestPreflightData::$cache_lifetime);
// ----Step 2c: Return corresponding response - This part should be customized with application specific constraints.....
return $this->makePreflightResponse($request);
}
break;
case CORSRequestPreflightType::COMPLEX_REQUEST:
{
$cache_id = $this->generatePreflightCacheKey($request);
// ----Step 2a: Check if the current request has an entry into the preflighted requests Cache
$data = $this->cache_service->getHash($cache_id, CORSRequestPreflightData::$cache_attributes);
if (!count($data))
{
// there wasnt preflight so just regular processing
return null;
}
// ----Step 2b: Check that pre-flight information declared during the pre-flight request match the current request on key information
$match = false;
// ------Start with comparison of "Origin" HTTP header (according to utility method impl. used to retrieve header reference cannot be null)...
if ($request->headers->get('Origin') === $data['origin'])
{
// ------Continue with HTTP method...
if ($request->getMethod() === $data['expected_method'])
{
// ------Finish with custom HTTP headers (use an method to avoid manual iteration on collection to increase the speed)...
$x_headers = self::getCustomHeaders($request);
$x_headers_pre = explode(',', $data['expected_custom_headers']);
sort($x_headers);
sort($x_headers_pre);
if (count(array_diff($x_headers, $x_headers_pre)) === 0)
{
$match = true;
}
}
}
if (!$match)
{
$response = new Response();
$response->setStatusCode(403);
return $response;
}
$actual_request = true;
}
break;
case CORSRequestPreflightType::SIMPLE_REQUEST:
{
// origins, do not set any additional headers and terminate this set of steps.
if (!$this->isAllowedOrigin($request)) {
$response = new Response();
$response->setStatusCode(403);
return $response;
}
$actual_request = true;
// If the resource supports credentials add a single Access-Control-Allow-Origin header, with the value
// of the Origin header as value, and add a single Access-Control-Allow-Credentials header with the
// case-sensitive string "true" as value.
// Otherwise, add a single Access-Control-Allow-Origin header, with either the value of the Origin header
// or the string "*" as value.
}
break;
}
}
if ($actual_request)
{
// Save response headers
$cache_id = $this->generatePreflightCacheKey($request);
// ----Step 2a: Check if the current request has an entry into the preflighted requests Cache
$data = $this->cache_service->getHash($cache_id, CORSRequestPreflightData::$cache_attributes);
$this->headers['Access-Control-Allow-Origin'] = $request->headers->get('Origin');
if (isset($data['allows_credentials']) && $data['allows_credentials'] == true)
{
$this->headers['Access-Control-Allow-Credentials'] = 'true';
}
/**
* During a CORS request, the getResponseHeader() method can only access simple response headers.
* Simple response headers are defined as follows:
** Cache-Control
** Content-Language
** Content-Type
** Expires
** Last-Modified
** Pragma
* If you want clients to be able to access other headers,
* you have to use the Access-Control-Expose-Headers header.
* The value of this header is a comma-delimited list of response headers you want to expose
* to the client.
*/
$exposed_headers = Config::get('cors.exposed_headers', 'Content-Type, Expires');
if (!empty($exposed_headers))
{
$this->headers['Access-Control-Expose-Headers'] = $exposed_headers ;
}
}
}
return $response;
}
$actual_request = true;
// If the resource supports credentials add a single Access-Control-Allow-Origin header, with the value
// of the Origin header as value, and add a single Access-Control-Allow-Credentials header with the
// case-sensitive string "true" as value.
// Otherwise, add a single Access-Control-Allow-Origin header, with either the value of the Origin header
// or the string "*" as value.
}
break;
}
}
if ($actual_request)
{
// Save response headers
$cache_id = $this->generatePreflightCacheKey($request);
// ----Step 2a: Check if the current request has an entry into the preflighted requests Cache
$data = $this->cache_service->getHash($cache_id, CORSRequestPreflightData::$cache_attributes);
$this->headers['Access-Control-Allow-Origin'] = $request->headers->get('Origin');
if (isset($data['allows_credentials']) && $data['allows_credentials'] == true)
{
$this->headers['Access-Control-Allow-Credentials'] = 'true';
}
/**
* During a CORS request, the getResponseHeader() method can only access simple response headers.
* Simple response headers are defined as follows:
** Cache-Control
** Content-Language
** Content-Type
** Expires
** Last-Modified
** Pragma
* If you want clients to be able to access other headers,
* you have to use the Access-Control-Expose-Headers header.
* The value of this header is a comma-delimited list of response headers you want to expose
* to the client.
*/
$exposed_headers = Config::get('cors.exposed_headers', 'Content-Type, Expires');
if (!empty($exposed_headers))
{
$this->headers['Access-Control-Expose-Headers'] = $exposed_headers ;
}
}
}
public function postProcess(Request $request, Response $response)
{
// add CORS response headers
if (count($this->headers) > 0)
{
$response->headers->add($this->headers);
}
return $response;
}
public function postProcess(Request $request, Response $response)
{
// add CORS response headers
if (count($this->headers) > 0)
{
$response->headers->add($this->headers);
}
return $response;
}
/**
* @param Request $request
* @return Response
*/
private function makePreflightResponse(Request $request)
{
$response = new Response();
if (!$this->isAllowedOrigin($request))
{
$response->headers->set('Access-Control-Allow-Origin', 'null');
$response->setStatusCode(403);
return $response;
}
$response->headers->set('Access-Control-Allow-Origin', $request->headers->get('Origin'));
// The Access-Control-Request-Method header indicates which method will be used in the actual
// request as part of the preflight request
// check request method
if ($request->headers->get('Access-Control-Request-Method') != $this->current_endpoint->getHttpMethod())
{
$response->setStatusCode(405);
return $response;
}
// The Access-Control-Allow-Credentials header indicates whether the response to request
// can be exposed when the omit credentials flag is unset. When part of the response to a preflight request
// it indicates that the actual request can include user credentials.
if ( $this->current_endpoint->isAllowCredentials())
{
$response->headers->set('Access-Control-Allow-Credentials', 'true');
}
if (Config::get('cors.use_pre_flight_caching', false))
{
// The Access-Control-Max-Age header indicates how long the response can be cached, so that for
// subsequent requests, within the specified time, no preflight request has to be made.
$response->headers->set('Access-Control-Max-Age', Config::get('cors.max_age', 32000));
}
// The Access-Control-Allow-Headers header indicates, as part of the response to a preflight request,
// which header field names can be used during the actual request
$response->headers->set('Access-Control-Allow-Headers', $this->allowed_headers);
/**
* @param Request $request
* @return Response
*/
private function makePreflightResponse(Request $request)
{
$response = new Response();
if (!$this->isAllowedOrigin($request))
{
$response->headers->set('Access-Control-Allow-Origin', 'null');
$response->setStatusCode(403);
return $response;
}
$response->headers->set('Access-Control-Allow-Origin', $request->headers->get('Origin'));
// The Access-Control-Request-Method header indicates which method will be used in the actual
// request as part of the preflight request
// check request method
if ($request->headers->get('Access-Control-Request-Method') != $this->current_endpoint->getHttpMethod())
{
$response->setStatusCode(405);
return $response;
}
// The Access-Control-Allow-Credentials header indicates whether the response to request
// can be exposed when the omit credentials flag is unset. When part of the response to a preflight request
// it indicates that the actual request can include user credentials.
if ( $this->current_endpoint->isAllowCredentials())
{
$response->headers->set('Access-Control-Allow-Credentials', 'true');
}
if (Config::get('cors.use_pre_flight_caching', false))
{
// The Access-Control-Max-Age header indicates how long the response can be cached, so that for
// subsequent requests, within the specified time, no preflight request has to be made.
$response->headers->set('Access-Control-Max-Age', Config::get('cors.max_age', 32000));
}
// The Access-Control-Allow-Headers header indicates, as part of the response to a preflight request,
// which header field names can be used during the actual request
$response->headers->set('Access-Control-Allow-Headers', $this->allowed_headers);
//The Access-Control-Allow-Methods header indicates, as part of the response to a preflight request,
// which methods can be used during the actual request.
$response->headers->set('Access-Control-Allow-Methods', $this->allowed_methods);
// The Access-Control-Request-Headers header indicates which headers will be used in the actual request
// as part of the preflight request.
$headers = $request->headers->get('Access-Control-Request-Headers');
if ($headers)
{
$headers = trim(strtolower($headers));
$allow_headers = explode(', ', $this->allowed_headers);
foreach (preg_split('{, *}', $headers) as $header)
{
//if they are simple headers then skip them
if (in_array($header, self::$simple_headers, true))
{
continue;
}
//check is the requested header is on the list of allowed headers
if (!in_array($header, $allow_headers, true))
{
$response->setStatusCode(400);
$response->setContent('Unauthorized header '.$header);
break;
}
}
}
//OK - No Content
$response->setStatusCode(204);
return $response;
}
//The Access-Control-Allow-Methods header indicates, as part of the response to a preflight request,
// which methods can be used during the actual request.
$response->headers->set('Access-Control-Allow-Methods', $this->allowed_methods);
// The Access-Control-Request-Headers header indicates which headers will be used in the actual request
// as part of the preflight request.
$headers = $request->headers->get('Access-Control-Request-Headers');
if ($headers)
{
$headers = trim(strtolower($headers));
$allow_headers = explode(', ', $this->allowed_headers);
foreach (preg_split('{, *}', $headers) as $header)
{
//if they are simple headers then skip them
if (in_array($header, self::$simple_headers, true))
{
continue;
}
//check is the requested header is on the list of allowed headers
if (!in_array($header, $allow_headers, true))
{
$response->setStatusCode(400);
$response->setContent('Unauthorized header '.$header);
break;
}
}
}
//OK - No Content
$response->setStatusCode(204);
return $response;
}
/**
* @param Request $request
* @returns bool
*/
private function isValidCORSRequest(Request $request)
{
/**
* The presence of the Origin header does not necessarily mean that the request is a cross-origin request.
* While all cross-origin requests will contain an Origin header,
/**
* @param Request $request
* @returns bool
*/
private function isValidCORSRequest(Request $request)
{
/**
* The presence of the Origin header does not necessarily mean that the request is a cross-origin request.
* While all cross-origin requests will contain an Origin header,
* Origin header on same-origin requests. But Chrome and Safari include an Origin header on
* same-origin POST/PUT/DELETE requests (same-origin GET requests will not have an Origin header).
*/
return $request->headers->has('Origin');
}
* Origin header on same-origin requests. But Chrome and Safari include an Origin header on
* same-origin POST/PUT/DELETE requests (same-origin GET requests will not have an Origin header).
*/
return $request->headers->has('Origin');
}
/**
* https://www.owasp.org/index.php/CORS_OriginHeaderScrutiny
* Filter that will ensure the following points for each incoming HTTP CORS requests:
* - Have only one and non empty instance of the origin header,
* - Have only one and non empty instance of the host header,
* - The value of the origin header is present in a internal allowed domains list (white list). As we act before the
* step 2 of the CORS HTTP requests/responses exchange process, allowed domains list is yet provided to client,
* - Cache IP of the sender for 1 hour. If the sender send one time a origin domain that is not in the white list
* then all is requests will return an HTTP 403 response (protract allowed domain guessing).
* We use the method above because it's not possible to identify up to 100% that the request come from one expected
* client application, since:
* - All information of a HTTP request can be faked,
* - It's the browser (or others tools) that send the HTTP request then the IP address that we have access to is the
* client IP address.
* @param Request $request
* @return bool
*/
private function testOriginHeaderScrutiny(Request $request)
{
/* Step 0 : Check presence of client IP in black list */
$client_ip = $request->getClientIp();
if (Cache::has(self::CORS_IP_BLACKLIST_PREFIX . $client_ip))
{
return false;
}
/* Step 1 : Check that we have only one and non empty instance of the "Origin" header */
$origin = $request->headers->get('Origin', null, false);
if (is_array($origin) && count($origin) > 1)
{
// If we reach this point it means that we have multiple instance of the "Origin" header
// Add client IP address to black listed client
$expiresAt = Carbon::now()->addMinutes(60);
Cache::put(self::CORS_IP_BLACKLIST_PREFIX . $client_ip, self::CORS_IP_BLACKLIST_PREFIX . $client_ip, $expiresAt);
return false;
}
/* Step 2 : Check that we have only one and non empty instance of the "Host" header */
$host = $request->headers->get('Host', null, false);
//Have only one and non empty instance of the host header,
if (is_array($host) && count($host) > 1)
{
// If we reach this point it means that we have multiple instance of the "Host" header
$expiresAt = Carbon::now()->addMinutes(60);
Cache::put(self::CORS_IP_BLACKLIST_PREFIX . $client_ip, self::CORS_IP_BLACKLIST_PREFIX . $client_ip, $expiresAt);
return false;
}
/* Step 3 : Perform analysis - Origin header is required */
/**
* https://www.owasp.org/index.php/CORS_OriginHeaderScrutiny
* Filter that will ensure the following points for each incoming HTTP CORS requests:
* - Have only one and non empty instance of the origin header,
* - Have only one and non empty instance of the host header,
* - The value of the origin header is present in a internal allowed domains list (white list). As we act before the
* step 2 of the CORS HTTP requests/responses exchange process, allowed domains list is yet provided to client,
* - Cache IP of the sender for 1 hour. If the sender send one time a origin domain that is not in the white list
* then all is requests will return an HTTP 403 response (protract allowed domain guessing).
* We use the method above because it's not possible to identify up to 100% that the request come from one expected
* client application, since:
* - All information of a HTTP request can be faked,
* - It's the browser (or others tools) that send the HTTP request then the IP address that we have access to is the
* client IP address.
* @param Request $request
* @return bool
*/
private function testOriginHeaderScrutiny(Request $request)
{
/* Step 0 : Check presence of client IP in black list */
$client_ip = $request->getClientIp();
if (Cache::has(self::CORS_IP_BLACKLIST_PREFIX . $client_ip))
{
return false;
}
/* Step 1 : Check that we have only one and non empty instance of the "Origin" header */
$origin = $request->headers->get('Origin', null, false);
if (is_array($origin) && count($origin) > 1)
{
// If we reach this point it means that we have multiple instance of the "Origin" header
// Add client IP address to black listed client
$expiresAt = Carbon::now()->addMinutes(60);
Cache::put(self::CORS_IP_BLACKLIST_PREFIX . $client_ip, self::CORS_IP_BLACKLIST_PREFIX . $client_ip, $expiresAt);
return false;
}
/* Step 2 : Check that we have only one and non empty instance of the "Host" header */
$host = $request->headers->get('Host', null, false);
//Have only one and non empty instance of the host header,
if (is_array($host) && count($host) > 1)
{
// If we reach this point it means that we have multiple instance of the "Host" header
$expiresAt = Carbon::now()->addMinutes(60);
Cache::put(self::CORS_IP_BLACKLIST_PREFIX . $client_ip, self::CORS_IP_BLACKLIST_PREFIX . $client_ip, $expiresAt);
return false;
}
/* Step 3 : Perform analysis - Origin header is required */
$origin = $request->headers->get('Origin');
$host = $request->headers->get('Host');
$server_name = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
$origin_host = @parse_url($origin, PHP_URL_HOST);
$origin = $request->headers->get('Origin');
$host = $request->headers->get('Host');
$server_name = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
$origin_host = @parse_url($origin, PHP_URL_HOST);
// check origin not empty and allowed
// check origin not empty and allowed
if (!$this->isAllowedOrigin($origin))
{
$expiresAt = Carbon::now()->addMinutes(60);
Cache::put(self::CORS_IP_BLACKLIST_PREFIX . $client_ip, self::CORS_IP_BLACKLIST_PREFIX . $client_ip, $expiresAt);
return false;
}
if (!$this->isAllowedOrigin($origin))
{
$expiresAt = Carbon::now()->addMinutes(60);
Cache::put(self::CORS_IP_BLACKLIST_PREFIX . $client_ip, self::CORS_IP_BLACKLIST_PREFIX . $client_ip, $expiresAt);
return false;
}
if (is_null($host) || $server_name != $host || is_null($origin_host) || $origin_host == $server_name)
{
$expiresAt = Carbon::now()->addMinutes(60);
Cache::put(self::CORS_IP_BLACKLIST_PREFIX . $client_ip, self::CORS_IP_BLACKLIST_PREFIX . $client_ip, $expiresAt);
return false;
}
if (is_null($host) || $server_name != $host || is_null($origin_host) || $origin_host == $server_name)
{
$expiresAt = Carbon::now()->addMinutes(60);
Cache::put(self::CORS_IP_BLACKLIST_PREFIX . $client_ip, self::CORS_IP_BLACKLIST_PREFIX . $client_ip, $expiresAt);
return false;
}
/* Step 4 : Finalize request next step */
return true;
}
/* Step 4 : Finalize request next step */
return true;
}
private function checkEndPoint($endpoint_path, $http_method)
{
$this->current_endpoint = $this->endpoint_repository->getApiEndpointByUrlAndMethod($endpoint_path, $http_method);
if (is_null($this->current_endpoint))
{
return false;
}
if (!$this->current_endpoint->isAllowCors() || !$this->current_endpoint->isActive())
{
return false;
}
return true;
}
private function checkEndPoint($endpoint_path, $http_method)
{
$this->current_endpoint = $this->endpoint_repository->getApiEndpointByUrlAndMethod($endpoint_path, $http_method);
if (is_null($this->current_endpoint))
{
return false;
}
if (!$this->current_endpoint->isAllowCors() || !$this->current_endpoint->isActive())
{
return false;
}
return true;
}
/**
* @param string $origin
* @return bool
*/
private function isAllowedOrigin($origin)
{
return true;
}
/**
* @param string $origin
* @return bool
*/
private function isAllowedOrigin($origin)
{
return true;
}
private static function getRequestType(Request $request)
{
private static function getRequestType(Request $request)
{
$type = CORSRequestPreflightType::UNKNOWN;
$http_method = $request->getMethod();
$content_type = $request->headers->has('Content-Type') ? strtolower( $request->headers->get('Content-Type')) : null;
$type = CORSRequestPreflightType::UNKNOWN;
$http_method = $request->getMethod();
$content_type = $request->headers->has('Content-Type') ? strtolower( $request->headers->get('Content-Type')) : null;
if (false !== $pos = strpos($content_type, ';')) {
if (false !== $pos = strpos($content_type, ';')) {
$content_type = substr($content_type, 0, $pos);
}
$http_method = strtoupper($http_method);
$http_method = strtoupper($http_method);
if ($http_method === 'OPTIONS' && $request->headers->has('Access-Control-Request-Method'))
{
$type = CORSRequestPreflightType::REQUEST_FOR_PREFLIGHT;
}
else
{
if (self::hasCustomHeaders($request))
{
$type = CORSRequestPreflightType::COMPLEX_REQUEST;
}
elseif ($http_method === 'POST' && !in_array($content_type, self::$simple_content_header_values, true))
{
$type = CORSRequestPreflightType::COMPLEX_REQUEST;
}
elseif (!in_array($http_method, self::$simple_http_methods, true))
{
$type = CORSRequestPreflightType::COMPLEX_REQUEST;
}
else
{
$type = CORSRequestPreflightType::SIMPLE_REQUEST;
}
}
return $type;
}
if ($http_method === 'OPTIONS' && $request->headers->has('Access-Control-Request-Method'))
{
$type = CORSRequestPreflightType::REQUEST_FOR_PREFLIGHT;
}
else
{
if (self::hasCustomHeaders($request))
{
$type = CORSRequestPreflightType::COMPLEX_REQUEST;
}
elseif ($http_method === 'POST' && !in_array($content_type, self::$simple_content_header_values, true))
{
$type = CORSRequestPreflightType::COMPLEX_REQUEST;
}
elseif (!in_array($http_method, self::$simple_http_methods, true))
{
$type = CORSRequestPreflightType::COMPLEX_REQUEST;
}
else
{
$type = CORSRequestPreflightType::SIMPLE_REQUEST;
}
}
return $type;
}
private static function getCustomHeaders(Request $request)
{
$custom_headers = array();
foreach ($request->headers->all() as $k => $h)
{
if (starts_with('X-', strtoupper(trim($k))))
{
array_push($custom_headers, strtoupper(trim($k)));
}
}
return $custom_headers;
}
private static function getCustomHeaders(Request $request)
{
$custom_headers = array();
foreach ($request->headers->all() as $k => $h)
{
if (starts_with('X-', strtoupper(trim($k))))
{
array_push($custom_headers, strtoupper(trim($k)));
}
}
return $custom_headers;
}
private static function hasCustomHeaders(Request $request)
{
return count(self::getCustomHeaders($request)) > 0;
}
private static function hasCustomHeaders(Request $request)
{
return count(self::getCustomHeaders($request)) > 0;
}
}

View File

@ -23,7 +23,7 @@ class CORSRequestPreflightData
// ttl on seconds
public static $cache_lifetime = 10;
public static $cache_attributes = array('sender', 'uri', 'origin', 'expected_method', 'expected_custom_headers', 'allows_credentials');
public static $cache_attributes = ['sender', 'uri', 'origin', 'expected_method', 'expected_custom_headers', 'allows_credentials'];
/** Final HTTP request expected method */
private $expected_method = null;
@ -69,7 +69,7 @@ class CORSRequestPreflightData
*/
public function toArray()
{
$res = array();
$res = [];
$res['sender'] = $this->sender;
$res['uri'] = $this->uri;
$res['origin'] = $this->origin;

View File

@ -148,8 +148,9 @@ class OAuth2BearerAccessTokenRequestValidator
if ((!in_array($realm, $audience))) {
throw new InvalidGrantTypeException(OAuth2Protocol::OAuth2Protocol_Error_InvalidToken);
}
if ($token_info->getApplicationType() === 'JS_CLIENT' && str_contains($token_info->getAllowedOrigins(),
$origin) === false
if (
$token_info->getApplicationType() === 'JS_CLIENT'
&& (is_null($origin) || empty($origin)|| str_contains($token_info->getAllowedOrigins(), $origin) === false )
) {
//check origins
throw new OAuth2ResourceServerException(
@ -197,6 +198,7 @@ class OAuth2BearerAccessTokenRequestValidator
if (!is_null($token_info->getUserId()))
{
Log::debug(sprintf("OAuth2BearerAccessTokenRequestValidator::handle user id is not null (%s)", $token_info->getUserId()));
$context['user_id'] = $token_info->getUserId();
$context['user_external_id'] = $token_info->getUserExternalId();
$context['user_identifier'] = $token_info->getUserIdentifier();

View File

@ -93,8 +93,8 @@ final class RateLimitMiddleware extends ThrottleRequests
return $next($request);
}
if ($this->limiter->tooManyAttempts($key, $max_attempts, $decay_minutes)) {
return $this->buildResponse($key, $max_attempts);
if ($this->limiter->tooManyAttempts($key, $max_attempts)) {
return $this->buildException($key, $max_attempts);
}
$this->limiter->hit($key, $decay_minutes);

View File

@ -11,6 +11,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Models\ResourceServer\ApiEndpoint;
use App\Models\ResourceServer\IApiEndpointRepository;
use Closure;

View File

@ -0,0 +1,23 @@
<?php namespace App\Http\Renderers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Interface IRenderer
* @package App\Http\Renderers
*/
interface IRenderer
{
public function render():string;
}

View File

@ -0,0 +1,23 @@
<?php namespace App\Http\Renderers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Interface IRenderersFormats
* @package App\Http\Renderers
*/
interface IRenderersFormats
{
const PDFFormat = 'PDF';
}

View File

@ -0,0 +1,124 @@
<?php namespace App\Http\Renderers;
/**
* Copyright 2019 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use TCPDF;
use models\summit\SummitAttendeeTicket;
/**
* Class SummitAttendeeTicketPDFRenderer
* @package App\Http\Renderers
*/
final class SummitAttendeeTicketPDFRenderer implements IRenderer
{
/**
* @var SummitAttendeeTicket
*/
private $ticket;
/**
* SummitAttendeeTicketPDFRenderer constructor.
* @param SummitAttendeeTicket $ticket
*/
public function __construct(SummitAttendeeTicket $ticket)
{
$this->ticket = $ticket;
}
public function render(): string
{
$order = $this->ticket->getOrder();
$summit = $order->getSummit();
$summit_name = $summit->getName();
$main_venues = $summit->getMainVenues();
$price = $this->ticket->getRawCost().' '.$this->ticket->getCurrency();
$ticket_number = $this->ticket->getNumber();
$location_name = "";
if(count($main_venues) > 0){
$location_name = $main_venues[0]->getName().', '.$main_venues[0]->getFullAddress();
}
$order_number = $order->getNumber();
$dates = $summit->getDatesLabel();
$owner_full_name = $order->getOwnerFullName();
$order_creation_date = $order->getCreatedUTC()->format("Y-m-d H:i:s");
$ticket_type = $this->ticket->getTicketType()->getName();
$attendee_name = $this->ticket->hasOwner() ? $this->ticket->getOwner()->getFullName() : 'TBD';
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetTitle($summit_name. ' '.$this->ticket->getNumber());
// remove default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set font
$pdf->SetFont('helvetica', '', 8);
// add a page
$pdf->AddPage();
$html = view('tickets.raw',[
'summit_name' => $summit_name,
'ticket_type' => $ticket_type,
'price' => $price,
'location_name' => $location_name,
'dates' => $dates,
'order_number' => $order_number,
'owner_full_name' => $owner_full_name,
'order_creation_date' => $order_creation_date,
'attendee_name' => $attendee_name,
])->render();
$pdf->writeHTMLCell(100, 80, 10, 25 , $html, $border=1, $ln=0, $fill=0, $reseth=true, $align='', $autopadding=true);
$pdf->SetFont('helvetica', '', 5.7);
// set style for barcode
$style = [
'border' => 2,
'vpadding' => 'auto',
'hpadding' => 'auto',
'fgcolor' => [0, 0, 0],
'bgcolor' => false, //array(255,255,255)
'module_width' => 1, // width of a single module in points
'module_height' => 1 // height of a single module in points
];
// QRCODE,L : QR-CODE Low error correction
$this->ticket->generateQRCode();
$pdf->write2DBarcode($this->ticket->getQRCode(), 'QRCODE,L', 125, 25, 50, 50, $style, 'N');
$pdf->Text(124, 85, $ticket_number);
//Close and output PDF document
return $pdf->Output($ticket_number.'.pdf', 'S');
}
}

View File

@ -11,30 +11,33 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Route;
// public api ( without AUTHZ [OAUTH2.0])
Route::group([
'namespace' => 'App\Http\Controllers',
'prefix' => 'api/public/v1',
'before' => [],
'after' => [],
'prefix' => 'api/public/v1',
'before' => [],
'after' => [],
'middleware' => [
'ssl',
'rate.limit:1000,1', // 1000 request per minute
'rate.limit:10000,1', // 10000 request per minute
'etags'
]
], function(){
], function () {
// members
Route::group(['prefix'=>'members'], function() {
Route::group(['prefix' => 'members'], function () {
Route::get('', 'OAuth2MembersApiController@getAll');
});
// speakers
Route::group(['prefix'=>'speakers'], function() {
Route::group(['prefix'=>'{speaker_id}'], function(){
Route::group(['prefix'=>'edit-permission'], function(){
Route::group(['prefix'=>'{token}'], function(){
Route::group(['prefix' => 'speakers'], function () {
Route::group(['prefix' => '{speaker_id}'], function () {
Route::group(['prefix' => 'edit-permission'], function () {
Route::group(['prefix' => '{token}'], function () {
Route::get('approve', 'OAuth2SummitSpeakersApiController@approveSpeakerEditPermission');
Route::get('decline', 'OAuth2SummitSpeakersApiController@declineSpeakerEditPermission');
});
@ -43,26 +46,54 @@ Route::group([
});
// summits
Route::group(['prefix'=>'summits'], function() {
Route::get('', [ 'middleware' => 'cache:'.Config::get('cache_api_response.get_summit_response_lifetime', 600), 'uses' => 'OAuth2SummitApiController@getSummits']);
Route::group(['prefix' => 'summits'], function () {
Route::get('', ['middleware' => 'cache:' . Config::get('cache_api_response.get_summit_response_lifetime', 600), 'uses' => 'OAuth2SummitApiController@getSummits']);
Route::group(['prefix' => 'all'], function () {
Route::get('current', 'OAuth2SummitApiController@getAllCurrentSummit');
Route::group(['prefix' => 'selection-plans'], function () {
Route::get('current/{status}', 'OAuth2SummitSelectionPlansApiController@getCurrentSelectionPlanByStatus')->where('status', 'submission|selection|voting');
Route::get('', 'OAuth2SummitApiController@getAllSummits');
Route::get('current', 'OAuth2SummitApiController@getAllCurrentSummit');
Route::get('{id}', 'OAuth2SummitApiController@getAllSummitByIdOrSlug');
Route::group(['prefix' => 'payments'], function () {
Route::group(['prefix' => '{application_name}'], function () {
Route::post('confirm', 'PaymentGatewayWebHookController@genericConfirm');
});
});
Route::group(['prefix' => 'bookable-rooms'], function () {
Route::group(['prefix' => 'orders'], function () {
Route::group(['prefix' => '{order_hash}'], function () {
Route::group(['prefix' => 'tickets'], function () {
Route::put('', "OAuth2SummitOrdersApiController@updateTicketsByOrderHash");
});
});
Route::group(['prefix' => 'all'], function () {
Route::group(['prefix' => 'reservations'], function () {
// api/public/v1/summits/all/bookable-rooms/all/reservations/confirm ( open endpoint for payment gateway callbacks)
Route::post("confirm", "OAuth2SummitLocationsApiController@confirmBookableVenueRoomReservation");
Route::group(['prefix' => 'tickets'], function () {
Route::group(['prefix' => '{hash}'], function () {
Route::get('', "OAuth2SummitOrdersApiController@getTicketByHash");
Route::put('', "OAuth2SummitOrdersApiController@updateTicketByHash");
Route::put('regenerate', "OAuth2SummitOrdersApiController@regenerateTicketHash");
Route::get('pdf', "OAuth2SummitOrdersApiController@getTicketPDFByHash");
});
});
});
});
});
Route::group(['prefix' => '{id}'], function () {
Route::group(['prefix' => 'payments'], function () {
Route::group(['prefix' => '{application_name}'], function () {
Route::post('confirm', 'PaymentGatewayWebHookController@confirm');
});
});
Route::group(['prefix' => 'selection-plans'], function () {
Route::get('current/{status}', 'OAuth2SummitSelectionPlansApiController@getCurrentSelectionPlanByStatus')->where('status', 'submission|selection|voting');
});
Route::get('', [ 'middleware' => 'cache:'.Config::get('cache_api_response.get_summit_response_lifetime', 1200), 'uses' => 'OAuth2SummitApiController@getSummit'])->where('id', 'current|[0-9]+');
// members
Route::group(['prefix' => 'members'], function () {
@ -97,7 +128,7 @@ Route::group([
Route::group(['prefix' => 'locations'], function () {
Route::group(['prefix' => '{location_id}'], function () {
Route::get('', 'OAuth2SummitLocationsApiController@getLocation');
Route::get('/events/published','OAuth2SummitLocationsApiController@getLocationPublishedEvents');
Route::get('/events/published', 'OAuth2SummitLocationsApiController@getLocationPublishedEvents');
Route::group(['prefix' => 'banners'], function () {
Route::get('', 'OAuth2SummitLocationsApiController@getLocationBanners');
});
@ -109,8 +140,6 @@ Route::group([
Route::get('sent', 'OAuth2SummitNotificationsApiController@getAllApprovedByUser');
});
// speakers
// speakers
Route::group(['prefix' => 'speakers'], function () {
Route::get('', 'OAuth2SummitSpeakersApiController@getSpeakers');
@ -119,6 +148,24 @@ Route::group([
});
});
// orders
Route::group(['prefix' => 'orders'], function () {
Route::post('reserve', 'OAuth2SummitOrdersApiController@reserve');
Route::group(['prefix' => '{hash}'], function () {
Route::put('checkout', 'OAuth2SummitOrdersApiController@checkout');
Route::group(['prefix' => 'tickets'], function () {
Route::get('mine', 'OAuth2SummitOrdersApiController@getMyTicketByOrderHash');
});
Route::delete('', 'OAuth2SummitOrdersApiController@cancel');
});
});
// registration invitations
Route::group(['prefix' => 'registration-invitations'], function () {
Route::group(['prefix' => '{email}'], function () {
Route::get('', 'OAuth2SummitOrdersApiController@getByEmail');
});
});
});
});
@ -162,7 +209,6 @@ Route::group([
});
Route::group([
'namespace' => 'App\Http\Controllers',
'prefix' => '.well-known',

View File

@ -48,21 +48,24 @@ final class CSVExporter
* @return string
*/
public function export(array $items, $field_separator = ",", array $header = [], array $formatters){
$flag = false;
$output = '';
$flag = false;
$output = '';
$header = [];
$originalHeader = [];
foreach ($items as $row) {
if (!$flag) {
// display field/column names as first row
if(!count($header))
$header = array_keys($row);
$originalHeader = $header = array_keys($row);
array_walk($header, array($this, 'cleanData'));
$output .= implode($field_separator, $header) . PHP_EOL;;
$flag = true;
}
array_walk($row, array($this, 'cleanData'));
$values = [];
foreach ($header as $key){
$val = isset($row[$key])? $row[$key] : '';
foreach ($originalHeader as $key){
$val = $row[$key] ?? '';
if(isset($formatters[$key]))
$val = $formatters[$key]->format($val);
if(is_array($val)) $val = '';

View File

@ -11,15 +11,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Services\FileSystem\FileNameSanitizer;
use App\Services\Model\IFolderService;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use models\exceptions\ValidationException;
use models\main\File;
use Behat\Transliterator\Transliterator;
use models\main\IFolderRepository;
/**
* Class FileUploader
* @package App\Http\Utils
@ -31,11 +30,6 @@ final class FileUploader implements IFileUploader
*/
private $folder_service;
/**
* @var IBucket
*/
private $bucket;
/**
* @var IFolderRepository
*/
@ -45,21 +39,17 @@ final class FileUploader implements IFileUploader
* FileUploader constructor.
* @param IFolderService $folder_service
* @param IFolderRepository $folder_repository
* @param IBucket $bucket
*/
public function __construct
(
IFolderService $folder_service,
IFolderRepository $folder_repository,
IBucket $bucket
IFolderRepository $folder_repository
)
{
$this->folder_service = $folder_service;
$this->folder_repository = $folder_repository;
$this->bucket = $bucket;
}
private static $default_replacements = [
'/\s/' => '-', // remove whitespace
'/_/' => '-', // underscores to dashes
@ -70,22 +60,18 @@ final class FileUploader implements IFileUploader
/**
* @param UploadedFile $file
* @param $folder_name
* @param string $path
* @param bool $is_image
* @return File
* @throws \Exception
*/
public function build(UploadedFile $file, $folder_name, $is_image = false){
public function build(UploadedFile $file, string $path, bool $is_image = false){
$attachment = new File();
try {
$client_original_name = $file->getClientOriginalName();
$ext = pathinfo($client_original_name, PATHINFO_EXTENSION);
$client_original_name = trim(Transliterator::utf8ToAscii($client_original_name));
foreach(self::$default_replacements as $regex => $replace) {
$client_original_name = preg_replace($regex, $replace, $client_original_name);
}
$client_original_name = FileNameSanitizer::sanitize($client_original_name);
$idx = 1;
$name = pathinfo($client_original_name, PATHINFO_FILENAME);
@ -105,18 +91,23 @@ final class FileUploader implements IFileUploader
throw new ValidationException("empty file name is not valid");
}
Log::debug(sprintf("FileUploader::build: folder_name %s client original name %s", $folder_name, $client_original_name));
Log::debug(sprintf("FileUploader::build: folder_name %s client original name %s", $path, $client_original_name));
$local_path = Storage::putFileAs(sprintf('/public/%s', $folder_name), $file, $client_original_name);
$local_path = Storage::disk('public')->putFileAs
(
$path,
$file,
$client_original_name
);
Log::debug(sprintf("FileUploader::build: saved to local path %s", $local_path));
Log::debug(sprintf("FileUploader::build: invoking folder service findOrMake folder_name %s", $folder_name));
$folder = $this->folder_service->findOrMake($folder_name);
$local_path = Storage::disk()->path($local_path);
Log::debug(sprintf("FileUploader::build: invoking folder service findOrMake folder_name %s", $path));
$folder = $this->folder_service->findOrMake($path);
$local_path = Storage::disk('public')->path($local_path);
$attachment->setParent($folder);
$attachment->setName($client_original_name);
$file_name = sprintf("assets/%s/%s", $folder_name, $client_original_name);
$file_name = sprintf("assets/%s/%s", $path, $client_original_name);
Log::debug(sprintf("FileUploader::build file_name %s", $file_name));
$attachment->setFilename($file_name);
$title = str_replace(['-','_'],' ', preg_replace('/\.[^.]+$/', '', $title));
@ -126,7 +117,13 @@ final class FileUploader implements IFileUploader
if ($is_image) // set className
$attachment->setImage();
Log::debug(sprintf("FileUploader::build uploading to bucket %s", $local_path));
$this->bucket->put($attachment, $local_path);
// store at cloud
Storage::disk('assets')->putFileAs
(
$path,
$file,
$client_original_name
);
$attachment->setCloudMeta('LastPut', time());
$attachment->setCloudStatus('Live');
$attachment->setCloudSize(filesize($local_path));

View File

@ -11,6 +11,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
@ -44,23 +45,52 @@ class DoctrineFilterMapping extends FilterMapping
* @param FilterElement $filter
* @return QueryBuilder
*/
public function apply(QueryBuilder $query, FilterElement $filter){
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
public function apply(QueryBuilder $query, FilterElement $filter)
{
$value = $filter->getValue();
if (is_array($value)) {
$inner_where = '( ';
if(strstr($where,":value")) {
$where = str_replace(":value", ":value_" . $param_count, $where);
$has_param = true;
}
foreach ($value as $val) {
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
if(strstr($where,":operator"))
$where = str_replace(":operator", $filter->getOperator(), $where);
if (strstr($where, ":value")) {
$where = str_replace(":value", ":value_" . $param_count, $where);
$has_param = true;
}
$query = $query->andWhere($where);
if (strstr($where, ":operator"))
$where = str_replace(":operator", $filter->getOperator(), $where);
if($has_param){
$query = $query->setParameter(":value_".$param_count, $filter->getValue());
if ($has_param) {
$query = $query->setParameter(":value_" . $param_count, $val);
}
$inner_where .= $where . " " . $filter->getSameFieldOp() . " ";
}
$inner_where = substr($inner_where, 0, (strlen($filter->getSameFieldOp()) + 1) * -1);
$inner_where .= ' )';
$query = $query->andWhere($inner_where);
} else {
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
if (strstr($where, ":value")) {
$where = str_replace(":value", ":value_" . $param_count, $where);
$has_param = true;
}
if (strstr($where, ":operator"))
$where = str_replace(":operator", $filter->getOperator(), $where);
$query = $query->andWhere($where);
if ($has_param) {
$query = $query->setParameter(":value_" . $param_count, $filter->getValue());
}
}
return $query;
}
@ -70,23 +100,53 @@ class DoctrineFilterMapping extends FilterMapping
* @param FilterElement $filter
* @return string
*/
public function applyOr(QueryBuilder $query, FilterElement $filter){
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
public function applyOr(QueryBuilder $query, FilterElement $filter)
{
$value = $filter->getValue();
if (is_array($value)) {
if(strstr($where,":value")) {
$inner_where = '( ';
foreach ($value as $val) {
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
if (strstr($where, ":value")) {
$where = str_replace(":value", ":value_" . $param_count, $where);
$has_param = true;
}
if (strstr($where, ":operator"))
$where = str_replace(":operator", $filter->getOperator(), $where);
if ($has_param) {
$query->setParameter(":value_" . $param_count, $value);
}
$inner_where .= $where . " " . $filter->getSameFieldOp() . " ";
}
$inner_where = substr($inner_where, 0, (strlen($filter->getSameFieldOp()) + 1) * -1);
$inner_where .= ' )';
return $inner_where;
}
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
if (strstr($where, ":value")) {
$where = str_replace(":value", ":value_" . $param_count, $where);
$has_param = true;
}
if(strstr($where,":operator"))
if (strstr($where, ":operator"))
$where = str_replace(":operator", $filter->getOperator(), $where);
if($has_param){
$query->setParameter(":value_".$param_count, $filter->getValue());
if ($has_param) {
$query->setParameter(":value_" . $param_count, $filter->getValue());
}
return $where;
}
}

View File

@ -11,8 +11,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
/**
* Class DoctrineJoinFilterMapping
* @package utils
@ -50,26 +52,60 @@ class DoctrineJoinFilterMapping extends FilterMapping
* @param FilterElement $filter
* @return QueryBuilder
*/
public function apply(QueryBuilder $query, FilterElement $filter){
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
public function apply(QueryBuilder $query, FilterElement $filter)
{
$value = $filter->getValue();
if(strstr($where,":value")) {
$where = str_replace(":value", ":value_" . $param_count, $where);
$has_param = true;
}
if (is_array($value)) {
$inner_where = '( ';
if(strstr($where,":operator"))
$where = str_replace(":operator", $filter->getOperator(), $where);
foreach ($value as $val) {
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
if(!in_array($this->alias, $query->getAllAliases()))
$query->innerJoin($this->table, $this->alias, Join::WITH);
if (strstr($where, ":value")) {
$where = str_replace(":value", ":value_" . $param_count, $where);
$has_param = true;
}
$query = $query->andWhere($where);
if (strstr($where, ":operator"))
$where = str_replace(":operator", $filter->getOperator(), $where);
if($has_param){
$query = $query->setParameter(":value_".$param_count, $filter->getValue());
if ($has_param) {
$query = $query->setParameter(":value_" . $param_count, $val);
}
$inner_where .= $where . " " . $filter->getSameFieldOp() . " ";
}
$inner_where = substr($inner_where, 0, (strlen($filter->getSameFieldOp()) + 1) * -1);
$inner_where .= ' )';
if (!in_array($this->alias, $query->getAllAliases()))
$query->innerJoin($this->table, $this->alias, Join::WITH);
$query = $query->andWhere($inner_where);
} else {
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
if (strstr($where, ":value")) {
$where = str_replace(":value", ":value_" . $param_count, $where);
$has_param = true;
}
if (strstr($where, ":operator"))
$where = str_replace(":operator", $filter->getOperator(), $where);
if (!in_array($this->alias, $query->getAllAliases()))
$query->innerJoin($this->table, $this->alias, Join::WITH);
$query = $query->andWhere($where);
if ($has_param) {
$query = $query->setParameter(":value_" . $param_count, $filter->getValue());
}
}
return $query;
@ -81,25 +117,60 @@ class DoctrineJoinFilterMapping extends FilterMapping
* @param FilterElement $filter
* @return string
*/
public function applyOr(QueryBuilder $query, FilterElement $filter){
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
public function applyOr(QueryBuilder $query, FilterElement $filter)
{
$value = $filter->getValue();
if (is_array($value)) {
$inner_where = '( ';
if(strstr($where,":value")) {
foreach ($value as $val) {
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
if (strstr($where, ":value")) {
$where = str_replace(":value", ":value_" . $param_count, $where);
$has_param = true;
}
if (strstr($where, ":operator"))
$where = str_replace(":operator", $filter->getOperator(), $where);
if ($has_param) {
$query->setParameter(":value_" . $param_count, $value);
}
$inner_where .= $where . " " . $filter->getSameFieldOp() . " ";
}
$inner_where = substr($inner_where, 0, (strlen($filter->getSameFieldOp()) + 1) * -1);
$inner_where .= ' )';
if (!in_array($this->alias, $query->getAllAliases()))
$query->innerJoin($this->table, $this->alias, Join::WITH);
return $inner_where;
}
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
if (strstr($where, ":value")) {
$where = str_replace(":value", ":value_" . $param_count, $where);
$has_param = true;
}
if(strstr($where,":operator"))
if (strstr($where, ":operator"))
$where = str_replace(":operator", $filter->getOperator(), $where);
if(!in_array($this->alias, $query->getAllAliases()))
if (!in_array($this->alias, $query->getAllAliases()))
$query->innerJoin($this->table, $this->alias, Join::WITH);
if($has_param){
$query->setParameter(":value_".$param_count, $filter->getValue());
if ($has_param) {
$query->setParameter(":value_" . $param_count, $value);
}
return $where;
}

View File

@ -25,6 +25,41 @@ class DoctrineLeftJoinFilterMapping extends DoctrineJoinFilterMapping
* @return QueryBuilder
*/
public function apply(QueryBuilder $query, FilterElement $filter){
$value = $filter->getValue();
if(is_array($value)){
$inner_where = '( ';
foreach ($value as $val) {
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
if (strstr($where, ":value")) {
$where = str_replace(":value", ":value_" . $param_count, $where);
$has_param = true;
}
if (strstr($where, ":operator"))
$where = str_replace(":operator", $filter->getOperator(), $where);
if ($has_param) {
$query = $query->setParameter(":value_" . $param_count, $val);
}
$inner_where .= $where . " " . $filter->getSameFieldOp() . " ";
}
$inner_where = substr($inner_where, 0, (strlen($filter->getSameFieldOp()) + 1) * -1);
$inner_where .= ' )';
$query = $query->andWhere($inner_where);
if(!in_array($this->alias, $query->getAllAliases()))
$query->leftJoin($this->table, $this->alias, Join::WITH);
return $query;
}
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
@ -37,15 +72,15 @@ class DoctrineLeftJoinFilterMapping extends DoctrineJoinFilterMapping
if(strstr($where,":operator"))
$where = str_replace(":operator", $filter->getOperator(), $where);
if(!in_array($this->alias, $query->getAllAliases()))
$query->leftJoin($this->table, $this->alias, Join::WITH);
$query = $query->andWhere($where);
if($has_param){
$query = $query->setParameter(":value_".$param_count, $filter->getValue());
$query = $query->setParameter(":value_".$param_count, $value);
}
if(!in_array($this->alias, $query->getAllAliases()))
$query->leftJoin($this->table, $this->alias, Join::WITH);
return $query;
}
@ -55,6 +90,39 @@ class DoctrineLeftJoinFilterMapping extends DoctrineJoinFilterMapping
* @return string
*/
public function applyOr(QueryBuilder $query, FilterElement $filter){
$value = $filter->getValue();
if(is_array($value)){
$inner_where = '( ';
foreach ($value as $val) {
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
if (strstr($where, ":value")) {
$where = str_replace(":value", ":value_" . $param_count, $where);
$has_param = true;
}
if (strstr($where, ":operator"))
$where = str_replace(":operator", $filter->getOperator(), $where);
if ($has_param) {
$query->setParameter(":value_" . $param_count, $value);
}
$inner_where .= $where . " " . $filter->getSameFieldOp() . " ";
}
$inner_where = substr($inner_where, 0, (strlen($filter->getSameFieldOp()) + 1) * -1);
$inner_where .= ' )';
if(!in_array($this->alias, $query->getAllAliases()))
$query->leftJoin($this->table, $this->alias, Join::WITH);
return $inner_where;
}
$param_count = $query->getParameters()->count() + 1;
$where = $this->where;
$has_param = false;
@ -67,15 +135,13 @@ class DoctrineLeftJoinFilterMapping extends DoctrineJoinFilterMapping
if(strstr($where,":operator"))
$where = str_replace(":operator", $filter->getOperator(), $where);
if(!in_array($this->alias, $query->getAllAliases()))
$query->leftJoin($this->table, $this->alias, Join::WITH);
if(!in_array($this->alias, $query->getAllAliases()))
$query->leftJoin($this->table, $this->alias, Join::WITH);
if($has_param){
$query->setParameter(":value_".$param_count, $filter->getValue());
$query->setParameter(":value_".$param_count, $value);
}
if(!in_array($this->alias, $query->getAllAliases()))
$query->leftJoin($this->table, $this->alias, Join::WITH);
return $where;
}
}

View File

@ -154,20 +154,31 @@ final class Filter
$values = $filter_key_values[$field];
if(!is_array($values)) $values = [$values];
foreach ($values as $val) {
$validation = Validator::make
(
[$field => $val],
[$field => $rule],
$messages
);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
if(is_array($val)){
foreach($val as $sub_val){
self::_validate($field, $sub_val, $rule, $messages);
}
}
else {
self::_validate($field, $val, $rule, $messages);
}
}
}
}
private static function _validate($field, $val, $rule, $messages){
$validation = Validator::make
(
[$field => $val],
[$field => $rule],
$messages
);
if ($validation->fails()) {
$ex = new ValidationException();
throw $ex->setMessages($validation->messages()->toArray());
}
}
/**
* @param Criteria $criteria
* @param array $mappings
@ -257,22 +268,55 @@ final class Filter
}
if(!empty($condition)) $condition .= ' OR ';
$bindings[sprintf($param_prefix, $param_idx)] = $value;
$condition .= sprintf("%s %s :%s", $mapping_or[0], $filter->getOperator(), sprintf($param_prefix, $param_idx));
++$param_idx;
/**********************/
if(is_array($value)){
$inner_condition = '( ';
foreach ($value as $val) {
$inner_condition .= sprintf(" %s %s :%s %s ", $mapping[0], $filter->getOperator(), sprintf($param_prefix, $param_idx), $filter->getSameFieldOp());
$bindings[sprintf($param_prefix, $param_idx)] = $val;
++$param_idx;
}
$inner_condition = substr($inner_condition, 0, (strlen($filter->getSameFieldOp())+1) * -1);
$inner_condition .= ' )';
$condition .= $inner_condition;
}
else {
$bindings[sprintf($param_prefix, $param_idx)] = $value;
$condition .= sprintf("%s %s :%s", $mapping_or[0], $filter->getOperator(), sprintf($param_prefix, $param_idx));
++$param_idx;
}
/**********************/
}
$query->andWhere($condition);
}
else {
$mapping = explode(':', $mapping);
$value = $filter->getValue();
$condition = '';
if (count($mapping) > 1) {
$value = $this->convertValue($value, $mapping[1]);
}
$bindings[sprintf($param_prefix, $param_idx)] = $value;
$query = $query->andWhere(sprintf("%s %s :%s", $mapping[0], $filter->getOperator(), sprintf($param_prefix, $param_idx)));
++$param_idx;
if(is_array($value)){
$inner_condition = '( ';
foreach ($value as $val) {
$inner_condition .= sprintf(" %s %s :%s %s ", $mapping[0], $filter->getOperator(), sprintf($param_prefix, $param_idx), $filter->getSameFieldOp());
$bindings[sprintf($param_prefix, $param_idx)] = $val;
++$param_idx;
}
$inner_condition = substr($inner_condition, 0, (strlen($filter->getSameFieldOp())+1) * -1);
$inner_condition .= ' )';
$condition .= $inner_condition;
}
else {
$bindings[sprintf($param_prefix, $param_idx)] = $value;
$condition .= sprintf("%s %s :%s", $mapping[0], $filter->getOperator(), sprintf($param_prefix, $param_idx));
++$param_idx;
}
$query->andWhere($condition);
}
}
else if (is_array($filter)) {
@ -316,9 +360,23 @@ final class Filter
}
if(!empty($condition)) $condition .= ' OR ';
$bindings[sprintf($param_prefix, $param_idx)] = $value;
$condition .= sprintf(" %s %s :%s ", $mapping_or[0], $e->getOperator(), sprintf($param_prefix, $param_idx));
++$param_idx;
if(is_array($value)){
$inner_condition = '( ';
foreach ($value as $val) {
$inner_condition .= sprintf(" %s %s :%s %s ", $mapping_or[0], $e->getOperator(), sprintf($param_prefix, $param_idx), $e->getSameFieldOp());
$bindings[sprintf($param_prefix, $param_idx)] = $val;
++$param_idx;
}
$inner_condition = substr($inner_condition, 0, (strlen($e->getSameFieldOp())+1) * -1);
$inner_condition .= ' )';
$condition .= $inner_condition;
}
else {
$bindings[sprintf($param_prefix, $param_idx)] = $value;
$condition .= sprintf("%s %s :%s", $mapping_or[0], $e->getOperator(), sprintf($param_prefix, $param_idx));
++$param_idx;
}
}
if(!empty($sub_or_query)) $sub_or_query .= ' OR ';
$sub_or_query .= ' ( '.$condition.' ) ';
@ -333,9 +391,22 @@ final class Filter
if(!empty($sub_or_query)) $sub_or_query .= ' OR ';
$bindings[sprintf($param_prefix, $param_idx)] = $value;
$sub_or_query .= sprintf(" %s %s :%s ", $mapping[0], $e->getOperator(), sprintf($param_prefix, $param_idx));
++$param_idx;
if(is_array($value)){
$inner_condition = '( ';
foreach ($value as $val) {
$inner_condition .= sprintf(" %s %s :%s %s ", $mapping[0], $e->getOperator(), sprintf($param_prefix, $param_idx), $e->getSameFieldOp());
$bindings[sprintf($param_prefix, $param_idx)] = $val;
++$param_idx;
}
$inner_condition = substr($inner_condition, 0, (strlen($e->getSameFieldOp())+1) * -1);
$inner_condition .= ' )';
$sub_or_query .= $inner_condition;
}
else {
$bindings[sprintf($param_prefix, $param_idx)] = $value;
$sub_or_query .= sprintf("%s %s :%s", $mapping[0], $e->getOperator(), sprintf($param_prefix, $param_idx));
++$param_idx;
}
}
}
}
@ -356,14 +427,36 @@ final class Filter
{
switch ($original_format) {
case 'datetime_epoch':
if(is_array($value)){
$res = [];
foreach ($value as $val){
$datetime = new \DateTime("@$val");
$res[] = sprintf("%s", $datetime->format("Y-m-d H:i:s"));
}
return $res;
}
$datetime = new \DateTime("@$value");
return sprintf("%s", $datetime->format("Y-m-d H:i:s"));
break;
case 'json_int':
if(is_array($value)){
$res = [];
foreach ($value as $val){
$res[] = intval($val);
}
return $res;
}
return intval($value);
break;
case 'json_string':
return sprintf("%s",$value);
if(is_array($value)){
$res = [];
foreach ($value as $val){
$res[] = sprintf("%s", $val);
}
return $res;
}
return sprintf("%s", $value);
break;
default:
return $value;
@ -401,9 +494,21 @@ final class Filter
if (count($mapping) > 1) {
$filter->setValue($this->convertValue($value, $mapping[1]));
}
$cond = sprintf(' %s %s :%s', $mapping[0], $op, sprintf($param_prefix, $param_idx));
$this->bindings[sprintf($param_prefix, $param_idx)] = $filter->getValue();
++$param_idx;
if(is_array($value)){
$cond = '( ';
foreach ($value as $val) {
$cond .= sprintf(" %s %s :%s %s ", $mapping[0], $op, sprintf($param_prefix, $param_idx), $filter->getSameFieldOp());
$this->bindings[sprintf($param_prefix, $param_idx)] = $val;
++$param_idx;
}
$cond = substr($cond, 0, (strlen($filter->getSameFieldOp())+1) * -1);
$cond .= ' )';
}
else {
$cond = sprintf(' %s %s :%s', $mapping[0], $op, sprintf($param_prefix, $param_idx));
$this->bindings[sprintf($param_prefix, $param_idx)] = $filter->getValue();
++$param_idx;
}
if (!empty($sql)) $sql .= " AND ";
$sql .= $cond;
}
@ -420,9 +525,22 @@ final class Filter
if (count($mapping) > 1) {
$e->setValue($this->convertValue($value, $mapping[1]));
}
$cond = sprintf(" %s %s :%s", $mapping[0], $op, sprintf($param_prefix, $param_idx));
$this->bindings[sprintf($param_prefix, $param_idx)] = $e->getValue();
++$param_idx;
if(is_array($value)){
$cond = '( ';
foreach ($value as $val) {
$cond .= sprintf(" %s %s :%s %s ", $mapping[0], $op, sprintf($param_prefix, $param_idx), $e->getSameFieldOp());
$this->bindings[sprintf($param_prefix, $param_idx)] = $val;
++$param_idx;
}
$cond = substr($cond, 0, (strlen($e->getSameFieldOp())+1) * -1);
$cond .= ' )';
}
else {
$cond = sprintf(" %s %s :%s", $mapping[0], $op, sprintf($param_prefix, $param_idx));
$this->bindings[sprintf($param_prefix, $param_idx)] = $e->getValue();
++$param_idx;
}
if (!empty($sql_or)) $sql_or .= " OR ";
$sql_or .= $cond;
}

Some files were not shown because too many files have changed in this diff Show More