feature/clinic-lab-invitation #14
@@ -0,0 +1,6 @@
|
|||||||
|
import { IsIn } from 'class-validator';
|
||||||
|
|
||||||
|
export class RespondLinkRequestDto {
|
||||||
|
@IsIn(['ACCEPT', 'REJECT'])
|
||||||
|
action: 'ACCEPT' | 'REJECT';
|
||||||
|
}
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
import {
|
import {
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
|
Delete,
|
||||||
Get,
|
Get,
|
||||||
|
Param,
|
||||||
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
Query,
|
Query,
|
||||||
Req,
|
Req,
|
||||||
@@ -13,6 +16,7 @@ import { AcceptOrganizationInviteDto } from './dto/accept-organization-invite.dt
|
|||||||
import { CreateLinkRequestDto } from './dto/create-link-request.dto';
|
import { CreateLinkRequestDto } from './dto/create-link-request.dto';
|
||||||
import { InviteOrganizationDto } from './dto/invite-organization.dto';
|
import { InviteOrganizationDto } from './dto/invite-organization.dto';
|
||||||
import { PreviewOrganizationInviteDto } from './dto/preview-organization-invite.dto';
|
import { PreviewOrganizationInviteDto } from './dto/preview-organization-invite.dto';
|
||||||
|
import { RespondLinkRequestDto } from './dto/respond-link-request.dto';
|
||||||
import { OrganizationService } from './organization.service';
|
import { OrganizationService } from './organization.service';
|
||||||
|
|
||||||
@ApiTags('organizations')
|
@ApiTags('organizations')
|
||||||
@@ -27,6 +31,14 @@ export class OrganizationController {
|
|||||||
return this.organizationService.previewInvite(query.token);
|
return this.organizationService.previewInvite(query.token);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get('invitations')
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
@ApiOperation({ summary: 'List invitation history for current organization' })
|
||||||
|
listInvitations(@Req() req: { user: { id: string; organizationId?: string } }) {
|
||||||
|
const organizationId = this.organizationService.getOrganizationIdFromUser(req.user);
|
||||||
|
return this.organizationService.listInvitationHistory(req.user.id, organizationId);
|
||||||
|
}
|
||||||
|
|
||||||
@Post('invitations/accept')
|
@Post('invitations/accept')
|
||||||
@ApiOperation({ summary: 'Accept organization invite and create/link counterpart org (public)' })
|
@ApiOperation({ summary: 'Accept organization invite and create/link counterpart org (public)' })
|
||||||
acceptInvite(@Body() dto: AcceptOrganizationInviteDto) {
|
acceptInvite(@Body() dto: AcceptOrganizationInviteDto) {
|
||||||
@@ -65,6 +77,40 @@ export class OrganizationController {
|
|||||||
return this.organizationService.createLinkRequest(req.user.id, organizationId, dto);
|
return this.organizationService.createLinkRequest(req.user.id, organizationId, dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Patch('links/:linkId/respond')
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
@ApiOperation({ summary: 'Accept or reject a pending link request for current organization' })
|
||||||
|
respondToLinkRequest(
|
||||||
|
@Req() req: { user: { id: string; organizationId?: string } },
|
||||||
|
@Param('linkId') linkId: string,
|
||||||
|
@Body() dto: RespondLinkRequestDto,
|
||||||
|
) {
|
||||||
|
const organizationId = this.organizationService.getOrganizationIdFromUser(req.user);
|
||||||
|
return this.organizationService.respondToLinkRequest(req.user.id, organizationId, linkId, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('links/:linkId')
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
@ApiOperation({ summary: 'Delete linked organization record' })
|
||||||
|
deleteLink(
|
||||||
|
@Req() req: { user: { id: string; organizationId?: string } },
|
||||||
|
@Param('linkId') linkId: string,
|
||||||
|
) {
|
||||||
|
const organizationId = this.organizationService.getOrganizationIdFromUser(req.user);
|
||||||
|
return this.organizationService.deleteLink(req.user.id, organizationId, linkId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('invitations/:invitationId/link')
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
@ApiOperation({ summary: 'Get a shareable invite link for a pending invitation' })
|
||||||
|
getInvitationLink(
|
||||||
|
@Req() req: { user: { id: string; organizationId?: string } },
|
||||||
|
@Param('invitationId') invitationId: string,
|
||||||
|
) {
|
||||||
|
const organizationId = this.organizationService.getOrganizationIdFromUser(req.user);
|
||||||
|
return this.organizationService.getInvitationLink(req.user.id, organizationId, invitationId);
|
||||||
|
}
|
||||||
|
|
||||||
@Post('invite')
|
@Post('invite')
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@ApiOperation({ summary: 'Create invite link for owner of not-yet-subscribed counterpart org' })
|
@ApiOperation({ summary: 'Create invite link for owner of not-yet-subscribed counterpart org' })
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { PrismaService } from '../../../prisma/prisma.service';
|
|||||||
import { AcceptOrganizationInviteDto } from './dto/accept-organization-invite.dto';
|
import { AcceptOrganizationInviteDto } from './dto/accept-organization-invite.dto';
|
||||||
import { CreateLinkRequestDto } from './dto/create-link-request.dto';
|
import { CreateLinkRequestDto } from './dto/create-link-request.dto';
|
||||||
import { InviteOrganizationDto } from './dto/invite-organization.dto';
|
import { InviteOrganizationDto } from './dto/invite-organization.dto';
|
||||||
|
import { RespondLinkRequestDto } from './dto/respond-link-request.dto';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class OrganizationService {
|
export class OrganizationService {
|
||||||
@@ -67,7 +68,7 @@ export class OrganizationService {
|
|||||||
throw new ForbiddenException('You do not have permission to manage organizations');
|
throw new ForbiddenException('You do not have permission to manage organizations');
|
||||||
}
|
}
|
||||||
|
|
||||||
const [linksA, linksB, invitations] = await Promise.all([
|
const [linksA, linksB] = await Promise.all([
|
||||||
this.prisma.organizationLink.findMany({
|
this.prisma.organizationLink.findMany({
|
||||||
where: { organizationAId: organizationId },
|
where: { organizationAId: organizationId },
|
||||||
include: {
|
include: {
|
||||||
@@ -82,61 +83,65 @@ export class OrganizationService {
|
|||||||
},
|
},
|
||||||
orderBy: { createdAt: 'desc' },
|
orderBy: { createdAt: 'desc' },
|
||||||
}),
|
}),
|
||||||
this.prisma.organizationInvitation.findMany({
|
|
||||||
where: { inviterOrganizationId: organizationId },
|
|
||||||
orderBy: { createdAt: 'desc' },
|
|
||||||
}),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const linkItems = [
|
const linkItems = [
|
||||||
...linksA.map((l) => ({
|
...linksA.map((l) => ({
|
||||||
|
requestedByOrganizationId: this.getRequesterOrganizationId(l.sharedDataTypes),
|
||||||
id: l.id,
|
id: l.id,
|
||||||
kind: 'LINK' as const,
|
|
||||||
counterpartOrganizationId: l.organizationB.id,
|
counterpartOrganizationId: l.organizationB.id,
|
||||||
organizationName: l.organizationB.name,
|
organizationName: l.organizationB.name,
|
||||||
ownerEmail: l.organizationB.email,
|
ownerEmail: l.organizationB.email,
|
||||||
phone: l.organizationB.phone,
|
phone: l.organizationB.phone,
|
||||||
status: l.status,
|
status: l.status,
|
||||||
invitationUrl: null as string | null,
|
|
||||||
createdAt: l.createdAt.toISOString(),
|
createdAt: l.createdAt.toISOString(),
|
||||||
acceptedAt: l.status === LinkStatus.ACTIVE ? l.updatedAt.toISOString() : null,
|
acceptedAt: l.status === LinkStatus.ACTIVE ? l.updatedAt.toISOString() : null,
|
||||||
})),
|
})),
|
||||||
...linksB.map((l) => ({
|
...linksB.map((l) => ({
|
||||||
|
requestedByOrganizationId: this.getRequesterOrganizationId(l.sharedDataTypes),
|
||||||
id: l.id,
|
id: l.id,
|
||||||
kind: 'LINK' as const,
|
|
||||||
counterpartOrganizationId: l.organizationA.id,
|
counterpartOrganizationId: l.organizationA.id,
|
||||||
organizationName: l.organizationA.name,
|
organizationName: l.organizationA.name,
|
||||||
ownerEmail: l.organizationA.email,
|
ownerEmail: l.organizationA.email,
|
||||||
phone: l.organizationA.phone,
|
phone: l.organizationA.phone,
|
||||||
status: l.status,
|
status: l.status,
|
||||||
invitationUrl: null as string | null,
|
|
||||||
createdAt: l.createdAt.toISOString(),
|
createdAt: l.createdAt.toISOString(),
|
||||||
acceptedAt: l.status === LinkStatus.ACTIVE ? l.updatedAt.toISOString() : null,
|
acceptedAt: l.status === LinkStatus.ACTIVE ? l.updatedAt.toISOString() : null,
|
||||||
})),
|
})),
|
||||||
];
|
];
|
||||||
|
|
||||||
const inviteItems = invitations.map((i) => ({
|
return {
|
||||||
id: i.id,
|
success: true,
|
||||||
kind: 'INVITATION' as const,
|
data: {
|
||||||
counterpartOrganizationId: i.invitedOrganizationId,
|
items: linkItems.sort((a, b) =>
|
||||||
organizationName: i.invitedOrganizationName,
|
a.createdAt < b.createdAt ? 1 : -1,
|
||||||
ownerEmail: i.invitedOwnerEmail,
|
),
|
||||||
phone: null as string | null,
|
},
|
||||||
status: this.mapInvitationStatus(i.acceptedAt, i.revokedAt, i.expiresAt),
|
};
|
||||||
invitationUrl:
|
}
|
||||||
!i.acceptedAt && !i.revokedAt && i.expiresAt.getTime() > Date.now()
|
|
||||||
? this.buildInviteUrlFromTokenHashPlaceholder()
|
async listInvitationHistory(userId: string, organizationId: string) {
|
||||||
: null,
|
const actor = await this.getActorMembership(userId, organizationId);
|
||||||
createdAt: i.createdAt.toISOString(),
|
if (!actor || !this.canEditOrganizations(actor)) {
|
||||||
acceptedAt: i.acceptedAt?.toISOString() ?? null,
|
throw new ForbiddenException('You do not have permission to manage organizations');
|
||||||
}));
|
}
|
||||||
|
|
||||||
|
const invitations = await this.prisma.organizationInvitation.findMany({
|
||||||
|
where: { inviterOrganizationId: organizationId },
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
items: [...linkItems, ...inviteItems].sort((a, b) =>
|
items: invitations.map((i) => ({
|
||||||
a.createdAt < b.createdAt ? 1 : -1,
|
id: i.id,
|
||||||
),
|
organizationName: i.invitedOrganizationName,
|
||||||
|
ownerEmail: i.invitedOwnerEmail,
|
||||||
|
status: this.mapInvitationStatus(i.acceptedAt, i.revokedAt, i.expiresAt),
|
||||||
|
createdAt: i.createdAt.toISOString(),
|
||||||
|
acceptedAt: i.acceptedAt?.toISOString() ?? null,
|
||||||
|
})),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -183,7 +188,7 @@ export class OrganizationService {
|
|||||||
organizationAId: aId,
|
organizationAId: aId,
|
||||||
organizationBId: bId,
|
organizationBId: bId,
|
||||||
status: LinkStatus.PENDING,
|
status: LinkStatus.PENDING,
|
||||||
sharedDataTypes: [],
|
sharedDataTypes: [`requested_by:${organizationId}`],
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -194,6 +199,118 @@ export class OrganizationService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async respondToLinkRequest(
|
||||||
|
userId: string,
|
||||||
|
organizationId: string,
|
||||||
|
linkId: string,
|
||||||
|
dto: RespondLinkRequestDto,
|
||||||
|
) {
|
||||||
|
const actor = await this.getActorMembership(userId, organizationId);
|
||||||
|
if (!actor || !this.canEditOrganizations(actor)) {
|
||||||
|
throw new ForbiddenException('You do not have permission to manage organizations');
|
||||||
|
}
|
||||||
|
|
||||||
|
const link = await this.prisma.organizationLink.findFirst({
|
||||||
|
where: {
|
||||||
|
id: linkId,
|
||||||
|
OR: [{ organizationAId: organizationId }, { organizationBId: organizationId }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!link) {
|
||||||
|
throw new NotFoundException('Link request not found');
|
||||||
|
}
|
||||||
|
if (link.status !== LinkStatus.PENDING) {
|
||||||
|
throw new BadRequestException('Only pending link requests can be responded to');
|
||||||
|
}
|
||||||
|
|
||||||
|
const requesterOrgId = this.getRequesterOrganizationId(link.sharedDataTypes);
|
||||||
|
if (requesterOrgId && requesterOrgId === organizationId) {
|
||||||
|
throw new ForbiddenException('You cannot respond to your own link request');
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextStatus = dto.action === 'ACCEPT' ? LinkStatus.ACTIVE : LinkStatus.REJECTED;
|
||||||
|
const updated = await this.prisma.organizationLink.update({
|
||||||
|
where: { id: link.id },
|
||||||
|
data: { status: nextStatus },
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: { id: updated.id, status: updated.status },
|
||||||
|
message: nextStatus === LinkStatus.ACTIVE ? 'Link request accepted' : 'Link request rejected',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteLink(userId: string, organizationId: string, linkId: string) {
|
||||||
|
const actor = await this.getActorMembership(userId, organizationId);
|
||||||
|
if (!actor || !this.canEditOrganizations(actor)) {
|
||||||
|
throw new ForbiddenException('You do not have permission to manage organizations');
|
||||||
|
}
|
||||||
|
|
||||||
|
const link = await this.prisma.organizationLink.findFirst({
|
||||||
|
where: {
|
||||||
|
id: linkId,
|
||||||
|
status: LinkStatus.ACTIVE,
|
||||||
|
OR: [{ organizationAId: organizationId }, { organizationBId: organizationId }],
|
||||||
|
},
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (!link) {
|
||||||
|
throw new NotFoundException('Linked organization not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.prisma.organizationLink.delete({ where: { id: link.id } });
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: { id: link.id },
|
||||||
|
message: 'Linked organization removed',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async getInvitationLink(userId: string, organizationId: string, invitationId: string) {
|
||||||
|
const actor = await this.getActorMembership(userId, organizationId);
|
||||||
|
if (!actor || !this.canEditOrganizations(actor)) {
|
||||||
|
throw new ForbiddenException('You do not have permission to manage organizations');
|
||||||
|
}
|
||||||
|
|
||||||
|
const invitation = await this.prisma.organizationInvitation.findFirst({
|
||||||
|
where: {
|
||||||
|
id: invitationId,
|
||||||
|
inviterOrganizationId: organizationId,
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
acceptedAt: true,
|
||||||
|
revokedAt: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!invitation) {
|
||||||
|
throw new NotFoundException('Invitation not found');
|
||||||
|
}
|
||||||
|
if (invitation.acceptedAt || invitation.revokedAt) {
|
||||||
|
throw new BadRequestException('Only pending invitations can provide a link');
|
||||||
|
}
|
||||||
|
|
||||||
|
const plainToken = this.generateInviteToken();
|
||||||
|
const tokenHash = this.hashInviteToken(plainToken);
|
||||||
|
await this.prisma.organizationInvitation.update({
|
||||||
|
where: { id: invitation.id },
|
||||||
|
data: {
|
||||||
|
tokenHash,
|
||||||
|
expiresAt: this.getInviteExpiryDate(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
invitationId: invitation.id,
|
||||||
|
invitationUrl: this.buildInviteUrl(plainToken),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
async inviteOrganization(userId: string, organizationId: string, dto: InviteOrganizationDto) {
|
async inviteOrganization(userId: string, organizationId: string, dto: InviteOrganizationDto) {
|
||||||
const actor = await this.getActorMembership(userId, organizationId);
|
const actor = await this.getActorMembership(userId, organizationId);
|
||||||
if (!actor || !this.canEditOrganizations(actor)) {
|
if (!actor || !this.canEditOrganizations(actor)) {
|
||||||
@@ -219,26 +336,77 @@ export class OrganizationService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const invitedOrg = await this.prisma.organization.findFirst({
|
const invitation = await this.prisma.$transaction(async (tx) => {
|
||||||
where: {
|
let owner = await tx.user.findUnique({ where: { email: ownerEmail } });
|
||||||
owner: { email: ownerEmail },
|
if (!owner) {
|
||||||
type: { name: invitedType },
|
owner = await tx.user.create({
|
||||||
},
|
data: {
|
||||||
select: { id: true, name: true },
|
email: ownerEmail,
|
||||||
orderBy: { createdAt: 'desc' },
|
name: dto.organizationName.trim(),
|
||||||
});
|
passwordHash: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const invitation = await this.prisma.organizationInvitation.create({
|
let invitedOrg = await tx.organization.findFirst({
|
||||||
data: {
|
where: {
|
||||||
inviterOrganizationId: organizationId,
|
ownerId: owner.id,
|
||||||
inviterUserId: userId,
|
type: { name: invitedType },
|
||||||
invitedOrganizationId: invitedOrg?.id ?? null,
|
},
|
||||||
invitedOrganizationName: dto.organizationName.trim(),
|
select: { id: true },
|
||||||
invitedOwnerEmail: ownerEmail,
|
orderBy: { createdAt: 'desc' },
|
||||||
invitedOrganizationType: invitedType,
|
});
|
||||||
tokenHash,
|
|
||||||
expiresAt: this.getInviteExpiryDate(),
|
if (!invitedOrg) {
|
||||||
},
|
invitedOrg = await tx.organization.create({
|
||||||
|
data: {
|
||||||
|
name: dto.organizationName.trim(),
|
||||||
|
email: `pending-${plainToken.slice(0, 12)}@dyolink.local`,
|
||||||
|
owner: { connect: { id: owner.id } },
|
||||||
|
type: { connect: { name: invitedType } },
|
||||||
|
},
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const [aId, bId] =
|
||||||
|
organizationId < invitedOrg.id
|
||||||
|
? [organizationId, invitedOrg.id]
|
||||||
|
: [invitedOrg.id, organizationId];
|
||||||
|
|
||||||
|
const existingLink = await tx.organizationLink.findUnique({
|
||||||
|
where: { organizationAId_organizationBId: { organizationAId: aId, organizationBId: bId } },
|
||||||
|
});
|
||||||
|
if (existingLink?.status === LinkStatus.ACTIVE) {
|
||||||
|
throw new ConflictException('These organizations are already linked');
|
||||||
|
}
|
||||||
|
|
||||||
|
await tx.organizationLink.upsert({
|
||||||
|
where: { organizationAId_organizationBId: { organizationAId: aId, organizationBId: bId } },
|
||||||
|
update: {
|
||||||
|
status: LinkStatus.PENDING,
|
||||||
|
sharedDataTypes: [`requested_by:${organizationId}`],
|
||||||
|
},
|
||||||
|
create: {
|
||||||
|
organizationAId: aId,
|
||||||
|
organizationBId: bId,
|
||||||
|
status: LinkStatus.PENDING,
|
||||||
|
sharedDataTypes: [`requested_by:${organizationId}`],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return tx.organizationInvitation.create({
|
||||||
|
data: {
|
||||||
|
inviterOrganizationId: organizationId,
|
||||||
|
inviterUserId: userId,
|
||||||
|
invitedOrganizationId: invitedOrg.id,
|
||||||
|
invitedOrganizationName: dto.organizationName.trim(),
|
||||||
|
invitedOwnerEmail: ownerEmail,
|
||||||
|
invitedOrganizationType: invitedType,
|
||||||
|
tokenHash,
|
||||||
|
expiresAt: this.getInviteExpiryDate(),
|
||||||
|
},
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -430,6 +598,17 @@ export class OrganizationService {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private getRequesterOrganizationId(sharedDataTypes: unknown): string | null {
|
||||||
|
if (!Array.isArray(sharedDataTypes)) return null;
|
||||||
|
for (const v of sharedDataTypes) {
|
||||||
|
if (typeof v !== 'string') continue;
|
||||||
|
if (!v.startsWith('requested_by:')) continue;
|
||||||
|
const id = v.slice('requested_by:'.length).trim();
|
||||||
|
if (id) return id;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
private async findValidInvitation(token: string) {
|
private async findValidInvitation(token: string) {
|
||||||
const invitation = await this.prisma.organizationInvitation.findUnique({
|
const invitation = await this.prisma.organizationInvitation.findUnique({
|
||||||
where: { tokenHash: this.hashInviteToken(token) },
|
where: { tokenHash: this.hashInviteToken(token) },
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useEffect, useMemo, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
import { Search } from 'lucide-react';
|
||||||
import { useAuth } from '@/lib/hooks/useAuth';
|
import { useAuth } from '@/lib/hooks/useAuth';
|
||||||
import {
|
import {
|
||||||
organizationApi,
|
organizationApi,
|
||||||
type CounterpartItemDto,
|
type CounterpartItemDto,
|
||||||
type CounterpartSearchResultDto,
|
type CounterpartSearchResultDto,
|
||||||
|
type OrganizationInvitationHistoryItemDto,
|
||||||
} from '@/lib/api/organization';
|
} from '@/lib/api/organization';
|
||||||
import { Button } from '@/components/ui/common/Button';
|
import { Button } from '@/components/ui/common/Button';
|
||||||
import { Badge, organizationLinkStatusVariant } from '@/components/ui/common/Badge';
|
import { Badge, organizationLinkStatusVariant } from '@/components/ui/common/Badge';
|
||||||
@@ -39,13 +41,26 @@ function writeStoredInviteLinks(orgId: string, links: Record<string, StoredInvit
|
|||||||
window.localStorage.setItem(inviteLinksStorageKey(orgId), JSON.stringify(links));
|
window.localStorage.setItem(inviteLinksStorageKey(orgId), JSON.stringify(links));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** First letter uppercase, rest lowercase (e.g. ACTIVE → Active). */
|
|
||||||
function formatOrganizationStatusLabel(status: string): string {
|
function formatOrganizationStatusLabel(status: string): string {
|
||||||
if (!status) return status;
|
if (!status) return status;
|
||||||
const lower = status.toLowerCase();
|
const lower = status.toLowerCase();
|
||||||
return lower.charAt(0).toUpperCase() + lower.slice(1);
|
return lower.charAt(0).toUpperCase() + lower.slice(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatLinkStatusLabel(status: CounterpartItemDto['status']): string {
|
||||||
|
if (status === 'PENDING') return 'Link request pending';
|
||||||
|
if (status === 'ACTIVE') return 'Linked';
|
||||||
|
if (status === 'REJECTED') return 'Link request rejected';
|
||||||
|
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 {
|
function formatApiMessage(err: unknown): string {
|
||||||
if (!err || typeof err !== 'object') return 'Something went wrong';
|
if (!err || typeof err !== 'object') return 'Something went wrong';
|
||||||
const m = (err as ApiError).message;
|
const m = (err as ApiError).message;
|
||||||
@@ -54,33 +69,36 @@ function formatApiMessage(err: unknown): string {
|
|||||||
return 'Something went wrong';
|
return 'Something went wrong';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type TableMode = 'existing' | 'search';
|
||||||
|
|
||||||
export default function OrganizationsPage() {
|
export default function OrganizationsPage() {
|
||||||
const { currentOrganization } = useAuth();
|
const { currentOrganization } = useAuth();
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
const [success, setSuccess] = useState('');
|
const [success, setSuccess] = useState('');
|
||||||
|
|
||||||
const [searchTerm, setSearchTerm] = useState('');
|
const [query, setQuery] = useState('');
|
||||||
const [searchLoading, setSearchLoading] = useState(false);
|
const [mode, setMode] = useState<TableMode>('existing');
|
||||||
const [results, setResults] = useState<CounterpartSearchResultDto[]>([]);
|
const [searching, setSearching] = useState(false);
|
||||||
const [selectedOrgId, setSelectedOrgId] = useState<string | null>(null);
|
const [searchResults, setSearchResults] = useState<CounterpartSearchResultDto[]>([]);
|
||||||
const [linkLoading, setLinkLoading] = useState(false);
|
const [requestLinkRowId, setRequestLinkRowId] = useState<string | null>(null);
|
||||||
|
const [deleteLinkRowId, setDeleteLinkRowId] = useState<string | null>(null);
|
||||||
|
|
||||||
const [items, setItems] = useState<CounterpartItemDto[]>([]);
|
const [items, setItems] = useState<CounterpartItemDto[]>([]);
|
||||||
const [manualOrganizationName, setManualOrganizationName] = useState('');
|
const [manualOrganizationName, setManualOrganizationName] = useState('');
|
||||||
const [manualOwnerEmail, setManualOwnerEmail] = useState('');
|
const [manualOwnerEmail, setManualOwnerEmail] = useState('');
|
||||||
const [manualPhone, setManualPhone] = useState('');
|
|
||||||
const [inviteLoading, setInviteLoading] = useState(false);
|
const [inviteLoading, setInviteLoading] = useState(false);
|
||||||
const [copiedId, setCopiedId] = useState<string | null>(null);
|
const [copiedId, setCopiedId] = useState<string | null>(null);
|
||||||
const [pendingInviteLinks, setPendingInviteLinks] = useState<Record<string, StoredInviteLink>>({});
|
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 counterpartLabel = currentOrganization?.type === 'LAB' ? 'Clinic' : 'Lab';
|
const counterpartLabel = currentOrganization?.type === 'LAB' ? 'Clinic' : 'Lab';
|
||||||
const tabLabel = currentOrganization?.type === 'LAB' ? 'Clinics' : 'Labs';
|
const tabLabel = currentOrganization?.type === 'LAB' ? 'Clinics' : 'Labs';
|
||||||
|
|
||||||
const selectedResult = useMemo(
|
const existingRows = items;
|
||||||
() => results.find((r) => r.id === selectedOrgId) ?? null,
|
|
||||||
[results, selectedOrgId],
|
|
||||||
);
|
|
||||||
|
|
||||||
async function loadList() {
|
async function loadList() {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -111,34 +129,43 @@ export default function OrganizationsPage() {
|
|||||||
}, [success]);
|
}, [success]);
|
||||||
|
|
||||||
async function runSearch() {
|
async function runSearch() {
|
||||||
setSearchLoading(true);
|
const q = query.trim();
|
||||||
|
if (!q) {
|
||||||
|
setMode('existing');
|
||||||
|
setSearchResults([]);
|
||||||
|
setShowInviteForm(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSearching(true);
|
||||||
setError('');
|
setError('');
|
||||||
setSelectedOrgId(null);
|
setMode('search');
|
||||||
|
setShowInviteForm(false);
|
||||||
try {
|
try {
|
||||||
const res = await organizationApi.search(searchTerm.trim());
|
const res = await organizationApi.search(q);
|
||||||
setResults(res.data);
|
setSearchResults(res.data);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(formatApiMessage(e));
|
setError(formatApiMessage(e));
|
||||||
|
setSearchResults([]);
|
||||||
} finally {
|
} finally {
|
||||||
setSearchLoading(false);
|
setSearching(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createLink() {
|
async function submitRequestLink(targetOrganizationId: string) {
|
||||||
if (!selectedOrgId) return;
|
setRequestLinkRowId(targetOrganizationId);
|
||||||
setLinkLoading(true);
|
|
||||||
setError('');
|
setError('');
|
||||||
try {
|
try {
|
||||||
await organizationApi.createLink(selectedOrgId);
|
await organizationApi.createLink(targetOrganizationId);
|
||||||
setSuccess(`${counterpartLabel} link request created`);
|
setSuccess(`${counterpartLabel} link request sent`);
|
||||||
setResults([]);
|
setSearchResults([]);
|
||||||
setSelectedOrgId(null);
|
setQuery('');
|
||||||
setSearchTerm('');
|
setMode('existing');
|
||||||
await loadList();
|
await loadList();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(formatApiMessage(e));
|
setError(formatApiMessage(e));
|
||||||
} finally {
|
} finally {
|
||||||
setLinkLoading(false);
|
setRequestLinkRowId(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,7 +176,6 @@ export default function OrganizationsPage() {
|
|||||||
const res = await organizationApi.invite({
|
const res = await organizationApi.invite({
|
||||||
organizationName: manualOrganizationName.trim(),
|
organizationName: manualOrganizationName.trim(),
|
||||||
ownerEmail: manualOwnerEmail.trim(),
|
ownerEmail: manualOwnerEmail.trim(),
|
||||||
phone: manualPhone.trim() || undefined,
|
|
||||||
});
|
});
|
||||||
if (currentOrganization?.id) {
|
if (currentOrganization?.id) {
|
||||||
const nextLinks = {
|
const nextLinks = {
|
||||||
@@ -166,7 +192,10 @@ export default function OrganizationsPage() {
|
|||||||
setSuccess(`Invitation link created for ${manualOwnerEmail.trim()}`);
|
setSuccess(`Invitation link created for ${manualOwnerEmail.trim()}`);
|
||||||
setManualOrganizationName('');
|
setManualOrganizationName('');
|
||||||
setManualOwnerEmail('');
|
setManualOwnerEmail('');
|
||||||
setManualPhone('');
|
setShowInviteForm(false);
|
||||||
|
setMode('existing');
|
||||||
|
setQuery('');
|
||||||
|
setSearchResults([]);
|
||||||
await loadList();
|
await loadList();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(formatApiMessage(e));
|
setError(formatApiMessage(e));
|
||||||
@@ -175,18 +204,100 @@ export default function OrganizationsPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function openInvitationHistory() {
|
||||||
|
setHistoryOpen(true);
|
||||||
|
setHistoryLoading(true);
|
||||||
|
setError('');
|
||||||
|
try {
|
||||||
|
const res = await organizationApi.listInvitations();
|
||||||
|
setHistoryItems(res.data.items);
|
||||||
|
} catch (e) {
|
||||||
|
setError(formatApiMessage(e));
|
||||||
|
} finally {
|
||||||
|
setHistoryLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function respondToPendingLink(linkId: string, action: 'ACCEPT' | 'REJECT') {
|
||||||
|
setRequestLinkRowId(linkId);
|
||||||
|
setError('');
|
||||||
|
try {
|
||||||
|
await organizationApi.respondLink(linkId, action);
|
||||||
|
setSuccess(action === 'ACCEPT' ? 'Link request accepted' : 'Link request rejected');
|
||||||
|
await loadList();
|
||||||
|
} catch (e) {
|
||||||
|
setError(formatApiMessage(e));
|
||||||
|
} finally {
|
||||||
|
setRequestLinkRowId(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteLinkedOrganization(linkId: string) {
|
||||||
|
setDeleteLinkRowId(linkId);
|
||||||
|
setError('');
|
||||||
|
try {
|
||||||
|
await organizationApi.deleteLink(linkId);
|
||||||
|
setSuccess('Linked organization removed');
|
||||||
|
await loadList();
|
||||||
|
} catch (e) {
|
||||||
|
setError(formatApiMessage(e));
|
||||||
|
} finally {
|
||||||
|
setDeleteLinkRowId(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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('');
|
||||||
|
setSearchResults([]);
|
||||||
|
setShowInviteForm(false);
|
||||||
|
}
|
||||||
|
|
||||||
if (!currentOrganization) {
|
if (!currentOrganization) {
|
||||||
return <p className="text-sm text-text-secondary">Loading organization...</p>;
|
return <p className="text-sm text-text-secondary">Loading organization...</p>;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div>
|
<div className="flex flex-col gap-1 sm:flex-row sm:items-start sm:justify-between">
|
||||||
<h1 className="text-2xl font-semibold text-text-primary">{tabLabel}</h1>
|
<div>
|
||||||
<p className="text-sm text-text-secondary mt-1">
|
<h1 className="text-2xl font-semibold text-text-primary">{tabLabel}</h1>
|
||||||
Search subscribed {tabLabel.toLowerCase()}, request link access, or invite a new{' '}
|
<p className="text-sm text-text-secondary mt-1">
|
||||||
{counterpartLabel.toLowerCase()} owner.
|
Search organizations and send link requests or invitation links in one place.
|
||||||
</p>
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button type="button" size="sm" onClick={() => void openInvitationHistory()}>
|
||||||
|
Invitation history
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
@@ -200,152 +311,256 @@ export default function OrganizationsPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="rounded-[var(--radius-md)] border border-border/70 p-4 space-y-3">
|
<div className="surface-card p-4">
|
||||||
<h2 className="text-base font-semibold text-text-primary">Search existing {tabLabel}</h2>
|
<div className="flex gap-4 items-center">
|
||||||
<div className="flex gap-2">
|
<div className="flex-1">
|
||||||
<Input
|
<Input
|
||||||
value={searchTerm}
|
placeholder={`Search ${counterpartLabel.toLowerCase()} by name, email, or phone...`}
|
||||||
onChange={(e) => setSearchTerm(e.target.value)}
|
value={query}
|
||||||
placeholder={`Search by ${counterpartLabel.toLowerCase()} name, email, or phone`}
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
/>
|
onKeyDown={(e) => {
|
||||||
<Button type="button" isLoading={searchLoading} onClick={() => void runSearch()}>
|
if (e.key === 'Enter') void runSearch();
|
||||||
|
}}
|
||||||
|
icon={<Search className="h-4 w-4 icon-flat" />}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button type="button" isLoading={searching} onClick={() => void runSearch()}>
|
||||||
Search
|
Search
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
{mode === 'search' && (
|
||||||
|
<Button type="button" variant="outline" onClick={clearSearchView}>
|
||||||
{results.length > 0 && (
|
Back to list
|
||||||
<div className="space-y-2 pt-1">
|
</Button>
|
||||||
{results.map((r) => (
|
)}
|
||||||
<button
|
|
||||||
key={r.id}
|
|
||||||
type="button"
|
|
||||||
onClick={() => setSelectedOrgId(r.id)}
|
|
||||||
className={`w-full text-left rounded-[var(--radius-md)] border px-3 py-2 ${
|
|
||||||
selectedOrgId === r.id
|
|
||||||
? 'border-primary/70 bg-primary-soft/30'
|
|
||||||
: 'border-border/60 hover:border-border-strong'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<p className="text-sm font-medium text-text-primary">{r.name}</p>
|
|
||||||
<p className="text-xs text-text-secondary mt-0.5">
|
|
||||||
{r.email}
|
|
||||||
{r.phone ? ` - ${r.phone}` : ''}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-text-muted mt-0.5">Owner: {r.owner.email}</p>
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex justify-end">
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
isLoading={linkLoading}
|
|
||||||
disabled={!selectedResult}
|
|
||||||
onClick={() => void createLink()}
|
|
||||||
>
|
|
||||||
Request link
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="rounded-[var(--radius-md)] border border-border/70 p-4 space-y-3">
|
<div className="surface-card overflow-hidden">
|
||||||
<h2 className="text-base font-semibold text-text-primary">Invite owner (not yet subscribed)</h2>
|
<table className="w-full">
|
||||||
<Input
|
<thead className="bg-background-secondary/70 border-b border-border">
|
||||||
label={`${counterpartLabel} name`}
|
<tr>
|
||||||
value={manualOrganizationName}
|
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
|
||||||
onChange={(e) => setManualOrganizationName(e.target.value)}
|
Organization
|
||||||
/>
|
</th>
|
||||||
<Input
|
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
|
||||||
label="Owner email"
|
Owner email
|
||||||
type="email"
|
</th>
|
||||||
value={manualOwnerEmail}
|
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
|
||||||
onChange={(e) => setManualOwnerEmail(e.target.value)}
|
Type
|
||||||
/>
|
</th>
|
||||||
<Input
|
<th className="px-6 py-3 text-center text-xs font-medium text-text-muted uppercase tracking-wider">
|
||||||
label="Mobile number (optional)"
|
Status
|
||||||
value={manualPhone}
|
</th>
|
||||||
onChange={(e) => setManualPhone(e.target.value)}
|
<th className="px-6 py-3 text-right text-xs font-medium text-text-muted uppercase tracking-wider">
|
||||||
/>
|
Action
|
||||||
<div className="flex justify-end">
|
</th>
|
||||||
<Button
|
</tr>
|
||||||
type="button"
|
</thead>
|
||||||
isLoading={inviteLoading}
|
<tbody className="divide-y divide-border/60">
|
||||||
disabled={!manualOrganizationName.trim() || !manualOwnerEmail.trim()}
|
{loading ? (
|
||||||
onClick={() => void sendInvite()}
|
<tr>
|
||||||
>
|
<td colSpan={5} className="px-6 py-8 text-sm text-text-secondary">
|
||||||
Send invite link
|
Loading...
|
||||||
</Button>
|
</td>
|
||||||
</div>
|
</tr>
|
||||||
</div>
|
) : mode === 'existing' ? (
|
||||||
|
existingRows.length === 0 ? (
|
||||||
<div className="rounded-[var(--radius-md)] border border-border/70">
|
<tr>
|
||||||
<div className="border-b border-border/70 px-4 py-3">
|
<td colSpan={5} className="px-6 py-8 text-sm text-text-secondary">
|
||||||
<h2 className="text-base font-semibold text-text-primary">Requests and invitations</h2>
|
No organizations linked or pending yet. Use search to find and connect.
|
||||||
</div>
|
</td>
|
||||||
{loading ? (
|
|
||||||
<p className="px-4 py-4 text-sm text-text-secondary">Loading list...</p>
|
|
||||||
) : items.length === 0 ? (
|
|
||||||
<p className="px-4 py-4 text-sm text-text-secondary">No records yet.</p>
|
|
||||||
) : (
|
|
||||||
<div className="overflow-x-auto">
|
|
||||||
<table className="w-full text-sm">
|
|
||||||
<thead>
|
|
||||||
<tr className="border-b border-border/70 text-left text-text-secondary">
|
|
||||||
<th className="p-3 font-medium">Type</th>
|
|
||||||
<th className="p-3 font-medium">Organization</th>
|
|
||||||
<th className="p-3 font-medium">Owner email</th>
|
|
||||||
<th className="p-3 font-medium">Status</th>
|
|
||||||
<th className="p-3 font-medium">Action</th>
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
) : (
|
||||||
<tbody>
|
existingRows.map((row) => {
|
||||||
{items.map((item) => (
|
const canRespond =
|
||||||
<tr key={item.id} className="border-b border-border/40 last:border-0">
|
row.status === 'PENDING' &&
|
||||||
<td className="p-3 text-text-secondary">
|
row.requestedByOrganizationId !== null &&
|
||||||
{item.kind === 'LINK' ? 'Link request' : 'Invitation'}
|
row.requestedByOrganizationId !== currentOrganization.id;
|
||||||
</td>
|
|
||||||
<td className="p-3 text-text-primary">{item.organizationName}</td>
|
return (
|
||||||
<td className="p-3 text-text-secondary">{item.ownerEmail}</td>
|
<tr key={row.id} className="hover:bg-background-secondary/45">
|
||||||
<td className="p-3">
|
<td className="px-6 py-4 text-sm font-medium text-text-primary">
|
||||||
<Badge
|
{row.organizationName}
|
||||||
variant={organizationLinkStatusVariant(item.status)}
|
</td>
|
||||||
fixedWidth
|
<td className="px-6 py-4 text-sm text-text-secondary">{row.ownerEmail}</td>
|
||||||
>
|
<td className="px-6 py-4 text-sm text-text-secondary">Link</td>
|
||||||
{formatOrganizationStatusLabel(item.status)}
|
<td className="px-6 py-4 text-center align-middle">
|
||||||
</Badge>
|
<Badge variant={organizationLinkStatusVariant(row.status)} fixedWidth={false}>
|
||||||
</td>
|
{formatLinkStatusLabel(row.status)}
|
||||||
<td className="p-3">
|
</Badge>
|
||||||
{item.kind === 'INVITATION' &&
|
</td>
|
||||||
item.status === 'PENDING' &&
|
<td className="px-6 py-4 text-right">
|
||||||
pendingInviteLinks[item.id]?.invitationUrl && (
|
<div className="inline-flex items-center gap-2">
|
||||||
|
{canRespond && (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
isLoading={requestLinkRowId === row.id}
|
||||||
|
disabled={requestLinkRowId !== null && requestLinkRowId !== row.id}
|
||||||
|
onClick={() => void respondToPendingLink(row.id, 'ACCEPT')}
|
||||||
|
>
|
||||||
|
Accept
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
isLoading={requestLinkRowId === row.id}
|
||||||
|
disabled={requestLinkRowId !== null && requestLinkRowId !== row.id}
|
||||||
|
onClick={() => void respondToPendingLink(row.id, 'REJECT')}
|
||||||
|
>
|
||||||
|
Reject
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{row.status === 'ACTIVE' && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
isLoading={deleteLinkRowId === row.id}
|
||||||
|
disabled={deleteLinkRowId !== null && deleteLinkRowId !== row.id}
|
||||||
|
onClick={() => void deleteLinkedOrganization(row.id)}
|
||||||
|
>
|
||||||
|
Delete link
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)
|
||||||
|
) : searchResults.length > 0 ? (
|
||||||
|
searchResults.map((r) => (
|
||||||
|
<tr key={r.id} className="hover:bg-background-secondary/45">
|
||||||
|
<td className="px-6 py-4 text-sm font-medium text-text-primary">{r.name}</td>
|
||||||
|
<td className="px-6 py-4 text-sm text-text-secondary">{r.owner.email}</td>
|
||||||
|
<td className="px-6 py-4 text-sm text-text-secondary">Directory match</td>
|
||||||
|
<td className="px-6 py-4 text-center align-middle">
|
||||||
|
<Badge variant="default" fixedWidth={false}>Found</Badge>
|
||||||
|
</td>
|
||||||
|
<td className="px-6 py-4 text-right">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
isLoading={requestLinkRowId === r.id}
|
||||||
|
disabled={requestLinkRowId !== null && requestLinkRowId !== r.id}
|
||||||
|
onClick={() => void submitRequestLink(r.id)}
|
||||||
|
>
|
||||||
|
Send link request
|
||||||
|
</Button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={5} className="px-6 py-6">
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<p className="text-sm text-text-secondary">
|
||||||
|
No organization found in directory search.
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<Button type="button" onClick={() => setShowInviteForm((v) => !v)}>
|
||||||
|
{showInviteForm ? 'Hide invitation fields' : 'Send invitation link'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{showInviteForm && (
|
||||||
|
<div className="grid gap-3 sm:grid-cols-3 mt-1">
|
||||||
|
<Input
|
||||||
|
label={`${counterpartLabel} name`}
|
||||||
|
value={manualOrganizationName}
|
||||||
|
onChange={(e) => setManualOrganizationName(e.target.value)}
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
label="Owner email"
|
||||||
|
type="email"
|
||||||
|
value={manualOwnerEmail}
|
||||||
|
onChange={(e) => setManualOwnerEmail(e.target.value)}
|
||||||
|
/>
|
||||||
|
<div className="flex items-end">
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
isLoading={inviteLoading}
|
||||||
size="sm"
|
disabled={!manualOrganizationName.trim() || !manualOwnerEmail.trim()}
|
||||||
onClick={async () => {
|
onClick={() => void sendInvite()}
|
||||||
try {
|
className="w-full"
|
||||||
await navigator.clipboard.writeText(
|
|
||||||
pendingInviteLinks[item.id].invitationUrl,
|
|
||||||
);
|
|
||||||
setCopiedId(item.id);
|
|
||||||
setTimeout(() => setCopiedId(null), 1500);
|
|
||||||
} catch {
|
|
||||||
setError('Could not copy invitation link');
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
{copiedId === item.id ? 'Copied' : 'Copy link'}
|
Send invitation
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
</div>
|
||||||
</td>
|
</div>
|
||||||
</tr>
|
)}
|
||||||
))}
|
</div>
|
||||||
</tbody>
|
</td>
|
||||||
</table>
|
</tr>
|
||||||
</div>
|
)}
|
||||||
)}
|
</tbody>
|
||||||
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{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>
|
||||||
|
) : (
|
||||||
|
<div className="overflow-x-auto rounded-[var(--radius-md)] border border-border/70">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-border/70 text-left text-text-secondary">
|
||||||
|
<th className="p-3 font-medium">Organization</th>
|
||||||
|
<th className="p-3 font-medium">Owner email</th>
|
||||||
|
<th className="p-3 font-medium">Status</th>
|
||||||
|
<th className="p-3 font-medium">Action</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{historyItems.map((inv) => (
|
||||||
|
<tr key={inv.id} className="border-b border-border/40 last:border-0">
|
||||||
|
<td className="p-3 text-text-primary">{inv.organizationName}</td>
|
||||||
|
<td className="p-3 text-text-secondary">{inv.ownerEmail}</td>
|
||||||
|
<td className="p-3">
|
||||||
|
<Badge variant={organizationLinkStatusVariant(inv.status)} fixedWidth={false}>
|
||||||
|
{formatInvitationStatusLabel(inv.status)}
|
||||||
|
</Badge>
|
||||||
|
</td>
|
||||||
|
<td className="p-3">
|
||||||
|
{inv.status === 'PENDING' ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => void copyInvitationLink(inv.id)}
|
||||||
|
>
|
||||||
|
{copiedId === inv.id ? 'Copied' : 'Copy link'}
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<span className="text-xs text-text-muted">—</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,13 +10,21 @@ export interface CounterpartSearchResultDto {
|
|||||||
|
|
||||||
export interface CounterpartItemDto {
|
export interface CounterpartItemDto {
|
||||||
id: string;
|
id: string;
|
||||||
kind: 'LINK' | 'INVITATION';
|
requestedByOrganizationId: string | null;
|
||||||
counterpartOrganizationId: string | null;
|
counterpartOrganizationId: string | null;
|
||||||
organizationName: string;
|
organizationName: string;
|
||||||
ownerEmail: string;
|
ownerEmail: string;
|
||||||
phone: string | null;
|
phone: string | null;
|
||||||
status: 'PENDING' | 'ACTIVE' | 'REJECTED' | 'EXPIRED';
|
status: 'PENDING' | 'ACTIVE' | 'REJECTED' | 'EXPIRED';
|
||||||
invitationUrl: string | null;
|
createdAt: string;
|
||||||
|
acceptedAt: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrganizationInvitationHistoryItemDto {
|
||||||
|
id: string;
|
||||||
|
organizationName: string;
|
||||||
|
ownerEmail: string;
|
||||||
|
status: 'PENDING' | 'ACTIVE' | 'REJECTED' | 'EXPIRED';
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
acceptedAt: string | null;
|
acceptedAt: string | null;
|
||||||
}
|
}
|
||||||
@@ -32,6 +40,14 @@ export const organizationApi = {
|
|||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
listInvitations: async (): Promise<{
|
||||||
|
success: boolean;
|
||||||
|
data: { items: OrganizationInvitationHistoryItemDto[] };
|
||||||
|
}> => {
|
||||||
|
const response = await apiClient.get('/organizations/invitations');
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
|
||||||
createLink: async (
|
createLink: async (
|
||||||
targetOrganizationId: string,
|
targetOrganizationId: string,
|
||||||
): Promise<{ success: boolean; data: { id: string; status: 'PENDING' | 'ACTIVE' | 'REJECTED' } }> => {
|
): Promise<{ success: boolean; data: { id: string; status: 'PENDING' | 'ACTIVE' | 'REJECTED' } }> => {
|
||||||
@@ -39,6 +55,19 @@ export const organizationApi = {
|
|||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
respondLink: async (
|
||||||
|
linkId: string,
|
||||||
|
action: 'ACCEPT' | 'REJECT',
|
||||||
|
): Promise<{ success: boolean; data: { id: string; status: 'PENDING' | 'ACTIVE' | 'REJECTED' } }> => {
|
||||||
|
const response = await apiClient.patch(`/organizations/links/${linkId}/respond`, { action });
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
deleteLink: async (linkId: string): Promise<{ success: boolean; data: { id: string }; message: string }> => {
|
||||||
|
const response = await apiClient.delete(`/organizations/links/${linkId}`);
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
|
||||||
invite: async (body: {
|
invite: async (body: {
|
||||||
organizationName: string;
|
organizationName: string;
|
||||||
ownerEmail: string;
|
ownerEmail: string;
|
||||||
@@ -48,6 +77,13 @@ export const organizationApi = {
|
|||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
getInvitationLink: async (
|
||||||
|
invitationId: string,
|
||||||
|
): Promise<{ success: boolean; data: { invitationId: string; invitationUrl: string } }> => {
|
||||||
|
const response = await apiClient.post(`/organizations/invitations/${invitationId}/link`);
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
|
||||||
previewInvite: async (
|
previewInvite: async (
|
||||||
token: string,
|
token: string,
|
||||||
): Promise<{
|
): Promise<{
|
||||||
|
|||||||
Reference in New Issue
Block a user