Create organisation functionality

This commit is contained in:
2022-02-04 11:23:48 +00:00
parent 584aa1909e
commit f850e4cace
11 changed files with 346 additions and 1 deletions

View File

@@ -2,6 +2,7 @@
"bundle": {
"js/pages/organisations": {
"scripts": [
"avsdev/js/widgets/organisations.js",
"avsdev/js/pages/organisations.js"
]
}

View File

@@ -13,4 +13,7 @@ $(document).ready(function() {
dataUrl: site.uri.public + "/api/organisations",
useLoadingTransition: site.uf_table.use_loading_transition
});
// Bind creation button
bindOrganisationCreationButton($("#widget-organisations"));
});

View File

@@ -0,0 +1,61 @@
/**
* Organisations widget. Sets up dropdowns, modals, etc for a table of organisations.
*/
/**
* Set up the form in a modal after being successfully attached to the body.
*/
function attachOrganisationForm() {
$("body").on('renderSuccess.ufModal', function(data) {
var modal = $(this).ufModal('getModal');
var form = modal.find('.js-form');
/**
* Set up modal widgets
*/
// Set up any widgets inside the modal
form.find(".js-select2").select2({
width: '100%'
});
// Auto-generate slug
form.find('input[name=name]').on('input change', function() {
var manualSlug = form.find('#form-organisation-slug-override').prop('checked');
if (!manualSlug) {
var slug = getSlug($(this).val());
form.find('input[name=slug]').val(slug);
}
});
form.find('#form-organisation-slug-override').on('change', function() {
if ($(this).prop('checked')) {
form.find('input[name=slug]').prop('readonly', false);
} else {
form.find('input[name=slug]').prop('readonly', true);
form.find('input[name=name]').trigger('change');
}
});
// Set up the form for submission
form.ufForm({
validator: page.validators
}).on("submitSuccess.ufForm", function() {
// Reload page on success
window.location.reload();
});
});
}
function bindOrganisationCreationButton(el) {
// Link create button
el.find('.js-organisation-create').click(function(e) {
e.preventDefault();
$("body").ufModal({
sourceUrl: site.uri.public + "/modals/organisations/create",
msgTarget: $("#alerts-page")
});
attachOrganisationForm();
});
};

View File

@@ -17,6 +17,18 @@ return [
1 => 'Organisation',
2 => 'Organisations',
'CREATE' => 'Create organisation',
'CREATION_SUCCESSFUL' => 'Successfully created organisation <strong>{{name}}</strong>',
'PAGE_DESCRIPTION' => 'A listing of the organisations for your site. Provides management tools for editing and deleting organisations.',
'NAME' => [
1 => 'Organisation name',
'EXPLAIN' => 'Please enter a name for the organisation',
'IN_USE' => 'Organisation name <strong>{{name}}</strong> is already in use.',
],
'SLUG' => [
'IN_USE' => 'Organisation slug <strong>{{slug}}</strong> is already in use.',
],
],
];

View File

@@ -19,6 +19,13 @@ $app->group('/organisations', function () {
$app->group('/api/organisations', function () {
$this->get('', 'UserFrosting\Sprinkle\Organisations\Controller\OrganisationController:getList');
$this->post('', 'UserFrosting\Sprinkle\Organisations\Controller\OrganisationController:create');
})->add('authGuard')->add(new NoCache());
$app->group('/modals/organisations', function () {
$this->get('/create', 'UserFrosting\Sprinkle\Organisations\Controller\OrganisationController:getModalCreate');
})->add('authGuard')->add(new NoCache());
// TODO: add route for accepting members
// TODO: add route for verifying organisations

View File

@@ -0,0 +1,26 @@
---
name:
validators:
required:
label: "&NAME"
message: VALIDATE.REQUIRED
length:
label: "&NAME"
min: 1
max: 255
message: VALIDATE.LENGTH_RANGE
transformations:
- trim
slug:
validators:
required:
label: "&SLUG"
message: VALIDATE.REQUIRED
length:
label: "&SLUG"
min: 1
max: 255
message: VALIDATE.LENGTH_RANGE
transformations:
- trim
description:

View File

@@ -29,6 +29,102 @@ use UserFrosting\Support\Exception\NotFoundException;
*/
class OrganisationController extends SimpleController
{
/**
* Processes the request to create a new organisation.
*
* Processes the request from the organisation creation form, checking that:
* 1. The organisation name and slug are not already in use;
* 2. The user has permission to create a new organisation;
* 3. The submitted data is valid.
* This route requires authentication (and should generally be limited to admins or the root user).
*
* Request type: POST
*
* @see getModalCreateOrganisation
*
* @param Request $request
* @param Response $response
* @param array $args
*
* @throws ForbiddenException If user is not authorized to access page
*/
public function create(Request $request, Response $response, $args)
{
// Get POST parameters: name, slug, icon, description
$params = $request->getParsedBody();
/** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
$authorizer = $this->ci->authorizer;
/** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
$currentUser = $this->ci->currentUser;
// Access-controlled page
if (!$authorizer->checkAccess($currentUser, 'create_organisation')) {
throw new ForbiddenException();
}
/** @var \UserFrosting\Sprinkle\Core\Alert\AlertStream $ms */
$ms = $this->ci->alerts;
// Load the request schema
$schema = new RequestSchema('schema://requests/organisation/create.yaml');
// Whitelist and set parameter defaults
$transformer = new RequestDataTransformer($schema);
$data = $transformer->transform($params);
$error = false;
// Validate request data
$validator = new ServerSideValidator($schema, $this->ci->translator);
if (!$validator->validate($data)) {
$ms->addValidationErrors($validator);
$error = true;
}
/** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
$classMapper = $this->ci->classMapper;
// Check if name or slug already exists
if ($classMapper->getClassMapping('organisation')::where('name', $data['name'])->first()) {
$ms->addMessageTranslated('danger', 'ORGANISATION.NAME.IN_USE', $data);
$error = true;
}
if ($classMapper->getClassMapping('organisation')::where('slug', $data['slug'])->first()) {
$ms->addMessageTranslated('danger', 'ORGANISATION.SLUG.IN_USE', $data);
$error = true;
}
if ($error) {
return $response->withJson([], 400);
}
/** @var \UserFrosting\Support\Repository\Repository $config */
$config = $this->ci->config;
// All checks passed! log events/activities and create organisation
// Begin transaction - DB will be rolled back if an exception occurs
Capsule::transaction(function () use ($classMapper, $data, $ms, $currentUser) {
// Create the organisation
$organisation = $classMapper->createInstance('organisation', $data);
// Store new organisation to database
$organisation->save();
// Create activity record
$this->ci->userActivityLogger->info("User {$currentUser->user_name} created organisation {$organisation->name}.", [
'type' => 'organisation_create',
'user_id' => $currentUser->id,
]);
$ms->addMessageTranslated('success', 'ORGANISATION.CREATION_SUCCESSFUL', $data);
});
return $response->withJson([], 200);
}
/**
* Returns a list of Organisations.
*
@@ -69,6 +165,66 @@ class OrganisationController extends SimpleController
return $sprunje->toResponse($response);
}
/**
* Renders the modal form for creating a new organisation.
*
* This does NOT render a complete page. Instead, it renders the HTML for the modal, which can be embedded in other pages.
* This page requires authentication.
*
* Request type: GET
*
* @param Request $request
* @param Response $response
* @param array $args
*
* @throws ForbiddenException If user is not authorized to access page
*/
public function getModalCreate(Request $request, Response $response, $args)
{
/** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
$authorizer = $this->ci->authorizer;
/** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
$currentUser = $this->ci->currentUser;
/** @var \UserFrosting\I18n\Translator $translator */
$translator = $this->ci->translator;
// Access-controlled page
if (!$authorizer->checkAccess($currentUser, 'create_organisation')) {
throw new ForbiddenException();
}
/** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
$classMapper = $this->ci->classMapper;
// Create a dummy organisation to prepopulate fields
$organisation = $classMapper->createInstance('organisation', []);
$fieldNames = ['name', 'slug', 'description'];
$fields = [
'hidden' => [],
'disabled' => [],
];
// Load validation rules
$schema = new RequestSchema('schema://requests/organisation/create.yaml');
$validator = new JqueryValidationAdapter($schema, $this->ci->translator);
return $this->ci->view->render($response, 'modals/organisation.html.twig', [
'organisation' => $organisation,
'form' => [
'action' => 'api/organisations',
'method' => 'POST',
'fields' => $fields,
'submit_text' => $translator->translate('CREATE'),
],
'page' => [
'validators' => $validator->rules('json', false),
],
]);
}
/**
* Renders the organisation listing page.
*

View File

@@ -43,6 +43,12 @@ class OrganisationPermissions extends BaseSeed
protected function getPermissions()
{
return [
'create_organisation' => new Permission([
'slug' => 'create_organisation',
'name' => 'Create organisation',
'conditions' => 'always()',
'description' => 'Create a new organisation.',
]),
'uri_organisations' => new Permission([
'slug' => 'uri_organisations',
'name' => 'Organisation management page',
@@ -84,6 +90,7 @@ class OrganisationPermissions extends BaseSeed
$roleSiteAdmin = Role::where('slug', 'site-admin')->first();
if ($roleSiteAdmin) {
$roleSiteAdmin->permissions()->sync([
$permissions['create_organisation'],
$permissions['uri_organisations'],
], false);
}

View File

@@ -0,0 +1,58 @@
<form class="js-form" method="{{form.method | default('POST')}}" action="{{site.uri.public}}/{{form.action}}">
{% include "forms/csrf.html.twig" %}
<div class="js-form-alerts">
</div>
<div class="row">
{% block organisation_form %}
{% if 'name' not in form.fields.hidden %}
<div class="col-sm-12">
<div class="form-group">
<label>{{translate("ORGANISATION.NAME")}}</label>
<div class="input-group">
<span class="input-group-addon"><i class="fas fa-edit fa-fw"></i></span>
<input type="text" class="form-control" name="name" autocomplete="off" value="{{organisation.name}}" placeholder="{{translate("ORGANISATION.NAME.EXPLAIN")}}" {% if 'name' in form.fields.disabled %}disabled{% endif %}>
</div>
</div>
</div>
{% endif %}
{% if 'slug' not in form.fields.hidden %}
<div class="col-sm-12">
<div class="form-group">
<label>{{translate("SLUG")}}</label>
<div class="input-group">
<span class="input-group-addon"><i class="fas fa-tag fa-fw"></i></span>
<input type="text" class="form-control" name="slug" autocomplete="off" value="{{organisation.slug}}" placeholder="{{translate("SLUG")}}" {% if 'slug' in form.fields.disabled %}disabled{% endif %} readonly>
{% if 'slug' not in form.fields.disabled %}
<span class="input-group-btn" data-toggle="buttons">
<label class="btn btn-primary">
<input type="checkbox" id="form-organisation-slug-override" autocomplete="off"> {{translate("OVERRIDE")}}
</label>
</span>
{% endif %}
</div>
</div>
</div>
{% endif %}
{% if 'description' not in form.fields.hidden %}
<div class="col-sm-12">
<div class="form-group">
<label for="input_description">{{translate("DESCRIPTION")}}</label>
<textarea id="input_description" class="form-control" type="text" name="description" {% if 'description' in form.fields.disabled %}disabled{% endif %} rows=6>{{organisation.description}}</textarea>
</div>
</div>
{% endif %}
{% endblock %}
</div><br>
<div class="row">
<div class="col-xs-6 col-sm-4">
<button type="submit" class="btn btn-block btn-lg btn-success">{{form.submit_text}}</button>
</div>
<div class="col-xs-4 col-sm-3 pull-right">
<button type="button" class="btn btn-block btn-lg btn-link" data-dismiss="modal">{{translate("CANCEL")}}</button>
</div>
</div>
</form>
<!-- Include validation rules -->
<script>
{% include "pages/partials/page.js.twig" %}
</script>

View File

@@ -0,0 +1,7 @@
{% extends "modals/modal.html.twig" %}
{% block modal_title %}{{translate('ORGANISATION')}}{% endblock %}
{% block modal_body %}
{% include "forms/organisation.html.twig" %}
{% endblock %}

View File

@@ -26,6 +26,13 @@
}
%}
</div>
{% if checkAccess('create_organisation') %}
<div class="box-footer">
<button type="button" class="btn btn-success js-organisation-create">
<i class="fas fa-plus-square"></i> {{translate("ORGANISATION.CREATE")}}
</button>
</div>
{% endif %}
</div>
</div>
</div>