Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions ProcessMaker/Models/Group.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace ProcessMaker\Models;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\Rule;
use ProcessMaker\Models\EmptyModel;
use ProcessMaker\Query\Traits\PMQL;
Expand Down Expand Up @@ -156,4 +158,63 @@ public function assigned()
{
return $this->morphMany(ProcessTaskAssignment::class, 'assigned', 'assignment_type', 'assignment_id');
}

/**
* Parent group IDs for the given groups (one walk up, not one query per group).
*/
public static function ancestorIdsFor(iterable $groupIds): Collection
{
$ids = collect($groupIds)->filter()->map(fn ($id) => (int) $id)->unique()->values();
if ($ids->isEmpty()) {
return collect();
}

return collect(static::computeAncestorIds($ids->all()));
}

public const SELF_SERVICE_HIERARCHY_VERSION_KEY = 'self_service:hierarchy_version';

public static function selfServiceHierarchyVersion(): int
{
return (int) Cache::get(self::SELF_SERVICE_HIERARCHY_VERSION_KEY, 1);
}

public static function bumpSelfServiceHierarchyVersion(): void
{
if (!Cache::has(self::SELF_SERVICE_HIERARCHY_VERSION_KEY)) {
Cache::forever(self::SELF_SERVICE_HIERARCHY_VERSION_KEY, 1);
}
Cache::increment(self::SELF_SERVICE_HIERARCHY_VERSION_KEY);
}

/**
* @return array<int>
*/
private static function computeAncestorIds(array $groupIds): array
{
$ancestors = [];
$queue = $groupIds;
$visited = array_fill_keys($groupIds, true);

while ($queue) {
$parents = GroupMember::query()
->where('member_type', self::class)
->whereIn('member_id', $queue)
->pluck('group_id')
->all();

$queue = [];
foreach ($parents as $parentId) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rodriquelca Could changing this foreach to a while loop cause any performance issues? Could you analyze it and also check what happens if a group has a recursive assignment?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rodriquelca consider to add a test with circular reference of groups:

Group0 -> Group1 -> Group0

Seems the code covers it but please include it in a test

$parentId = (int) $parentId;
if (isset($visited[$parentId])) {
continue;
}
$visited[$parentId] = true;
$ancestors[] = $parentId;
$queue[] = $parentId;
}
}

return $ancestors;
}
}
5 changes: 3 additions & 2 deletions ProcessMaker/Models/ProcessMakerModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ public function scopeExclude($query, array $columns)
}

$columnsToShow = array_diff($this->getTableColumns(), $columns);
$columnsToShow = array_map(function ($column) {
return $this->table . '.' . $column;
$table = $this->getTable();
$columnsToShow = array_map(function ($column) use ($table) {
return $table . '.' . $column;
}, $columnsToShow);

return $query->select($columnsToShow);
Expand Down
56 changes: 56 additions & 0 deletions ProcessMaker/Models/Relations/UserGroups.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace ProcessMaker\Models\Relations;

use Illuminate\Database\Eloquent\Relations\MorphToMany;
use ProcessMaker\Models\User;

class UserGroups extends MorphToMany
{
public function attach($id, array $attributes = [], $touch = true)
{
$result = parent::attach($id, $attributes, $touch);
$this->flushSelfServiceGroupCache();

return $result;
}

public function detach($ids = null, $touch = true, $pivotAttributes = [])
{
$result = parent::detach($ids, $touch, $pivotAttributes);
$this->flushSelfServiceGroupCache();

return $result;
}

public function sync($ids, $detaching = true)
{
$result = parent::sync($ids, $detaching);
$this->flushSelfServiceGroupCache();

return $result;
}

public function syncWithoutDetaching($ids)
{
$result = parent::syncWithoutDetaching($ids);
$this->flushSelfServiceGroupCache();

return $result;
}

public function toggle($ids, $touch = true)
{
$result = parent::toggle($ids, $touch);
$this->flushSelfServiceGroupCache();

return $result;
}

private function flushSelfServiceGroupCache(): void
{
if ($this->parent instanceof User && $this->parent->getKey() !== null) {
User::flushSelfServiceGroupIdsCache((int) $this->parent->getKey());
}
}
}
56 changes: 48 additions & 8 deletions ProcessMaker/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ class User extends Authenticatable implements HasMedia
// Session key to save request ids that the user started
public const REQUESTS_SESSION_KEY = 'web-entry-request-ids';

public const SELF_SERVICE_GROUP_IDS_CACHE_PREFIX = 'self_service:user_group_ids:';

public const SELF_SERVICE_GROUP_IDS_CACHE_TTL_MINUTES = 10;

/**
* The attributes that are mass assignable.
*
Expand Down Expand Up @@ -297,7 +301,17 @@ public function groupMembersFromMemberable()

public function groups()
{
return $this->morphToMany('ProcessMaker\Models\Group', 'member', 'group_members');
return new Relations\UserGroups(
Group::query(),
$this,
'member',
'group_members',
'member_id',
'group_id',
$this->getKeyName(),
(new Group())->getKeyName(),
'groups'
);
}

public function projectMembers()
Expand Down Expand Up @@ -451,15 +465,13 @@ public function canSelfServe(ProcessRequestToken $task)
return true;
} elseif (array_key_exists('groups', $task->self_service_groups)) {
return collect($task->self_service_groups['groups'])
->intersect(
$this->groups()->pluck('groups.id')
)->count() > 0;
->intersect($this->selfServiceGroupIds())
->count() > 0;
} else {
// For older processes
return collect($task->self_service_groups)
->intersect(
$this->groups()->pluck('groups.id')
)->count() > 0;
->intersect($this->selfServiceGroupIds())
->count() > 0;
}
}

Expand All @@ -468,9 +480,37 @@ public function removeFromGroups()
$this->groups()->detach();
}

/**
* Direct group IDs plus ancestor groups. Cached per user; skipped on inbox repeats.
*/
public function selfServiceGroupIds()
{
$key = $this->selfServiceGroupIdsCacheKey();

return collect(Cache::remember($key, now()->addMinutes(self::SELF_SERVICE_GROUP_IDS_CACHE_TTL_MINUTES), function () {
$direct = $this->groups()->pluck('groups.id');
if ($direct->isEmpty()) {
return [];
}

return $direct->merge(Group::ancestorIdsFor($direct))->unique()->values()->all();
}));
}

public static function flushSelfServiceGroupIdsCache(int $userId): void
{
$version = Group::selfServiceHierarchyVersion();
Cache::forget(self::SELF_SERVICE_GROUP_IDS_CACHE_PREFIX . $userId . ':' . $version);
}

private function selfServiceGroupIdsCacheKey(): string
{
return self::SELF_SERVICE_GROUP_IDS_CACHE_PREFIX . $this->id . ':' . Group::selfServiceHierarchyVersion();
}

public function availableSelfServiceTasksQuery()
{
$groupIds = $this->groups()->pluck('groups.id');
$groupIds = $this->selfServiceGroupIds();

$taskQuery = ProcessRequestToken::select(['process_request_tokens.id'])
->where([
Expand Down
22 changes: 22 additions & 0 deletions ProcessMaker/Observers/GroupMemberObserver.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use ProcessMaker\Events\GroupMembershipChanged;
use ProcessMaker\Models\Group;
use ProcessMaker\Models\GroupMember;
use ProcessMaker\Models\User;

class GroupMemberObserver
{
Expand All @@ -14,6 +15,8 @@ class GroupMemberObserver
*/
public function created(GroupMember $groupMember): void
{
$this->invalidateSelfServiceGroupCache($groupMember);

// Only handle group-to-group relationships, not user-to-group
if ($groupMember->member_type === Group::class) {
$group = Group::find($groupMember->member_id);
Expand All @@ -32,6 +35,8 @@ public function created(GroupMember $groupMember): void
*/
public function updated(GroupMember $groupMember): void
{
$this->invalidateSelfServiceGroupCache($groupMember);

// Only handle group-to-group relationships, not user-to-group
if ($groupMember->member_type === Group::class) {
$group = Group::find($groupMember->member_id);
Expand All @@ -50,6 +55,8 @@ public function updated(GroupMember $groupMember): void
*/
public function deleted(GroupMember $groupMember): void
{
$this->invalidateSelfServiceGroupCache($groupMember);

// Only handle group-to-group relationships, not user-to-group
if ($groupMember->member_type === Group::class) {
$group = Group::find($groupMember->member_id);
Expand All @@ -68,6 +75,8 @@ public function deleted(GroupMember $groupMember): void
*/
public function restored(GroupMember $groupMember): void
{
$this->invalidateSelfServiceGroupCache($groupMember);

// Only handle group-to-group relationships, not user-to-group
if ($groupMember->member_type === Group::class) {
$group = Group::find($groupMember->member_id);
Expand All @@ -80,4 +89,17 @@ public function restored(GroupMember $groupMember): void
}
}
}

private function invalidateSelfServiceGroupCache(GroupMember $groupMember): void
{
if ($groupMember->member_type === Group::class) {
Group::bumpSelfServiceHierarchyVersion();

return;
}

if ($groupMember->member_type === User::class) {
User::flushSelfServiceGroupIdsCache((int) $groupMember->member_id);
}
}
Comment thread
cursor[bot] marked this conversation as resolved.
}
16 changes: 16 additions & 0 deletions ProcessMaker/Observers/GroupObserver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace ProcessMaker\Observers;

use ProcessMaker\Models\Group;

class GroupObserver
{
/**
* DB cascade deletes group_members without firing GroupMember events.
*/
public function deleting(Group $group): void
{
Group::bumpSelfServiceHierarchyVersion();
}
}
2 changes: 2 additions & 0 deletions ProcessMaker/Providers/ProcessMakerServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,8 @@ protected static function bootObservers(): void
{
Models\User::observe(Observers\UserObserver::class);

Models\Group::observe(Observers\GroupObserver::class);

Models\Setting::observe(Observers\SettingObserver::class);

Models\Process::observe(Observers\ProcessObserver::class);
Expand Down
Loading
Loading