diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index a34915941..e5ad549a6 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -376,7 +376,7 @@ Sources: [Starred page](resources/js/pages/starred/index.tsx), [Starred controll ### Pinning a commit -Pin one of your own top-level commits to feature it at the top of your profile's Commits tab. Pinning another replaces the previous pin; unpin to return to the normal list. Replies cannot be pinned, and pinning does not override a commit's visibility or moderation state. +Pin one of your own top-level commits to feature it at the top of your profile's Commits tab. Pinning another replaces the previous pin; unpin to return to the normal list. Replies and guild board posts cannot be pinned, and pinning does not override a commit's visibility or moderation state. Sources: [pin authorization](app/Http/Requests/UpdateCommitPinRequest.php), [pin action](app/Actions/UpdateCommitPin.php), [profile page](resources/js/pages/user/show.tsx). @@ -662,9 +662,9 @@ Guilds are public groups around hashtags and are not generally available yet. In The Guilds page lists groups by member count. Joining adds matching commits to Following without following every author and clears any existing mute. When a commit appears only because of a joined guild, it says “because you joined” beside the guild label. Leave a guild to reveal its Mute control. Muting hides matching commits from logs and search, including commits by followed authors. You can still open the guild or a commit directly. -Each guild's bulletin board shows commits containing its exact hashtag, newest first, with pagination—not semantic search. Post directly from its composer; the hashtag is added automatically unless already present outside code and links, and is included in the preview. The automatic hashtag and its separator do not use any of your 4,000-character writing allowance, including when scheduling a board post. Hashtags you type yourself still count. Typing a hashtag offers matching guilds in the autocomplete menu; select one with the keyboard or pointer to insert its handle. +Each guild's bulletin board shows commits posted directly to it and regular commits containing its exact hashtag—not semantic search. Matching replies bring their thread onto the board, even when the root has no hashtag. Threads show reply previews and expand like a regular commit log, ordered by root date, newest first. Each page contains 30 distinct root commits; replies do not use up that limit, and Load more adds the next page. Posts from the board's composer stay attached to that guild without an automatic hashtag, including scheduled posts. They count toward the author's commit count but do not appear in their profile log or general feeds. They appear in Following when you join the guild, and in semantic search suggestions and results under a divider with the guild's name and icon. Regular hashtag commits keep appearing on profiles and in feeds as usual. Typing a hashtag offers matching guilds in the autocomplete menu; select one with the keyboard or pointer to insert its handle. -Guild descriptions can be reported privately. When a guild loses its moderator, its page, icon, description, memberships and mute preferences disappear; the original hashtag commits remain. A different person can claim the hashtag, but a removed moderator cannot reclaim it. +Guild descriptions can be reported privately. When a guild has no moderator, including after its moderator deletes their account, it is paused, not deleted. Its page, posts, icon, description, memberships and mute preferences stay connected. New board posts wait until it has a moderator; scheduled board posts stay pending and keep their guild. Ordinary hashtag commits still appear. A different person can claim the hashtag to resume the same guild, but a removed moderator cannot reclaim it. ### Exporting your data @@ -687,7 +687,7 @@ Sources: [export settings](resources/js/pages/user-profile/edit.tsx), [export co ### Deleting your account -Settings → Profile → **Delete account** opens a confirmation for permanent deletion of your /dev/null account; an app can also delete it through the signed API. It does not delete your GitHub account. Your top-level commits and every reply under those threads are erased. Your replies are also removed, except that replies from other people beneath them survive under authorless `[deleted]` placeholders. Your devices, the messages and reactions you sent, and all your uploaded images are erased too; other people's messages in your conversations stay with them. Account deletion is not covered by the 30-second commit undo. +Settings → Profile → **Delete account** opens a confirmation for permanent deletion of your /dev/null account; an app can also delete it through the signed API. It does not delete your GitHub account. Your top-level commits and every reply under those threads are erased. Your replies are also removed, except that replies from other people beneath them survive under authorless `[deleted]` placeholders. Your devices, the messages and reactions you sent, and your personal uploaded images are erased too; other people's messages in your conversations stay with them. A guild you moderated is paused and keeps its shared icon and description, memberships and other people's posts. Account deletion is not covered by the 30-second commit undo. You can sign in with GitHub again later, but start from a new account rather than restoring the deleted one. Export your data first if you want a copy. Deleting from /dev/null cannot retract copies of public content held elsewhere. diff --git a/app/Actions/CreateCommit.php b/app/Actions/CreateCommit.php index a08c3c009..8a6ae42a9 100644 --- a/app/Actions/CreateCommit.php +++ b/app/Actions/CreateCommit.php @@ -12,6 +12,7 @@ use App\Events\CommitsUpdated; use App\Events\ProfilesUpdated; use App\Events\UsersUpdated; +use App\Exceptions\GuildPaused; use App\Jobs\CheckUserLevel; use App\Jobs\EmbedCommit; use App\Jobs\LinkCommitTopics; @@ -20,6 +21,7 @@ use App\Jobs\ReplyAsTom; use App\Jobs\UnfurlLink; use App\Models\Commit; +use App\Models\Guild; use App\Models\LinkPreview; use App\Models\Organization; use App\Models\User; @@ -62,7 +64,7 @@ public function __construct( * @param array $imageDescriptions * @param array $replyRecipients */ - public function handle(User $user, string $body, ?Commit $parent = null, ?Commit $quotedCommit = null, array $images = [], array $imageDescriptions = [], bool|string $linkPreview = true, ?NewPoll $poll = null, array $replyRecipients = [], ?Organization $organization = null): Commit + public function handle(User $user, string $body, ?Commit $parent = null, ?Commit $quotedCommit = null, array $images = [], array $imageDescriptions = [], bool|string $linkPreview = true, ?NewPoll $poll = null, array $replyRecipients = [], ?Organization $organization = null, ?Guild $guild = null): Commit { $url = match ($linkPreview) { true => $this->urls->first($body), @@ -70,7 +72,11 @@ public function handle(User $user, string $body, ?Commit $parent = null, ?Commit default => $linkPreview, }; - return DB::transaction(function () use ($user, $body, $parent, $quotedCommit, $images, $imageDescriptions, $url, $poll, $replyRecipients, $organization): Commit { + return DB::transaction(function () use ($user, $body, $parent, $quotedCommit, $images, $imageDescriptions, $url, $poll, $replyRecipients, $organization, $guild): Commit { + if ($guild instanceof Guild && Guild::query()->whereKey($guild->id)->sharedLock()->firstOrFail()->user_id === null) { + throw new GuildPaused; + } + $linkPreview = $this->linkPreviewFor($url); $createdAt = now(); $hasGoodReputation = $user->hasGoodReputation(); @@ -79,6 +85,7 @@ public function handle(User $user, string $body, ?Commit $parent = null, ?Commit $commit = Commit::query()->create([ 'user_id' => $user->id, 'author_id' => $organization->id ?? $user->id, + 'guild_id' => $guild?->id, 'body' => $this->emojiShortcodes->replace($body), 'mentions' => [...$replyRecipients, ...$mentions], 'parent_id' => $parent?->id, diff --git a/app/Actions/CreateExport.php b/app/Actions/CreateExport.php index 9fc47fc58..1a3a5ea0b 100644 --- a/app/Actions/CreateExport.php +++ b/app/Actions/CreateExport.php @@ -222,8 +222,8 @@ private function commits(User $user): Generator { $commits = $user->commits() ->withTrashed() - ->select(['id', 'parent_id', 'quoted_commit_id', 'body', 'status', 'pasteis_count', 'created_at', 'updated_at', 'deleted_at']) - ->with('images:id,commit_id') + ->select(['id', 'parent_id', 'quoted_commit_id', 'guild_id', 'body', 'status', 'pasteis_count', 'created_at', 'updated_at', 'deleted_at']) + ->with(['images:id,commit_id', 'guild']) ->lazyById(500); $translations = resolve(CommitTranslations::class); @@ -236,6 +236,7 @@ private function commits(User $user): Generator 'id' => $commit->id, 'parent_id' => $commit->parent_id, 'quoted_commit_id' => $commit->quoted_commit_id, + 'guild_handle' => $commit->guild?->handle, 'body' => $commit->body, 'cached_translations' => $cached[$translations->key($commit)], 'status' => $commit->status->value, diff --git a/app/Actions/CreateGuild.php b/app/Actions/CreateGuild.php index 3b501421b..782d1837d 100644 --- a/app/Actions/CreateGuild.php +++ b/app/Actions/CreateGuild.php @@ -39,6 +39,13 @@ public function handle(User $user, string $handle, string $name, string $descrip } $this->membership->handle($user, $guild, true); + } else { + $guild = Guild::query()->whereKey($guild->id)->lockForUpdate()->firstOrFail(); + + if ($guild->user_id === null) { + $guild->update(['user_id' => $user->id]); + $this->membership->handle($user, $guild, true); + } } return $guild; diff --git a/app/Actions/CreateScheduledCommit.php b/app/Actions/CreateScheduledCommit.php index e8a3009ad..ad17fae20 100644 --- a/app/Actions/CreateScheduledCommit.php +++ b/app/Actions/CreateScheduledCommit.php @@ -7,6 +7,8 @@ use App\Dto\NewPoll; use App\Enums\UserUpdate; use App\Events\UsersUpdated; +use App\Exceptions\GuildPaused; +use App\Models\Guild; use App\Models\Organization; use App\Models\ScheduledCommit; use App\Models\User; @@ -29,14 +31,19 @@ public function __construct(private CreateImageFiles $createImageFiles, private * @param list $images * @param array $imageDescriptions */ - public function handle(User $user, string $body, CarbonImmutable $scheduledAt, array $images = [], array $imageDescriptions = [], ?NewPoll $poll = null, bool|string $linkPreview = true, ?Organization $organization = null): ScheduledCommit + public function handle(User $user, string $body, CarbonImmutable $scheduledAt, array $images = [], array $imageDescriptions = [], ?NewPoll $poll = null, bool|string $linkPreview = true, ?Organization $organization = null, ?Guild $guild = null): ScheduledCommit { $body = mb_trim($body); - return DB::transaction(function () use ($user, $organization, $body, $poll, $images, $imageDescriptions, $linkPreview, $scheduledAt): ScheduledCommit { + return DB::transaction(function () use ($user, $organization, $body, $poll, $images, $imageDescriptions, $linkPreview, $scheduledAt, $guild): ScheduledCommit { + if ($guild instanceof Guild && Guild::query()->whereKey($guild->id)->sharedLock()->firstOrFail()->user_id === null) { + throw new GuildPaused; + } + $scheduled = ScheduledCommit::query()->create([ 'user_id' => $user->id, 'author_id' => $organization?->id, + 'guild_id' => $guild?->id, 'body' => $body, 'poll' => $poll instanceof NewPoll ? ['options' => $poll->options, 'duration' => $poll->duration->value] : null, 'images' => $images === [] ? null : $this->createImageFiles->handle($images, $imageDescriptions), diff --git a/app/Actions/CreateUserFeed.php b/app/Actions/CreateUserFeed.php index 145731b7a..1527a1d7d 100644 --- a/app/Actions/CreateUserFeed.php +++ b/app/Actions/CreateUserFeed.php @@ -19,6 +19,7 @@ public function handle(User $user): string { $commits = $user->commits() + ->whereNull('guild_id') ->approved() ->topLevel() ->with('images') diff --git a/app/Actions/DeleteGuild.php b/app/Actions/DeleteGuildModerator.php similarity index 63% rename from app/Actions/DeleteGuild.php rename to app/Actions/DeleteGuildModerator.php index 436bb9607..e3154d318 100644 --- a/app/Actions/DeleteGuild.php +++ b/app/Actions/DeleteGuildModerator.php @@ -11,9 +11,9 @@ use App\Queries\AdminsQuery; use Illuminate\Support\Facades\DB; -final readonly class DeleteGuild +final readonly class DeleteGuildModerator { - public function __construct(private DeleteStoredFiles $files, private AdminsQuery $admins) + public function __construct(private AdminsQuery $admins) { // } @@ -21,14 +21,17 @@ public function __construct(private DeleteStoredFiles $files, private AdminsQuer public function handle(Guild $guild): void { DB::transaction(function () use ($guild): void { - $moderator = User::query()->whereKey($guild->user_id)->lockForUpdate()->firstOrFail(); + $moderator = User::query()->whereKey($guild->user_id)->lockForUpdate()->first(); $guild = Guild::query()->whereKey($guild->id)->lockForUpdate()->firstOrFail(); - DB::table('guild_moderator_removals')->insertOrIgnore([ - 'github_id' => $moderator->github_id, 'handle' => $guild->handle, 'created_at' => now(), - ]); - $this->files->retain($guild->icon_path === null ? [] : [$guild->icon_path]); + + if ($moderator instanceof User && $guild->user_id === $moderator->id) { + DB::table('guild_moderator_removals')->insertOrIgnore([ + 'github_id' => $moderator->github_id, 'handle' => $guild->handle, 'created_at' => now(), + ]); + $guild->update(['user_id' => null]); + } + $viewers = DB::table('guild_preferences')->where('guild_id', $guild->id)->pluck('user_id'); - $guild->delete(); event(new UsersUpdated($viewers, UserUpdate::Guilds)); event(new UsersUpdated($this->admins->ids(), UserUpdate::Moderation)); event(new UsersUpdated($viewers, UserUpdate::Relationships)); diff --git a/app/Actions/DeleteUser.php b/app/Actions/DeleteUser.php index 2ee71e764..440267d5e 100644 --- a/app/Actions/DeleteUser.php +++ b/app/Actions/DeleteUser.php @@ -75,8 +75,7 @@ public function handle(User $user): void // Report creation holds shared reporter and commit locks until its attachment paths are saved. $guilds = Guild::query()->where('user_id', $user->id)->orderBy('id')->lockForUpdate()->get(); $guildMembers = DB::table('guild_preferences')->whereIn('guild_id', $guilds->modelKeys())->whereNot('user_id', $user->id)->pluck('user_id'); - $guildIcons = $guilds->flatMap(fn (Guild $guild): array => $guild->icon_path === null ? [] : [$guild->icon_path])->all(); - $imagePaths = [...$guildIcons, ...$this->reportImagePaths($user), ...$this->imagePaths($user), ...$this->scheduledImagePaths($user), ...$this->messageImagePaths($user), ...$this->messageVoicePaths($user)]; + $imagePaths = [...$this->reportImagePaths($user), ...$this->imagePaths($user), ...$this->scheduledImagePaths($user), ...$this->messageImagePaths($user), ...$this->messageVoicePaths($user)]; resolve(DeleteStoredFiles::class)->retain($imagePaths); DB::table('commit_topics')->whereIn('commit_id', $this->touchedCommits($user)->select('id'))->delete(); diff --git a/app/Actions/UpdateGuild.php b/app/Actions/UpdateGuild.php index 43d290d67..3ecad564f 100644 --- a/app/Actions/UpdateGuild.php +++ b/app/Actions/UpdateGuild.php @@ -6,7 +6,9 @@ use App\Enums\UserUpdate; use App\Events\UsersUpdated; +use App\Exceptions\GuildModeratorRemoved; use App\Models\Guild; +use App\Models\User; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\DB; @@ -17,10 +19,15 @@ public function __construct(private CreateImageFiles $images, private DeleteStor // } - public function handle(Guild $guild, string $description, string $emoji, ?UploadedFile $icon, bool $removeIcon): void + public function handle(Guild $guild, User $user, string $description, string $emoji, ?UploadedFile $icon, bool $removeIcon): void { - DB::transaction(function () use ($guild, $description, $emoji, $icon, $removeIcon): void { + DB::transaction(function () use ($guild, $user, $description, $emoji, $icon, $removeIcon): void { $guild = Guild::query()->whereKey($guild->id)->lockForUpdate()->firstOrFail(); + + if ($guild->user_id !== $user->id) { + throw new GuildModeratorRemoved; + } + $path = $guild->icon_path; if ($icon instanceof UploadedFile || $removeIcon) { diff --git a/app/Actions/UpdateScheduledCommitSubmittedAt.php b/app/Actions/UpdateScheduledCommitSubmittedAt.php index ca5935083..a61da9155 100644 --- a/app/Actions/UpdateScheduledCommitSubmittedAt.php +++ b/app/Actions/UpdateScheduledCommitSubmittedAt.php @@ -8,6 +8,7 @@ use App\Enums\PollDuration; use App\Enums\UserUpdate; use App\Events\UsersUpdated; +use App\Exceptions\GuildPaused; use App\Models\ScheduledCommit; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Query\Builder as QueryBuilder; @@ -26,45 +27,49 @@ public function __construct(private CreateCommit $createCommit, private DeleteSc */ public function handle(string $id, bool $early = false): bool { - return DB::transaction(function () use ($id, $early): bool { - $postable = fn (Builder $query): Builder => $query->whereNull('author_id') - ->orWhereExists(fn (QueryBuilder $members): QueryBuilder => $members - ->from('organization_members') - ->whereColumn('organization_members.organization_id', 'scheduled_commits.author_id') - ->whereColumn('organization_members.user_id', 'scheduled_commits.user_id')); + try { + return DB::transaction(function () use ($id, $early): bool { + $postable = fn (Builder $query): Builder => $query->whereNull('author_id') + ->orWhereExists(fn (QueryBuilder $members): QueryBuilder => $members + ->from('organization_members') + ->whereColumn('organization_members.organization_id', 'scheduled_commits.author_id') + ->whereColumn('organization_members.user_id', 'scheduled_commits.user_id')); - // Claim with a conditional write before reading. - // Creation and the claim roll back together if either operation fails. - // Moderation is checked in the claim too, since a timeout or ban can land after the batch was selected... - $claimed = ScheduledCommit::query()->whereKey($id) - ->whereNull('submitted_at')->whereNull('canceled_at') - ->unless($early, fn (Builder $query): Builder => $query->where('scheduled_at', '<=', now())) - ->whereDoesntHave('user.timeouts', fn (Builder $query): Builder => $query->where('ends_at', '>', now())) - ->whereDoesntHave('user.ban') - ->where($postable) - ->update(['submitted_at' => now()]); + // Claim with a conditional write before reading. + // Creation and the claim roll back together if either operation fails. + // Moderation is checked in the claim too, since a timeout or ban can land after the batch was selected... + $claimed = ScheduledCommit::query()->whereKey($id) + ->whereNull('submitted_at')->whereNull('canceled_at') + ->unless($early, fn (Builder $query): Builder => $query->where('scheduled_at', '<=', now())) + ->whereDoesntHave('user.timeouts', fn (Builder $query): Builder => $query->where('ends_at', '>', now())) + ->whereDoesntHave('user.ban') + ->where($postable) + ->update(['submitted_at' => now()]); - if ($claimed === 0) { - $lost = ScheduledCommit::query()->with('user')->whereKey($id)->whereNot($postable)->first(); + if ($claimed === 0) { + $lost = ScheduledCommit::query()->with('user')->whereKey($id)->whereNot($postable)->first(); - if ($lost instanceof ScheduledCommit) { - $this->deleteScheduledCommit->handle($lost->user, $lost); - } + if ($lost instanceof ScheduledCommit) { + $this->deleteScheduledCommit->handle($lost->user, $lost); + } - return false; - } + return false; + } - $scheduled = ScheduledCommit::query()->with(['user', 'author'])->findOrFail($id); - assert(is_string($scheduled->body)); - $poll = $scheduled->poll === null ? null : new NewPoll($scheduled->poll['options'], PollDuration::from($scheduled->poll['duration'])); - $commit = $this->createCommit->handle($scheduled->user, $scheduled->body, linkPreview: $scheduled->link_preview_url ?? false, poll: $poll, organization: $scheduled->author?->organization); - $commit->images()->createMany($scheduled->images ?? []); + $scheduled = ScheduledCommit::query()->with(['user', 'author', 'guild'])->findOrFail($id); + assert(is_string($scheduled->body)); + $poll = $scheduled->poll === null ? null : new NewPoll($scheduled->poll['options'], PollDuration::from($scheduled->poll['duration'])); + $commit = $this->createCommit->handle($scheduled->user, $scheduled->body, linkPreview: $scheduled->link_preview_url ?? false, poll: $poll, organization: $scheduled->author?->organization, guild: $scheduled->guild); + $commit->images()->createMany($scheduled->images ?? []); - $scheduled->forceFill(['commit_id' => $commit->id, 'body' => null, 'poll' => null, 'images' => null, 'link_preview_url' => null])->save(); + $scheduled->forceFill(['commit_id' => $commit->id, 'body' => null, 'poll' => null, 'images' => null, 'link_preview_url' => null])->save(); - event(new UsersUpdated([$scheduled->user_id], UserUpdate::ScheduledCommits)); + event(new UsersUpdated([$scheduled->user_id], UserUpdate::ScheduledCommits)); - return true; - }, attempts: 5); + return true; + }, attempts: 5); + } catch (GuildPaused) { + return false; + } } } diff --git a/app/Console/Commands/SubmitScheduledCommitsCommand.php b/app/Console/Commands/SubmitScheduledCommitsCommand.php index b68d63be1..466e12eb8 100644 --- a/app/Console/Commands/SubmitScheduledCommitsCommand.php +++ b/app/Console/Commands/SubmitScheduledCommitsCommand.php @@ -23,6 +23,8 @@ public function handle(UpdateScheduledCommitSubmittedAt $action): int $scheduledCommits = ScheduledCommit::query()->whereNull('submitted_at')->whereNull('canceled_at') ->whereDoesntHave('user.timeouts', fn (Builder $query): Builder => $query->where('ends_at', '>', now())) ->whereDoesntHave('user.ban') + ->where(fn (Builder $query): Builder => $query->whereNull('guild_id') + ->orWhereHas('guild', fn (Builder $guilds): Builder => $guilds->whereNotNull('user_id'))) ->where('scheduled_at', '<=', now())->oldest('scheduled_at')->orderBy('id')->limit(100)->get(['id']); foreach ($scheduledCommits as $scheduled) { diff --git a/app/Exceptions/GuildPaused.php b/app/Exceptions/GuildPaused.php new file mode 100644 index 000000000..faca6c3ce --- /dev/null +++ b/app/Exceptions/GuildPaused.php @@ -0,0 +1,9 @@ +where('author_id', $organization->id) + ->whereNull('guild_id') ->approved() ->topLevel() ->withPublicPreview() diff --git a/app/Http/Controllers/Api/UserCommitController.php b/app/Http/Controllers/Api/UserCommitController.php index fcbdd549b..f521c5226 100644 --- a/app/Http/Controllers/Api/UserCommitController.php +++ b/app/Http/Controllers/Api/UserCommitController.php @@ -31,6 +31,7 @@ public function index(ListApiUserCommitsRequest $request, #[CurrentUser] ?User $ } return CommitResource::collection($user->commits() + ->whereNull('guild_id') ->approved() ->when( $request->replies(), diff --git a/app/Http/Controllers/CommitController.php b/app/Http/Controllers/CommitController.php index 02fc2bf2f..c86037c6f 100644 --- a/app/Http/Controllers/CommitController.php +++ b/app/Http/Controllers/CommitController.php @@ -8,6 +8,7 @@ use App\Actions\DeleteCommit; use App\Dto\ThreadContinuation; use App\Enums\CommitStatus; +use App\Exceptions\GuildPaused; use App\Http\Requests\CreateCommitRequest; use App\Http\Requests\DeleteCommitRequest; use App\Http\Requests\ShowCommitRequest; @@ -68,13 +69,18 @@ public function store(CreateCommitRequest $request, #[CurrentUser] User $user, C $before = $achievements->unlockedBadgeNames($user); $organization = $request->organization(); - $commit = $action->handle($user, $request->string('body')->value(), quotedCommit: $request->quotedCommit(), images: $request->images(), imageDescriptions: $request->imageDescriptions(), linkPreview: $request->linkPreview(), poll: $request->poll(), organization: $organization); + try { + $commit = $action->handle($user, $request->string('body')->value(), quotedCommit: $request->quotedCommit(), images: $request->images(), imageDescriptions: $request->imageDescriptions(), linkPreview: $request->linkPreview(), poll: $request->poll(), organization: $organization, guild: $request->guild()); + } catch (GuildPaused) { + return back()->withErrors(['guild_handle' => 'This guild is paused until it has a moderator.']); + } $unlocked = $achievements->unlockedBadgeNames($user)->diff($before)->values(); Inertia::flash('committed', [ 'id' => $commit->id, 'body' => $commit->body, + 'guild_handle' => $commit->guild?->handle, 'author' => ['handle' => ($organization ?? $user)->handle], ]); diff --git a/app/Http/Controllers/GuildController.php b/app/Http/Controllers/GuildController.php index eb2a24346..93fd6eaab 100644 --- a/app/Http/Controllers/GuildController.php +++ b/app/Http/Controllers/GuildController.php @@ -5,11 +5,9 @@ namespace App\Http\Controllers; use App\Actions\CreateGuild; -use App\Actions\DeleteGuild; use App\Actions\UpdateGuild; use App\Exceptions\GuildModeratorRemoved; use App\Http\Requests\CreateGuildRequest; -use App\Http\Requests\DeleteGuildRequest; use App\Http\Requests\ListGuildsRequest; use App\Http\Requests\ShowGuildRequest; use App\Http\Requests\UpdateGuildRequest; @@ -51,25 +49,25 @@ public function show(ShowGuildRequest $request, Guild $guild, #[CurrentUser] Use return Inertia::render('guild/show', [ 'handle' => $guild->handle, 'canModerate' => $guild->user_id === $user->id, - 'commits' => ShownStreams::commits($commits), + 'commits' => $commits->currentPage() > 1 + ? Inertia::merge(ShownStreams::commits($commits))->matchOn('id') + : ShownStreams::commits($commits), 'page' => $commits->currentPage(), 'hasMore' => $commits->hasMorePages(), ])->withViewData(['robots' => 'noindex, follow']); } - public function update(UpdateGuildRequest $request, Guild $guild, UpdateGuild $action): RedirectResponse + public function update(UpdateGuildRequest $request, Guild $guild, #[CurrentUser] User $user, UpdateGuild $action): RedirectResponse { $icon = $request->file('images.0'); assert($icon instanceof UploadedFile || $icon === null); - $action->handle($guild, $request->string('description')->value(), $request->string('emoji')->value(), $icon, $request->boolean('remove_icon')); - return to_route('guild.show', $guild->handle); - } - - public function destroy(DeleteGuildRequest $request, Guild $guild, DeleteGuild $action): RedirectResponse - { - $action->handle($guild); + try { + $action->handle($guild, $user, $request->string('description')->value(), $request->string('emoji')->value(), $icon, $request->boolean('remove_icon')); + } catch (GuildModeratorRemoved) { + return back()->withErrors(['description' => 'You no longer moderate this guild.']); + } - return to_route('search.index', ['q' => '#'.$guild->handle]); + return to_route('guild.show', $guild->handle); } } diff --git a/app/Http/Controllers/GuildModeratorController.php b/app/Http/Controllers/GuildModeratorController.php new file mode 100644 index 000000000..92b56a771 --- /dev/null +++ b/app/Http/Controllers/GuildModeratorController.php @@ -0,0 +1,20 @@ +handle($guild); + + return to_route('guild.show', $guild->handle); + } +} diff --git a/app/Http/Controllers/ScheduledCommitController.php b/app/Http/Controllers/ScheduledCommitController.php index 12cf0ac1f..a9c7ae55d 100644 --- a/app/Http/Controllers/ScheduledCommitController.php +++ b/app/Http/Controllers/ScheduledCommitController.php @@ -7,6 +7,7 @@ use App\Actions\CreateScheduledCommit; use App\Actions\DeleteScheduledCommit; use App\Enums\UserUpdate; +use App\Exceptions\GuildPaused; use App\Http\Requests\CreateScheduledCommitRequest; use App\Http\Requests\DeleteScheduledCommitRequest; use App\Http\Resources\ScheduledCommitResource; @@ -34,7 +35,11 @@ public function index(Request $request, #[CurrentUser] User $user, ScheduledComm public function store(CreateScheduledCommitRequest $request, #[CurrentUser] User $user, CreateScheduledCommit $action): RedirectResponse { - $action->handle($user, $request->string('body')->value(), CarbonImmutable::parse($request->string('scheduled_at')->value())->utc(), $request->images(), $request->imageDescriptions(), $request->poll(), $request->linkPreview(), $request->organization()); + try { + $action->handle($user, $request->string('body')->value(), CarbonImmutable::parse($request->string('scheduled_at')->value())->utc(), $request->images(), $request->imageDescriptions(), $request->poll(), $request->linkPreview(), $request->organization(), guild: $request->guild()); + } catch (GuildPaused) { + return back()->withErrors(['guild_handle' => 'This guild is paused until it has a moderator.']); + } Inertia::flash('scheduled', true); Inertia::flash('toast', ['type' => 'success', 'message' => 'Commit scheduled. Only you can see it until it is submitted.']); diff --git a/app/Http/Middleware/HandleInertiaRequests.php b/app/Http/Middleware/HandleInertiaRequests.php index a283eaf0b..64cac1a2a 100644 --- a/app/Http/Middleware/HandleInertiaRequests.php +++ b/app/Http/Middleware/HandleInertiaRequests.php @@ -174,6 +174,7 @@ public function share(Request $request): array 'member_count' => $guild->members_count, 'is_joined' => $guild->is_joined, 'is_muted' => $guild->is_muted, + 'is_paused' => $guild->user_id === null, 'icon_url' => $guild->icon_path === null ? null : route('guild-icon.show', ['guild' => $guild->handle, 'v' => $guild->updated_at->getTimestampMs()]), ])->all() : null)->until(60)->fresh($request->routeIs('guild.*', 'search.index'))->live(UserUpdate::Guilds->value, new PrivateChannel($user)) : null, diff --git a/app/Http/Requests/CreateCommitPreviewRequest.php b/app/Http/Requests/CreateCommitPreviewRequest.php index a0d79b252..65db1a431 100644 --- a/app/Http/Requests/CreateCommitPreviewRequest.php +++ b/app/Http/Requests/CreateCommitPreviewRequest.php @@ -30,9 +30,4 @@ public function rules(): array ...CreateCommitRequest::guildRules($this), ]; } - - public function passedValidation(): void - { - CreateCommitRequest::appendGuildHashtag($this); - } } diff --git a/app/Http/Requests/CreateCommitRequest.php b/app/Http/Requests/CreateCommitRequest.php index 12537ce00..ca9cfe980 100644 --- a/app/Http/Requests/CreateCommitRequest.php +++ b/app/Http/Requests/CreateCommitRequest.php @@ -9,6 +9,7 @@ use App\Enums\Feature; use App\Enums\PollDuration; use App\Models\Commit; +use App\Models\Guild; use App\Models\Organization; use App\Models\User; use App\Rules\CommitBodyLength; @@ -16,7 +17,6 @@ use App\Rules\VisibleCommit; use App\Services\CommitBodies; use App\Services\Features; -use App\Services\Hashtags; use App\Services\Urls; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Foundation\Http\FormRequest; @@ -54,25 +54,11 @@ public static function guildRules(FormRequest $request): array { return [ 'guild_handle' => ['sometimes', 'required', 'string', 'max:60', resolve(Features::class)->available(Feature::Guilds, $request->user()) - ? 'exists:guilds,handle' + ? 'exists:guilds,handle,user_id,NOT_NULL' : Rule::in([])], ]; } - public static function appendGuildHashtag(FormRequest $request): void - { - if (! $request->filled('guild_handle')) { - return; - } - - $handle = $request->string('guild_handle')->value(); - $body = $request->string('body')->value(); - - if (! in_array($handle, resolve(Hashtags::class)->handles($body), true)) { - $request->merge(['body' => mb_rtrim($body)."\n\n#".$handle]); - } - } - /** * Images are checked by their contents, not their extension, and SVG is never accepted since it can carry scripts. * @@ -216,8 +202,8 @@ public function organization(): ?Organization return OrganizationToPostAs::of($user, $this->input('author')); } - public function passedValidation(): void + public function guild(): ?Guild { - self::appendGuildHashtag($this); + return Guild::query()->where('handle', $this->string('guild_handle')->value())->first(); } } diff --git a/app/Http/Requests/CreateGuildRequest.php b/app/Http/Requests/CreateGuildRequest.php index d6abf422f..8d967d7e2 100644 --- a/app/Http/Requests/CreateGuildRequest.php +++ b/app/Http/Requests/CreateGuildRequest.php @@ -16,6 +16,7 @@ use Illuminate\Support\Facades\DB; use Illuminate\Validation\Rule; use Illuminate\Validation\Rules\In; +use Illuminate\Validation\Rules\Unique; use Illuminate\Validation\Validator; final class CreateGuildRequest extends FormRequest @@ -27,11 +28,11 @@ public function authorize(Features $features): Response return $features->available(Feature::Guilds, $this->user()) ? Response::allow() : Response::denyAsNotFound(); } - /** @return array> */ + /** @return array> */ public function rules(EmojiShortcodes $emoji): array { return [ - 'handle' => ['required', 'string', 'max:60', 'regex:/^\p{L}[\p{L}\p{M}\p{N}_]*$/uD', 'unique:guilds,handle'], + 'handle' => ['required', 'string', 'max:60', 'regex:/^\p{L}[\p{L}\p{M}\p{N}_]*$/uD', Rule::unique('guilds', 'handle')->whereNotNull('user_id')], 'name' => ['required', 'string', 'max:60'], 'description' => ['required', 'string', 'max:500'], 'emoji' => ['required', 'string', Rule::in($emoji->emoji())], diff --git a/app/Http/Requests/CreateScheduledCommitRequest.php b/app/Http/Requests/CreateScheduledCommitRequest.php index f40361036..d2ad82f60 100644 --- a/app/Http/Requests/CreateScheduledCommitRequest.php +++ b/app/Http/Requests/CreateScheduledCommitRequest.php @@ -6,6 +6,7 @@ use App\Dto\NewPoll; use App\Enums\PollDuration; +use App\Models\Guild; use App\Models\Organization; use App\Models\User; use App\Rules\OrganizationToPostAs; @@ -126,8 +127,8 @@ public function prepareForValidation(): void CreateCommitRequest::normalizeBody($this); } - public function passedValidation(): void + public function guild(): ?Guild { - CreateCommitRequest::appendGuildHashtag($this); + return Guild::query()->where('handle', $this->string('guild_handle')->value())->first(); } } diff --git a/app/Http/Requests/DeleteGuildRequest.php b/app/Http/Requests/DeleteGuildModeratorRequest.php similarity index 89% rename from app/Http/Requests/DeleteGuildRequest.php rename to app/Http/Requests/DeleteGuildModeratorRequest.php index d0b8d7e35..b2951d0ed 100644 --- a/app/Http/Requests/DeleteGuildRequest.php +++ b/app/Http/Requests/DeleteGuildModeratorRequest.php @@ -9,7 +9,7 @@ use Illuminate\Auth\Access\Response; use Illuminate\Foundation\Http\FormRequest; -final class DeleteGuildRequest extends FormRequest +final class DeleteGuildModeratorRequest extends FormRequest { public function authorize(Features $features): Response { diff --git a/app/Http/Requests/UpdateApiCommitPinRequest.php b/app/Http/Requests/UpdateApiCommitPinRequest.php index 855cb9e31..b69940f4d 100644 --- a/app/Http/Requests/UpdateApiCommitPinRequest.php +++ b/app/Http/Requests/UpdateApiCommitPinRequest.php @@ -23,7 +23,7 @@ public function authorize(): Response assert($commit instanceof Commit); return match (true) { - $commit->author_id === $user->id && $commit->parent_id === null => Response::allow(), + $commit->author_id === $user->id && $commit->parent_id === null && $commit->guild_id === null => Response::allow(), $commit->isVisibleTo($user) => Response::deny(), default => Response::denyAsNotFound(), }; diff --git a/app/Http/Requests/UpdateCommitPinRequest.php b/app/Http/Requests/UpdateCommitPinRequest.php index d1653657d..ac347c45b 100644 --- a/app/Http/Requests/UpdateCommitPinRequest.php +++ b/app/Http/Requests/UpdateCommitPinRequest.php @@ -18,7 +18,7 @@ public function authorize(): bool $commit = $this->route('commit'); assert($commit instanceof Commit); - return $commit->author_id === $user->id && $commit->parent_id === null; + return $commit->author_id === $user->id && $commit->parent_id === null && $commit->guild_id === null; } /** diff --git a/app/Http/Resources/CommitResource.php b/app/Http/Resources/CommitResource.php index 31dc2a058..b5571c26e 100644 --- a/app/Http/Resources/CommitResource.php +++ b/app/Http/Resources/CommitResource.php @@ -7,6 +7,7 @@ use App\Enums\CommitStatus; use App\Models\Commit; use App\Models\CommitImage; +use App\Models\Guild; use App\Models\Poll; use App\Models\User; use App\Services\CommitBodies; @@ -56,6 +57,7 @@ public function toArray(Request $request): array 'id' => $this->id, 'short_hash' => mb_substr(str_replace('-', '', $this->id), -7), 'body' => $this->body, + 'guild_handle' => $this->whenLoaded('guild', fn (Guild $guild): string => $guild->handle), 'parent_id' => $isSigned ? $this->parent_id : $this->parent?->id, 'html_url' => route('commit.show', [$this->author, $this->resource]), 'created_at' => $this->created_at->toIso8601ZuluString(), diff --git a/app/Http/Resources/ShownStreams.php b/app/Http/Resources/ShownStreams.php index 48ca21b57..9904abeb0 100644 --- a/app/Http/Resources/ShownStreams.php +++ b/app/Http/Resources/ShownStreams.php @@ -67,6 +67,8 @@ public static function commit(?Commit $commit): ?array return $shown; } + $shown['guild_handle'] = $commit->relationLoaded('guild') ? $commit->guild?->handle : null; + if (is_array($shown['author'] ?? null) && $commit->relationLoaded('author') && $commit->author instanceof Profile) { $shown['author'] = self::authored($shown['author'], $commit->author); } diff --git a/app/Models/Commit.php b/app/Models/Commit.php index 805af50de..93adc3ffd 100644 --- a/app/Models/Commit.php +++ b/app/Models/Commit.php @@ -27,6 +27,8 @@ * @property-read string $id * @property-read string|null $user_id * @property-read string|null $author_id + * @property-read string|null $guild_id + * @property-read Guild|null $guild * @property-read string|null $parent_id * @property-read string|null $root_id * @property-read float $hot_score @@ -65,6 +67,8 @@ 'user', 'user_id', 'author_id', + 'guild_id', + 'guild', 'ai_decision', 'ai_categories', 'embedding', @@ -110,6 +114,12 @@ final class Commit extends Model */ private ?array $segments = null; + /** @return BelongsTo */ + public function guild(): BelongsTo + { + return $this->belongsTo(Guild::class); + } + /** * @return array */ diff --git a/app/Models/Guild.php b/app/Models/Guild.php index f56a77b31..b39d44ed9 100644 --- a/app/Models/Guild.php +++ b/app/Models/Guild.php @@ -11,10 +11,11 @@ use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; +use Illuminate\Database\Eloquent\Relations\HasMany; /** * @property-read string $id - * @property-read string $user_id + * @property-read string|null $user_id * @property-read string $handle * @property-read string $name * @property-read string $description @@ -34,6 +35,12 @@ final class Guild extends Model use HasUuids; + /** @return HasMany */ + public function commits(): HasMany + { + return $this->hasMany(Commit::class); + } + /** @return BelongsToMany */ public function members(): BelongsToMany { diff --git a/app/Models/ScheduledCommit.php b/app/Models/ScheduledCommit.php index 5bd7170ce..bcd34cfc8 100644 --- a/app/Models/ScheduledCommit.php +++ b/app/Models/ScheduledCommit.php @@ -7,6 +7,7 @@ use Carbon\CarbonInterface; use Database\Factories\ScheduledCommitFactory; use Illuminate\Database\Eloquent\Attributes\Fillable; +use Illuminate\Database\Eloquent\Attributes\Hidden; use Illuminate\Database\Eloquent\Concerns\HasUuids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; @@ -16,6 +17,8 @@ * @property-read string $id * @property-read string $user_id * @property-read string|null $author_id + * @property-read string|null $guild_id + * @property-read Guild|null $guild * @property-read string|null $commit_id * @property-read string|null $body * @property-read array{options: list, duration: int}|null $poll @@ -28,7 +31,8 @@ * @property-read Profile|null $author * @property-read Commit|null $commit */ -#[Fillable(['user_id', 'author_id', 'body', 'poll', 'images', 'link_preview_url', 'scheduled_at'])] +#[Fillable(['user_id', 'author_id', 'guild_id', 'body', 'poll', 'images', 'link_preview_url', 'scheduled_at'])] +#[Hidden(['guild_id', 'guild'])] final class ScheduledCommit extends Model { /** @use HasFactory */ @@ -36,6 +40,12 @@ final class ScheduledCommit extends Model use HasUuids; + /** @return BelongsTo */ + public function guild(): BelongsTo + { + return $this->belongsTo(Guild::class); + } + /** @return array */ public function casts(): array { diff --git a/app/Queries/CommitBuilder.php b/app/Queries/CommitBuilder.php index db4715bb9..7e65e3d4b 100644 --- a/app/Queries/CommitBuilder.php +++ b/app/Queries/CommitBuilder.php @@ -31,7 +31,7 @@ final class CommitBuilder extends Builder private const array COLUMNS_BUT_EMBEDDING = [ 'id', 'user_id', 'body', 'created_at', 'updated_at', 'status', 'parent_id', 'deleted_at', 'link_preview_id', 'quoted_commit_id', 'mentions', 'ai_decision', 'ai_categories', 'root_id', 'hot_score', 'pasteis_count', 'author_id', - 'headlines_classified_at', + 'headlines_classified_at', 'guild_id', ]; /** @@ -219,7 +219,7 @@ public function withQuotedCommitFor(?User $viewer): self 'quotedCommit' => fn (BelongsTo $query): BelongsTo => $query ->withTrashed() ->where(fn (self $query): self => $query->visibleTo($viewer)) - ->with(['author', 'linkPreview', 'images']) + ->with(['author', 'linkPreview', 'images', 'guild']) ->withPollFor($viewer), ]); } @@ -249,7 +249,7 @@ public function withPublicPreview(): self return $this ->withVisibleReplyCount(null) ->withCount('stars') - ->with(['author', 'linkPreview', 'images', 'parent' => fn (BelongsTo $query): BelongsTo => $query->where('status', CommitStatus::Approved)]); + ->with(['author', 'linkPreview', 'images', 'guild', 'parent' => fn (BelongsTo $query): BelongsTo => $query->where('status', CommitStatus::Approved)]); } public function pending(): self @@ -317,7 +317,7 @@ public function withPollFor(?User $viewer): self public function withCardDataFor(?User $viewer): self { return $this - ->with(['author', 'linkPreview', 'images']) + ->with(['author', 'linkPreview', 'images', 'guild']) ->withQuotedCommitFor($viewer) ->withStarsFor($viewer) ->withPollFor($viewer) diff --git a/app/Queries/GuildCommitsQuery.php b/app/Queries/GuildCommitsQuery.php index c84a66ea3..59479e6dc 100644 --- a/app/Queries/GuildCommitsQuery.php +++ b/app/Queries/GuildCommitsQuery.php @@ -12,6 +12,7 @@ use App\Services\Hashtags; use Closure; use Illuminate\Database\Query\Builder; +use Illuminate\Database\Query\JoinClause; use Illuminate\Pagination\Paginator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Fluent; @@ -78,25 +79,31 @@ public function joinedFor(iterable $commits, User $user): array $authors = $following->newPivotQuery()->pluck($following->getRelatedPivotKeyName()) ->merge($organizations->newPivotQuery()->pluck($organizations->getRelatedPivotKeyName()))->push($user->id); - return collect($commits)->reject(fn (Commit $commit): bool => $authors->contains($commit->author_id)) - ->mapWithKeys(fn (Commit $commit): array => [$commit->id => collect($this->hashtags->handles($commit->body))->first(fn (string $handle): bool => in_array($handle, $handles, true))]) + return collect($commits)->reject(fn (Commit $commit): bool => $commit->guild_id === null && $authors->contains($commit->author_id)) + ->mapWithKeys(fn (Commit $commit): array => [$commit->id => $commit->guild->handle ?? collect($this->hashtags->handles($commit->body))->first(fn (string $handle): bool => in_array($handle, $handles, true))]) ->filter()->all(); } /** @return Paginator */ private function page(Guild $guild, User $viewer, int $page): Paginator { - $ids = $this->ids($viewer, [$guild->handle]) - ->skip(($page - 1) * 20) - ->take(21) - ->all(); + $roots = Commit::query()->topLevel()->visibleTo($viewer)->withoutMutedAuthorsFor($viewer)->select(['id', 'created_at']); + $ids = Commit::query()->visibleTo($viewer)->withoutMutedAuthorsFor($viewer) + ->where(fn (CommitBuilder $query): CommitBuilder => $query->where('guild_id', $guild->id) + ->orWhere(fn (CommitBuilder $query): CommitBuilder => $query->whereNull('guild_id')->whereLike('body', '%#%'))) + ->joinSub($roots, 'roots', fn (JoinClause $join): JoinClause => $join->on('roots.id', '=', DB::raw('coalesce(commits.root_id, commits.id)'))) + ->orderByDesc('roots.created_at')->orderByDesc('roots.id')->orderBy('commits.id') + ->select(['roots.id', 'commits.body', 'commits.guild_id'])->toBase()->lazy(100) + ->map(fn (stdClass $commit): Fluent => new Fluent(get_object_vars($commit))) + ->filter(fn (Fluent $commit): bool => $commit->get('guild_id') !== null || in_array($guild->handle, $this->hashtags->handles($commit->string('body')->value()), true)) + ->map(fn (Fluent $commit): string => $commit->string('id')->value()) + ->unique()->skip(($page - 1) * 30)->take(31)->values()->all(); $commits = Commit::query()->whereKey($ids) - ->visibleTo($viewer)->withoutMutedAuthorsFor($viewer) - ->withVisibleReplyCount($viewer)->withContinuationId($viewer)->withCardDataFor($viewer) + ->withVisibleReplyCount($viewer)->withReplyPreviews($viewer)->withCardDataFor($viewer) ->newestFirst()->get(); - return new Paginator($commits, 20, $page); + return new Paginator($commits, 30, $page, ['path' => Paginator::resolveCurrentPath()]); } /** @@ -109,10 +116,15 @@ private function ids(User $viewer, array $handles): LazyCollection return new LazyCollection; } + $guildIds = Guild::query()->whereIn('handle', $handles)->pluck('id')->all(); + return Commit::query()->visibleTo($viewer)->withoutMutedAuthorsFor($viewer) - ->whereLike('body', '%#%')->newestFirst()->select(['id', 'body'])->toBase()->cursor() + ->where(fn (CommitBuilder $query): CommitBuilder => $query->whereIn('guild_id', $guildIds)->orWhereLike('body', '%#%')) + ->newestFirst()->select(['id', 'body', 'guild_id'])->toBase()->cursor() ->map(fn (stdClass $commit): Fluent => new Fluent(get_object_vars($commit))) - ->filter(fn (Fluent $commit): bool => array_intersect($handles, $this->hashtags->handles($commit->string('body')->value())) !== []) + ->filter(fn (Fluent $commit): bool => $commit->get('guild_id') !== null + ? in_array($commit->string('guild_id')->value(), $guildIds, true) + : array_intersect($handles, $this->hashtags->handles($commit->string('body')->value())) !== []) ->map(fn (Fluent $commit): string => $commit->string('id')->value()); } } diff --git a/app/Queries/LogQueries/FollowingLogQuery.php b/app/Queries/LogQueries/FollowingLogQuery.php index 66fd700eb..83d40675e 100644 --- a/app/Queries/LogQueries/FollowingLogQuery.php +++ b/app/Queries/LogQueries/FollowingLogQuery.php @@ -22,9 +22,11 @@ public function builder(?User $user): CommitBuilder return Commit::query() ->where(fn (CommitBuilder $query): CommitBuilder => $query - ->whereIn('author_id', $following->newPivotQuery()->select($following->getRelatedPivotKeyName())) - ->orWhereIn('author_id', $organizations->newPivotQuery()->select($organizations->getRelatedPivotKeyName())) - ->orWhere('author_id', $user->id) + ->where(fn (CommitBuilder $query): CommitBuilder => $query->whereNull('guild_id') + ->where(fn (CommitBuilder $query): CommitBuilder => $query + ->whereIn('author_id', $following->newPivotQuery()->select($following->getRelatedPivotKeyName())) + ->orWhereIn('author_id', $organizations->newPivotQuery()->select($organizations->getRelatedPivotKeyName())) + ->orWhere('author_id', $user->id))) ->orWhere(fn (CommitBuilder $query): CommitBuilder => $query->fromJoinedGuilds($user))) ->visibleTo($user) ->withoutMutedAuthorsFor($user) diff --git a/app/Queries/LogQueries/LatestLogQuery.php b/app/Queries/LogQueries/LatestLogQuery.php index 3aad2f33f..66f437acb 100644 --- a/app/Queries/LogQueries/LatestLogQuery.php +++ b/app/Queries/LogQueries/LatestLogQuery.php @@ -14,6 +14,7 @@ public function builder(?User $user): CommitBuilder { return Commit::query() + ->whereNull('guild_id') ->visibleTo($user) ->withoutMutedAuthorsFor($user) ->withoutMutedGuildsFor($user) diff --git a/app/Queries/OrganizationCommitsQuery.php b/app/Queries/OrganizationCommitsQuery.php index a4ff2f68f..9e7fc4dd4 100644 --- a/app/Queries/OrganizationCommitsQuery.php +++ b/app/Queries/OrganizationCommitsQuery.php @@ -17,6 +17,7 @@ public function builder(Organization $organization, ?User $viewer): CommitBuilde { return Commit::query() ->where('author_id', $organization->id) + ->whereNull('guild_id') ->visibleTo($viewer) ->topLevel() ->withVisibleReplyCount($viewer) diff --git a/app/Queries/PinnedCommitQuery.php b/app/Queries/PinnedCommitQuery.php index d0a2f7423..f5c664a71 100644 --- a/app/Queries/PinnedCommitQuery.php +++ b/app/Queries/PinnedCommitQuery.php @@ -20,6 +20,7 @@ public function get(User $user, ?User $viewer): ?Commit return Commit::query() ->where('author_id', $user->id) + ->whereNull('guild_id') ->visibleTo($viewer) ->topLevel() ->withVisibleReplyCount($viewer) diff --git a/app/Queries/SuggestedCommitsQuery.php b/app/Queries/SuggestedCommitsQuery.php index 048889048..7f6280075 100644 --- a/app/Queries/SuggestedCommitsQuery.php +++ b/app/Queries/SuggestedCommitsQuery.php @@ -20,6 +20,7 @@ public function get(User $user, int $limit = 3): Collection ->withoutMutedAuthorsFor($user) ->withoutMutedGuildsFor($user) ->topLevel() + ->whereNull('guild_id') ->withStarsFor($user) ->whereNot('author_id', $user->id) ->latest() diff --git a/app/Queries/UserCommitsQuery.php b/app/Queries/UserCommitsQuery.php index a097dc0fe..336bc0012 100644 --- a/app/Queries/UserCommitsQuery.php +++ b/app/Queries/UserCommitsQuery.php @@ -19,6 +19,7 @@ public function builder(User $user, ?User $viewer, bool $replies = false): Commi { return Commit::query() ->where('author_id', $user->id) + ->whereNull('guild_id') ->visibleTo($viewer) ->when( $replies, diff --git a/app/Services/TheAlgorithm.php b/app/Services/TheAlgorithm.php index 2e5eb2269..ae139a717 100644 --- a/app/Services/TheAlgorithm.php +++ b/app/Services/TheAlgorithm.php @@ -118,6 +118,7 @@ public function draw(?User $viewer, int $seed, float $temperature): CommitBuilde return Commit::query() ->topLevel() + ->whereNull('guild_id') ->where('commits.created_at', '>=', now()->subDays(self::CANDIDATE_MAX_AGE_DAYS)) ->visibleTo($viewer) ->withoutMutedAuthorsFor($viewer) diff --git a/database/migrations/2026_11_17_104522_add_guild_id_to_commits_and_scheduled_commits.php b/database/migrations/2026_11_17_104522_add_guild_id_to_commits_and_scheduled_commits.php new file mode 100644 index 000000000..6dc209919 --- /dev/null +++ b/database/migrations/2026_11_17_104522_add_guild_id_to_commits_and_scheduled_commits.php @@ -0,0 +1,22 @@ +foreignUuid('guild_id')->nullable()->constrained()->cascadeOnDelete(); + $table->index('guild_id'); + }); + + Schema::table('scheduled_commits', function (Blueprint $table): void { + $table->foreignUuid('guild_id')->nullable()->constrained()->cascadeOnDelete(); + }); + } +}; diff --git a/database/migrations/2026_11_17_115459_make_guild_moderator_nullable.php b/database/migrations/2026_11_17_115459_make_guild_moderator_nullable.php new file mode 100644 index 000000000..e556e982e --- /dev/null +++ b/database/migrations/2026_11_17_115459_make_guild_moderator_nullable.php @@ -0,0 +1,19 @@ +dropForeign(['user_id']); + $table->uuid('user_id')->nullable()->change(); + $table->foreign('user_id')->references('id')->on('users')->nullOnDelete(); + }); + } +}; diff --git a/resources/js/components/commit-composer.tsx b/resources/js/components/commit-composer.tsx index 115756896..c23a228c1 100644 --- a/resources/js/components/commit-composer.tsx +++ b/resources/js/components/commit-composer.tsx @@ -53,7 +53,6 @@ import { import { useUser } from '@/hooks/use-user'; import { bodyCharacterCount, - bodyWithHashtag, isSavedAs, maxBodyLength, maxRawBodyLength, @@ -350,7 +349,7 @@ function CommitComposerBody({ {guildHandle && (

- #{guildHandle} is added automatically if missing. + Posted to this guild, not your profile log.

)} {issue.hint && ( @@ -640,9 +639,6 @@ export function CommitComposer({ guildHandle ? `guild:${guildHandle}` : 'commit', ); const { body } = stash; - const submittedBody = guildHandle - ? bodyWithHashtag(body, guildHandle) - : body; const linkCard = useLinkCard(body); const [draftVersion, setDraftVersion] = useState(0); const drop = () => { @@ -699,7 +695,8 @@ export function CommitComposer({ useEffect(() => { if ( committed !== undefined && - isSavedAs(submittedBody, committed.body) + (committed.guild_handle ?? null) === (guildHandle ?? null) && + isSavedAs(body, committed.body) ) { drop(); } diff --git a/resources/js/components/commit-search-results.tsx b/resources/js/components/commit-search-results.tsx index 7c0c8723d..36fe2e720 100644 --- a/resources/js/components/commit-search-results.tsx +++ b/resources/js/components/commit-search-results.tsx @@ -1,11 +1,28 @@ -import type { ReactNode } from 'react'; +import { usePage } from '@inertiajs/react'; +import { Fragment, type ReactNode } from 'react'; import { CommitCard } from '@/components/commit-card'; import { CommitSkeleton, EmptyFeed } from '@/components/commit-feed'; import { GraphCanvas } from '@/components/graph-canvas'; +import { GuildIcon } from '@/components/guild-icon'; +import { groupSearchCommits } from '@/lib/commit-search-results'; import type { Commit } from '@/types'; export type SearchResultSet = { term: string; commits: Commit[] }; +export function GuildSearchHeading({ handle }: { handle: string }) { + const { guilds } = usePage().props; + const guild = guilds?.find((guild) => guild.handle === handle); + + return ( + + + + {guild?.name ?? `#${handle}`} + + + ); +} + export function SearchResults({ results, isWaiting = false, @@ -54,15 +71,24 @@ export function SearchResults({ ) : ( - - {results.commits.map((commit) => ( - - ))} - + groupSearchCommits(results.commits).map(([handle, commits]) => ( + + {handle && ( +

+ +

+ )} + + {commits.map((commit) => ( + + ))} + +
+ )) )} ); diff --git a/resources/js/components/composer-preview.tsx b/resources/js/components/composer-preview.tsx index e066e7029..80791aa08 100644 --- a/resources/js/components/composer-preview.tsx +++ b/resources/js/components/composer-preview.tsx @@ -13,7 +13,6 @@ import type { PollDraft } from '@/components/poll-editor'; import { Button } from '@/components/ui/button'; import { useNow } from '@/hooks/use-now'; import { bodySegments, hasCodeBlock } from '@/lib/code'; -import { bodyWithHashtag } from '@/lib/commit'; import { hasModKey, useKeyLabels } from '@/lib/keyboard'; import { cn } from '@/lib/utils'; import type { BodySegment } from '@/types'; @@ -65,9 +64,7 @@ export function useComposerPreview({ body: '', }); - const draft = ( - guildHandle ? bodyWithHashtag(body, guildHandle) : body - ).trim(); + const draft = body.trim(); const isResolved = resolved?.body === draft; const segments = isResolved ? resolved.segments : bodySegments(draft); diff --git a/resources/js/components/guild-moderation.tsx b/resources/js/components/guild-moderation.tsx index 23e11a26b..24d12a5a7 100644 --- a/resources/js/components/guild-moderation.tsx +++ b/resources/js/components/guild-moderation.tsx @@ -1,6 +1,6 @@ import { Form, router } from '@inertiajs/react'; import { useState } from 'react'; -import { destroy } from '@/actions/App/Http/Controllers/GuildController'; +import { destroy } from '@/actions/App/Http/Controllers/GuildModeratorController'; import { store } from '@/actions/App/Http/Controllers/GuildReportController'; import InputError from '@/components/input-error'; import { Button } from '@/components/ui/button'; @@ -95,11 +95,11 @@ export function GuildRemovalButton({ Remove {guild.name}’s moderator? - This is the guild’s last moderator. Removing them hides - the guild page until a different moderator claims # - {guild.handle}. Its icon, description, memberships and - mute preferences will be removed. Commits keep their - hashtag. This moderator cannot reclaim the guild. + This is the guild’s last moderator. Removing them pauses + the guild until a different moderator claims # + {guild.handle}. Its posts, icon, description, + memberships and mute preferences stay connected. This + moderator cannot reclaim the guild.
+ ); } diff --git a/resources/js/components/search-dialog.tsx b/resources/js/components/search-dialog.tsx index ac99d227f..ce29f4019 100644 --- a/resources/js/components/search-dialog.tsx +++ b/resources/js/components/search-dialog.tsx @@ -19,6 +19,7 @@ import HeadlineController from '@/actions/App/Http/Controllers/HeadlineControlle import ProfileSearchController from '@/actions/App/Http/Controllers/ProfileSearchController'; import SearchController from '@/actions/App/Http/Controllers/SearchController'; import { AuthorAvatar } from '@/components/author-avatar'; +import { GuildSearchHeading } from '@/components/commit-search-results'; import { HotTopicContent } from '@/components/hot-topics'; import { OrganizationAvatar } from '@/components/organization-avatar'; import { DialogOverlay, DialogPortal } from '@/components/ui/dialog'; @@ -33,6 +34,7 @@ import { import { signIn } from '@/lib/auth'; import { searchCandidates } from '@/lib/chat'; import { searchCommits, TooManySearches } from '@/lib/commit-search'; +import { groupSearchCommits } from '@/lib/commit-search-results'; import { useKeyLabels } from '@/lib/keyboard'; import type { SearchAction } from '@/lib/search-actions'; import { searchActions } from '@/lib/search-actions'; @@ -564,11 +566,13 @@ function optionsFor( organization, }), ); - const commitOptions: Option[] = commits.map((commit) => ({ - kind: 'commit', - id: `commit-${commit.id}`, - commit, - })); + const commitOptions: Option[] = groupSearchCommits(commits) + .flatMap(([, group]) => group) + .map((commit) => ({ + kind: 'commit', + id: `commit-${commit.id}`, + commit, + })); const seeAll: Option[] = commitTerm === '' ? [] : [{ kind: 'all', id: 'all', needsSignIn }]; @@ -612,9 +616,19 @@ const headings: Record = { }; function headingBefore(options: Option[], index: number): ReactNode { - const kind = options[index].kind; + const option = options[index]; + const previous = options[index - 1]; + const kind = option.kind; + + if (option.kind === 'commit' && option.commit.guild_handle) { + return previous?.kind === 'commit' && + previous.commit.guild_handle === + option.commit.guild_handle ? null : ( + + ); + } - if (options[index - 1]?.kind === kind) { + if (previous?.kind === kind) { return null; } @@ -690,7 +704,7 @@ function ResultOption({ {heading && (
  • {heading}
  • diff --git a/resources/js/lib/commit-search-results.ts b/resources/js/lib/commit-search-results.ts index 741c8f4ad..6426800e6 100644 --- a/resources/js/lib/commit-search-results.ts +++ b/resources/js/lib/commit-search-results.ts @@ -1,5 +1,18 @@ import type { Commit } from '@/types'; +export function groupSearchCommits(commits: Commit[]) { + const groups = new Map([[null, []]]); + + for (const commit of commits) { + const handle = commit.guild_handle ?? null; + const group = groups.get(handle) ?? []; + group.push(commit); + groups.set(handle, group); + } + + return [...groups].filter(([, group]) => group.length > 0); +} + export class CommitSearchResults { term: string; commits: Commit[]; diff --git a/resources/js/lib/commit.ts b/resources/js/lib/commit.ts index f8d0aa51e..edd3be28d 100644 --- a/resources/js/lib/commit.ts +++ b/resources/js/lib/commit.ts @@ -28,25 +28,6 @@ export function isSavedAs(draft: string, saved: string): boolean { return emojify(normalizeBody(draft)) === saved; } -export function bodyWithHashtag(body: string, handle: string): string { - const hasHashtag = bodySegments(body).some((segment) => { - if (segment.type !== 'text') return false; - - const prose = segment.text.replace(urlPattern, (url) => - hrefFor(withoutTrailingPunctuation(url)) === null ? url : '', - ); - - // Keep exact hashtag boundaries in sync with App\Services\Hashtags. - return [ - ...prose.matchAll( - /(?-])#(\p{L}[\p{L}\p{M}\p{N}_]*)/gu, - ), - ].some((match) => match[1].toLowerCase() === handle); - }); - - return hasHashtag ? body : `${body.trimEnd()}\n\n#${handle}`; -} - /** * Each prose link counts as at most 23 characters. Keep in sync with App\Services\Urls::characterCount(). */ diff --git a/resources/js/pages/guild/show.tsx b/resources/js/pages/guild/show.tsx index 9ff9136a6..949b42c0a 100644 --- a/resources/js/pages/guild/show.tsx +++ b/resources/js/pages/guild/show.tsx @@ -1,7 +1,11 @@ -import { Head, Link, router, usePage } from '@inertiajs/react'; +import { Head, router, usePage } from '@inertiajs/react'; +import { Pencil } from 'lucide-react'; +import { useState } from 'react'; import { show } from '@/actions/App/Http/Controllers/GuildController'; +import { CommitCard } from '@/components/commit-card'; import { CommitComposer } from '@/components/commit-composer'; -import { SearchResults } from '@/components/commit-search-results'; +import { EmptyFeed } from '@/components/commit-feed'; +import { GraphCanvas } from '@/components/graph-canvas'; import { GuildDialog } from '@/components/guild-dialog'; import { GuildIcon } from '@/components/guild-icon'; import { @@ -13,6 +17,7 @@ import { GuildPreferences, } from '@/components/guild-preferences'; import { Button } from '@/components/ui/button'; +import { Spinner } from '@/components/ui/spinner'; import AppLayout from '@/layouts/app-layout'; import type { Commit } from '@/types'; @@ -30,6 +35,7 @@ export default function Show({ hasMore: boolean; }) { const { guilds, auth } = usePage().props; + const [isLoading, setIsLoading] = useState(false); const guild = guilds?.find((guild) => guild.handle === handle); if (!guild) { @@ -53,88 +59,127 @@ export default function Show({

    {guild.name}

    -

    - #{handle} · Public guild -

    + +
    + + {canModerate && ( + + + + )}
    +
    + + #{handle} + + · + + {guild.is_paused + ? 'Public guild · Paused' + : 'Public guild'} + + · + +

    {guild.description}

    - - - {canModerate && ( - - - - )} {!canModerate && } - {auth.isAdmin && } + {auth.isAdmin && !guild.is_paused && ( + + )}

    - Include #{handle} in a commit to post here. + {guild.is_paused + ? 'This guild is paused until it has a moderator. Its board and members are preserved.' + : `Include #${handle} in any commit to post here.`}

    - 1 - ? () => - router.get( - show.url(handle), - {}, - { - only: ['commits', 'page', 'hasMore'], - preserveScroll: true, - }, - ) - : undefined - } - /> - - {(page > 1 || hasMore) && ( + {!guild.is_paused && ( + 1 + ? () => + router.get( + show.url(handle), + {}, + { + only: ['commits', 'page', 'hasMore'], + preserveScroll: true, + }, + ) + : undefined + } + /> + )} +
    +

    + Bulletin board · Latest commits +

    + {commits.length === 0 ? ( +
    + + Post to the board or include #{handle} in a commit. + +
    + ) : ( + + {commits.map((commit) => ( + + ))} + + )} +
    + {hasMore && ( )} diff --git a/resources/js/types/commit.ts b/resources/js/types/commit.ts index 829903c30..2727ec34b 100644 --- a/resources/js/types/commit.ts +++ b/resources/js/types/commit.ts @@ -87,6 +87,7 @@ export type OrganizationAuthor = Extract< export type Commit = { id: string; joined_guild?: string | null; + guild_handle?: string | null; parent_id: string | null; hot_score: number; body: string; diff --git a/resources/js/types/guild.ts b/resources/js/types/guild.ts index 0e2178577..ca7c8e166 100644 --- a/resources/js/types/guild.ts +++ b/resources/js/types/guild.ts @@ -8,4 +8,5 @@ export type Guild = { member_count: number; is_joined: boolean; is_muted: boolean; + is_paused: boolean; }; diff --git a/resources/js/types/ui.ts b/resources/js/types/ui.ts index 3980184d0..aa66dcd3c 100644 --- a/resources/js/types/ui.ts +++ b/resources/js/types/ui.ts @@ -19,6 +19,7 @@ export type TimeoutFlash = { export type CommittedFlash = { id: string; body: string; + guild_handle?: string | null; author: { handle: string }; }; diff --git a/routes/web.php b/routes/web.php index 15be6e448..2da68649e 100644 --- a/routes/web.php +++ b/routes/web.php @@ -63,6 +63,7 @@ use App\Http\Controllers\GuildController; use App\Http\Controllers\GuildIconController; use App\Http\Controllers\GuildMembershipController; +use App\Http\Controllers\GuildModeratorController; use App\Http\Controllers\GuildMuteController; use App\Http\Controllers\GuildReportController; use App\Http\Controllers\HeadlineController; @@ -619,7 +620,7 @@ // Moderation... Route::get('moderation', [ModerationController::class, 'show'])->name('moderation.show'); Route::get('moderation/guilds', [GuildReportController::class, 'index'])->name('guild-report.index'); - Route::delete('moderation/guilds/{guild}', [GuildController::class, 'destroy'])->whereUuid('guild')->name('guild.destroy'); + Route::delete('moderation/guilds/{guild}/moderator', [GuildModeratorController::class, 'destroy'])->whereUuid('guild')->name('guild-moderator.destroy'); Route::delete('moderation/guild-reports/{report}', [GuildReportController::class, 'destroy'])->whereUuid('report')->name('guild-report.destroy'); Route::get('moderation/reports/{report}/images/{image}', [CommitReportImageController::class, 'show'])->whereUuid('report')->whereIn('image', ['0', '1', '2'])->name('commit-report-image.show'); Route::get('moderation/reports', [ReportedCommitController::class, 'index'])->name('reported-commit.index'); diff --git a/tests/Feature/Controllers/Api/CommitControllerTest.php b/tests/Feature/Controllers/Api/CommitControllerTest.php index 79bb90d31..c983dd694 100644 --- a/tests/Feature/Controllers/Api/CommitControllerTest.php +++ b/tests/Feature/Controllers/Api/CommitControllerTest.php @@ -9,6 +9,7 @@ use App\Jobs\ModerateCommit; use App\Models\Commit; use App\Models\CommitImage; +use App\Models\Guild; use App\Models\LinkPreview; use App\Models\Organization; use App\Models\Poll; @@ -65,6 +66,7 @@ 'id' => '019a2b3c-4d5e-7f60-8a9b-0c1d2e3f4a5b', 'short_hash' => 'e3f4a5b', 'body' => 'Shipped the public API', + 'guild_handle' => null, 'parent_id' => null, 'html_url' => route('commit.show', [$user, $commit]), 'created_at' => now()->toIso8601ZuluString(), @@ -91,6 +93,27 @@ ]]); }); +it('includes the guild handle in a public commit preview', function (): void { + $guild = Guild::factory()->create(); + $commit = Commit::factory()->for($guild)->create(); + + $this->getJson(route('api-commit.show', $commit)) + ->assertOk() + ->assertJsonPath('data.guild_handle', $guild->handle); +}); + +it('includes the guild handle of a quoted commit for a signed request', function (): void { + $guild = Guild::factory()->create(); + $quoted = Commit::factory()->for($guild)->create(); + $quote = Commit::factory()->for($quoted, 'quotedCommit')->create(); + $viewer = User::factory()->create(); + + signedApiRequest(apiKeyPairFor($viewer), 'GET', route('api-commit.show', $quote)) + ->assertOk() + ->assertJsonPath('data.quoted_commit.id', $quoted->id) + ->assertJsonPath('data.quoted_commit.guild_handle', $guild->handle); +}); + it('shows the organization a commit is from as its author', function (): void { $organization = Organization::factory()->create(['handle' => 'laravel', 'name' => 'Laravel']); $commit = Commit::factory()->create(['author_id' => $organization->id]); @@ -258,7 +281,7 @@ it('shows a signed request the commit as its page shows it to its user', function (): void { $user = User::factory()->create(['handle' => 'octocat']); $keyPair = apiKeyPairFor($user); - $root = Commit::factory()->create(['body' => 'Who broke prod?', 'created_at' => now()->subMinute()]); + $root = Commit::factory()->for(Guild::factory()->state(['handle' => 'rust']))->create(['body' => 'Who broke prod?', 'created_at' => now()->subMinute()]); $commit = Commit::factory()->for($user)->for($root, 'parent')->create([ 'id' => '019a2b3c-4d5e-7f60-8a9b-0c1d2e3f4a5b', 'body' => 'Ask @nunomaduro about `@Override`', @@ -295,6 +318,7 @@ 'id' => '019a2b3c-4d5e-7f60-8a9b-0c1d2e3f4a5b', 'short_hash' => 'e3f4a5b', 'body' => 'Ask @nunomaduro about `@Override`', + 'guild_handle' => null, 'parent_id' => $root->id, 'html_url' => route('commit.show', [$user, $commit]), 'created_at' => now()->toIso8601ZuluString(), @@ -324,6 +348,7 @@ 'id' => $root->id, 'short_hash' => mb_substr(str_replace('-', '', $root->id), -7), 'body' => 'Who broke prod?', + 'guild_handle' => 'rust', 'parent_id' => null, 'html_url' => route('commit.show', [$root->user, $root]), 'created_at' => now()->subMinute()->toIso8601ZuluString(), diff --git a/tests/Feature/Controllers/Api/CommitPinControllerTest.php b/tests/Feature/Controllers/Api/CommitPinControllerTest.php index 6e2add212..420ad6957 100644 --- a/tests/Feature/Controllers/Api/CommitPinControllerTest.php +++ b/tests/Feature/Controllers/Api/CommitPinControllerTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use App\Models\Commit; +use App\Models\Guild; use App\Models\User; beforeEach(function (): void { @@ -22,6 +23,16 @@ expect($this->user->fresh()->pinned_commit_id)->toBe($commit->id); })->with(['approved', 'pending', 'rejected']); +it('forbids pinning an own guild commit without replacing the existing pin', function (): void { + $pinned = Commit::factory()->for($this->user)->create(); + $this->user->update(['pinned_commit_id' => $pinned->id]); + $commit = Commit::factory()->for($this->user)->for(Guild::factory())->create(); + + signedApiRequest($this->keyPair, 'PUT', route('api-commit-pin.update', $commit))->assertForbidden(); + + expect($this->user->fresh()->pinned_commit_id)->toBe($pinned->id); +}); + it('replaces the commit pinned before', function (): void { $first = Commit::factory()->for($this->user)->create(); $replacement = Commit::factory()->for($this->user)->create(); diff --git a/tests/Feature/Controllers/Api/LogControllerTest.php b/tests/Feature/Controllers/Api/LogControllerTest.php index febb51c34..9d4fa4ebb 100644 --- a/tests/Feature/Controllers/Api/LogControllerTest.php +++ b/tests/Feature/Controllers/Api/LogControllerTest.php @@ -51,6 +51,7 @@ 'id' => $older->id, 'short_hash' => mb_substr(str_replace('-', '', $older->id), -7), 'body' => 'It was DNS.', + 'guild_handle' => null, 'parent_id' => null, 'html_url' => route('commit.show', [$author, $older]), 'created_at' => now()->subMinute()->toIso8601ZuluString(), diff --git a/tests/Feature/Controllers/Api/OrganizationCommitControllerTest.php b/tests/Feature/Controllers/Api/OrganizationCommitControllerTest.php index 2802f90d6..538f6f05a 100644 --- a/tests/Feature/Controllers/Api/OrganizationCommitControllerTest.php +++ b/tests/Feature/Controllers/Api/OrganizationCommitControllerTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use App\Models\Commit; +use App\Models\Guild; use App\Models\Organization; use App\Models\User; @@ -12,6 +13,7 @@ $older = Commit::factory()->for($poster)->create(['author_id' => $laravel->id, 'created_at' => now()->subHour()]); $newer = Commit::factory()->for($poster)->create(['author_id' => $laravel->id]); + Commit::factory()->for($poster)->for(Guild::factory())->create(['author_id' => $laravel->id]); Commit::factory()->for($poster)->for($newer, 'parent')->create(['author_id' => $laravel->id]); Commit::factory()->for($poster)->pending()->create(['author_id' => $laravel->id]); Commit::factory()->for($poster)->create(['author_id' => $laravel->id])->delete(); @@ -35,6 +37,7 @@ $pending = Commit::factory()->for($admin)->pending()->create(['author_id' => $laravel->id]); $approved = Commit::factory()->for($admin)->create(['author_id' => $laravel->id, 'created_at' => now()->subHour()]); + Commit::factory()->for($admin)->for(Guild::factory())->create(['author_id' => $laravel->id]); signedApiRequest(apiKeyPairFor($admin), 'GET', route('api-organization-commit.index', 'laravel')) ->assertOk() diff --git a/tests/Feature/Controllers/Api/UserCommitControllerTest.php b/tests/Feature/Controllers/Api/UserCommitControllerTest.php index bf8c346ed..8dbc09469 100644 --- a/tests/Feature/Controllers/Api/UserCommitControllerTest.php +++ b/tests/Feature/Controllers/Api/UserCommitControllerTest.php @@ -5,6 +5,7 @@ use App\Jobs\DetectCommitLanguage; use App\Models\Commit; use App\Models\CommitImage; +use App\Models\Guild; use App\Models\LinkPreview; use App\Models\User; use Illuminate\Support\Facades\DB; @@ -20,6 +21,7 @@ Commit::factory()->for($user)->rejected()->create(); Commit::factory()->for($user)->create()->delete(); Commit::factory()->create(); + Commit::factory()->for($user)->for(Guild::factory())->create(); $response = $this->getJson('/api/v1/users/octocat/commits'); diff --git a/tests/Feature/Controllers/CommitControllerTest.php b/tests/Feature/Controllers/CommitControllerTest.php index 8edc654c7..ccc05d74a 100644 --- a/tests/Feature/Controllers/CommitControllerTest.php +++ b/tests/Feature/Controllers/CommitControllerTest.php @@ -48,6 +48,7 @@ $response->assertInertiaFlash('committed', [ 'id' => $commit->id, 'body' => 'Initial commit', + 'guild_handle' => null, 'author' => ['handle' => $user->handle], ])->assertInertiaFlash('achievementsUnlocked', ['init']); }); @@ -67,6 +68,7 @@ expect($page['flash']['committed'] ?? null)->toBe([ 'id' => $user->commits()->sole()->id, 'body' => 'Initial commit', + 'guild_handle' => null, 'author' => ['handle' => $user->handle], ]); }); diff --git a/tests/Feature/Controllers/CommitPinControllerTest.php b/tests/Feature/Controllers/CommitPinControllerTest.php index f6408903e..51ba6e6ac 100644 --- a/tests/Feature/Controllers/CommitPinControllerTest.php +++ b/tests/Feature/Controllers/CommitPinControllerTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use App\Models\Commit; +use App\Models\Guild; use App\Models\User; it('pins an own top-level commit', function (): void { @@ -17,6 +18,17 @@ expect($user->fresh()->pinned_commit_id)->toBe($commit->id); }); +it('forbids pinning an own guild commit without replacing the existing pin', function (): void { + $user = User::factory()->create(); + $pinned = Commit::factory()->for($user)->create(); + $user->update(['pinned_commit_id' => $pinned->id]); + $commit = Commit::factory()->for($user)->for(Guild::factory())->create(); + + $this->actingAs($user)->put(route('commit-pin.update', $commit))->assertForbidden(); + + expect($user->fresh()->pinned_commit_id)->toBe($pinned->id); +}); + it('replaces a pin idempotently without changing identity or content', function (string $status): void { $user = User::factory()->create(); $originalIdentity = $user->getAttributes(); diff --git a/tests/Feature/Controllers/CommitSearchControllerTest.php b/tests/Feature/Controllers/CommitSearchControllerTest.php index 0f69045e9..aa9d35d4a 100644 --- a/tests/Feature/Controllers/CommitSearchControllerTest.php +++ b/tests/Feature/Controllers/CommitSearchControllerTest.php @@ -19,7 +19,8 @@ }); it('returns the commits matching the query, with what the card renders', function (): void { - $commit = Commit::factory()->create(['body' => 'Shipped a new feature', 'embedding' => embeddingVector(0)]); + $guild = Guild::factory()->create(['handle' => 'rust']); + $commit = Commit::factory()->for($guild)->create(['body' => 'Shipped a new feature', 'embedding' => embeddingVector(0)]); Commit::factory()->create(['body' => 'Something else', 'embedding' => embeddingVector(1)]); $response = $this->getJson('/search/commits?q=feature'); @@ -27,6 +28,7 @@ $response->assertOk() ->assertJsonCount(2, 'commits') ->assertJsonPath('commits.0.id', $commit->id) + ->assertJsonPath('commits.0.guild_handle', 'rust') ->assertJsonPath('commits.0.stars_count', 0) ->assertJsonPath('commits.0.starred', false) ->assertJsonPath('commits.0.replies_count', 0) @@ -54,7 +56,7 @@ $author = User::factory()->create(); $admin->following()->attach($author); $guild = Guild::factory()->create(['handle' => 'rust']); - $hidden = Commit::factory()->for($author)->create(['body' => 'Learning #RuSt', 'embedding' => embeddingVector(0)]); + $hidden = Commit::factory()->for($author)->for($guild)->create(['body' => 'Learning Rust', 'embedding' => embeddingVector(0)]); $visible = Commit::factory()->for($author)->create(['body' => 'Literal `#rust` and #rustlang', 'embedding' => embeddingVector(1)]); $this->actingAs($admin)->put(route('guild-mute.update', $guild), ['muted' => true])->assertRedirect(); diff --git a/tests/Feature/Controllers/ExportControllerTest.php b/tests/Feature/Controllers/ExportControllerTest.php index 347604612..e776a5c22 100644 --- a/tests/Feature/Controllers/ExportControllerTest.php +++ b/tests/Feature/Controllers/ExportControllerTest.php @@ -6,7 +6,7 @@ use App\Actions\CreateCommitTranslation; use App\Actions\CreateExport; use App\Actions\CreateGuildReport; -use App\Actions\DeleteGuild; +use App\Actions\DeleteGuildModerator; use App\Actions\DeleteUser; use App\Actions\UpdateDevicePushToken; use App\Contracts\Services\TranslationProvider; @@ -256,7 +256,7 @@ $parent = Commit::factory()->for($other)->rejected()->create(['body' => 'Another developer private parent body']); $approved = Commit::factory()->for($user)->create(['body' => "Shipped Unicode support 🚀\nNext: docs.", 'pasteis_count' => 3]); $approved->headlines()->create(['name' => 'Unicode support ships']); - $pending = Commit::factory()->for($user)->pending()->create(); + $pending = Commit::factory()->for($user)->for(Guild::factory()->state(['handle' => 'rust']))->pending()->create(); $rejected = Commit::factory()->for($user)->rejected()->create(); $reply = Commit::factory()->for($user)->create(['parent_id' => $parent->id]); $quote = Commit::factory()->for($user)->create(['quoted_commit_id' => $parent->id]); @@ -281,6 +281,7 @@ 'id' => $approved->id, 'parent_id' => null, 'quoted_commit_id' => null, + 'guild_handle' => null, 'body' => $approved->body, 'cached_translations' => [ 'source_language' => 'en', @@ -296,6 +297,7 @@ 'deleted_at' => null, ]) ->and($commits[$pending->id]['status'])->toBe('pending') + ->and($commits[$pending->id]['guild_handle'])->toBe('rust') ->and($commits[$rejected->id]['status'])->toBe('rejected') ->and($commits[$reply->id]['parent_id'])->toBe($parent->id) ->and($commits[$quote->id]['quoted_commit_id'])->toBe($parent->id) @@ -764,8 +766,8 @@ $guild->members()->attach($user, ['joined_at' => now(), 'muted_at' => now()]); $guild->members()->attach(User::factory()->create(), ['joined_at' => now()]); resolve(CreateGuildReport::class)->handle(User::factory()->create(), $guild, 'Someone elses report.'); - resolve(DeleteGuild::class)->handle(Guild::factory()->create(['user_id' => $user->id, 'handle' => 'rust'])); - resolve(DeleteGuild::class)->handle(Guild::factory()->create(['handle' => 'php'])); + resolve(DeleteGuildModerator::class)->handle(Guild::factory()->create(['user_id' => $user->id, 'handle' => 'rust'])); + resolve(DeleteGuildModerator::class)->handle(Guild::factory()->create(['handle' => 'php'])); $data = json_decode($this->actingAs($user)->get(route('export'))->streamedContent(), true, flags: JSON_THROW_ON_ERROR); diff --git a/tests/Feature/Controllers/GuildControllerTest.php b/tests/Feature/Controllers/GuildControllerTest.php index c2df8f9a8..da32fae80 100644 --- a/tests/Feature/Controllers/GuildControllerTest.php +++ b/tests/Feature/Controllers/GuildControllerTest.php @@ -2,9 +2,13 @@ declare(strict_types=1); +use App\Actions\CreateCommit; use App\Actions\CreateGuild; use App\Actions\CreateGuildReport; +use App\Actions\CreateScheduledCommit; use App\Actions\DeleteUser; +use App\Actions\UpdateGuild; +use App\Actions\UpdateScheduledCommitSubmittedAt; use App\Contracts\Services\ModerationProvider; use App\Enums\CommitStatus; use App\Enums\Feature; @@ -30,24 +34,57 @@ config(['app.admins' => ['admin', 'other-admin']]); }); -it('adds the bulletin board hashtag after validating the full writing budget', function (string $body, string $saved): void { +it('keeps bulletin board text unchanged and preserves the guild when scheduling', function (string $body): void { $user = User::factory()->create(['handle' => 'admin']); - Guild::factory()->create(['handle' => 'rust']); + $guild = Guild::factory()->create(['handle' => 'rust']); $payload = ['body' => $body, 'guild_handle' => 'rust']; $preview = $this->actingAs($user)->postJson(route('commit-preview.store'), $payload)->assertOk(); - $this->post(route('commit.store'), $payload)->assertSessionHasNoErrors(); - expect($user->commits()->sole()->body)->toBe($saved); + $this->post(route('commit.store'), $payload)->assertSessionHasNoErrors()->assertInertiaFlash('committed.guild_handle', 'rust'); + expect($user->commits()->sole())->body->toBe($body)->guild_id->toBe($guild->id); + expect($guild->commits()->sole()->guild->id)->toBe($guild->id); $preview->assertJsonPath('segments', $user->commits()->sole()->toArray()['body_segments']); $this->post(route('scheduled-commit.store'), [...$payload, 'scheduled_at' => now()->addHour()->toIso8601String()])->assertSessionHasNoErrors(); - expect(ScheduledCommit::query()->sole()->body)->toBe($saved); + $scheduled = ScheduledCommit::query()->sole(); + expect($scheduled)->body->toBe($body)->guild_id->toBe($guild->id); + resolve(UpdateScheduledCommitSubmittedAt::class)->handle($scheduled->id, early: true); + expect($scheduled->fresh()->commit)->body->toBe($body)->guild_id->toBe($guild->id); })->with([ - 'full budget' => [str_repeat('x', 4000), str_repeat('x', 4000)."\n\n#rust"], - 'already present' => ['Learning #RUST!', 'Learning #RUST!'], - 'only inside code or a link' => ['`#rust` https://example.com/#rust', "`#rust` https://example.com/#rust\n\n#rust"], + 'full budget' => [str_repeat('x', 4000)], + 'already present' => ['Learning #RUST!'], + 'only inside code or a link' => ['`#rust` https://example.com/#rust'], ]); +it('keeps board posts on their guild counts them but leaves them off profile and general logs', function (): void { + $author = User::factory()->create(['handle' => 'admin']); + $viewer = User::factory()->create(['handle' => 'other-admin']); + $guild = Guild::factory()->create(['handle' => 'rust']); + Guild::factory()->create(['handle' => 'jobs']); + $regular = Commit::factory()->for($author)->create(['body' => 'Learning #rust']); + $this->actingAs($author)->post(route('commit.store'), ['body' => 'A board post with #jobs', 'guild_handle' => 'rust'])->assertSessionHasNoErrors(); + $board = $author->commits()->whereNotNull('guild_id')->sole(); + $author->forceFill(['pinned_commit_id' => $board->id])->save(); + + $this->get(route('guild.show', 'rust'))->assertInertia(fn ($page) => $page->has('commits', 2)->where('commits.0.id', $board->id)); + $this->get(route('guild.show', 'jobs'))->assertInertia(fn ($page) => $page->has('commits', 0)); + $this->get(route('user.show', $author))->assertInertia(fn ($page) => $page + ->where('user.commits_count', 2)->where('pinnedCommit', null)->has('commits.data', 1)->where('commits.data.0.id', $regular->id)); + $this->get(route('log.show', 'following'))->assertInertia(fn ($page) => $page->has('commits.data', 1)); + $viewer->following()->attach($author); + $this->actingAs($viewer)->get(route('log.show', 'following'))->assertInertia(fn ($page) => $page->has('commits.data', 1)); + $this->put(route('guild-membership.update', $guild), ['joined' => true])->assertRedirect(); + $this->get(route('log.show', 'following'))->assertInertia(fn ($page) => $page + ->has('commits.data', 2)->where('commits.data.0.id', $board->id)->where('commits.data.0.joined_guild', 'rust')); + foreach (['latest', 'trending'] as $log) { + $this->get(route('log.show', $log))->assertInertia(fn ($page) => $page->has('commits.data', 1)->where('commits.data.0.id', $regular->id)); + } + + $this->put(route('guild-mute.update', $guild), ['muted' => true])->assertRedirect(); + $this->get(route('log.show', 'following'))->assertInertia(fn ($page) => $page->has('commits.data', 0)); + $this->get(route('commit.show', [$author, $board]))->assertOk(); +}); + it('does not let bulletin board context bypass validation', function (string $route, array $payload, bool $admin, string $field): void { Guild::factory()->create(['handle' => 'rust']); $this->actingAs(User::factory()->create(['handle' => $admin ? 'admin' : 'member'])) @@ -213,6 +250,25 @@ $this->get(route('guild-icon.show', 'jobs'))->assertNotFound(); }); +it('preserves a guild when its moderator loses ownership after edit validation', function (bool $reclaimed): void { + Storage::fake(); + $moderator = User::factory()->create(['handle' => 'admin']); + $replacement = $reclaimed ? User::factory()->create() : null; + $guild = Guild::factory()->create(['user_id' => $moderator->id, 'icon_path' => 'guild-icons/original.webp']); + Storage::put($guild->icon_path, 'original'); + $this->app->beforeResolving(UpdateGuild::class, function () use ($guild, $replacement): void { + Guild::query()->whereKey($guild->id)->update(['user_id' => $replacement?->id]); + }); + + $this->actingAs($moderator)->put(route('guild.update', $guild->handle), [ + 'description' => 'A stale edit.', 'emoji' => '🌍', 'remove_icon' => true, + ])->assertSessionHasErrors(['description' => 'You no longer moderate this guild.']); + + expect($guild->fresh())->description->toBe($guild->description)->emoji->toBe($guild->emoji) + ->icon_path->toBe('guild-icons/original.webp')->user_id->toBe($replacement?->id); + Storage::assertExists('guild-icons/original.webp'); +})->with([false, true]); + it('shows exact prose hashtags including older commits but excludes prefixes code urls and hidden authors', function (): void { $admin = User::factory()->create(['handle' => 'admin']); $guild = Guild::factory()->create(['handle' => 'jobs']); @@ -235,16 +291,51 @@ ->has('commits', 2)->where('commits.0.id', $new->id)->where('commits.1.id', $old->id)->where('hasMore', false)); }); -it('paginates matching hashtags without gaps caused by nonmatching candidates', function (): void { +it('merges board posts and exact hashtags newest first with thirty roots per page', function (): void { $admin = User::factory()->create(['handle' => 'admin']); - Guild::factory()->create(['handle' => 'café_dev']); - Commit::factory()->count(21)->create(['body' => '#CAFÉ_DEV']); - Commit::factory()->count(22)->create(['body' => '`#café_dev` #café_developers']); - $this->actingAs($admin)->get(route('guild.show', 'café_dev'))->assertOk()->assertInertia(fn ($page) => $page->has('commits', 20)->where('hasMore', true)->where('page', 1)); - $this->get(route('guild.show', ['guild' => 'café_dev', 'page' => 2]))->assertOk()->assertInertia(fn ($page) => $page->has('commits', 1)->where('hasMore', false)->where('page', 2)); + $guild = Guild::factory()->create(['handle' => 'café_dev']); + $old = Commit::factory()->create(['body' => 'An old regular commit', 'created_at' => now()->subYear()]); + $tagged = Commit::factory()->count(15)->create(['body' => '#CAFÉ_DEV', 'created_at' => now()->subDay()]); + $board = Commit::factory()->for($guild)->count(15)->create(['body' => 'Direct to the board']); + Commit::factory()->count(122)->create(['body' => '`#café_dev` #café_developers']); + Commit::factory()->for(Guild::factory())->create(['body' => 'Another board #café_dev']); + $reply = Commit::factory()->for($old, 'parent')->create(['body' => '#café_dev']); + Commit::factory()->for($reply, 'parent')->create(['body' => 'A nested #café_dev reply']); + $boardReply = Commit::factory()->for($board->last(), 'parent')->create(['body' => 'An ordinary reply']); + Commit::factory()->count(101)->for($board->last(), 'parent')->create(['body' => 'An older #café_dev match', 'created_at' => now()->subHour()]); + Commit::factory()->for($board->last(), 'parent')->create(['body' => 'Another #café_dev match']); + $this->actingAs($admin)->get(route('guild.show', 'café_dev'))->assertOk()->assertInertia(fn ($page) => $page + ->has('commits', 30)->where('hasMore', true)->where('page', 1) + ->where('commits.0.id', $board->last()->id)->where('commits.15.id', $tagged->last()->id) + ->has('commits.0.reply_preview.data', 3)->where('commits.0.reply_preview.data.1.id', $boardReply->id)); + $this->get(route('guild.show', ['guild' => 'café_dev', 'page' => 2]))->assertOk()->assertInertia(fn ($page) => $page + ->has('commits', 1)->where('commits.0.id', $old->id)->where('hasMore', false)->where('page', 2) + ->where('commits.0.reply_preview.data.0.id', $reply->id)); $this->getJson(route('guild.show', ['guild' => 'café_dev', 'page' => 0]))->assertUnprocessable()->assertJsonValidationErrors('page'); }); +it('includes roots matched only by nested replies without exposing hidden roots or replies', function (): void { + $admin = User::factory()->create(['handle' => 'admin']); + Guild::factory()->create(['handle' => 'rust']); + $root = Commit::factory()->create(['body' => 'A regular thread']); + $parent = Commit::factory()->for($root, 'parent')->create(['body' => 'An untagged reply']); + $match = Commit::factory()->for($parent, 'parent')->create(['body' => 'A nested #rust reply']); + $pending = Commit::factory()->pending()->create(); + Commit::factory()->for($pending, 'parent')->create(['body' => '#rust']); + $muted = User::factory()->create(); + $admin->muting()->attach($muted); + $mutedRoot = Commit::factory()->for($muted)->create(); + Commit::factory()->for($mutedRoot, 'parent')->create(['body' => '#rust']); + $unmatched = Commit::factory()->create(); + Commit::factory()->for($unmatched, 'parent')->pending()->create(['body' => '#rust']); + Commit::factory()->for($muted)->for($unmatched, 'parent')->create(['body' => '#rust']); + + $this->actingAs($admin)->get(route('guild.show', 'rust'))->assertOk()->assertInertia(fn ($page) => $page + ->has('commits', 1)->where('commits.0.id', $root->id)->where('hasMore', false) + ->where('commits.0.reply_preview.data.0.id', $parent->id)); + $this->getJson(route('commit-reply.index', $parent))->assertOk()->assertJsonPath('data.0.id', $match->id); +}); + it('matches decorated names to their hashtag while preserving their display spelling', function (string $handle, string $name): void { $this->actingAs(User::factory()->create(['handle' => 'admin']))->post(route('guild.store'), [ 'handle' => $handle, 'name' => $name, 'description' => 'A developer community.', 'emoji' => '☕', @@ -280,7 +371,7 @@ ->and($report->fresh()->dismissed_at)->toBeNull(); }); -it('removes the moderator and guild but not commits and forbids every removed moderator from reclaiming it', function (): void { +it('pauses the guild without disconnecting its content and forbids removed moderators from reclaiming it', function (): void { Storage::fake(); $owner = User::factory()->create(['handle' => 'admin']); $other = User::factory()->create(['handle' => 'other-admin']); @@ -289,24 +380,30 @@ $guild->muters()->attach($other, ['muted_at' => now()]); Storage::put($guild->icon_path, 'image'); $commit = Commit::factory()->create(['body' => '#jobs opportunity']); + $board = Commit::factory()->for($other)->for($guild)->create(); + $scheduled = ScheduledCommit::factory()->for($other)->for($guild)->create(['scheduled_at' => now()]); resolve(CreateGuildReport::class)->handle($other, $guild, 'Unrelated description.'); - $this->actingAs($other)->delete(route('guild.destroy', $guild))->assertRedirectToRoute('search.index', ['q' => '#jobs']); - $this->assertModelMissing($guild); + $this->actingAs($other)->delete(route('guild-moderator.destroy', $guild))->assertRedirectToRoute('guild.show', 'jobs'); + expect($guild->fresh())->user_id->toBeNull()->description->toBe($guild->description)->icon_path->toBe($guild->icon_path); $this->assertModelExists($commit); - $this->assertDatabaseCount('guild_reports', 0); - $this->assertDatabaseCount('guild_preferences', 0); - Storage::assertMissing('guild-icons/removed.webp'); - $this->get(route('guild.show', 'jobs'))->assertNotFound(); - $this->get('/search?q=%23jobs', ['X-Inertia-Except-Once-Props' => 'guilds'])->assertInertia(fn ($page) => $page->has('guilds', 0)); + expect($board->fresh()->guild_id)->toBe($guild->id); + expect(resolve(UpdateScheduledCommitSubmittedAt::class)->handle($scheduled->id))->toBeFalse(); + expect($scheduled->fresh())->guild_id->toBe($guild->id)->submitted_at->toBeNull()->canceled_at->toBeNull(); + $this->assertDatabaseCount('guild_reports', 1); + $this->assertDatabaseCount('guild_preferences', 2); + Storage::assertExists('guild-icons/removed.webp'); + $this->get(route('guild.show', 'jobs'))->assertOk()->assertInertia(fn ($page) => $page->where('guilds.0.is_paused', true)->has('commits', 2)); + $this->delete(route('guild-moderator.destroy', $guild))->assertRedirect(); $payload = ['handle' => 'JOBS', 'name' => 'Jobs', 'description' => 'Real jobs.', 'emoji' => '💼']; $this->actingAs($owner)->postJson(route('guild.store'), $payload)->assertUnprocessable()->assertJsonValidationErrors('handle'); $this->postJson(route('guild.store'), array_diff_key($payload, ['handle' => true]))->assertUnprocessable()->assertJsonValidationErrors('handle'); expect(fn () => resolve(CreateGuild::class)->handle($owner, 'JOBS', 'Jobs', 'Real jobs.', '💼', null))->toThrow(GuildModeratorRemoved::class); $this->actingAs($other)->post(route('guild.store'), $payload)->assertRedirectToRoute('guild.show', 'jobs'); $replacement = Guild::query()->sole(); - expect($replacement->user_id)->toBe($other->id)->and($replacement->id)->not->toBe($guild->id); - $this->delete(route('guild.destroy', $guild))->assertNotFound(); - $this->delete(route('guild.destroy', $replacement))->assertRedirect(); + expect($replacement)->user_id->toBe($other->id)->id->toBe($guild->id)->description->toBe($guild->description)->icon_path->toBe($guild->icon_path); + expect(resolve(UpdateScheduledCommitSubmittedAt::class)->handle($scheduled->id))->toBeTrue(); + expect($scheduled->fresh()->commit->guild_id)->toBe($guild->id); + $this->delete(route('guild-moderator.destroy', $replacement))->assertRedirect(); $this->postJson(route('guild.store'), $payload)->assertUnprocessable()->assertJsonValidationErrors('handle'); $this->actingAs($owner)->postJson(route('guild.store'), $payload)->assertUnprocessable()->assertJsonValidationErrors('handle'); }); @@ -333,7 +430,7 @@ $this->actingAs($user)->postJson(route('guild-report.store', $guild), ['details' => 'Report'])->assertNotFound(); $this->get(route('guild-report.index'))->assertNotFound(); $this->delete(route('guild-report.destroy', $report))->assertNotFound(); - $this->delete(route('guild.destroy', $guild))->assertNotFound(); + $this->delete(route('guild-moderator.destroy', $guild))->assertNotFound(); $this->assertModelExists($guild); expect($report->fresh()->dismissed_at)->toBeNull(); })->with([false, true]); @@ -352,7 +449,7 @@ $plain = Commit::factory()->for($user)->create(['body' => 'An unrelated commit']); $changed = false; DB::listen(function (QueryExecuted $query) use (&$changed, $commits, $user): void { - if (! $changed && $query->connectionName === 'guild_reader' && str_starts_with($query->sql, 'select "id", "body"')) { + if (! $changed && $query->connectionName === 'guild_reader' && str_starts_with($query->sql, 'select "id", "body", "guild_id"')) { $changed = true; DB::connection('guild_writer')->table('commits')->where('id', $commits->last()->id)->delete(); Commit::factory()->connection('guild_writer')->for($user)->create(['body' => 'A concurrent #rust commit']); @@ -364,6 +461,7 @@ expect($changed)->toBeTrue()->and($page->getCollection()->modelKeys())->toBe([$plain->id]); expect(DB::transactionLevel())->toBe(0); } finally { + Guild::query()->where('user_id', $user->id)->delete(); resolve(DeleteUser::class)->handle($user); DB::table('deleted_github_accounts')->where('github_id', $user->github_id)->delete(); DB::setDefaultConnection($default); @@ -392,7 +490,8 @@ ])->assertOk()->assertJsonCount(1, 'props.refreshedCommits') ->assertJsonPath('props.refreshedCommits.0.id', $parent->id) ->assertJsonCount(0, 'props.refreshedCommits.0.reply_preview.data'); - $this->get(route('guild.show', 'rust'))->assertInertia(fn ($page) => $page->where('commits.0.id', $reply->id)); + $this->get(route('guild.show', 'rust'))->assertInertia(fn ($page) => $page + ->has('commits', 1)->where('commits.0.id', $parent->id)->where('commits.0.reply_preview.data.0.id', $reply->id)); $this->getJson(route('commit-reply.index', [$parent, 'in_log' => true]))->assertOk()->assertJsonCount(0, 'data'); $this->getJson(route('commit-reply.index', [$parent, 'in_log' => true, 'ids' => [$reply->id]]))->assertOk()->assertJsonCount(0, 'data'); $this->getJson(route('commit-reply.index', $parent))->assertOk()->assertJsonPath('data.0.id', $reply->id); @@ -629,7 +728,7 @@ $this->assertDatabaseCount('guilds', 0); }); -it('announces the removal of a guild only to its members and to the admins', function (): void { +it('announces a paused guild only to its members and to the admins', function (): void { $admin = User::factory()->create(['handle' => 'admin']); $member = User::factory()->create(); $stranger = User::factory()->create(); @@ -637,9 +736,50 @@ $guild->members()->attach($member, ['joined_at' => now()]); Event::fake([UsersUpdated::class]); - $this->actingAs($admin)->delete(route('guild.destroy', $guild))->assertRedirect(); + $this->actingAs($admin)->delete(route('guild-moderator.destroy', $guild))->assertRedirect(); Event::assertDispatched(UsersUpdated::class, fn (UsersUpdated $event): bool => $event->update === UserUpdate::Guilds && $event->userIds === [$member->id]); Event::assertDispatched(UsersUpdated::class, fn (UsersUpdated $event): bool => $event->update === UserUpdate::Relationships && $event->userIds === [$member->id]); Event::assertNotDispatched(UsersUpdated::class, fn (UsersUpdated $event): bool => in_array($stranger->id, $event->userIds, true)); }); + +it('refuses new board submissions to a paused guild but still shows regular hashtag commits', function (string $route): void { + $user = User::factory()->create(['handle' => 'admin']); + Guild::factory()->create(['handle' => 'rust', 'user_id' => null]); + + $this->actingAs($user)->postJson(route($route), ['body' => 'Board post', 'guild_handle' => 'rust', 'scheduled_at' => now()->addHour()->toIso8601String()]) + ->assertUnprocessable()->assertJsonValidationErrors('guild_handle'); + $this->assertDatabaseCount('commits', 0); + $this->assertDatabaseCount('scheduled_commits', 0); + $this->post(route('commit.store'), ['body' => 'A regular #rust commit'])->assertSessionHasNoErrors(); + $this->get(route('guild.show', 'rust'))->assertOk()->assertInertia(fn ($page) => $page->has('commits', 1)->where('guilds.0.is_paused', true)); +})->with(['commit.store', 'commit-preview.store', 'scheduled-commit.store']); + +it('refuses a board submission if the guild is paused after validation', function (string $route, string $action): void { + $user = User::factory()->create(['handle' => 'admin']); + $guild = Guild::factory()->create(['handle' => 'rust']); + $this->app->beforeResolving($action, function () use ($guild): void { + $guild->update(['user_id' => null]); + }); + + $this->actingAs($user)->post(route($route), ['body' => 'Board post', 'guild_handle' => 'rust', 'scheduled_at' => now()->addHour()->toIso8601String()]) + ->assertSessionHasErrors(['guild_handle' => 'This guild is paused until it has a moderator.']); + $this->assertDatabaseCount('commits', 0); + $this->assertDatabaseCount('scheduled_commits', 0); +})->with([ + ['commit.store', CreateCommit::class], + ['scheduled-commit.store', CreateScheduledCommit::class], +]); + +it('cascades an actual guild deletion without turning board posts into ordinary posts', function (): void { + $guild = Guild::factory()->create(); + $board = Commit::factory()->for($guild)->create(); + $scheduled = ScheduledCommit::factory()->for($guild)->create(); + $regular = Commit::factory()->create(['body' => 'A regular #'.$guild->handle.' commit']); + + $guild->delete(); + + $this->assertModelMissing($board); + $this->assertModelMissing($scheduled); + $this->assertModelExists($regular); +}); diff --git a/tests/Feature/Controllers/UserFeedControllerTest.php b/tests/Feature/Controllers/UserFeedControllerTest.php index e6d486dd6..7488013a6 100644 --- a/tests/Feature/Controllers/UserFeedControllerTest.php +++ b/tests/Feature/Controllers/UserFeedControllerTest.php @@ -4,6 +4,7 @@ use App\Models\Commit; use App\Models\CommitImage; +use App\Models\Guild; use App\Models\User; use Illuminate\Support\Facades\DB; use Illuminate\Testing\TestResponse; @@ -34,6 +35,7 @@ function atomFeed(TestResponse $response): SimpleXMLElement 'created_at' => now()->subDay(), ]); $newer = Commit::factory()->for($user)->create(['body' => 'Second commit']); + Commit::factory()->for($user)->for(Guild::factory())->create(['body' => 'Only on the guild board']); Commit::factory()->for($user)->for($older, 'parent')->create(['body' => 'A reply']); Commit::factory()->for($user)->pending()->create(['body' => 'Pending commit']); Commit::factory()->for($user)->rejected()->create(['body' => 'Rejected commit']); @@ -44,6 +46,7 @@ function atomFeed(TestResponse $response): SimpleXMLElement $response->assertOk() ->assertHeader('Content-Type', 'application/atom+xml; charset=UTF-8') + ->assertDontSee('Only on the guild board') ->assertDontSee('A reply') ->assertDontSee('Pending commit') ->assertDontSee('Rejected commit') diff --git a/tests/Feature/OrganizationCommitsTest.php b/tests/Feature/OrganizationCommitsTest.php index f0821688d..0df146e01 100644 --- a/tests/Feature/OrganizationCommitsTest.php +++ b/tests/Feature/OrganizationCommitsTest.php @@ -16,6 +16,7 @@ use App\Jobs\ModerateCommit; use App\Models\Commit; use App\Models\CommitImage; +use App\Models\Guild; use App\Models\Notification; use App\Models\Organization; use App\Models\Poll; @@ -236,6 +237,7 @@ it('lists the commits of an organization on its page, first', function (): void { $commit = Commit::factory()->create(['author_id' => $this->organization->id]); Commit::factory()->for($commit, 'parent')->create(['author_id' => $this->organization->id]); + Commit::factory()->for(Guild::factory())->create(['author_id' => $this->organization->id]); $this->get('/@Laravel') ->assertOk() diff --git a/tests/Feature/ScheduledCommitsTest.php b/tests/Feature/ScheduledCommitsTest.php index 6408bd13a..4986427c4 100644 --- a/tests/Feature/ScheduledCommitsTest.php +++ b/tests/Feature/ScheduledCommitsTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use App\Actions\CreateGuild; use App\Actions\CreateScheduledCommit; use App\Actions\DeleteScheduledCommit; use App\Actions\DeleteUser; @@ -12,6 +13,7 @@ use App\Jobs\UnfurlLink; use App\Models\Commit; use App\Models\CommitImage; +use App\Models\Guild; use App\Models\Notification; use App\Models\Poll; use App\Models\ScheduledCommit; @@ -468,6 +470,29 @@ expect(Commit::query()->count())->toBe(101); }); +it('skips paused guilds before limiting the batch and drains their posts after resuming', function (): void { + $user = User::factory()->create(); + $paused = Guild::factory()->create(['user_id' => null]); + $active = Guild::factory()->create(['user_id' => $user->id]); + ScheduledCommit::factory()->for($user)->for($paused)->count(100)->create(['scheduled_at' => now()->subHour()]); + $regular = ScheduledCommit::factory()->for($user)->create(['scheduled_at' => now()]); + $board = ScheduledCommit::factory()->for($user)->for($active)->create(['scheduled_at' => now()]); + + $this->artisan('commits:submit-scheduled')->assertSuccessful(); + + expect(Commit::query()->count())->toBe(2); + expect($regular->fresh()->commit->guild_id)->toBeNull(); + expect($board->fresh()->commit->guild_id)->toBe($active->id); + expect(ScheduledCommit::query()->where('guild_id', $paused->id)->whereNull('submitted_at')->count())->toBe(100); + + resolve(CreateGuild::class)->handle($user, $paused->handle, $paused->name, $paused->description, $paused->emoji, null); + $this->artisan('commits:submit-scheduled')->assertSuccessful(); + + expect(Commit::query()->count())->toBe(102); + expect(Commit::query()->where('guild_id', $paused->id)->count())->toBe(100); + expect(ScheduledCommit::query()->whereNull('submitted_at')->count())->toBe(0); +}); + it('deletes scheduled content with the account and handles stale delivery attempts', function (): void { $scheduled = ScheduledCommit::factory()->create(['scheduled_at' => now()]); resolve(DeleteUser::class)->handle($scheduled->user); diff --git a/tests/Unit/Actions/DeleteUserTest.php b/tests/Unit/Actions/DeleteUserTest.php index e7f91aebe..c746f144d 100644 --- a/tests/Unit/Actions/DeleteUserTest.php +++ b/tests/Unit/Actions/DeleteUserTest.php @@ -7,7 +7,7 @@ use App\Actions\CreateCommitTranslation; use App\Actions\CreateGuild; use App\Actions\CreateGuildReport; -use App\Actions\DeleteGuild; +use App\Actions\DeleteGuildModerator; use App\Actions\DeleteUser; use App\Actions\UpdateCommitHotScores; use App\Contracts\Services\TranslationProvider; @@ -33,6 +33,7 @@ use App\Models\PollOption; use App\Models\PollVote; use App\Models\PushSubscription; +use App\Models\ScheduledCommit; use App\Models\User; use App\Queries\HeadlineSummaryQuery; use App\Services\CommitTranslations; @@ -483,26 +484,34 @@ expect(PushSubscription::query()->count())->toBe(0); }); -it('erases created guilds and their icons but leaves other peoples hashtag commits', function (): void { +it('pauses moderated guilds and preserves other peoples posts memberships and scheduled posts', function (): void { Storage::fake(); $user = User::factory()->create(); $guild = Guild::factory()->create(['user_id' => $user->id, 'handle' => 'jobs', 'icon_path' => 'guild-icons/example.webp']); Storage::disk()->put($guild->icon_path, 'image'); $other = Guild::factory()->create(); $commit = Commit::factory()->create(['body' => 'Hiring #jobs']); + $board = Commit::factory()->for($user)->for($guild)->create(['body' => 'A board post']); + $member = User::factory()->create(); + $otherBoard = Commit::factory()->for($member)->for($guild)->create(); + $scheduled = ScheduledCommit::factory()->for($member)->for($guild)->create(); $other->members()->attach($user, ['joined_at' => now(), 'muted_at' => now()]); - $guild->members()->attach(User::factory()->create(), ['joined_at' => now()]); + $guild->members()->attach($member, ['joined_at' => now(), 'muted_at' => now()]); resolve(DeleteUser::class)->handle($user); - $this->assertModelMissing($guild); - $this->assertDatabaseCount('guild_preferences', 0); + expect($guild->fresh()->user_id)->toBeNull(); + $this->assertModelMissing($board); + expect($otherBoard->fresh()->guild_id)->toBe($guild->id); + expect($scheduled->fresh())->guild_id->toBe($guild->id)->canceled_at->toBeNull(); + $this->assertDatabaseCount('guild_preferences', 1); + $this->assertDatabaseHas('guild_preferences', ['guild_id' => $guild->id, 'user_id' => $member->id, 'joined_at' => now(), 'muted_at' => now()]); $this->assertModelExists($other); $this->assertModelExists($commit); - Storage::disk()->assertMissing('guild-icons/example.webp'); + Storage::disk()->assertExists('guild-icons/example.webp'); }); -it('announces the removal of created guilds only to their other members', function (): void { +it('announces paused guilds only to their other members', function (): void { $user = User::factory()->create(); $member = User::factory()->create(); $stranger = User::factory()->create(); @@ -526,12 +535,12 @@ resolve(CreateGuildReport::class)->handle($user, $guild, 'My report.'); resolve(CreateGuildReport::class)->handle($other, $guild, 'Other report.'); resolve(CreateGuildReport::class)->handle($other, Guild::factory()->create(['user_id' => $user->id]), 'My guild.'); - resolve(DeleteGuild::class)->handle(Guild::factory()->create(['user_id' => $user->id, 'handle' => 'jobs'])); - resolve(DeleteGuild::class)->handle(Guild::factory()->create(['user_id' => $other->id, 'handle' => 'rust'])); + resolve(DeleteGuildModerator::class)->handle(Guild::factory()->create(['user_id' => $user->id, 'handle' => 'jobs'])); + resolve(DeleteGuildModerator::class)->handle(Guild::factory()->create(['user_id' => $other->id, 'handle' => 'rust'])); resolve(DeleteUser::class)->handle($user); - expect(GuildReport::query()->sole()->details)->toBe('Other report.'); + expect(GuildReport::query()->pluck('details')->all())->toBe(['Other report.', 'My guild.']); $this->assertDatabaseHas('guild_moderator_removals', ['github_id' => $user->github_id, 'handle' => 'jobs']); $this->assertDatabaseHas('guild_moderator_removals', ['github_id' => $other->github_id, 'handle' => 'rust']); $returning = User::factory()->create(['github_id' => $user->github_id]); diff --git a/tests/Unit/CommitSearchResults.test.ts b/tests/Unit/CommitSearchResults.test.ts index 26a0da1d3..a12692fb0 100644 --- a/tests/Unit/CommitSearchResults.test.ts +++ b/tests/Unit/CommitSearchResults.test.ts @@ -1,8 +1,25 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { CommitSearchResults } from '../../resources/js/lib/commit-search-results.ts'; +import { CommitSearchResults, groupSearchCommits } from '../../resources/js/lib/commit-search-results.ts'; import type { Commit } from '../../resources/js/types'; +await test('groups board matches by guild after regular matches while preserving order within each group', () => { + const commits = [ + { id: 'rust-first', guild_handle: 'rust' }, + { id: 'plain-first' }, + { id: 'jobs', guild_handle: 'jobs' }, + { id: 'rust-second', guild_handle: 'rust' }, + { id: 'plain-second', guild_handle: null }, + ] as Commit[]; + + assert.deepEqual(groupSearchCommits(commits).map(([handle, group]) => [handle, group.map((commit) => commit.id)]), [ + [null, ['plain-first', 'plain-second']], + ['rust', ['rust-first', 'rust-second']], + ['jobs', ['jobs']], + ]); + assert.deepEqual(groupSearchCommits([]), []); +}); + await test('latest keeps the past week newest first without changing relevance order', (context) => { context.mock.method(Date, 'now', () => Date.parse('2026-11-03T12:00:00Z')); const commits = [ diff --git a/tests/Unit/ComposerDraft.test.tsx b/tests/Unit/ComposerDraft.test.tsx index 6b361215c..a1513495b 100644 --- a/tests/Unit/ComposerDraft.test.tsx +++ b/tests/Unit/ComposerDraft.test.tsx @@ -140,7 +140,7 @@ beforeEach(() => { draft.descriptions = []; }); -test('previews the guild hashtag without spending the draft character budget', () => { +test('previews guild text unchanged and uses the full draft character budget', () => { draft.body = 'Learning Rust'; let view = render('rust'); assert.equal( @@ -153,7 +153,7 @@ test('previews the guild hashtag without spending the draft character budget', ( )!; assert.equal( (toggle.props.preview as { draft: string }).draft, - 'Learning Rust\n\n#rust', + 'Learning Rust', ); assert.equal(view.form.props.onBefore(), true); @@ -180,7 +180,7 @@ test('previews the guild hashtag without spending the draft character budget', ( const preview = render('rust').fields.find( (element) => element.type === PreviewToggle, )!.props.preview as { draft: string }; - assert.equal(preview.draft, `${body}\n\n#rust`); + assert.equal(preview.draft, body); } draft.body = 'x'.repeat(4000); assert.equal(render('rust').form.props.onBefore(), true); @@ -198,12 +198,27 @@ test('previews the guild hashtag without spending the draft character budget', ( test('recognizes a guild draft after a successful post reload and leaves other drafts alone', () => { draft.body = 'Learning Rust'; - flash = { committed: { body: 'Learning Rust\n\n#rust' } }; + flash = { committed: { body: 'Learning Rust', guild_handle: 'rust' } }; render('rust'); effects.forEach((effect) => effect()); assert.equal(draft.drop.mock.calls.length, 1); }); +test('keeps identical restored text when another posting context was submitted', () => { + draft.body = 'Learning Rust'; + for (const [guild, committedGuild] of [ + ['rust', null], + [undefined, 'rust'], + ['rust', 'go'], + ]) { + effects = []; + flash = { committed: { body: draft.body, guild_handle: committedGuild } }; + render(guild ?? undefined); + effects.forEach((effect) => effect()); + assert.equal(draft.drop.mock.calls.length, 0); + } +}); + test('preserves restored images and link cards and allows scheduling them', () => { draft.images = [image]; draft.descriptions = ['A restored screenshot']; diff --git a/tests/Unit/Queries/SuggestedCommitsQueryTest.php b/tests/Unit/Queries/SuggestedCommitsQueryTest.php index c5c7d8c27..36c616f4f 100644 --- a/tests/Unit/Queries/SuggestedCommitsQueryTest.php +++ b/tests/Unit/Queries/SuggestedCommitsQueryTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use App\Models\Commit; +use App\Models\Guild; use App\Models\User; use App\Queries\SuggestedCommitsQuery; @@ -21,6 +22,22 @@ ->and($commits->first()->relationLoaded('author'))->toBeTrue(); }); +it('suggests an author personal commit instead of their newer guild commit', function (bool $joined): void { + $user = User::factory()->create(); + $author = User::factory()->create(); + $guild = Guild::factory()->create(); + if ($joined) { + $guild->members()->attach($user, ['joined_at' => now()]); + } + + $personal = Commit::factory()->for($author)->create(['created_at' => now()->subMinute()]); + Commit::factory()->for($author)->for($guild)->create(); + + $commits = resolve(SuggestedCommitsQuery::class)->get($user); + + expect($commits->pluck('id')->all())->toBe([$personal->id]); +})->with(['unjoined guild' => false, 'joined guild' => true]); + it('only suggests approved commits', function (): void { $user = User::factory()->create();