feat: product team members

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Doar Mihai
2026-10-17 16:04:25 +03:00
co-authored by Claude Sonnet 5.5
parent 768c814762
commit fbb4862454
11 changed files with 321 additions and 5 deletions
+14 -4
View File
@@ -112,7 +112,7 @@ class ProductController extends Controller
'category_id' => 'required|exists:categories,id',
'tags' => 'nullable|array',
'tags.*' => 'exists:tags,id',
] + $this->detailRules());
] + $this->detailRules(Auth::id()));
foreach (array_keys(Product::BADGES) as $badge) {
$validated[$badge] = $request->boolean($badge);
@@ -150,7 +150,7 @@ class ProductController extends Controller
abort(404);
}
$product->load(['user', 'category', 'tags', 'comments.user', 'upvotes', 'bookmarks']);
$product->load(['user', 'category', 'tags', 'members', 'comments.user', 'upvotes', 'bookmarks']);
return view('products.show', compact('product'));
}
@@ -182,7 +182,7 @@ class ProductController extends Controller
'category_id' => 'required|exists:categories,id',
'tags' => 'nullable|array',
'tags.*' => 'exists:tags,id',
] + $this->detailRules());
] + $this->detailRules($product->user_id));
// Badges are locked for non-moderators once the product is approved
if ($product->status !== 'approved' || Auth::user()->hasAnyRole(['moderator', 'admin'])) {
@@ -218,7 +218,7 @@ class ProductController extends Controller
/**
* Validation rules for the product detail fields.
*/
protected function detailRules(): array
protected function detailRules(int $ownerId): array
{
return [
'free_tier' => 'boolean',
@@ -234,6 +234,9 @@ class ProductController extends Controller
'plans.*.price' => 'required|numeric|min:0|max:99999',
'plans.*.period' => ['required', Rule::in(PricingPlan::PERIODS)],
'plans.*.description' => 'nullable|string|max:255',
'members' => 'nullable|array',
'members.*.user_id' => ['required', 'distinct', 'exists:users,id', Rule::notIn([$ownerId])],
'members.*.role' => 'required|string|max:100',
];
}
@@ -254,6 +257,13 @@ class ProductController extends Controller
]);
}
// The submitted member list replaces all existing members
$members = [];
foreach ((array) $request->input('members', []) as $member) {
$members[$member['user_id']] = ['role' => $member['role']];
}
$product->members()->sync($members);
// Only rows belonging to this product may be removed
$ids = array_filter((array) $request->input('remove_screenshots', []));
if ($ids) {
@@ -0,0 +1,34 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class UserSearchController extends Controller
{
/**
* Search users by name (only public identifiers are returned).
*/
public function __invoke(Request $request): JsonResponse
{
$q = trim((string) $request->query('q', ''));
if (mb_strlen($q) < 2) {
return response()->json([]);
}
$escaped = addcslashes($q, '\\%_');
return response()->json(
User::query()
->where('name', 'like', "%{$escaped}%")
->orderBy('name')
->limit(10)
->get(['id', 'name', 'slug'])
->map(fn (User $u) => ['id' => $u->id, 'name' => $u->name, 'slug' => $u->slug])
->values()
);
}
}
+11
View File
@@ -138,6 +138,17 @@ class Product extends Model
return $this->hasMany(PricingPlan::class)->orderBy('position')->orderBy('id');
}
/**
* Get the team members of the product (besides the submitter).
*/
public function members(): BelongsToMany
{
return $this->belongsToMany(User::class, 'product_members')
->withPivot('role')
->withTimestamps()
->orderBy('product_members.id');
}
/**
* Get the user that owns the product.
*/
@@ -0,0 +1,26 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('product_members', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('role', 100);
$table->timestamps();
$table->unique(['product_id', 'user_id']);
});
}
public function down(): void
{
Schema::dropIfExists('product_members');
}
};
@@ -0,0 +1,60 @@
@props(['members' => []])
@php
$initial = collect(old('members', collect($members)->map(fn ($m) => [
'user_id' => $m->id,
'name' => $m->name,
'role' => $m->pivot->role,
])->all()))->map(fn ($m) => [
'user_id' => $m['user_id'] ?? '',
'name' => $m['name'] ?? ('User #' . ($m['user_id'] ?? '')),
'role' => $m['role'] ?? '',
])->values()->all();
$input = 'block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm';
@endphp
<!-- Team members -->
<div x-data="{
members: @js($initial),
q: '',
results: [],
timer: null,
search() {
clearTimeout(this.timer);
if (this.q.trim().length < 2) { this.results = []; return; }
this.timer = setTimeout(async () => {
const res = await fetch(@js(route('users.search')) + '?q=' + encodeURIComponent(this.q.trim()), { headers: { 'Accept': 'application/json' } });
this.results = res.ok ? (await res.json()).filter(u => !this.members.some(m => String(m.user_id) === String(u.id))) : [];
}, 300);
},
add(u) {
this.members.push({ user_id: u.id, name: u.name, role: '' });
this.q = ''; this.results = [];
}
}">
<label class="block text-sm font-medium text-gray-700">Team members</label>
<div class="relative mt-2">
<input type="text" x-model="q" @input="search()" placeholder="Search users by name" autocomplete="off" class="{{ $input }}">
<ul x-show="results.length" x-cloak class="absolute z-10 mt-1 w-full bg-white border border-gray-200 rounded-md shadow-lg">
<template x-for="u in results" :key="u.id">
<li><button type="button" @click="add(u)" class="w-full text-left px-3 py-2 text-sm hover:bg-gray-50" x-text="u.name"></button></li>
</template>
</ul>
</div>
<div class="mt-3 space-y-3">
<template x-for="(member, i) in members" :key="member.user_id">
<div class="grid grid-cols-1 sm:grid-cols-12 gap-2 p-3 border border-gray-200 rounded-md items-center">
<input type="hidden" :name="`members[${i}][user_id]`" :value="member.user_id">
<span class="sm:col-span-4 text-sm text-gray-900" x-text="member.name"></span>
<input type="text" :name="`members[${i}][role]`" x-model="member.role" placeholder="Role (e.g. Designer)" maxlength="100" class="{{ $input }} sm:col-span-7">
<button type="button" @click="members.splice(i, 1)" class="sm:col-span-1 text-sm text-red-600 hover:text-red-800">Remove</button>
</div>
</template>
</div>
@foreach($errors->get('members.*') as $messages)
<p class="mt-2 text-sm text-red-600">{{ $messages[0] }}</p>
@endforeach
@error('members')
<p class="mt-2 text-sm text-red-600">{{ $message }}</p>
@enderror
</div>
@@ -0,0 +1,17 @@
@props(['product'])
<div data-team {{ $attributes->class('bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6') }}>
<h2 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Team</h2>
<ul class="space-y-3">
<li>
<a href="{{ route('profile.show', $product->user) }}" class="font-medium text-gray-900 dark:text-white hover:text-primary-600">{{ $product->user->name }}</a>
<span class="block text-sm text-gray-500 dark:text-gray-400">Author</span>
</li>
@foreach($product->members as $member)
<li data-team-members>
<a href="{{ route('profile.show', $member) }}" class="font-medium text-gray-900 dark:text-white hover:text-primary-600">{{ $member->name }}</a>
<span class="block text-sm text-gray-500 dark:text-gray-400">{{ $member->pivot->role }}</span>
</li>
@endforeach
</ul>
</div>
@@ -209,6 +209,8 @@
<x-product.plans-form />
<x-product.team-form />
<!-- Info Alert -->
<div class="rounded-md bg-blue-50 p-4">
<div class="flex">
+2
View File
@@ -253,6 +253,8 @@
<x-product.plans-form :plans="$product->pricingPlans->toArray()" />
<x-product.team-form :members="$product->members" />
<!-- Info Alert -->
<div class="rounded-md bg-blue-50 p-4">
<div class="flex">
+1 -1
View File
@@ -282,7 +282,7 @@
<!-- Sidebar column -->
<div class="lg:col-span-1 space-y-6">
<!-- slot:team -->
<x-product.team :product="$product" />
</div>
</div>
+4
View File
@@ -11,6 +11,7 @@ use App\Http\Controllers\ProductController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\TagController;
use App\Http\Controllers\UpvoteController;
use App\Http\Controllers\UserSearchController;
use App\Http\Controllers\WaitlistController;
use Illuminate\Support\Facades\Route;
@@ -44,6 +45,9 @@ Route::middleware(['auth'])->group(function () {
Route::put('/products/{product}', [ProductController::class, 'update'])->name('products.update');
Route::delete('/products/{product}', [ProductController::class, 'destroy'])->name('products.destroy');
// User search (team member picker)
Route::get('/users/search', UserSearchController::class)->name('users.search');
// Upvotes
Route::post('/products/{product}/upvote', [UpvoteController::class, 'store'])->name('products.upvote');
Route::get('/upvotes', [UpvoteController::class, 'index'])->name('upvotes.index');
+150
View File
@@ -0,0 +1,150 @@
<?php
use App\Models\Product;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
function teamPayload(array $overrides = []): array
{
return array_merge([
'title' => 'Team Product',
'description' => 'A product description',
'website_url' => 'https://example.com',
'category_id' => makeCategory()->id,
], $overrides);
}
test('user search returns matching users, requires auth', function () {
$this->getJson(route('users.search', ['q' => 'ali']))->assertUnauthorized();
$viewer = userWithRole('user');
$alice = User::factory()->create(['name' => 'Alice Wonder']);
User::factory()->create(['name' => 'Bob Builder']);
$response = $this->actingAs($viewer)->getJson(route('users.search', ['q' => 'lic']))->assertOk();
expect($response->json())->toHaveCount(1);
expect($response->json(0))->toBe(['id' => $alice->id, 'name' => 'Alice Wonder', 'slug' => $alice->slug]);
});
test('user search returns empty for one character queries', function () {
$viewer = userWithRole('user');
User::factory()->create(['name' => 'Alice Wonder']);
$this->actingAs($viewer)->getJson(route('users.search', ['q' => 'a']))->assertOk()->assertExactJson([]);
});
test('submitter adds members with roles', function () {
$user = userWithRole('user');
$a = User::factory()->create();
$b = User::factory()->create();
$this->actingAs($user)->post(route('products.store'), teamPayload([
'members' => [
['user_id' => $a->id, 'role' => 'Designer'],
['user_id' => $b->id, 'role' => 'Engineer'],
],
]))->assertRedirect()->assertSessionHasNoErrors();
$members = Product::firstOrFail()->members;
expect($members->pluck('id')->all())->toEqualCanonicalizing([$a->id, $b->id]);
expect($members->firstWhere('id', $a->id)->pivot->role)->toBe('Designer');
});
test('update replaces members and uses the product owner for the owner rule', function () {
$owner = userWithRole('user');
$admin = userWithRole('admin');
$a = User::factory()->create();
$b = User::factory()->create();
$product = Product::factory()->pending()->create(['user_id' => $owner->id]);
$product->members()->attach($a->id, ['role' => 'Old']);
$this->actingAs($admin)->put(route('products.update', $product), teamPayload([
'category_id' => $product->category_id,
'members' => [['user_id' => $owner->id, 'role' => 'Founder']],
]))->assertSessionHasErrors('members.0.user_id');
expect($product->members()->pluck('users.id')->all())->toBe([$a->id]);
$this->actingAs($admin)->put(route('products.update', $product), teamPayload([
'category_id' => $product->category_id,
'members' => [['user_id' => $admin->id, 'role' => 'Helper'], ['user_id' => $b->id, 'role' => 'New']],
]))->assertRedirect()->assertSessionHasNoErrors();
expect($product->members()->pluck('users.id')->all())->toEqualCanonicalizing([$admin->id, $b->id]);
});
test('submitter cannot be added as a member', function () {
$user = userWithRole('user');
$this->actingAs($user)->post(route('products.store'), teamPayload([
'members' => [['user_id' => $user->id, 'role' => 'Founder']],
]))->assertSessionHasErrors('members.0.user_id');
expect(Product::count())->toBe(0);
});
test('same user cannot be added twice', function () {
$user = userWithRole('user');
$a = User::factory()->create();
$this->actingAs($user)->post(route('products.store'), teamPayload([
'members' => [
['user_id' => $a->id, 'role' => 'One'],
['user_id' => $a->id, 'role' => 'Two'],
],
]))->assertSessionHasErrors();
expect(Product::count())->toBe(0);
expect(\DB::table('product_members')->count())->toBe(0);
});
test('unknown user id fails validation', function () {
$user = userWithRole('user');
$this->actingAs($user)->post(route('products.store'), teamPayload([
'members' => [['user_id' => 999999, 'role' => 'Ghost']],
]))->assertSessionHasErrors('members.0.user_id');
expect(Product::count())->toBe(0);
});
test('missing role fails validation', function () {
$user = userWithRole('user');
$a = User::factory()->create();
$this->actingAs($user)->post(route('products.store'), teamPayload([
'members' => [['user_id' => $a->id, 'role' => '']],
]))->assertSessionHasErrors('members.0.role');
expect(Product::count())->toBe(0);
});
test('deleting a user removes their membership', function () {
$product = Product::factory()->approved()->create();
$member = User::factory()->create();
$product->members()->attach($member->id, ['role' => 'Dev']);
$member->delete();
expect(\DB::table('product_members')->count())->toBe(0);
expect(Product::find($product->id))->not->toBeNull();
});
test('show page lists submitter first as Author then members linking to profiles', function () {
$product = Product::factory()->approved()->create();
$member = User::factory()->create(['name' => 'Zed Member']);
$product->members()->attach($member->id, ['role' => 'Designer']);
$this->get(route('products.show', $product))->assertOk()
->assertSeeInOrder([$product->user->name, 'Author', 'Zed Member', 'Designer'])
->assertSee(route('profile.show', $member), false);
});
test('no members shows only the submitter as author', function () {
$product = Product::factory()->approved()->create();
$this->get(route('products.show', $product))->assertOk()
->assertSee('Author')
->assertDontSee('data-team-members', false);
});