add: port noticelists

pull/9123/head
Luciano Righetti 2023-06-06 11:33:17 +02:00
parent ab1540ba19
commit 3a657aaf17
19 changed files with 910 additions and 11 deletions

View File

@ -257,6 +257,16 @@ class ACLComponent extends Component
'admin_index' => ['perm_regexp_access'],
'index' => ['*'],
],
'Noticelists' => [
'delete' => [],
'enableNoticelist' => [],
'getToggleField' => [],
'index' => array('*'),
'toggleEnable' => [],
'update' => [],
'view' => ['*'],
'preview_entries' => ['*']
],
'Api' => [
'index' => ['*']
]

View File

@ -12,10 +12,10 @@ class CryptographicKeysController extends AppController
{
use LocatorAwareTrait;
public $paginate = array(
public $paginate = [
'limit' => 60,
'maxLimit' => 9999
);
];
public function add($type, $parent_id)
{
@ -24,7 +24,7 @@ class CryptographicKeysController extends AppController
}
if ($type === 'Event') {
$existingEvent = $this->CryptographicKey->Event->fetchSimpleEvent(
$existingEvent = $this->CryptographicKeys->Event->fetchSimpleEvent(
$this->Auth->user(),
$parent_id,
[
@ -61,22 +61,27 @@ class CryptographicKeysController extends AppController
$instanceKey = file_exists(APP . 'webroot/gpg.asc') ? FileAccessTool::readFromFile(APP . 'webroot/gpg.asc') : '';
$this->set('instanceKey', $instanceKey);
$this->set('menuData', array('menuList' => 'cryptographic_keys', 'menuItem' => 'add_cryptographic_key'));
$this->set('menuData', ['menuList' => 'cryptographic_keys', 'menuItem' => 'add_cryptographic_key']);
}
public function delete($id)
{
$user = $this->ACL->getUser();
$this->CRUD->delete($id, [
$this->CRUD->delete(
$id,
[
'beforeDelete' => function ($data) use ($user) {
$parent_type = $data['CryptographicKey']['parent_type'];
$tempModel = $this->fetchTable($parent_type);
$existingData = $tempModel->find('all', [
$existingData = $tempModel->find(
'all',
[
'conditions' => [
$parent_type . '.id' => $data['CryptographicKey']['parent_id']
],
'recursive' => -1
])->first();
]
)->first();
if ($parent_type === 'Event') {
if (!$user['Role']['perm_site_admin'] && $existingData['Event']['orgc_id'] !== $user['org_id']) {
return false;
@ -84,7 +89,8 @@ class CryptographicKeysController extends AppController
}
return $data;
}
]);
]
);
if ($this->ParamHandler->isRest()) {
return $this->restResponsePayload;
@ -93,12 +99,14 @@ class CryptographicKeysController extends AppController
public function view($id)
{
$this->CryptographicKey = $this->fetchTable('CryptographicKeys');
$key = $this->CryptographicKey->find('all', [
$key = $this->CryptographicKeys->find(
'all',
[
'recursive' => -1,
'fields' => ['id', 'type', 'key_data', 'fingerprint'],
'conditions' => ['id' => $id]
])->first();
]
)->first();
if ($this->ParamHandler->isRest()) {
return $this->RestResponse->viewData($key);

View File

@ -0,0 +1,238 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Http\Exception\MethodNotAllowedException;
use Cake\Http\Exception\NotFoundException;
use Cake\Http\Response;
use App\Lib\Tools\CustomPaginationTool;
use Cake\ORM\Locator\LocatorAwareTrait;
use App\Model\Entity\Log;
class NoticelistsController extends AppController
{
use LocatorAwareTrait;
public $paginate = [
'limit' => 60,
'maxLimit' => 9999,
'order' => [
'Noticelist.id' => 'DESC'
],
];
public function index()
{
$this->CRUD->index([
'quickFilters' => ['name', 'expanded_name'],
]);
if ($this->ParamHandler->isRest()) {
return $this->restResponsePayload;
}
$this->set('menuData', array('menuList' => 'noticelist', 'menuItem' => 'list_noticelists'));
}
public function update()
{
$this->Log = $this->fetchTable('Logs');
//if (!$this->request->is('post')) throw new MethodNotAllowedException('This action is only accessible via POST requests.');
$result = $this->Noticelists->update();
$fails = 0;
$successes = 0;
if (!empty($result)) {
if (isset($result['success'])) {
foreach ($result['success'] as $id => $success) {
if (isset($success['old'])) {
$change = $success['name'] . ': updated from v' . $success['old'] . ' to v' . $success['new'];
} else {
$change = $success['name'] . ' v' . $success['new'] . ' installed';
}
$log = new Log([
'org' => $this->ACL->getUser()->Organisation->name,
'model' => 'Noticelist',
'model_id' => $id,
'email' => $this->ACL->getUser()->email,
'action' => 'update',
'user_id' => $this->ACL->getUser()->id,
'title' => 'Notice list updated',
'changes' => $change,
'created' => date('Y-m-d H:i:s')
]);
$this->Log->save($log);
$successes++;
}
}
if (isset($result['fails'])) {
foreach ($result['fails'] as $id => $fail) {
$log = new Log([
'org' => $this->ACL->getUser()->Organisation->name,
'model' => 'Noticelist',
'model_id' => $id,
'email' => $this->ACL->getUser()->email,
'action' => 'update',
'user_id' => $this->ACL->getUser()->id,
'title' => 'Notice list failed to update',
'changes' => $fail['name'] . ' could not be installed/updated. Error: ' . $fail['fail'],
'created' => date('Y-m-d H:i:s')
]);
$this->Log->save($log);
$fails++;
}
}
} else {
$log = new Log([
'org' => $this->ACL->getUser()->Organisation->name,
'model' => 'Noticelist',
'email' => $this->ACL->getUser()->email,
'action' => 'update',
'user_id' => $this->ACL->getUser()->id,
'title' => 'Noticelist update (nothing to update)',
'changes' => 'Executed an update of the notice lists, but there was nothing to update.',
'created' => date('Y-m-d H:i:s')
]);
$this->Log->save($log);
}
if ($successes == 0 && $fails == 0) {
$flashType = 'success';
$message = 'All noticelists are up to date already.';
} elseif ($successes == 0) {
$flashType = 'error';
$message = 'Could not update any of the notice lists';
} else {
$flashType = 'success';
$message = 'Successfully updated ' . $successes . ' noticelists.';
if ($fails != 0) {
$message . ' However, could not update ' . $fails . ' notice list.';
}
}
if ($this->ParamHandler->isRest()) {
return $this->RestResponse->saveSuccessResponse('Noticelist', 'update', false, false, $message);
} else {
$this->Flash->{$flashType}($message);
$this->redirect(array('controller' => 'noticelists', 'action' => 'index'));
}
}
public function toggleEnable($noticelist_id = false)
{
if ($this->request->is('post')) {
$noticelist = $this->Noticelists->find('all', array(
'conditions' => array('id' => $noticelist_id),
'recursive' => -1,
'fields' => array('id', 'enabled')
))->first();
if ($noticelist === null) {
$message = __('Noticelist not found.');
if ($this->ParamHandler->isRest()) {
return $this->RestResponse->saveFailResponse('Noticelists', 'toggleEnable', $noticelist_id, $message);
} else {
return new Response(array('body' => json_encode(array('saved' => false, 'errors' => $message)), 'status' => 200, 'type' => 'json'));
}
}
$enable = (int)!$noticelist['enabled'];
$noticelist['enabled'] = $enable;
$result = $this->Noticelists->save($noticelist);
$message = $enable ? __('Noticelist enabled.') : __('Noticelist disabled.');
if ($this->ParamHandler->isRest()) {
return $this->RestResponse->saveSuccessResponse('Noticelists', 'toggleEnable', $noticelist_id, false, $message);
} else {
return new Response(array('body' => json_encode(array('saved' => true, 'success' => $message)), 'status' => 200, 'type' => 'json'));
}
} else {
if ($this->ParamHandler->isRest()) {
return $this->RestResponse->saveFailResponse('Noticelists', 'toggleEnable', false, __('This endpoint expects a POST request.'), $this->response->getType());
} else {
$this->layout = false;
}
}
}
public function enableNoticelist($id, $enable = false)
{
$this->Noticelists->id = $id;
if (!$this->Noticelists->exists()) {
throw new NotFoundException(__('Noticelist not found.'));
}
// DBMS interoperability: convert boolean false to integer 0 so cakephp doesn't try to insert an empty string into the database
if ($enable === false) {
$enable = 0;
}
$this->Noticelists->saveField('enabled', $enable);
$this->Flash->info('Noticelist enabled');
$this->redirect(array('controller' => 'noticelists', 'action' => 'view', $id));
}
public function getToggleField()
{
if (!$this->request->is('ajax')) {
throw new MethodNotAllowedException('This action is available via AJAX only.');
}
$this->layout = false;
$this->render('ajax/getToggleField');
}
public function view($id)
{
$this->CRUD->view(
$id,
[
'contain' => ['NoticelistEntries']
]
);
if ($this->ParamHandler->isRest()) {
return $this->restResponsePayload;
}
$this->set('id', $id);
$this->set('menuData', array('menuList' => 'noticelist', 'menuItem' => 'view_noticelist'));
}
public function delete($id)
{
if ($this->request->is('post')) {
$id = intval($id);
$result = $this->Noticelists->quickDelete($id);
if ($result) {
$this->Flash->success('Noticelist successfuly deleted.');
$this->redirect(array('controller' => 'noticelists', 'action' => 'index'));
} else {
$this->Flash->error('Noticelists could not be deleted.');
$this->redirect(array('controller' => 'noticelists', 'action' => 'index'));
}
} else {
if ($this->request->is('ajax')) {
$this->set('id', $id);
$this->render('ajax/delete_confirmation');
} else {
throw new MethodNotAllowedException('This function can only be reached via AJAX.');
}
}
}
public function previewEntries($id)
{
$this->set('menuData', ['menuList' => 'sync', 'menuItem' => 'previewNoticelistEntries']);
$noticelist = $this->Noticelists->find('all', array('contain' => array('NoticelistEntries'), 'conditions' => array('id' => $id)))->first();
if (empty($noticelist)) {
throw new NotFoundException(__('Noticelist not found.'));
}
$noticelistEntries = $noticelist['noticelist_entries'];
if ($this->ParamHandler->isRest()) {
return $this->RestResponse->viewData($noticelistEntries);
} else {
$customPagination = new CustomPaginationTool();
$params = $this->request->getQueryParams();
$customPagination->truncateAndPaginate($noticelistEntries, $params, 'NoticelistEntry', true);
$this->set('data', $noticelistEntries);
$this->set('noticelist', $noticelist);
}
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace App\Model\Entity;
use App\Model\Entity\AppModel;
class Noticelist extends AppModel
{
}

View File

@ -0,0 +1,9 @@
<?php
namespace App\Model\Entity;
use App\Model\Entity\AppModel;
class NoticelistEntry extends AppModel
{
}

View File

@ -0,0 +1,16 @@
<?php
namespace App\Model\Table;
use App\Model\Table\AppTable;
class NoticelistEntriesTable extends AppTable
{
public function initialize(array $config): void
{
parent::initialize($config);
$this->addBehavior('JsonFields', [
'fields' => ['data'],
]);
}
}

View File

@ -0,0 +1,140 @@
<?php
namespace App\Model\Table;
use App\Model\Table\AppTable;
use Cake\Validation\Validator;
use App\Lib\Tools\FileAccessTool;
use App\Model\Entity\Noticelist;
use App\Model\Entity\NoticelistEntry;
use Cake\ORM\Locator\LocatorAwareTrait;
class NoticelistsTable extends AppTable
{
use LocatorAwareTrait;
public function initialize(array $config): void
{
parent::initialize($config);
$this->addBehavior('AuditLog');
$this->addBehavior('JsonFields', [
'fields' => ['ref', 'geographical_area'],
]);
$this->hasMany(
'NoticelistEntries',
[
'dependent' => true,
]
);
}
public function validationDefault(Validator $validator): Validator
{
$validator
->requirePresence(['name'], 'create')
->add('version', 'numeric');
return $validator;
}
public function update()
{
$directories = glob(APP . '..' . DS . 'libraries' . DS . 'noticelists' . DS . 'lists' . DS . '*', GLOB_ONLYDIR);
$updated = array();
foreach ($directories as $dir) {
$list = FileAccessTool::readJsonFromFile($dir . DS . 'list.json');
if (!isset($list['version'])) {
$list['version'] = 1;
}
$current = $this->find('all', array(
'conditions' => array('name' => $list['name']),
'recursive' => -1
))->first();
if (empty($current) || $list['version'] > $current['version']) {
$result = $this->__updateList($list, $current);
if (is_numeric($result)) {
$updated['success'][$result] = array('name' => $list['name'], 'new' => $list['version']);
if (!empty($current)) {
$updated['success'][$result]['old'] = $current['version'];
}
} else {
$updated['fails'][] = array('name' => $list['name'], 'fail' => json_encode($result));
}
}
}
if (empty($updated)) {
return 'All noticelists are up to date already.';
}
return $updated;
}
private function __updateList($list, $current)
{
$list['enabled'] = 0;
$noticelist = array();
if (!empty($current)) {
if ($current['enabled']) {
$list['enabled'] = 1;
}
$this->quickDelete($current['id']);
}
$fieldsToSave = array('name', 'expanded_name', 'ref', 'geographical_area', 'version', 'enabled');
foreach ($fieldsToSave as $fieldToSave) {
$noticelist[$fieldToSave] = $list[$fieldToSave];
}
$noticelist = new Noticelist($noticelist);
$result = $this->save($noticelist);
if ($result) {
$values = array();
foreach ($list['notice'] as $value) {
if (!empty($value)) {
$values[] = array('data' => $value, 'noticelist_id' => $result->id);
}
}
unset($list['notice']);
$NoticelistEntries = $this->fetchTable('NoticelistEntries');
foreach ($values as $value) {
$entry = new NoticelistEntry($value);
$NoticelistEntries->save($entry);
}
return $result->id;
} else {
return $this->validationErrors;
}
}
public function getTriggerData($scope = 'attribute')
{
$noticelists = $this->find('all', array(
'conditions' => array('enabled' => 1),
'recursive' => -1,
'contain' => 'NoticelistEntry'
));
$noticelist_triggers = array();
$validTriggers = array(
'attribute' => array(
'category',
'type'
)
);
foreach ($noticelists as $noticelist) {
foreach ($noticelist['NoticelistEntry'] as $entry) {
if (in_array('attribute', $entry['data']['scope'])) {
foreach ($entry['data']['field'] as $data_field) {
if (in_array($data_field, $validTriggers[$scope])) {
foreach ($entry['data']['value'] as $value) {
$noticelist_triggers[$data_field][$value][] = array(
'message' => $entry['data']['message'],
'list_id' => $noticelist['id'],
'list_name' => $noticelist['name']
);
}
}
}
}
}
}
return $noticelist_triggers;
}
}

View File

@ -0,0 +1,33 @@
<div class="confirmation">
<?php
echo $this->Form->create('Noticelist', array(
'style' => 'margin:0px;',
'id' => 'PromptForm',
'url' => array('controller' => 'noticelists', 'action' => 'delete', $id)
));
?>
<legend><?php echo __('Noticelist Deletion');?></legend>
<div style="padding-left:5px;padding-right:5px;padding-bottom:5px;">
<p><?php echo __('Are you sure you want to delete Noticelist #%s?', h($id));?></p>
<table>
<tr>
<td style="vertical-align:top">
<?php
echo $this->Form->button('Yes', array(
'type' => 'submit',
'class' => 'btn btn-primary'
));
?>
</td>
<td style="width:540px;">
</td>
<td style="vertical-align:top;">
<span role="button" tabindex="0" aria-label="<?php echo __('Cancel');?>" class="btn btn-inverse" id="PromptNoButton" onClick="cancelPrompt();"><?php echo __('No');?></span>
</td>
</tr>
</table>
</div>
<?php
echo $this->Form->end();
?>
</div>

View File

@ -0,0 +1,4 @@
<?php
echo $this->Form->create('Noticelist', array('id' => 'NoticelistIndexForm', 'url' => $baseurl . '/noticelists/toggleEnable'));
echo $this->Form->input('data', array('id' => 'NoticelistData', 'label' => false, 'style' => 'display:none;'));
echo $this->Form->end();

View File

@ -0,0 +1,79 @@
<?php
$fields = [
[
'name' => __('ID'),
'sort' => 'id',
'data_path' => 'id'
],
[
'name' => __('Name'),
'sort' => 'name',
'data_path' => 'name'
],
[
'name' => __('Expanded Name'),
'sort' => 'expanded_name',
'data_path' => 'expanded_name'
],
[
'name' => __('Ref'),
'data_path' => 'ref'
],
[
'name' => __('Geographical area'),
'data_path' => 'geographical_area',
'element' => 'list'
],
[
'name' => __('Version'),
'data_path' => 'version',
],
[
'name' => __('Enabled'),
'data_path' => 'enabled',
'element' => 'toggle',
'url' => '/noticelists/toggleEnable',
'url_params_vars' => [
[
'datapath' => [
'id'
]
]
],
'requirement' => $isSiteAdmin,
],
[
'name' => __('Default'),
'data_path' => 'enabled',
'element' => 'boolean',
'colors' => true,
'requirement' => !$isSiteAdmin,
],
];
echo $this->element('genericElements/IndexTable/index_table', [
'data' => [
'data' => $data,
'top_bar' => [
'pull' => 'right',
'children' => [
[
'type' => 'search',
'button' => __('Filter'),
'placeholder' => __('Enter value to search'),
'searchKey' => 'quickFilter',
]
]
],
'fields' => $fields,
'title' => empty($ajax) ? __('Noticelists') : false,
'actions' => [
[
'url' => '/noticelists/view',
'url_params_data_paths' => ['id'],
'icon' => 'eye'
],
]
]
]);

View File

@ -0,0 +1,45 @@
<?php
$fields = [
[
'name' => __('Scope'),
'data_path' => 'data.scope',
'class' => 'short'
],
[
'name' => __('Field'),
'data_path' => 'data.field',
'class' => 'short'
],
[
'name' => __('Value'),
'data_path' => 'data.value',
'class' => 'shortish'
],
[
'name' => __('Tags'),
'data_path' => 'data.tags',
'class' => 'shortish'
],
[
'name' => __('Message'),
'data_path' => 'data.message.en',
'class' => 'shortish'
],
];
echo $this->element('genericElements/IndexTable/index_table', [
'data' => [
'data' => $data,
'fields' => $fields,
'title' => 'Values',
'paginatorOptions' => [
'url' => [$noticelist['id']]
],
'persistUrlParams' => [0, 'quickFilter']
],
'containerId' => 'preview_entries_container'
]);
?>
<script type="text/javascript">
var passedArgsArray = <?= json_encode([h($noticelist['id'])]) ?>;
</script>

View File

@ -0,0 +1,4 @@
<?php
echo $this->Form->create('Noticelist');
echo $this->Form->end();
?>

View File

@ -0,0 +1,53 @@
<?php
echo $this->element(
'genericElements/SingleViews/single_view',
[
'title' => 'Noticelist view',
'data' => $entity,
'fields' => [
[
'key' => __('ID'),
'path' => 'id'
],
[
'key' => __('Name'),
'path' => 'name'
],
[
'key' => __('Version'),
'path' => 'version'
],
[
'key' => __('Expanded Name'),
'path' => 'expanded_name'
],
[
'key' => __('Ref'),
'type' => 'custom',
'function' => function ($entity) {
return implode('<br>', array_map('h', $entity->ref));
}
],
[
'key' => __('Geographical Area'),
'type' => 'custom',
'function' => function ($entity) {
return implode('<br>', array_map('h', $entity->geographical_area));
}
],
[
'key' => __('Enabled'),
'path' => 'enabled',
'type' => 'boolean'
]
],
'children' => [
[
'url' => '/noticelists/preview_entries/{{0}}/',
'url_params' => ['id'],
'title' => __('Values'),
'elementId' => 'preview_entries_container'
]
]
]
);

View File

@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Test\Fixture;
use Cake\TestSuite\Fixture\TestFixture;
class NoticelistEntriesFixture extends TestFixture
{
public $connection = 'test';
public const NOTICELIST_ENTRY_1_ID = 1;
public function init(): void
{
$this->records = [
[
'id' => self::NOTICELIST_ENTRY_1_ID,
'noticelist_id' => NoticelistsFixture::NOTICELIST_1_ID,
'data' => json_encode([
'scope' => ['attribute'],
'field' => ['category'],
'value' => ['ip-src'],
'tags' => ['test'],
'message' => [
'en' => 'This a test noticelist entry',
]
])
]
];
parent::init();
}
}

View File

@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Test\Fixture;
use Cake\TestSuite\Fixture\TestFixture;
class NoticelistsFixture extends TestFixture
{
public $connection = 'test';
public const NOTICELIST_1_ID = 1;
public const NOTICELIST_1_NAME = 'disabled test noticelist';
public const NOTICELIST_2_ID = 2;
public const NOTICELIST_2_NAME = 'enabled test noticelist';
public function init(): void
{
$this->records = [
[
'id' => self::NOTICELIST_1_ID,
'name' => self::NOTICELIST_1_NAME,
'expanded_name' => 'test disabled noticelist expanded name',
'ref' => json_encode(['test_ref']),
'geographical_area' => json_encode(['TEST']),
'version' => '1',
'enabled' => false
],
[
'id' => self::NOTICELIST_2_ID,
'name' => self::NOTICELIST_2_NAME,
'expanded_name' => 'test enabled noticelist expanded name',
'ref' => json_encode(['test_ref']),
'geographical_area' => json_encode(['TEST']),
'version' => '1',
'enabled' => true
]
];
parent::init();
}
}

View File

@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Api\Noticelists;
use Cake\TestSuite\TestCase;
use App\Test\Fixture\AuthKeysFixture;
use App\Test\Fixture\NoticelistsFixture;
use App\Test\Helper\ApiTestTrait;
class IndexNoticelistsApiTest extends TestCase
{
use ApiTestTrait;
protected const ENDPOINT = '/noticelists/index';
protected $fixtures = [
'app.Organisations',
'app.Users',
'app.AuthKeys',
'app.Noticelists',
'app.NoticelistEntries',
];
public function testIndexNoticelists(): void
{
$this->skipOpenApiValidations();
$this->setAuthToken(AuthKeysFixture::ADMIN_API_KEY);
$this->get(self::ENDPOINT);
$this->assertResponseOk();
$this->assertResponseContains(sprintf('"name": "%s"', NoticelistsFixture::NOTICELIST_1_NAME));
}
}

View File

@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Api\Noticelists;
use Cake\TestSuite\TestCase;
use App\Test\Fixture\AuthKeysFixture;
use App\Test\Fixture\NoticelistsFixture;
use App\Test\Helper\ApiTestTrait;
class ToggleEnableNoticelistApiTest extends TestCase
{
use ApiTestTrait;
protected const ENDPOINT = '/noticelists/toggleEnable';
protected $fixtures = [
'app.Organisations',
'app.Users',
'app.AuthKeys',
'app.Noticelists',
'app.NoticelistEntries',
];
public function testToggleEnableNoticelist(): void
{
$this->skipOpenApiValidations();
$this->setAuthToken(AuthKeysFixture::ADMIN_API_KEY);
$url = sprintf('%s/%d', self::ENDPOINT, NoticelistsFixture::NOTICELIST_1_ID);
# enable
$this->assertDbRecordExists('Noticelists', ['id' => NoticelistsFixture::NOTICELIST_1_ID, 'enabled' => false]);
$this->post($url);
$this->assertResponseOk();
$this->assertResponseContains('"message": "Noticelist enabled."');
$this->assertDbRecordExists('Noticelists', ['id' => NoticelistsFixture::NOTICELIST_1_ID, 'enabled' => true]);
}
public function testToggleDisableNoticelist(): void
{
$this->skipOpenApiValidations();
$this->setAuthToken(AuthKeysFixture::ADMIN_API_KEY);
$url = sprintf('%s/%d', self::ENDPOINT, NoticelistsFixture::NOTICELIST_2_ID);
$this->assertDbRecordExists('Noticelists', ['id' => NoticelistsFixture::NOTICELIST_2_ID, 'enabled' => true]);
$this->post($url);
$this->assertResponseOk();
$this->assertResponseContains('"message": "Noticelist disabled."');
$this->assertDbRecordExists('Noticelists', ['id' => NoticelistsFixture::NOTICELIST_2_ID, 'enabled' => false]);
}
}

View File

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Api\Noticelists;
use Cake\TestSuite\TestCase;
use App\Test\Fixture\AuthKeysFixture;
use App\Test\Helper\ApiTestTrait;
class AddNoticelistApiTest extends TestCase
{
use ApiTestTrait;
protected const ENDPOINT = '/noticelists/update';
protected $fixtures = [
'app.Organisations',
'app.Users',
'app.AuthKeys',
'app.Noticelists',
'app.NoticelistEntries',
];
public function testUpdateNoticelists(): void
{
$this->skipOpenApiValidations();
$this->setAuthToken(AuthKeysFixture::ADMIN_API_KEY);
$this->post(self::ENDPOINT);
$this->assertResponseOk();
$this->assertDbRecordExists('Noticelists', ['name' => 'gdpr']);
}
}

View File

@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Api\Noticelists;
use Cake\TestSuite\TestCase;
use App\Test\Fixture\AuthKeysFixture;
use App\Test\Fixture\NoticelistsFixture;
use App\Test\Fixture\NoticelistEntriesFixture;
use App\Test\Helper\ApiTestTrait;
class ViewNoticelistApiTest extends TestCase
{
use ApiTestTrait;
protected const ENDPOINT = '/noticelists/view';
protected $fixtures = [
'app.Organisations',
'app.Users',
'app.AuthKeys',
'app.Noticelists',
'app.NoticelistEntries',
];
public function testViewNoticelistById(): void
{
$this->skipOpenApiValidations();
$this->setAuthToken(AuthKeysFixture::ADMIN_API_KEY);
$url = sprintf('%s/%d', self::ENDPOINT, NoticelistsFixture::NOTICELIST_1_ID);
$this->get($url);
$this->assertResponseOk();
$noticelist = $this->getJsonResponseAsArray();
$this->assertEquals(NoticelistsFixture::NOTICELIST_1_ID, $noticelist['id']);
$this->assertEquals(NoticelistsFixture::NOTICELIST_1_NAME, $noticelist['name']);
$this->assertArrayHasKey('noticelist_entries', $noticelist);
$this->assertCount(1, $noticelist['noticelist_entries']);
$this->assertEquals(NoticelistEntriesFixture::NOTICELIST_ENTRY_1_ID, $noticelist['noticelist_entries'][0]['id']);
}
}