Added endpoint get promo code csv format

GET /api/v1/summits/{id}/promo-codes/csv

Change-Id: I4cbfd87f856f54c57f026b18d96f39cf7c1a31b1
This commit is contained in:
Sebastian Marcet 2018-01-30 17:31:23 -03:00
parent ed4e072989
commit 7d72a3fff6
7 changed files with 253 additions and 4 deletions

View File

@ -227,6 +227,104 @@ final class OAuth2SummitPromoCodesApiController extends OAuth2ProtectedControlle
}
}
public function getAllBySummitCSV($summit_id){
$values = Input::all();
$rules = [
];
try {
$summit = SummitFinderStrategyFactory::build($this->summit_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 = PHP_INT_MAX;
$filter = null;
if (Input::has('filter')) {
$filter = FilterParser::parse(Input::get('filter'), [
'code' => ['=@', '=='],
'creator' => ['=@', '=='],
'creator_email' => ['=@', '=='],
'owner' => ['=@', '=='],
'owner_email' => ['=@', '=='],
'speaker' => ['=@', '=='],
'speaker_email' => ['=@', '=='],
'sponsor' => ['=@', '=='],
'class_name' => ['=='],
'type' => ['=='],
]);
}
$order = null;
if (Input::has('order'))
{
$order = OrderParser::parse(Input::get('order'), [
'id',
'code',
]);
}
if(is_null($filter)) $filter = new Filter();
if($filter->hasFilter("class_name") && !$this->validateClassName($filter->getFilter("class_name"))){
throw new ValidationException(
sprintf
(
"class_name filter has an invalid value ( valid values are %s",
implode(", ", PromoCodesConstants::$valid_class_names)
)
);
}
if($filter->hasFilter("type") && !$this->validateTypes($filter->getFilter("type"))){
throw new ValidationException(
sprintf
(
"type filter has an invalid value ( valid values are %s",
implode(", ", PromoCodesConstants::getValidTypes())
)
);
}
$data = $this->promo_code_repository->getBySummit($summit, new PagingInfo($page, $per_page), $filter, $order);
$filename = "promocodes-" . date('Ymd');
$list = $data->toArray();
return $this->export('csv', $filename, $list['data']);
}
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
* @return mixed

View File

@ -1,5 +1,4 @@
<?php namespace App\Http\Controllers;
/**
* Copyright 2015 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
@ -12,12 +11,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
**/
use App\Http\Utils\CSVExporter;
use Exception;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;
/**
* Class JsonController
* @package App\Http\Controllers
@ -123,4 +121,34 @@ abstract class JsonController extends Controller
{
return Response::json(array('message' => 'Validation Failed', 'errors' => $messages), 412);
}
/**
* @param string $format
* @param string $filename
* @param array $items
* @return \Illuminate\Http\Response
*/
protected function export($format, $filename, array $items){
if($format == 'csv') return $this->csv($filename, $items);
}
/**
* @param string $filename
* @param array $items
* @param string $field_separator
* @param string $mime_type
* @return \Illuminate\Http\Response
*/
private function csv($filename, array $items, $field_separator = ",", $mime_type = 'application/vnd.ms-excel'){
$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",
'Expires' => '0',
'Pragma' => 'public',
];
return Response::make(CSVExporter::getInstance()->export($items, $field_separator), 200, $headers);
}
}

View File

@ -0,0 +1,84 @@
<?php namespace App\Http\Utils;
/**
* 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 CSVExporter
* @package App\Http\Utils
*/
final class CSVExporter
{
/**
* @var CSVExporter
*/
private static $instance;
private function __construct()
{
}
private function __clone()
{
}
/**
* @return CSVExporter
*/
public static function getInstance()
{
if (!is_object(self::$instance)) {
self::$instance = new CSVExporter();
}
return self::$instance;
}
/**
* @param array $items
* @param string $field_separator
* @param array $header
* @return string
*/
public function export(array $items, $field_separator = ",", array $header = []){
$flag = false;
$output = '';
foreach ($items as $row) {
if (!$flag) {
// display field/column names as first row
if(!count($header))
$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){
$values[] = isset($row[$key])? $row[$key] : '';
}
$output .= implode($field_separator, $values) . PHP_EOL;;
}
return $output;
}
function cleanData(&$str)
{
if (is_null($str)) {$str = ''; return;};
if(is_bool($str)){
$str = boolval($str) ? '1' : '0';
return;
}
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
$str = preg_replace("/,/", "-", $str);
if (strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
}

View File

@ -344,6 +344,7 @@ Route::group([
// promo codes
Route::group(['prefix' => 'promo-codes'], function () {
Route::get('', [ 'middleware' => 'auth.user:administrators|summit-front-end-administrators', 'uses' => 'OAuth2SummitPromoCodesApiController@getAllBySummit']);
Route::get('csv', [ 'middleware' => 'auth.user:administrators|summit-front-end-administrators', 'uses' => 'OAuth2SummitPromoCodesApiController@getAllBySummitCSV']);
Route::post('', [ 'middleware' => 'auth.user:administrators|summit-front-end-administrators', 'uses' => 'OAuth2SummitPromoCodesApiController@addPromoCodeBySummit']);
Route::get('metadata', [ 'middleware' => 'auth.user:administrators|summit-front-end-administrators', 'uses' => 'OAuth2SummitPromoCodesApiController@getMetadata']);
Route::group(['prefix' => '{promo_code_id}'], function () {

View File

@ -15,6 +15,8 @@ use models\utils\IBaseRepository;
use utils\Filter;
use utils\Order;
use utils\PagingInfo;
use utils\PagingResponse;
/**
* Interface ISummitRegistrationPromoCodeRepository
* @package models\summit
@ -26,7 +28,7 @@ interface ISummitRegistrationPromoCodeRepository extends IBaseRepository
* @param PagingInfo $paging_info
* @param Filter|null $filter
* @param Order|null $order
* @return mixed
* @return PagingResponse
*/
public function getBySummit
(

View File

@ -691,6 +691,14 @@ class ApiEndpointsSeeder extends Seeder
sprintf(SummitScopes::ReadAllSummitData, $current_realm)
],
],
[
'name' => 'get-promo-codes-csv',
'route' => '/api/v1/summits/{id}/promo-codes/csv',
'http_method' => 'GET',
'scopes' => [
sprintf(SummitScopes::ReadAllSummitData, $current_realm)
],
],
[
'name' => 'get-promo-code',
'route' => '/api/v1/summits/{id}/promo-codes/{promo_code_id}',

View File

@ -79,6 +79,34 @@ final class OAuth2PromoCodesApiTest extends ProtectedApiTest
$this->assertTrue(!is_null($promo_codes));
}
public function testGetPromoCodesByClassNameSpeakerSummitRegistrationPromoCodeCSV(){
$params = [
'id' => 23,
'filter' => 'class_name=='.\models\summit\SpeakerSummitRegistrationPromoCode::ClassName,
'order' => '+code'
];
$headers = [
"HTTP_Authorization" => " Bearer " . $this->access_token,
"CONTENT_TYPE" => "application/json"
];
$response = $this->action(
"GET",
"OAuth2SummitPromoCodesApiController@getAllBySummitCSV",
$params,
[],
[],
[],
$headers
);
$content = $response->getContent();
$this->assertResponseStatus(200);
$this->assertTrue(!is_null($content));
}
public function testGetPromoCodesByClassNameOR(){
$params = [