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

#80 - Inviting to quizzes - Backend #95

Draft
wants to merge 24 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
86bf145
Add invite vue, controller, resource for admin panel
PrabuckiDominik Sep 6, 2024
656d053
fix code style
PrabuckiDominik Sep 6, 2024
b61b1c7
Merge branch 'main' of https://github.com/blumilksoftware/interns2024…
PrabuckiDominik Sep 6, 2024
dd9095a
Merge branch 'main' of https://github.com/blumilksoftware/interns2024…
PrabuckiDominik Sep 9, 2024
3fd3a2f
add pagination
PrabuckiDominik Sep 9, 2024
0a2ffbc
Move logic to quiz
PrabuckiDominik Sep 9, 2024
575416d
Add invitation
PrabuckiDominik Sep 9, 2024
45f3b98
Reset password now queue
PrabuckiDominik Sep 10, 2024
89c4472
Add invite user to quiz is queued
PrabuckiDominik Sep 10, 2024
b682746
Add jobs for sending mails
PrabuckiDominik Sep 10, 2024
af069f3
Update quiz policy
PrabuckiDominik Sep 10, 2024
a4af77d
Fix invite title
PrabuckiDominik Sep 10, 2024
dae1f07
Fix code style
PrabuckiDominik Sep 10, 2024
db94388
Add sort by name/surname with watch
PrabuckiDominik Sep 11, 2024
2e1b01e
Fix password notification link
PrabuckiDominik Sep 11, 2024
4b00c7b
Fix search while sorting by school
PrabuckiDominik Sep 11, 2024
c059f53
Fix searchbar
PrabuckiDominik Sep 11, 2024
b13dac5
Add limit to filter
PrabuckiDominik Sep 11, 2024
c349688
Add assignment to test while inviting user to it
PrabuckiDominik Sep 11, 2024
e8ca731
Merge branch 'main' of https://github.com/blumilksoftware/interns2024…
PrabuckiDominik Sep 11, 2024
ffaa248
Fix issue in policy, allowing publish ranking without quiz being publ…
PrabuckiDominik Sep 11, 2024
82591c8
Fix tests
PrabuckiDominik Sep 11, 2024
fe0299f
Fix code style
PrabuckiDominik Sep 11, 2024
eafae0b
Add assign button to quiz without sending mail to users
PrabuckiDominik Sep 11, 2024
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
135 changes: 135 additions & 0 deletions app/Http/Controllers/InviteController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Requests\InviteQuizRequest;
use App\Http\Resources\UserResource;
use App\Jobs\SendInviteJob;
use App\Models\Quiz;
use App\Models\School;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class InviteController extends Controller
{
public function index(Quiz $quiz, Request $request): Response
{
$this->authorize("invite", $quiz);

$searchText = $request->query("search");
$sortField = $request->query("sort", "id");
$sortDirection = $request->query("order", "asc");
$schoolId = $request->query("schoolId") !== null ? (int)$request->query("schoolId") : null;
$limit = $request->query("limit");

$users = User::query()->role("user")->with("school")->whereNotNull("email_verified_at");

$schools = School::all(["id", "name", "city"]);

$this->applyFilters($users, $searchText, $schoolId);
$this->applySorting($users, $sortField, $sortDirection);

if ($limit && $limit > 0) {
$users = $users->paginate((int)$limit);
} else {
$users = $users->paginate(100);
}

return Inertia::render("Admin/Invite", [
"users" => UserResource::collection($users),
"quiz" => $quiz,
"schools" => $schools,
"filters" => [
"search" => $searchText,
"sort" => $sortField,
"order" => $sortDirection,
"schoolId" => $schoolId,
"limit" => $limit,
],
]);
}

public function store(Quiz $quiz, InviteQuizRequest $request): RedirectResponse
{
$this->authorize("invite", $quiz);
$userIds = $request->input("ids", []);

if (empty($userIds)) {
return redirect()->back()->withErrors("Brak użytkowników do zaproszenia.");
}

$users = User::query()->whereIn("id", $userIds)->get();

$quiz->assignedUsers()->attach($userIds);

foreach ($users as $user) {
SendInviteJob::dispatch($user, $quiz)->delay(now()->addMinutes(5));
}

return redirect()
->back()
->with("status", "Zaproszenia zostały zaplanowane do wysłania.");
}

public function assign(Quiz $quiz, InviteQuizRequest $request): RedirectResponse
{
$this->authorize("invite", $quiz);
$userIds = $request->input("ids", []);

if (empty($userIds)) {
return redirect()->back()->withErrors("Brak użytkowników do przypisania.");
}

$quiz->assignedUsers()->attach($userIds);

return redirect()
->back()
->with("status", "Użytkownicy zostali przypisani do quizu.");
}

private function applySorting($query, string $sortField, string $sortDirection): void
{
$allowedFields = ["id", "name", "surname", "school"];
$allowedDirections = ["asc", "desc"];

if (!in_array($sortField, $allowedFields, true)) {
$sortField = "id";
}

if (!in_array($sortDirection, $allowedDirections, true)) {
$sortDirection = "asc";
}

switch ($sortField) {
case "school":
$query->join("schools", "users.school_id", "=", "schools.id")
->orderBy("schools.name", $sortDirection)
->select("users.*");

break;
default:
$query->orderBy($sortField, $sortDirection);

break;
}
}

private function applyFilters($query, ?string $searchText, ?int $schoolId): void
{
if ($schoolId) {
$query->where("school_id", $schoolId);
}

if ($searchText) {
$query->where(function ($query) use ($searchText): void {
$query->where("users.name", "like", "%$searchText%")
->orWhere("users.surname", "like", "%$searchText%");
});
}
}
}
26 changes: 26 additions & 0 deletions app/Http/Requests/InviteQuizRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;

class InviteQuizRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}

/**
* @return array<string, ValidationRule|array|string>
*/
public function rules(): array
{
return [
"ids.*" => ["required", "integer"],
];
}
}
27 changes: 27 additions & 0 deletions app/Http/Resources/InviteResource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class InviteResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
"user" => [
"id" => $this->user->id,
"name" => $this->user->name,
"surname" => $this->user->surname,
"school" => $this->user->school,
],
"points" => $this->points,
];
}
}
34 changes: 34 additions & 0 deletions app/Jobs/SendInviteJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Models\Quiz;
use App\Models\User;
use App\Notifications\InviteUserNotification;
use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendInviteJob implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
use Batchable;

public function __construct(
protected User $user,
protected Quiz $quiz,
) {}

public function handle(): void
{
$this->user->notify(new InviteUserNotification($this->quiz));
}
}
31 changes: 31 additions & 0 deletions app/Jobs/SendPasswordResetJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Models\User;
use App\Notifications\ResetPasswordNotification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendPasswordResetJob implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;

public function __construct(
protected User $user,
protected string $token,
) {}

public function handle(): void
{
$this->user->notify(new ResetPasswordNotification($this->token));
}
}
30 changes: 30 additions & 0 deletions app/Jobs/SendVerificationEmailJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Models\User;
use App\Notifications\SendVerificationEmail;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendVerificationEmailJob implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;

public function __construct(
protected User $user,
) {}

public function handle(): void
{
$this->user->notify(new SendVerificationEmail());
}
}
8 changes: 4 additions & 4 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

namespace App\Models;

use App\Notifications\ResetPasswordNotification;
use App\Notifications\SendVerificationEmail;
use App\Jobs\SendPasswordResetJob;
use App\Jobs\SendVerificationEmailJob;
use Carbon\Carbon;
use Illuminate\Contracts\Auth\CanResetPassword;
use Illuminate\Contracts\Auth\MustVerifyEmail;
Expand Down Expand Up @@ -57,12 +57,12 @@ public function school(): BelongsTo

public function sendEmailVerificationNotification(): void
{
$this->notify(new SendVerificationEmail());
SendVerificationEmailJob::dispatch($this);
}

public function sendPasswordResetNotification($token): void
{
$this->notify(new ResetPasswordNotification($token));
SendPasswordResetJob::dispatch($this, $token);
}

public function quizSubmissions(): HasMany
Expand Down
35 changes: 35 additions & 0 deletions app/Notifications/InviteUserNotification.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

namespace App\Notifications;

use App\Models\Quiz;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class InviteUserNotification extends Notification implements ShouldQueue
{
use Queueable;

public function __construct(
protected Quiz $quiz,
) {}

public function via(object $notifiable): array
{
return ["mail"];
}

public function toMail(object $notifiable): MailMessage
{
return (new MailMessage())
->subject("Zaproszenie do Quizu")
->view("emails.auth.invite-user", [
"user" => $notifiable,
"quiz" => $this->quiz,
]);
}
}
5 changes: 3 additions & 2 deletions app/Notifications/ResetPasswordNotification.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class ResetPasswordNotification extends Notification
class ResetPasswordNotification extends Notification implements ShouldQueue
{
use Queueable;

Expand All @@ -23,7 +24,7 @@ public function via(object $notifiable): array

public function toMail(object $notifiable): MailMessage
{
$resetUrl = url("/auth/password/reset/" . $this->token . "&email=" . urlencode($notifiable->email));
$resetUrl = url("/auth/password/reset/" . $this->token . "?email=" . urlencode($notifiable->email));

return (new MailMessage())
->subject("Resetowanie hasła")
Expand Down
9 changes: 7 additions & 2 deletions app/Policies/QuizPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function assign(User $user, Quiz $quiz): bool

public function viewAdminRanking(User $user, Quiz $quiz): Response
{
return ($quiz->isLocked && $user->hasRole("admin|super_admin")) ? Response::allow() : Response::deny("Nie masz uprawnień do zobaczenia rankingu.");
return ($quiz->isPublished && $user->hasRole("admin|super_admin")) ? Response::allow() : Response::deny("Nie masz uprawnień do zobaczenia rankingu.");
}

public function viewUserRanking(User $user, Quiz $quiz): Response
Expand All @@ -65,6 +65,11 @@ public function viewUserRanking(User $user, Quiz $quiz): Response

public function publish(User $user, Quiz $quiz): bool
{
return $quiz->isLocked && $user->hasRole("admin|super_admin");
return $quiz->isPublished && $user->hasRole("admin|super_admin");
}

public function invite(User $user, Quiz $quiz): Response
{
return $user->hasRole("admin|super_admin") ? (!$quiz->isPublished && $quiz->isLocked) ? Response::allow() : Response::deny("Stan quizu uniemożliwia Ci zaproszenie użytkowników do niego.") : Response::deny("Nie masz uprawnień do zapraszania użytkowników do quizu.");
}
}
Loading
Loading