Files
mytodos/resources/views/pages/workspace/⚡members.blade.php
T

335 lines
12 KiB
PHP
Raw Normal View History

2026-10-15 20:59:32 -07:00
<?php
use App\Mail\InvitationMail;
use App\Models\Invitation;
use App\Models\Organization;
use App\Models\User;
use App\OrganizationRole;
use App\WorkspaceType;
use Flux\Flux;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Title;
use Livewire\Component;
new #[Title('Members')] class extends Component
{
public string $inviteEmail = '';
public string $inviteRole = 'member';
/** @var array<int, string> */
public array $memberRoles = [];
public function mount(): void
{
$this->seedMemberRoles();
}
#[Computed]
public function organization(): Organization
{
return auth()->user()->currentOrganization()->firstOrFail();
}
#[Computed]
public function canManage(): bool
{
return auth()->user()->can('manageMembers', $this->organization);
}
/**
* @return Collection<int, User>
*/
#[Computed]
public function members(): Collection
{
return $this->organization->users()->orderBy('name')->get();
}
/**
* @return Collection<int, Invitation>
*/
#[Computed]
public function invitations(): Collection
{
return $this->organization->invitations()->pending()->orderBy('email')->get();
}
/**
* Invite someone to the active workspace by email. The seat limit is a
* hard cap, so no invitation is sent once every seat is taken.
*/
public function inviteMember(): void
{
abort_unless($this->canManage, 403);
$organization = $this->organization;
$validated = $this->validate([
'inviteEmail' => ['required', 'string', 'email', 'max:255'],
'inviteRole' => ['required', Rule::in([OrganizationRole::Admin->value, OrganizationRole::Member->value])],
]);
$email = Str::lower($validated['inviteEmail']);
if ($organization->users()->where('users.email', $email)->exists()) {
$this->addError('inviteEmail', __('That person is already a member of this workspace.'));
return;
}
if (! $organization->canAddMember()) {
$this->addError('inviteEmail', __('This workspace is full, so no more invitations can be sent.'));
return;
}
$invitation = Invitation::updateOrCreate(
[
'inviteable_type' => Organization::class,
'inviteable_id' => $organization->id,
'email' => $email,
],
[
'inviter_id' => auth()->id(),
'role' => $validated['inviteRole'],
'token' => Str::random(64),
'expires_at' => now()->addDays(Invitation::EXPIRY_DAYS),
'accepted_at' => null,
'accepted_by_id' => null,
],
);
Mail::to($email)->send(new InvitationMail($invitation));
$this->reset('inviteEmail', 'inviteRole');
unset($this->invitations);
Flux::toast(variant: 'success', text: __('Invitation sent to :email.', ['email' => $email]));
}
public function updateMemberRole(int $userId, string $role): void
{
abort_unless($this->canManage, 403);
$organization = $this->organization;
if ($this->memberRole($organization, $userId) === OrganizationRole::Owner) {
return;
}
$validated = validator(
['role' => $role],
['role' => ['required', Rule::in([OrganizationRole::Admin->value, OrganizationRole::Member->value])]],
)->validate();
$organization->users()->updateExistingPivot($userId, ['role' => $validated['role']]);
unset($this->members);
Flux::toast(variant: 'success', text: __('Member role updated.'));
}
public function updatedMemberRoles(string $value, string $key): void
{
$this->updateMemberRole((int) $key, $value);
}
public function removeMember(int $userId): void
{
abort_unless($this->canManage, 403);
if ($userId === auth()->id()) {
Flux::toast(variant: 'danger', text: __('You cannot remove yourself from the workspace.'));
return;
}
$organization = $this->organization;
if ($this->memberRole($organization, $userId) === OrganizationRole::Owner) {
return;
}
$organization->users()->detach($userId);
// Move the removed member back to their personal workspace if they
// were currently working in this one.
$user = User::find($userId);
if ($user !== null && (int) $user->current_organization_id === $organization->id) {
$fallback = $user->organizations()
->where('type', WorkspaceType::Personal->value)
->first() ?? $user->organizations()->first();
if ($fallback !== null) {
$user->forceFill(['current_organization_id' => $fallback->id])->save();
}
}
unset($this->members);
$this->seedMemberRoles();
Flux::toast(variant: 'success', text: __('Member removed.'));
}
public function revokeInvitation(int $invitationId): void
{
abort_unless($this->canManage, 403);
$invitation = $this->organization->invitations()->whereKey($invitationId)->firstOrFail();
abort_unless(auth()->user()->can('delete', $invitation), 403);
$invitation->delete();
unset($this->invitations);
Flux::toast(variant: 'success', text: __('Invitation revoked.'));
}
private function memberRole(Organization $organization, int $userId): ?OrganizationRole
{
return OrganizationRole::tryFrom((string) $organization->users()
->where('users.id', $userId)
->withPivot('role')
->first()?->pivot->role);
}
private function seedMemberRoles(): void
{
$this->memberRoles = $this->members
->mapWithKeys(fn (User $member): array => [$member->id => (string) $member->pivot->role])
->all();
}
}; ?>
<div class="flex h-full w-full flex-1 flex-col gap-6">
<div>
<flux:heading size="xl">{{ __('Members') }}</flux:heading>
<flux:text class="mt-1">
{{ __('People with access to the ":name" workspace.', ['name' => $this->organization->name]) }}
</flux:text>
</div>
@php($limit = $this->organization->seatLimit())
<flux:text size="sm" class="text-zinc-500 dark:text-zinc-400" data-test="seat-usage">
@if ($limit === null)
{{ __(':count members', ['count' => $this->organization->memberCount()]) }}
@else
{{ __(':count of :limit seats used', ['count' => $this->organization->memberCount(), 'limit' => $limit]) }}
@endif
</flux:text>
<flux:card>
<div class="space-y-4">
<flux:heading size="sm">{{ __('Current members') }}</flux:heading>
@foreach ($this->members as $member)
@php($role = OrganizationRole::tryFrom((string) $member->pivot->role))
<div class="flex flex-wrap items-center justify-between gap-3" data-test="member-row-{{ $member->id }}">
<div class="flex min-w-0 items-center gap-2">
<flux:text class="truncate">{{ $member->name }}</flux:text>
<flux:text size="sm" class="truncate text-zinc-500 dark:text-zinc-400">{{ $member->email }}</flux:text>
</div>
<div class="flex items-center gap-2">
@if ($role === OrganizationRole::Owner || ! $this->canManage || $member->id === auth()->id())
<flux:badge size="sm" color="{{ $role === OrganizationRole::Owner ? 'blue' : 'zinc' }}" data-test="member-role-{{ $member->id }}">
{{ $role?->label() ?? $member->pivot->role }}
</flux:badge>
@else
<flux:select
size="sm"
wire:model.live="memberRoles.{{ $member->id }}"
data-test="member-role-select-{{ $member->id }}"
>
@foreach ([OrganizationRole::Admin, OrganizationRole::Member] as $option)
<flux:select.option value="{{ $option->value }}">{{ $option->label() }}</flux:select.option>
@endforeach
</flux:select>
@if ($role !== OrganizationRole::Owner)
<flux:button
size="sm"
variant="ghost"
icon="trash"
wire:click="removeMember({{ $member->id }})"
data-test="remove-member-{{ $member->id }}"
/>
@endif
@endif
</div>
</div>
@endforeach
</div>
</flux:card>
@if ($this->canManage)
@if ($this->organization->canAddMember())
<flux:card>
<form wire:submit="inviteMember" class="space-y-4">
<flux:heading size="sm">{{ __('Invite a member') }}</flux:heading>
<div class="flex flex-wrap items-start gap-3">
<div class="min-w-56 flex-1">
<flux:input
wire:model="inviteEmail"
type="email"
placeholder="name@example.com"
data-test="member-invite-email-input"
/>
<flux:error name="inviteEmail" />
</div>
<div>
<flux:select wire:model="inviteRole" data-test="member-invite-role-select">
@foreach ([OrganizationRole::Admin, OrganizationRole::Member] as $option)
<flux:select.option value="{{ $option->value }}">{{ $option->label() }}</flux:select.option>
@endforeach
</flux:select>
<flux:error name="inviteRole" />
</div>
<flux:button type="submit" variant="primary" icon="paper-airplane" data-test="invite-member-button">
{{ __('Send invite') }}
</flux:button>
</div>
</form>
</flux:card>
@else
<flux:callout variant="warning" icon="users" data-test="workspace-full-notice">
{{ __('Every seat in this workspace is taken, so no more members can be invited.') }}
</flux:callout>
@endif
@if ($this->invitations->isNotEmpty())
<flux:card>
<div class="space-y-4">
<flux:heading size="sm">{{ __('Pending invitations') }}</flux:heading>
@foreach ($this->invitations as $invitation)
<div class="flex flex-wrap items-center justify-between gap-3" data-test="member-invitation-row-{{ $invitation->id }}">
<div class="flex min-w-0 items-center gap-2">
<flux:text class="truncate">{{ $invitation->email }}</flux:text>
<flux:badge size="sm">{{ $invitation->roleLabel() }}</flux:badge>
</div>
<flux:button
size="sm"
variant="ghost"
icon="x-mark"
wire:click="revokeInvitation({{ $invitation->id }})"
data-test="revoke-member-invitation-{{ $invitation->id }}"
>
{{ __('Revoke') }}
</flux:button>
</div>
@endforeach
</div>
</flux:card>
@endif
@endif
</div>