engagement system

This commit is contained in:
2026-02-06 15:13:20 +02:00
parent 2e1ce0d93b
commit 7a99c3eb59
15 changed files with 1079 additions and 2 deletions
@@ -0,0 +1,43 @@
<?php
namespace App\Http\Controllers;
use App\Models\Bookmark;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class BookmarkController extends Controller
{
/**
* Toggle bookmark for a product.
*/
public function store(Product $product): JsonResponse
{
$user = Auth::user();
// Check if user already bookmarked
$existingBookmark = Bookmark::where('user_id', $user->id)
->where('product_id', $product->id)
->first();
if ($existingBookmark) {
// Remove bookmark
$existingBookmark->delete();
$bookmarked = false;
} else {
// Add bookmark
Bookmark::create([
'user_id' => $user->id,
'product_id' => $product->id,
]);
$bookmarked = true;
}
return response()->json([
'success' => true,
'bookmarked' => $bookmarked,
]);
}
}
@@ -0,0 +1,43 @@
<?php
namespace App\Http\Controllers;
use App\Models\Comment;
use App\Models\Product;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
class CommentController extends Controller
{
/**
* Store a newly created comment.
*/
public function store(Request $request, Product $product): RedirectResponse
{
$validated = $request->validate([
'body' => 'required|string|max:1000',
]);
Comment::create([
'user_id' => Auth::id(),
'product_id' => $product->id,
'body' => $validated['body'],
]);
return back()->with('success', 'Comment posted successfully!');
}
/**
* Remove the specified comment.
*/
public function destroy(Comment $comment): RedirectResponse
{
Gate::authorize('delete-comment', $comment);
$comment->delete();
return back()->with('success', 'Comment deleted successfully!');
}
}
+1 -1
View File
@@ -79,7 +79,7 @@ class ProductController extends Controller
abort(404); abort(404);
} }
$product->load(['user', 'category']); $product->load(['user', 'category', 'comments.user', 'upvotes', 'bookmarks']);
return view('products.show', compact('product')); return view('products.show', compact('product'));
} }
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use App\Models\Upvote;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class UpvoteController extends Controller
{
/**
* Toggle upvote for a product.
*/
public function store(Product $product): JsonResponse
{
$user = Auth::user();
// Check if user already upvoted
$existingUpvote = Upvote::where('user_id', $user->id)
->where('product_id', $product->id)
->first();
if ($existingUpvote) {
// Remove upvote
$existingUpvote->delete();
$upvoted = false;
} else {
// Add upvote
Upvote::create([
'user_id' => $user->id,
'product_id' => $product->id,
]);
$upvoted = true;
}
// Get fresh upvotes count
$upvotesCount = $product->upvotes()->count();
return response()->json([
'success' => true,
'upvoted' => $upvoted,
'upvotesCount' => $upvotesCount,
]);
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Bookmark extends Model
{
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'user_id',
'product_id',
];
/**
* Get the user that owns the bookmark.
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* Get the product that owns the bookmark.
*/
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Comment extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'user_id',
'product_id',
'body',
];
/**
* Get the user that owns the comment.
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* Get the product that owns the comment.
*/
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}
+64
View File
@@ -197,4 +197,68 @@ class Product extends Model
'approved_at' => null, 'approved_at' => null,
]); ]);
} }
/**
* Get the upvotes for the product.
*/
public function upvotes()
{
return $this->hasMany(Upvote::class);
}
/**
* Get the comments for the product.
*/
public function comments()
{
return $this->hasMany(Comment::class)->latest();
}
/**
* Get the bookmarks for the product.
*/
public function bookmarks()
{
return $this->hasMany(Bookmark::class);
}
/**
* Check if a user has upvoted the product.
*/
public function isUpvotedBy(?User $user): bool
{
if (!$user) {
return false;
}
return $this->upvotes()->where('user_id', $user->id)->exists();
}
/**
* Check if a user has bookmarked the product.
*/
public function isBookmarkedBy(?User $user): bool
{
if (!$user) {
return false;
}
return $this->bookmarks()->where('user_id', $user->id)->exists();
}
/**
* Get the upvotes count for the product.
*/
public function getUpvotesCountAttribute(): int
{
return $this->upvotes()->count();
}
/**
* Get the comments count for the product.
*/
public function getCommentsCountAttribute(): int
{
return $this->comments()->count();
}
} }
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Upvote extends Model
{
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'user_id',
'product_id',
];
/**
* Get the user that owns the upvote.
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* Get the product that owns the upvote.
*/
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}
+24
View File
@@ -120,4 +120,28 @@ class User extends Authenticatable
{ {
return $this->hasMany(Product::class); return $this->hasMany(Product::class);
} }
/**
* Get the upvotes for the user.
*/
public function upvotes(): HasMany
{
return $this->hasMany(Upvote::class);
}
/**
* Get the comments for the user.
*/
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
/**
* Get the bookmarks for the user.
*/
public function bookmarks(): HasMany
{
return $this->hasMany(Bookmark::class);
}
} }
@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('upvotes', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('product_id')->constrained()->onDelete('cascade');
$table->timestamp('created_at')->useCurrent();
// Unique composite index to prevent duplicate upvotes
$table->unique(['user_id', 'product_id']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('upvotes');
}
};
@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('product_id')->constrained()->onDelete('cascade');
$table->text('body');
$table->timestamps();
$table->index('product_id');
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('comments');
}
};
@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('bookmarks', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('product_id')->constrained()->onDelete('cascade');
$table->timestamp('created_at')->useCurrent();
// Unique composite index to prevent duplicate bookmarks
$table->unique(['user_id', 'product_id']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('bookmarks');
}
};
+179 -1
View File
@@ -28,7 +28,31 @@
@endif @endif
</p> </p>
</div> </div>
<div> <div class="d-flex align-items-center gap-2">
@auth
<!-- Upvote Button -->
<button
class="btn btn-outline-primary upvote-btn {{ $product->isUpvotedBy(auth()->user()) ? 'active' : '' }}"
data-product-id="{{ $product->id }}"
data-upvoted="{{ $product->isUpvotedBy(auth()->user()) ? 'true' : 'false' }}">
<i class="bi bi-arrow-up-circle"></i>
<span class="upvote-count">{{ $product->upvotes()->count() }}</span>
</button>
<!-- Bookmark Button -->
<button
class="btn btn-outline-secondary bookmark-btn {{ $product->isBookmarkedBy(auth()->user()) ? 'active' : '' }}"
data-product-id="{{ $product->id }}"
data-bookmarked="{{ $product->isBookmarkedBy(auth()->user()) ? 'true' : 'false' }}">
<i class="bi {{ $product->isBookmarkedBy(auth()->user()) ? 'bi-bookmark-fill' : 'bi-bookmark' }}"></i>
</button>
@else
<div class="text-muted">
<i class="bi bi-arrow-up-circle"></i>
<span>{{ $product->upvotes()->count() }}</span> upvotes
</div>
@endauth
@can('edit-product', $product) @can('edit-product', $product)
<a href="{{ route('products.edit', $product) }}" class="btn btn-sm btn-outline-primary">Edit</a> <a href="{{ route('products.edit', $product) }}" class="btn btn-sm btn-outline-primary">Edit</a>
@endcan @endcan
@@ -84,6 +108,77 @@
</div> </div>
</div> </div>
<!-- Comments Section -->
<div class="card mt-3">
<div class="card-header">
<h5 class="mb-0">Comments ({{ $product->comments()->count() }})</h5>
</div>
<div class="card-body">
@auth
<!-- Comment Form -->
<form action="{{ route('products.comments.store', $product) }}" method="POST" class="mb-4">
@csrf
<div class="mb-3">
<textarea
class="form-control @error('body') is-invalid @enderror"
name="body"
rows="3"
placeholder="Share your thoughts about this product..."
required
maxlength="1000">{{ old('body') }}</textarea>
@error('body')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
<button type="submit" class="btn btn-primary">Post Comment</button>
</form>
@else
<p class="text-muted">
<a href="{{ route('login') }}">Login</a> to post a comment.
</p>
@endauth
<!-- Comments List -->
@forelse($product->comments as $comment)
<div class="border-top pt-3 mt-3">
<div class="d-flex">
<div class="me-3">
@if($comment->user->avatar_url)
<img src="{{ $comment->user->avatar_url }}" alt="{{ $comment->user->name }}" class="rounded-circle" style="width: 40px; height: 40px; object-fit: cover;">
@else
<div class="bg-secondary text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
{{ strtoupper(substr($comment->user->name, 0, 1)) }}
</div>
@endif
</div>
<div class="flex-grow-1">
<div class="d-flex justify-content-between align-items-start">
<div>
<strong>{{ $comment->user->name }}</strong>
<span class="text-muted small">· {{ $comment->created_at->diffForHumans() }}</span>
</div>
@can('delete-comment', $comment)
<form action="{{ route('comments.destroy', $comment) }}" method="POST" class="d-inline">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-sm btn-link text-danger p-0" onclick="return confirm('Are you sure you want to delete this comment?');">
Delete
</button>
</form>
@endcan
</div>
<p class="mb-0 mt-2">{{ $comment->body }}</p>
</div>
</div>
</div>
@empty
<p class="text-muted text-center py-4">No comments yet. Be the first to comment!</p>
@endforelse
</div>
</div>
<!-- Moderator Actions --> <!-- Moderator Actions -->
@can('approve-product') @can('approve-product')
@if($product->isPending() || $product->isRejected()) @if($product->isPending() || $product->isRejected())
@@ -111,4 +206,87 @@
</div> </div>
</div> </div>
</div> </div>
@push('styles')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
@endpush
@push('scripts')
<script>
// Upvote functionality
document.querySelectorAll('.upvote-btn').forEach(button => {
button.addEventListener('click', async function() {
const productId = this.getAttribute('data-product-id');
const isUpvoted = this.getAttribute('data-upvoted') === 'true';
try {
const response = await fetch(`/products/${productId}/upvote`, {
method: 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
const data = await response.json();
if (data.success) {
// Update button state
this.setAttribute('data-upvoted', data.upvoted ? 'true' : 'false');
if (data.upvoted) {
this.classList.add('active');
} else {
this.classList.remove('active');
}
// Update count
this.querySelector('.upvote-count').textContent = data.upvotesCount;
}
} catch (error) {
console.error('Error toggling upvote:', error);
}
});
});
// Bookmark functionality
document.querySelectorAll('.bookmark-btn').forEach(button => {
button.addEventListener('click', async function() {
const productId = this.getAttribute('data-product-id');
const isBookmarked = this.getAttribute('data-bookmarked') === 'true';
try {
const response = await fetch(`/products/${productId}/bookmark`, {
method: 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
'Content-Type': 'application/json',
'Accept': 'application/json',
},
});
const data = await response.json();
if (data.success) {
// Update button state
this.setAttribute('data-bookmarked', data.bookmarked ? 'true' : 'false');
const icon = this.querySelector('i');
if (data.bookmarked) {
this.classList.add('active');
icon.classList.remove('bi-bookmark');
icon.classList.add('bi-bookmark-fill');
} else {
this.classList.remove('active');
icon.classList.remove('bi-bookmark-fill');
icon.classList.add('bi-bookmark');
}
}
} catch (error) {
console.error('Error toggling bookmark:', error);
}
});
});
</script>
@endpush
@endsection @endsection
+13
View File
@@ -1,7 +1,10 @@
<?php <?php
use App\Http\Controllers\BookmarkController;
use App\Http\Controllers\CommentController;
use App\Http\Controllers\ProductController; use App\Http\Controllers\ProductController;
use App\Http\Controllers\ProfileController; use App\Http\Controllers\ProfileController;
use App\Http\Controllers\UpvoteController;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::get('/', function () { Route::get('/', function () {
@@ -31,6 +34,16 @@ Route::middleware(['auth'])->group(function () {
Route::get('/products/{product}/edit', [ProductController::class, 'edit'])->name('products.edit'); Route::get('/products/{product}/edit', [ProductController::class, 'edit'])->name('products.edit');
Route::put('/products/{product}', [ProductController::class, 'update'])->name('products.update'); Route::put('/products/{product}', [ProductController::class, 'update'])->name('products.update');
Route::delete('/products/{product}', [ProductController::class, 'destroy'])->name('products.destroy'); Route::delete('/products/{product}', [ProductController::class, 'destroy'])->name('products.destroy');
// Upvotes
Route::post('/products/{product}/upvote', [UpvoteController::class, 'store'])->name('products.upvote');
// Comments
Route::post('/products/{product}/comments', [CommentController::class, 'store'])->name('products.comments.store');
Route::delete('/comments/{comment}', [CommentController::class, 'destroy'])->name('comments.destroy');
// Bookmarks
Route::post('/products/{product}/bookmark', [BookmarkController::class, 'store'])->name('products.bookmark');
}); });
// Admin/Moderator Product Management Routes // Admin/Moderator Product Management Routes
+448
View File
@@ -0,0 +1,448 @@
<?php
use App\Models\Bookmark;
use App\Models\Category;
use App\Models\Comment;
use App\Models\Product;
use App\Models\Role;
use App\Models\Upvote;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
// Create roles
$this->userRole = Role::create([
'name' => 'User',
'slug' => 'user',
'description' => 'Regular user',
]);
$this->moderatorRole = Role::create([
'name' => 'Moderator',
'slug' => 'moderator',
'description' => 'Moderator',
]);
$this->adminRole = Role::create([
'name' => 'Admin',
'slug' => 'admin',
'description' => 'Admin',
]);
// Create category
$this->category = Category::create([
'name' => 'Test Category',
'slug' => 'test-category',
'description' => 'Test description',
]);
});
// ============ UPVOTE TESTS ============
test('authenticated users can upvote a product', function () {
$user = User::factory()->create();
$user->roles()->attach($this->userRole);
$owner = User::factory()->create();
$owner->roles()->attach($this->userRole);
$product = Product::create([
'title' => 'Test Product',
'slug' => 'test-product',
'description' => 'Test description',
'website_url' => 'https://example.com',
'user_id' => $owner->id,
'category_id' => $this->category->id,
'status' => 'approved',
]);
$response = $this->actingAs($user)->postJson(route('products.upvote', $product));
$response->assertStatus(200);
$response->assertJson([
'success' => true,
'upvoted' => true,
'upvotesCount' => 1,
]);
$this->assertDatabaseHas('upvotes', [
'user_id' => $user->id,
'product_id' => $product->id,
]);
});
test('authenticated users can remove their upvote', function () {
$user = User::factory()->create();
$user->roles()->attach($this->userRole);
$owner = User::factory()->create();
$owner->roles()->attach($this->userRole);
$product = Product::create([
'title' => 'Test Product',
'slug' => 'test-product',
'description' => 'Test description',
'website_url' => 'https://example.com',
'user_id' => $owner->id,
'category_id' => $this->category->id,
'status' => 'approved',
]);
// First upvote
Upvote::create([
'user_id' => $user->id,
'product_id' => $product->id,
]);
// Remove upvote
$response = $this->actingAs($user)->postJson(route('products.upvote', $product));
$response->assertStatus(200);
$response->assertJson([
'success' => true,
'upvoted' => false,
'upvotesCount' => 0,
]);
$this->assertDatabaseMissing('upvotes', [
'user_id' => $user->id,
'product_id' => $product->id,
]);
});
test('guests cannot upvote products', function () {
$owner = User::factory()->create();
$owner->roles()->attach($this->userRole);
$product = Product::create([
'title' => 'Test Product',
'slug' => 'test-product',
'description' => 'Test description',
'website_url' => 'https://example.com',
'user_id' => $owner->id,
'category_id' => $this->category->id,
'status' => 'approved',
]);
$response = $this->postJson(route('products.upvote', $product));
$response->assertStatus(401);
});
test('users cannot upvote the same product twice', function () {
$user = User::factory()->create();
$user->roles()->attach($this->userRole);
$owner = User::factory()->create();
$owner->roles()->attach($this->userRole);
$product = Product::create([
'title' => 'Test Product',
'slug' => 'test-product',
'description' => 'Test description',
'website_url' => 'https://example.com',
'user_id' => $owner->id,
'category_id' => $this->category->id,
'status' => 'approved',
]);
// First upvote
$this->actingAs($user)->postJson(route('products.upvote', $product));
// Second upvote should toggle (remove)
$response = $this->actingAs($user)->postJson(route('products.upvote', $product));
$response->assertJson(['upvoted' => false]);
expect(Upvote::where('user_id', $user->id)->where('product_id', $product->id)->count())->toBe(0);
});
// ============ COMMENT TESTS ============
test('authenticated users can comment on products', function () {
$user = User::factory()->create();
$user->roles()->attach($this->userRole);
$owner = User::factory()->create();
$owner->roles()->attach($this->userRole);
$product = Product::create([
'title' => 'Test Product',
'slug' => 'test-product',
'description' => 'Test description',
'website_url' => 'https://example.com',
'user_id' => $owner->id,
'category_id' => $this->category->id,
'status' => 'approved',
]);
$response = $this->actingAs($user)->post(route('products.comments.store', $product), [
'body' => 'This is a great product!',
]);
$response->assertRedirect();
$response->assertSessionHas('success');
$this->assertDatabaseHas('comments', [
'user_id' => $user->id,
'product_id' => $product->id,
'body' => 'This is a great product!',
]);
});
test('guests cannot comment on products', function () {
$owner = User::factory()->create();
$owner->roles()->attach($this->userRole);
$product = Product::create([
'title' => 'Test Product',
'slug' => 'test-product',
'description' => 'Test description',
'website_url' => 'https://example.com',
'user_id' => $owner->id,
'category_id' => $this->category->id,
'status' => 'approved',
]);
$response = $this->post(route('products.comments.store', $product), [
'body' => 'This is a great product!',
]);
$response->assertRedirect(route('login'));
});
test('comment body is required', function () {
$user = User::factory()->create();
$user->roles()->attach($this->userRole);
$owner = User::factory()->create();
$owner->roles()->attach($this->userRole);
$product = Product::create([
'title' => 'Test Product',
'slug' => 'test-product',
'description' => 'Test description',
'website_url' => 'https://example.com',
'user_id' => $owner->id,
'category_id' => $this->category->id,
'status' => 'approved',
]);
$response = $this->actingAs($user)->post(route('products.comments.store', $product), [
'body' => '',
]);
$response->assertSessionHasErrors('body');
});
test('comment body cannot exceed 1000 characters', function () {
$user = User::factory()->create();
$user->roles()->attach($this->userRole);
$owner = User::factory()->create();
$owner->roles()->attach($this->userRole);
$product = Product::create([
'title' => 'Test Product',
'slug' => 'test-product',
'description' => 'Test description',
'website_url' => 'https://example.com',
'user_id' => $owner->id,
'category_id' => $this->category->id,
'status' => 'approved',
]);
$response = $this->actingAs($user)->post(route('products.comments.store', $product), [
'body' => str_repeat('a', 1001),
]);
$response->assertSessionHasErrors('body');
});
test('comment owners can delete their comments', function () {
$user = User::factory()->create();
$user->roles()->attach($this->userRole);
$owner = User::factory()->create();
$owner->roles()->attach($this->userRole);
$product = Product::create([
'title' => 'Test Product',
'slug' => 'test-product',
'description' => 'Test description',
'website_url' => 'https://example.com',
'user_id' => $owner->id,
'category_id' => $this->category->id,
'status' => 'approved',
]);
$comment = Comment::create([
'user_id' => $user->id,
'product_id' => $product->id,
'body' => 'Test comment',
]);
$response = $this->actingAs($user)->delete(route('comments.destroy', $comment));
$response->assertRedirect();
$response->assertSessionHas('success');
$this->assertDatabaseMissing('comments', ['id' => $comment->id]);
});
test('non-owners cannot delete comments', function () {
$user1 = User::factory()->create();
$user1->roles()->attach($this->userRole);
$user2 = User::factory()->create();
$user2->roles()->attach($this->userRole);
$owner = User::factory()->create();
$owner->roles()->attach($this->userRole);
$product = Product::create([
'title' => 'Test Product',
'slug' => 'test-product',
'description' => 'Test description',
'website_url' => 'https://example.com',
'user_id' => $owner->id,
'category_id' => $this->category->id,
'status' => 'approved',
]);
$comment = Comment::create([
'user_id' => $user1->id,
'product_id' => $product->id,
'body' => 'Test comment',
]);
$response = $this->actingAs($user2)->delete(route('comments.destroy', $comment));
$response->assertStatus(403);
});
test('moderators can delete any comment', function () {
$moderator = User::factory()->create();
$moderator->roles()->attach($this->moderatorRole);
$user = User::factory()->create();
$user->roles()->attach($this->userRole);
$owner = User::factory()->create();
$owner->roles()->attach($this->userRole);
$product = Product::create([
'title' => 'Test Product',
'slug' => 'test-product',
'description' => 'Test description',
'website_url' => 'https://example.com',
'user_id' => $owner->id,
'category_id' => $this->category->id,
'status' => 'approved',
]);
$comment = Comment::create([
'user_id' => $user->id,
'product_id' => $product->id,
'body' => 'Test comment',
]);
$response = $this->actingAs($moderator)->delete(route('comments.destroy', $comment));
$response->assertRedirect();
$response->assertSessionHas('success');
$this->assertDatabaseMissing('comments', ['id' => $comment->id]);
});
// ============ BOOKMARK TESTS ============
test('authenticated users can bookmark a product', function () {
$user = User::factory()->create();
$user->roles()->attach($this->userRole);
$owner = User::factory()->create();
$owner->roles()->attach($this->userRole);
$product = Product::create([
'title' => 'Test Product',
'slug' => 'test-product',
'description' => 'Test description',
'website_url' => 'https://example.com',
'user_id' => $owner->id,
'category_id' => $this->category->id,
'status' => 'approved',
]);
$response = $this->actingAs($user)->postJson(route('products.bookmark', $product));
$response->assertStatus(200);
$response->assertJson([
'success' => true,
'bookmarked' => true,
]);
$this->assertDatabaseHas('bookmarks', [
'user_id' => $user->id,
'product_id' => $product->id,
]);
});
test('authenticated users can remove their bookmark', function () {
$user = User::factory()->create();
$user->roles()->attach($this->userRole);
$owner = User::factory()->create();
$owner->roles()->attach($this->userRole);
$product = Product::create([
'title' => 'Test Product',
'slug' => 'test-product',
'description' => 'Test description',
'website_url' => 'https://example.com',
'user_id' => $owner->id,
'category_id' => $this->category->id,
'status' => 'approved',
]);
// First bookmark
Bookmark::create([
'user_id' => $user->id,
'product_id' => $product->id,
]);
// Remove bookmark
$response = $this->actingAs($user)->postJson(route('products.bookmark', $product));
$response->assertStatus(200);
$response->assertJson([
'success' => true,
'bookmarked' => false,
]);
$this->assertDatabaseMissing('bookmarks', [
'user_id' => $user->id,
'product_id' => $product->id,
]);
});
test('guests cannot bookmark products', function () {
$owner = User::factory()->create();
$owner->roles()->attach($this->userRole);
$product = Product::create([
'title' => 'Test Product',
'slug' => 'test-product',
'description' => 'Test description',
'website_url' => 'https://example.com',
'user_id' => $owner->id,
'category_id' => $this->category->id,
'status' => 'approved',
]);
$response = $this->postJson(route('products.bookmark', $product));
$response->assertStatus(401);
});