Compare commits
15 Commits
09b511a136
...
bugfix/dem
| Author | SHA1 | Date | |
|---|---|---|---|
| 3a0f5cbc6e | |||
| 10d8fac3f8 | |||
| 4487d3260b | |||
| 81fe14823f | |||
| 7dba7cc144 | |||
| 95ed1bd4ab | |||
| 535b49310f | |||
| 3b12c52fd3 | |||
| eb636db653 | |||
| 4590255b31 | |||
| 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) {}
|
||||
@@ -126,7 +126,11 @@ export class AuthController {
|
||||
@ApiBearerAuth('JWT-auth')
|
||||
@ApiOperation({ summary: 'Create organization for current user' })
|
||||
async createOrganization(@Req() req, @Body() dto: CreateOrganizationDto) {
|
||||
return this.authService.createOrganization(req.user.id, dto);
|
||||
return this.authService.createOrganization(
|
||||
req.user.id,
|
||||
req.user.organizationId,
|
||||
dto,
|
||||
);
|
||||
}
|
||||
|
||||
// =========================
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
UnauthorizedException,
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
InternalServerErrorException
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
@@ -270,7 +271,11 @@ export class AuthService {
|
||||
return this.login({ email, password } as any, validatedUser);
|
||||
}
|
||||
|
||||
async createOrganization(userId: string, dto: CreateOrganizationDto) {
|
||||
async createOrganization(
|
||||
userId: string,
|
||||
currentOrganizationId: string | undefined,
|
||||
dto: CreateOrganizationDto,
|
||||
) {
|
||||
const owner = await this.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { id: true },
|
||||
@@ -280,6 +285,28 @@ export class AuthService {
|
||||
throw new UnauthorizedException('User not found');
|
||||
}
|
||||
|
||||
if (!currentOrganizationId) {
|
||||
throw new ForbiddenException(
|
||||
'Select an organization before creating a new one.',
|
||||
);
|
||||
}
|
||||
|
||||
const currentMembership = await this.prisma.membership.findUnique({
|
||||
where: {
|
||||
userId_organizationId: {
|
||||
userId,
|
||||
organizationId: currentOrganizationId,
|
||||
},
|
||||
},
|
||||
select: { isOwner: true },
|
||||
});
|
||||
|
||||
if (!currentMembership?.isOwner) {
|
||||
throw new ForbiddenException(
|
||||
'Only owners of the current organization can create new organizations.',
|
||||
);
|
||||
}
|
||||
|
||||
const organization = await this.prisma.$transaction(async (tx) => {
|
||||
const createdOrganization = await tx.organization.create({
|
||||
data: {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -80,6 +80,32 @@ export class StaffController {
|
||||
return this.staffService.updateMember(req.user.id, organizationId, membershipId, dto);
|
||||
}
|
||||
|
||||
@Patch('members/:membershipId/enable')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiOperation({
|
||||
summary: 'Re-enable a disabled staff member (uses one plan seat; no new invitation)',
|
||||
})
|
||||
enableMember(
|
||||
@Req() req: { user: { id: string; organizationId?: string } },
|
||||
@Param('membershipId') membershipId: string,
|
||||
) {
|
||||
const organizationId = this.staffService.getOrganizationIdFromUser(req.user);
|
||||
return this.staffService.enableMember(req.user.id, organizationId, membershipId);
|
||||
}
|
||||
|
||||
@Patch('members/:membershipId/disable')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiOperation({
|
||||
summary: 'Disable staff member (frees a seat; member cannot access this organization)',
|
||||
})
|
||||
disableMember(
|
||||
@Req() req: { user: { id: string; organizationId?: string } },
|
||||
@Param('membershipId') membershipId: string,
|
||||
) {
|
||||
const organizationId = this.staffService.getOrganizationIdFromUser(req.user);
|
||||
return this.staffService.disableMember(req.user.id, organizationId, membershipId);
|
||||
}
|
||||
|
||||
@Delete('members/:membershipId')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiOperation({ summary: 'Remove staff member from organization' })
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { createHash, randomBytes } from 'crypto';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../../../prisma/prisma.service';
|
||||
import { AcceptStaffInviteDto } from './dto/accept-staff-invite.dto';
|
||||
import { isUnlimitedSeats, normalizeTabPermissions } from '../../common/permissions';
|
||||
@@ -399,6 +400,88 @@ export class StaffService {
|
||||
return { success: true, message: 'Member updated' };
|
||||
}
|
||||
|
||||
async enableMember(actorUserId: string, organizationId: string, membershipId: string) {
|
||||
const actor = await this.getActorMembership(actorUserId, organizationId);
|
||||
if (!actor || !this.canEditStaff(actor)) {
|
||||
throw new ForbiddenException('You cannot manage staff');
|
||||
}
|
||||
|
||||
const target = await this.prisma.membership.findFirst({
|
||||
where: { id: membershipId, organizationId },
|
||||
include: {
|
||||
invitations: { orderBy: { createdAt: 'desc' }, take: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
if (!target) {
|
||||
throw new NotFoundException('Member not found');
|
||||
}
|
||||
if (target.isOwner) {
|
||||
throw new ForbiddenException('Cannot enable the organization owner');
|
||||
}
|
||||
if (target.isActive) {
|
||||
throw new BadRequestException('This member is already active');
|
||||
}
|
||||
|
||||
const invitation = target.invitations[0];
|
||||
if (invitation && !invitation.acceptedAt) {
|
||||
throw new BadRequestException(
|
||||
'This member has not completed their invitation yet. Share the invite link instead.',
|
||||
);
|
||||
}
|
||||
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await this.assertOrganizationHasAvailableSeat(organizationId, tx);
|
||||
await tx.membership.update({
|
||||
where: { id: membershipId },
|
||||
data: { isActive: true },
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Member enabled. They can sign in to this organization again.',
|
||||
};
|
||||
}
|
||||
|
||||
async disableMember(actorUserId: string, organizationId: string, membershipId: string) {
|
||||
const actor = await this.getActorMembership(actorUserId, organizationId);
|
||||
if (!actor || !this.canEditStaff(actor)) {
|
||||
throw new ForbiddenException('You cannot manage staff');
|
||||
}
|
||||
|
||||
const target = await this.prisma.membership.findFirst({
|
||||
where: { id: membershipId, organizationId },
|
||||
});
|
||||
|
||||
if (!target) {
|
||||
throw new NotFoundException('Member not found');
|
||||
}
|
||||
if (target.isOwner) {
|
||||
throw new ForbiddenException('Cannot disable the organization owner');
|
||||
}
|
||||
if (actorUserId === target.userId) {
|
||||
throw new BadRequestException('You cannot disable your own access');
|
||||
}
|
||||
if (!target.isActive) {
|
||||
throw new BadRequestException('This member is already disabled or pending activation');
|
||||
}
|
||||
|
||||
await this.prisma.membership.update({
|
||||
where: { id: membershipId },
|
||||
data: { isActive: false },
|
||||
});
|
||||
|
||||
await this.prisma.session.deleteMany({
|
||||
where: { userId: target.userId },
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Member disabled. Their seat is now available for another invite.',
|
||||
};
|
||||
}
|
||||
|
||||
async removeMember(actorUserId: string, organizationId: string, membershipId: string) {
|
||||
const actor = await this.getActorMembership(actorUserId, organizationId);
|
||||
if (!actor || !this.canEditStaff(actor)) {
|
||||
@@ -421,6 +504,37 @@ export class StaffService {
|
||||
return { success: true, message: 'Member removed' };
|
||||
}
|
||||
|
||||
private async assertOrganizationHasAvailableSeat(
|
||||
organizationId: string,
|
||||
db: Prisma.TransactionClient | PrismaService = this.prisma,
|
||||
) {
|
||||
const org = await db.organization.findUnique({
|
||||
where: { id: organizationId },
|
||||
include: { plan: true },
|
||||
});
|
||||
if (!org) {
|
||||
throw new NotFoundException('Organization not found');
|
||||
}
|
||||
if (!org.plan) {
|
||||
throw new BadRequestException(
|
||||
'This organization has no active subscription. Please choose a plan before adding staff.',
|
||||
);
|
||||
}
|
||||
|
||||
const maxUsers = org.plan.maxUsers;
|
||||
const seatsUsed = await db.membership.count({
|
||||
where: {
|
||||
organizationId,
|
||||
OR: [{ isOwner: true }, { isActive: true }],
|
||||
},
|
||||
});
|
||||
if (!isUnlimitedSeats(maxUsers) && seatsUsed >= maxUsers) {
|
||||
throw new BadRequestException(
|
||||
`Your plan allows ${maxUsers} team members. Free a seat by disabling another member or upgrade your plan.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async getActorMembership(userId: string, organizationId: string) {
|
||||
return this.prisma.membership.findFirst({
|
||||
where: { userId, organizationId },
|
||||
@@ -435,11 +549,12 @@ export class StaffService {
|
||||
isOwner: boolean;
|
||||
isActive: boolean;
|
||||
invitations: { acceptedAt: Date | null; revokedAt: Date | null; expiresAt: Date }[];
|
||||
}): 'ACTIVE' | 'PENDING' | 'EXPIRED' {
|
||||
if (m.isOwner || m.isActive) return 'ACTIVE';
|
||||
}): 'ACTIVE' | 'PENDING' | 'EXPIRED' | 'DISABLED' {
|
||||
if (m.isOwner) return 'ACTIVE';
|
||||
if (m.isActive) return 'ACTIVE';
|
||||
const invitation = m.invitations[0];
|
||||
if (!invitation) return 'EXPIRED';
|
||||
if (invitation.acceptedAt) return 'ACTIVE';
|
||||
if (invitation?.acceptedAt) return 'DISABLED';
|
||||
if (!invitation) return 'DISABLED';
|
||||
if (invitation.revokedAt) return 'EXPIRED';
|
||||
return invitation.expiresAt.getTime() > Date.now() ? 'PENDING' : 'EXPIRED';
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { appointmentsApi } from '@/lib/api/appointments';
|
||||
import { patientsApi } from '@/lib/api/patients';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { canEditAppointments, hasPermission } from '@/shared/permissions';
|
||||
import { canEditAppointments, hasPermission } from '@/components/shared/permissions';
|
||||
import type { AppointmentColumnProvider, AppointmentRecord } from '@/types/appointment';
|
||||
import type { CreatePatientInput, Patient } from '@/types/patient';
|
||||
import { CreatePatientModal } from '@/components/ui/patient/CreatePatientModal';
|
||||
@@ -13,11 +13,12 @@ import { AppointmentBookingModal } from '@/components/ui/appointments/Appointmen
|
||||
import { AppointmentScheduleGrid } from '@/components/ui/appointments/AppointmentScheduleGrid';
|
||||
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 { ScheduleDayPicker } from '@/components/ui/shared/ScheduleDayPicker';
|
||||
import { ToastStack } from '@/components/ui/shared/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';
|
||||
import { formatApiErrorMessage } from '@/components/shared/formatApiError';
|
||||
import { compareLocalDayStart, getLocalDayIsoRange, startOfLocalDay } from '@/components/appointments/appointmentTime';
|
||||
|
||||
const EMPTY_PATIENT_FORM: CreatePatientInput = {
|
||||
firstName: '',
|
||||
@@ -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}
|
||||
@@ -299,6 +273,7 @@ export default function AppointmentsPage() {
|
||||
if (!canEditPatients) {
|
||||
return;
|
||||
}
|
||||
setPatientForm(EMPTY_PATIENT_FORM);
|
||||
setIsCreateOpen(true);
|
||||
}}
|
||||
/>
|
||||
@@ -311,7 +286,6 @@ export default function AppointmentsPage() {
|
||||
<div className="flex flex-col sm:flex-row sm:items-end gap-4 sm:justify-between">
|
||||
<ScheduleDayPicker
|
||||
value={scheduleDate}
|
||||
minDate={todayStart}
|
||||
onChange={(d) => setScheduleDate(startOfLocalDay(d))}
|
||||
/>
|
||||
{loadingSchedule && (
|
||||
@@ -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,31 +318,24 @@ export default function AppointmentsPage() {
|
||||
}}
|
||||
onSubmit={handleSaveAppointment}
|
||||
loading={savingAppointment}
|
||||
canDelete={canManageAppointments && !isViewingPastDay && !!activeEditingAppointment}
|
||||
onDelete={() => void handleDeleteEditingAppointment()}
|
||||
deleting={deletingAppointment}
|
||||
/>
|
||||
|
||||
{isCreateOpen && (
|
||||
<div className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/55">
|
||||
<CreatePatientModal
|
||||
isOpen={isCreateOpen}
|
||||
formData={patientForm}
|
||||
onChange={(patch) => setPatientForm((prev) => ({ ...prev, ...patch }))}
|
||||
onSubmit={() => void handleCreatePatient()}
|
||||
onClose={() => setIsCreateOpen(false)}
|
||||
loading={savingPatient}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<CreatePatientModal
|
||||
variant="dialog"
|
||||
isOpen={isCreateOpen}
|
||||
formData={patientForm}
|
||||
onChange={(patch) => setPatientForm((prev) => ({ ...prev, ...patch }))}
|
||||
onSubmit={() => void handleCreatePatient()}
|
||||
onClose={() => {
|
||||
setIsCreateOpen(false);
|
||||
setPatientForm(EMPTY_PATIENT_FORM);
|
||||
}}
|
||||
loading={savingPatient}
|
||||
/>
|
||||
|
||||
{(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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
'use client';
|
||||
import { useState } from 'react';
|
||||
import { Pencil } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Badge } from '@/components/ui/common/Badge';
|
||||
import { Card } from '@/components/ui/common/Card';
|
||||
import { Table } from '@/components/ui/common/Table';
|
||||
import { SearchBar } from '@/components/ui/common/SearchBar';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { Badge } from '@/components/ui/shared/Badge';
|
||||
import { Card } from '@/components/ui/shared/Card';
|
||||
import { Table } from '@/components/ui/shared/Table';
|
||||
import { SearchBar } from '@/components/ui/shared/SearchBar';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { hasPermission } from '@/shared/permissions';
|
||||
import { hasPermission } from '@/components/shared/permissions';
|
||||
// Mock data matching your design
|
||||
const invoices = [
|
||||
{ id: '#123456', patient: 'Ali Rahmani', date: '24/9/2026', service: 'Hygiene', amount: 300, paid: 0, status: 'unpaid' },
|
||||
|
||||
@@ -3,15 +3,15 @@
|
||||
import { memo, useEffect } from 'react';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import Sidebar from '@/components/ui/common/Sidebar';
|
||||
import { ThemeToggle } from '@/components/ui/common/ThemeToggle';
|
||||
import Sidebar from '@/components/ui/shared/Sidebar';
|
||||
import { ThemeToggle } from '@/components/ui/shared/ThemeToggle';
|
||||
import { DashboardAccountMenu } from '@/components/ui/dashboard/DashboardAccountMenu';
|
||||
import {
|
||||
canAccessAppointmentsSection,
|
||||
firstAccessibleDashboardPath,
|
||||
getRequiredReadPermissionForPath,
|
||||
hasPermission,
|
||||
} from '@/shared/permissions';
|
||||
} from '@/components/shared/permissions';
|
||||
|
||||
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
|
||||
const { user, currentOrganization, isAuthReady } = useAuth();
|
||||
|
||||
@@ -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 { Input } from '@/components/ui/common/Input';
|
||||
import { SearchBar } from '@/components/ui/common/SearchBar';
|
||||
import { Table } from '@/components/ui/common/Table';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { Badge, organizationConnectionStatusVariant } from '@/components/ui/shared/Badge';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
import { SearchBar } from '@/components/ui/shared/SearchBar';
|
||||
import { Table } from '@/components/ui/shared/Table';
|
||||
import { ToastStack } from '@/components/ui/shared/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>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { ToastStack } from '@/components/ui/shared/Toast';
|
||||
import { patientsApi } from '@/lib/api/patients';
|
||||
import { formatApiErrorMessage } from '@/components/shared/formatApiError';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { hasPermission } from '@/shared/permissions';
|
||||
import { useToast } from '@/lib/hooks/useToast';
|
||||
import { hasPermission } from '@/components/shared/permissions';
|
||||
import {
|
||||
CreatePatientInput,
|
||||
CreateTreatmentHistoryInput,
|
||||
@@ -25,6 +28,7 @@ const EMPTY_PATIENT_FORM: CreatePatientInput = {
|
||||
|
||||
export default function PatientsPage() {
|
||||
const { currentOrganization } = useAuth();
|
||||
const toast = useToast();
|
||||
const [search, setSearch] = useState('');
|
||||
const [patients, setPatients] = useState<Patient[]>([]);
|
||||
const [selectedPatient, setSelectedPatient] = useState<Patient | undefined>();
|
||||
@@ -35,8 +39,6 @@ export default function PatientsPage() {
|
||||
const [savingPatient, setSavingPatient] = useState(false);
|
||||
const [savingTreatment, setSavingTreatment] = useState(false);
|
||||
const [patientForm, setPatientForm] = useState<CreatePatientInput>(EMPTY_PATIENT_FORM);
|
||||
const [errorMessage, setErrorMessage] = useState<string>('');
|
||||
const [successMessage, setSuccessMessage] = useState<string>('');
|
||||
const canEditPatients = hasPermission(currentOrganization, 'TAB_PATIENTS_EDIT');
|
||||
|
||||
const sortedPatients = useMemo(
|
||||
@@ -58,21 +60,9 @@ export default function PatientsPage() {
|
||||
void loadPatients('');
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!successMessage) {
|
||||
return;
|
||||
}
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
setSuccessMessage('');
|
||||
}, 3000);
|
||||
|
||||
return () => clearTimeout(timeout);
|
||||
}, [successMessage]);
|
||||
|
||||
async function loadPatients(q: string) {
|
||||
setLoadingPatients(true);
|
||||
setErrorMessage('');
|
||||
toast.setError('');
|
||||
try {
|
||||
const response = await patientsApi.list({ q, page: 1, limit: 25 });
|
||||
const items = response.data.items;
|
||||
@@ -82,9 +72,8 @@ export default function PatientsPage() {
|
||||
const freshSelected = items.find((item) => item.id === selectedPatient.id);
|
||||
setSelectedPatient(freshSelected);
|
||||
}
|
||||
} catch (error: any) {
|
||||
const message = Array.isArray(error?.message) ? error.message.join(', ') : error?.message;
|
||||
setErrorMessage(message || 'Failed to load patients.');
|
||||
} catch (error: unknown) {
|
||||
toast.showError(formatApiErrorMessage(error, 'Failed to load patients.'));
|
||||
} finally {
|
||||
setLoadingPatients(false);
|
||||
}
|
||||
@@ -92,13 +81,12 @@ export default function PatientsPage() {
|
||||
|
||||
async function loadTreatments(patientId: string) {
|
||||
setLoadingTreatments(true);
|
||||
setErrorMessage('');
|
||||
toast.setError('');
|
||||
try {
|
||||
const response = await patientsApi.listTreatments(patientId);
|
||||
setTreatments(response.data);
|
||||
} catch (error: any) {
|
||||
const message = Array.isArray(error?.message) ? error.message.join(', ') : error?.message;
|
||||
setErrorMessage(message || 'Failed to load treatment history.');
|
||||
} catch (error: unknown) {
|
||||
toast.showError(formatApiErrorMessage(error, 'Failed to load treatment history.'));
|
||||
} finally {
|
||||
setLoadingTreatments(false);
|
||||
}
|
||||
@@ -106,8 +94,7 @@ export default function PatientsPage() {
|
||||
|
||||
async function handleCreatePatient() {
|
||||
setSavingPatient(true);
|
||||
setErrorMessage('');
|
||||
setSuccessMessage('');
|
||||
toast.setError('');
|
||||
try {
|
||||
const response = await patientsApi.create(patientForm);
|
||||
setIsCreateOpen(false);
|
||||
@@ -115,12 +102,11 @@ export default function PatientsPage() {
|
||||
await loadPatients(search);
|
||||
setSelectedPatient(response.data);
|
||||
await loadTreatments(response.data.id);
|
||||
setSuccessMessage(
|
||||
toast.showSuccess(
|
||||
`Patient ${response.data.firstName} ${response.data.lastName} was saved successfully.`,
|
||||
);
|
||||
} catch (error: any) {
|
||||
const message = Array.isArray(error?.message) ? error.message.join(', ') : error?.message;
|
||||
setErrorMessage(message || 'Failed to save patient.');
|
||||
} catch (error: unknown) {
|
||||
toast.showError(formatApiErrorMessage(error, 'Failed to save patient.'));
|
||||
} finally {
|
||||
setSavingPatient(false);
|
||||
}
|
||||
@@ -139,29 +125,29 @@ export default function PatientsPage() {
|
||||
};
|
||||
|
||||
setSavingTreatment(true);
|
||||
setErrorMessage('');
|
||||
setSuccessMessage('');
|
||||
toast.setError('');
|
||||
try {
|
||||
await patientsApi.addTreatment(selectedPatient.id, payload);
|
||||
await loadTreatments(selectedPatient.id);
|
||||
setSuccessMessage('Treatment entry added successfully.');
|
||||
} catch (error: any) {
|
||||
const message = Array.isArray(error?.message) ? error.message.join(', ') : error?.message;
|
||||
setErrorMessage(message || 'Failed to add treatment entry.');
|
||||
toast.showSuccess('Treatment entry added successfully.');
|
||||
} catch (error: unknown) {
|
||||
toast.showError(formatApiErrorMessage(error, 'Failed to add treatment entry.'));
|
||||
} finally {
|
||||
setSavingTreatment(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative space-y-6 pb-20">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h1 className="text-2xl font-semibold text-text-primary">Patients</h1>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={!canEditPatients}
|
||||
onClick={() => {
|
||||
if (!canEditPatients) return;
|
||||
toast.clear();
|
||||
setPatientForm(EMPTY_PATIENT_FORM);
|
||||
setIsCreateOpen(true);
|
||||
}}
|
||||
title={!canEditPatients ? 'Read-only access for this organization.' : undefined}
|
||||
@@ -170,14 +156,21 @@ export default function PatientsPage() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<CreatePatientModal
|
||||
isOpen={isCreateOpen}
|
||||
formData={patientForm}
|
||||
onChange={(patch) => setPatientForm((prev) => ({ ...prev, ...patch }))}
|
||||
onSubmit={handleCreatePatient}
|
||||
onClose={() => setIsCreateOpen(false)}
|
||||
loading={savingPatient}
|
||||
/>
|
||||
<ToastStack {...toast.messages} />
|
||||
|
||||
{isCreateOpen && (
|
||||
<CreatePatientModal
|
||||
isOpen={isCreateOpen}
|
||||
formData={patientForm}
|
||||
onChange={(patch) => setPatientForm((prev) => ({ ...prev, ...patch }))}
|
||||
onSubmit={() => void handleCreatePatient()}
|
||||
onClose={() => {
|
||||
setIsCreateOpen(false);
|
||||
setPatientForm(EMPTY_PATIENT_FORM);
|
||||
}}
|
||||
loading={savingPatient}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
|
||||
<div className="xl:col-span-1">
|
||||
@@ -213,21 +206,6 @@ export default function PatientsPage() {
|
||||
<TreatmentHistoryPreview items={treatments} loading={loadingTreatments} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(errorMessage || successMessage) && (
|
||||
<div className="absolute bottom-0 left-0 right-0 z-10 w-full">
|
||||
{errorMessage && (
|
||||
<div className="rounded-[var(--radius-sm)] border border-red-500/50 bg-red-500/10 px-3 py-2 text-sm text-red-300 shadow-lg">
|
||||
{errorMessage}
|
||||
</div>
|
||||
)}
|
||||
{successMessage && (
|
||||
<div className="rounded-[var(--radius-sm)] border border-emerald-500/50 bg-emerald-500/10 px-3 py-2 text-sm text-emerald-300 shadow-lg">
|
||||
{successMessage}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@ import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { authApi } from '@/lib/api/auth';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Toast } from '@/components/ui/common/Toast';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { Toast } from '@/components/ui/shared/Toast';
|
||||
import type { SubscriptionAlertData } from '@/types/subscription';
|
||||
|
||||
const PLAN_OPTIONS = [
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
firstAccessibleDashboardPath,
|
||||
canEditStaff,
|
||||
canViewStaff,
|
||||
} from '@/shared/permissions';
|
||||
} from '@/components/shared/permissions';
|
||||
import {
|
||||
STAFF_FEATURE_GROUPS,
|
||||
permissionNamesFromFeatureState,
|
||||
@@ -16,16 +16,18 @@ import {
|
||||
formatAccessSummary,
|
||||
type FeaturePermState,
|
||||
} from '../../../components/staff/staff-permission-form';
|
||||
import { Pencil, Trash2, Copy, Check, X } from 'lucide-react';
|
||||
import { DialogCloseButton } from '@/components/ui/common/DialogCloseButton';
|
||||
import { Pencil, Trash2, Copy, Check, X, UserX, UserCheck } from 'lucide-react';
|
||||
import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { staffApi, type StaffMemberDto } from '@/lib/api/staff';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Badge } from '@/components/ui/common/Badge';
|
||||
import { Input } from '@/components/ui/common/Input';
|
||||
import { Checkbox } from '@/components/ui/common/Checkbox';
|
||||
import { Table } from '@/components/ui/common/Table';
|
||||
import type { ApiError } from '@/types/api';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { Badge } from '@/components/ui/shared/Badge';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
import { Checkbox } from '@/components/ui/shared/Checkbox';
|
||||
import { Table } from '@/components/ui/shared/Table';
|
||||
import { ToastStack } from '@/components/ui/shared/Toast';
|
||||
import { formatApiErrorMessage } from '@/components/shared/formatApiError';
|
||||
import { useToast } from '@/lib/hooks/useToast';
|
||||
|
||||
type StoredInviteLink = {
|
||||
membershipId: string;
|
||||
@@ -54,16 +56,19 @@ function writeStoredInviteLinks(orgId: string, links: Record<string, StoredInvit
|
||||
window.localStorage.setItem(inviteLinksStorageKey(orgId), JSON.stringify(links));
|
||||
}
|
||||
|
||||
function formatApiMessage(err: unknown): string {
|
||||
if (!err || typeof err !== 'object') return 'Something went wrong';
|
||||
const m = (err as ApiError).message;
|
||||
if (Array.isArray(m)) return m.join(', ');
|
||||
if (typeof m === 'string') return m;
|
||||
return 'Something went wrong';
|
||||
function canShareStaffInviteLink(member: StaffMemberDto): boolean {
|
||||
return (
|
||||
!member.isOwner &&
|
||||
(member.invitationStatus === 'PENDING' || member.invitationStatus === 'EXPIRED')
|
||||
);
|
||||
}
|
||||
|
||||
function canShareStaffInviteLink(member: StaffMemberDto): boolean {
|
||||
return !member.isOwner && member.invitationStatus !== 'ACTIVE';
|
||||
function canDisableStaff(member: StaffMemberDto): boolean {
|
||||
return !member.isOwner && member.isActive;
|
||||
}
|
||||
|
||||
function canEnableStaff(member: StaffMemberDto): boolean {
|
||||
return !member.isOwner && member.invitationStatus === 'DISABLED';
|
||||
}
|
||||
|
||||
function PermissionGrid({
|
||||
@@ -136,8 +141,7 @@ export default function StaffPage() {
|
||||
unlimited: boolean;
|
||||
} | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState('');
|
||||
const toast = useToast();
|
||||
|
||||
const [inviteOpen, setInviteOpen] = useState(false);
|
||||
const [inviteEmail, setInviteEmail] = useState('');
|
||||
@@ -159,6 +163,10 @@ export default function StaffPage() {
|
||||
const [editName, setEditName] = useState('');
|
||||
const [editPerms, setEditPerms] = useState(() => emptyFeaturePermissionState());
|
||||
const [editLoading, setEditLoading] = useState(false);
|
||||
const [disableTarget, setDisableTarget] = useState<StaffMemberDto | null>(null);
|
||||
const [disablingMembershipId, setDisablingMembershipId] = useState<string | null>(null);
|
||||
const [enableTarget, setEnableTarget] = useState<StaffMemberDto | null>(null);
|
||||
const [enablingMembershipId, setEnablingMembershipId] = useState<string | null>(null);
|
||||
|
||||
const canEdit = useMemo(() => canEditStaff(currentOrganization), [currentOrganization]);
|
||||
const hasActivePlan = Boolean(currentOrganization?.plan);
|
||||
@@ -168,15 +176,21 @@ export default function StaffPage() {
|
||||
return seats.used >= seats.limit;
|
||||
}, [seats]);
|
||||
|
||||
const hasAvailableSeat = useMemo(() => {
|
||||
if (!seats || seats.unlimited) return true;
|
||||
if (seats.limit == null) return true;
|
||||
return seats.used < seats.limit;
|
||||
}, [seats]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setError('');
|
||||
toast.setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await staffApi.list();
|
||||
setMembers(res.data.members);
|
||||
setSeats(res.data.seats);
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
toast.showError(formatApiErrorMessage(e, 'Failed to load staff.'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -221,17 +235,11 @@ export default function StaffPage() {
|
||||
}
|
||||
}, [currentOrganization, router]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!success) return;
|
||||
const t = setTimeout(() => setSuccess(''), 4000);
|
||||
return () => clearTimeout(t);
|
||||
}, [success]);
|
||||
|
||||
async function copyStaffInviteLink(member: StaffMemberDto) {
|
||||
if (!canShareStaffInviteLink(member)) return;
|
||||
|
||||
setCopyingInviteMembershipId(member.id);
|
||||
setError('');
|
||||
toast.setError('');
|
||||
try {
|
||||
let invitationUrl = pendingInviteLinks[member.id]?.invitationUrl;
|
||||
if (!invitationUrl || member.invitationStatus === 'EXPIRED') {
|
||||
@@ -257,7 +265,7 @@ export default function StaffPage() {
|
||||
await load();
|
||||
}
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
toast.showError(formatApiErrorMessage(e, 'Could not copy invitation link.'));
|
||||
} finally {
|
||||
setCopyingInviteMembershipId(null);
|
||||
}
|
||||
@@ -265,7 +273,7 @@ export default function StaffPage() {
|
||||
|
||||
async function submitInvite() {
|
||||
setInviteLoading(true);
|
||||
setError('');
|
||||
toast.setError('');
|
||||
setLastInviteInfo(null);
|
||||
const displayName = inviteName.trim();
|
||||
const displayEmail = inviteEmail.trim();
|
||||
@@ -295,14 +303,13 @@ export default function StaffPage() {
|
||||
setPendingInviteLinks(nextLinks);
|
||||
writeStoredInviteLinks(currentOrganization.id, nextLinks);
|
||||
}
|
||||
setSuccess('');
|
||||
setInviteOpen(false);
|
||||
setInviteEmail('');
|
||||
setInviteName('');
|
||||
setInvitePerms(emptyFeaturePermissionState());
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
toast.showError(formatApiErrorMessage(e, 'Failed to send invitation.'));
|
||||
} finally {
|
||||
setInviteLoading(false);
|
||||
}
|
||||
@@ -320,36 +327,57 @@ export default function StaffPage() {
|
||||
async function submitEdit() {
|
||||
if (!editing) return;
|
||||
setEditLoading(true);
|
||||
setError('');
|
||||
toast.setError('');
|
||||
try {
|
||||
await staffApi.updateMember(editing.id, {
|
||||
name: editName.trim(),
|
||||
permissionNames: permissionNamesFromFeatureState(editPerms),
|
||||
});
|
||||
setSuccess('Member updated');
|
||||
toast.showSuccess('Member updated.');
|
||||
setEditing(null);
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
toast.showError(formatApiErrorMessage(e, 'Failed to update member.'));
|
||||
} finally {
|
||||
setEditLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeMember(m: StaffMemberDto) {
|
||||
if (m.isOwner) return;
|
||||
if (m.userId === user?.id) {
|
||||
if (!confirm('Remove yourself from this organization? You will lose access.')) return;
|
||||
} else {
|
||||
if (!confirm(`Remove ${m.name} from this organization?`)) return;
|
||||
}
|
||||
setError('');
|
||||
function handleDeleteMember() {
|
||||
toast.showError('Delete is not implemented yet.');
|
||||
}
|
||||
|
||||
async function confirmDisableMember() {
|
||||
if (!disableTarget || !canDisableStaff(disableTarget)) return;
|
||||
|
||||
setDisablingMembershipId(disableTarget.id);
|
||||
toast.setError('');
|
||||
try {
|
||||
await staffApi.removeMember(m.id);
|
||||
setSuccess('Member removed');
|
||||
await staffApi.disableMember(disableTarget.id);
|
||||
toast.showSuccess(`${disableTarget.name} was disabled. A seat is now available.`);
|
||||
setDisableTarget(null);
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
toast.showError(formatApiErrorMessage(e, 'Failed to disable member.'));
|
||||
} finally {
|
||||
setDisablingMembershipId(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmEnableMember() {
|
||||
if (!enableTarget || !canEnableStaff(enableTarget) || !hasAvailableSeat) return;
|
||||
|
||||
setEnablingMembershipId(enableTarget.id);
|
||||
toast.setError('');
|
||||
try {
|
||||
await staffApi.enableMember(enableTarget.id);
|
||||
toast.showSuccess(`${enableTarget.name} was enabled and can sign in again.`);
|
||||
setEnableTarget(null);
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.showError(formatApiErrorMessage(e, 'Failed to enable member.'));
|
||||
} finally {
|
||||
setEnablingMembershipId(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -383,6 +411,8 @@ export default function StaffPage() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<ToastStack {...toast.messages} />
|
||||
|
||||
{seats && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
Seats:{' '}
|
||||
@@ -400,18 +430,6 @@ export default function StaffPage() {
|
||||
</p>
|
||||
)}
|
||||
|
||||
{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>
|
||||
)}
|
||||
|
||||
{lastInviteInfo && (
|
||||
<div className="relative rounded-[var(--radius-md)] border border-border-strong bg-background-secondary/90 px-4 py-3 pr-12 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)] space-y-3">
|
||||
<button
|
||||
@@ -453,7 +471,7 @@ export default function StaffPage() {
|
||||
}
|
||||
void (async () => {
|
||||
setCopyingInviteMembershipId(lastInviteInfo.membershipId);
|
||||
setError('');
|
||||
toast.setError('');
|
||||
try {
|
||||
const res = await staffApi.getInvitationLink(lastInviteInfo.membershipId);
|
||||
if (currentOrganization?.id) {
|
||||
@@ -473,7 +491,7 @@ export default function StaffPage() {
|
||||
setCopiedInviteMembershipId(lastInviteInfo.membershipId);
|
||||
setTimeout(() => setCopiedInviteMembershipId(null), 1500);
|
||||
} catch (e) {
|
||||
setError(formatApiMessage(e));
|
||||
toast.showError(formatApiErrorMessage(e, 'Could not copy invitation link.'));
|
||||
} finally {
|
||||
setCopyingInviteMembershipId(null);
|
||||
}
|
||||
@@ -501,7 +519,9 @@ export default function StaffPage() {
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">Role</th>
|
||||
<th className="px-6 py-3 text-center text-xs font-medium text-text-muted uppercase tracking-wider">Status</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">Access</th>
|
||||
<th className="px-6 py-3 text-right text-xs font-medium text-text-muted uppercase tracking-wider w-28">Actions</th>
|
||||
<th className="px-6 py-3 text-center text-xs font-medium text-text-muted uppercase tracking-wider w-36">
|
||||
Action
|
||||
</th>
|
||||
</tr>
|
||||
}
|
||||
body={
|
||||
@@ -522,6 +542,8 @@ export default function StaffPage() {
|
||||
<Badge variant="success">Active</Badge>
|
||||
) : m.invitationStatus === 'PENDING' ? (
|
||||
<Badge variant="warning">Pending</Badge>
|
||||
) : m.invitationStatus === 'DISABLED' ? (
|
||||
<Badge variant="default">Disabled</Badge>
|
||||
) : (
|
||||
<Badge variant="danger">Expired</Badge>
|
||||
)}
|
||||
@@ -535,9 +557,9 @@ export default function StaffPage() {
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-6 py-1.5 align-middle">
|
||||
<td className="px-6 py-1.5 align-middle text-center">
|
||||
{!m.isOwner && (
|
||||
<div className="flex min-h-[36px] items-center justify-end gap-1">
|
||||
<div className="flex min-h-[36px] items-center justify-center gap-1 mx-auto w-fit">
|
||||
{canShareStaffInviteLink(m) && (
|
||||
<button
|
||||
type="button"
|
||||
@@ -554,6 +576,44 @@ export default function StaffPage() {
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
{canEnableStaff(m) && (
|
||||
<button
|
||||
type="button"
|
||||
className={`p-2 rounded-md ${
|
||||
canEdit
|
||||
? 'text-text-secondary hover:bg-background-card/80 hover:text-primary'
|
||||
: 'text-text-muted opacity-50 cursor-not-allowed'
|
||||
}`}
|
||||
aria-label="Enable member"
|
||||
disabled={!canEdit || enablingMembershipId === m.id}
|
||||
title="Enable member (uses a seat)"
|
||||
onClick={() => {
|
||||
if (!canEdit) return;
|
||||
setEnableTarget(m);
|
||||
}}
|
||||
>
|
||||
<UserCheck className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
{canDisableStaff(m) && (
|
||||
<button
|
||||
type="button"
|
||||
className={`p-2 rounded-md ${
|
||||
canEdit
|
||||
? 'text-text-secondary hover:bg-background-card/80 hover:text-amber-600'
|
||||
: 'text-text-muted opacity-50 cursor-not-allowed'
|
||||
}`}
|
||||
aria-label="Disable member"
|
||||
disabled={!canEdit || disablingMembershipId === m.id}
|
||||
title="Disable member (frees a seat)"
|
||||
onClick={() => {
|
||||
if (!canEdit) return;
|
||||
setDisableTarget(m);
|
||||
}}
|
||||
>
|
||||
<UserX className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={`p-2 rounded-md ${
|
||||
@@ -577,11 +637,12 @@ export default function StaffPage() {
|
||||
? 'text-text-secondary hover:bg-red-500/15 hover:text-red-600'
|
||||
: 'text-text-muted opacity-50 cursor-not-allowed'
|
||||
}`}
|
||||
aria-label="Remove member"
|
||||
aria-label="Delete member"
|
||||
disabled={!canEdit}
|
||||
title="Delete member (not implemented)"
|
||||
onClick={() => {
|
||||
if (!canEdit) return;
|
||||
void removeMember(m);
|
||||
handleDeleteMember();
|
||||
}}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
@@ -647,6 +708,120 @@ export default function StaffPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{enableTarget && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/55">
|
||||
<div
|
||||
className="surface-card w-full max-w-md p-5 space-y-4 shadow-xl"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="enable-staff-title"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<h2 id="enable-staff-title" className="text-lg font-semibold text-text-primary pr-2">
|
||||
Enable team member
|
||||
</h2>
|
||||
<DialogCloseButton
|
||||
onClick={() => {
|
||||
if (enablingMembershipId) return;
|
||||
setEnableTarget(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Enable <span className="font-medium text-text-primary">{enableTarget.name}</span> (
|
||||
{enableTarget.email})?
|
||||
</p>
|
||||
<ul className="text-sm text-text-secondary space-y-2 list-disc pl-5">
|
||||
<li>They can sign in to this organization again with their existing account.</li>
|
||||
<li>No new invitation is sent and no data was removed while they were disabled.</li>
|
||||
<li>
|
||||
Enabling uses <span className="text-text-primary font-medium">one seat</span> on your
|
||||
plan.
|
||||
</li>
|
||||
</ul>
|
||||
{!hasAvailableSeat && (
|
||||
<p className="text-sm text-amber-600 dark:text-amber-400">
|
||||
No seats are available. Disable another member or upgrade your plan before enabling
|
||||
this person.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex justify-end gap-2 pt-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={Boolean(enablingMembershipId)}
|
||||
onClick={() => setEnableTarget(null)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
isLoading={enablingMembershipId === enableTarget.id}
|
||||
disabled={Boolean(enablingMembershipId) || !hasAvailableSeat}
|
||||
onClick={() => void confirmEnableMember()}
|
||||
>
|
||||
Enable member
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{disableTarget && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/55">
|
||||
<div
|
||||
className="surface-card w-full max-w-md p-5 space-y-4 shadow-xl"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="disable-staff-title"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<h2 id="disable-staff-title" className="text-lg font-semibold text-text-primary pr-2">
|
||||
Disable team member
|
||||
</h2>
|
||||
<DialogCloseButton
|
||||
onClick={() => {
|
||||
if (disablingMembershipId) return;
|
||||
setDisableTarget(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Disable <span className="font-medium text-text-primary">{disableTarget.name}</span> (
|
||||
{disableTarget.email})?
|
||||
</p>
|
||||
<ul className="text-sm text-text-secondary space-y-2 list-disc pl-5">
|
||||
<li>They will not be able to sign in to this organization.</li>
|
||||
<li>No data will be removed.</li>
|
||||
<li>
|
||||
Disabling frees <span className="text-text-primary font-medium">one seat</span> on your
|
||||
plan so you can invite someone else.
|
||||
</li>
|
||||
</ul>
|
||||
<div className="flex justify-end gap-2 pt-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={Boolean(disablingMembershipId)}
|
||||
onClick={() => setDisableTarget(null)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="danger"
|
||||
isLoading={disablingMembershipId === disableTarget.id}
|
||||
disabled={Boolean(disablingMembershipId)}
|
||||
onClick={() => void confirmDisableMember()}
|
||||
>
|
||||
Disable member
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editing && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
|
||||
<div
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { Card } from '@/components/ui/common/Card';
|
||||
import { Card } from '@/components/ui/shared/Card';
|
||||
|
||||
export default function TodayPage() {
|
||||
const { currentOrganization } = useAuth();
|
||||
@@ -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 && (
|
||||
|
||||
@@ -4,8 +4,8 @@ import { useEffect, useMemo, useState } from 'react';
|
||||
import { Suspense } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Input } from '@/components/ui/common/Input';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
import { staffApi } from '@/lib/api/staff';
|
||||
|
||||
function AcceptInviteContent() {
|
||||
|
||||
@@ -8,8 +8,8 @@ import type { OrganizationDetailsFormValues } from '@/components/ui/auth/Organiz
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { Lock, Mail, User } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Input } from '@/components/ui/common/Input';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
import { OrganizationDetailsFields } from '@/components/ui/auth/OrganizationDetailsFields';
|
||||
import { RegistrationProgressSteps } from '@/components/ui/auth/RegistrationProgressSteps';
|
||||
import { organizationApi } from '@/lib/api/organization';
|
||||
|
||||
@@ -116,8 +116,8 @@ import Link from 'next/link';
|
||||
import { Mail, Lock } from 'lucide-react';
|
||||
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Input } from '@/components/ui/common/Input';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().email('Please enter a valid email address'),
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { ThemeToggle } from '@/components/ui/common/ThemeToggle';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { ThemeToggle } from '@/components/ui/shared/ThemeToggle';
|
||||
import { Building2, Beaker, Calendar, Shield, Clock, Users } from 'lucide-react';
|
||||
|
||||
export default function HomePage() {
|
||||
|
||||
@@ -9,8 +9,8 @@ import { Mail, Lock, User } from 'lucide-react';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { OrganizationDetailsFields } from '@/components/ui/auth/OrganizationDetailsFields';
|
||||
import { RegistrationProgressSteps } from '@/components/ui/auth/RegistrationProgressSteps';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Input } from '@/components/ui/common/Input';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
const registerSchema = z.object({
|
||||
name: z.string().min(2, 'Name must be at least 2 characters'),
|
||||
email: z.string().email('Please enter a valid email address'),
|
||||
|
||||
173
frontend/src/components/appointments/appointmentOverlapLayout.ts
Normal file
173
frontend/src/components/appointments/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}%`,
|
||||
};
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
16
frontend/src/components/shared/organizationTypeIcon.ts
Normal file
16
frontend/src/components/shared/organizationTypeIcon.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Building2, Beaker, type LucideIcon } from 'lucide-react';
|
||||
import type { Organization } from '@/types/organization';
|
||||
|
||||
/** Clinic → Building2, Lab → Beaker (switch-organization cards). */
|
||||
export function organizationTypeIcon(type: Organization['type']): LucideIcon {
|
||||
return type === 'CLINIC' ? Building2 : Beaker;
|
||||
}
|
||||
|
||||
/** Organizations tab lists counterpart orgs (labs for clinics, clinics for labs). */
|
||||
export function counterpartOrganizationType(
|
||||
currentType: Organization['type'] | undefined,
|
||||
): Organization['type'] {
|
||||
if (currentType === 'CLINIC') return 'LAB';
|
||||
if (currentType === 'LAB') return 'CLINIC';
|
||||
return 'CLINIC';
|
||||
}
|
||||
@@ -16,6 +16,11 @@ export function hasPermission(org: Organization | null, permission: string): boo
|
||||
return Boolean(org.permissions?.includes(permission));
|
||||
}
|
||||
|
||||
/** True when the user is owner of the currently selected organization. */
|
||||
export function canCreateOrganizationFromCurrentOrg(org: Organization | null): boolean {
|
||||
return Boolean(org?.isOwner);
|
||||
}
|
||||
|
||||
/** Sidebar / route guard: READ access to a tab */
|
||||
export function canViewTab(org: Organization | null, readPermission: string): boolean {
|
||||
return hasPermission(org, readPermission);
|
||||
@@ -1,4 +1,4 @@
|
||||
import { isSameLocalCalendarDay } from '@/lib/appointmentTime';
|
||||
import { isSameLocalCalendarDay } from '@/components/appointments/appointmentTime';
|
||||
import type { TreatmentAppointment } from '@/types/treatment';
|
||||
|
||||
/**
|
||||
@@ -1,9 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { DialogCloseButton } from '@/components/ui/common/DialogCloseButton';
|
||||
import { Dropdown } from '@/components/ui/common/Dropdown';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton';
|
||||
import { Dropdown } from '@/components/ui/shared/Dropdown';
|
||||
import type { AppointmentPurpose, AppointmentRecord } from '@/types/appointment';
|
||||
import { APPOINTMENT_PURPOSE_LABEL } from '@/components/ui/appointments/appointmentPurposeStyles';
|
||||
import type { Patient } from '@/types/patient';
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
compareLocalDayStart,
|
||||
formatTimeForInput,
|
||||
isSameLocalCalendarDay,
|
||||
} from '@/lib/appointmentTime';
|
||||
} from '@/components/appointments/appointmentTime';
|
||||
|
||||
interface AppointmentBookingModalProps {
|
||||
open: boolean;
|
||||
@@ -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/shared/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 { formatHourLabel } from '@/components/appointments/appointmentTime';
|
||||
import {
|
||||
purposeDeleteIconClass,
|
||||
purposeStyle,
|
||||
} from '@/components/ui/appointments/appointmentPurposeStyles';
|
||||
computeAppointmentLaneLayouts,
|
||||
findOverlapCluster,
|
||||
lanePositionStyles,
|
||||
} from '@/components/appointments/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)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { Search } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Input } from '@/components/ui/common/Input';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
import type { Patient } from '@/types/patient';
|
||||
|
||||
interface AppointmentsPatientSearchProps {
|
||||
@@ -49,7 +49,7 @@ export function AppointmentsPatientSearch({
|
||||
onClick={onAddPatient}
|
||||
title={!canAddPatient ? 'You do not have permission to add patients.' : undefined}
|
||||
>
|
||||
+ Add New Patient
|
||||
New Patient
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { Building2, Mail } from 'lucide-react';
|
||||
import type { FieldErrors, UseFormRegister, UseFormSetValue } from 'react-hook-form';
|
||||
import { Input } from '@/components/ui/common/Input';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
|
||||
export type OrganizationDetailsFormValues = {
|
||||
organizationName: string;
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { addCalendarDays } from '@/lib/appointmentTime';
|
||||
|
||||
interface ScheduleDayPickerProps {
|
||||
value: Date;
|
||||
onChange: (day: Date) => void;
|
||||
/** Optional lower bound; picker navigation is unrestricted for history browsing. */
|
||||
minDate?: Date;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export function ScheduleDayPicker({ value, onChange, label = 'Schedule date' }: ScheduleDayPickerProps) {
|
||||
const labelText = value.toLocaleDateString(undefined, {
|
||||
weekday: 'short',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="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"
|
||||
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))}
|
||||
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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { BadgeVariant } from '@/components/ui/common/Badge';
|
||||
|
||||
interface ToastProps {
|
||||
children: ReactNode;
|
||||
variant?: BadgeVariant;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const variantStyles: Record<BadgeVariant, string> = {
|
||||
success: 'bg-badge-success-bg text-badge-success-fg border-badge-success-border',
|
||||
warning: 'bg-badge-warning-bg text-badge-warning-fg border-badge-warning-border',
|
||||
danger: 'bg-badge-danger-bg text-badge-danger-fg border-badge-danger-border',
|
||||
default: 'bg-badge-default-bg text-badge-default-fg border-badge-default-border',
|
||||
};
|
||||
|
||||
export function Toast({ children, variant = 'default', className = '' }: ToastProps) {
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
className={`w-full rounded-[var(--radius-md)] border px-4 py-3 text-sm shadow-lg ${variantStyles[variant]} ${className}`}
|
||||
>
|
||||
{children}
|
||||
</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 { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton';
|
||||
import { ToastStack, type ToastMessages } from '@/components/ui/shared/Toast';
|
||||
import type { OrganizationInvitationHistoryItemDto } from '@/lib/api/organization';
|
||||
import { canShareOrganizationInviteLink } from '@/components/invitations/organizationInviteLinks';
|
||||
import { Badge, organizationLinkStatusVariant } from '@/components/ui/common/Badge';
|
||||
import { Table } from '@/components/ui/common/Table';
|
||||
import { Badge, organizationConnectionStatusVariant } from '@/components/ui/shared/Badge';
|
||||
import { Table } from '@/components/ui/shared/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>
|
||||
))}
|
||||
|
||||
@@ -1,13 +1,26 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { canCreateOrganizationFromCurrentOrg } from '@/components/shared/permissions';
|
||||
import { Building2, Beaker, Mail } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/common/Input';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
|
||||
export function OrganizationSelectorContent() {
|
||||
const { organizations, selectOrganization, createOrganization, isLoading, error, clearError } = useAuth();
|
||||
const {
|
||||
organizations,
|
||||
currentOrganization,
|
||||
selectOrganization,
|
||||
createOrganization,
|
||||
isLoading,
|
||||
error,
|
||||
clearError,
|
||||
} = useAuth();
|
||||
const canCreateOrganization = useMemo(
|
||||
() => canCreateOrganizationFromCurrentOrg(currentOrganization),
|
||||
[currentOrganization],
|
||||
);
|
||||
const [isCreateOpen, setIsCreateOpen] = useState(false);
|
||||
const [organizationName, setOrganizationName] = useState('');
|
||||
const [organizationEmail, setOrganizationEmail] = useState('');
|
||||
@@ -44,22 +57,26 @@ export function OrganizationSelectorContent() {
|
||||
<div>
|
||||
<h1 className="text-3xl font-semibold text-text-primary">Organizations</h1>
|
||||
<p className="text-text-secondary mt-2">
|
||||
Select an organization to continue, or create a new one.
|
||||
{canCreateOrganization
|
||||
? 'Select an organization to continue, or create a new one.'
|
||||
: 'Select an organization to continue.'}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant={isCreateOpen ? 'outline' : 'primary'}
|
||||
onClick={() => {
|
||||
clearError();
|
||||
setIsCreateOpen((prev) => !prev);
|
||||
}}
|
||||
>
|
||||
{isCreateOpen ? 'Cancel' : 'Create Organization'}
|
||||
</Button>
|
||||
{canCreateOrganization && (
|
||||
<Button
|
||||
type="button"
|
||||
variant={isCreateOpen ? 'outline' : 'primary'}
|
||||
onClick={() => {
|
||||
clearError();
|
||||
setIsCreateOpen((prev) => !prev);
|
||||
}}
|
||||
>
|
||||
{isCreateOpen ? 'Cancel' : 'Create Organization'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isCreateOpen && (
|
||||
{canCreateOrganization && isCreateOpen && (
|
||||
<div className="surface-card p-6 space-y-4">
|
||||
<Input
|
||||
label="Organization name"
|
||||
@@ -126,7 +143,11 @@ export function OrganizationSelectorContent() {
|
||||
|
||||
{!organizations.length ? (
|
||||
<div className="surface-card p-8 text-center">
|
||||
<p className="text-text-secondary">No organizations found. Create your first one to continue.</p>
|
||||
<p className="text-text-secondary">
|
||||
{canCreateOrganization
|
||||
? 'No organizations found. Create your first one to continue.'
|
||||
: 'No organizations found. Ask an organization owner to invite you.'}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4">
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Input } from '@/components/ui/common/Input';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
import { CreatePatientInput } from '@/types/patient';
|
||||
|
||||
interface CreatePatientModalProps {
|
||||
@@ -11,22 +12,27 @@ interface CreatePatientModalProps {
|
||||
onSubmit: () => void;
|
||||
onClose: () => void;
|
||||
loading?: boolean;
|
||||
/** Inline panel on Patients page; centered dialog on Appointments. */
|
||||
variant?: 'inline' | 'dialog';
|
||||
}
|
||||
|
||||
export function CreatePatientModal({
|
||||
isOpen,
|
||||
function CreatePatientFormFields({
|
||||
formData,
|
||||
onChange,
|
||||
onSubmit,
|
||||
onClose,
|
||||
loading = false,
|
||||
}: CreatePatientModalProps) {
|
||||
if (!isOpen) {
|
||||
return null;
|
||||
}
|
||||
|
||||
loading,
|
||||
showCancel,
|
||||
}: {
|
||||
formData: CreatePatientInput;
|
||||
onChange: (patch: Partial<CreatePatientInput>) => void;
|
||||
onSubmit: () => void;
|
||||
onClose: () => void;
|
||||
loading: boolean;
|
||||
showCancel: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className="surface-card p-4 space-y-3">
|
||||
<>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<Input
|
||||
label="First name"
|
||||
@@ -60,10 +66,80 @@ export function CreatePatientModal({
|
||||
>
|
||||
Save Patient
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
{showCancel && (
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function CreatePatientModal({
|
||||
isOpen,
|
||||
formData,
|
||||
onChange,
|
||||
onSubmit,
|
||||
onClose,
|
||||
loading = false,
|
||||
variant = 'inline',
|
||||
}: CreatePatientModalProps) {
|
||||
if (!isOpen) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (variant === 'dialog') {
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/55"
|
||||
role="presentation"
|
||||
onMouseDown={(e) => {
|
||||
if (e.target === e.currentTarget) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="surface-card w-full max-w-[min(56rem,calc(100vw-17rem))] p-5 space-y-4 shadow-xl"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="create-patient-dialog-title"
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<h2
|
||||
id="create-patient-dialog-title"
|
||||
className="text-lg font-semibold text-text-primary pr-2"
|
||||
>
|
||||
New patient
|
||||
</h2>
|
||||
<DialogCloseButton onClick={onClose} />
|
||||
</div>
|
||||
|
||||
<CreatePatientFormFields
|
||||
formData={formData}
|
||||
onChange={onChange}
|
||||
onSubmit={onSubmit}
|
||||
onClose={onClose}
|
||||
loading={loading}
|
||||
showCancel={false}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="surface-card p-4 space-y-3">
|
||||
<CreatePatientFormFields
|
||||
formData={formData}
|
||||
onChange={onChange}
|
||||
onSubmit={onSubmit}
|
||||
onClose={onClose}
|
||||
loading={loading}
|
||||
showCancel
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { Search } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/common/Input';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
import { Patient } from '@/types/patient';
|
||||
|
||||
interface PatientSearchSelectProps {
|
||||
|
||||
@@ -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,7 +1,8 @@
|
||||
// src/components/ui/OrganizationCard.tsx
|
||||
import React from 'react';
|
||||
import { Building2, Beaker, ChevronRight } from 'lucide-react';
|
||||
import { ChevronRight } from 'lucide-react';
|
||||
import type { Organization } from '@/types/organization';
|
||||
import { organizationTypeIcon } from '@/components/shared/organizationTypeIcon';
|
||||
|
||||
interface OrganizationCardProps {
|
||||
organization: Organization;
|
||||
@@ -12,7 +13,7 @@ export const OrganizationCard: React.FC<OrganizationCardProps> = ({
|
||||
organization,
|
||||
onSelect,
|
||||
}) => {
|
||||
const Icon = organization.type === 'CLINIC' ? Building2 : Beaker;
|
||||
const Icon = organizationTypeIcon(organization.type);
|
||||
const typeText = organization.type === 'CLINIC' ? 'Dental Clinic' : 'Dental Lab';
|
||||
|
||||
return (
|
||||
251
frontend/src/components/ui/shared/ScheduleDayPicker.tsx
Normal file
251
frontend/src/components/ui/shared/ScheduleDayPicker.tsx
Normal file
@@ -0,0 +1,251 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useId, useRef, useState } from 'react';
|
||||
import { ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { addCalendarDays, startOfLocalDay } from '@/components/appointments/appointmentTime';
|
||||
|
||||
interface ScheduleDayPickerProps {
|
||||
value: Date;
|
||||
onChange: (day: Date) => void;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
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 yearRange(anchor: Date): number[] {
|
||||
const anchorYear = anchor.getFullYear();
|
||||
const startYear = anchorYear - 10;
|
||||
const endYear = anchorYear + 2;
|
||||
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
|
||||
`;
|
||||
|
||||
/**
|
||||
* Calendar day navigator (arrows + year/month/day panel).
|
||||
* Does not restrict past dates — parent pages enforce read-only vs editable for schedule grids/forms.
|
||||
*/
|
||||
export function ScheduleDayPicker({ value, onChange, label = 'Schedule date' }: ScheduleDayPickerProps) {
|
||||
const panelId = useId();
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const [panelOpen, setPanelOpen] = useState(false);
|
||||
|
||||
const normalizedValue = startOfLocalDay(value);
|
||||
|
||||
const labelText = normalizedValue.toLocaleDateString(undefined, {
|
||||
weekday: 'short',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
});
|
||||
|
||||
const years = yearRange(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) {
|
||||
const maxDay = daysInMonth(year, month);
|
||||
onChange(buildLocalDay(year, month, Math.min(Math.max(1, day), maxDay)));
|
||||
if (closePanel) {
|
||||
setPanelOpen(false);
|
||||
}
|
||||
}
|
||||
|
||||
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 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(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="Previous day"
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4 icon-flat" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
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) => (
|
||||
<option key={name} value={index}>
|
||||
{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) => (
|
||||
<option key={day} value={day}>
|
||||
{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>
|
||||
);
|
||||
}
|
||||
@@ -13,10 +13,14 @@ import {
|
||||
CreditCard,
|
||||
} from 'lucide-react';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { canAccessAppointmentsSection, canViewTab } from '@/shared/permissions';
|
||||
import { canAccessAppointmentsSection, canViewTab } from '@/components/shared/permissions';
|
||||
import {
|
||||
counterpartOrganizationType,
|
||||
organizationTypeIcon,
|
||||
} from '@/components/shared/organizationTypeIcon';
|
||||
|
||||
const menu = [
|
||||
{ name: 'Today', path: '/today', icon: LayoutDashboard, read: 'TAB_TODAY_READ' as const },
|
||||
{ name: 'Dashboard', path: '/today', icon: LayoutDashboard, read: 'TAB_TODAY_READ' as const },
|
||||
{ name: 'Staff', path: '/staff', icon: UserCog, read: 'TAB_STAFF_READ' as const },
|
||||
{ name: 'Patients', path: '/patients', icon: Users, read: 'TAB_PATIENTS_READ' as const },
|
||||
{ name: 'Appointment', path: '/appointments', icon: Calendar, read: 'TAB_APPOINTMENTS_READ' as const },
|
||||
@@ -29,6 +33,9 @@ function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
const { currentOrganization } = useAuth();
|
||||
const counterpartLabel = currentOrganization?.type === 'LAB' ? 'Clinics' : 'Labs';
|
||||
const organizationsTabIcon = organizationTypeIcon(
|
||||
counterpartOrganizationType(currentOrganization?.type),
|
||||
);
|
||||
|
||||
const visibleMenu = useMemo(
|
||||
() => {
|
||||
@@ -38,7 +45,7 @@ function Sidebar() {
|
||||
{
|
||||
name: counterpartLabel,
|
||||
path: '/organizations',
|
||||
icon: FlaskConical,
|
||||
icon: organizationsTabIcon,
|
||||
read: 'TAB_ORGANIZATIONS_READ' as const,
|
||||
},
|
||||
menu[2],
|
||||
@@ -54,7 +61,7 @@ function Sidebar() {
|
||||
return canViewTab(currentOrganization, item.read);
|
||||
});
|
||||
},
|
||||
[counterpartLabel, currentOrganization],
|
||||
[counterpartLabel, organizationsTabIcon, currentOrganization],
|
||||
);
|
||||
|
||||
return (
|
||||
93
frontend/src/components/ui/shared/Toast.tsx
Normal file
93
frontend/src/components/ui/shared/Toast.tsx
Normal file
@@ -0,0 +1,93 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { BadgeVariant } from '@/components/ui/shared/Badge';
|
||||
|
||||
interface ToastProps {
|
||||
children: ReactNode;
|
||||
variant?: BadgeVariant;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const variantStyles: Record<BadgeVariant, string> = {
|
||||
success: 'bg-badge-success-bg text-badge-success-fg border-badge-success-border',
|
||||
warning: 'bg-badge-warning-bg text-badge-warning-fg border-badge-warning-border',
|
||||
danger: 'bg-badge-danger-bg text-badge-danger-fg border-badge-danger-border',
|
||||
default: 'bg-badge-default-bg text-badge-default-fg border-badge-default-border',
|
||||
};
|
||||
|
||||
export function Toast({ children, variant = 'default', className = '' }: ToastProps) {
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
className={`w-full rounded-[var(--radius-md)] border px-4 py-3 text-sm shadow-lg ${variantStyles[variant]} ${className}`}
|
||||
>
|
||||
{children}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
import { CalendarDays } from 'lucide-react';
|
||||
import { purposeStyle } from '@/components/ui/appointments/appointmentPurposeStyles';
|
||||
import { Card } from '@/components/ui/common/Card';
|
||||
import { ScheduleDayPicker } from '@/components/ui/common/ScheduleDayPicker';
|
||||
import { startOfLocalDay } from '@/lib/appointmentTime';
|
||||
import { Card } from '@/components/ui/shared/Card';
|
||||
import { ScheduleDayPicker } from '@/components/ui/shared/ScheduleDayPicker';
|
||||
import { startOfLocalDay } from '@/components/appointments/appointmentTime';
|
||||
import type { TreatmentAppointment } from '@/types/treatment';
|
||||
|
||||
interface AppointmentsStripProps {
|
||||
@@ -12,8 +12,6 @@ interface AppointmentsStripProps {
|
||||
onToggleStripHidden: () => void;
|
||||
selectedDay: Date;
|
||||
onSelectDay: (day: Date) => void;
|
||||
/** Same lower bound as Appointments schedule (cannot pick days before this). */
|
||||
minScheduleDate: Date;
|
||||
appointments: TreatmentAppointment[];
|
||||
selectedAppointmentId: string | null;
|
||||
onSelectAppointment: (id: string) => void;
|
||||
@@ -25,7 +23,6 @@ export function AppointmentsStrip({
|
||||
onToggleStripHidden,
|
||||
selectedDay,
|
||||
onSelectDay,
|
||||
minScheduleDate,
|
||||
appointments,
|
||||
selectedAppointmentId,
|
||||
onSelectAppointment,
|
||||
@@ -65,7 +62,6 @@ export function AppointmentsStrip({
|
||||
<div className="flex flex-col sm:flex-row sm:items-end gap-4 sm:justify-between">
|
||||
<ScheduleDayPicker
|
||||
value={selectedDay}
|
||||
minDate={minScheduleDate}
|
||||
onChange={(d) => onSelectDay(startOfLocalDay(d))}
|
||||
/>
|
||||
{loading && (
|
||||
|
||||
@@ -4,12 +4,12 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { AppointmentsStrip } from '@/components/ui/treatment/AppointmentsStrip';
|
||||
import { FdiToothChart } from '@/components/ui/treatment/FdiToothChart';
|
||||
import { PastTreatmentsPanel } from '@/components/ui/treatment/PastTreatmentsPanel';
|
||||
import { Checkbox } from '@/components/ui/common/Checkbox';
|
||||
import { Button } from '@/components/ui/common/Button';
|
||||
import { Dropdown } from '@/components/ui/common/Dropdown';
|
||||
import { SearchBar } from '@/components/ui/common/SearchBar';
|
||||
import { Toast } from '@/components/ui/common/Toast';
|
||||
import { isSameLocalCalendarDay, startOfLocalDay } from '@/lib/appointmentTime';
|
||||
import { Checkbox } from '@/components/ui/shared/Checkbox';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { Dropdown } from '@/components/ui/shared/Dropdown';
|
||||
import { SearchBar } from '@/components/ui/shared/SearchBar';
|
||||
import { Toast } from '@/components/ui/shared/Toast';
|
||||
import { compareLocalDayStart, isSameLocalCalendarDay, startOfLocalDay } from '@/components/appointments/appointmentTime';
|
||||
import {
|
||||
fetchLinkedOrganizations,
|
||||
fetchMyAppointmentsForDay,
|
||||
@@ -17,8 +17,8 @@ import {
|
||||
saveTreatmentDraft,
|
||||
sendTreatmentRecord,
|
||||
} from '@/lib/mocks/treatmentMockApi';
|
||||
import { pickAutoAppointment } from '@/lib/treatmentSelection';
|
||||
import { canEditTreatment } from '@/shared/permissions';
|
||||
import { pickAutoAppointment } from '@/components/shared/treatmentSelection';
|
||||
import { canEditTreatment } from '@/components/shared/permissions';
|
||||
import type { Organization } from '@/types/organization';
|
||||
import type {
|
||||
FdiToothId,
|
||||
@@ -54,7 +54,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
|
||||
const [stripHidden, setStripHidden] = useState(false);
|
||||
|
||||
const scheduleMinDate = useMemo(() => startOfLocalDay(new Date()), []);
|
||||
const todayStart = useMemo(() => startOfLocalDay(new Date()), []);
|
||||
|
||||
const [selectedDay, setSelectedDay] = useState(() => startOfLocalDay(new Date()));
|
||||
const [appointments, setAppointments] = useState<TreatmentAppointment[]>([]);
|
||||
@@ -87,6 +87,13 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
[appointments, selectedAppointmentId],
|
||||
);
|
||||
|
||||
const isViewingPastDay = useMemo(
|
||||
() => compareLocalDayStart(selectedDay, todayStart) < 0,
|
||||
[selectedDay, todayStart],
|
||||
);
|
||||
|
||||
const canEditTreatmentForDay = Boolean(selectedAppointment) && !isViewingPastDay;
|
||||
|
||||
const activeRecord = useMemo(
|
||||
() => records.find((r) => r.clientId === activeRecordId) ?? records[0],
|
||||
[records, activeRecordId],
|
||||
@@ -339,13 +346,19 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
onToggleStripHidden={() => setStripHidden((s) => !s)}
|
||||
selectedDay={selectedDay}
|
||||
onSelectDay={setSelectedDay}
|
||||
minScheduleDate={scheduleMinDate}
|
||||
appointments={appointments}
|
||||
selectedAppointmentId={selectedAppointmentId}
|
||||
onSelectAppointment={onPickAppointment}
|
||||
loading={apptsLoading}
|
||||
/>
|
||||
|
||||
{isViewingPastDay && (
|
||||
<p className="text-sm text-text-secondary rounded-[var(--radius-md)] border border-border/60 bg-background-secondary/50 px-3 py-2">
|
||||
Past days are view-only. You can review appointments and history, but treatment records
|
||||
cannot be added or changed.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 xl:grid-cols-[minmax(280px,380px)_minmax(0,1fr)] gap-6 items-start">
|
||||
<div className="space-y-4">
|
||||
{selectedAppointment ? (
|
||||
@@ -423,7 +436,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
<FdiToothChart
|
||||
selected={selectedTeethSet}
|
||||
onToggle={toggleTooth}
|
||||
disabled={!selectedAppointment}
|
||||
disabled={!canEditTreatmentForDay}
|
||||
/>
|
||||
|
||||
<div className="surface-card p-4 space-y-4">
|
||||
@@ -437,7 +450,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
disabled={!selectedAppointment}
|
||||
disabled={!canEditTreatmentForDay}
|
||||
onClick={() => {
|
||||
const nr = newRecord();
|
||||
fixActiveAfterRecordsChange([...records, nr]);
|
||||
@@ -486,7 +499,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
}}
|
||||
placeholder="Write clinical notes for this record…"
|
||||
rows={5}
|
||||
disabled={!selectedAppointment}
|
||||
disabled={!canEditTreatmentForDay}
|
||||
className="mt-1.5 w-full rounded-[var(--radius-md)] border border-border bg-background-secondary/90 text-text-primary text-sm px-3 py-2 placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/35 resize-y min-h-[120px]"
|
||||
/>
|
||||
</label>
|
||||
@@ -503,7 +516,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
),
|
||||
);
|
||||
}}
|
||||
disabled={!selectedAppointment}
|
||||
disabled={!canEditTreatmentForDay}
|
||||
className="capitalize"
|
||||
style={{ color: treatmentTypeTextColor }}
|
||||
>
|
||||
@@ -522,7 +535,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
id="treatment-record-attachments"
|
||||
type="file"
|
||||
multiple
|
||||
disabled={!selectedAppointment}
|
||||
disabled={!canEditTreatmentForDay}
|
||||
onChange={(e) => {
|
||||
addAttachments(e.target.files);
|
||||
e.target.value = '';
|
||||
@@ -533,7 +546,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
disabled={!selectedAppointment}
|
||||
disabled={!canEditTreatmentForDay}
|
||||
onClick={() => attachmentInputRef.current?.click()}
|
||||
aria-controls="treatment-record-attachments"
|
||||
>
|
||||
@@ -589,7 +602,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
<Checkbox
|
||||
key={o.id}
|
||||
checked={activeRecord.sendToOrganizationIds.includes(o.id)}
|
||||
disabled={!selectedAppointment || Boolean(activeRecord.sentAt)}
|
||||
disabled={!canEditTreatmentForDay || Boolean(activeRecord.sentAt)}
|
||||
onChange={(checked) => {
|
||||
setRecords((prev) =>
|
||||
prev.map((r) => {
|
||||
@@ -614,7 +627,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
disabled={!selectedAppointment || Boolean(activeRecord.sentAt) || sendBusyId === activeRecord.clientId}
|
||||
disabled={!canEditTreatmentForDay || Boolean(activeRecord.sentAt) || sendBusyId === activeRecord.clientId}
|
||||
isLoading={sendBusyId === activeRecord.clientId}
|
||||
onClick={() => void handleSendRecord(activeRecord)}
|
||||
>
|
||||
@@ -633,7 +646,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
disabled={!selectedAppointment || saveBusy}
|
||||
disabled={!canEditTreatmentForDay || saveBusy}
|
||||
isLoading={saveBusy}
|
||||
onClick={() => void handleSaveAll()}
|
||||
>
|
||||
|
||||
@@ -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;
|
||||
},
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ export interface StaffMemberDto {
|
||||
name: string;
|
||||
isOwner: boolean;
|
||||
isActive: boolean;
|
||||
invitationStatus: 'ACTIVE' | 'PENDING' | 'EXPIRED';
|
||||
invitationStatus: 'ACTIVE' | 'PENDING' | 'EXPIRED' | 'DISABLED';
|
||||
invitedAt: string | null;
|
||||
acceptedAt: string | null;
|
||||
permissions: string[] | null;
|
||||
@@ -100,6 +100,20 @@ export const staffApi = {
|
||||
return response.data;
|
||||
},
|
||||
|
||||
disableMember: async (
|
||||
membershipId: string,
|
||||
): Promise<{ success: boolean; message: string }> => {
|
||||
const response = await apiClient.patch(`/staff/members/${membershipId}/disable`);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
enableMember: async (
|
||||
membershipId: string,
|
||||
): Promise<{ success: boolean; message: string }> => {
|
||||
const response = await apiClient.patch(`/staff/members/${membershipId}/enable`);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
removeMember: async (
|
||||
membershipId: string,
|
||||
): Promise<{ success: boolean; message: string }> => {
|
||||
|
||||
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/shared/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,
|
||||
};
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
addCalendarDays,
|
||||
isSameLocalCalendarDay,
|
||||
startOfLocalDay,
|
||||
} from '@/lib/appointmentTime';
|
||||
} from '@/components/appointments/appointmentTime';
|
||||
import type {
|
||||
FdiToothId,
|
||||
LinkedOrganizationOption,
|
||||
|
||||
Reference in New Issue
Block a user