diff --git a/app/Actions/CreateGuild.php b/app/Actions/CreateGuild.php index b4e61728a0..d18df06c65 100644 --- a/app/Actions/CreateGuild.php +++ b/app/Actions/CreateGuild.php @@ -4,6 +4,7 @@ namespace App\Actions; +use App\Exceptions\GuildModeratorLimitReached; use App\Exceptions\GuildModeratorRemoved; use App\Models\Guild; use App\Models\GuildSubmission; @@ -26,6 +27,11 @@ public function handle(User $user, string $handle, string $name, string $descrip return DB::transaction(function () use ($user, $handle, $name, $description, $emoji, $icon, $flagged): Guild|GuildSubmission { User::query()->whereKey($user->id)->lockForUpdate()->firstOrFail(); + // Counted again under the lock, since a handover may have given the user another guild after validation. + if (Guild::query()->where('user_id', $user->id)->count() >= Guild::MAX_PER_USER) { + throw new GuildModeratorLimitReached; + } + if (DB::table('guild_moderator_removals')->where('github_id', $user->github_id)->where('handle', mb_strtolower($handle))->exists()) { throw new GuildModeratorRemoved; } diff --git a/app/Actions/CreateGuildSubmissionApproval.php b/app/Actions/CreateGuildSubmissionApproval.php index f104739bb2..47739744ee 100644 --- a/app/Actions/CreateGuildSubmissionApproval.php +++ b/app/Actions/CreateGuildSubmissionApproval.php @@ -4,6 +4,7 @@ namespace App\Actions; +use App\Exceptions\GuildModeratorLimitReached; use App\Exceptions\GuildModeratorRemoved; use App\Models\Guild; use App\Models\GuildSubmission; @@ -20,7 +21,7 @@ public function __construct(private CreateGuild $createGuild, private UpdateGuil /** * Publishes the submission as if it had passed the moderation: an edit when its author still moderates the guild, * otherwise a new guild, which claims a paused one and leaves one someone else moderates alone. An author removed - * from the guild meanwhile gets nothing. + * from the guild meanwhile, or who reached the guild limit, gets nothing. */ public function handle(?GuildSubmission $submission): void { @@ -43,7 +44,7 @@ public function handle(?GuildSubmission $submission): void } else { $this->createGuild->handle($submission->user, $submission->handle, $submission->name, $submission->description, $submission->emoji, $submission->icon_path); } - } catch (GuildModeratorRemoved) { + } catch (GuildModeratorRemoved|GuildModeratorLimitReached) { // } diff --git a/app/Actions/UpdateGuild.php b/app/Actions/UpdateGuild.php index 782b1ce3bf..70d08ef315 100644 --- a/app/Actions/UpdateGuild.php +++ b/app/Actions/UpdateGuild.php @@ -6,6 +6,9 @@ use App\Enums\UserUpdate; use App\Events\UsersUpdated; +use App\Exceptions\GuildModeratorLimitReached; +use App\Exceptions\GuildModeratorNotMember; +use App\Exceptions\GuildModeratorPreviouslyRemoved; use App\Exceptions\GuildModeratorRemoved; use App\Models\Guild; use App\Models\GuildSubmission; @@ -21,40 +24,74 @@ public function __construct(private CreateImageFiles $images, private DeleteStor } /** - * The icon is an upload, or the path of one already stored, such as a reviewed submission's. + * The icon is an upload, or the path of one already stored, such as a reviewed submission's. A flagged edit waits for + * review, while a handover, which the moderation doesn't read, happens right away. A new moderator must still be a + * member who wasn't removed from moderating it, with room for another guild, when the guild is saved; both users' rows are locked before the guild, in the + * same order every time, so neither can leave or take on more guilds halfway through the handover. */ - public function handle(Guild $guild, User $user, string $name, string $description, string $emoji, UploadedFile|string|null $icon, bool $removeIcon, bool $flagged = false): void + public function handle(Guild $guild, User $user, string $name, string $description, string $emoji, UploadedFile|string|null $icon, bool $removeIcon, bool $flagged = false, ?User $moderator = null): void { - DB::transaction(function () use ($guild, $user, $name, $description, $emoji, $icon, $removeIcon, $flagged): void { - User::query()->whereKey($user->id)->lockForUpdate()->firstOrFail(); + DB::transaction(function () use ($guild, $user, $name, $description, $emoji, $icon, $removeIcon, $flagged, $moderator): void { + $handover = $moderator instanceof User && $moderator->id !== $user->id; + $locked = $handover ? [$user->id, $moderator->id] : [$user->id]; + sort($locked); + + foreach ($locked as $id) { + User::query()->whereKey($id)->lockForUpdate()->firstOrFail(); + } + + if ($handover && Guild::query()->where('user_id', $moderator->id)->count() >= Guild::MAX_PER_USER) { + throw new GuildModeratorLimitReached; + } + $guild = Guild::query()->whereKey($guild->id)->lockForUpdate()->firstOrFail(); if ($guild->user_id !== $user->id) { throw new GuildModeratorRemoved; } + if ($handover && ! $guild->members()->whereKey($moderator->id)->exists()) { + throw new GuildModeratorNotMember; + } + + // Checked again under the guild's lock, which an admin's removal takes too, so a handover validated before it can't undo it. + if ($handover && DB::table('guild_moderator_removals')->where('github_id', $moderator->github_id)->where('handle', $guild->handle)->exists()) { + throw new GuildModeratorPreviouslyRemoved; + } + if ($flagged) { assert($icon instanceof UploadedFile || $icon === null); $this->submit->handle($user, $guild->handle, $name, $description, $emoji, $icon, $removeIcon); + } else { + $path = $guild->icon_path; - return; - } + if ($icon !== null || $removeIcon) { + $this->deleteFiles->retain($path === null ? [] : [$path]); + $path = $icon instanceof UploadedFile ? $this->images->handle([$icon], directory: 'guild-icons')[0]['path'] : $icon; + } - $path = $guild->icon_path; + $guild->update(['name' => $name, 'description' => $description, 'emoji' => $emoji, 'icon_path' => $path]); + $submission = GuildSubmission::query()->where('user_id', $user->id)->where('handle', $guild->handle)->first(); - if ($icon !== null || $removeIcon) { - $this->deleteFiles->retain($path === null ? [] : [$path]); - $path = $icon instanceof UploadedFile ? $this->images->handle([$icon], directory: 'guild-icons')[0]['path'] : $icon; + if ($submission instanceof GuildSubmission) { + $this->deleteSubmission->handle($submission); + } } - $guild->update(['name' => $name, 'description' => $description, 'emoji' => $emoji, 'icon_path' => $path]); - $submission = GuildSubmission::query()->where('user_id', $user->id)->where('handle', $guild->handle)->first(); + if ($handover) { + $guild->update(['user_id' => $moderator->id]); + } - if ($submission instanceof GuildSubmission) { - $this->deleteSubmission->handle($submission); + if ($flagged && ! $handover) { + return; } - event(new UsersUpdated(DB::table('guild_preferences')->where('guild_id', $guild->id)->pluck('user_id')->push($guild->user_id), UserUpdate::Guilds)); + $viewers = DB::table('guild_preferences')->where('guild_id', $guild->id)->pluck('user_id')->push($user->id); + event(new UsersUpdated($viewers, UserUpdate::Guilds)); + + if ($handover) { + event(new UsersUpdated($viewers, UserUpdate::Relationships)); + } }); } } diff --git a/app/Exceptions/GuildModeratorLimitReached.php b/app/Exceptions/GuildModeratorLimitReached.php new file mode 100644 index 0000000000..9f2636e351 --- /dev/null +++ b/app/Exceptions/GuildModeratorLimitReached.php @@ -0,0 +1,9 @@ +handle($user, $request->string('handle')->value(), $request->string('name')->value(), $request->string('description')->value(), $request->string('emoji')->value(), $icon, $request->isFlagged()); } catch (GuildModeratorRemoved) { return $this->handleRefused(CreateGuildRequest::RECLAIM_REFUSED); + } catch (GuildModeratorLimitReached) { + return $this->handleRefused('You can create up to '.Guild::MAX_PER_USER.' guilds.'); } if ($guild instanceof GuildSubmission) { diff --git a/app/Http/Controllers/GuildController.php b/app/Http/Controllers/GuildController.php index 00f6e1ff90..d25d11b032 100644 --- a/app/Http/Controllers/GuildController.php +++ b/app/Http/Controllers/GuildController.php @@ -7,6 +7,9 @@ use App\Actions\CreateGuild; use App\Actions\UpdateGuild; use App\Enums\UserUpdate; +use App\Exceptions\GuildModeratorLimitReached; +use App\Exceptions\GuildModeratorNotMember; +use App\Exceptions\GuildModeratorPreviouslyRemoved; use App\Exceptions\GuildModeratorRemoved; use App\Http\Requests\CreateGuildRequest; use App\Http\Requests\ListGuildsRequest; @@ -49,6 +52,8 @@ public function store(CreateGuildRequest $request, #[CurrentUser] User $user, Cr $guild = $action->handle($user, $request->string('handle')->value(), $request->string('name')->value(), $request->string('description')->value(), $request->string('emoji')->value(), $icon, $request->isFlagged()); } catch (GuildModeratorRemoved) { return back()->withErrors(['handle' => CreateGuildRequest::RECLAIM_REFUSED]); + } catch (GuildModeratorLimitReached) { + return back()->withErrors(['handle' => 'You can create up to '.Guild::MAX_PER_USER.' guilds.']); } if ($guild instanceof GuildSubmission) { @@ -84,9 +89,15 @@ public function update(UpdateGuildRequest $request, Guild $guild, #[CurrentUser] assert($icon instanceof UploadedFile || $icon === null); try { - $action->handle($guild, $user, $request->string('name')->value(), $request->string('description')->value(), $request->string('emoji')->value(), $icon, $request->boolean('remove_icon'), $request->isFlagged()); + $action->handle($guild, $user, $request->string('name')->value(), $request->string('description')->value(), $request->string('emoji')->value(), $icon, $request->boolean('remove_icon'), $request->isFlagged(), $request->moderator()); } catch (GuildModeratorRemoved) { return back()->withErrors(['description' => 'You no longer moderate this guild.']); + } catch (GuildModeratorNotMember) { + return back()->withErrors(['moderator_id' => 'Pick a member of this guild.']); + } catch (GuildModeratorPreviouslyRemoved) { + return back()->withErrors(['moderator_id' => UpdateGuildRequest::MODERATOR_REMOVED]); + } catch (GuildModeratorLimitReached) { + return back()->withErrors(['moderator_id' => UpdateGuildRequest::moderatorLimitMessage()]); } if ($request->isFlagged()) { diff --git a/app/Http/Controllers/GuildMemberSuggestionController.php b/app/Http/Controllers/GuildMemberSuggestionController.php new file mode 100644 index 0000000000..7ca13336c5 --- /dev/null +++ b/app/Http/Controllers/GuildMemberSuggestionController.php @@ -0,0 +1,18 @@ +json(['members' => $suggestions->get($guild, $request->string('q')->value())]); + } +} diff --git a/app/Http/Requests/CreateGuildRequest.php b/app/Http/Requests/CreateGuildRequest.php index 0af968a8a4..23e39d9806 100644 --- a/app/Http/Requests/CreateGuildRequest.php +++ b/app/Http/Requests/CreateGuildRequest.php @@ -26,8 +26,6 @@ final class CreateGuildRequest extends FormRequest { public const string RECLAIM_REFUSED = 'You cannot reclaim a guild you were removed from.'; - private const int MAX_PER_USER = 100; - private bool $isFlagged = false; /** @@ -65,8 +63,8 @@ public static function validateNewGuild(Validator $validator, FlaggedGuild $flag $guilds = Guild::query()->where('user_id', $user->id); $submissions = GuildSubmission::query()->where('user_id', $user->id)->where('handle', '!=', $handle)->whereNotIn('handle', (clone $guilds)->select('handle')); - if ($guilds->count() + $submissions->count() >= self::MAX_PER_USER) { - $validator->errors()->add('handle', 'You can create up to '.self::MAX_PER_USER.' guilds.'); + if ($guilds->count() + $submissions->count() >= Guild::MAX_PER_USER) { + $validator->errors()->add('handle', 'You can create up to '.Guild::MAX_PER_USER.' guilds.'); } return $validator->errors()->isEmpty() && $flagged->validate($validator, $name."\n\n".$description, $icon); diff --git a/app/Http/Requests/ListGuildMemberSuggestionsRequest.php b/app/Http/Requests/ListGuildMemberSuggestionsRequest.php new file mode 100644 index 0000000000..c4e23421b9 --- /dev/null +++ b/app/Http/Requests/ListGuildMemberSuggestionsRequest.php @@ -0,0 +1,32 @@ +route('guild'); + assert($guild instanceof Guild); + + return $features->available(Feature::Guilds, $this->user()) && $guild->user_id === $this->user()?->id + ? Response::allow() : Response::denyAsNotFound(); + } + + /** @return array> */ + public function rules(): array + { + return ['q' => ['nullable', 'string', 'max:60']]; + } +} diff --git a/app/Http/Requests/UpdateGuildRequest.php b/app/Http/Requests/UpdateGuildRequest.php index b78592b578..61a3c7b0bb 100644 --- a/app/Http/Requests/UpdateGuildRequest.php +++ b/app/Http/Requests/UpdateGuildRequest.php @@ -6,6 +6,7 @@ use App\Enums\Feature; use App\Models\Guild; +use App\Models\User; use App\Rules\FlaggedGuild; use App\Services\EmojiShortcodes; use App\Services\Features; @@ -13,14 +14,24 @@ use Illuminate\Auth\Access\Response; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\UploadedFile; +use Illuminate\Support\Facades\DB; use Illuminate\Validation\Rule; use Illuminate\Validation\Rules\In; use Illuminate\Validation\Validator; final class UpdateGuildRequest extends FormRequest { + public const string MODERATOR_REMOVED = 'This member was removed as its moderator.'; + + public const string HANDOVER_NEEDS_REVIEW = "These changes need an admin's review first. Save them without handing moderation over."; + private bool $isFlagged = false; + public static function moderatorLimitMessage(): string + { + return 'This member already moderates '.Guild::MAX_PER_USER.' guilds.'; + } + /** * The rules a guild edit follows, wherever it's made. * @@ -65,7 +76,10 @@ public function authorize(Features $features): Response /** @return array> */ public function rules(EmojiShortcodes $emoji): array { - return self::guildRules($emoji); + return [ + ...self::guildRules($emoji), + 'moderator_id' => ['sometimes', 'string', 'uuid'], + ]; } /** @return list */ @@ -78,11 +92,31 @@ public function after(FlaggedGuild $flagged): array $guild = $this->route('guild'); assert($guild instanceof Guild); + $this->validateModerator($validator, $guild); + + if ($validator->errors()->isNotEmpty()) { + return; + } + $icon = $this->file('images.0'); $this->isFlagged = self::validateEdit($validator, $flagged, $guild, $this->string('name')->value(), $this->string('description')->value(), $icon instanceof UploadedFile ? $icon : null); + + // A queued edit is only published while its author moderates the guild, so a handover in the same save would drop it. + if ($this->isFlagged && $this->handsOverModeration()) { + if ($this->changes($guild, $icon instanceof UploadedFile)) { + $validator->errors()->add('moderator_id', self::HANDOVER_NEEDS_REVIEW); + } + + $this->isFlagged = false; + } }]; } + public function moderator(): ?User + { + return $this->filled('moderator_id') ? User::query()->find($this->string('moderator_id')->value()) : null; + } + /** * Whether the moderation flagged the edit, so it waits for an admin instead of being published. */ @@ -90,4 +124,47 @@ public function isFlagged(): bool { return $this->isFlagged; } + + private function handsOverModeration(): bool + { + $moderator = $this->moderator(); + + return $moderator instanceof User && $moderator->id !== $this->user()?->id; + } + + /** + * Whether the save changes anything about the guild itself, rather than only who moderates it. + */ + private function changes(Guild $guild, bool $hasIcon): bool + { + return $hasIcon + || ($this->boolean('remove_icon') && $guild->icon_path !== null) + || $this->string('name')->value() !== $guild->name + || $this->string('description')->value() !== $guild->description + || $this->string('emoji')->value() !== $guild->emoji; + } + + /** + * Moderation can only go to someone who already joined the guild, wasn't removed from moderating it, and has room for another guild. + */ + private function validateModerator(Validator $validator, Guild $guild): void + { + $moderator = $this->moderator(); + + if (! $moderator instanceof User || $moderator->id === $this->user()?->id) { + if ($this->filled('moderator_id') && ! $moderator instanceof User) { + $validator->errors()->add('moderator_id', 'Pick a member of this guild.'); + } + + return; + } + + if (! $guild->members()->whereKey($moderator->id)->exists()) { + $validator->errors()->add('moderator_id', 'Pick a member of this guild.'); + } elseif (DB::table('guild_moderator_removals')->where('github_id', $moderator->github_id)->where('handle', $guild->handle)->exists()) { + $validator->errors()->add('moderator_id', self::MODERATOR_REMOVED); + } elseif (Guild::query()->where('user_id', $moderator->id)->count() >= Guild::MAX_PER_USER) { + $validator->errors()->add('moderator_id', self::moderatorLimitMessage()); + } + } } diff --git a/app/Models/Guild.php b/app/Models/Guild.php index fe4d6ab8e7..287368255e 100644 --- a/app/Models/Guild.php +++ b/app/Models/Guild.php @@ -37,6 +37,11 @@ final class Guild extends Model use HasUuids; + /** + * How many guilds one person can moderate, counting the ones they created and the ones handed to them. + */ + public const int MAX_PER_USER = 100; + /** @return HasMany */ public function commits(): HasMany { diff --git a/app/Queries/GuildMemberSuggestionsQuery.php b/app/Queries/GuildMemberSuggestionsQuery.php new file mode 100644 index 0000000000..18417978b6 --- /dev/null +++ b/app/Queries/GuildMemberSuggestionsQuery.php @@ -0,0 +1,51 @@ + + */ + public function get(Guild $guild, string $term, int $limit = 8): Collection + { + $term = Str::of($term)->trim()->ltrim('@')->lower()->value(); + $escaped = str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $term); + + return $guild->members() + ->select('users.*') + ->join('profiles', 'profiles.id', '=', 'users.id') + ->when($guild->user_id !== null, fn (Builder $query): Builder => $query->whereKeyNot($guild->user_id)) + ->when($term !== '', fn (Builder $query): Builder => $query + ->where(fn (Builder $query): Builder => $query + ->whereRaw("LOWER(profiles.handle) LIKE ? ESCAPE '!'", ["%{$escaped}%"]) + ->orWhereRaw("LOWER(profiles.name) LIKE ? ESCAPE '!'", ["%{$escaped}%"])) + ->orderByRaw( + "CASE WHEN LOWER(profiles.handle) = ? THEN 0 WHEN LOWER(profiles.handle) LIKE ? ESCAPE '!' THEN 1 WHEN LOWER(profiles.name) LIKE ? ESCAPE '!' THEN 2 ELSE 3 END", + [$term, "{$escaped}%", "{$escaped}%"], + )) + ->orderByPivot('joined_at', 'desc') + ->latest('users.id') + ->limit($limit) + ->get() + ->map(fn (User $member): array => [ + 'id' => $member->id, + 'handle' => $member->handle, + 'name' => $member->name, + 'avatar_url' => $member->avatar_url, + ]) + ->values() + ->toBase(); + } +} diff --git a/resources/js/components/guild-dialog.tsx b/resources/js/components/guild-dialog.tsx index 35b0291c2e..dacb35cd9f 100644 --- a/resources/js/components/guild-dialog.tsx +++ b/resources/js/components/guild-dialog.tsx @@ -5,6 +5,7 @@ import { type ReactNode, useRef, useState } from 'react'; import { store, update } from '@/actions/App/Http/Controllers/GuildController'; import { EmojiPickerButton } from '@/components/emoji-picker'; import { GuildIcon } from '@/components/guild-icon'; +import { GuildModeratorPicker } from '@/components/guild-moderator-picker'; import InputError from '@/components/input-error'; import { Button } from '@/components/ui/button'; import { @@ -57,7 +58,7 @@ export function GuildDialog({ {guild - ? 'As the moderator, you can change the display name, icon and description.' + ? 'As the moderator, you can change the display name, icon and description, or hand moderation to another member.' : handle ? `Give #${handle} a home. Its commits stay public and keep appearing in the log.` : 'Create a public group. Its name determines the hashtag that brings commits into the guild.'} @@ -238,6 +239,18 @@ export function GuildDialog({ /> + {guild && ( + + form.current?.clearErrors( + 'moderator_id', + ) + } + /> + )} diff --git a/resources/js/components/guild-moderator-picker.tsx b/resources/js/components/guild-moderator-picker.tsx new file mode 100644 index 0000000000..e16b9b1492 --- /dev/null +++ b/resources/js/components/guild-moderator-picker.tsx @@ -0,0 +1,226 @@ +import { usePage } from '@inertiajs/react'; +import { useEffect, useId, useState } from 'react'; +import { index as memberSuggestions } from '@/actions/App/Http/Controllers/GuildMemberSuggestionController'; +import InputError from '@/components/input-error'; +import { Button } from '@/components/ui/button'; +import { Label } from '@/components/ui/label'; +import { Spinner } from '@/components/ui/spinner'; +import { UserAvatar } from '@/components/user-avatar'; +import { toastWhenThrottled } from '@/lib/throttle'; +import { cn } from '@/lib/utils'; +import type { User } from '@/types'; + +type Member = Pick; + +/** + * Hands moderation to another member. Only people who already joined the guild show up, and the server checks it again on save. + */ +export function GuildModeratorPicker({ + handle, + fieldClass, + error, + onChange, +}: { + handle: string; + fieldClass: string; + error?: string; + onChange?: () => void; +}) { + const me = usePage().props.auth.user; + const id = useId(); + const [moderator, setModerator] = useState(me); + const [searching, setSearching] = useState(false); + const [query, setQuery] = useState(''); + const [members, setMembers] = useState(null); + + useEffect(() => { + if (!searching) return; + + const controller = new AbortController(); + const timeout = setTimeout( + () => { + fetch( + memberSuggestions.url(handle, { + query: { q: query.trim() || undefined }, + }), + { + headers: { + Accept: 'application/json', + 'X-Requested-With': 'XMLHttpRequest', + }, + signal: controller.signal, + }, + ) + .then(async (response) => { + if (!response.ok) { + toastWhenThrottled(response); + throw new Error('Unable to load members'); + } + + return (await response.json()) as { + members: Member[]; + }; + }) + .then((data) => { + if (!controller.signal.aborted) + setMembers(data.members); + }) + .catch(() => { + if (!controller.signal.aborted) setMembers([]); + }); + }, + query ? 200 : 0, + ); + + return () => { + clearTimeout(timeout); + controller.abort(); + }; + }, [handle, query, searching]); + + if (!me) return null; + + const handover = moderator !== null && moderator.id !== me.id; + + const pick = (member: Member) => { + setModerator(member); + setSearching(false); + setQuery(''); + setMembers(null); + onChange?.(); + }; + + return ( +
+ + + {searching ? ( +
+ { + // Results for an older search are dropped at once, so neither Enter nor a click can pick from them. + setQuery(event.target.value); + setMembers(null); + }} + onKeyDown={(event) => { + if (event.key === 'Enter') { + event.preventDefault(); + if (members?.[0]) pick(members[0]); + } + }} + className={fieldClass} + aria-controls={`${id}-members`} + aria-describedby={`${id}-error`} + /> +
    + {members === null ? ( +
  • + +
  • + ) : members.length === 0 ? ( +
  • + {query + ? 'No members match.' + : 'Nobody else has joined yet.'} +
  • + ) : ( + members.map((member) => ( +
  • + +
  • + )) + )} +
+
+ +
+
+ ) : ( +
+ + {!handover && ( + + You + + )} + +
+ )} + {handover && !searching && ( +

+ Once you save, @{moderator.handle} moderates #{handle} and + you can no longer edit it.{' '} + +

+ )} +
+ +
+
+ ); +} + +function MemberRow({ member }: { member: Member }) { + return ( + <> + + + {member.name}{' '} + @{member.handle} + + + ); +} diff --git a/routes/web.php b/routes/web.php index e4b8c6961f..91cb2544a0 100644 --- a/routes/web.php +++ b/routes/web.php @@ -64,6 +64,7 @@ use App\Http\Controllers\GuildController; use App\Http\Controllers\GuildIconController; use App\Http\Controllers\GuildMembershipController; +use App\Http\Controllers\GuildMemberSuggestionController; use App\Http\Controllers\GuildModeratorController; use App\Http\Controllers\GuildMuteController; use App\Http\Controllers\GuildReadController; @@ -378,6 +379,7 @@ Route::get('guilds', [GuildController::class, 'index'])->name('guild.index'); Route::get('guilds/{guild:handle}', [GuildController::class, 'show'])->name('guild.show'); Route::get('guilds/{guild:handle}/members', [GuildMembershipController::class, 'index'])->name('guild-membership.index'); + Route::get('guilds/{guild:handle}/member-suggestions', [GuildMemberSuggestionController::class, 'index'])->middleware('throttle:people')->name('guild-member-suggestion.index'); Route::get('guilds/{guild:handle}/icon', [GuildIconController::class, 'show'])->name('guild-icon.show'); Route::post('guilds', [GuildController::class, 'store'])->middleware([PreventPostingInTimeout::class, 'throttle:10,1'])->name('guild.store'); Route::put('guilds/{guild:handle}', [GuildController::class, 'update'])->middleware([PreventPostingInTimeout::class, 'throttle:10,1'])->name('guild.update'); diff --git a/tests/Feature/Controllers/GuildControllerTest.php b/tests/Feature/Controllers/GuildControllerTest.php index e9881b13f1..984bc8e48c 100644 --- a/tests/Feature/Controllers/GuildControllerTest.php +++ b/tests/Feature/Controllers/GuildControllerTest.php @@ -21,6 +21,7 @@ use App\Events\UsersUpdated; use App\Exceptions\GuildModeratorRemoved; use App\Http\Middleware\HandleInertiaRequests; +use App\Http\Requests\UpdateGuildRequest; use App\Models\Commit; use App\Models\Guild; use App\Models\GuildReport; @@ -34,6 +35,7 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Storage; +use Illuminate\Support\Str; beforeEach(function (): void { config(['app.admins' => ['admin', 'other-admin']]); @@ -1227,3 +1229,165 @@ $this->assertModelMissing($scheduled); $this->assertModelExists($regular); }); + +it('lets the moderator hand moderation only to a current member', function (): void { + Event::fake([UsersUpdated::class]); + $moderator = User::factory()->create(['handle' => 'admin']); + $member = User::factory()->create(['handle' => 'other-admin']); + $outsider = User::factory()->create(); + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'jobs']); + $guild->members()->attach($moderator, ['joined_at' => now()]); + $guild->members()->attach($member, ['joined_at' => now()]); + $guild->muters()->attach($outsider, ['muted_at' => now()]); + $payload = ['name' => 'Jobs', 'description' => 'Remote jobs.', 'emoji' => '🌍', 'remove_icon' => false]; + + $this->actingAs($moderator)->put(route('guild.update', 'jobs'), [...$payload, 'moderator_id' => $outsider->id])->assertSessionHasErrors(['moderator_id' => 'Pick a member of this guild.']); + $this->put(route('guild.update', 'jobs'), [...$payload, 'moderator_id' => (string) Str::uuid()])->assertSessionHasErrors(['moderator_id' => 'Pick a member of this guild.']); + $this->putJson(route('guild.update', 'jobs'), [...$payload, 'moderator_id' => 'nope'])->assertJsonValidationErrors('moderator_id'); + expect($guild->fresh())->user_id->toBe($moderator->id)->description->toBe($guild->description); + + $this->put(route('guild.update', 'jobs'), [...$payload, 'moderator_id' => $moderator->id])->assertRedirectToRoute('guild.show', 'jobs'); + expect($guild->fresh()->user_id)->toBe($moderator->id); + + $this->put(route('guild.update', 'jobs'), [...$payload, 'moderator_id' => $member->id])->assertRedirectToRoute('guild.show', 'jobs'); + expect($guild->fresh())->user_id->toBe($member->id)->description->toBe('Remote jobs.'); + Event::assertDispatched(UsersUpdated::class, fn (UsersUpdated $event): bool => $event->update === UserUpdate::Relationships && in_array($member->id, $event->userIds, true)); + $this->get(route('guild.show', 'jobs'))->assertInertia(fn ($page) => $page->where('canModerate', false)); + $this->put(route('guild.update', 'jobs'), $payload)->assertNotFound(); + + $this->actingAs($member)->get(route('guild.show', 'jobs'))->assertInertia(fn ($page) => $page->where('canModerate', true)); + $this->put(route('guild.update', 'jobs'), [...$payload, 'description' => 'Still hiring.'])->assertRedirectToRoute('guild.show', 'jobs'); + expect($guild->fresh())->user_id->toBe($member->id)->description->toBe('Still hiring.'); +}); + +it('refuses a handover to members removed from moderating it or at the guild limit', function (): void { + $moderator = User::factory()->create(['handle' => 'admin']); + $member = User::factory()->create(); + $removed = User::factory()->create(); + $busy = User::factory()->create(); + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'jobs']); + $guild->members()->attach([$member->id => ['joined_at' => now()], $removed->id => ['joined_at' => now()], $busy->id => ['joined_at' => now()]]); + DB::table('guild_moderator_removals')->insert(['github_id' => $removed->github_id, 'handle' => 'jobs', 'created_at' => now()]); + Guild::factory()->count(Guild::MAX_PER_USER)->create(['user_id' => $busy->id]); + $payload = ['name' => 'Jobs', 'description' => 'Remote jobs.', 'emoji' => '🌍', 'remove_icon' => false]; + + $this->actingAs($moderator)->put(route('guild.update', 'jobs'), [...$payload, 'moderator_id' => $removed->id])->assertSessionHasErrors(['moderator_id' => 'This member was removed as its moderator.']); + $this->put(route('guild.update', 'jobs'), [...$payload, 'moderator_id' => $busy->id])->assertSessionHasErrors(['moderator_id' => 'This member already moderates 100 guilds.']); + expect($guild->fresh()->user_id)->toBe($moderator->id); + $this->put(route('guild.update', 'jobs'), [...$payload, 'moderator_id' => $member->id])->assertRedirectToRoute('guild.show', 'jobs'); + expect($guild->fresh()->user_id)->toBe($member->id); +}); + +it('keeps the moderator when the new one reaches the guild limit after validation', function (): void { + $moderator = User::factory()->create(['handle' => 'admin']); + $member = User::factory()->create(['handle' => 'other-admin']); + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'jobs']); + $guild->members()->attach($member, ['joined_at' => now()]); + $this->app->beforeResolving(UpdateGuild::class, function () use ($member): void { + Guild::factory()->count(Guild::MAX_PER_USER)->create(['user_id' => $member->id]); + }); + + $this->actingAs($moderator)->put(route('guild.update', 'jobs'), [ + 'name' => 'Jobs', 'description' => 'Remote jobs.', 'emoji' => '🌍', 'remove_icon' => false, 'moderator_id' => $member->id, + ])->assertSessionHasErrors(['moderator_id' => 'This member already moderates 100 guilds.']); + + expect($guild->fresh())->user_id->toBe($moderator->id)->description->toBe($guild->description); +}); + +it('keeps the moderator when the new one leaves after validation', function (): void { + $moderator = User::factory()->create(['handle' => 'admin']); + $member = User::factory()->create(['handle' => 'other-admin']); + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'jobs']); + $guild->members()->attach($member, ['joined_at' => now()]); + $this->app->beforeResolving(UpdateGuild::class, function () use ($guild, $member): void { + $guild->members()->detach($member); + }); + + $this->actingAs($moderator)->put(route('guild.update', 'jobs'), [ + 'name' => 'Jobs', 'description' => 'Remote jobs.', 'emoji' => '🌍', 'remove_icon' => false, 'moderator_id' => $member->id, + ])->assertSessionHasErrors(['moderator_id' => 'Pick a member of this guild.']); + + expect($guild->fresh())->user_id->toBe($moderator->id)->description->toBe($guild->description); +}); + +it('keeps the moderator when the new one is removed from moderating the guild after validation', function (): void { + $moderator = User::factory()->create(['handle' => 'admin']); + $member = User::factory()->create(['handle' => 'other-admin']); + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'jobs']); + $guild->members()->attach($member, ['joined_at' => now()]); + $this->app->beforeResolving(UpdateGuild::class, function () use ($member): void { + DB::table('guild_moderator_removals')->insert(['github_id' => $member->github_id, 'handle' => 'jobs', 'created_at' => now()]); + }); + + $this->actingAs($moderator)->put(route('guild.update', 'jobs'), [ + 'name' => 'Jobs', 'description' => 'Remote jobs.', 'emoji' => '🌍', 'remove_icon' => false, 'moderator_id' => $member->id, + ])->assertSessionHasErrors(['moderator_id' => 'This member was removed as its moderator.']); + + expect($guild->fresh())->user_id->toBe($moderator->id)->description->toBe($guild->description); +}); + +it('suggests only other members to the moderator', function (): void { + $moderator = User::factory()->create(['handle' => 'admin']); + $admin = User::factory()->create(['handle' => 'other-admin', 'name' => 'Other Admin']); + $ada = User::factory()->create(['handle' => 'ada', 'name' => 'Ada Lovelace']); + $grace = User::factory()->create(['handle' => 'grace', 'name' => 'Grace Hopper']); + $muter = User::factory()->create(['handle' => 'adam']); + $outsider = User::factory()->create(['handle' => 'adaline']); + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'jobs']); + $guild->members()->attach([ + $admin->id => ['joined_at' => now()->subDays(4)], + $moderator->id => ['joined_at' => now()->subDays(3)], + $ada->id => ['joined_at' => now()->subDays(2)], + $grace->id => ['joined_at' => now()->subDay()], + ]); + $guild->muters()->attach($muter, ['muted_at' => now()]); + + $this->actingAs($moderator)->getJson(route('guild-member-suggestion.index', 'jobs'))->assertOk() + ->assertExactJson(['members' => [ + ['id' => $grace->id, 'handle' => 'grace', 'name' => 'Grace Hopper', 'avatar_url' => $grace->avatar_url], + ['id' => $ada->id, 'handle' => 'ada', 'name' => 'Ada Lovelace', 'avatar_url' => $ada->avatar_url], + ['id' => $admin->id, 'handle' => 'other-admin', 'name' => 'Other Admin', 'avatar_url' => $admin->avatar_url], + ]]); + $this->getJson(route('guild-member-suggestion.index', ['guild' => 'jobs', 'q' => '@ADA']))->assertOk() + ->assertJsonPath('members.*.handle', ['ada']); + $this->getJson(route('guild-member-suggestion.index', ['guild' => 'jobs', 'q' => 'hopper']))->assertOk() + ->assertJsonPath('members.*.handle', ['grace']); + + $this->actingAs($ada)->getJson(route('guild-member-suggestion.index', 'jobs'))->assertNotFound(); + $this->actingAs($outsider)->getJson(route('guild-member-suggestion.index', 'jobs'))->assertNotFound(); +}); + +it('refuses to create a guild once a handover filled the creator up after validation', function (): void { + $creator = User::factory()->create(['handle' => 'admin']); + Guild::factory()->count(Guild::MAX_PER_USER - 1)->create(['user_id' => $creator->id]); + $this->app->beforeResolving(CreateGuild::class, function () use ($creator): void { + Guild::factory()->create(['user_id' => $creator->id]); + }); + + $this->actingAs($creator)->post(route('guild.store'), ['handle' => 'jobs', 'name' => 'Jobs', 'description' => 'Hiring.', 'emoji' => '💼']) + ->assertSessionHasErrors(['handle' => 'You can create up to 100 guilds.']); + expect(Guild::query()->where('handle', 'jobs')->exists())->toBeFalse() + ->and(Guild::query()->where('user_id', $creator->id)->count())->toBe(Guild::MAX_PER_USER); +}); + +it('refuses a handover saved with changes that wait for review, but hands over unchanged flagged text right away', function (): void { + $moderator = User::factory()->create(['handle' => 'admin']); + $member = User::factory()->create(); + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'handle' => 'jobs', 'name' => 'Jobs', 'description' => 'Hiring.', 'emoji' => '💻']); + $guild->members()->attach($moderator, ['joined_at' => now()]); + $guild->members()->attach($member, ['joined_at' => now()]); + $this->mock(ModerationProvider::class)->shouldReceive('moderate')->andReturn(['harassment' => 0.7]); + + $this->actingAs($moderator)->put(route('guild.update', 'jobs'), ['name' => 'Jobs', 'description' => 'Flagged words.', 'emoji' => '💼', 'remove_icon' => false, 'moderator_id' => $member->id]) + ->assertSessionHasErrors(['moderator_id' => UpdateGuildRequest::HANDOVER_NEEDS_REVIEW]); + + expect($guild->fresh())->user_id->toBe($moderator->id)->description->toBe('Hiring.')->emoji->toBe('💻'); + expect(GuildSubmission::query()->exists())->toBeFalse(); + + $this->put(route('guild.update', 'jobs'), ['name' => 'Jobs', 'description' => 'Hiring.', 'emoji' => '💻', 'remove_icon' => false, 'moderator_id' => $member->id]) + ->assertRedirectToRoute('guild.show', 'jobs') + ->assertSessionHasNoErrors(); + + expect($guild->fresh())->user_id->toBe($member->id)->description->toBe('Hiring.'); + expect(GuildSubmission::query()->exists())->toBeFalse(); +});