bugfix: a new flow added to disable staffs and free the used seats.

This commit is contained in:
2026-05-18 14:56:07 +03:30
parent 81fe14823f
commit 4487d3260b
5 changed files with 184 additions and 23 deletions

View File

@@ -756,7 +756,18 @@ export class AuthService {
throw new UnauthorizedException('Access denied to this organization'); throw new UnauthorizedException('Access denied to this organization');
} }
if (!membership.isOwner && !membership.isActive) { if (!membership.isOwner && !membership.isActive) {
throw new UnauthorizedException('Your invitation is still pending activation'); const acceptedInvite = await this.prisma.staffInvitation.findFirst({
where: {
membershipId: membership.id,
acceptedAt: { not: null },
},
select: { id: true },
});
throw new UnauthorizedException(
acceptedInvite
? 'Your access to this organization has been disabled.'
: 'Your invitation is still pending activation.',
);
} }
// 2. Build payload WITH org context // 2. Build payload WITH org context

View File

@@ -80,6 +80,19 @@ export class StaffController {
return this.staffService.updateMember(req.user.id, organizationId, membershipId, dto); return this.staffService.updateMember(req.user.id, organizationId, membershipId, dto);
} }
@Patch('members/:membershipId/disable')
@UseGuards(JwtAuthGuard)
@ApiOperation({
summary: 'Disable staff member (frees a seat; member cannot access this organization)',
})
disableMember(
@Req() req: { user: { id: string; organizationId?: string } },
@Param('membershipId') membershipId: string,
) {
const organizationId = this.staffService.getOrganizationIdFromUser(req.user);
return this.staffService.disableMember(req.user.id, organizationId, membershipId);
}
@Delete('members/:membershipId') @Delete('members/:membershipId')
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Remove staff member from organization' }) @ApiOperation({ summary: 'Remove staff member from organization' })

View File

@@ -399,6 +399,44 @@ export class StaffService {
return { success: true, message: 'Member updated' }; return { success: true, message: 'Member updated' };
} }
async disableMember(actorUserId: string, organizationId: string, membershipId: string) {
const actor = await this.getActorMembership(actorUserId, organizationId);
if (!actor || !this.canEditStaff(actor)) {
throw new ForbiddenException('You cannot manage staff');
}
const target = await this.prisma.membership.findFirst({
where: { id: membershipId, organizationId },
});
if (!target) {
throw new NotFoundException('Member not found');
}
if (target.isOwner) {
throw new ForbiddenException('Cannot disable the organization owner');
}
if (actorUserId === target.userId) {
throw new BadRequestException('You cannot disable your own access');
}
if (!target.isActive) {
throw new BadRequestException('This member is already disabled or pending activation');
}
await this.prisma.membership.update({
where: { id: membershipId },
data: { isActive: false },
});
await this.prisma.session.deleteMany({
where: { userId: target.userId },
});
return {
success: true,
message: 'Member disabled. Their seat is now available for another invite.',
};
}
async removeMember(actorUserId: string, organizationId: string, membershipId: string) { async removeMember(actorUserId: string, organizationId: string, membershipId: string) {
const actor = await this.getActorMembership(actorUserId, organizationId); const actor = await this.getActorMembership(actorUserId, organizationId);
if (!actor || !this.canEditStaff(actor)) { if (!actor || !this.canEditStaff(actor)) {
@@ -435,11 +473,12 @@ export class StaffService {
isOwner: boolean; isOwner: boolean;
isActive: boolean; isActive: boolean;
invitations: { acceptedAt: Date | null; revokedAt: Date | null; expiresAt: Date }[]; invitations: { acceptedAt: Date | null; revokedAt: Date | null; expiresAt: Date }[];
}): 'ACTIVE' | 'PENDING' | 'EXPIRED' { }): 'ACTIVE' | 'PENDING' | 'EXPIRED' | 'DISABLED' {
if (m.isOwner || m.isActive) return 'ACTIVE'; if (m.isOwner) return 'ACTIVE';
if (m.isActive) return 'ACTIVE';
const invitation = m.invitations[0]; const invitation = m.invitations[0];
if (!invitation) return 'EXPIRED'; if (invitation?.acceptedAt) return 'DISABLED';
if (invitation.acceptedAt) return 'ACTIVE'; if (!invitation) return 'DISABLED';
if (invitation.revokedAt) return 'EXPIRED'; if (invitation.revokedAt) return 'EXPIRED';
return invitation.expiresAt.getTime() > Date.now() ? 'PENDING' : 'EXPIRED'; return invitation.expiresAt.getTime() > Date.now() ? 'PENDING' : 'EXPIRED';
} }

View File

@@ -16,7 +16,7 @@ import {
formatAccessSummary, formatAccessSummary,
type FeaturePermState, type FeaturePermState,
} from '../../../components/staff/staff-permission-form'; } from '../../../components/staff/staff-permission-form';
import { Pencil, Trash2, Copy, Check, X } from 'lucide-react'; import { Pencil, Trash2, Copy, Check, X, UserX } from 'lucide-react';
import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton'; import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton';
import { useAuth } from '@/lib/hooks/useAuth'; import { useAuth } from '@/lib/hooks/useAuth';
import { staffApi, type StaffMemberDto } from '@/lib/api/staff'; import { staffApi, type StaffMemberDto } from '@/lib/api/staff';
@@ -57,7 +57,14 @@ function writeStoredInviteLinks(orgId: string, links: Record<string, StoredInvit
} }
function canShareStaffInviteLink(member: StaffMemberDto): boolean { function canShareStaffInviteLink(member: StaffMemberDto): boolean {
return !member.isOwner && member.invitationStatus !== 'ACTIVE'; return (
!member.isOwner &&
(member.invitationStatus === 'PENDING' || member.invitationStatus === 'EXPIRED')
);
}
function canDisableStaff(member: StaffMemberDto): boolean {
return !member.isOwner && member.isActive;
} }
function PermissionGrid({ function PermissionGrid({
@@ -152,6 +159,8 @@ export default function StaffPage() {
const [editName, setEditName] = useState(''); const [editName, setEditName] = useState('');
const [editPerms, setEditPerms] = useState(() => emptyFeaturePermissionState()); const [editPerms, setEditPerms] = useState(() => emptyFeaturePermissionState());
const [editLoading, setEditLoading] = useState(false); const [editLoading, setEditLoading] = useState(false);
const [disableTarget, setDisableTarget] = useState<StaffMemberDto | null>(null);
const [disablingMembershipId, setDisablingMembershipId] = useState<string | null>(null);
const canEdit = useMemo(() => canEditStaff(currentOrganization), [currentOrganization]); const canEdit = useMemo(() => canEditStaff(currentOrganization), [currentOrganization]);
const hasActivePlan = Boolean(currentOrganization?.plan); const hasActivePlan = Boolean(currentOrganization?.plan);
@@ -322,20 +331,24 @@ export default function StaffPage() {
} }
} }
async function removeMember(m: StaffMemberDto) { function handleDeleteMember() {
if (m.isOwner) return; toast.showError('Delete is not implemented yet.');
if (m.userId === user?.id) {
if (!confirm('Remove yourself from this organization? You will lose access.')) return;
} else {
if (!confirm(`Remove ${m.name} from this organization?`)) return;
} }
async function confirmDisableMember() {
if (!disableTarget || !canDisableStaff(disableTarget)) return;
setDisablingMembershipId(disableTarget.id);
toast.setError(''); toast.setError('');
try { try {
await staffApi.removeMember(m.id); await staffApi.disableMember(disableTarget.id);
toast.showSuccess('Member removed.'); toast.showSuccess(`${disableTarget.name} was disabled. A seat is now available.`);
setDisableTarget(null);
await load(); await load();
} catch (e) { } catch (e) {
toast.showError(formatApiErrorMessage(e, 'Failed to remove member.')); toast.showError(formatApiErrorMessage(e, 'Failed to disable member.'));
} finally {
setDisablingMembershipId(null);
} }
} }
@@ -477,7 +490,9 @@ export default function StaffPage() {
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">Role</th> <th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">Role</th>
<th className="px-6 py-3 text-center text-xs font-medium text-text-muted uppercase tracking-wider">Status</th> <th className="px-6 py-3 text-center text-xs font-medium text-text-muted uppercase tracking-wider">Status</th>
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">Access</th> <th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">Access</th>
<th className="px-6 py-3 text-right text-xs font-medium text-text-muted uppercase tracking-wider w-28">Actions</th> <th className="px-6 py-3 text-center text-xs font-medium text-text-muted uppercase tracking-wider w-36">
Action
</th>
</tr> </tr>
} }
body={ body={
@@ -498,6 +513,8 @@ export default function StaffPage() {
<Badge variant="success">Active</Badge> <Badge variant="success">Active</Badge>
) : m.invitationStatus === 'PENDING' ? ( ) : m.invitationStatus === 'PENDING' ? (
<Badge variant="warning">Pending</Badge> <Badge variant="warning">Pending</Badge>
) : m.invitationStatus === 'DISABLED' ? (
<Badge variant="default">Disabled</Badge>
) : ( ) : (
<Badge variant="danger">Expired</Badge> <Badge variant="danger">Expired</Badge>
)} )}
@@ -511,9 +528,9 @@ export default function StaffPage() {
</span> </span>
)} )}
</td> </td>
<td className="px-6 py-1.5 align-middle"> <td className="px-6 py-1.5 align-middle text-center">
{!m.isOwner && ( {!m.isOwner && (
<div className="flex min-h-[36px] items-center justify-end gap-1"> <div className="flex min-h-[36px] items-center justify-center gap-1 mx-auto w-fit">
{canShareStaffInviteLink(m) && ( {canShareStaffInviteLink(m) && (
<button <button
type="button" type="button"
@@ -530,6 +547,25 @@ export default function StaffPage() {
)} )}
</button> </button>
)} )}
{canDisableStaff(m) && (
<button
type="button"
className={`p-2 rounded-md ${
canEdit
? 'text-text-secondary hover:bg-background-card/80 hover:text-amber-600'
: 'text-text-muted opacity-50 cursor-not-allowed'
}`}
aria-label="Disable member"
disabled={!canEdit || disablingMembershipId === m.id}
title="Disable member (frees a seat)"
onClick={() => {
if (!canEdit) return;
setDisableTarget(m);
}}
>
<UserX className="w-4 h-4" />
</button>
)}
<button <button
type="button" type="button"
className={`p-2 rounded-md ${ className={`p-2 rounded-md ${
@@ -553,11 +589,12 @@ export default function StaffPage() {
? 'text-text-secondary hover:bg-red-500/15 hover:text-red-600' ? 'text-text-secondary hover:bg-red-500/15 hover:text-red-600'
: 'text-text-muted opacity-50 cursor-not-allowed' : 'text-text-muted opacity-50 cursor-not-allowed'
}`} }`}
aria-label="Remove member" aria-label="Delete member"
disabled={!canEdit} disabled={!canEdit}
title="Delete member (not implemented)"
onClick={() => { onClick={() => {
if (!canEdit) return; if (!canEdit) return;
void removeMember(m); handleDeleteMember();
}} }}
> >
<Trash2 className="w-4 h-4" /> <Trash2 className="w-4 h-4" />
@@ -623,6 +660,60 @@ export default function StaffPage() {
</div> </div>
)} )}
{disableTarget && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/55">
<div
className="surface-card w-full max-w-md p-5 space-y-4 shadow-xl"
role="dialog"
aria-modal="true"
aria-labelledby="disable-staff-title"
>
<div className="flex items-start justify-between gap-2">
<h2 id="disable-staff-title" className="text-lg font-semibold text-text-primary pr-2">
Disable team member
</h2>
<DialogCloseButton
onClick={() => {
if (disablingMembershipId) return;
setDisableTarget(null);
}}
/>
</div>
<p className="text-sm text-text-secondary">
Disable <span className="font-medium text-text-primary">{disableTarget.name}</span> (
{disableTarget.email})?
</p>
<ul className="text-sm text-text-secondary space-y-2 list-disc pl-5">
<li>They will not be able to sign in to this organization.</li>
<li>No data will be removed.</li>
<li>
Disabling frees <span className="text-text-primary font-medium">one seat</span> on your
plan so you can invite someone else.
</li>
</ul>
<div className="flex justify-end gap-2 pt-1">
<Button
type="button"
variant="outline"
disabled={Boolean(disablingMembershipId)}
onClick={() => setDisableTarget(null)}
>
Cancel
</Button>
<Button
type="button"
variant="danger"
isLoading={disablingMembershipId === disableTarget.id}
disabled={Boolean(disablingMembershipId)}
onClick={() => void confirmDisableMember()}
>
Disable member
</Button>
</div>
</div>
</div>
)}
{editing && ( {editing && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50"> <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
<div <div

View File

@@ -7,7 +7,7 @@ export interface StaffMemberDto {
name: string; name: string;
isOwner: boolean; isOwner: boolean;
isActive: boolean; isActive: boolean;
invitationStatus: 'ACTIVE' | 'PENDING' | 'EXPIRED'; invitationStatus: 'ACTIVE' | 'PENDING' | 'EXPIRED' | 'DISABLED';
invitedAt: string | null; invitedAt: string | null;
acceptedAt: string | null; acceptedAt: string | null;
permissions: string[] | null; permissions: string[] | null;
@@ -100,6 +100,13 @@ export const staffApi = {
return response.data; return response.data;
}, },
disableMember: async (
membershipId: string,
): Promise<{ success: boolean; message: string }> => {
const response = await apiClient.patch(`/staff/members/${membershipId}/disable`);
return response.data;
},
removeMember: async ( removeMember: async (
membershipId: string, membershipId: string,
): Promise<{ success: boolean; message: string }> => { ): Promise<{ success: boolean; message: string }> => {