Compare commits
5 Commits
09b511a136
...
8278fd9012
| Author | SHA1 | Date | |
|---|---|---|---|
| 8278fd9012 | |||
| e119d02759 | |||
| 375fdc60b4 | |||
| 2025a868ea | |||
| 046257c071 |
@@ -217,6 +217,17 @@ model Feature {
|
||||
@@map("features")
|
||||
}
|
||||
|
||||
/// Bidirectional clinic↔lab relationship. One row per unordered pair (A id < B id).
|
||||
///
|
||||
/// Two product flows share this table:
|
||||
/// 1. **Connection request** — inviter found an existing subscribed org in search; row is PENDING
|
||||
/// until the counterpart accepts. No OrganizationInvitation row.
|
||||
/// 2. **Invitation link** — inviter could not find the org; inviteOrganization() creates a
|
||||
/// placeholder org, an OrganizationInvitation (signup token), and a PENDING link here so the
|
||||
/// inviter does not need a second request after signup. acceptInvite() sets the link to ACTIVE.
|
||||
///
|
||||
/// `sharedDataTypes` stores metadata (not shared clinical data yet). While PENDING, entries like
|
||||
/// `requested_by:{orgId}` record who initiated the request (see OrganizationService).
|
||||
model OrganizationLink {
|
||||
id String @id @default(uuid())
|
||||
|
||||
@@ -235,6 +246,16 @@ model OrganizationLink {
|
||||
@@map("organization_links")
|
||||
}
|
||||
|
||||
/// Signup invite for a counterpart org that is not on DyoLink yet (or has no active subscription).
|
||||
/// Complements OrganizationLink: invite flow always creates both records in one transaction.
|
||||
///
|
||||
/// Only the token *hash* is stored; the plain token is returned once on create/regenerate and may
|
||||
/// be cached in the browser (see frontend useOrganizationInviteLinkCopy). Regenerating rotates
|
||||
/// tokenHash and expiresAt on the same invitation row.
|
||||
///
|
||||
/// `invitedOrganizationId` points at a placeholder Organization (pending-* email) until accept;
|
||||
/// list() joins open invitations to links so the UI can offer "copy invitation link" on the
|
||||
/// pending connection row (pendingInvitationId on the API response).
|
||||
model OrganizationInvitation {
|
||||
id String @id @default(uuid())
|
||||
|
||||
@@ -278,6 +299,8 @@ model Session {
|
||||
@@map("sessions")
|
||||
}
|
||||
|
||||
/// OrganizationLink lifecycle. Invitation rows use overlapping semantics in API mappers
|
||||
/// (e.g. accepted invitation → ACTIVE in listInvitationHistory).
|
||||
enum LinkStatus {
|
||||
PENDING
|
||||
ACTIVE
|
||||
|
||||
@@ -1,9 +1,21 @@
|
||||
import { Body, Controller, Delete, Get, Param, Post, Query, Req, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { AppointmentsService } from './appointments.service';
|
||||
import { CreateAppointmentDto } from './dto/create-appointment.dto';
|
||||
import { ListAppointmentsDto } from './dto/list-appointments.dto';
|
||||
import { UpdateAppointmentDto } from './dto/update-appointment.dto';
|
||||
|
||||
@ApiTags('appointments')
|
||||
@ApiBearerAuth('JWT-auth')
|
||||
@@ -39,6 +51,17 @@ export class AppointmentsController {
|
||||
return this.appointmentsService.create(dto, organizationId, req.user.id);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@ApiOperation({ summary: 'Update appointment (requires TAB_APPOINTMENTS_EDIT or owner)' })
|
||||
update(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateAppointmentDto,
|
||||
@Req() req: { user: { id: string; organizationId?: string } },
|
||||
) {
|
||||
const organizationId = this.appointmentsService.getOrganizationIdFromUser(req.user);
|
||||
return this.appointmentsService.update(id, dto, organizationId, req.user.id);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@ApiOperation({ summary: 'Delete appointment (requires TAB_APPOINTMENTS_EDIT or owner)' })
|
||||
remove(
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
import { PrismaService } from '../../../prisma/prisma.service';
|
||||
import { CreateAppointmentDto } from './dto/create-appointment.dto';
|
||||
import { ListAppointmentsDto } from './dto/list-appointments.dto';
|
||||
import { UpdateAppointmentDto } from './dto/update-appointment.dto';
|
||||
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
|
||||
@@ -109,20 +110,6 @@ export class AppointmentsService {
|
||||
await this.ensurePatientInOrg(dto.patientId, organizationId);
|
||||
await this.ensureProviderIsTreatmentEditor(dto.providerUserId, organizationId);
|
||||
|
||||
const overlap = await this.prisma.appointment.findFirst({
|
||||
where: {
|
||||
organizationId,
|
||||
providerUserId: dto.providerUserId,
|
||||
startAt: { lt: endAt },
|
||||
endAt: { gt: startAt },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (overlap) {
|
||||
throw new BadRequestException('This time slot overlaps an existing appointment for that provider');
|
||||
}
|
||||
|
||||
const appointment = await this.prisma.appointment.create({
|
||||
data: {
|
||||
organizationId,
|
||||
@@ -142,6 +129,63 @@ export class AppointmentsService {
|
||||
return { success: true, data: appointment };
|
||||
}
|
||||
|
||||
async update(
|
||||
id: string,
|
||||
dto: UpdateAppointmentDto,
|
||||
organizationId: string,
|
||||
actorUserId: string,
|
||||
) {
|
||||
await this.assertCanEditAppointments(actorUserId, organizationId);
|
||||
|
||||
const existing = await this.prisma.appointment.findFirst({
|
||||
where: { id, organizationId },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new NotFoundException('Appointment not found');
|
||||
}
|
||||
|
||||
const startAt = dto.startAt ? new Date(dto.startAt) : existing.startAt;
|
||||
const endAt = dto.endAt ? new Date(dto.endAt) : existing.endAt;
|
||||
|
||||
if (Number.isNaN(startAt.getTime()) || Number.isNaN(endAt.getTime())) {
|
||||
throw new BadRequestException('Invalid start or end time');
|
||||
}
|
||||
|
||||
if (endAt <= startAt) {
|
||||
throw new BadRequestException('End time must be after start time');
|
||||
}
|
||||
|
||||
if (endAt.getTime() - startAt.getTime() > MS_PER_DAY) {
|
||||
throw new BadRequestException('Appointment cannot span more than 24 hours');
|
||||
}
|
||||
|
||||
const patientId = dto.patientId ?? existing.patientId;
|
||||
const providerUserId = dto.providerUserId ?? existing.providerUserId;
|
||||
const purpose = dto.purpose ?? existing.purpose;
|
||||
|
||||
await this.ensurePatientInOrg(patientId, organizationId);
|
||||
await this.ensureProviderIsTreatmentEditor(providerUserId, organizationId);
|
||||
|
||||
const appointment = await this.prisma.appointment.update({
|
||||
where: { id },
|
||||
data: {
|
||||
patientId,
|
||||
providerUserId,
|
||||
startAt,
|
||||
endAt,
|
||||
purpose,
|
||||
},
|
||||
include: {
|
||||
patient: {
|
||||
select: { id: true, firstName: true, lastName: true, phone: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true, data: appointment };
|
||||
}
|
||||
|
||||
async remove(id: string, organizationId: string, actorUserId: string) {
|
||||
await this.assertCanEditAppointments(actorUserId, organizationId);
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateAppointmentDto } from './create-appointment.dto';
|
||||
|
||||
export class UpdateAppointmentDto extends PartialType(CreateAppointmentDto) {}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import { IsUUID } from 'class-validator';
|
||||
|
||||
export class CreateLinkRequestDto {
|
||||
@IsUUID()
|
||||
targetOrganizationId: string;
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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';
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import { IsIn } from 'class-validator';
|
||||
|
||||
export class RespondLinkRequestDto {
|
||||
@IsIn(['ACCEPT', 'REJECT'])
|
||||
action: 'ACCEPT' | 'REJECT';
|
||||
}
|
||||
@@ -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')
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -14,7 +14,8 @@ import { AppointmentScheduleGrid } from '@/components/ui/appointments/Appointmen
|
||||
import { AppointmentsPatientSearch } from '@/components/ui/appointments/AppointmentsPatientSearch';
|
||||
import { AppointmentScheduleLegend } from '@/components/ui/appointments/AppointmentScheduleLegend';
|
||||
import { ScheduleDayPicker } from '@/components/ui/common/ScheduleDayPicker';
|
||||
import { Toast } from '@/components/ui/common/Toast';
|
||||
import { ToastStack } from '@/components/ui/common/Toast';
|
||||
import { useToast } from '@/lib/hooks/useToast';
|
||||
import type { AppointmentPurpose } from '@/types/appointment';
|
||||
import { formatApiErrorMessage } from '@/lib/formatApiError';
|
||||
import { compareLocalDayStart, getLocalDayIsoRange, startOfLocalDay } from '@/lib/appointmentTime';
|
||||
@@ -33,7 +34,7 @@ export default function AppointmentsPage() {
|
||||
const [providers, setProviders] = useState<AppointmentColumnProvider[]>([]);
|
||||
const [appointments, setAppointments] = useState<AppointmentRecord[]>([]);
|
||||
const [loadingSchedule, setLoadingSchedule] = useState(false);
|
||||
const [scheduleError, setScheduleError] = useState('');
|
||||
const toast = useToast();
|
||||
|
||||
const [search, setSearch] = useState('');
|
||||
const [patients, setPatients] = useState<Patient[]>([]);
|
||||
@@ -50,10 +51,8 @@ export default function AppointmentsPage() {
|
||||
const [bookingProviderName, setBookingProviderName] = useState('');
|
||||
const [editingAppointmentId, setEditingAppointmentId] = useState<string | null>(null);
|
||||
const [savingAppointment, setSavingAppointment] = useState(false);
|
||||
const [deletingAppointment, setDeletingAppointment] = useState(false);
|
||||
|
||||
const [toastError, setToastError] = useState('');
|
||||
const [toastSuccess, setToastSuccess] = useState('');
|
||||
const [toastInfo, setToastInfo] = useState('');
|
||||
|
||||
const canManageAppointments = canEditAppointments(currentOrganization);
|
||||
const canEditPatients = hasPermission(currentOrganization, 'TAB_PATIENTS_EDIT');
|
||||
@@ -84,7 +83,7 @@ export default function AppointmentsPage() {
|
||||
}
|
||||
const gen = ++scheduleLoadGen.current;
|
||||
setLoadingSchedule(true);
|
||||
setScheduleError('');
|
||||
toast.setError('');
|
||||
try {
|
||||
const range = getLocalDayIsoRange(scheduleDate);
|
||||
const [pRes, aRes] = await Promise.all([
|
||||
@@ -100,7 +99,7 @@ export default function AppointmentsPage() {
|
||||
if (gen !== scheduleLoadGen.current) {
|
||||
return;
|
||||
}
|
||||
setScheduleError(formatApiErrorMessage(err, 'Failed to load schedule.'));
|
||||
toast.showError(formatApiErrorMessage(err, 'Failed to load schedule.'));
|
||||
} finally {
|
||||
if (gen === scheduleLoadGen.current) {
|
||||
setLoadingSchedule(false);
|
||||
@@ -143,21 +142,20 @@ export default function AppointmentsPage() {
|
||||
|
||||
async function handleCreatePatient() {
|
||||
setSavingPatient(true);
|
||||
setToastError('');
|
||||
setToastSuccess('');
|
||||
toast.setError('');
|
||||
try {
|
||||
const response = await patientsApi.create(patientForm);
|
||||
setIsCreateOpen(false);
|
||||
setPatientForm(EMPTY_PATIENT_FORM);
|
||||
await loadPatientsSearch(search);
|
||||
setSelectedPatient(response.data);
|
||||
setToastSuccess(`Patient ${response.data.firstName} ${response.data.lastName} was saved.`);
|
||||
toast.showSuccess(`Patient ${response.data.firstName} ${response.data.lastName} was saved.`);
|
||||
} catch (err: unknown) {
|
||||
const message =
|
||||
err && typeof err === 'object' && 'message' in err
|
||||
? String((err as { message: unknown }).message)
|
||||
: 'Failed to save patient.';
|
||||
setToastError(message);
|
||||
toast.showError(message);
|
||||
} finally {
|
||||
setSavingPatient(false);
|
||||
}
|
||||
@@ -165,15 +163,11 @@ export default function AppointmentsPage() {
|
||||
|
||||
function handleSlotClick(hour: number, providerUserId: string, providerName: string) {
|
||||
if (isViewingPastDay) {
|
||||
setToastSuccess('');
|
||||
setToastError('');
|
||||
setToastInfo('Past appointments are view-only.');
|
||||
toast.showInfo('Past appointments are view-only.');
|
||||
return;
|
||||
}
|
||||
if (!selectedPatient) {
|
||||
setToastSuccess('');
|
||||
setToastError('');
|
||||
setToastInfo('Select a patient before booking.');
|
||||
toast.showInfo('Select a patient before booking.');
|
||||
return;
|
||||
}
|
||||
setBookingHour(hour);
|
||||
@@ -185,9 +179,7 @@ export default function AppointmentsPage() {
|
||||
|
||||
function handleAppointmentClick(appointment: AppointmentRecord) {
|
||||
if (isViewingPastDay) {
|
||||
setToastSuccess('');
|
||||
setToastError('');
|
||||
setToastInfo('Past appointments are view-only.');
|
||||
toast.showInfo('Past appointments are view-only.');
|
||||
return;
|
||||
}
|
||||
const provider = providers.find((p) => p.userId === appointment.providerUserId);
|
||||
@@ -206,9 +198,7 @@ export default function AppointmentsPage() {
|
||||
purpose: AppointmentPurpose;
|
||||
}) {
|
||||
setSavingAppointment(true);
|
||||
setToastError('');
|
||||
setToastSuccess('');
|
||||
setToastInfo('');
|
||||
toast.setError('');
|
||||
try {
|
||||
if (activeEditingAppointment) {
|
||||
await appointmentsApi.update(activeEditingAppointment.id, payload);
|
||||
@@ -217,7 +207,7 @@ export default function AppointmentsPage() {
|
||||
}
|
||||
setBookingOpen(false);
|
||||
setEditingAppointmentId(null);
|
||||
setToastSuccess(activeEditingAppointment ? 'Appointment updated.' : 'Appointment saved.');
|
||||
toast.showSuccess(activeEditingAppointment ? 'Appointment updated.' : 'Appointment saved.');
|
||||
await loadSchedule();
|
||||
} catch (err: unknown) {
|
||||
const message =
|
||||
@@ -226,67 +216,51 @@ export default function AppointmentsPage() {
|
||||
: activeEditingAppointment
|
||||
? 'Could not update appointment.'
|
||||
: 'Could not save appointment.';
|
||||
setToastError(message);
|
||||
toast.showError(message);
|
||||
} finally {
|
||||
setSavingAppointment(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteAppointment(id: string) {
|
||||
async function handleDeleteEditingAppointment() {
|
||||
if (!activeEditingAppointment) {
|
||||
return;
|
||||
}
|
||||
if (!window.confirm('Remove this appointment?')) {
|
||||
return;
|
||||
}
|
||||
setToastError('');
|
||||
setToastSuccess('');
|
||||
setToastInfo('');
|
||||
setDeletingAppointment(true);
|
||||
toast.setError('');
|
||||
try {
|
||||
await appointmentsApi.remove(id);
|
||||
setToastSuccess('Appointment removed.');
|
||||
await appointmentsApi.remove(activeEditingAppointment.id);
|
||||
setBookingOpen(false);
|
||||
setEditingAppointmentId(null);
|
||||
toast.showSuccess('Appointment removed.');
|
||||
await loadSchedule();
|
||||
} catch (err: unknown) {
|
||||
const message =
|
||||
err && typeof err === 'object' && 'message' in err
|
||||
? String((err as { message: unknown }).message)
|
||||
: 'Could not delete appointment.';
|
||||
setToastError(message);
|
||||
toast.showError(message);
|
||||
} finally {
|
||||
setDeletingAppointment(false);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!toastSuccess) {
|
||||
return;
|
||||
}
|
||||
const id = setTimeout(() => setToastSuccess(''), 3200);
|
||||
return () => clearTimeout(id);
|
||||
}, [toastSuccess]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!toastError) {
|
||||
return;
|
||||
}
|
||||
const id = setTimeout(() => setToastError(''), 4000);
|
||||
return () => clearTimeout(id);
|
||||
}, [toastError]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!toastInfo) {
|
||||
return;
|
||||
}
|
||||
const id = setTimeout(() => setToastInfo(''), 4000);
|
||||
return () => clearTimeout(id);
|
||||
}, [toastInfo]);
|
||||
|
||||
return (
|
||||
<div className="relative space-y-6 pb-24">
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-2xl font-semibold text-text-primary">Appointments</h1>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Search a patient, pick a date, then click a time slot under a provider to book.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ToastStack {...toast.messages} />
|
||||
|
||||
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
|
||||
<div className="xl:col-span-1 space-y-4">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-2xl font-semibold text-text-primary">Appointments</h1>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Search a patient, pick a date, then click a time slot under a provider to book.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<AppointmentsPatientSearch
|
||||
search={search}
|
||||
onSearchChange={setSearch}
|
||||
@@ -324,8 +298,6 @@ export default function AppointmentsPage() {
|
||||
providers={providers}
|
||||
appointments={appointments}
|
||||
canBook={canManageAppointments && !isViewingPastDay}
|
||||
canDelete={canManageAppointments}
|
||||
onDeleteAppointment={(id) => void handleDeleteAppointment(id)}
|
||||
onSlotClick={(hour, uid, name) => handleSlotClick(hour, uid, name)}
|
||||
onAppointmentClick={(apt) => handleAppointmentClick(apt)}
|
||||
/>
|
||||
@@ -346,6 +318,9 @@ export default function AppointmentsPage() {
|
||||
}}
|
||||
onSubmit={handleSaveAppointment}
|
||||
loading={savingAppointment}
|
||||
canDelete={canManageAppointments && !isViewingPastDay && !!activeEditingAppointment}
|
||||
onDelete={() => void handleDeleteEditingAppointment()}
|
||||
deleting={deletingAppointment}
|
||||
/>
|
||||
|
||||
{isCreateOpen && (
|
||||
@@ -361,16 +336,6 @@ export default function AppointmentsPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(scheduleError || toastError || toastSuccess || toastInfo) && (
|
||||
<div className="fixed bottom-4 left-0 right-0 z-[70] px-4 pointer-events-none">
|
||||
<div className="pointer-events-auto w-full space-y-2">
|
||||
{scheduleError && <Toast variant="danger">{scheduleError}</Toast>}
|
||||
{toastError && <Toast variant="danger">{toastError}</Toast>}
|
||||
{toastInfo && <Toast variant="warning">{toastInfo}</Toast>}
|
||||
{toastSuccess && <Toast variant="success">{toastSuccess}</Toast>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Check, Link2, Trash2, X } from 'lucide-react';
|
||||
import { useToast } from '@/lib/hooks/useToast';
|
||||
import { Check, Trash2, UserPlus, X } from 'lucide-react';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { useOrganizationInviteLinkCopy } from '@/lib/hooks/useOrganizationInviteLinkCopy';
|
||||
import {
|
||||
@@ -10,12 +11,15 @@ import {
|
||||
type CounterpartSearchResultDto,
|
||||
type OrganizationInvitationHistoryItemDto,
|
||||
} from '@/lib/api/organization';
|
||||
import { invitationTargetFromConnectionRow } from '@/components/invitations/organizationInviteLinks';
|
||||
import { CopyInvitationLinkButton } from '@/components/ui/organizations/CopyInvitationLinkButton';
|
||||
import { InvitationHistoryDialog } from '@/components/ui/organizations/InvitationHistoryDialog';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Badge, organizationLinkStatusVariant } from '@/components/ui/common/Badge';
|
||||
import { Badge, organizationConnectionStatusVariant } from '@/components/ui/common/Badge';
|
||||
import { Input } from '@/components/ui/common/Input';
|
||||
import { SearchBar } from '@/components/ui/common/SearchBar';
|
||||
import { Table } from '@/components/ui/common/Table';
|
||||
import { ToastStack } from '@/components/ui/common/Toast';
|
||||
import type { ApiError } from '@/types/api';
|
||||
|
||||
function formatOrganizationStatusLabel(status: string): string {
|
||||
@@ -24,11 +28,22 @@ function formatOrganizationStatusLabel(status: string): string {
|
||||
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 formatConnectionStatusLabel(
|
||||
row: CounterpartItemDto,
|
||||
currentOrganizationId: string,
|
||||
): string {
|
||||
if (row.status === 'PENDING') {
|
||||
if (
|
||||
row.pendingInvitationId &&
|
||||
row.requestedByOrganizationId === currentOrganizationId
|
||||
) {
|
||||
return 'Invitation pending';
|
||||
}
|
||||
return 'Connection request pending';
|
||||
}
|
||||
if (row.status === 'ACTIVE') return 'Connected';
|
||||
if (row.status === 'REJECTED') return 'Connection request declined';
|
||||
return formatOrganizationStatusLabel(row.status);
|
||||
}
|
||||
|
||||
function formatApiMessage(err: unknown): string {
|
||||
@@ -41,7 +56,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 '\u2014';
|
||||
return d.toLocaleDateString();
|
||||
}
|
||||
|
||||
@@ -50,15 +65,14 @@ type TableMode = 'existing' | 'search';
|
||||
export default function OrganizationsPage() {
|
||||
const { currentOrganization } = useAuth();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState('');
|
||||
const toast = useToast();
|
||||
|
||||
const [query, setQuery] = useState('');
|
||||
const [mode, setMode] = useState<TableMode>('existing');
|
||||
const [searching, setSearching] = useState(false);
|
||||
const [searchResults, setSearchResults] = useState<CounterpartSearchResultDto[]>([]);
|
||||
const [requestLinkRowId, setRequestLinkRowId] = useState<string | null>(null);
|
||||
const [deleteLinkRowId, setDeleteLinkRowId] = useState<string | null>(null);
|
||||
const [pendingConnectionRowId, setPendingConnectionRowId] = useState<string | null>(null);
|
||||
const [deleteConnectionRowId, setDeleteConnectionRowId] = useState<string | null>(null);
|
||||
|
||||
const [items, setItems] = useState<CounterpartItemDto[]>([]);
|
||||
const [manualOrganizationName, setManualOrganizationName] = useState('');
|
||||
@@ -68,8 +82,6 @@ export default function OrganizationsPage() {
|
||||
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,
|
||||
@@ -86,12 +98,12 @@ export default function OrganizationsPage() {
|
||||
|
||||
async function loadList() {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
toast.setError('');
|
||||
try {
|
||||
const res = await organizationApi.list();
|
||||
setItems(res.data.items);
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
toast.showError(formatApiMessage(e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -101,12 +113,6 @@ export default function OrganizationsPage() {
|
||||
void loadList();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!success) return;
|
||||
const t = setTimeout(() => setSuccess(''), 4000);
|
||||
return () => clearTimeout(t);
|
||||
}, [success]);
|
||||
|
||||
async function runSearch() {
|
||||
const q = query.trim();
|
||||
if (!q) {
|
||||
@@ -117,47 +123,47 @@ export default function OrganizationsPage() {
|
||||
}
|
||||
|
||||
setSearching(true);
|
||||
setError('');
|
||||
toast.setError('');
|
||||
setMode('search');
|
||||
setShowInviteForm(false);
|
||||
try {
|
||||
const res = await organizationApi.search(q);
|
||||
setSearchResults(res.data);
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
toast.showError(formatApiMessage(e));
|
||||
setSearchResults([]);
|
||||
} finally {
|
||||
setSearching(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function submitRequestLink(targetOrganizationId: string) {
|
||||
setRequestLinkRowId(targetOrganizationId);
|
||||
setError('');
|
||||
async function submitConnectionRequest(targetOrganizationId: string) {
|
||||
setPendingConnectionRowId(targetOrganizationId);
|
||||
toast.setError('');
|
||||
try {
|
||||
await organizationApi.createLink(targetOrganizationId);
|
||||
setSuccess(`${counterpartLabel} link request sent`);
|
||||
await organizationApi.createConnectionRequest(targetOrganizationId);
|
||||
toast.showSuccess(`${counterpartLabel} connection request sent.`);
|
||||
setSearchResults([]);
|
||||
setQuery('');
|
||||
setMode('existing');
|
||||
await loadList();
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
toast.showError(formatApiMessage(e));
|
||||
} finally {
|
||||
setRequestLinkRowId(null);
|
||||
setPendingConnectionRowId(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function sendInvite() {
|
||||
setInviteLoading(true);
|
||||
setError('');
|
||||
toast.setError('');
|
||||
try {
|
||||
const res = await organizationApi.invite({
|
||||
organizationName: manualOrganizationName.trim(),
|
||||
ownerEmail: manualOwnerEmail.trim(),
|
||||
});
|
||||
storeInviteLink(res.data.invitationId, manualOwnerEmail, res.data.invitationUrl);
|
||||
setSuccess(`Invitation link created for ${manualOwnerEmail.trim()}`);
|
||||
toast.showSuccess(`Invitation link created for ${manualOwnerEmail.trim()}`);
|
||||
setManualOrganizationName('');
|
||||
setManualOwnerEmail('');
|
||||
setShowInviteForm(false);
|
||||
@@ -166,7 +172,7 @@ export default function OrganizationsPage() {
|
||||
setSearchResults([]);
|
||||
await loadList();
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
toast.showError(formatApiMessage(e));
|
||||
} finally {
|
||||
setInviteLoading(false);
|
||||
}
|
||||
@@ -182,59 +188,83 @@ export default function OrganizationsPage() {
|
||||
async function openInvitationHistory() {
|
||||
setHistoryOpen(true);
|
||||
setHistoryLoading(true);
|
||||
setHistoryCopyError('');
|
||||
setHistoryCopySuccess('');
|
||||
setError('');
|
||||
toast.clear();
|
||||
try {
|
||||
await loadInvitationHistory();
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
toast.showError(formatApiMessage(e));
|
||||
} finally {
|
||||
setHistoryLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleHistoryCopy(invitation: OrganizationInvitationHistoryItemDto) {
|
||||
setHistoryCopyError('');
|
||||
setHistoryCopySuccess('');
|
||||
toast.setError('');
|
||||
try {
|
||||
await copyInvitationLink(invitation, {
|
||||
onRegenerated: async () => {
|
||||
await loadInvitationHistory();
|
||||
},
|
||||
});
|
||||
setHistoryCopySuccess('Invitation link copied to clipboard.');
|
||||
setTimeout(() => setHistoryCopySuccess(''), 3000);
|
||||
toast.showSuccess('Invitation link copied to clipboard.');
|
||||
} catch (e) {
|
||||
setHistoryCopyError(formatApiMessage(e));
|
||||
toast.showError(formatApiMessage(e));
|
||||
}
|
||||
}
|
||||
|
||||
async function respondToPendingLink(linkId: string, action: 'ACCEPT' | 'REJECT') {
|
||||
setRequestLinkRowId(linkId);
|
||||
setError('');
|
||||
async function handleCopyInvitationFromRow(row: CounterpartItemDto) {
|
||||
const target = invitationTargetFromConnectionRow(row, currentOrganization!.id);
|
||||
if (!target) return;
|
||||
toast.setError('');
|
||||
try {
|
||||
await organizationApi.respondLink(linkId, action);
|
||||
setSuccess(action === 'ACCEPT' ? 'Link request accepted' : 'Link request rejected');
|
||||
await loadList();
|
||||
await copyInvitationLink(
|
||||
{
|
||||
id: target.id,
|
||||
organizationName: row.organizationName,
|
||||
ownerEmail: target.ownerEmail,
|
||||
status: target.status,
|
||||
createdAt: row.createdAt,
|
||||
acceptedAt: target.acceptedAt,
|
||||
},
|
||||
{
|
||||
onRegenerated: async () => {
|
||||
await loadList();
|
||||
},
|
||||
},
|
||||
);
|
||||
toast.showSuccess('Invitation link copied to clipboard.');
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
} finally {
|
||||
setRequestLinkRowId(null);
|
||||
toast.showError(formatApiMessage(e));
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteLinkedOrganization(linkId: string) {
|
||||
setDeleteLinkRowId(linkId);
|
||||
setError('');
|
||||
async function respondToPendingConnection(connectionId: string, action: 'ACCEPT' | 'REJECT') {
|
||||
setPendingConnectionRowId(connectionId);
|
||||
toast.setError('');
|
||||
try {
|
||||
await organizationApi.deleteLink(linkId);
|
||||
setSuccess('Linked organization removed');
|
||||
await organizationApi.respondToConnectionRequest(connectionId, action);
|
||||
toast.showSuccess(
|
||||
action === 'ACCEPT' ? 'Connection request accepted.' : 'Connection request declined.',
|
||||
);
|
||||
await loadList();
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
toast.showError(formatApiMessage(e));
|
||||
} finally {
|
||||
setDeleteLinkRowId(null);
|
||||
setPendingConnectionRowId(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteConnection(connectionId: string) {
|
||||
setDeleteConnectionRowId(connectionId);
|
||||
toast.setError('');
|
||||
try {
|
||||
await organizationApi.deleteConnection(connectionId);
|
||||
toast.showSuccess('Connection removed.');
|
||||
await loadList();
|
||||
} catch (e) {
|
||||
toast.showError(formatApiMessage(e));
|
||||
} finally {
|
||||
setDeleteConnectionRowId(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,7 +285,8 @@ export default function OrganizationsPage() {
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-text-primary">{tabLabel}</h1>
|
||||
<p className="text-sm text-text-secondary mt-1">
|
||||
Search organizations and send link requests or invitation links in one place.
|
||||
Search organizations, send connection requests to existing accounts, or invitation
|
||||
links when they are not on DyoLink yet.
|
||||
</p>
|
||||
</div>
|
||||
<Button type="button" size="sm" onClick={() => void openInvitationHistory()}>
|
||||
@@ -263,16 +294,7 @@ export default function OrganizationsPage() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<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">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
{success && (
|
||||
<div className="rounded-[var(--radius-md)] border border-primary/30 bg-primary-soft/40 px-4 py-3 text-sm text-text-primary">
|
||||
{success}
|
||||
</div>
|
||||
)}
|
||||
{!historyOpen && <ToastStack {...toast.messages} />}
|
||||
|
||||
<SearchBar
|
||||
value={query}
|
||||
@@ -334,7 +356,7 @@ export default function OrganizationsPage() {
|
||||
existingRows.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={5} className="px-6 py-8 text-sm text-text-secondary">
|
||||
No organizations linked or pending yet. Use search to find and connect.
|
||||
No connections yet. Search to send a connection request or an invitation link.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
@@ -343,6 +365,10 @@ export default function OrganizationsPage() {
|
||||
row.status === 'PENDING' &&
|
||||
row.requestedByOrganizationId !== null &&
|
||||
row.requestedByOrganizationId !== currentOrganization.id;
|
||||
const invitationTarget = invitationTargetFromConnectionRow(
|
||||
row,
|
||||
currentOrganization.id,
|
||||
);
|
||||
|
||||
return (
|
||||
<tr key={row.id} className="hover:bg-background-secondary/45">
|
||||
@@ -354,31 +380,39 @@ export default function OrganizationsPage() {
|
||||
{formatTableDate(row.createdAt)}
|
||||
</td>
|
||||
<td className="px-6 py-1.5 text-center align-middle">
|
||||
<Badge variant={organizationLinkStatusVariant(row.status)} fixedWidth={false}>
|
||||
{formatLinkStatusLabel(row.status)}
|
||||
<Badge variant={organizationConnectionStatusVariant(row.status)} fixedWidth={false}>
|
||||
{formatConnectionStatusLabel(row, currentOrganization.id)}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-6 py-1.5 text-right">
|
||||
<div className="inline-flex items-center gap-2">
|
||||
{invitationTarget && (
|
||||
<CopyInvitationLinkButton
|
||||
invitation={invitationTarget}
|
||||
copied={copiedId === invitationTarget.id}
|
||||
copying={copyingInvitationId === invitationTarget.id}
|
||||
onCopy={() => void handleCopyInvitationFromRow(row)}
|
||||
/>
|
||||
)}
|
||||
{canRespond && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary disabled:text-text-muted disabled:opacity-50"
|
||||
disabled={requestLinkRowId !== null && requestLinkRowId !== row.id}
|
||||
onClick={() => void respondToPendingLink(row.id, 'ACCEPT')}
|
||||
aria-label="Accept link request"
|
||||
title="Accept link request"
|
||||
disabled={pendingConnectionRowId !== null && pendingConnectionRowId !== row.id}
|
||||
onClick={() => void respondToPendingConnection(row.id, 'ACCEPT')}
|
||||
aria-label="Accept connection request"
|
||||
title="Accept connection request"
|
||||
>
|
||||
<Check className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="p-2 rounded-md text-text-secondary hover:bg-red-500/15 hover:text-red-600 disabled:text-text-muted disabled:opacity-50"
|
||||
disabled={requestLinkRowId !== null && requestLinkRowId !== row.id}
|
||||
onClick={() => void respondToPendingLink(row.id, 'REJECT')}
|
||||
aria-label="Reject link request"
|
||||
title="Reject link request"
|
||||
disabled={pendingConnectionRowId !== null && pendingConnectionRowId !== row.id}
|
||||
onClick={() => void respondToPendingConnection(row.id, 'REJECT')}
|
||||
aria-label="Decline connection request"
|
||||
title="Decline connection request"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
@@ -388,10 +422,10 @@ export default function OrganizationsPage() {
|
||||
<button
|
||||
type="button"
|
||||
className="p-2 rounded-md text-text-secondary hover:bg-red-500/15 hover:text-red-600 disabled:text-text-muted disabled:opacity-50"
|
||||
disabled={deleteLinkRowId !== null && deleteLinkRowId !== row.id}
|
||||
onClick={() => void deleteLinkedOrganization(row.id)}
|
||||
aria-label="Delete link"
|
||||
title="Delete link"
|
||||
disabled={deleteConnectionRowId !== null && deleteConnectionRowId !== row.id}
|
||||
onClick={() => void deleteConnection(row.id)}
|
||||
aria-label="Remove connection"
|
||||
title="Remove connection"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
@@ -415,12 +449,14 @@ export default function OrganizationsPage() {
|
||||
<button
|
||||
type="button"
|
||||
className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary disabled:text-text-muted disabled:opacity-50"
|
||||
disabled={requestLinkRowId !== null && requestLinkRowId !== r.id}
|
||||
onClick={() => void submitRequestLink(r.id)}
|
||||
aria-label="Send link request"
|
||||
title="Send link request"
|
||||
disabled={
|
||||
pendingConnectionRowId !== null && pendingConnectionRowId !== r.id
|
||||
}
|
||||
onClick={() => void submitConnectionRequest(r.id)}
|
||||
aria-label="Send connection request"
|
||||
title="Send connection request"
|
||||
>
|
||||
<Link2 className="w-4 h-4" />
|
||||
<UserPlus className="w-4 h-4" />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -473,18 +509,13 @@ export default function OrganizationsPage() {
|
||||
|
||||
<InvitationHistoryDialog
|
||||
open={historyOpen}
|
||||
onClose={() => {
|
||||
setHistoryOpen(false);
|
||||
setHistoryCopyError('');
|
||||
setHistoryCopySuccess('');
|
||||
}}
|
||||
onClose={() => setHistoryOpen(false)}
|
||||
loading={historyLoading}
|
||||
items={historyItems}
|
||||
copiedId={copiedId}
|
||||
copyingInvitationId={copyingInvitationId}
|
||||
onCopy={(invitation) => void handleHistoryCopy(invitation)}
|
||||
copyError={historyCopyError}
|
||||
copySuccess={historyCopySuccess}
|
||||
toastMessages={toast.messages}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -12,7 +12,7 @@ export default function TodayPage() {
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold mb-6">
|
||||
Welcome back Babak !!
|
||||
Welcome back!!
|
||||
</h1>
|
||||
|
||||
{showNoSubscriptionNotice && (
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import type { OrganizationInvitationHistoryItemDto } from '@/lib/api/organization';
|
||||
import type {
|
||||
CounterpartItemDto,
|
||||
OrganizationInvitationHistoryItemDto,
|
||||
} from '@/lib/api/organization';
|
||||
|
||||
export type InvitationLinkTarget = Pick<
|
||||
OrganizationInvitationHistoryItemDto,
|
||||
'id' | 'ownerEmail' | 'status' | 'acceptedAt'
|
||||
>;
|
||||
|
||||
/** Cached after POST /organizations/invite because only tokenHash is persisted server-side. */
|
||||
export type StoredOrganizationInviteLink = {
|
||||
invitationId: string;
|
||||
ownerEmail: string;
|
||||
@@ -39,3 +48,21 @@ export function canShareOrganizationInviteLink(
|
||||
if (invitation.acceptedAt) return false;
|
||||
return invitation.status === 'PENDING' || invitation.status === 'EXPIRED';
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a connections-list row to copy/regenerate UI when it was created by the invitation flow.
|
||||
* Plain invite URLs are not stored in the DB; use localStorage (storeInviteLink) or POST …/link.
|
||||
*/
|
||||
export function invitationTargetFromConnectionRow(
|
||||
row: CounterpartItemDto,
|
||||
currentOrganizationId: string,
|
||||
): InvitationLinkTarget | null {
|
||||
if (!row.pendingInvitationId) return null;
|
||||
if (row.requestedByOrganizationId !== currentOrganizationId) return null;
|
||||
return {
|
||||
id: row.pendingInvitationId,
|
||||
ownerEmail: row.ownerEmail,
|
||||
status: row.invitationStatus ?? 'PENDING',
|
||||
acceptedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -31,6 +31,9 @@ interface AppointmentBookingModalProps {
|
||||
}) => Promise<void>;
|
||||
editingAppointment?: AppointmentRecord | null;
|
||||
loading?: boolean;
|
||||
canDelete?: boolean;
|
||||
onDelete?: () => void | Promise<void>;
|
||||
deleting?: boolean;
|
||||
}
|
||||
|
||||
export function AppointmentBookingModal({
|
||||
@@ -44,6 +47,9 @@ export function AppointmentBookingModal({
|
||||
onSubmit,
|
||||
editingAppointment = null,
|
||||
loading = false,
|
||||
canDelete = false,
|
||||
onDelete,
|
||||
deleting = false,
|
||||
}: AppointmentBookingModalProps) {
|
||||
const [startTime, setStartTime] = useState('09:00');
|
||||
const [endTime, setEndTime] = useState('10:00');
|
||||
@@ -227,13 +233,34 @@ export function AppointmentBookingModal({
|
||||
|
||||
{error && <p className="text-sm text-red-400">{error}</p>}
|
||||
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button type="button" variant="ghost" onClick={onClose} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="button" variant="primary" onClick={() => void handleSubmit()} isLoading={loading}>
|
||||
Save
|
||||
</Button>
|
||||
<div className="flex flex-wrap items-center gap-2 justify-between">
|
||||
{editingAppointment && canDelete && onDelete ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="danger"
|
||||
onClick={() => void onDelete()}
|
||||
disabled={loading || deleting}
|
||||
isLoading={deleting}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<div className="flex gap-2 ml-auto">
|
||||
<Button type="button" variant="ghost" onClick={onClose} disabled={loading || deleting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
onClick={() => void handleSubmit()}
|
||||
isLoading={loading}
|
||||
disabled={deleting}
|
||||
>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { DialogCloseButton } from '@/components/ui/common/DialogCloseButton';
|
||||
import {
|
||||
APPOINTMENT_PURPOSE_LABEL,
|
||||
purposeStyle,
|
||||
} from '@/components/ui/appointments/appointmentPurposeStyles';
|
||||
import type { AppointmentRecord } from '@/types/appointment';
|
||||
|
||||
type AppointmentOverlapPopoverProps = {
|
||||
appointments: AppointmentRecord[];
|
||||
anchorRect: DOMRect;
|
||||
onSelect: (appointment: AppointmentRecord) => void;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
function formatTimeRange(apt: AppointmentRecord): string {
|
||||
const start = new Date(apt.startAt);
|
||||
const end = new Date(apt.endAt);
|
||||
const opts: Intl.DateTimeFormatOptions = { hour: 'numeric', minute: '2-digit' };
|
||||
return `${start.toLocaleTimeString(undefined, opts)} – ${end.toLocaleTimeString(undefined, opts)}`;
|
||||
}
|
||||
|
||||
export function AppointmentOverlapPopover({
|
||||
appointments,
|
||||
anchorRect,
|
||||
onSelect,
|
||||
onClose,
|
||||
}: AppointmentOverlapPopoverProps) {
|
||||
const panelRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
function onPointerDown(event: MouseEvent) {
|
||||
if (!panelRef.current?.contains(event.target as Node)) {
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
function onKeyDown(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') {
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', onPointerDown);
|
||||
document.addEventListener('keydown', onKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', onPointerDown);
|
||||
document.removeEventListener('keydown', onKeyDown);
|
||||
};
|
||||
}, [onClose]);
|
||||
|
||||
const sorted = [...appointments].sort(
|
||||
(a, b) => new Date(a.startAt).getTime() - new Date(b.startAt).getTime(),
|
||||
);
|
||||
|
||||
const viewportPadding = 12;
|
||||
const panelWidth = Math.min(320, window.innerWidth - viewportPadding * 2);
|
||||
let top = anchorRect.bottom + 8;
|
||||
let left = anchorRect.left + anchorRect.width / 2 - panelWidth / 2;
|
||||
left = Math.max(viewportPadding, Math.min(left, window.innerWidth - panelWidth - viewportPadding));
|
||||
const estimatedHeight = 56 + sorted.length * 52;
|
||||
if (top + estimatedHeight > window.innerHeight - viewportPadding) {
|
||||
top = Math.max(viewportPadding, anchorRect.top - estimatedHeight - 8);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[65] pointer-events-none" aria-hidden>
|
||||
<div
|
||||
ref={panelRef}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="overlap-popover-title"
|
||||
className="pointer-events-auto fixed rounded-[var(--radius-md)] border border-border bg-background-secondary p-3 shadow-xl"
|
||||
style={{ top, left, width: panelWidth }}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2 mb-2">
|
||||
<h3 id="overlap-popover-title" className="text-sm font-semibold text-text-primary pr-2">
|
||||
Overlapping appointments ({sorted.length})
|
||||
</h3>
|
||||
<DialogCloseButton onClick={onClose} />
|
||||
</div>
|
||||
<ul className="space-y-1.5 max-h-[min(16rem,50vh)] overflow-y-auto">
|
||||
{sorted.map((apt) => {
|
||||
const purpose = apt.purpose as keyof typeof APPOINTMENT_PURPOSE_LABEL;
|
||||
return (
|
||||
<li key={apt.id}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onSelect(apt);
|
||||
onClose();
|
||||
}}
|
||||
className={`w-full rounded-[var(--radius-sm)] border px-2.5 py-2 text-left transition-colors hover:brightness-110 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/35 ${purposeStyle(apt.purpose)}`}
|
||||
>
|
||||
<p className="text-xs font-medium truncate">
|
||||
{apt.patient.firstName} {apt.patient.lastName}
|
||||
</p>
|
||||
<p className="text-[11px] opacity-90 tabular-nums">{formatTimeRange(apt)}</p>
|
||||
<p className="text-[10px] opacity-80 truncate">
|
||||
{APPOINTMENT_PURPOSE_LABEL[purpose] ?? apt.purpose}
|
||||
</p>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
'use client';
|
||||
|
||||
import { Trash2 } from 'lucide-react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import type { AppointmentColumnProvider, AppointmentRecord } from '@/types/appointment';
|
||||
import { formatHourLabel } from '@/lib/appointmentTime';
|
||||
import {
|
||||
purposeDeleteIconClass,
|
||||
purposeStyle,
|
||||
} from '@/components/ui/appointments/appointmentPurposeStyles';
|
||||
computeAppointmentLaneLayouts,
|
||||
findOverlapCluster,
|
||||
lanePositionStyles,
|
||||
} from '@/lib/appointmentOverlapLayout';
|
||||
import { purposeStyle } from '@/components/ui/appointments/appointmentPurposeStyles';
|
||||
import { AppointmentOverlapPopover } from '@/components/ui/appointments/AppointmentOverlapPopover';
|
||||
|
||||
const HOUR_PX = 40;
|
||||
const HOURS = Array.from({ length: 24 }, (_, i) => i);
|
||||
@@ -27,13 +30,37 @@ function layoutBlock(apt: AppointmentRecord, day: Date): { top: string; height:
|
||||
return { top: `${top}%`, height: `${height}%` };
|
||||
}
|
||||
|
||||
function appointmentDurationMinutes(apt: AppointmentRecord): number {
|
||||
const start = new Date(apt.startAt).getTime();
|
||||
const end = new Date(apt.endAt).getTime();
|
||||
return Math.max(0, Math.round((end - start) / 60_000));
|
||||
}
|
||||
|
||||
function appointmentBannerHeightPx(durationMin: number): number {
|
||||
return (durationMin / (24 * 60)) * HOURS.length * HOUR_PX;
|
||||
}
|
||||
|
||||
function shortBannerNameClass(durationMin: number): string {
|
||||
const heightPx = appointmentBannerHeightPx(durationMin);
|
||||
if (heightPx < 18) {
|
||||
return 'text-[8px] leading-none';
|
||||
}
|
||||
if (durationMin < 60) {
|
||||
return 'text-[9px] leading-none';
|
||||
}
|
||||
return 'text-[11px] leading-tight';
|
||||
}
|
||||
|
||||
type OverlapPopoverState = {
|
||||
appointments: AppointmentRecord[];
|
||||
anchorRect: DOMRect;
|
||||
};
|
||||
|
||||
interface AppointmentScheduleGridProps {
|
||||
day: Date;
|
||||
providers: AppointmentColumnProvider[];
|
||||
appointments: AppointmentRecord[];
|
||||
canBook: boolean;
|
||||
canDelete?: boolean;
|
||||
onDeleteAppointment?: (id: string) => void;
|
||||
onSlotClick: (hour: number, providerUserId: string, providerName: string) => void;
|
||||
onAppointmentClick?: (appointment: AppointmentRecord) => void;
|
||||
}
|
||||
@@ -43,12 +70,36 @@ export function AppointmentScheduleGrid({
|
||||
providers,
|
||||
appointments,
|
||||
canBook,
|
||||
canDelete = false,
|
||||
onDeleteAppointment,
|
||||
onSlotClick,
|
||||
onAppointmentClick,
|
||||
}: AppointmentScheduleGridProps) {
|
||||
const gridHeight = HOURS.length * HOUR_PX;
|
||||
const [overlapPopover, setOverlapPopover] = useState<OverlapPopoverState | null>(null);
|
||||
|
||||
const laneLayoutsByProvider = useMemo(() => {
|
||||
const map = new Map<string, ReturnType<typeof computeAppointmentLaneLayouts>>();
|
||||
for (const provider of providers) {
|
||||
const providerApts = appointments.filter((a) => a.providerUserId === provider.userId);
|
||||
map.set(provider.userId, computeAppointmentLaneLayouts(providerApts));
|
||||
}
|
||||
return map;
|
||||
}, [appointments, providers]);
|
||||
|
||||
function handleAppointmentBannerClick(
|
||||
apt: AppointmentRecord,
|
||||
providerAppointments: AppointmentRecord[],
|
||||
anchor: HTMLElement,
|
||||
) {
|
||||
const cluster = findOverlapCluster(apt.id, providerAppointments);
|
||||
if (cluster.length > 1) {
|
||||
setOverlapPopover({
|
||||
appointments: cluster,
|
||||
anchorRect: anchor.getBoundingClientRect(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
onAppointmentClick?.(apt);
|
||||
}
|
||||
|
||||
if (providers.length === 0) {
|
||||
return (
|
||||
@@ -59,106 +110,145 @@ export function AppointmentScheduleGrid({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="surface-card overflow-x-auto">
|
||||
<div className="min-w-[640px]">
|
||||
<div className="flex border-b border-border">
|
||||
<div className="w-14 flex-shrink-0" />
|
||||
{providers.map((p) => (
|
||||
<div
|
||||
key={p.userId}
|
||||
className="flex-1 min-w-[130px] text-center text-sm font-medium text-text-primary py-2.5 px-1 border-l border-border"
|
||||
>
|
||||
{p.name}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex">
|
||||
<div className="w-14 flex-shrink-0 border-r border-border bg-background-secondary/40">
|
||||
{HOURS.map((h) => (
|
||||
<div
|
||||
key={h}
|
||||
className="text-[11px] text-text-muted flex items-start justify-end pr-1.5 pt-0.5 border-b border-border/50"
|
||||
style={{ height: HOUR_PX }}
|
||||
>
|
||||
{formatHourLabel(h)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 flex min-w-0">
|
||||
<>
|
||||
<div className="surface-card overflow-x-auto">
|
||||
<div className="min-w-[640px]">
|
||||
<div className="flex border-b border-border">
|
||||
<div className="w-14 flex-shrink-0" />
|
||||
{providers.map((p) => (
|
||||
<div
|
||||
key={p.userId}
|
||||
className="flex-1 min-w-[130px] border-l border-border relative"
|
||||
style={{ height: gridHeight }}
|
||||
className="flex-1 min-w-[130px] text-center text-sm font-medium text-text-primary py-2.5 px-1 border-l border-border"
|
||||
>
|
||||
{HOURS.map((h) => {
|
||||
const slotDisabled = !canBook;
|
||||
return (
|
||||
<button
|
||||
key={h}
|
||||
type="button"
|
||||
disabled={slotDisabled}
|
||||
title={
|
||||
slotDisabled ? 'You cannot create appointments' : `Book ${formatHourLabel(h)}`
|
||||
}
|
||||
className={`absolute left-0 right-0 border-b border-border/50 transition-colors ${
|
||||
slotDisabled
|
||||
? 'cursor-not-allowed opacity-50'
|
||||
: 'hover:bg-primary/8 cursor-pointer'
|
||||
}`}
|
||||
style={{ top: h * HOUR_PX, height: HOUR_PX }}
|
||||
onClick={() => onSlotClick(h, p.userId, p.name)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
{appointments
|
||||
.filter((a) => a.providerUserId === p.userId)
|
||||
.map((apt) => {
|
||||
const pos = layoutBlock(apt, day);
|
||||
if (!pos) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={apt.id}
|
||||
onClick={() => onAppointmentClick?.(apt)}
|
||||
className={`absolute left-0.5 right-0.5 rounded-[var(--radius-sm)] border pointer-events-auto z-10 flex flex-row items-center gap-1.5 px-1.5 py-1 min-h-[36px] text-left ${purposeStyle(apt.purpose)} focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/35`}
|
||||
style={{ top: pos.top, height: pos.height, minHeight: 36 }}
|
||||
>
|
||||
<div className="pointer-events-none flex-1 min-w-0 overflow-hidden text-left">
|
||||
<p className="text-[11px] font-medium leading-tight truncate">
|
||||
{apt.patient.firstName} {apt.patient.lastName}
|
||||
</p>
|
||||
{apt.patient.phone && (
|
||||
<p className="text-[10px] opacity-90 truncate">{apt.patient.phone}</p>
|
||||
)}
|
||||
</div>
|
||||
{canDelete && onDeleteAppointment && (
|
||||
<button
|
||||
type="button"
|
||||
className="group pointer-events-auto shrink-0 self-center z-20 mr-0.5 ml-0.5 inline-flex cursor-pointer items-center justify-center rounded-[var(--radius-sm)] bg-transparent p-1 outline-none focus-visible:ring-2 focus-visible:ring-primary/35"
|
||||
aria-label="Delete appointment"
|
||||
title="Delete appointment"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onDeleteAppointment(apt.id);
|
||||
}}
|
||||
>
|
||||
<Trash2 className={`w-4 h-4 ${purposeDeleteIconClass(apt.purpose)}`} />
|
||||
</button>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{p.name}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex">
|
||||
<div className="w-14 flex-shrink-0 border-r border-border bg-background-secondary/40">
|
||||
{HOURS.map((h) => (
|
||||
<div
|
||||
key={h}
|
||||
className="text-[11px] text-text-muted flex items-start justify-end pr-1.5 pt-0.5 border-b border-border/50"
|
||||
style={{ height: HOUR_PX }}
|
||||
>
|
||||
{formatHourLabel(h)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 flex min-w-0">
|
||||
{providers.map((p) => {
|
||||
const providerAppointments = appointments.filter(
|
||||
(a) => a.providerUserId === p.userId,
|
||||
);
|
||||
const laneLayouts = laneLayoutsByProvider.get(p.userId) ?? new Map();
|
||||
|
||||
return (
|
||||
<div
|
||||
key={p.userId}
|
||||
className="flex-1 min-w-[130px] border-l border-border relative"
|
||||
style={{ height: gridHeight }}
|
||||
>
|
||||
{HOURS.map((h) => {
|
||||
const slotDisabled = !canBook;
|
||||
return (
|
||||
<button
|
||||
key={h}
|
||||
type="button"
|
||||
disabled={slotDisabled}
|
||||
title={
|
||||
slotDisabled
|
||||
? 'You cannot create appointments'
|
||||
: `Book ${formatHourLabel(h)}`
|
||||
}
|
||||
className={`absolute left-0 right-0 border-b border-border/50 transition-colors ${
|
||||
slotDisabled
|
||||
? 'cursor-not-allowed opacity-50'
|
||||
: 'hover:bg-primary/8 cursor-pointer'
|
||||
}`}
|
||||
style={{ top: h * HOUR_PX, height: HOUR_PX }}
|
||||
onClick={() => onSlotClick(h, p.userId, p.name)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
{providerAppointments.map((apt) => {
|
||||
const pos = layoutBlock(apt, day);
|
||||
if (!pos) {
|
||||
return null;
|
||||
}
|
||||
const lane = laneLayouts.get(apt.id) ?? { lane: 0, laneCount: 1 };
|
||||
const lanePos = lanePositionStyles(lane.lane, lane.laneCount);
|
||||
const durationMin = appointmentDurationMinutes(apt);
|
||||
const clusterSize = findOverlapCluster(apt.id, providerAppointments).length;
|
||||
const isUnderOneHour = durationMin < 60;
|
||||
const patientName = `${apt.patient.firstName} ${apt.patient.lastName}`;
|
||||
const bannerTitle = [
|
||||
patientName,
|
||||
clusterSize > 1 ? `${clusterSize} overlapping — click to choose` : null,
|
||||
!isUnderOneHour && apt.patient.phone ? apt.patient.phone : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={apt.id}
|
||||
onClick={(e) =>
|
||||
handleAppointmentBannerClick(apt, providerAppointments, e.currentTarget)
|
||||
}
|
||||
className={`absolute min-h-0 overflow-hidden rounded-[var(--radius-sm)] border pointer-events-auto z-10 flex text-left ${purposeStyle(apt.purpose)} focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/35 ${
|
||||
isUnderOneHour
|
||||
? 'items-center justify-center px-0.5 py-0'
|
||||
: 'flex-col justify-start gap-0.5 px-1 py-0.5'
|
||||
}`}
|
||||
style={{
|
||||
top: pos.top,
|
||||
height: pos.height,
|
||||
left: lanePos.left,
|
||||
width: lanePos.width,
|
||||
}}
|
||||
title={bannerTitle}
|
||||
>
|
||||
<span
|
||||
className={`block w-full truncate pointer-events-none font-medium ${shortBannerNameClass(durationMin)}`}
|
||||
>
|
||||
{patientName}
|
||||
</span>
|
||||
{!isUnderOneHour &&
|
||||
apt.patient.phone &&
|
||||
lane.laneCount === 1 && (
|
||||
<span className="block w-full truncate pointer-events-none text-[10px] leading-tight opacity-90">
|
||||
{apt.patient.phone}
|
||||
</span>
|
||||
)}
|
||||
{!isUnderOneHour && clusterSize > 1 && (
|
||||
<span className="block w-full truncate pointer-events-none text-[9px] leading-tight opacity-75">
|
||||
{clusterSize} overlapping
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{overlapPopover && (
|
||||
<AppointmentOverlapPopover
|
||||
appointments={overlapPopover.appointments}
|
||||
anchorRect={overlapPopover.anchorRect}
|
||||
onSelect={(apt) => onAppointmentClick?.(apt)}
|
||||
onClose={() => setOverlapPopover(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -23,19 +23,6 @@ export function purposeStyle(purpose: string): string {
|
||||
return APPOINTMENT_PURPOSE_STYLES[p] ?? 'bg-surface-elevated border-border text-text-secondary';
|
||||
}
|
||||
|
||||
/** Trash icon — legend hues; `!` overrides global `.lucide { color: var(--color-icon) }`. */
|
||||
export function purposeDeleteIconClass(purpose: string): string {
|
||||
const p = purpose as AppointmentPurpose;
|
||||
const map: Record<AppointmentPurpose, string> = {
|
||||
consultation: '!text-purpose-consultation-fg',
|
||||
filling: '!text-purpose-filling-fg',
|
||||
endo: '!text-purpose-endo-fg',
|
||||
visit: '!text-purpose-visit-fg',
|
||||
hygiene: '!text-purpose-hygiene-fg',
|
||||
};
|
||||
return map[p] ?? '!text-text-muted';
|
||||
}
|
||||
|
||||
/** Small swatch for legend (background + border only). */
|
||||
export const APPOINTMENT_PURPOSE_LEGEND_SWATCH: Record<AppointmentPurpose, string> = {
|
||||
consultation: 'bg-violet-500/85 border-violet-400/75',
|
||||
|
||||
@@ -43,8 +43,8 @@ export function Badge({
|
||||
);
|
||||
}
|
||||
|
||||
/** Map organization link / invitation row status to badge variant. */
|
||||
export function organizationLinkStatusVariant(status: string): BadgeVariant {
|
||||
/** Map organization connection / invitation row status to badge variant. */
|
||||
export function organizationConnectionStatusVariant(status: string): BadgeVariant {
|
||||
switch (status) {
|
||||
case 'ACTIVE':
|
||||
return 'success';
|
||||
|
||||
@@ -1,48 +1,299 @@
|
||||
'use client';
|
||||
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { addCalendarDays } from '@/lib/appointmentTime';
|
||||
import { useEffect, useId, useRef, useState } from 'react';
|
||||
import { ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import {
|
||||
addCalendarDays,
|
||||
compareLocalDayStart,
|
||||
startOfLocalDay,
|
||||
} from '@/lib/appointmentTime';
|
||||
|
||||
interface ScheduleDayPickerProps {
|
||||
value: Date;
|
||||
onChange: (day: Date) => void;
|
||||
/** Optional lower bound; picker navigation is unrestricted for history browsing. */
|
||||
/** Optional lower bound for day selection and previous-day navigation. */
|
||||
minDate?: Date;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export function ScheduleDayPicker({ value, onChange, label = 'Schedule date' }: ScheduleDayPickerProps) {
|
||||
const labelText = value.toLocaleDateString(undefined, {
|
||||
const MONTH_LABELS = [
|
||||
'January',
|
||||
'February',
|
||||
'March',
|
||||
'April',
|
||||
'May',
|
||||
'June',
|
||||
'July',
|
||||
'August',
|
||||
'September',
|
||||
'October',
|
||||
'November',
|
||||
'December',
|
||||
] as const;
|
||||
|
||||
function daysInMonth(year: number, month: number): number {
|
||||
return new Date(year, month + 1, 0).getDate();
|
||||
}
|
||||
|
||||
function buildLocalDay(year: number, month: number, day: number): Date {
|
||||
return new Date(year, month, day, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
function clampToValidDay(
|
||||
year: number,
|
||||
month: number,
|
||||
day: number,
|
||||
min?: Date,
|
||||
): Date {
|
||||
const maxDay = daysInMonth(year, month);
|
||||
let next = buildLocalDay(year, month, Math.min(Math.max(1, day), maxDay));
|
||||
if (min) {
|
||||
const floor = startOfLocalDay(min);
|
||||
if (compareLocalDayStart(next, floor) < 0) {
|
||||
next = floor;
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function yearRange(min?: Date, anchor?: Date): number[] {
|
||||
const now = new Date();
|
||||
const startYear = min ? min.getFullYear() : now.getFullYear() - 5;
|
||||
const endYear = Math.max(now.getFullYear() + 2, anchor?.getFullYear() ?? now.getFullYear());
|
||||
const years: number[] = [];
|
||||
for (let y = startYear; y <= endYear; y += 1) {
|
||||
years.push(y);
|
||||
}
|
||||
return years;
|
||||
}
|
||||
|
||||
const selectClassName = `
|
||||
w-full appearance-none rounded-[var(--radius-sm)] border border-border
|
||||
bg-background-card/90 text-text-primary text-sm
|
||||
pl-2 pr-7 py-1.5
|
||||
focus:outline-none focus:ring-2 focus:ring-primary/35 focus:border-border-strong
|
||||
disabled:opacity-50 disabled:cursor-not-allowed
|
||||
`;
|
||||
|
||||
export function ScheduleDayPicker({
|
||||
value,
|
||||
onChange,
|
||||
minDate,
|
||||
label = 'Schedule date',
|
||||
}: ScheduleDayPickerProps) {
|
||||
const panelId = useId();
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const [panelOpen, setPanelOpen] = useState(false);
|
||||
|
||||
const normalizedValue = startOfLocalDay(value);
|
||||
const normalizedMin = minDate ? startOfLocalDay(minDate) : undefined;
|
||||
|
||||
const labelText = normalizedValue.toLocaleDateString(undefined, {
|
||||
weekday: 'short',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
});
|
||||
|
||||
const previousDay = addCalendarDays(normalizedValue, -1);
|
||||
const canGoPrevious =
|
||||
!normalizedMin || compareLocalDayStart(previousDay, normalizedMin) >= 0;
|
||||
|
||||
const years = yearRange(normalizedMin, normalizedValue);
|
||||
const selectedYear = normalizedValue.getFullYear();
|
||||
const selectedMonth = normalizedValue.getMonth();
|
||||
const selectedDay = normalizedValue.getDate();
|
||||
const dayCount = daysInMonth(selectedYear, selectedMonth);
|
||||
|
||||
function applyParts(year: number, month: number, day: number, closePanel = false) {
|
||||
onChange(clampToValidDay(year, month, day, normalizedMin));
|
||||
if (closePanel) {
|
||||
setPanelOpen(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handlePreviousDay() {
|
||||
if (!canGoPrevious) return;
|
||||
onChange(previousDay);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!panelOpen) return;
|
||||
|
||||
function onPointerDown(event: MouseEvent) {
|
||||
if (!rootRef.current?.contains(event.target as Node)) {
|
||||
setPanelOpen(false);
|
||||
}
|
||||
}
|
||||
|
||||
function onKeyDown(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') {
|
||||
setPanelOpen(false);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('mousedown', onPointerDown);
|
||||
document.addEventListener('keydown', onKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', onPointerDown);
|
||||
document.removeEventListener('keydown', onKeyDown);
|
||||
};
|
||||
}, [panelOpen]);
|
||||
|
||||
return (
|
||||
<div className="w-full max-w-md">
|
||||
<div ref={rootRef} className="relative w-full max-w-md">
|
||||
<p className="text-sm font-medium text-text-secondary mb-2">{label}</p>
|
||||
<div className="flex items-center gap-1 rounded-[var(--radius-md)] border border-border bg-background-secondary/90 px-1 py-1 shadow-[inset_0_1px_0_rgba(255,255,255,0.02)]">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(addCalendarDays(value, -1))}
|
||||
className="shrink-0 rounded-[var(--radius-sm)] p-2 text-text-muted hover:text-text-primary hover:bg-background-card/80 focus:outline-none focus:ring-2 focus:ring-primary/35"
|
||||
onClick={handlePreviousDay}
|
||||
disabled={!canGoPrevious}
|
||||
className="shrink-0 rounded-[var(--radius-sm)] p-2 text-text-muted hover:text-text-primary hover:bg-background-card/80 focus:outline-none focus:ring-2 focus:ring-primary/35 disabled:opacity-40 disabled:pointer-events-none"
|
||||
aria-label="Previous day"
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4 icon-flat" />
|
||||
</button>
|
||||
<div className="flex-1 min-w-0 text-center text-sm font-medium text-text-primary tabular-nums px-2 py-1.5">
|
||||
{labelText}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(addCalendarDays(value, 1))}
|
||||
onClick={() => setPanelOpen((open) => !open)}
|
||||
aria-expanded={panelOpen}
|
||||
aria-controls={panelId}
|
||||
aria-haspopup="dialog"
|
||||
className="flex flex-1 min-w-0 items-center justify-center gap-1 rounded-[var(--radius-sm)] px-2 py-1.5 text-sm font-medium text-text-primary tabular-nums hover:bg-background-card/80 focus:outline-none focus:ring-2 focus:ring-primary/35"
|
||||
>
|
||||
<span className="truncate">{labelText}</span>
|
||||
<ChevronDown
|
||||
className={`h-3.5 w-3.5 shrink-0 text-text-muted icon-flat transition-transform ${panelOpen ? 'rotate-180' : ''}`}
|
||||
aria-hidden
|
||||
/>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(addCalendarDays(normalizedValue, 1))}
|
||||
className="shrink-0 rounded-[var(--radius-sm)] p-2 text-text-muted hover:text-text-primary hover:bg-background-card/80 focus:outline-none focus:ring-2 focus:ring-primary/35"
|
||||
aria-label="Next day"
|
||||
>
|
||||
<ChevronRight className="h-4 w-4 icon-flat" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{panelOpen && (
|
||||
<div
|
||||
id={panelId}
|
||||
role="dialog"
|
||||
aria-label="Choose schedule date"
|
||||
className="absolute left-0 right-0 top-full z-50 mt-2 rounded-[var(--radius-md)] border border-border bg-background-secondary p-3 shadow-lg"
|
||||
>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<label
|
||||
htmlFor={`${panelId}-year`}
|
||||
className="mb-1 block text-xs font-medium text-text-muted"
|
||||
>
|
||||
Year
|
||||
</label>
|
||||
<div className="relative">
|
||||
<select
|
||||
id={`${panelId}-year`}
|
||||
value={selectedYear}
|
||||
onChange={(e) =>
|
||||
applyParts(Number(e.target.value), selectedMonth, selectedDay)
|
||||
}
|
||||
className={selectClassName}
|
||||
>
|
||||
{years.map((year) => (
|
||||
<option key={year} value={year}>
|
||||
{year}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown
|
||||
className="pointer-events-none absolute right-1.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-text-muted icon-flat"
|
||||
aria-hidden
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor={`${panelId}-month`}
|
||||
className="mb-1 block text-xs font-medium text-text-muted"
|
||||
>
|
||||
Month
|
||||
</label>
|
||||
<div className="relative">
|
||||
<select
|
||||
id={`${panelId}-month`}
|
||||
value={selectedMonth}
|
||||
onChange={(e) =>
|
||||
applyParts(selectedYear, Number(e.target.value), selectedDay)
|
||||
}
|
||||
className={selectClassName}
|
||||
>
|
||||
{MONTH_LABELS.map((name, index) => {
|
||||
const disabled =
|
||||
normalizedMin &&
|
||||
selectedYear === normalizedMin.getFullYear() &&
|
||||
index < normalizedMin.getMonth();
|
||||
return (
|
||||
<option key={name} value={index} disabled={disabled}>
|
||||
{name}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
<ChevronDown
|
||||
className="pointer-events-none absolute right-1.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-text-muted icon-flat"
|
||||
aria-hidden
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor={`${panelId}-day`}
|
||||
className="mb-1 block text-xs font-medium text-text-muted"
|
||||
>
|
||||
Day
|
||||
</label>
|
||||
<div className="relative">
|
||||
<select
|
||||
id={`${panelId}-day`}
|
||||
value={selectedDay}
|
||||
onChange={(e) =>
|
||||
applyParts(
|
||||
selectedYear,
|
||||
selectedMonth,
|
||||
Number(e.target.value),
|
||||
true,
|
||||
)
|
||||
}
|
||||
className={selectClassName}
|
||||
>
|
||||
{Array.from({ length: dayCount }, (_, i) => i + 1).map((day) => {
|
||||
const disabled =
|
||||
normalizedMin &&
|
||||
selectedYear === normalizedMin.getFullYear() &&
|
||||
selectedMonth === normalizedMin.getMonth() &&
|
||||
day < normalizedMin.getDate();
|
||||
return (
|
||||
<option key={day} value={day} disabled={disabled}>
|
||||
{day}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
<ChevronDown
|
||||
className="pointer-events-none absolute right-1.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-text-muted icon-flat"
|
||||
aria-hidden
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -24,3 +24,70 @@ export function Toast({ children, variant = 'default', className = '' }: ToastPr
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export type ToastMessages = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
info?: string;
|
||||
default?: string;
|
||||
};
|
||||
|
||||
export type ToastStackProps = ToastMessages & {
|
||||
className?: string;
|
||||
};
|
||||
|
||||
function hasToastMessages(messages: ToastMessages): boolean {
|
||||
return Boolean(messages.error || messages.success || messages.info || messages.default);
|
||||
}
|
||||
|
||||
/** Renders active toast messages with shared badge colors (success / warning / danger / default). */
|
||||
export function ToastStack({ error, success, info, default: defaultMessage, className = '' }: ToastStackProps) {
|
||||
if (!hasToastMessages({ error, success, info, default: defaultMessage })) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`space-y-2 ${className}`.trim()} aria-live="polite">
|
||||
{error && <Toast variant="danger">{error}</Toast>}
|
||||
{info && <Toast variant="warning">{info}</Toast>}
|
||||
{success && <Toast variant="success">{success}</Toast>}
|
||||
{defaultMessage && <Toast variant="default">{defaultMessage}</Toast>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export type ToastViewportPosition = 'inline' | 'top' | 'bottom';
|
||||
|
||||
export type ToastViewportProps = ToastStackProps & {
|
||||
position?: ToastViewportPosition;
|
||||
};
|
||||
|
||||
const viewportPositionClass: Record<Exclude<ToastViewportPosition, 'inline'>, string> = {
|
||||
top: 'fixed top-4 left-0 right-0 z-[70] px-4 pointer-events-none',
|
||||
bottom: 'fixed bottom-4 left-0 right-0 z-[70] px-4 pointer-events-none',
|
||||
};
|
||||
|
||||
/**
|
||||
* Positions a ToastStack on the page. Use `inline` below a heading; `bottom` / `top` for overlays.
|
||||
*/
|
||||
export function ToastViewport({
|
||||
position = 'inline',
|
||||
className = '',
|
||||
...messages
|
||||
}: ToastViewportProps) {
|
||||
if (!hasToastMessages(messages)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const stack = <ToastStack {...messages} className={className} />;
|
||||
|
||||
if (position === 'inline') {
|
||||
return stack;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={viewportPositionClass[position]}>
|
||||
<div className="pointer-events-auto w-full">{stack}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
'use client';
|
||||
|
||||
import { Check, Copy } from 'lucide-react';
|
||||
import {
|
||||
canShareOrganizationInviteLink,
|
||||
type InvitationLinkTarget,
|
||||
} from '@/components/invitations/organizationInviteLinks';
|
||||
|
||||
type CopyInvitationLinkButtonProps = {
|
||||
invitation: InvitationLinkTarget;
|
||||
copied: boolean;
|
||||
copying: boolean;
|
||||
onCopy: () => void;
|
||||
};
|
||||
|
||||
export function CopyInvitationLinkButton({
|
||||
invitation,
|
||||
copied,
|
||||
copying,
|
||||
onCopy,
|
||||
}: CopyInvitationLinkButtonProps) {
|
||||
if (!canShareOrganizationInviteLink(invitation)) {
|
||||
return <span className="text-xs text-text-muted">—</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary disabled:opacity-50"
|
||||
disabled={copying}
|
||||
onClick={onCopy}
|
||||
aria-label="Copy invitation link"
|
||||
title="Copy invitation link (generates a new link if needed)"
|
||||
>
|
||||
{copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
'use client';
|
||||
|
||||
import { Check, Copy } from 'lucide-react';
|
||||
import { DialogCloseButton } from '@/components/ui/common/DialogCloseButton';
|
||||
import { ToastStack, type ToastMessages } from '@/components/ui/common/Toast';
|
||||
import type { OrganizationInvitationHistoryItemDto } from '@/lib/api/organization';
|
||||
import { canShareOrganizationInviteLink } from '@/components/invitations/organizationInviteLinks';
|
||||
import { Badge, organizationLinkStatusVariant } from '@/components/ui/common/Badge';
|
||||
import { Badge, organizationConnectionStatusVariant } from '@/components/ui/common/Badge';
|
||||
import { Table } from '@/components/ui/common/Table';
|
||||
import { CopyInvitationLinkButton } from '@/components/ui/organizations/CopyInvitationLinkButton';
|
||||
|
||||
function formatInvitationStatusLabel(status: OrganizationInvitationHistoryItemDto['status']): string {
|
||||
if (status === 'PENDING') return 'Invitation pending';
|
||||
if (status === 'ACTIVE') return 'Invitation Accepted';
|
||||
if (status === 'ACTIVE') return 'Invitation accepted';
|
||||
if (status === 'REJECTED') return 'Invitation rejected';
|
||||
if (status === 'EXPIRED') return 'Invitation expired';
|
||||
return status;
|
||||
@@ -29,8 +29,8 @@ type InvitationHistoryDialogProps = {
|
||||
copiedId: string | null;
|
||||
copyingInvitationId: string | null;
|
||||
onCopy: (invitation: OrganizationInvitationHistoryItemDto) => void;
|
||||
copyError?: string;
|
||||
copySuccess?: string;
|
||||
/** Same page-level toasts, rendered at top of dialog while it is open. */
|
||||
toastMessages?: ToastMessages;
|
||||
};
|
||||
|
||||
export function InvitationHistoryDialog({
|
||||
@@ -41,8 +41,7 @@ export function InvitationHistoryDialog({
|
||||
copiedId,
|
||||
copyingInvitationId,
|
||||
onCopy,
|
||||
copyError,
|
||||
copySuccess,
|
||||
toastMessages,
|
||||
}: InvitationHistoryDialogProps) {
|
||||
if (!open) return null;
|
||||
|
||||
@@ -61,17 +60,7 @@ export function InvitationHistoryDialog({
|
||||
<DialogCloseButton onClick={onClose} />
|
||||
</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>
|
||||
)}
|
||||
{toastMessages && <ToastStack {...toastMessages} />}
|
||||
|
||||
{loading ? (
|
||||
<p className="text-sm text-text-secondary">Loading invitation history...</p>
|
||||
@@ -94,7 +83,7 @@ export function InvitationHistoryDialog({
|
||||
Status
|
||||
</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-text-muted uppercase tracking-wider">
|
||||
Action
|
||||
Invitation link
|
||||
</th>
|
||||
</tr>
|
||||
}
|
||||
@@ -108,29 +97,17 @@ export function InvitationHistoryDialog({
|
||||
{formatTableDate(inv.createdAt)}
|
||||
</td>
|
||||
<td className="px-6 py-1.5 text-center align-middle">
|
||||
<Badge variant={organizationLinkStatusVariant(inv.status)} fixedWidth={false}>
|
||||
<Badge variant={organizationConnectionStatusVariant(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>
|
||||
)}
|
||||
<CopyInvitationLinkButton
|
||||
invitation={inv}
|
||||
copied={copiedId === inv.id}
|
||||
copying={copyingInvitationId === inv.id}
|
||||
onCopy={() => onCopy(inv)}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
|
||||
@@ -18,6 +18,12 @@ export interface CounterpartItemDto {
|
||||
status: 'PENDING' | 'ACTIVE' | 'REJECTED' | 'EXPIRED';
|
||||
createdAt: string;
|
||||
acceptedAt: string | null;
|
||||
/**
|
||||
* Set by GET /organizations/connections when this PENDING row came from inviteOrganization()
|
||||
* (joined server-side). Lets the main table show copy-invite without opening history.
|
||||
*/
|
||||
pendingInvitationId?: string | null;
|
||||
invitationStatus?: OrganizationInvitationHistoryItemDto['status'] | null;
|
||||
}
|
||||
|
||||
export interface OrganizationInvitationHistoryItemDto {
|
||||
@@ -36,7 +42,7 @@ export const organizationApi = {
|
||||
},
|
||||
|
||||
list: async (): Promise<{ success: boolean; data: { items: CounterpartItemDto[] } }> => {
|
||||
const response = await apiClient.get('/organizations/links');
|
||||
const response = await apiClient.get('/organizations/connections');
|
||||
return response.data;
|
||||
},
|
||||
|
||||
@@ -48,23 +54,27 @@ export const organizationApi = {
|
||||
return response.data;
|
||||
},
|
||||
|
||||
createLink: async (
|
||||
createConnectionRequest: async (
|
||||
targetOrganizationId: string,
|
||||
): Promise<{ success: boolean; data: { id: string; status: 'PENDING' | 'ACTIVE' | 'REJECTED' } }> => {
|
||||
const response = await apiClient.post('/organizations/links', { targetOrganizationId });
|
||||
const response = await apiClient.post('/organizations/connections', { targetOrganizationId });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
respondLink: async (
|
||||
linkId: string,
|
||||
respondToConnectionRequest: async (
|
||||
connectionId: string,
|
||||
action: 'ACCEPT' | 'REJECT',
|
||||
): Promise<{ success: boolean; data: { id: string; status: 'PENDING' | 'ACTIVE' | 'REJECTED' } }> => {
|
||||
const response = await apiClient.patch(`/organizations/links/${linkId}/respond`, { action });
|
||||
const response = await apiClient.patch(`/organizations/connections/${connectionId}/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}`);
|
||||
deleteConnection: async (
|
||||
connectionId: string,
|
||||
): Promise<{ success: boolean; data: { id: string }; message: string }> => {
|
||||
const response = await apiClient.delete(`/organizations/connections/${connectionId}`);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
|
||||
173
frontend/src/lib/appointmentOverlapLayout.ts
Normal file
173
frontend/src/lib/appointmentOverlapLayout.ts
Normal file
@@ -0,0 +1,173 @@
|
||||
import type { AppointmentRecord } from '@/types/appointment';
|
||||
|
||||
export type AppointmentTimedInterval = {
|
||||
id: string;
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
|
||||
export type AppointmentLaneLayout = {
|
||||
lane: number;
|
||||
/** Max concurrent overlaps in this appointment's cluster (column count). */
|
||||
laneCount: number;
|
||||
};
|
||||
|
||||
function intervalsOverlap(a: AppointmentTimedInterval, b: AppointmentTimedInterval): boolean {
|
||||
return a.start < b.end && b.start < a.end;
|
||||
}
|
||||
|
||||
export function toTimedInterval(apt: AppointmentRecord): AppointmentTimedInterval {
|
||||
return {
|
||||
id: apt.id,
|
||||
start: new Date(apt.startAt).getTime(),
|
||||
end: new Date(apt.endAt).getTime(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Connected overlap component containing `appointmentId`. */
|
||||
export function findOverlapCluster(
|
||||
appointmentId: string,
|
||||
appointments: AppointmentRecord[],
|
||||
): AppointmentRecord[] {
|
||||
const byId = new Map(appointments.map((a) => [a.id, a]));
|
||||
if (!byId.has(appointmentId)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const timed = appointments.map(toTimedInterval);
|
||||
const clusterIds = new Set<string>([appointmentId]);
|
||||
let changed = true;
|
||||
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const interval of timed) {
|
||||
if (clusterIds.has(interval.id)) {
|
||||
continue;
|
||||
}
|
||||
for (const memberId of clusterIds) {
|
||||
const member = timed.find((t) => t.id === memberId);
|
||||
if (member && intervalsOverlap(interval, member)) {
|
||||
clusterIds.add(interval.id);
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return appointments.filter((a) => clusterIds.has(a.id));
|
||||
}
|
||||
|
||||
function maxConcurrentCount(intervals: AppointmentTimedInterval[]): number {
|
||||
if (intervals.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
type Point = { time: number; delta: number };
|
||||
const points: Point[] = [];
|
||||
for (const interval of intervals) {
|
||||
points.push({ time: interval.start, delta: 1 });
|
||||
points.push({ time: interval.end, delta: -1 });
|
||||
}
|
||||
points.sort((a, b) => a.time - b.time || a.delta - b.delta);
|
||||
|
||||
let current = 0;
|
||||
let max = 0;
|
||||
for (const point of points) {
|
||||
current += point.delta;
|
||||
max = Math.max(max, current);
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
function assignGreedyLanes(intervals: AppointmentTimedInterval[]): Map<string, number> {
|
||||
const sorted = [...intervals].sort((a, b) => a.start - b.start || a.end - b.end);
|
||||
const laneEndTimes: number[] = [];
|
||||
const laneById = new Map<string, number>();
|
||||
|
||||
for (const interval of sorted) {
|
||||
let lane = laneEndTimes.findIndex((end) => end <= interval.start);
|
||||
if (lane === -1) {
|
||||
lane = laneEndTimes.length;
|
||||
laneEndTimes.push(interval.end);
|
||||
} else {
|
||||
laneEndTimes[lane] = interval.end;
|
||||
}
|
||||
laneById.set(interval.id, lane);
|
||||
}
|
||||
|
||||
return laneById;
|
||||
}
|
||||
|
||||
function buildClusters(intervals: AppointmentTimedInterval[]): AppointmentTimedInterval[][] {
|
||||
const visited = new Set<string>();
|
||||
const clusters: AppointmentTimedInterval[][] = [];
|
||||
|
||||
for (const seed of intervals) {
|
||||
if (visited.has(seed.id)) {
|
||||
continue;
|
||||
}
|
||||
const cluster: AppointmentTimedInterval[] = [];
|
||||
const queue = [seed];
|
||||
visited.add(seed.id);
|
||||
while (queue.length > 0) {
|
||||
const current = queue.pop()!;
|
||||
cluster.push(current);
|
||||
for (const other of intervals) {
|
||||
if (!visited.has(other.id) && intervalsOverlap(current, other)) {
|
||||
visited.add(other.id);
|
||||
queue.push(other);
|
||||
}
|
||||
}
|
||||
}
|
||||
clusters.push(cluster);
|
||||
}
|
||||
|
||||
return clusters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns side-by-side lanes per provider column (Google Calendar style).
|
||||
*/
|
||||
export function computeAppointmentLaneLayouts(
|
||||
appointments: AppointmentRecord[],
|
||||
): Map<string, AppointmentLaneLayout> {
|
||||
const timed = appointments.map(toTimedInterval);
|
||||
if (timed.length === 0) {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
const layouts = new Map<string, AppointmentLaneLayout>();
|
||||
const clusters = buildClusters(timed);
|
||||
|
||||
for (const cluster of clusters) {
|
||||
const laneCount = Math.max(1, maxConcurrentCount(cluster));
|
||||
const greedyLanes = assignGreedyLanes(cluster);
|
||||
const usedLaneIndices = [...new Set(cluster.map((c) => greedyLanes.get(c.id) ?? 0))].sort(
|
||||
(a, b) => a - b,
|
||||
);
|
||||
const remap = new Map(usedLaneIndices.map((lane, index) => [lane, index]));
|
||||
|
||||
for (const interval of cluster) {
|
||||
const rawLane = greedyLanes.get(interval.id) ?? 0;
|
||||
layouts.set(interval.id, {
|
||||
lane: remap.get(rawLane) ?? 0,
|
||||
laneCount,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return layouts;
|
||||
}
|
||||
|
||||
export function lanePositionStyles(lane: number, laneCount: number): {
|
||||
left: string;
|
||||
width: string;
|
||||
} {
|
||||
const gapPct = 1;
|
||||
const widthPct = (100 - gapPct * (laneCount + 1)) / laneCount;
|
||||
return {
|
||||
left: `calc(${gapPct}% + ${lane} * (${widthPct}% + ${gapPct}%))`,
|
||||
width: `${widthPct}%`,
|
||||
};
|
||||
}
|
||||
103
frontend/src/lib/hooks/useToast.ts
Normal file
103
frontend/src/lib/hooks/useToast.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import type { ToastMessages } from '@/components/ui/common/Toast';
|
||||
|
||||
const DEFAULT_DURATION_MS = 4000;
|
||||
|
||||
export type UseToastOptions = {
|
||||
successMs?: number;
|
||||
errorMs?: number;
|
||||
infoMs?: number;
|
||||
defaultMs?: number;
|
||||
};
|
||||
|
||||
export function useToast(options: UseToastOptions = {}) {
|
||||
const successMs = options.successMs ?? DEFAULT_DURATION_MS;
|
||||
const errorMs = options.errorMs ?? DEFAULT_DURATION_MS;
|
||||
const infoMs = options.infoMs ?? DEFAULT_DURATION_MS;
|
||||
const defaultMs = options.defaultMs ?? DEFAULT_DURATION_MS;
|
||||
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState('');
|
||||
const [info, setInfo] = useState('');
|
||||
const [defaultMessage, setDefaultMessage] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (!success) return;
|
||||
const id = setTimeout(() => setSuccess(''), successMs);
|
||||
return () => clearTimeout(id);
|
||||
}, [success, successMs]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!error) return;
|
||||
const id = setTimeout(() => setError(''), errorMs);
|
||||
return () => clearTimeout(id);
|
||||
}, [error, errorMs]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!info) return;
|
||||
const id = setTimeout(() => setInfo(''), infoMs);
|
||||
return () => clearTimeout(id);
|
||||
}, [info, infoMs]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!defaultMessage) return;
|
||||
const id = setTimeout(() => setDefaultMessage(''), defaultMs);
|
||||
return () => clearTimeout(id);
|
||||
}, [defaultMessage, defaultMs]);
|
||||
|
||||
const clear = useCallback(() => {
|
||||
setError('');
|
||||
setSuccess('');
|
||||
setInfo('');
|
||||
setDefaultMessage('');
|
||||
}, []);
|
||||
|
||||
const showError = useCallback((message: string) => {
|
||||
setSuccess('');
|
||||
setInfo('');
|
||||
setDefaultMessage('');
|
||||
setError(message);
|
||||
}, []);
|
||||
|
||||
const showSuccess = useCallback((message: string) => {
|
||||
setError('');
|
||||
setInfo('');
|
||||
setDefaultMessage('');
|
||||
setSuccess(message);
|
||||
}, []);
|
||||
|
||||
const showInfo = useCallback((message: string) => {
|
||||
setError('');
|
||||
setSuccess('');
|
||||
setDefaultMessage('');
|
||||
setInfo(message);
|
||||
}, []);
|
||||
|
||||
const showDefault = useCallback((message: string) => {
|
||||
setError('');
|
||||
setSuccess('');
|
||||
setInfo('');
|
||||
setDefaultMessage(message);
|
||||
}, []);
|
||||
|
||||
const messages: ToastMessages = { error, success, info, default: defaultMessage };
|
||||
|
||||
return {
|
||||
error,
|
||||
success,
|
||||
info,
|
||||
defaultMessage,
|
||||
setError,
|
||||
setSuccess,
|
||||
setInfo,
|
||||
setDefaultMessage,
|
||||
showError,
|
||||
showSuccess,
|
||||
showInfo,
|
||||
showDefault,
|
||||
clear,
|
||||
messages,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user