Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: "user followed you" notification #505

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions app/Http/Controllers/NotificationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
namespace App\Http\Controllers;

use App\Models\Question;
use App\Models\User;
use App\Notifications\UserFollowed;
use Illuminate\Http\RedirectResponse;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\View\View;
Expand All @@ -23,6 +25,17 @@ public function index(): View
* Display the given notification.
*/
public function show(DatabaseNotification $notification): RedirectResponse
{
return match ($notification->type) {
UserFollowed::class => $this->handleUserFollowed($notification),
default => $this->handleQuestionBasedNotification($notification)
};
}

/**
* Handle the question based notification.
*/
private function handleQuestionBasedNotification(DatabaseNotification $notification): RedirectResponse
{
$question = type(Question::findOrFail($notification->data['question_id']))->as(Question::class);

Expand All @@ -35,4 +48,18 @@ public function show(DatabaseNotification $notification): RedirectResponse
'question' => $question,
]);
}

/**
* Handle the UserFollowed notification.
*/
private function handleUserFollowed(DatabaseNotification $notification): RedirectResponse
{
$follower = User::find($notification->data['follower_id']);

$notification->delete();

return $follower
? to_route('profile.show', ['username' => type($follower)->as(User::class)->username])
: back();
}
}
8 changes: 8 additions & 0 deletions app/Livewire/Links/Index.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
use App\Jobs\UpdateUserAvatar;
use App\Models\Link;
use App\Models\User;
use App\Notifications\UserFollowed;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;
use Livewire\Attributes\Locked;
Expand Down Expand Up @@ -125,6 +127,8 @@ public function follow(int $targetId): void

$user->following()->attach($targetId);

$target->notify(new UserFollowed($user));

$this->dispatch('user.followed');
}

Expand All @@ -151,6 +155,10 @@ public function unfollow(int $targetId): void

$user->following()->detach($targetId);

$target->notifications()
->whereJsonContains('data->follower_id', $user->id)
->each(fn (DatabaseNotification $notification): ?bool => $notification->delete());

$this->dispatch('user.unfollowed');
}

Expand Down
45 changes: 45 additions & 0 deletions app/Notifications/UserFollowed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

declare(strict_types=1);

namespace App\Notifications;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;

final class UserFollowed extends Notification
{
use Queueable;

/**
* Create a new notification instance.
*/
public function __construct(
public User $follower
) {
//
}

/**
* Get the notification's delivery channels.
*
* @return array<int, string>
*/
public function via(object $notifiable): array
{
return ['database'];
}

/**
* Get the array representation of the notification.
*
* @return array<string, mixed>
*/
public function toDatabase(object $notifiable): array
{
return [
'follower_id' => $this->follower->id,
];
}
}
173 changes: 107 additions & 66 deletions resources/views/livewire/notifications/index.blade.php
Original file line number Diff line number Diff line change
@@ -1,87 +1,128 @@
<div class="mb-20 flex flex-col gap-2">
@foreach ($notifications as $notification)
@php
$question = \App\Models\Question::find($notification->data['question_id']);
$isMention = $notification->type === 'App\Notifications\UserMentioned';
if (isset($notification->data['question_id'])) {
$question = \App\Models\Question::find($notification->data['question_id']);
$isMention = $notification->type === 'App\Notifications\UserMentioned';

if ($question === null) {
$notification->delete();
if ($question === null) {
$notification->delete();

continue;
continue;
}
}
@endphp

<a
href="{{ route('notifications.show', ['notification' => $notification->id]) }}"
wire:navigate
>
<div class="group overflow-hidden rounded-2xl border border-slate-900 bg-slate-950 bg-opacity-80 p-4 transition-colors hover:bg-slate-900">
<div
class="cursor-help text-right text-xs text-slate-400"
title="{{ $notification->created_at->timezone(session()->get('timezone', 'UTC'))->isoFormat('ddd, D MMMM YYYY HH:mm') }}"
datetime="{{ $notification->created_at->timezone(session()->get('timezone', 'UTC'))->toIso8601String() }}"
@if ($notification->type === \App\Notifications\UserFollowed::class)
@php
/** @var \Illuminate\Notifications\DatabaseNotification $notification */
$follower = \App\Models\User::find($notification->data['follower_id']);

if (!$follower) {
$notification->delete();
}
@endphp
@if($follower)
<a
href="{{ route('notifications.show', ['notification' => $notification->id]) }}"
wire:navigate
class="group overflow-hidden rounded-2xl border border-slate-900 bg-slate-950 bg-opacity-80 p-4 transition-colors hover:bg-slate-900"
>
{{
$notification->created_at->timezone(session()->get('timezone', 'UTC'))
->diffForHumans()
}}
</div>
@if (! $isMention)
@if ($question->parent_id !== null)
<div class="flex items center gap-3 text-sm text-slate-500">
<figure class="{{ $question->from->is_company_verified ? 'rounded-md' : 'rounded-full' }} h-10 w-10 flex-shrink-0 bg-slate-800 transition-opacity group-hover:opacity-90">
<img
src="{{ $question->from->avatar_url }}"
alt="{{ $question->from->username }}"
class="{{ $question->from->is_company_verified ? 'rounded-md' : 'rounded-full' }} h-10 w-10"
/>
</figure>
<p>{{ $question->from->name }} commented on your {{ $question->parent->parent_id !== null ? 'comment' : ($question->parent->isSharedUpdate() ? 'Update' : 'Answer') }}:
</div>
@elseif ($question->from->is(auth()->user()) && $question->answer !== null)
<div class="flex items-center gap-3 text-sm text-slate-500">
<figure class="{{ $question->to->is_company_verified ? 'rounded-md' : 'rounded-full' }} h-10 w-10 flex-shrink-0 bg-slate-800 transition-opacity group-hover:opacity-90">
<img
src="{{ $question->to->avatar_url }}"
alt="{{ $question->to->username }}"
class="{{ $question->to->is_company_verified ? 'rounded-md' : 'rounded-full' }} h-10 w-10"
/>
</figure>
<p>{{ $question->to->name }} answered your {{ $question->anonymously ? 'anonymous' : '' }} question:</p>
</div>
@else
@if ($question->anonymously)
<div
class="cursor-help text-right text-xs text-slate-400"
title="{{ $notification->created_at->timezone(session()->get('timezone', 'UTC'))->isoFormat('ddd, D MMMM YYYY HH:mm') }}"
datetime="{{ $notification->created_at->timezone(session()->get('timezone', 'UTC'))->toIso8601String() }}"
>
{{
$notification->created_at->timezone(session()->get('timezone', 'UTC'))
->diffForHumans()
}}
</div>
<div class="flex items-center gap-3 text-sm text-slate-500">
<figure class="{{ $follower->is_company_verified ? 'rounded-md' : 'rounded-full' }} h-10 w-10 flex-shrink-0 bg-slate-800 transition-opacity group-hover:opacity-90">
<img
src="{{ $follower->avatar_url }}"
alt="{{ $follower->username }}"
class="{{ $follower->is_company_verified ? 'rounded-md' : 'rounded-full' }} h-10 w-10"
/>
</figure>
<p>{{ $follower->name }} followed you.</p>
</div>
</a>
@endif
@else
<a
href="{{ route('notifications.show', ['notification' => $notification->id]) }}"
wire:navigate
>
<div class="group overflow-hidden rounded-2xl border border-slate-900 bg-slate-950 bg-opacity-80 p-4 transition-colors hover:bg-slate-900">
<div
class="cursor-help text-right text-xs text-slate-400"
title="{{ $notification->created_at->timezone(session()->get('timezone', 'UTC'))->isoFormat('ddd, D MMMM YYYY HH:mm') }}"
datetime="{{ $notification->created_at->timezone(session()->get('timezone', 'UTC'))->toIso8601String() }}"
>
{{
$notification->created_at->timezone(session()->get('timezone', 'UTC'))
->diffForHumans()
}}
</div>
@if (! $isMention)
@if ($question->parent_id !== null)
<div class="flex items-center gap-3 text-sm text-slate-500">
<div class="border-1 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full border border-dashed border-slate-400">
<span>?</span>
</div>
<p>Someone asked you anonymously:</p>
<figure class="{{ $question->from->is_company_verified ? 'rounded-md' : 'rounded-full' }} h-10 w-10 flex-shrink-0 bg-slate-800 transition-opacity group-hover:opacity-90">
<img
src="{{ $question->from->avatar_url }}"
alt="{{ $question->from->username }}"
class="{{ $question->from->is_company_verified ? 'rounded-md' : 'rounded-full' }} h-10 w-10"
/>
</figure>
<p>{{ $question->from->name }} commented on your {{ $question->parent->parent_id !== null ? 'comment' : ($question->parent->isSharedUpdate() ? 'Update' : 'Answer') }}:
</div>
@else
@elseif ($question->from->is(auth()->user()) && $question->answer !== null)
<div class="flex items-center gap-3 text-sm text-slate-500">
<figure class="{{ $question->from->is_company_verified ? 'rounded-md' : 'rounded-full' }} h-10 w-10 flex-shrink-0 bg-slate-800 transition-opacity group-hover:opacity-90">
<figure class="{{ $question->to->is_company_verified ? 'rounded-md' : 'rounded-full' }} h-10 w-10 flex-shrink-0 bg-slate-800 transition-opacity group-hover:opacity-90">
<img
src="{{ $question->from->avatar_url }}"
alt="{{ $question->from->username }}"
class="{{ $question->from->is_company_verified ? 'rounded-md' : 'rounded-full' }} h-10 w-10"
src="{{ $question->to->avatar_url }}"
alt="{{ $question->to->username }}"
class="{{ $question->to->is_company_verified ? 'rounded-md' : 'rounded-full' }} h-10 w-10"
/>
</figure>
<p>{{ $question->from->name }} asked you:</p>
<p>{{ $question->to->name }} answered your {{ $question->anonymously ? 'anonymous' : '' }} question:</p>
</div>
@else
@if ($question->anonymously)
<div class="flex items-center gap-3 text-sm text-slate-500">
<div class="border-1 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full border border-dashed border-slate-400">
<span>?</span>
</div>
<p>Someone asked you anonymously:</p>
</div>
@else
<div class="flex items-center gap-3 text-sm text-slate-500">
<figure class="{{ $question->from->is_company_verified ? 'rounded-md' : 'rounded-full' }} h-10 w-10 flex-shrink-0 bg-slate-800 transition-opacity group-hover:opacity-90">
<img
src="{{ $question->from->avatar_url }}"
alt="{{ $question->from->username }}"
class="{{ $question->from->is_company_verified ? 'rounded-md' : 'rounded-full' }} h-10 w-10"
/>
</figure>
<p>{{ $question->from->name }} asked you:</p>
</div>
@endif
@endif
@elseif ($question->parent !== null)
<p class="text-sm text-slate-500">You have been mentioned in a comment by {{ '@' . $question->to->username }}</p>
@else
<p class="text-sm text-slate-500">You have been mentioned in a {{ $question->isSharedUpdate() ? 'update by @'.$question->to->username : 'question:'}}</p>
@endif
@elseif ($question->parent !== null)
<p class="text-sm text-slate-500">You have been mentioned in a comment by {{ '@' . $question->to->username }}</p>
@else
<p class="text-sm text-slate-500">You have been mentioned in a {{ $question->isSharedUpdate() ? 'update by @'.$question->to->username : 'question:'}}</p>
@endif
@if(!$question->isSharedUpdate())
<p class="mt-2 text-slate-200">
{!! $question->content !!}
</p>
@endif
</div>
</a>
@if(!$question->isSharedUpdate())
<p class="mt-2 text-slate-200">
{!! $question->content !!}
</p>
@endif
</div>
</a>
@endif
@endforeach

@if ($notifications->count() === 0)
Expand Down
1 change: 1 addition & 0 deletions tests/Arch/NotificationsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@
'App\Console\Commands',
'App\Http\Controllers',
'App\Observers',
App\Livewire\Links\Index::class,
]);
19 changes: 19 additions & 0 deletions tests/Http/Notifications/ShowTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,22 @@
$response->assertRedirectToRoute('questions.show', ['question' => $question, 'username' => $question->to->username]);
expect($notification->fresh())->not->toBeNull();
});

test('notifications for UserFollowed are handled correctly', function () {
$followed = App\Models\User::factory()->create();
$follower = App\Models\User::factory()->create();

$follower->following()->attach($followed);

$followed->notify(new App\Notifications\UserFollowed($follower));
$notification = $followed->notifications()->first();

/** @var Illuminate\Testing\TestResponse $response */
$response = $this->actingAs($followed)
->get(route('notifications.show', [
'notification' => $notification,
]));

$response->assertRedirectToRoute('profile.show', ['username' => $follower->username]);
expect($followed->notifications()->get())->toBeEmpty();
});
17 changes: 17 additions & 0 deletions tests/Unit/Livewire/Links/IndexTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
});

test('follow is idempotent', function () {
Illuminate\Support\Facades\Notification::fake();

$user = User::factory()->create();
$target = User::factory()->create();

Expand All @@ -200,6 +202,12 @@
$component->call('follow', $target->id);

expect($user->following->count())->toBe(1);

Illuminate\Support\Facades\Notification::assertSentToTimes(
$target,
App\Notifications\UserFollowed::class,
1
);
});

test('unfollow is idempotent', function () {
Expand All @@ -211,13 +219,20 @@
]);

$component->call('follow', $target->id);
expect($target->notifications()->whereJsonContains('data->follower_id', $user->id)->count())->toBe(1);

$component->call('unfollow', $target->id);
$component->call('unfollow', $target->id);

expect($user->following->count())->toBe(0);

// Assert the notification was removed.
expect($target->notifications()->whereJsonContains('data->follower_id', $user->id)->count())->toBe(0);
});

test('guest cannot follow', function () {
Illuminate\Support\Facades\Notification::fake();

$user = User::factory()->create();
$component = Livewire::test(Index::class, [
'userId' => $user->id,
Expand All @@ -226,6 +241,8 @@
$component->call('follow', 1);

$component->assertRedirect(route('login'));

Illuminate\Support\Facades\Notification::assertNothingSent();
});

test('guest cannot unfollow', function () {
Expand Down
Loading