Added capability to merge organisations
- Added an interface for organisation - Added beforeDelete and beforeMerge callbacks - Added hard/soft delete to organisations
This commit is contained in:
@@ -298,6 +298,110 @@ class OrganisationController extends SimpleController
|
||||
return $response->withJson([], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes the request to merge two organisations.
|
||||
*
|
||||
* Processes the request from the merge organisation form, checking that:
|
||||
* 1. The source organisation slug exists;
|
||||
* 2. The target organisation slug exists;
|
||||
* 3. The user has permission to merge organisations;
|
||||
* 4. The submitted data is valid.
|
||||
* This route requires authentication (and should generally be limited to admins or the root user).
|
||||
*
|
||||
* Request type: POST
|
||||
*
|
||||
* @see getModalMerge
|
||||
*
|
||||
* @param Request $request
|
||||
* @param Response $response
|
||||
* @param array $args
|
||||
*
|
||||
* @throws ForbiddenException If user is not authorized to access page
|
||||
*/
|
||||
public function merge(Request $request, Response $response, $args)
|
||||
{
|
||||
// Get POST parameters
|
||||
$params = $request->getParsedBody();
|
||||
|
||||
// Load the request schema
|
||||
$schema = new RequestSchema('schema://requests/organisation/merge.yaml');
|
||||
|
||||
// Whitelist and set parameter defaults
|
||||
$transformer = new RequestDataTransformer($schema);
|
||||
$data = $transformer->transform($params);
|
||||
|
||||
// Validate, and throw exception on validation errors.
|
||||
$validator = new ServerSideValidator($schema, $this->ci->translator);
|
||||
if (!$validator->validate($data)) {
|
||||
$e = new BadRequestException();
|
||||
|
||||
foreach ($validator->errors() as $idx => $field) {
|
||||
foreach ($field as $eidx => $error) {
|
||||
$e->addUserMessage($error);
|
||||
}
|
||||
}
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
/** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
|
||||
$classMapper = $this->ci->classMapper;
|
||||
|
||||
// Get the organisations
|
||||
$source = $classMapper->getClassMapping('organisation')::where('slug', $data['source_slug'])->first();
|
||||
$target = $classMapper->getClassMapping('organisation')::where('slug', $data['target_slug'])->first();
|
||||
|
||||
// If a organisation doesn't exist, return 404
|
||||
if (!$source || !$target) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
/** @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, 'merge_organisation')) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
/** @var \UserFrosting\Support\Repository\Repository $config */
|
||||
$config = $this->ci->config;
|
||||
|
||||
/** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
|
||||
$classMapper = $this->ci->classMapper;
|
||||
|
||||
$sourceName = $source->name;
|
||||
|
||||
// Begin transaction - DB will be rolled back if an exception occurs
|
||||
Capsule::transaction(function () use ($source, $sourceName, $target, $currentUser) {
|
||||
$this->ci->get('organisation.beforeMerge')($source, $target);
|
||||
|
||||
$source->beforeMerge($target, ['currentUser' => $currentUser]);
|
||||
|
||||
$source->delete();
|
||||
unset($source);
|
||||
|
||||
// Create activity record
|
||||
$this->ci->userActivityLogger->info("User {$currentUser->user_name} merged organisation {$sourceName} into {$target->name}.", [
|
||||
'type' => 'organisation_merge',
|
||||
'user_id' => $currentUser->id,
|
||||
]);
|
||||
});
|
||||
|
||||
/** @var \UserFrosting\Sprinkle\Core\Alert\AlertStream $ms */
|
||||
$ms = $this->ci->alerts;
|
||||
|
||||
$ms->addMessageTranslated('success', 'ORGANISATION.MERGE_SUCCESSFUL', [
|
||||
'source' => $sourceName,
|
||||
'target' => $target->name,
|
||||
]);
|
||||
|
||||
return $response->withJson([], 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes the request to delete an existing organisation.
|
||||
*
|
||||
@@ -589,7 +693,70 @@ class OrganisationController extends SimpleController
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders the modal form for merging two organisations.
|
||||
*
|
||||
* 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 getModalMerge(Request $request, Response $response, $args)
|
||||
{
|
||||
// GET parameters
|
||||
$params = $request->getQueryParams();
|
||||
|
||||
$organisation = $this->getOrganisationFromParams($params);
|
||||
|
||||
// If the organisation doesn't exist, return 404
|
||||
if (!$organisation) {
|
||||
throw new NotFoundException();
|
||||
}
|
||||
|
||||
/** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
|
||||
$classMapper = $this->ci->classMapper;
|
||||
|
||||
/** @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 resource - check that currentUser has permission to merge organisations.
|
||||
if (!$authorizer->checkAccess($currentUser, 'organisation_merge')) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
|
||||
// Load validation rules
|
||||
$schema = new RequestSchema('schema://requests/organisation/merge.yaml');
|
||||
$validator = new JqueryValidationAdapter($schema, $translator);
|
||||
|
||||
$otherOrganisations = $classMapper->getClassMapping('organisation')::where('id', '!=', $organisation->id)->get();
|
||||
|
||||
return $this->ci->view->render($response, 'modals/organisation-merge.html.twig', [
|
||||
'organisation' => $organisation,
|
||||
'other_organisations' => $otherOrganisations,
|
||||
'form' => [
|
||||
'action' => "api/organisations/o/{$organisation->slug}/merge",
|
||||
'method' => 'POST',
|
||||
'submit_text' => $translator->translate('MERGE'),
|
||||
],
|
||||
'page' => [
|
||||
'validators' => $validator->rules('json', false),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders a page displaying a organisation's information, in read-only mode.
|
||||
|
||||
85
src/Database/Models/Interfaces/OrganisationInterface.php
Normal file
85
src/Database/Models/Interfaces/OrganisationInterface.php
Normal file
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* AVSDev UF Organisations (https://avsdev.uk)
|
||||
*
|
||||
* @link https://git.avsdev.uk/avsdev/sprinkle-organisations
|
||||
* @license https://git.avsdev.uk/avsdev/sprinkle-organisations/blob/master/LICENSE.md (LGPL-3.0 License)
|
||||
*/
|
||||
|
||||
namespace UserFrosting\Sprinkle\Organisations\Database\Models\Interfaces;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
/**
|
||||
* Organisation Interface.
|
||||
*
|
||||
* Represents a Organisation object as stored in the database.
|
||||
*/
|
||||
interface OrganisationInterface
|
||||
{
|
||||
/**
|
||||
* Get a count of members within this organisation (includes admins).
|
||||
*
|
||||
* @return integer The number of members within the organisation.
|
||||
*/
|
||||
public function getMemberCountAttribute();
|
||||
|
||||
/**
|
||||
* Get a count of administrators within this organisation.
|
||||
*
|
||||
* @return integer The number of admins within the organisation.
|
||||
*/
|
||||
public function getAdminCountAttribute();
|
||||
|
||||
/**
|
||||
* Get a count of members within this organisation (excludes admins).
|
||||
*
|
||||
* @return integer The number of members within the organisation.
|
||||
*/
|
||||
public function getTotalMemberCountAttribute();
|
||||
|
||||
/**
|
||||
* Delete this organisation from the database, along with any linked objects.
|
||||
*
|
||||
* @param bool $hardDelete Set to true to completely remove the organisation and all associated objects.
|
||||
*
|
||||
* @return bool true if the deletion was successful, false otherwise.
|
||||
*/
|
||||
public function delete($hardDelete = false);
|
||||
|
||||
/**
|
||||
* Return this organisations's members.
|
||||
*
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
||||
*/
|
||||
public function members();
|
||||
|
||||
/**
|
||||
* Return this organisations's admins.
|
||||
*
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
||||
*/
|
||||
public function administrators();
|
||||
|
||||
/**
|
||||
* Performs tasks to be done before an organisation is merged
|
||||
*
|
||||
* By default, adds a new sign-in activity and updates any legacy hash.
|
||||
*
|
||||
* @param OrganisationInterface $target The organisation that will be merged towards.
|
||||
* @param mixed[] $params Optional array of parameters used for this event handler.
|
||||
*
|
||||
* @todo Transition to Laravel Event dispatcher to handle this
|
||||
*/
|
||||
public function beforeMerge($target, $params = []);
|
||||
|
||||
/**
|
||||
* Joins the organisation's member count, so we can do things like sort, search, paginate, etc.
|
||||
*
|
||||
* @param Builder $query
|
||||
*
|
||||
* @return Builder
|
||||
*/
|
||||
public function scopeJoinMemberCounts($query);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ namespace UserFrosting\Sprinkle\Organisations\Database\Models;
|
||||
|
||||
use Illuminate\Database\Capsule\Manager as DB;
|
||||
use UserFrosting\Sprinkle\Core\Database\Models\Model;
|
||||
use UserFrosting\Sprinkle\Organisations\Database\Models\Interfaces\OrganisationInterface;
|
||||
|
||||
/**
|
||||
* Organisation Class.
|
||||
@@ -26,7 +27,7 @@ use UserFrosting\Sprinkle\Core\Database\Models\Model;
|
||||
* @property timestamp $updated_at
|
||||
* @property timestamp $deleted_at
|
||||
*/
|
||||
class Organisation extends Model
|
||||
class Organisation extends Model implements OrganisationInterface
|
||||
{
|
||||
/**
|
||||
* @var string The name of the table for the current model.
|
||||
@@ -131,6 +132,86 @@ class Organisation extends Model
|
||||
->withTimestamps();
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete this organisation from the database, along with any linked objects.
|
||||
*
|
||||
* @param bool $hardDelete Set to true to completely remove the organisation and all associated objects.
|
||||
*
|
||||
* @return bool true if the deletion was successful, false otherwise.
|
||||
*/
|
||||
public function delete($hardDelete = false)
|
||||
{
|
||||
/** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
|
||||
$classMapper = static::$ci->classMapper;
|
||||
|
||||
if ($hardDelete) {
|
||||
static::$ci->get('organisation.beforeDelete')($this);
|
||||
|
||||
// Remove all member associations
|
||||
$this->members()->detach();
|
||||
|
||||
// Delete the organisation
|
||||
$result = $this->forceDelete();
|
||||
} else {
|
||||
// Soft delete the organisation, leaving all associated records alone
|
||||
$result = parent::delete();
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs tasks to be done before an organisation is merged
|
||||
*
|
||||
* By default, adds a new sign-in activity and updates any legacy hash.
|
||||
*
|
||||
* @param mixed[] $params Optional array of parameters used for this event handler.
|
||||
*
|
||||
* @todo Transition to Laravel Event dispatcher to handle this
|
||||
*/
|
||||
public function beforeMerge($target, $params = [])
|
||||
{
|
||||
/** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
|
||||
$classMapper = static::$ci->classMapper;
|
||||
|
||||
/** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
|
||||
$currentUser = static::$ci->authenticator->user();
|
||||
|
||||
/** @var \UserFrosting\Sprinkle\???? $activityLogger */
|
||||
$activityLogger = static::$ci->userActivityLogger;
|
||||
|
||||
$logEntry = function($activityLogger, $currentUser, $user, $target) {
|
||||
$activityLogger->info("User {$currentUser->user_name} moved user {$user->user_name} from organisation {$this->name} into {$target->name}.", [
|
||||
'type' => 'organisation_merge',
|
||||
'user_id' => $currentUser->id,
|
||||
]);
|
||||
$activityLogger->info("User {$user->user_name} was removed from the organisation {$this->name} by {$currentUser->user_name} during an organisation merge.", [
|
||||
'type' => 'group_leave',
|
||||
'user_id' => $user->id,
|
||||
]);
|
||||
$activityLogger->info("User {$user->user_name} was added to the organisation {$target->name} by {$currentUser->user_name} during an organisation merge.", [
|
||||
'type' => 'group_join',
|
||||
'user_id' => $user->id,
|
||||
]);
|
||||
};
|
||||
|
||||
// Move all the users from this organisation to the target
|
||||
$this->members()->each(function ($user) use ($target, $activityLogger, $currentUser, $logEntry) {
|
||||
$this->members()->detach($user); // NOTE: Should this record be retained? Or is the activity log enough of an audit?
|
||||
$target->members()->attach($user, ['flag_admin' => false]);
|
||||
$logEntry($activityLogger, $currentUser, $user, $target);
|
||||
});
|
||||
$this->administrators()->each(function ($user) use ($target, $activityLogger, $currentUser, $logEntry) {
|
||||
$this->administrators()->detach($user); // NOTE: Should this record be retained? Or is the activity log enough of an audit?
|
||||
$target->administrators()->attach($user, ['flag_admin' => true]);
|
||||
$logEntry($activityLogger, $currentUser, $user, $target);
|
||||
});
|
||||
$this->save();
|
||||
$target->save();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Joins the organisation's member count, so we can do things like sort, search, paginate, etc.
|
||||
*
|
||||
|
||||
@@ -61,6 +61,12 @@ class OrganisationPermissions extends BaseSeed
|
||||
'conditions' => 'always()',
|
||||
'description' => 'Edit basic properties of any organisation.',
|
||||
]),
|
||||
'merge_organisations' => new Permission([
|
||||
'slug' => 'merge_organisations',
|
||||
'name' => 'Merge two organisations',
|
||||
'conditions' => 'always()',
|
||||
'description' => 'Merge two organisations together, including all the members.',
|
||||
]),
|
||||
'delete_organisation' => new Permission([
|
||||
'slug' => 'delete_organisation',
|
||||
'name' => 'Delete organisation',
|
||||
|
||||
@@ -12,6 +12,7 @@ namespace UserFrosting\Sprinkle\Organisations\ServicesProvider;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
use UserFrosting\Sprinkle\Organisations\Database\Models\Interfaces\OrganisationInterface as OrganisationInterface;
|
||||
|
||||
/**
|
||||
* Registers services for the organisation sprinkle.
|
||||
@@ -40,5 +41,44 @@ class ServicesProvider
|
||||
|
||||
return $classMapper;
|
||||
});
|
||||
|
||||
|
||||
/*
|
||||
* Returns a callback that handles merging any organisation objects.
|
||||
*
|
||||
* @return callable
|
||||
*/
|
||||
$container['organisation.beforeMerge'] = function ($c) {
|
||||
/*
|
||||
* This method is invoked when an organisation is about to be merged
|
||||
*
|
||||
* Returns a callback that handles re-owning any organisation objects.
|
||||
* Throwing exceptions is allowed but not recommended. This method is triggered within a Capsule context.
|
||||
* @param \UserFrosting\Sprinkle\Organisations\Database\Models\Interfaces\OrganisationInterfaces $source Organisation merging from
|
||||
* @param \UserFrosting\Sprinkle\Organisations\Database\Models\Interfaces\OrganisationInterfaces $target Organisation merging towards
|
||||
*/
|
||||
return function (OrganisationInterface $source, OrganisationInterface $target) use ($c) {
|
||||
|
||||
};
|
||||
};
|
||||
|
||||
/*
|
||||
* Returns a callback that handles hard deleting an organisation (clean up any associated objects).
|
||||
*
|
||||
* @return callable
|
||||
*/
|
||||
$container['organisation.beforeDelete'] = function ($c) {
|
||||
/*
|
||||
* This method is invoked when an organisation is about to be merged
|
||||
*
|
||||
* Returns a callback that handles re-owning any organisation objects.
|
||||
* Throwing exceptions is allowed but not recommended. This method is triggered within a Capsule context.
|
||||
* @param \UserFrosting\Sprinkle\Organisations\Database\Models\Interfaces\OrganisationInterfaces $organisation Organisation about to be deleted
|
||||
*/
|
||||
return function (OrganisationInterface $organisation) use ($c) {
|
||||
|
||||
};
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user