bugfix: copy/regenerate link for invitation action added to connection request lis in orgs feature.

This commit is contained in:
2026-05-17 13:13:59 +03:30
parent 09b511a136
commit 046257c071
14 changed files with 384 additions and 171 deletions

View File

@@ -0,0 +1,7 @@
import { IsUUID } from 'class-validator';
/** Existing subscribed counterpart org (search result). Does not create an OrganizationInvitation. */
export class CreateConnectionRequestDto {
@IsUUID()
targetOrganizationId: string;
}

View File

@@ -1,6 +0,0 @@
import { IsUUID } from 'class-validator';
export class CreateLinkRequestDto {
@IsUUID()
targetOrganizationId: string;
}

View File

@@ -1,5 +1,6 @@
import { IsEmail, IsOptional, IsString, MinLength } from 'class-validator';
/** Starts invitation-link flow: creates OrganizationInvitation + PENDING OrganizationLink. */
export class InviteOrganizationDto {
@IsString()
@MinLength(1)

View File

@@ -0,0 +1,7 @@
import { IsIn } from 'class-validator';
/** Counterpart org accepts or declines an incoming OrganizationLink (connection request). */
export class RespondConnectionRequestDto {
@IsIn(['ACCEPT', 'REJECT'])
action: 'ACCEPT' | 'REJECT';
}

View File

@@ -1,6 +0,0 @@
import { IsIn } from 'class-validator';
export class RespondLinkRequestDto {
@IsIn(['ACCEPT', 'REJECT'])
action: 'ACCEPT' | 'REJECT';
}

View File

@@ -13,12 +13,18 @@ import {
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { AcceptOrganizationInviteDto } from './dto/accept-organization-invite.dto';
import { CreateLinkRequestDto } from './dto/create-link-request.dto';
import { CreateConnectionRequestDto } from './dto/create-connection-request.dto';
import { InviteOrganizationDto } from './dto/invite-organization.dto';
import { PreviewOrganizationInviteDto } from './dto/preview-organization-invite.dto';
import { RespondLinkRequestDto } from './dto/respond-link-request.dto';
import { RespondConnectionRequestDto } from './dto/respond-connection-request.dto';
import { OrganizationService } from './organization.service';
/**
* Counterpart orgs (clinic↔lab).
*
* - `/connections` — OrganizationLink rows (connection requests + links created by invites).
* - `/invite`, `/invitations/*` — signup invitation tokens (orgs not yet on DyoLink).
*/
@ApiTags('organizations')
@ApiBearerAuth('JWT-auth')
@Controller('organizations')
@@ -58,46 +64,53 @@ export class OrganizationController {
return this.organizationService.searchCounterpartOrganizations(req.user.id, organizationId, q);
}
@Get('links')
@Get('connections')
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'List counterpart links and invitations for current org' })
list(@Req() req: { user: { id: string; organizationId?: string } }) {
@ApiOperation({ summary: 'List counterpart connections for current organization' })
listConnections(@Req() req: { user: { id: string; organizationId?: string } }) {
const organizationId = this.organizationService.getOrganizationIdFromUser(req.user);
return this.organizationService.list(req.user.id, organizationId);
}
@Post('links')
@Post('connections')
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Create pending link request to an existing subscribed counterpart org' })
createLinkRequest(
@ApiOperation({
summary: 'Create pending connection request to an existing subscribed counterpart org',
})
createConnectionRequest(
@Req() req: { user: { id: string; organizationId?: string } },
@Body() dto: CreateLinkRequestDto,
@Body() dto: CreateConnectionRequestDto,
) {
const organizationId = this.organizationService.getOrganizationIdFromUser(req.user);
return this.organizationService.createLinkRequest(req.user.id, organizationId, dto);
return this.organizationService.createConnectionRequest(req.user.id, organizationId, dto);
}
@Patch('links/:linkId/respond')
@Patch('connections/:connectionId/respond')
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Accept or reject a pending link request for current organization' })
respondToLinkRequest(
@ApiOperation({ summary: 'Accept or reject a pending connection request for current organization' })
respondToConnectionRequest(
@Req() req: { user: { id: string; organizationId?: string } },
@Param('linkId') linkId: string,
@Body() dto: RespondLinkRequestDto,
@Param('connectionId') connectionId: string,
@Body() dto: RespondConnectionRequestDto,
) {
const organizationId = this.organizationService.getOrganizationIdFromUser(req.user);
return this.organizationService.respondToLinkRequest(req.user.id, organizationId, linkId, dto);
return this.organizationService.respondToConnectionRequest(
req.user.id,
organizationId,
connectionId,
dto,
);
}
@Delete('links/:linkId')
@Delete('connections/:connectionId')
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Delete linked organization record' })
deleteLink(
@ApiOperation({ summary: 'Remove an active connection' })
deleteConnection(
@Req() req: { user: { id: string; organizationId?: string } },
@Param('linkId') linkId: string,
@Param('connectionId') connectionId: string,
) {
const organizationId = this.organizationService.getOrganizationIdFromUser(req.user);
return this.organizationService.deleteLink(req.user.id, organizationId, linkId);
return this.organizationService.deleteConnection(req.user.id, organizationId, connectionId);
}
@Post('invitations/:invitationId/link')

View File

@@ -10,10 +10,22 @@ import * as bcrypt from 'bcrypt';
import { createHash, randomBytes } from 'crypto';
import { PrismaService } from '../../../prisma/prisma.service';
import { AcceptOrganizationInviteDto } from './dto/accept-organization-invite.dto';
import { CreateLinkRequestDto } from './dto/create-link-request.dto';
import { CreateConnectionRequestDto } from './dto/create-connection-request.dto';
import { InviteOrganizationDto } from './dto/invite-organization.dto';
import { RespondLinkRequestDto } from './dto/respond-link-request.dto';
import { RespondConnectionRequestDto } from './dto/respond-connection-request.dto';
/**
* Clinic↔lab counterpart relationships.
*
* **Connection request** (`createConnectionRequest`): target org already exists with a subscription.
* Creates OrganizationLink PENDING only; counterpart accepts via `respondToConnectionRequest`.
*
* **Invitation link** (`inviteOrganization`): target not in directory (no subscription). Creates
* placeholder Organization + OrganizationInvitation + PENDING OrganizationLink in one transaction.
* Invitee signs up via `acceptInvite`, which activates the link—no second connection request needed.
*
* API name is "connection"; Prisma model remains `OrganizationLink` (historical table name).
*/
@Injectable()
export class OrganizationService {
constructor(private readonly prisma: PrismaService) {}
@@ -62,13 +74,16 @@ export class OrganizationService {
return { success: true, data: organizations };
}
/** Connections list for the Organizations tab (both sides of each link). */
async list(userId: string, organizationId: 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 [linksA, linksB] = await Promise.all([
// Open outbound invitations keyed by placeholder/real invited org id — lets UI show copy-invite
// on the auto-created PENDING link without opening invitation history.
const [linksA, linksB, outboundInvitations] = await Promise.all([
this.prisma.organizationLink.findMany({
where: { organizationAId: organizationId },
include: {
@@ -83,31 +98,56 @@ export class OrganizationService {
},
orderBy: { createdAt: 'desc' },
}),
this.prisma.organizationInvitation.findMany({
where: {
inviterOrganizationId: organizationId,
acceptedAt: null,
revokedAt: null,
invitedOrganizationId: { not: null },
},
select: {
id: true,
invitedOrganizationId: true,
invitedOwnerEmail: true,
expiresAt: true,
acceptedAt: true,
revokedAt: true,
},
}),
]);
const invitationByOrgId = new Map(
outboundInvitations
.filter((inv) => inv.invitedOrganizationId)
.map((inv) => [inv.invitedOrganizationId as string, inv]),
);
const mapLinkItem = (
l: (typeof linksA)[number] | (typeof linksB)[number],
counterpart: { id: string; name: string; email: string; phone: string | null },
) => {
const invitation = invitationByOrgId.get(counterpart.id);
return {
requestedByOrganizationId: this.getRequesterOrganizationId(l.sharedDataTypes),
id: l.id,
counterpartOrganizationId: counterpart.id,
organizationName: counterpart.name,
ownerEmail: invitation?.invitedOwnerEmail ?? counterpart.email,
phone: counterpart.phone,
status: l.status,
createdAt: l.createdAt.toISOString(),
acceptedAt: l.status === LinkStatus.ACTIVE ? l.updatedAt.toISOString() : null,
// Present only for invite-flow pending links (see inviteOrganization).
pendingInvitationId: invitation?.id ?? null,
invitationStatus: invitation
? this.mapInvitationStatus(invitation.acceptedAt, invitation.revokedAt, invitation.expiresAt)
: null,
};
};
const linkItems = [
...linksA.map((l) => ({
requestedByOrganizationId: this.getRequesterOrganizationId(l.sharedDataTypes),
id: l.id,
counterpartOrganizationId: l.organizationB.id,
organizationName: l.organizationB.name,
ownerEmail: l.organizationB.email,
phone: l.organizationB.phone,
status: l.status,
createdAt: l.createdAt.toISOString(),
acceptedAt: l.status === LinkStatus.ACTIVE ? l.updatedAt.toISOString() : null,
})),
...linksB.map((l) => ({
requestedByOrganizationId: this.getRequesterOrganizationId(l.sharedDataTypes),
id: l.id,
counterpartOrganizationId: l.organizationA.id,
organizationName: l.organizationA.name,
ownerEmail: l.organizationA.email,
phone: l.organizationA.phone,
status: l.status,
createdAt: l.createdAt.toISOString(),
acceptedAt: l.status === LinkStatus.ACTIVE ? l.updatedAt.toISOString() : null,
})),
...linksA.map((l) => mapLinkItem(l, l.organizationB)),
...linksB.map((l) => mapLinkItem(l, l.organizationA)),
];
return {
@@ -146,7 +186,12 @@ export class OrganizationService {
};
}
async createLinkRequest(userId: string, organizationId: string, dto: CreateLinkRequestDto) {
/** Flow 1: request to connect with an org that already has planId (found via search). */
async createConnectionRequest(
userId: string,
organizationId: string,
dto: CreateConnectionRequestDto,
) {
const actor = await this.getActorMembership(userId, organizationId);
if (!actor || !this.canEditOrganizations(actor)) {
throw new ForbiddenException('You do not have permission to manage organizations');
@@ -188,6 +233,7 @@ export class OrganizationService {
organizationAId: aId,
organizationBId: bId,
status: LinkStatus.PENDING,
// Who initiated; counterpart uses this to block self-accept (see respondToConnectionRequest).
sharedDataTypes: [`requested_by:${organizationId}`],
},
});
@@ -195,79 +241,83 @@ export class OrganizationService {
return {
success: true,
data: { id: created.id, status: created.status },
message: 'Link request created',
message: 'Connection request created',
};
}
async respondToLinkRequest(
async respondToConnectionRequest(
userId: string,
organizationId: string,
linkId: string,
dto: RespondLinkRequestDto,
connectionId: string,
dto: RespondConnectionRequestDto,
) {
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({
const connection = await this.prisma.organizationLink.findFirst({
where: {
id: linkId,
id: connectionId,
OR: [{ organizationAId: organizationId }, { organizationBId: organizationId }],
},
});
if (!link) {
throw new NotFoundException('Link request not found');
if (!connection) {
throw new NotFoundException('Connection request not found');
}
if (link.status !== LinkStatus.PENDING) {
throw new BadRequestException('Only pending link requests can be responded to');
if (connection.status !== LinkStatus.PENDING) {
throw new BadRequestException('Only pending connection requests can be responded to');
}
const requesterOrgId = this.getRequesterOrganizationId(link.sharedDataTypes);
const requesterOrgId = this.getRequesterOrganizationId(connection.sharedDataTypes);
if (requesterOrgId && requesterOrgId === organizationId) {
throw new ForbiddenException('You cannot respond to your own link request');
throw new ForbiddenException('You cannot respond to your own connection request');
}
const nextStatus = dto.action === 'ACCEPT' ? LinkStatus.ACTIVE : LinkStatus.REJECTED;
const updated = await this.prisma.organizationLink.update({
where: { id: link.id },
where: { id: connection.id },
data: { status: nextStatus },
});
return {
success: true,
data: { id: updated.id, status: updated.status },
message: nextStatus === LinkStatus.ACTIVE ? 'Link request accepted' : 'Link request rejected',
message:
nextStatus === LinkStatus.ACTIVE
? 'Connection request accepted'
: 'Connection request declined',
};
}
async deleteLink(userId: string, organizationId: string, linkId: string) {
async deleteConnection(userId: string, organizationId: string, connectionId: 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({
const connection = await this.prisma.organizationLink.findFirst({
where: {
id: linkId,
id: connectionId,
status: LinkStatus.ACTIVE,
OR: [{ organizationAId: organizationId }, { organizationBId: organizationId }],
},
select: { id: true },
});
if (!link) {
throw new NotFoundException('Linked organization not found');
if (!connection) {
throw new NotFoundException('Connected organization not found');
}
await this.prisma.organizationLink.delete({ where: { id: link.id } });
await this.prisma.organizationLink.delete({ where: { id: connection.id } });
return {
success: true,
data: { id: link.id },
message: 'Linked organization removed',
data: { id: connection.id },
message: 'Connection removed',
};
}
/** Re-issue a shareable URL for a pending invitation (rotates token; previous URL stops working). */
async getInvitationLink(userId: string, organizationId: string, invitationId: string) {
const actor = await this.getActorMembership(userId, organizationId);
if (!actor || !this.canEditOrganizations(actor)) {
@@ -314,6 +364,10 @@ export class OrganizationService {
};
}
/**
* Flow 2: invitation link when search finds no subscribed counterpart.
* Always creates/updates PENDING OrganizationLink + OrganizationInvitation together.
*/
async inviteOrganization(userId: string, organizationId: string, dto: InviteOrganizationDto) {
const actor = await this.getActorMembership(userId, organizationId);
if (!actor || !this.canEditOrganizations(actor)) {
@@ -361,6 +415,7 @@ export class OrganizationService {
});
if (!invitedOrg) {
// Placeholder org until acceptInvite; real email is set on acceptance.
invitedOrg = await tx.organization.create({
data: {
name: dto.organizationName.trim(),
@@ -384,6 +439,7 @@ export class OrganizationService {
throw new ConflictException('These organizations are already linked');
}
// Pre-create connection so inviter sees one pending row; acceptInvite() flips to ACTIVE.
await tx.organizationLink.upsert({
where: { organizationAId_organizationBId: { organizationAId: aId, organizationBId: bId } },
update: {
@@ -412,6 +468,7 @@ export class OrganizationService {
});
});
// Plain token is only available here and after getInvitationLink; UI may cache it in localStorage.
return {
success: true,
data: {
@@ -448,6 +505,7 @@ export class OrganizationService {
};
}
/** Public signup completion: activates trial org and the pre-created OrganizationLink. */
async acceptInvite(dto: AcceptOrganizationInviteDto) {
const invitation = await this.findValidInvitation(dto.token);
if (invitation.acceptedAt) {
@@ -528,6 +586,7 @@ export class OrganizationService {
? [invitation.inviterOrganizationId, targetOrganizationId]
: [targetOrganizationId, invitation.inviterOrganizationId];
// Same link row created at invite time; inviter never needs a separate connection request.
await tx.organizationLink.upsert({
where: { organizationAId_organizationBId: { organizationAId: aId, organizationBId: bId } },
update: { status: LinkStatus.ACTIVE },
@@ -554,7 +613,7 @@ export class OrganizationService {
return {
success: true,
data: { organizationId: organization },
message: 'Invitation accepted. Organization trial has started and link is active.',
message: 'Invitation accepted. Organization trial has started and connection is active.',
};
}
@@ -616,11 +675,7 @@ export class OrganizationService {
return `${appUrl}/accept-organization-invite?token=${encodeURIComponent(token)}`;
}
private buildInviteUrlFromTokenHashPlaceholder(): null {
// Raw token cannot be reconstructed from hash, so pending links are preserved client-side after creation.
return null;
}
/** Parses `requested_by:{orgId}` from OrganizationLink.sharedDataTypes while status is PENDING. */
private getRequesterOrganizationId(sharedDataTypes: unknown): string | null {
if (!Array.isArray(sharedDataTypes)) return null;
for (const v of sharedDataTypes) {