bugfix: invitation link copy option disapearing fixed. route problem for unauthorizrd users opening invitation link fixed.
This commit is contained in:
@@ -288,8 +288,11 @@ export class OrganizationService {
|
||||
if (!invitation) {
|
||||
throw new NotFoundException('Invitation not found');
|
||||
}
|
||||
if (invitation.acceptedAt || invitation.revokedAt) {
|
||||
throw new BadRequestException('Only pending invitations can provide a link');
|
||||
if (invitation.acceptedAt) {
|
||||
throw new BadRequestException('This invitation has already been accepted');
|
||||
}
|
||||
if (invitation.revokedAt) {
|
||||
throw new BadRequestException('This invitation is no longer valid');
|
||||
}
|
||||
|
||||
const plainToken = this.generateInviteToken();
|
||||
|
||||
@@ -55,6 +55,19 @@ export class StaffController {
|
||||
return this.staffService.invite(req.user.id, organizationId, dto);
|
||||
}
|
||||
|
||||
@Post('members/:membershipId/invitation-link')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiOperation({
|
||||
summary: 'Regenerate and return invite link for a pending staff member',
|
||||
})
|
||||
getInvitationLink(
|
||||
@Req() req: { user: { id: string; organizationId?: string } },
|
||||
@Param('membershipId') membershipId: string,
|
||||
) {
|
||||
const organizationId = this.staffService.getOrganizationIdFromUser(req.user);
|
||||
return this.staffService.getInvitationLink(req.user.id, organizationId, membershipId);
|
||||
}
|
||||
|
||||
@Patch('members/:membershipId')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiOperation({ summary: 'Update staff member name and/or permissions' })
|
||||
|
||||
@@ -224,6 +224,62 @@ export class StaffService {
|
||||
};
|
||||
}
|
||||
|
||||
async getInvitationLink(userId: string, organizationId: string, membershipId: string) {
|
||||
const actor = await this.getActorMembership(userId, organizationId);
|
||||
if (!actor || !this.canEditStaff(actor)) {
|
||||
throw new ForbiddenException('You cannot invite or manage staff');
|
||||
}
|
||||
|
||||
const membership = await this.prisma.membership.findFirst({
|
||||
where: { id: membershipId, organizationId },
|
||||
include: {
|
||||
user: { select: { email: true } },
|
||||
invitations: { orderBy: { createdAt: 'desc' }, take: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new NotFoundException('Member not found');
|
||||
}
|
||||
if (membership.isOwner) {
|
||||
throw new BadRequestException('Owner does not use an invitation link');
|
||||
}
|
||||
if (membership.isActive) {
|
||||
throw new BadRequestException('This member has already accepted their invitation');
|
||||
}
|
||||
|
||||
const invitation = membership.invitations[0];
|
||||
if (!invitation) {
|
||||
throw new BadRequestException('No invitation found for this member');
|
||||
}
|
||||
if (invitation.acceptedAt) {
|
||||
throw new BadRequestException('This invitation has already been accepted');
|
||||
}
|
||||
if (invitation.revokedAt) {
|
||||
throw new BadRequestException('This invitation is no longer valid');
|
||||
}
|
||||
|
||||
const plainToken = this.generateInviteToken();
|
||||
const tokenHash = this.hashInviteToken(plainToken);
|
||||
await this.prisma.staffInvitation.update({
|
||||
where: { id: invitation.id },
|
||||
data: {
|
||||
tokenHash,
|
||||
expiresAt: this.getInviteExpiryDate(),
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
membershipId: membership.id,
|
||||
invitationId: invitation.id,
|
||||
email: membership.user.email,
|
||||
invitationUrl: this.buildInviteUrl(plainToken),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async previewInvite(token: string) {
|
||||
const invitation = await this.findValidInvitation(token);
|
||||
const org = invitation.membership.organization;
|
||||
@@ -383,7 +439,8 @@ export class StaffService {
|
||||
if (m.isOwner || m.isActive) return 'ACTIVE';
|
||||
const invitation = m.invitations[0];
|
||||
if (!invitation) return 'EXPIRED';
|
||||
if (invitation.acceptedAt || invitation.revokedAt) return 'ACTIVE';
|
||||
if (invitation.acceptedAt) return 'ACTIVE';
|
||||
if (invitation.revokedAt) return 'EXPIRED';
|
||||
return invitation.expiresAt.getTime() > Date.now() ? 'PENDING' : 'EXPIRED';
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
'use client';
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Check, Copy, Link2, Trash2, X } from 'lucide-react';
|
||||
import { Check, Link2, Trash2, X } from 'lucide-react';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { useOrganizationInviteLinkCopy } from '@/lib/hooks/useOrganizationInviteLinkCopy';
|
||||
import {
|
||||
organizationApi,
|
||||
type CounterpartItemDto,
|
||||
type CounterpartSearchResultDto,
|
||||
type OrganizationInvitationHistoryItemDto,
|
||||
} from '@/lib/api/organization';
|
||||
import { InvitationHistoryDialog } from '@/components/ui/organizations/InvitationHistoryDialog';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Badge, organizationLinkStatusVariant } from '@/components/ui/common/Badge';
|
||||
import { Input } from '@/components/ui/common/Input';
|
||||
@@ -16,33 +18,6 @@ import { SearchBar } from '@/components/ui/common/SearchBar';
|
||||
import { Table } from '@/components/ui/common/Table';
|
||||
import type { ApiError } from '@/types/api';
|
||||
|
||||
type StoredInviteLink = {
|
||||
invitationId: string;
|
||||
ownerEmail: string;
|
||||
invitationUrl: string;
|
||||
};
|
||||
|
||||
function inviteLinksStorageKey(orgId: string): string {
|
||||
return `counterpartInviteLinks:${orgId}`;
|
||||
}
|
||||
|
||||
function readStoredInviteLinks(orgId: string): Record<string, StoredInviteLink> {
|
||||
if (typeof window === 'undefined') return {};
|
||||
try {
|
||||
const raw = window.localStorage.getItem(inviteLinksStorageKey(orgId));
|
||||
if (!raw) return {};
|
||||
const parsed = JSON.parse(raw) as Record<string, StoredInviteLink>;
|
||||
return parsed && typeof parsed === 'object' ? parsed : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeStoredInviteLinks(orgId: string, links: Record<string, StoredInviteLink>) {
|
||||
if (typeof window === 'undefined') return;
|
||||
window.localStorage.setItem(inviteLinksStorageKey(orgId), JSON.stringify(links));
|
||||
}
|
||||
|
||||
function formatOrganizationStatusLabel(status: string): string {
|
||||
if (!status) return status;
|
||||
const lower = status.toLowerCase();
|
||||
@@ -56,13 +31,6 @@ function formatLinkStatusLabel(status: CounterpartItemDto['status']): string {
|
||||
return formatOrganizationStatusLabel(status);
|
||||
}
|
||||
|
||||
function formatInvitationStatusLabel(status: OrganizationInvitationHistoryItemDto['status']): string {
|
||||
if (status === 'PENDING') return 'Invitation pending';
|
||||
if (status === 'ACTIVE') return 'Invitation Accepted';
|
||||
if (status === 'REJECTED') return 'Invitation rejected';
|
||||
return formatOrganizationStatusLabel(status);
|
||||
}
|
||||
|
||||
function formatApiMessage(err: unknown): string {
|
||||
if (!err || typeof err !== 'object') return 'Something went wrong';
|
||||
const m = (err as ApiError).message;
|
||||
@@ -73,7 +41,7 @@ function formatApiMessage(err: unknown): string {
|
||||
|
||||
function formatTableDate(value: string): string {
|
||||
const d = new Date(value);
|
||||
if (Number.isNaN(d.getTime())) return '—';
|
||||
if (Number.isNaN(d.getTime())) return '—';
|
||||
return d.toLocaleDateString();
|
||||
}
|
||||
|
||||
@@ -96,12 +64,20 @@ export default function OrganizationsPage() {
|
||||
const [manualOrganizationName, setManualOrganizationName] = useState('');
|
||||
const [manualOwnerEmail, setManualOwnerEmail] = useState('');
|
||||
const [inviteLoading, setInviteLoading] = useState(false);
|
||||
const [copiedId, setCopiedId] = useState<string | null>(null);
|
||||
const [pendingInviteLinks, setPendingInviteLinks] = useState<Record<string, StoredInviteLink>>({});
|
||||
const [showInviteForm, setShowInviteForm] = useState(false);
|
||||
const [historyOpen, setHistoryOpen] = useState(false);
|
||||
const [historyLoading, setHistoryLoading] = useState(false);
|
||||
const [historyItems, setHistoryItems] = useState<OrganizationInvitationHistoryItemDto[]>([]);
|
||||
const [historyCopyError, setHistoryCopyError] = useState('');
|
||||
const [historyCopySuccess, setHistoryCopySuccess] = useState('');
|
||||
|
||||
const {
|
||||
copiedId,
|
||||
copyingInvitationId,
|
||||
storeInviteLink,
|
||||
copyInvitationLink,
|
||||
pruneAcceptedLinks,
|
||||
} = useOrganizationInviteLinkCopy(currentOrganization?.id);
|
||||
|
||||
const counterpartLabel = currentOrganization?.type === 'LAB' ? 'Clinic' : 'Lab';
|
||||
const tabLabel = currentOrganization?.type === 'LAB' ? 'Clinics' : 'Labs';
|
||||
@@ -121,11 +97,6 @@ export default function OrganizationsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentOrganization?.id) return;
|
||||
setPendingInviteLinks(readStoredInviteLinks(currentOrganization.id));
|
||||
}, [currentOrganization?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadList();
|
||||
}, []);
|
||||
@@ -185,18 +156,7 @@ export default function OrganizationsPage() {
|
||||
organizationName: manualOrganizationName.trim(),
|
||||
ownerEmail: manualOwnerEmail.trim(),
|
||||
});
|
||||
if (currentOrganization?.id) {
|
||||
const nextLinks = {
|
||||
...pendingInviteLinks,
|
||||
[res.data.invitationId]: {
|
||||
invitationId: res.data.invitationId,
|
||||
ownerEmail: manualOwnerEmail.trim().toLowerCase(),
|
||||
invitationUrl: res.data.invitationUrl,
|
||||
},
|
||||
};
|
||||
setPendingInviteLinks(nextLinks);
|
||||
writeStoredInviteLinks(currentOrganization.id, nextLinks);
|
||||
}
|
||||
storeInviteLink(res.data.invitationId, manualOwnerEmail, res.data.invitationUrl);
|
||||
setSuccess(`Invitation link created for ${manualOwnerEmail.trim()}`);
|
||||
setManualOrganizationName('');
|
||||
setManualOwnerEmail('');
|
||||
@@ -212,13 +172,21 @@ export default function OrganizationsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadInvitationHistory() {
|
||||
const res = await organizationApi.listInvitations();
|
||||
setHistoryItems(res.data.items);
|
||||
pruneAcceptedLinks(res.data.items);
|
||||
return res.data.items;
|
||||
}
|
||||
|
||||
async function openInvitationHistory() {
|
||||
setHistoryOpen(true);
|
||||
setHistoryLoading(true);
|
||||
setHistoryCopyError('');
|
||||
setHistoryCopySuccess('');
|
||||
setError('');
|
||||
try {
|
||||
const res = await organizationApi.listInvitations();
|
||||
setHistoryItems(res.data.items);
|
||||
await loadInvitationHistory();
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
} finally {
|
||||
@@ -226,6 +194,22 @@ export default function OrganizationsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleHistoryCopy(invitation: OrganizationInvitationHistoryItemDto) {
|
||||
setHistoryCopyError('');
|
||||
setHistoryCopySuccess('');
|
||||
try {
|
||||
await copyInvitationLink(invitation, {
|
||||
onRegenerated: async () => {
|
||||
await loadInvitationHistory();
|
||||
},
|
||||
});
|
||||
setHistoryCopySuccess('Invitation link copied to clipboard.');
|
||||
setTimeout(() => setHistoryCopySuccess(''), 3000);
|
||||
} catch (e) {
|
||||
setHistoryCopyError(formatApiMessage(e));
|
||||
}
|
||||
}
|
||||
|
||||
async function respondToPendingLink(linkId: string, action: 'ACCEPT' | 'REJECT') {
|
||||
setRequestLinkRowId(linkId);
|
||||
setError('');
|
||||
@@ -254,35 +238,6 @@ export default function OrganizationsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function copyInvitationLink(invitationId: string) {
|
||||
setError('');
|
||||
try {
|
||||
let invitationUrl = pendingInviteLinks[invitationId]?.invitationUrl;
|
||||
if (!invitationUrl) {
|
||||
const res = await organizationApi.getInvitationLink(invitationId);
|
||||
invitationUrl = res.data.invitationUrl;
|
||||
if (currentOrganization?.id) {
|
||||
const nextLinks = {
|
||||
...pendingInviteLinks,
|
||||
[invitationId]: {
|
||||
invitationId,
|
||||
ownerEmail:
|
||||
historyItems.find((item) => item.id === invitationId)?.ownerEmail?.toLowerCase() ?? '',
|
||||
invitationUrl,
|
||||
},
|
||||
};
|
||||
setPendingInviteLinks(nextLinks);
|
||||
writeStoredInviteLinks(currentOrganization.id, nextLinks);
|
||||
}
|
||||
}
|
||||
await navigator.clipboard.writeText(invitationUrl);
|
||||
setCopiedId(invitationId);
|
||||
setTimeout(() => setCopiedId(null), 1500);
|
||||
} catch {
|
||||
setError('Could not copy invitation link');
|
||||
}
|
||||
}
|
||||
|
||||
function clearSearchView() {
|
||||
setMode('existing');
|
||||
setQuery('');
|
||||
@@ -516,87 +471,21 @@ export default function OrganizationsPage() {
|
||||
}
|
||||
/>
|
||||
|
||||
{historyOpen && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
|
||||
<div
|
||||
className="w-full max-w-3xl max-h-[90vh] overflow-y-auto rounded-[var(--radius-md)] border border-border bg-background-secondary p-6 shadow-xl space-y-4"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold text-text-primary">Invitation History</h2>
|
||||
<Button type="button" size="sm" onClick={() => setHistoryOpen(false)}>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{historyLoading ? (
|
||||
<p className="text-sm text-text-secondary">Loading invitation history...</p>
|
||||
) : historyItems.length === 0 ? (
|
||||
<p className="text-sm text-text-secondary">No invitations yet.</p>
|
||||
) : (
|
||||
<Table
|
||||
headers={
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
|
||||
Organization
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
|
||||
Owner email
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
|
||||
Date
|
||||
</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-right text-xs font-medium text-text-muted uppercase tracking-wider">
|
||||
Action
|
||||
</th>
|
||||
</tr>
|
||||
}
|
||||
body={
|
||||
<>
|
||||
{historyItems.map((inv) => (
|
||||
<tr key={inv.id} className="hover:bg-background-secondary/45">
|
||||
<td className="px-6 py-1.5 text-sm text-text-primary">{inv.organizationName}</td>
|
||||
<td className="px-6 py-1.5 text-sm text-text-secondary">{inv.ownerEmail}</td>
|
||||
<td className="px-6 py-1.5 text-sm text-text-secondary">
|
||||
{formatTableDate(inv.createdAt)}
|
||||
</td>
|
||||
<td className="px-6 py-1.5 text-center align-middle">
|
||||
<Badge variant={organizationLinkStatusVariant(inv.status)} fixedWidth={false}>
|
||||
{formatInvitationStatusLabel(inv.status)}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-6 py-1.5 text-right">
|
||||
{inv.status === 'PENDING' ? (
|
||||
<button
|
||||
type="button"
|
||||
className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary"
|
||||
onClick={() => void copyInvitationLink(inv.id)}
|
||||
aria-label="Copy invitation link"
|
||||
title="Copy invitation link"
|
||||
>
|
||||
{copiedId === inv.id ? (
|
||||
<Check className="w-4 h-4" />
|
||||
) : (
|
||||
<Copy className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<span className="text-xs text-text-muted">—</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</>
|
||||
}
|
||||
<InvitationHistoryDialog
|
||||
open={historyOpen}
|
||||
onClose={() => {
|
||||
setHistoryOpen(false);
|
||||
setHistoryCopyError('');
|
||||
setHistoryCopySuccess('');
|
||||
}}
|
||||
loading={historyLoading}
|
||||
items={historyItems}
|
||||
copiedId={copiedId}
|
||||
copyingInvitationId={copyingInvitationId}
|
||||
onCopy={(invitation) => void handleHistoryCopy(invitation)}
|
||||
copyError={historyCopyError}
|
||||
copySuccess={historyCopySuccess}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { OrganizationSelectorContent } from '@/components/ui/organization/OrganizationSelectorContent';
|
||||
import { OrganizationSelectorContent } from '@/components/ui/organizations/OrganizationSelectorContent';
|
||||
|
||||
export default function DashboardOrganizationsSettingsPage() {
|
||||
return (
|
||||
|
||||
@@ -61,6 +61,10 @@ function formatApiMessage(err: unknown): string {
|
||||
return 'Something went wrong';
|
||||
}
|
||||
|
||||
function canShareStaffInviteLink(member: StaffMemberDto): boolean {
|
||||
return !member.isOwner && member.invitationStatus !== 'ACTIVE';
|
||||
}
|
||||
|
||||
function PermissionGrid({
|
||||
state,
|
||||
onChange,
|
||||
@@ -140,6 +144,7 @@ export default function StaffPage() {
|
||||
const [invitePerms, setInvitePerms] = useState(() => emptyFeaturePermissionState());
|
||||
const [inviteLoading, setInviteLoading] = useState(false);
|
||||
const [copiedInviteMembershipId, setCopiedInviteMembershipId] = useState<string | null>(null);
|
||||
const [copyingInviteMembershipId, setCopyingInviteMembershipId] = useState<string | null>(null);
|
||||
const [lastInviteInfo, setLastInviteInfo] = useState<{
|
||||
membershipId: string;
|
||||
name: string;
|
||||
@@ -221,6 +226,42 @@ export default function StaffPage() {
|
||||
return () => clearTimeout(t);
|
||||
}, [success]);
|
||||
|
||||
async function copyStaffInviteLink(member: StaffMemberDto) {
|
||||
if (!canShareStaffInviteLink(member)) return;
|
||||
|
||||
setCopyingInviteMembershipId(member.id);
|
||||
setError('');
|
||||
try {
|
||||
let invitationUrl = pendingInviteLinks[member.id]?.invitationUrl;
|
||||
if (!invitationUrl || member.invitationStatus === 'EXPIRED') {
|
||||
const res = await staffApi.getInvitationLink(member.id);
|
||||
invitationUrl = res.data.invitationUrl;
|
||||
if (currentOrganization?.id) {
|
||||
const nextLinks = {
|
||||
...pendingInviteLinks,
|
||||
[member.id]: {
|
||||
membershipId: member.id,
|
||||
email: member.email,
|
||||
invitationUrl,
|
||||
},
|
||||
};
|
||||
setPendingInviteLinks(nextLinks);
|
||||
writeStoredInviteLinks(currentOrganization.id, nextLinks);
|
||||
}
|
||||
}
|
||||
await navigator.clipboard.writeText(invitationUrl);
|
||||
setCopiedInviteMembershipId(member.id);
|
||||
setTimeout(() => setCopiedInviteMembershipId(null), 1500);
|
||||
if (member.invitationStatus === 'EXPIRED') {
|
||||
await load();
|
||||
}
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
} finally {
|
||||
setCopyingInviteMembershipId(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function submitInvite() {
|
||||
setInviteLoading(true);
|
||||
setError('');
|
||||
@@ -388,34 +429,60 @@ export default function StaffPage() {
|
||||
? ' Invitation is pending until they open the link, set a password, and log in.'
|
||||
: ' Invitation was accepted immediately.'}
|
||||
</p>
|
||||
{lastInviteInfo.invitationUrl && (
|
||||
{lastInviteInfo.invitationStatus === 'PENDING' && (
|
||||
<div className="space-y-2 pt-1 border-t border-border/60">
|
||||
<p className="text-xs font-medium text-text-secondary uppercase tracking-wide">
|
||||
Invite link
|
||||
</p>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<code className="text-sm px-2 py-1.5 rounded-[var(--radius-sm)] bg-background-card border border-border font-mono break-all">
|
||||
{lastInviteInfo.invitationUrl && (
|
||||
<code className="block text-sm px-2 py-1.5 rounded-[var(--radius-sm)] bg-background-card border border-border font-mono break-all">
|
||||
{lastInviteInfo.invitationUrl}
|
||||
</code>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
isLoading={copyingInviteMembershipId === lastInviteInfo.membershipId}
|
||||
onClick={() => {
|
||||
const member = members.find((item) => item.id === lastInviteInfo.membershipId);
|
||||
if (member) {
|
||||
void copyStaffInviteLink(member);
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
setCopyingInviteMembershipId(lastInviteInfo.membershipId);
|
||||
setError('');
|
||||
try {
|
||||
await navigator.clipboard.writeText(lastInviteInfo.invitationUrl as string);
|
||||
const res = await staffApi.getInvitationLink(lastInviteInfo.membershipId);
|
||||
if (currentOrganization?.id) {
|
||||
const nextLinks = {
|
||||
...pendingInviteLinks,
|
||||
[lastInviteInfo.membershipId]: {
|
||||
membershipId: lastInviteInfo.membershipId,
|
||||
email: lastInviteInfo.email,
|
||||
invitationUrl: res.data.invitationUrl,
|
||||
},
|
||||
};
|
||||
setPendingInviteLinks(nextLinks);
|
||||
writeStoredInviteLinks(currentOrganization.id, nextLinks);
|
||||
}
|
||||
setLastInviteInfo({ ...lastInviteInfo, invitationUrl: res.data.invitationUrl });
|
||||
await navigator.clipboard.writeText(res.data.invitationUrl);
|
||||
setCopiedInviteMembershipId(lastInviteInfo.membershipId);
|
||||
setTimeout(() => setCopiedInviteMembershipId(null), 1500);
|
||||
} catch {
|
||||
setError('Could not copy invitation link');
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
} finally {
|
||||
setCopyingInviteMembershipId(null);
|
||||
}
|
||||
})();
|
||||
}}
|
||||
>
|
||||
{copiedInviteMembershipId === lastInviteInfo.membershipId ? 'Copied' : 'Copy link'}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-text-muted">
|
||||
Share this link manually via SMS or email. They must set password first.
|
||||
Share this link manually via SMS or email. A new link is generated if the previous one expired or was lost.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
@@ -470,21 +537,14 @@ export default function StaffPage() {
|
||||
<td className="px-6 py-1.5 align-middle">
|
||||
{!m.isOwner && (
|
||||
<div className="flex min-h-[36px] items-center justify-end gap-1">
|
||||
{m.invitationStatus === 'PENDING' && pendingInviteLinks[m.id]?.invitationUrl && (
|
||||
{canShareStaffInviteLink(m) && (
|
||||
<button
|
||||
type="button"
|
||||
className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(pendingInviteLinks[m.id].invitationUrl);
|
||||
setCopiedInviteMembershipId(m.id);
|
||||
setTimeout(() => setCopiedInviteMembershipId(null), 1500);
|
||||
} catch {
|
||||
setError('Could not copy invitation link');
|
||||
}
|
||||
}}
|
||||
aria-label="Copy invite link"
|
||||
title="Copy invite link"
|
||||
className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary disabled:opacity-50"
|
||||
disabled={copyingInviteMembershipId === m.id}
|
||||
onClick={() => void copyStaffInviteLink(m)}
|
||||
aria-label="Copy invitation link"
|
||||
title="Copy invitation link (generates a new link if needed)"
|
||||
>
|
||||
{copiedInviteMembershipId === m.id ? (
|
||||
<Check className="w-4 h-4" />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { OrganizationSelectorContent } from '@/components/ui/organization/OrganizationSelectorContent';
|
||||
import { OrganizationSelectorContent } from '@/components/ui/organizations/OrganizationSelectorContent';
|
||||
|
||||
export default function SelectOrganizationPage() {
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { OrganizationInvitationHistoryItemDto } from '@/lib/api/organization';
|
||||
|
||||
export type StoredOrganizationInviteLink = {
|
||||
invitationId: string;
|
||||
ownerEmail: string;
|
||||
invitationUrl: string;
|
||||
};
|
||||
|
||||
export function organizationInviteLinksStorageKey(orgId: string): string {
|
||||
return `counterpartInviteLinks:${orgId}`;
|
||||
}
|
||||
|
||||
export function readOrganizationInviteLinks(
|
||||
orgId: string,
|
||||
): Record<string, StoredOrganizationInviteLink> {
|
||||
if (typeof window === 'undefined') return {};
|
||||
try {
|
||||
const raw = window.localStorage.getItem(organizationInviteLinksStorageKey(orgId));
|
||||
if (!raw) return {};
|
||||
const parsed = JSON.parse(raw) as Record<string, StoredOrganizationInviteLink>;
|
||||
return parsed && typeof parsed === 'object' ? parsed : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function writeOrganizationInviteLinks(
|
||||
orgId: string,
|
||||
links: Record<string, StoredOrganizationInviteLink>,
|
||||
): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
window.localStorage.setItem(organizationInviteLinksStorageKey(orgId), JSON.stringify(links));
|
||||
}
|
||||
|
||||
/** Show copy/regenerate only until the invitee accepts (first login / setup). */
|
||||
export function canShareOrganizationInviteLink(
|
||||
invitation: Pick<OrganizationInvitationHistoryItemDto, 'status' | 'acceptedAt'>,
|
||||
): boolean {
|
||||
if (invitation.acceptedAt) return false;
|
||||
return invitation.status === 'PENDING' || invitation.status === 'EXPIRED';
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
'use client';
|
||||
|
||||
import { Check, Copy } from 'lucide-react';
|
||||
import type { OrganizationInvitationHistoryItemDto } from '@/lib/api/organization';
|
||||
import { canShareOrganizationInviteLink } from '@/components/invitations/organizationInviteLinks';
|
||||
import { Badge, organizationLinkStatusVariant } from '@/components/ui/common/Badge';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Table } from '@/components/ui/common/Table';
|
||||
|
||||
function formatInvitationStatusLabel(status: OrganizationInvitationHistoryItemDto['status']): string {
|
||||
if (status === 'PENDING') return 'Invitation pending';
|
||||
if (status === 'ACTIVE') return 'Invitation Accepted';
|
||||
if (status === 'REJECTED') return 'Invitation rejected';
|
||||
if (status === 'EXPIRED') return 'Invitation expired';
|
||||
return status;
|
||||
}
|
||||
|
||||
function formatTableDate(value: string): string {
|
||||
const d = new Date(value);
|
||||
if (Number.isNaN(d.getTime())) return '—';
|
||||
return d.toLocaleDateString();
|
||||
}
|
||||
|
||||
type InvitationHistoryDialogProps = {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
loading: boolean;
|
||||
items: OrganizationInvitationHistoryItemDto[];
|
||||
copiedId: string | null;
|
||||
copyingInvitationId: string | null;
|
||||
onCopy: (invitation: OrganizationInvitationHistoryItemDto) => void;
|
||||
copyError?: string;
|
||||
copySuccess?: string;
|
||||
};
|
||||
|
||||
export function InvitationHistoryDialog({
|
||||
open,
|
||||
onClose,
|
||||
loading,
|
||||
items,
|
||||
copiedId,
|
||||
copyingInvitationId,
|
||||
onCopy,
|
||||
copyError,
|
||||
copySuccess,
|
||||
}: InvitationHistoryDialogProps) {
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
|
||||
<div
|
||||
className="w-full max-w-3xl max-h-[90vh] overflow-y-auto rounded-[var(--radius-md)] border border-border bg-background-secondary p-6 shadow-xl space-y-4"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="invitation-history-title"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 id="invitation-history-title" className="text-lg font-semibold text-text-primary">
|
||||
Invitation History
|
||||
</h2>
|
||||
<Button type="button" size="sm" onClick={onClose}>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{copyError && (
|
||||
<div className="rounded-[var(--radius-md)] border border-red-500/40 bg-red-500/10 px-4 py-3 text-sm text-red-700 dark:text-red-300">
|
||||
{copyError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{copySuccess && (
|
||||
<div className="rounded-[var(--radius-md)] border border-primary/30 bg-primary-soft/40 px-4 py-3 text-sm text-text-primary">
|
||||
{copySuccess}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<p className="text-sm text-text-secondary">Loading invitation history...</p>
|
||||
) : items.length === 0 ? (
|
||||
<p className="text-sm text-text-secondary">No invitations yet.</p>
|
||||
) : (
|
||||
<Table
|
||||
headers={
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
|
||||
Organization
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
|
||||
Owner email
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
|
||||
Date
|
||||
</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-right text-xs font-medium text-text-muted uppercase tracking-wider">
|
||||
Action
|
||||
</th>
|
||||
</tr>
|
||||
}
|
||||
body={
|
||||
<>
|
||||
{items.map((inv) => (
|
||||
<tr key={inv.id} className="hover:bg-background-secondary/45">
|
||||
<td className="px-6 py-1.5 text-sm text-text-primary">{inv.organizationName}</td>
|
||||
<td className="px-6 py-1.5 text-sm text-text-secondary">{inv.ownerEmail}</td>
|
||||
<td className="px-6 py-1.5 text-sm text-text-secondary">
|
||||
{formatTableDate(inv.createdAt)}
|
||||
</td>
|
||||
<td className="px-6 py-1.5 text-center align-middle">
|
||||
<Badge variant={organizationLinkStatusVariant(inv.status)} fixedWidth={false}>
|
||||
{formatInvitationStatusLabel(inv.status)}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-6 py-1.5 text-right align-middle">
|
||||
{canShareOrganizationInviteLink(inv) ? (
|
||||
<button
|
||||
type="button"
|
||||
className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary disabled:opacity-50"
|
||||
disabled={copyingInvitationId === inv.id}
|
||||
onClick={() => onCopy(inv)}
|
||||
aria-label="Copy invitation link"
|
||||
title="Copy invitation link (generates a new link if needed)"
|
||||
>
|
||||
{copiedId === inv.id ? (
|
||||
<Check className="w-4 h-4" />
|
||||
) : (
|
||||
<Copy className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<span className="text-xs text-text-muted">—</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,17 @@ export const apiClient = axios.create({
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
/** Invitation preview/accept must work with no cookies (public API, no JWT). */
|
||||
function isPublicInvitationRequest(url: string | undefined): boolean {
|
||||
if (!url) return false;
|
||||
return (
|
||||
url.includes('/staff/invitations/preview') ||
|
||||
url.includes('/staff/invitations/accept') ||
|
||||
url.includes('/organizations/invitations/preview') ||
|
||||
url.includes('/organizations/invitations/accept')
|
||||
);
|
||||
}
|
||||
|
||||
// ❌ REMOVE request interceptor completely (no Authorization header)
|
||||
|
||||
// ✅ Response interceptor
|
||||
@@ -23,7 +34,11 @@ apiClient.interceptors.response.use(
|
||||
async (error: AxiosError) => {
|
||||
const originalRequest = error.config as CustomAxiosRequestConfig;
|
||||
|
||||
if (error.response?.status === 401 && !originalRequest._retry) {
|
||||
if (
|
||||
error.response?.status === 401 &&
|
||||
!originalRequest._retry &&
|
||||
!isPublicInvitationRequest(originalRequest.url)
|
||||
) {
|
||||
originalRequest._retry = true;
|
||||
|
||||
try {
|
||||
|
||||
@@ -63,6 +63,21 @@ export const staffApi = {
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getInvitationLink: async (
|
||||
membershipId: string,
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
data: {
|
||||
membershipId: string;
|
||||
invitationId: string;
|
||||
email: string;
|
||||
invitationUrl: string;
|
||||
};
|
||||
}> => {
|
||||
const response = await apiClient.post(`/staff/members/${membershipId}/invitation-link`);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
previewInvite: async (token: string): Promise<PreviewInviteResponse> => {
|
||||
const response = await apiClient.get(`/staff/invitations/preview?token=${encodeURIComponent(token)}`);
|
||||
return response.data;
|
||||
|
||||
107
frontend/src/lib/hooks/useOrganizationInviteLinkCopy.ts
Normal file
107
frontend/src/lib/hooks/useOrganizationInviteLinkCopy.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
organizationApi,
|
||||
type OrganizationInvitationHistoryItemDto,
|
||||
} from '@/lib/api/organization';
|
||||
import {
|
||||
canShareOrganizationInviteLink,
|
||||
readOrganizationInviteLinks,
|
||||
type StoredOrganizationInviteLink,
|
||||
writeOrganizationInviteLinks,
|
||||
} from '@/components/invitations/organizationInviteLinks';
|
||||
|
||||
export function useOrganizationInviteLinkCopy(organizationId: string | undefined) {
|
||||
const [pendingInviteLinks, setPendingInviteLinks] = useState<
|
||||
Record<string, StoredOrganizationInviteLink>
|
||||
>({});
|
||||
const [copiedId, setCopiedId] = useState<string | null>(null);
|
||||
const [copyingInvitationId, setCopyingInvitationId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!organizationId) return;
|
||||
setPendingInviteLinks(readOrganizationInviteLinks(organizationId));
|
||||
}, [organizationId]);
|
||||
|
||||
const storeInviteLink = useCallback(
|
||||
(invitationId: string, ownerEmail: string, invitationUrl: string) => {
|
||||
if (!organizationId) return;
|
||||
setPendingInviteLinks((prev) => {
|
||||
const next = {
|
||||
...prev,
|
||||
[invitationId]: {
|
||||
invitationId,
|
||||
ownerEmail: ownerEmail.trim().toLowerCase(),
|
||||
invitationUrl,
|
||||
},
|
||||
};
|
||||
writeOrganizationInviteLinks(organizationId, next);
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[organizationId],
|
||||
);
|
||||
|
||||
const pruneAcceptedLinks = useCallback(
|
||||
(items: OrganizationInvitationHistoryItemDto[]) => {
|
||||
if (!organizationId) return;
|
||||
const acceptedIds = new Set(
|
||||
items.filter((item) => item.acceptedAt || item.status === 'ACTIVE').map((item) => item.id),
|
||||
);
|
||||
|
||||
setPendingInviteLinks((prev) => {
|
||||
let changed = false;
|
||||
const next = { ...prev };
|
||||
for (const id of Object.keys(next)) {
|
||||
if (acceptedIds.has(id)) {
|
||||
delete next[id];
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
writeOrganizationInviteLinks(organizationId, next);
|
||||
}
|
||||
return changed ? next : prev;
|
||||
});
|
||||
},
|
||||
[organizationId],
|
||||
);
|
||||
|
||||
const copyInvitationLink = useCallback(
|
||||
async (
|
||||
invitation: OrganizationInvitationHistoryItemDto,
|
||||
options?: { onRegenerated?: () => void | Promise<void> },
|
||||
): Promise<string | null> => {
|
||||
if (!canShareOrganizationInviteLink(invitation)) return null;
|
||||
|
||||
setCopyingInvitationId(invitation.id);
|
||||
try {
|
||||
let invitationUrl = pendingInviteLinks[invitation.id]?.invitationUrl;
|
||||
if (!invitationUrl || invitation.status === 'EXPIRED') {
|
||||
const res = await organizationApi.getInvitationLink(invitation.id);
|
||||
invitationUrl = res.data.invitationUrl;
|
||||
storeInviteLink(invitation.id, invitation.ownerEmail, invitationUrl);
|
||||
await options?.onRegenerated?.();
|
||||
}
|
||||
|
||||
await navigator.clipboard.writeText(invitationUrl);
|
||||
setCopiedId(invitation.id);
|
||||
setTimeout(() => setCopiedId(null), 1500);
|
||||
return invitationUrl;
|
||||
} finally {
|
||||
setCopyingInvitationId(null);
|
||||
}
|
||||
},
|
||||
[pendingInviteLinks, storeInviteLink],
|
||||
);
|
||||
|
||||
return {
|
||||
pendingInviteLinks,
|
||||
copiedId,
|
||||
copyingInvitationId,
|
||||
storeInviteLink,
|
||||
copyInvitationLink,
|
||||
pruneAcceptedLinks,
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,17 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
const publicRoutes = ['/', '/login', '/register', '/terms', '/privacy', '/forgot-password'];
|
||||
/** Routes that must work without an existing session (first-time invitees). */
|
||||
const publicRoutes = [
|
||||
'/',
|
||||
'/login',
|
||||
'/register',
|
||||
'/terms',
|
||||
'/privacy',
|
||||
'/forgot-password',
|
||||
'/accept-invite',
|
||||
'/accept-organization-invite',
|
||||
];
|
||||
|
||||
export function proxy(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
|
||||
Reference in New Issue
Block a user