Compare commits

...

9 Commits

Author SHA1 Message Date
09b511a136 bugfix: org invitation flow updated so that the invited org follows the exact steps of free trial registration. 2026-05-17 02:03:18 +03:30
201be53ddd bugfix: some minor ui updates for invitation history dialog. 2026-05-17 01:39:49 +03:30
2d43254af2 bugfix: invitation link copy option disapearing fixed. route problem for unauthorizrd users opening invitation link fixed. 2026-05-17 00:02:13 +03:30
627219df58 bugfix: .env.example files updated. some minor changes in jwt strategy to avoid failing when .env files does not contain needed keys. 2026-05-16 22:40:42 +03:30
105175ff4d Merge pull request 'improvement/ui-ux-improvements' (#17) from improvement/ui-ux-improvements into master
All checks were successful
Registry — build, push, deploy / temp-success (push) Successful in 0s
Reviewed-on: http://178.131.50.201:3000/admin/dyolink/pulls/17
2026-05-08 14:30:13 +03:30
803564802c improvement: datepicker component now let user choose past dates too. 2026-05-08 14:25:44 +03:30
a0348e4079 improvement: toast component created and used every where in the app. 2026-05-08 14:07:21 +03:30
dcc4b10f00 improvement: badge & card components colour pallete updated so their text become more readable in light mode. 2026-05-08 13:56:33 +03:30
f314c116ec Merge pull request 'feature/treatment' (#16) from feature/treatment into master
All checks were successful
Registry — build, push, deploy / temp-success (push) Successful in 1s
Reviewed-on: http://178.131.50.201:3000/admin/dyolink/pulls/16
2026-05-08 12:45:23 +03:30
47 changed files with 1592 additions and 552 deletions

View File

@@ -1,23 +1,41 @@
# Database
DATABASE_URL=postgresql://dyolink_user:password@postgres:5432/dyolink_db
POSTGRES_HOST=postgres
#
# Local dev (Nest on your machine + Postgres via docker-compose.postgres.yml):
# Use host "localhost" — hostname "postgres" only works inside Docker networks.
DATABASE_URL=postgresql://dyolink_user:password@localhost:5432/dyolink_db
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=dyolink_user
POSTGRES_PASSWORD=CHANGE_ME_IN_PRODUCTION
POSTGRES_PASSWORD=password
POSTGRES_DB=dyolink_db
#
# If you run the API inside the same Compose stack as Postgres, use instead:
# DATABASE_URL=postgresql://dyolink_user:password@postgres:5432/dyolink_db
# POSTGRES_HOST=postgres
# JWT
# JWT (required for register/login)
JWT_SECRET=CHANGE_ME_TO_A_STRONG_SECRET_32_CHARS_MIN
JWT_EXPIRES_IN=7d
JWT_REFRESH_SECRET=CHANGE_ME_TO_ANOTHER_STRONG_SECRET
JWT_REFRESH_EXPIRES_IN=30d
# Application
PORT=3000
NODE_ENV=development
API_PREFIX=/api
CORS_ORIGIN=http://localhost:3000
# CORS and invite links — must match the URL where the Next.js app runs
FRONTEND_URL=http://localhost:3001
# OAuth (optional — uncomment when configured)
# GOOGLE_CLIENT_ID=your-google-client-id
# GOOGLE_CLIENT_SECRET=your-google-client-secret
# GOOGLE_CALLBACK_URL=http://localhost:3000/auth/google/callback
# FACEBOOK_CLIENT_ID=your-facebook-app-id
# FACEBOOK_CLIENT_SECRET=your-facebook-app-secret
# FACEBOOK_CALLBACK_URL=http://localhost:3000/auth/facebook/callback
# Email (configure for production)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your_email@gmail.com
SMTP_PASSWORD=your_app_password
SMTP_PASSWORD=your_app_password

View File

@@ -3,7 +3,7 @@
## Prerequisites
- **Node.js 20+** and **npm**
- **PostgreSQL** reachable from your machine (local or remote)
- **PostgreSQL** reachable from your machine — either installed locally **or** run via Docker (see below)
## First-time setup
@@ -28,9 +28,23 @@
- `JWT_SECRET` — strong secret for signing tokens
Do not commit `.env`.
4. **Database URL for local dev**
4. **Database for local dev**
Point `DATABASE_URL` at a database you created in Postgres (create an empty DB first if needed).
**Option A — Postgres in Docker (no local install, e.g. Mac)**
From `backend/`, with `.env` present (copy from `.env.example` first):
- Ensure `DATABASE_URL` uses **`localhost`** as the host (not `postgres`). Match user, password, and DB name to `POSTGRES_USER`, `POSTGRES_PASSWORD`, and `POSTGRES_DB` in the same file.
```bash
docker compose -f docker-compose.postgres.yml up -d
```
Wait until Postgres is healthy (`docker compose -f docker-compose.postgres.yml ps`). The container creates the database on first start.
To stop Postgres (data is kept in the named volume): `docker compose -f docker-compose.postgres.yml down`
**Option B — Postgres installed on the machine**
Create an empty database, then point `DATABASE_URL` at it.
5. **Generate Prisma Client**
@@ -46,12 +60,43 @@
This runs `prisma migrate dev`. Use it during development when the schema changes.
7. **Seed** (optional — sample data / bootstrap)
7. **Seed** (optional — reference data only)
```bash
npm run prisma:seed
```
This **does not** wipe your database. It only upserts lookup data: organization types (`CLINIC`, `LAB`), subscription plans, and tab permissions. Existing users, organizations, memberships, patients, appointments, and links are **left unchanged**.
To start from an empty database with fresh tables and reference data, see [Reset database (clean slate)](#reset-database-clean-slate) below.
## Reset database (clean slate)
Use this when you want to **delete all application data** (users, organizations, patients, sessions, etc.) and rebuild the schema from migrations, then run the seed.
From `backend/`:
```bash
npx prisma migrate reset
```
Prisma will prompt for confirmation, drop the database, re-apply all migrations, and run `prisma/seed.ts` automatically.
**What gets removed:** everything in the database, including organizations and all related rows.
**What the seed adds back:** only reference data (types, plans, permissions) — not demo users or organizations. Register again or use your own test data after a reset.
**Docker Postgres dev:** if you also want to wipe the Docker volume (not only tables), stop the container and remove the volume:
```bash
docker compose -f docker-compose.postgres.yml down -v
docker compose -f docker-compose.postgres.yml up -d
npm run prisma:migrate
npm run prisma:seed
```
Do **not** run `migrate reset` against production or shared staging databases.
## Run (development)
```bash
@@ -60,7 +105,7 @@ npm run start:dev
API listens on **`http://localhost:3000`** by default (`PORT` in `.env`).
If the frontend runs on another origin (e.g. `http://localhost:3001`), set `CORS_ORIGIN` in `.env` to that URL.
If the frontend runs on another origin (e.g. `http://localhost:3001`), set `FRONTEND_URL` in `.env` to that URL (CORS and invite links use it).
## After pulling latest `main`
@@ -71,7 +116,7 @@ npm run prisma:generate
npm run prisma:migrate
```
If teammates added migrations, step 4 applies them. Resolve migration conflicts locally before pushing.
If teammates added migrations, the migrate step above applies them. Resolve migration conflicts locally before pushing.
## Useful commands
@@ -80,9 +125,16 @@ If teammates added migrations, step 4 applies them. Resolve migration conflicts
| `npm run prisma:generate` | Regenerate client after `schema.prisma` changes |
| `npm run prisma:migrate` | Dev migrations (`migrate dev`) |
| `npm run prisma:deploy` | Production-style apply (`migrate deploy`) — e.g. CI/containers |
| `npm run prisma:seed` | Upsert reference data only (does not clear existing rows) |
| `npx prisma migrate reset` | Drop DB, re-migrate, run seed — **dev clean slate** |
| `npm run build` | Compile Nest app |
| `npm run start:prod` | Run compiled app (`node dist/main`) |
## Docker
Image build is defined in **`Dockerfile`** at this folder. For full-stack deployment and CI, see the **repository root `README.md`**.
| File | Purpose |
|------|--------|
| **`Dockerfile`** | Production API image |
| **`docker-compose.postgres.yml`** | Local dev Postgres only (port mapped to host) |
For full-stack deployment and CI, see the **repository root `README.md`**.

View File

@@ -0,0 +1,29 @@
# Local development Postgres only.
# Run from backend/: docker compose -f docker-compose.postgres.yml up -d
#
# Nest runs on your Mac/PC; use DATABASE_URL with host "localhost" (not "postgres").
# Variables POSTGRES_* and POSTGRES_PORT are read from .env (see .env.example).
services:
postgres:
image: postgres:15-alpine
container_name: dyolink-postgres-dev
restart: unless-stopped
ports:
- "${POSTGRES_PORT:-5432}:5432"
environment:
POSTGRES_USER: ${POSTGRES_USER:-dyolink_user}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-password}
POSTGRES_DB: ${POSTGRES_DB:-dyolink_db}
volumes:
- dyolink_pgdata_dev:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
interval: 5s
timeout: 5s
retries: 10
start_period: 10s
volumes:
dyolink_pgdata_dev:
name: dyolink_postgres_data_dev

View File

@@ -1,4 +1,36 @@
// backend/src/config/configuration.ts
/** Matches values accepted by jsonwebtoken `expiresIn` (via ms), e.g. 7d, 15m, or plain seconds. */
const JWT_TIMESPAN_PATTERN =
/^\d+(\.\d+)?(ms|s|m|h|d|w|y)?$/i;
function assertJwtSecret(value: string, envKey: string): string {
const trimmed = value.trim();
if (!trimmed) {
throw new Error(`❌ Environment variable ${envKey} is required but not set`);
}
if (trimmed.length < 16) {
throw new Error(`${envKey} must be at least 16 characters`);
}
if (/CHANGE_ME/i.test(trimmed)) {
throw new Error(`${envKey} must be changed from the placeholder value`);
}
return trimmed;
}
function assertJwtTimespan(value: string, envKey: string): string {
const trimmed = value.trim();
if (!trimmed) {
throw new Error(`❌ Environment variable ${envKey} is required but not set`);
}
if (!/^\d+$/.test(trimmed) && !JWT_TIMESPAN_PATTERN.test(trimmed)) {
throw new Error(
`${envKey}="${value}" is invalid. Use a duration like 7d, 15m, 30d, or a number of seconds.`,
);
}
return trimmed;
}
export interface Config {
port: number;
database: {
@@ -7,6 +39,8 @@ export interface Config {
jwt: {
secret: string;
expiresIn: string;
refreshSecret: string;
refreshExpiresIn: string;
};
throttle: {
ttl: number;
@@ -24,9 +58,10 @@ export default (): Config => {
return value;
};
// Helper for optional env vars with defaults
// Helper for optional env vars with defaults (whitespace-only counts as unset)
const getEnvVarWithDefault = (key: string, defaultValue: string): string => {
return process.env[key] || defaultValue;
const value = process.env[key]?.trim();
return value ? value : defaultValue;
};
const getEnvVarAsNumber = (key: string, defaultValue: number): number => {
@@ -36,14 +71,30 @@ export default (): Config => {
return isNaN(parsed) ? defaultValue : parsed;
};
const jwtSecret = assertJwtSecret(getEnvVar('JWT_SECRET'), 'JWT_SECRET');
const jwtExpiresIn = assertJwtTimespan(
getEnvVarWithDefault('JWT_EXPIRES_IN', '7d'),
'JWT_EXPIRES_IN',
);
const jwtRefreshSecret = assertJwtSecret(
getEnvVarWithDefault('JWT_REFRESH_SECRET', jwtSecret),
'JWT_REFRESH_SECRET',
);
const jwtRefreshExpiresIn = assertJwtTimespan(
getEnvVarWithDefault('JWT_REFRESH_EXPIRES_IN', '30d'),
'JWT_REFRESH_EXPIRES_IN',
);
return {
port: getEnvVarAsNumber('PORT', 3000),
database: {
url: getEnvVar('DATABASE_URL'),
},
jwt: {
secret: getEnvVar('JWT_SECRET'),
expiresIn: getEnvVarWithDefault('JWT_EXPIRES_IN', '7d'),
secret: jwtSecret,
expiresIn: jwtExpiresIn,
refreshSecret: jwtRefreshSecret,
refreshExpiresIn: jwtRefreshExpiresIn,
},
throttle: {
ttl: getEnvVarAsNumber('THROTTLE_TTL', 60),

View File

@@ -7,6 +7,7 @@ import {
InternalServerErrorException
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import type { JwtSignOptions } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import * as bcrypt from 'bcrypt';
import { PrismaService } from '../../../prisma/prisma.service';
@@ -53,6 +54,20 @@ export class AuthService {
private configService: ConfigService,
) { }
private accessJwtSignOptions(): JwtSignOptions {
return {
secret: this.configService.get<string>('jwt.secret')!,
expiresIn: this.configService.get<string>('jwt.expiresIn')!,
} as JwtSignOptions;
}
private refreshJwtSignOptions(): JwtSignOptions {
return {
secret: this.configService.get<string>('jwt.refreshSecret')!,
expiresIn: this.configService.get<string>('jwt.refreshExpiresIn')!,
} as JwtSignOptions;
}
/**
* Validate user credentials (used by LocalStrategy)
* @param email - User's email
@@ -128,14 +143,8 @@ export class AuthService {
};
const [accessToken, refreshToken] = await Promise.all([
this.jwtService.signAsync(accessPayload, {
secret: this.configService.get('JWT_SECRET'),
expiresIn: this.configService.get('JWT_EXPIRES_IN'),
}),
this.jwtService.signAsync(refreshPayload, {
secret: this.configService.get('JWT_REFRESH_SECRET'),
expiresIn: this.configService.get('JWT_REFRESH_EXPIRES_IN'),
}),
this.jwtService.signAsync(accessPayload, this.accessJwtSignOptions()),
this.jwtService.signAsync(refreshPayload, this.refreshJwtSignOptions()),
]);
// Store session in database
@@ -398,7 +407,7 @@ export class AuthService {
try {
// Verify the refresh token
const payload = await this.jwtService.verifyAsync(refreshToken, {
secret: this.configService.get('jwt.refreshSecret'),
secret: this.configService.get<string>('jwt.refreshSecret'),
});
// Ensure this is a refresh token
@@ -446,10 +455,10 @@ export class AuthService {
type: 'access',
};
const newAccessToken = await this.jwtService.signAsync(newAccessPayload, {
secret: this.configService.get('jwt.secret'),
expiresIn: this.configService.get('jwt.expiresIn'),
});
const newAccessToken = await this.jwtService.signAsync(
newAccessPayload,
this.accessJwtSignOptions(),
);
// Update session with new access token
await this.prisma.session.update({
@@ -732,10 +741,7 @@ export class AuthService {
};
// 3. Generate new token
const accessToken = await this.jwtService.signAsync(payload, {
secret: this.configService.get('JWT_SECRET'),
expiresIn: this.configService.get('JWT_EXPIRES_IN'),
});
const accessToken = await this.jwtService.signAsync(payload, this.accessJwtSignOptions());
// 4. Format permissions
const permissions = this.getMembershipPermissions(membership);

View File

@@ -17,7 +17,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
return req?.cookies?.accessToken; // ✅ READ FROM COOKIE
},
ignoreExpiration: false,
secretOrKey: configService.get('JWT_SECRET'),
secretOrKey: configService.get<string>('jwt.secret'),
});
}

View File

@@ -1,4 +1,4 @@
import { IsString, MinLength } from 'class-validator';
import { IsEmail, IsEnum, IsString, MinLength } from 'class-validator';
export class AcceptOrganizationInviteDto {
@IsString()
@@ -9,6 +9,12 @@ export class AcceptOrganizationInviteDto {
@MinLength(1)
organizationName: string;
@IsEmail()
organizationEmail: string;
@IsEnum(['CLINIC', 'LAB'])
organizationType: 'CLINIC' | 'LAB';
@IsString()
@MinLength(1)
ownerName: string;

View File

@@ -288,8 +288,11 @@ export class OrganizationService {
if (!invitation) {
throw new NotFoundException('Invitation not found');
}
if (invitation.acceptedAt || invitation.revokedAt) {
throw new BadRequestException('Only pending invitations can provide a link');
if (invitation.acceptedAt) {
throw new BadRequestException('This invitation has already been accepted');
}
if (invitation.revokedAt) {
throw new BadRequestException('This invitation is no longer valid');
}
const plainToken = this.generateInviteToken();
@@ -421,12 +424,23 @@ export class OrganizationService {
async previewInvite(token: string) {
const invitation = await this.findValidInvitation(token);
let organizationEmail = '';
if (invitation.invitedOrganizationId) {
const invitedOrg = await this.prisma.organization.findUnique({
where: { id: invitation.invitedOrganizationId },
select: { email: true },
});
if (invitedOrg?.email && !invitedOrg.email.includes('@dyolink.local')) {
organizationEmail = invitedOrg.email;
}
}
return {
success: true,
data: {
ownerEmail: invitation.invitedOwnerEmail,
organizationName: invitation.invitedOrganizationName,
organizationType: invitation.invitedOrganizationType,
organizationEmail,
inviterOrganizationName: invitation.inviterOrganization.name,
expiresAt: invitation.expiresAt.toISOString(),
status: invitation.acceptedAt ? 'ACCEPTED' : 'PENDING',
@@ -440,6 +454,14 @@ export class OrganizationService {
throw new BadRequestException('This invitation has already been accepted');
}
if (dto.organizationType !== invitation.invitedOrganizationType) {
throw new BadRequestException(
`Organization type must be ${invitation.invitedOrganizationType} for this invitation`,
);
}
const organizationEmail = dto.organizationEmail.trim().toLowerCase();
const organization = await this.prisma.$transaction(async (tx) => {
const passwordHash = await bcrypt.hash(dto.password, 10);
const ownerEmail = invitation.invitedOwnerEmail;
@@ -467,8 +489,9 @@ export class OrganizationService {
where: { id: targetOrganizationId },
data: {
name: dto.organizationName.trim(),
email: ownerEmail,
email: organizationEmail,
owner: { connect: { id: owner.id } },
type: { connect: { name: dto.organizationType } },
plan: { connect: { name: 'trial' } },
},
});
@@ -476,9 +499,9 @@ export class OrganizationService {
const createdOrg = await tx.organization.create({
data: {
name: dto.organizationName.trim(),
email: ownerEmail,
email: organizationEmail,
owner: { connect: { id: owner.id } },
type: { connect: { name: invitation.invitedOrganizationType } },
type: { connect: { name: dto.organizationType } },
plan: { connect: { name: 'trial' } },
},
});

View File

@@ -55,6 +55,19 @@ export class StaffController {
return this.staffService.invite(req.user.id, organizationId, dto);
}
@Post('members/:membershipId/invitation-link')
@UseGuards(JwtAuthGuard)
@ApiOperation({
summary: 'Regenerate and return invite link for a pending staff member',
})
getInvitationLink(
@Req() req: { user: { id: string; organizationId?: string } },
@Param('membershipId') membershipId: string,
) {
const organizationId = this.staffService.getOrganizationIdFromUser(req.user);
return this.staffService.getInvitationLink(req.user.id, organizationId, membershipId);
}
@Patch('members/:membershipId')
@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Update staff member name and/or permissions' })

View File

@@ -224,6 +224,62 @@ export class StaffService {
};
}
async getInvitationLink(userId: string, organizationId: string, membershipId: string) {
const actor = await this.getActorMembership(userId, organizationId);
if (!actor || !this.canEditStaff(actor)) {
throw new ForbiddenException('You cannot invite or manage staff');
}
const membership = await this.prisma.membership.findFirst({
where: { id: membershipId, organizationId },
include: {
user: { select: { email: true } },
invitations: { orderBy: { createdAt: 'desc' }, take: 1 },
},
});
if (!membership) {
throw new NotFoundException('Member not found');
}
if (membership.isOwner) {
throw new BadRequestException('Owner does not use an invitation link');
}
if (membership.isActive) {
throw new BadRequestException('This member has already accepted their invitation');
}
const invitation = membership.invitations[0];
if (!invitation) {
throw new BadRequestException('No invitation found for this member');
}
if (invitation.acceptedAt) {
throw new BadRequestException('This invitation has already been accepted');
}
if (invitation.revokedAt) {
throw new BadRequestException('This invitation is no longer valid');
}
const plainToken = this.generateInviteToken();
const tokenHash = this.hashInviteToken(plainToken);
await this.prisma.staffInvitation.update({
where: { id: invitation.id },
data: {
tokenHash,
expiresAt: this.getInviteExpiryDate(),
},
});
return {
success: true,
data: {
membershipId: membership.id,
invitationId: invitation.id,
email: membership.user.email,
invitationUrl: this.buildInviteUrl(plainToken),
},
};
}
async previewInvite(token: string) {
const invitation = await this.findValidInvitation(token);
const org = invitation.membership.organization;
@@ -383,7 +439,8 @@ export class StaffService {
if (m.isOwner || m.isActive) return 'ACTIVE';
const invitation = m.invitations[0];
if (!invitation) return 'EXPIRED';
if (invitation.acceptedAt || invitation.revokedAt) return 'ACTIVE';
if (invitation.acceptedAt) return 'ACTIVE';
if (invitation.revokedAt) return 'EXPIRED';
return invitation.expiresAt.getTime() > Date.now() ? 'PENDING' : 'EXPIRED';
}

7
frontend/.env.example Normal file
View File

@@ -0,0 +1,7 @@
# Copy to .env.local for local development (Next.js loads .env.local automatically).
# Do not commit .env.local — only this template is tracked in git.
NEXT_PUBLIC_API_URL=http://localhost:3000/api
NEXT_PUBLIC_APP_NAME=DyoLink
# URL where users open the frontend (used for metadata, images, etc.)
NEXT_PUBLIC_APP_URL=http://localhost:3001

4
frontend/.gitignore vendored
View File

@@ -31,7 +31,9 @@ yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
.env
.env.*
!.env.example
# vercel
.vercel

View File

@@ -5,7 +5,7 @@
"scripts": {
"dev": "next dev -p 3001",
"build": "next build",
"start": "next start -p 3000",
"start": "next start -p 3001",
"lint": "next lint"
},
"dependencies": {

View File

@@ -14,9 +14,10 @@ import { AppointmentScheduleGrid } from '@/components/ui/appointments/Appointmen
import { AppointmentsPatientSearch } from '@/components/ui/appointments/AppointmentsPatientSearch';
import { AppointmentScheduleLegend } from '@/components/ui/appointments/AppointmentScheduleLegend';
import { ScheduleDayPicker } from '@/components/ui/common/ScheduleDayPicker';
import { Toast } from '@/components/ui/common/Toast';
import type { AppointmentPurpose } from '@/types/appointment';
import { formatApiErrorMessage } from '@/lib/formatApiError';
import { getLocalDayIsoRange, startOfLocalDay } from '@/lib/appointmentTime';
import { compareLocalDayStart, getLocalDayIsoRange, startOfLocalDay } from '@/lib/appointmentTime';
const EMPTY_PATIENT_FORM: CreatePatientInput = {
firstName: '',
@@ -47,6 +48,7 @@ export default function AppointmentsPage() {
const [bookingHour, setBookingHour] = useState(9);
const [bookingProviderId, setBookingProviderId] = useState<string | null>(null);
const [bookingProviderName, setBookingProviderName] = useState('');
const [editingAppointmentId, setEditingAppointmentId] = useState<string | null>(null);
const [savingAppointment, setSavingAppointment] = useState(false);
const [toastError, setToastError] = useState('');
@@ -57,6 +59,14 @@ export default function AppointmentsPage() {
const canEditPatients = hasPermission(currentOrganization, 'TAB_PATIENTS_EDIT');
const todayStart = useMemo(() => startOfLocalDay(new Date()), []);
const isViewingPastDay = useMemo(
() => compareLocalDayStart(scheduleDate, todayStart) < 0,
[scheduleDate, todayStart],
);
const activeEditingAppointment = useMemo(
() => appointments.find((a) => a.id === editingAppointmentId) ?? null,
[appointments, editingAppointmentId],
);
const scheduleLoadGen = useRef(0);
@@ -154,6 +164,12 @@ export default function AppointmentsPage() {
}
function handleSlotClick(hour: number, providerUserId: string, providerName: string) {
if (isViewingPastDay) {
setToastSuccess('');
setToastError('');
setToastInfo('Past appointments are view-only.');
return;
}
if (!selectedPatient) {
setToastSuccess('');
setToastError('');
@@ -163,6 +179,22 @@ export default function AppointmentsPage() {
setBookingHour(hour);
setBookingProviderId(providerUserId);
setBookingProviderName(providerName);
setEditingAppointmentId(null);
setBookingOpen(true);
}
function handleAppointmentClick(appointment: AppointmentRecord) {
if (isViewingPastDay) {
setToastSuccess('');
setToastError('');
setToastInfo('Past appointments are view-only.');
return;
}
const provider = providers.find((p) => p.userId === appointment.providerUserId);
setBookingHour(new Date(appointment.startAt).getHours());
setBookingProviderId(appointment.providerUserId);
setBookingProviderName(provider?.name ?? bookingProviderName);
setEditingAppointmentId(appointment.id);
setBookingOpen(true);
}
@@ -178,15 +210,22 @@ export default function AppointmentsPage() {
setToastSuccess('');
setToastInfo('');
try {
await appointmentsApi.create(payload);
if (activeEditingAppointment) {
await appointmentsApi.update(activeEditingAppointment.id, payload);
} else {
await appointmentsApi.create(payload);
}
setBookingOpen(false);
setToastSuccess('Appointment saved.');
setEditingAppointmentId(null);
setToastSuccess(activeEditingAppointment ? 'Appointment updated.' : 'Appointment saved.');
await loadSchedule();
} catch (err: unknown) {
const message =
err && typeof err === 'object' && 'message' in err
? String((err as { message: unknown }).message)
: 'Could not save appointment.';
: activeEditingAppointment
? 'Could not update appointment.'
: 'Could not save appointment.';
setToastError(message);
} finally {
setSavingAppointment(false);
@@ -280,20 +319,15 @@ export default function AppointmentsPage() {
)}
</div>
{scheduleError && (
<div className="rounded-[var(--radius-sm)] border border-red-500/50 bg-red-500/10 px-3 py-2 text-sm text-red-300">
{scheduleError}
</div>
)}
<AppointmentScheduleGrid
day={scheduleDate}
providers={providers}
appointments={appointments}
canBook={canManageAppointments}
canBook={canManageAppointments && !isViewingPastDay}
canDelete={canManageAppointments}
onDeleteAppointment={(id) => void handleDeleteAppointment(id)}
onSlotClick={(hour, uid, name) => handleSlotClick(hour, uid, name)}
onAppointmentClick={(apt) => handleAppointmentClick(apt)}
/>
</div>
</div>
@@ -305,7 +339,11 @@ export default function AppointmentsPage() {
providerUserId={bookingProviderId}
providerName={bookingProviderName}
initialHour={bookingHour}
onClose={() => setBookingOpen(false)}
editingAppointment={activeEditingAppointment}
onClose={() => {
setBookingOpen(false);
setEditingAppointmentId(null);
}}
onSubmit={handleSaveAppointment}
loading={savingAppointment}
/>
@@ -323,24 +361,13 @@ export default function AppointmentsPage() {
</div>
)}
{(toastError || toastSuccess || toastInfo) && (
<div className="fixed bottom-4 left-4 right-4 z-[70] flex justify-center pointer-events-none">
<div className="pointer-events-auto w-full max-w-lg space-y-2">
{toastError && (
<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">
{toastError}
</div>
)}
{toastInfo && (
<div className="rounded-[var(--radius-sm)] border border-amber-500/45 bg-amber-500/10 px-3 py-2 text-sm text-amber-100 shadow-lg">
{toastInfo}
</div>
)}
{toastSuccess && (
<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">
{toastSuccess}
</div>
)}
{(scheduleError || toastError || toastSuccess || toastInfo) && (
<div className="fixed bottom-4 left-0 right-0 z-[70] px-4 pointer-events-none">
<div className="pointer-events-auto w-full space-y-2">
{scheduleError && <Toast variant="danger">{scheduleError}</Toast>}
{toastError && <Toast variant="danger">{toastError}</Toast>}
{toastInfo && <Toast variant="warning">{toastInfo}</Toast>}
{toastSuccess && <Toast variant="success">{toastSuccess}</Toast>}
</div>
</div>
)}

View File

@@ -4,6 +4,7 @@ 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 { useAuth } from '@/lib/hooks/useAuth';
@@ -195,19 +196,19 @@ export default function BillingPage() {
}
function StatCard({ title, count, amount, color }: StatCardProps) {
const colors: Record<StatCardColor, string> = {
blue: 'bg-sky-900/30 text-sky-300 border-sky-700/60',
yellow: 'bg-amber-900/30 text-amber-300 border-amber-700/60',
green: 'bg-emerald-900/30 text-emerald-300 border-emerald-700/60',
red: 'bg-red-950/30 text-red-300 border-red-700/60',
blue: '!bg-purpose-visit-bg !text-purpose-visit-fg !border-purpose-visit-border',
yellow: '!bg-badge-warning-bg !text-badge-warning-fg !border-badge-warning-border',
green: '!bg-badge-success-bg !text-badge-success-fg !border-badge-success-border',
red: '!bg-badge-danger-bg !text-badge-danger-fg !border-badge-danger-border',
};
return (
<div className={`p-4 rounded-xl border ${colors[color]}`}>
<p className="text-sm font-medium opacity-80">{title}</p>
<Card className={`${colors[color]}`}>
<p className="text-sm font-medium">{title}</p>
<p className="text-2xl font-bold mt-1">{count}</p>
<p className="text-sm font-medium mt-1">
${amount.toLocaleString()}
</p>
</div>
</Card>
);
}

View File

@@ -1,14 +1,16 @@
'use client';
'use client';
import { useEffect, useState } from 'react';
import { Check, Copy, Link2, Trash2, X } from 'lucide-react';
import { Check, Link2, Trash2, X } from 'lucide-react';
import { useAuth } from '@/lib/hooks/useAuth';
import { useOrganizationInviteLinkCopy } from '@/lib/hooks/useOrganizationInviteLinkCopy';
import {
organizationApi,
type CounterpartItemDto,
type CounterpartSearchResultDto,
type OrganizationInvitationHistoryItemDto,
} from '@/lib/api/organization';
import { InvitationHistoryDialog } from '@/components/ui/organizations/InvitationHistoryDialog';
import { Button } from '@/components/ui/common/Button';
import { Badge, organizationLinkStatusVariant } from '@/components/ui/common/Badge';
import { Input } from '@/components/ui/common/Input';
@@ -16,33 +18,6 @@ import { SearchBar } from '@/components/ui/common/SearchBar';
import { Table } from '@/components/ui/common/Table';
import type { ApiError } from '@/types/api';
type StoredInviteLink = {
invitationId: string;
ownerEmail: string;
invitationUrl: string;
};
function inviteLinksStorageKey(orgId: string): string {
return `counterpartInviteLinks:${orgId}`;
}
function readStoredInviteLinks(orgId: string): Record<string, StoredInviteLink> {
if (typeof window === 'undefined') return {};
try {
const raw = window.localStorage.getItem(inviteLinksStorageKey(orgId));
if (!raw) return {};
const parsed = JSON.parse(raw) as Record<string, StoredInviteLink>;
return parsed && typeof parsed === 'object' ? parsed : {};
} catch {
return {};
}
}
function writeStoredInviteLinks(orgId: string, links: Record<string, StoredInviteLink>) {
if (typeof window === 'undefined') return;
window.localStorage.setItem(inviteLinksStorageKey(orgId), JSON.stringify(links));
}
function formatOrganizationStatusLabel(status: string): string {
if (!status) return status;
const lower = status.toLowerCase();
@@ -56,13 +31,6 @@ function formatLinkStatusLabel(status: CounterpartItemDto['status']): string {
return formatOrganizationStatusLabel(status);
}
function formatInvitationStatusLabel(status: OrganizationInvitationHistoryItemDto['status']): string {
if (status === 'PENDING') return 'Invitation pending';
if (status === 'ACTIVE') return 'Invitation Accepted';
if (status === 'REJECTED') return 'Invitation rejected';
return formatOrganizationStatusLabel(status);
}
function formatApiMessage(err: unknown): string {
if (!err || typeof err !== 'object') return 'Something went wrong';
const m = (err as ApiError).message;
@@ -73,7 +41,7 @@ function formatApiMessage(err: unknown): string {
function formatTableDate(value: string): string {
const d = new Date(value);
if (Number.isNaN(d.getTime())) return '';
if (Number.isNaN(d.getTime())) return '—';
return d.toLocaleDateString();
}
@@ -96,12 +64,20 @@ export default function OrganizationsPage() {
const [manualOrganizationName, setManualOrganizationName] = useState('');
const [manualOwnerEmail, setManualOwnerEmail] = useState('');
const [inviteLoading, setInviteLoading] = useState(false);
const [copiedId, setCopiedId] = useState<string | null>(null);
const [pendingInviteLinks, setPendingInviteLinks] = useState<Record<string, StoredInviteLink>>({});
const [showInviteForm, setShowInviteForm] = useState(false);
const [historyOpen, setHistoryOpen] = useState(false);
const [historyLoading, setHistoryLoading] = useState(false);
const [historyItems, setHistoryItems] = useState<OrganizationInvitationHistoryItemDto[]>([]);
const [historyCopyError, setHistoryCopyError] = useState('');
const [historyCopySuccess, setHistoryCopySuccess] = useState('');
const {
copiedId,
copyingInvitationId,
storeInviteLink,
copyInvitationLink,
pruneAcceptedLinks,
} = useOrganizationInviteLinkCopy(currentOrganization?.id);
const counterpartLabel = currentOrganization?.type === 'LAB' ? 'Clinic' : 'Lab';
const tabLabel = currentOrganization?.type === 'LAB' ? 'Clinics' : 'Labs';
@@ -121,11 +97,6 @@ export default function OrganizationsPage() {
}
}
useEffect(() => {
if (!currentOrganization?.id) return;
setPendingInviteLinks(readStoredInviteLinks(currentOrganization.id));
}, [currentOrganization?.id]);
useEffect(() => {
void loadList();
}, []);
@@ -185,18 +156,7 @@ export default function OrganizationsPage() {
organizationName: manualOrganizationName.trim(),
ownerEmail: manualOwnerEmail.trim(),
});
if (currentOrganization?.id) {
const nextLinks = {
...pendingInviteLinks,
[res.data.invitationId]: {
invitationId: res.data.invitationId,
ownerEmail: manualOwnerEmail.trim().toLowerCase(),
invitationUrl: res.data.invitationUrl,
},
};
setPendingInviteLinks(nextLinks);
writeStoredInviteLinks(currentOrganization.id, nextLinks);
}
storeInviteLink(res.data.invitationId, manualOwnerEmail, res.data.invitationUrl);
setSuccess(`Invitation link created for ${manualOwnerEmail.trim()}`);
setManualOrganizationName('');
setManualOwnerEmail('');
@@ -212,13 +172,21 @@ export default function OrganizationsPage() {
}
}
async function loadInvitationHistory() {
const res = await organizationApi.listInvitations();
setHistoryItems(res.data.items);
pruneAcceptedLinks(res.data.items);
return res.data.items;
}
async function openInvitationHistory() {
setHistoryOpen(true);
setHistoryLoading(true);
setHistoryCopyError('');
setHistoryCopySuccess('');
setError('');
try {
const res = await organizationApi.listInvitations();
setHistoryItems(res.data.items);
await loadInvitationHistory();
} catch (e) {
setError(formatApiMessage(e));
} finally {
@@ -226,6 +194,22 @@ export default function OrganizationsPage() {
}
}
async function handleHistoryCopy(invitation: OrganizationInvitationHistoryItemDto) {
setHistoryCopyError('');
setHistoryCopySuccess('');
try {
await copyInvitationLink(invitation, {
onRegenerated: async () => {
await loadInvitationHistory();
},
});
setHistoryCopySuccess('Invitation link copied to clipboard.');
setTimeout(() => setHistoryCopySuccess(''), 3000);
} catch (e) {
setHistoryCopyError(formatApiMessage(e));
}
}
async function respondToPendingLink(linkId: string, action: 'ACCEPT' | 'REJECT') {
setRequestLinkRowId(linkId);
setError('');
@@ -254,35 +238,6 @@ export default function OrganizationsPage() {
}
}
async function copyInvitationLink(invitationId: string) {
setError('');
try {
let invitationUrl = pendingInviteLinks[invitationId]?.invitationUrl;
if (!invitationUrl) {
const res = await organizationApi.getInvitationLink(invitationId);
invitationUrl = res.data.invitationUrl;
if (currentOrganization?.id) {
const nextLinks = {
...pendingInviteLinks,
[invitationId]: {
invitationId,
ownerEmail:
historyItems.find((item) => item.id === invitationId)?.ownerEmail?.toLowerCase() ?? '',
invitationUrl,
},
};
setPendingInviteLinks(nextLinks);
writeStoredInviteLinks(currentOrganization.id, nextLinks);
}
}
await navigator.clipboard.writeText(invitationUrl);
setCopiedId(invitationId);
setTimeout(() => setCopiedId(null), 1500);
} catch {
setError('Could not copy invitation link');
}
}
function clearSearchView() {
setMode('existing');
setQuery('');
@@ -516,87 +471,21 @@ export default function OrganizationsPage() {
}
/>
{historyOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
<div
className="w-full max-w-3xl max-h-[90vh] overflow-y-auto rounded-[var(--radius-md)] border border-border bg-background-secondary p-6 shadow-xl space-y-4"
role="dialog"
aria-modal="true"
>
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold text-text-primary">Invitation History</h2>
<Button type="button" size="sm" onClick={() => setHistoryOpen(false)}>
Close
</Button>
</div>
{historyLoading ? (
<p className="text-sm text-text-secondary">Loading invitation history...</p>
) : historyItems.length === 0 ? (
<p className="text-sm text-text-secondary">No invitations yet.</p>
) : (
<Table
headers={
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
Organization
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
Owner email
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
Date
</th>
<th className="px-6 py-3 text-center text-xs font-medium text-text-muted uppercase tracking-wider">
Status
</th>
<th className="px-6 py-3 text-right text-xs font-medium text-text-muted uppercase tracking-wider">
Action
</th>
</tr>
}
body={
<>
{historyItems.map((inv) => (
<tr key={inv.id} className="hover:bg-background-secondary/45">
<td className="px-6 py-1.5 text-sm text-text-primary">{inv.organizationName}</td>
<td className="px-6 py-1.5 text-sm text-text-secondary">{inv.ownerEmail}</td>
<td className="px-6 py-1.5 text-sm text-text-secondary">
{formatTableDate(inv.createdAt)}
</td>
<td className="px-6 py-1.5 text-center align-middle">
<Badge variant={organizationLinkStatusVariant(inv.status)} fixedWidth={false}>
{formatInvitationStatusLabel(inv.status)}
</Badge>
</td>
<td className="px-6 py-1.5 text-right">
{inv.status === 'PENDING' ? (
<button
type="button"
className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary"
onClick={() => void copyInvitationLink(inv.id)}
aria-label="Copy invitation link"
title="Copy invitation link"
>
{copiedId === inv.id ? (
<Check className="w-4 h-4" />
) : (
<Copy className="w-4 h-4" />
)}
</button>
) : (
<span className="text-xs text-text-muted"></span>
)}
</td>
</tr>
))}
</>
}
/>
)}
</div>
</div>
)}
<InvitationHistoryDialog
open={historyOpen}
onClose={() => {
setHistoryOpen(false);
setHistoryCopyError('');
setHistoryCopySuccess('');
}}
loading={historyLoading}
items={historyItems}
copiedId={copiedId}
copyingInvitationId={copyingInvitationId}
onCopy={(invitation) => void handleHistoryCopy(invitation)}
copyError={historyCopyError}
copySuccess={historyCopySuccess}
/>
</div>
);
}

View File

@@ -1,7 +1,7 @@
'use client';
import Link from 'next/link';
import { OrganizationSelectorContent } from '@/components/ui/organization/OrganizationSelectorContent';
import { OrganizationSelectorContent } from '@/components/ui/organizations/OrganizationSelectorContent';
export default function DashboardOrganizationsSettingsPage() {
return (

View File

@@ -6,6 +6,7 @@ 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 type { SubscriptionAlertData } from '@/types/subscription';
const PLAN_OPTIONS = [
@@ -69,7 +70,7 @@ export default function SubscriptionsSettingsPage() {
: 'text-red-400';
return (
<div className="space-y-6">
<div className="relative space-y-6 pb-24">
<div>
<Link
href="/today"
@@ -189,13 +190,16 @@ export default function SubscriptionsSettingsPage() {
>
Start purchase process
</Button>
{purchaseNotice && (
<div className="rounded-[var(--radius-md)] border border-emerald-500/30 bg-emerald-500/10 px-4 py-3">
<p className="text-sm text-emerald-200">{purchaseNotice}</p>
</div>
)}
</div>
</div>
{purchaseNotice && (
<div className="fixed bottom-4 left-0 right-0 z-[70] px-4 pointer-events-none">
<div className="pointer-events-auto w-full">
<Toast variant="success">{purchaseNotice}</Toast>
</div>
</div>
)}
</div>
);
}

View File

@@ -17,6 +17,7 @@ import {
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 { useAuth } from '@/lib/hooks/useAuth';
import { staffApi, type StaffMemberDto } from '@/lib/api/staff';
import { Button } from '@/components/ui/common/Button';
@@ -61,6 +62,10 @@ function formatApiMessage(err: unknown): string {
return 'Something went wrong';
}
function canShareStaffInviteLink(member: StaffMemberDto): boolean {
return !member.isOwner && member.invitationStatus !== 'ACTIVE';
}
function PermissionGrid({
state,
onChange,
@@ -140,6 +145,7 @@ export default function StaffPage() {
const [invitePerms, setInvitePerms] = useState(() => emptyFeaturePermissionState());
const [inviteLoading, setInviteLoading] = useState(false);
const [copiedInviteMembershipId, setCopiedInviteMembershipId] = useState<string | null>(null);
const [copyingInviteMembershipId, setCopyingInviteMembershipId] = useState<string | null>(null);
const [lastInviteInfo, setLastInviteInfo] = useState<{
membershipId: string;
name: string;
@@ -221,6 +227,42 @@ export default function StaffPage() {
return () => clearTimeout(t);
}, [success]);
async function copyStaffInviteLink(member: StaffMemberDto) {
if (!canShareStaffInviteLink(member)) return;
setCopyingInviteMembershipId(member.id);
setError('');
try {
let invitationUrl = pendingInviteLinks[member.id]?.invitationUrl;
if (!invitationUrl || member.invitationStatus === 'EXPIRED') {
const res = await staffApi.getInvitationLink(member.id);
invitationUrl = res.data.invitationUrl;
if (currentOrganization?.id) {
const nextLinks = {
...pendingInviteLinks,
[member.id]: {
membershipId: member.id,
email: member.email,
invitationUrl,
},
};
setPendingInviteLinks(nextLinks);
writeStoredInviteLinks(currentOrganization.id, nextLinks);
}
}
await navigator.clipboard.writeText(invitationUrl);
setCopiedInviteMembershipId(member.id);
setTimeout(() => setCopiedInviteMembershipId(null), 1500);
if (member.invitationStatus === 'EXPIRED') {
await load();
}
} catch (e) {
setError(formatApiMessage(e));
} finally {
setCopyingInviteMembershipId(null);
}
}
async function submitInvite() {
setInviteLoading(true);
setError('');
@@ -388,34 +430,60 @@ export default function StaffPage() {
? ' Invitation is pending until they open the link, set a password, and log in.'
: ' Invitation was accepted immediately.'}
</p>
{lastInviteInfo.invitationUrl && (
{lastInviteInfo.invitationStatus === 'PENDING' && (
<div className="space-y-2 pt-1 border-t border-border/60">
<p className="text-xs font-medium text-text-secondary uppercase tracking-wide">
Invite link
</p>
<div className="flex flex-wrap items-center gap-2">
<code className="text-sm px-2 py-1.5 rounded-[var(--radius-sm)] bg-background-card border border-border font-mono break-all">
{lastInviteInfo.invitationUrl && (
<code className="block text-sm px-2 py-1.5 rounded-[var(--radius-sm)] bg-background-card border border-border font-mono break-all">
{lastInviteInfo.invitationUrl}
</code>
<Button
type="button"
variant="outline"
size="sm"
onClick={async () => {
)}
<Button
type="button"
variant="outline"
size="sm"
isLoading={copyingInviteMembershipId === lastInviteInfo.membershipId}
onClick={() => {
const member = members.find((item) => item.id === lastInviteInfo.membershipId);
if (member) {
void copyStaffInviteLink(member);
return;
}
void (async () => {
setCopyingInviteMembershipId(lastInviteInfo.membershipId);
setError('');
try {
await navigator.clipboard.writeText(lastInviteInfo.invitationUrl as string);
const res = await staffApi.getInvitationLink(lastInviteInfo.membershipId);
if (currentOrganization?.id) {
const nextLinks = {
...pendingInviteLinks,
[lastInviteInfo.membershipId]: {
membershipId: lastInviteInfo.membershipId,
email: lastInviteInfo.email,
invitationUrl: res.data.invitationUrl,
},
};
setPendingInviteLinks(nextLinks);
writeStoredInviteLinks(currentOrganization.id, nextLinks);
}
setLastInviteInfo({ ...lastInviteInfo, invitationUrl: res.data.invitationUrl });
await navigator.clipboard.writeText(res.data.invitationUrl);
setCopiedInviteMembershipId(lastInviteInfo.membershipId);
setTimeout(() => setCopiedInviteMembershipId(null), 1500);
} catch {
setError('Could not copy invitation link');
} catch (e) {
setError(formatApiMessage(e));
} finally {
setCopyingInviteMembershipId(null);
}
}}
>
{copiedInviteMembershipId === lastInviteInfo.membershipId ? 'Copied' : 'Copy link'}
</Button>
</div>
})();
}}
>
{copiedInviteMembershipId === lastInviteInfo.membershipId ? 'Copied' : 'Copy link'}
</Button>
<p className="text-xs text-text-muted">
Share this link manually via SMS or email. They must set password first.
Share this link manually via SMS or email. A new link is generated if the previous one expired or was lost.
</p>
</div>
)}
@@ -470,21 +538,14 @@ export default function StaffPage() {
<td className="px-6 py-1.5 align-middle">
{!m.isOwner && (
<div className="flex min-h-[36px] items-center justify-end gap-1">
{m.invitationStatus === 'PENDING' && pendingInviteLinks[m.id]?.invitationUrl && (
{canShareStaffInviteLink(m) && (
<button
type="button"
className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary"
onClick={async () => {
try {
await navigator.clipboard.writeText(pendingInviteLinks[m.id].invitationUrl);
setCopiedInviteMembershipId(m.id);
setTimeout(() => setCopiedInviteMembershipId(null), 1500);
} catch {
setError('Could not copy invitation link');
}
}}
aria-label="Copy invite link"
title="Copy invite link"
className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary disabled:opacity-50"
disabled={copyingInviteMembershipId === m.id}
onClick={() => void copyStaffInviteLink(m)}
aria-label="Copy invitation link"
title="Copy invitation link (generates a new link if needed)"
>
{copiedInviteMembershipId === m.id ? (
<Check className="w-4 h-4" />
@@ -543,9 +604,12 @@ export default function StaffPage() {
aria-modal="true"
aria-labelledby="invite-staff-title"
>
<h2 id="invite-staff-title" className="text-lg font-semibold text-text-primary">
Invite team member
</h2>
<div className="flex items-start justify-between gap-3">
<h2 id="invite-staff-title" className="text-lg font-semibold text-text-primary pr-2">
Invite team member
</h2>
<DialogCloseButton onClick={() => setInviteOpen(false)} />
</div>
<Input
label="Email"
type="email"
@@ -590,7 +654,10 @@ export default function StaffPage() {
role="dialog"
aria-modal="true"
>
<h2 className="text-lg font-semibold text-text-primary">Edit member</h2>
<div className="flex items-start justify-between gap-3">
<h2 className="text-lg font-semibold text-text-primary pr-2">Edit member</h2>
<DialogCloseButton onClick={() => setEditing(null)} />
</div>
<p className="text-xs text-text-muted">{editing.email}</p>
<Input label="Display name" value={editName} onChange={(e) => setEditName(e.target.value)} />
<div>

View File

@@ -2,6 +2,7 @@
import Link from 'next/link';
import { useAuth } from '@/lib/hooks/useAuth';
import { Card } from '@/components/ui/common/Card';
export default function TodayPage() {
const { currentOrganization } = useAuth();
@@ -27,29 +28,26 @@ export default function TodayPage() {
)}
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
<Card title="Today's Appointments" value="12" sub="Monday 2/5/2026" />
<Card title="Active Patients" value="675" />
<Card title="New Lab Case" value="5" sub="35 ↑" />
<Card title="Today invoices" value="1200$" sub="21,300 $" />
<Card>
<p className="text-sm text-card-muted">Today's Appointments</p>
<p className="text-2xl font-semibold mt-2">12</p>
<p className="text-xs text-text-muted mt-1">Monday 2/5/2026</p>
</Card>
<Card>
<p className="text-sm text-card-muted">Active Patients</p>
<p className="text-2xl font-semibold mt-2">675</p>
</Card>
<Card>
<p className="text-sm text-card-muted">New Lab Case</p>
<p className="text-2xl font-semibold mt-2">5</p>
<p className="text-xs text-text-muted mt-1">35 </p>
</Card>
<Card>
<p className="text-sm text-card-muted">Today invoices</p>
<p className="text-2xl font-semibold mt-2">1200$</p>
<p className="text-xs text-text-muted mt-1">21,300 $</p>
</Card>
</div>
</div>
);
}
function Card({
title,
value,
sub,
}: {
title: string;
value: string;
sub?: string;
}) {
return (
<div className="surface-card p-4">
<p className="text-sm text-text-secondary">{title}</p>
<p className="text-2xl font-semibold mt-2">{value}</p>
{sub && <p className="text-xs text-text-muted mt-1">{sub}</p>}
</div>
);
}

View File

@@ -3,15 +3,45 @@
import { Suspense, useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useForm, type FieldErrors, type UseFormRegister, type UseFormSetValue } from 'react-hook-form';
import type { OrganizationDetailsFormValues } from '@/components/ui/auth/OrganizationDetailsFields';
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 { OrganizationDetailsFields } from '@/components/ui/auth/OrganizationDetailsFields';
import { RegistrationProgressSteps } from '@/components/ui/auth/RegistrationProgressSteps';
import { organizationApi } from '@/lib/api/organization';
const acceptOrganizationInviteSchema = z
.object({
ownerName: z.string().min(2, 'Name must be at least 2 characters'),
password: z
.string()
.min(8, 'Password must be at least 8 characters')
.regex(/[A-Z]/, 'Password must contain at least one uppercase letter')
.regex(/[0-9]/, 'Password must contain at least one number'),
confirmPassword: z.string(),
organizationName: z.string().min(2, 'Organization name must be at least 2 characters'),
organizationEmail: z.string().email('Please enter a valid organization email'),
organizationType: z.enum(['CLINIC', 'LAB'], {
message: 'Please select organization type',
}),
})
.refine((data) => data.password === data.confirmPassword, {
message: "Passwords don't match",
path: ['confirmPassword'],
});
type AcceptOrganizationInviteForm = z.infer<typeof acceptOrganizationInviteSchema>;
function AcceptOrganizationInviteContent() {
const params = useSearchParams();
const router = useRouter();
const token = useMemo(() => params.get('token') || '', [params]);
const [step, setStep] = useState(1);
const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState('');
@@ -20,15 +50,29 @@ function AcceptOrganizationInviteContent() {
ownerEmail: string;
organizationName: string;
organizationType: 'CLINIC' | 'LAB';
organizationEmail?: string;
inviterOrganizationName: string;
expiresAt: string;
status: 'PENDING' | 'ACCEPTED';
} | null>(null);
const [ownerName, setOwnerName] = useState('');
const [organizationName, setOrganizationName] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const {
register,
handleSubmit,
watch,
trigger,
setValue,
reset,
formState: { errors },
} = useForm<AcceptOrganizationInviteForm>({
resolver: zodResolver(acceptOrganizationInviteSchema),
mode: 'onChange',
defaultValues: {
organizationType: undefined,
},
});
const organizationType = watch('organizationType');
useEffect(() => {
if (!token) {
@@ -43,102 +87,168 @@ function AcceptOrganizationInviteContent() {
try {
const res = await organizationApi.previewInvite(token);
setInviteInfo(res.data);
setOrganizationName(res.data.organizationName || '');
reset({
ownerName: '',
password: '',
confirmPassword: '',
organizationName: res.data.organizationName || '',
organizationEmail: res.data.organizationEmail || '',
organizationType: res.data.organizationType,
});
if (res.data.status === 'ACCEPTED') {
setSuccess('This invitation is already accepted. You can log in now.');
}
} catch (e: any) {
setError(e?.message || 'Could not load invitation');
} catch (e: unknown) {
const message = e && typeof e === 'object' && 'message' in e ? String(e.message) : '';
setError(message || 'Could not load invitation');
} finally {
setLoading(false);
}
})();
}, [token]);
}, [token, reset]);
async function onAccept() {
const handleNext = async () => {
const isValid = await trigger(['ownerName', 'password', 'confirmPassword']);
if (isValid) {
setStep(2);
setError('');
}
};
const onSubmit = async (data: AcceptOrganizationInviteForm) => {
if (!token) return;
setError('');
setSuccess('');
if (!ownerName.trim()) return setError('Owner name is required');
if (!organizationName.trim()) return setError('Organization name is required');
if (password.length < 8) return setError('Password must be at least 8 characters');
if (password !== confirmPassword) return setError('Passwords do not match');
setSubmitting(true);
try {
await organizationApi.acceptInvite({
token,
ownerName: ownerName.trim(),
organizationName: organizationName.trim(),
password,
ownerName: data.ownerName.trim(),
password: data.password,
organizationName: data.organizationName.trim(),
organizationEmail: data.organizationEmail.trim(),
organizationType: data.organizationType,
});
setSuccess('Invitation Accepted. Redirecting to login...');
setSuccess('Invitation accepted. Redirecting to login...');
setTimeout(() => router.replace('/login'), 1000);
} catch (e: any) {
setError(e?.message || 'Could not accept invitation');
} catch (e: unknown) {
const message = e && typeof e === 'object' && 'message' in e ? String(e.message) : '';
setError(message || 'Could not accept invitation');
} finally {
setSubmitting(false);
}
}
};
return (
<div className="min-h-screen app-web-bg flex items-center justify-center p-4">
<div className="w-full max-w-md surface-card p-6 space-y-5">
<h1 className="text-xl font-semibold text-text-primary">Accept organization invitation</h1>
{loading ? (
<p className="text-sm text-text-secondary">Loading invitation...</p>
) : (
<>
{inviteInfo && (
<div className="rounded-[var(--radius-md)] border border-border/70 bg-background-secondary/70 px-3 py-2 text-sm text-text-secondary space-y-1">
<p>
Invited by: <span className="text-text-primary">{inviteInfo.inviterOrganizationName}</span>
</p>
<p>
Owner email: <span className="text-text-primary">{inviteInfo.ownerEmail}</span>
</p>
</div>
)}
{error && (
<div className="rounded-[var(--radius-md)] border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300">
{error}
</div>
)}
{success && (
<div className="rounded-[var(--radius-md)] border border-primary/30 bg-primary-soft/40 px-3 py-2 text-sm text-text-primary">
{success}
</div>
)}
{inviteInfo?.status !== 'ACCEPTED' && (
<div className="space-y-3">
<Input label="Owner name" value={ownerName} onChange={(e) => setOwnerName(e.target.value)} />
<Input
label="Organization name"
value={organizationName}
onChange={(e) => setOrganizationName(e.target.value)}
/>
<Input
label="Create password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<Input
label="Confirm password"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
/>
<Button type="button" fullWidth isLoading={submitting} onClick={() => void onAccept()}>
Activate organization
</Button>
</div>
)}
<p className="text-xs text-text-muted">
Already have access? <Link href="/login" className="text-primary">Go to login</Link>
</p>
</>
)}
<div className="min-h-screen app-web-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8">
<div className="sm:mx-auto sm:w-full sm:max-w-md">
<Link href="/" className="flex justify-center">
<span className="text-3xl font-semibold text-text-primary">DyoLink</span>
</Link>
<h2 className="mt-6 text-center text-2xl font-semibold text-text-primary">
Accept organization invitation
</h2>
<p className="mt-2 text-center text-sm text-text-secondary">
Already have an account?{' '}
<Link href="/login" className="font-medium text-primary hover:opacity-90">
Sign in
</Link>
</p>
</div>
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
<div className="surface-card py-8 px-4 sm:px-10">
{loading ? (
<p className="text-sm text-text-secondary">Loading invitation...</p>
) : (
<>
{inviteInfo && (
<div className="mb-6 rounded-[var(--radius-md)] border border-border/70 bg-background-secondary/70 px-3 py-2 text-sm text-text-secondary space-y-1">
<p>
Invited by:{' '}
<span className="text-text-primary">{inviteInfo.inviterOrganizationName}</span>
</p>
</div>
)}
{inviteInfo?.status !== 'ACCEPTED' && (
<RegistrationProgressSteps step={step} />
)}
{error && (
<div className="mb-4 p-3 bg-red-950/30 border border-red-600/40 rounded-[var(--radius-md)]">
<p className="text-sm text-red-600">{error}</p>
</div>
)}
{success && (
<div className="mb-4 rounded-[var(--radius-md)] border border-primary/30 bg-primary-soft/40 px-3 py-2 text-sm text-text-primary">
{success}
</div>
)}
{inviteInfo?.status !== 'ACCEPTED' && (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
{step === 1 && (
<>
<Input
label="Owner email"
value={inviteInfo?.ownerEmail ?? ''}
readOnly
disabled
icon={<Mail className="h-5 w-5 icon-flat" />}
/>
<Input
label="Full name"
{...register('ownerName')}
placeholder="John Doe"
error={errors.ownerName?.message}
icon={<User className="h-5 w-5 icon-flat" />}
/>
<Input
label="Password"
{...register('password')}
type="password"
placeholder="••••••••"
error={errors.password?.message}
icon={<Lock className="h-5 w-5 icon-flat" />}
/>
<Input
label="Confirm password"
{...register('confirmPassword')}
type="password"
placeholder="••••••••"
error={errors.confirmPassword?.message}
icon={<Lock className="h-5 w-5 icon-flat" />}
/>
<Button type="button" variant="primary" onClick={() => void handleNext()} fullWidth>
Continue
</Button>
</>
)}
{step === 2 && (
<>
<OrganizationDetailsFields
register={register as unknown as UseFormRegister<OrganizationDetailsFormValues>}
errors={errors as FieldErrors<OrganizationDetailsFormValues>}
organizationType={organizationType}
setValue={setValue as unknown as UseFormSetValue<OrganizationDetailsFormValues>}
/>
<div className="flex gap-3">
<Button type="button" variant="outline" onClick={() => setStep(1)}>
Back
</Button>
<Button type="submit" variant="primary" isLoading={submitting} fullWidth>
Activate organization
</Button>
</div>
</>
)}
</form>
)}
</>
)}
</div>
</div>
</div>
);

View File

@@ -5,8 +5,10 @@ import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import Link from 'next/link';
import { Building2, Mail, Lock, User, ChevronRight } from 'lucide-react';
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';
const registerSchema = z.object({
@@ -89,31 +91,7 @@ export default function RegisterPage() {
</div>
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
<div className="surface-card py-8 px-4 sm:px-10">
{/* Progress Steps */}
<div className="mb-8">
<div className="flex items-center justify-between">
<div className="flex items-center">
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${step >= 1 ? 'bg-primary text-primary-contrast' : 'bg-background-secondary text-text-secondary border border-border'}`}>
1
</div>
<div className={`ml-2 text-sm font-medium ${step >= 1 ? 'text-primary' : 'text-text-muted'
}`}>
Account
</div>
</div>
<ChevronRight className="h-5 w-5 text-text-muted icon-flat" />
<div className="flex items-center">
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${step >= 2 ? 'bg-primary text-primary-contrast' : 'bg-background-secondary text-text-secondary border border-border'}`}>
2
</div>
<div className={`ml-2 text-sm font-medium ${step >= 2 ? 'text-primary' : 'text-text-muted'
}`}>
Organization
</div>
</div>
</div>
</div>
<RegistrationProgressSteps step={step} />
{/* Trial Info Banner */}
<div className="mb-6 p-4 bg-primary-soft rounded-[var(--radius-md)] border border-primary/35">
<h3 className="text-sm font-medium text-text-primary mb-2">Your trial
@@ -177,57 +155,12 @@ export default function RegisterPage() {
)}
{step === 2 && (
<>
<Input
label="Organization name"
{...register('organizationName')}
placeholder="Sunshine Dental Clinic"
error={errors.organizationName?.message}
icon={<Building2 className="h-5 w-5 icon-flat" />}
<OrganizationDetailsFields
register={register as never}
errors={errors as never}
organizationType={organizationType}
setValue={setValue as never}
/>
<Input
label="Organization email"
{...register('organizationEmail')}
type="email"
placeholder="contact@sunshineclinic.com"
error={errors.organizationEmail?.message}
icon={<Mail className="h-5 w-5 icon-flat" />}
/>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Organization type
</label>
<input type="hidden" {...register('organizationType')} />
<div className="grid grid-cols-2 gap-4">
<button
type="button"
onClick={() => {
setValue('organizationType', 'CLINIC', { shouldValidate: true });
}}
className={`p-4 border rounded-[var(--radius-md)] text-center transition-colors ${organizationType === 'CLINIC' ? 'border-primary/60 bg-primary-soft text-text-primary'
: 'border-border text-text-secondary hover:border-border-strong'
}`}
>
<Building2 className="h-8 w-8 mx-auto mb-2 icon-flat" />
<span className="text-sm font-medium">Dental Clinic</span>
</button>
<button
type="button"
onClick={() => {
setValue('organizationType', 'LAB', { shouldValidate: true });
}}
className={`p-4 border rounded-[var(--radius-md)] text-center transition-colors ${organizationType === 'LAB'
? 'border-primary/60 bg-primary-soft text-text-primary'
: 'border-border text-text-secondary hover:border-border-strong'
}`}
>
<Building2 className="h-8 w-8 mx-auto mb-2 icon-flat" />
<span className="text-sm font-medium">Dental Lab</span>
</button>
</div>
{errors.organizationType && (
<p className="mt-2 text-sm text-red-600">{errors.organizationType.message}</p>
)}
</div>
{error && (
<div className="p-3 bg-red-950/30 border border-red-600/40 rounded-[var(--radius-md)]">
<p className="text-sm text-red-600">{error}</p>

View File

@@ -1,6 +1,6 @@
'use client';
import { OrganizationSelectorContent } from '@/components/ui/organization/OrganizationSelectorContent';
import { OrganizationSelectorContent } from '@/components/ui/organizations/OrganizationSelectorContent';
export default function SelectOrganizationPage() {
return (

View File

@@ -0,0 +1,41 @@
import type { OrganizationInvitationHistoryItemDto } from '@/lib/api/organization';
export type StoredOrganizationInviteLink = {
invitationId: string;
ownerEmail: string;
invitationUrl: string;
};
export function organizationInviteLinksStorageKey(orgId: string): string {
return `counterpartInviteLinks:${orgId}`;
}
export function readOrganizationInviteLinks(
orgId: string,
): Record<string, StoredOrganizationInviteLink> {
if (typeof window === 'undefined') return {};
try {
const raw = window.localStorage.getItem(organizationInviteLinksStorageKey(orgId));
if (!raw) return {};
const parsed = JSON.parse(raw) as Record<string, StoredOrganizationInviteLink>;
return parsed && typeof parsed === 'object' ? parsed : {};
} catch {
return {};
}
}
export function writeOrganizationInviteLinks(
orgId: string,
links: Record<string, StoredOrganizationInviteLink>,
): void {
if (typeof window === 'undefined') return;
window.localStorage.setItem(organizationInviteLinksStorageKey(orgId), JSON.stringify(links));
}
/** Show copy/regenerate only until the invitee accepts (first login / setup). */
export function canShareOrganizationInviteLink(
invitation: Pick<OrganizationInvitationHistoryItemDto, 'status' | 'acceptedAt'>,
): boolean {
if (invitation.acceptedAt) return false;
return invitation.status === 'PENDING' || invitation.status === 'EXPIRED';
}

View File

@@ -1,14 +1,15 @@
'use client';
import { useEffect, useState } from 'react';
import { X } from 'lucide-react';
import { Button } from '@/components/ui/common/Button';
import { DialogCloseButton } from '@/components/ui/common/DialogCloseButton';
import { Dropdown } from '@/components/ui/common/Dropdown';
import type { AppointmentPurpose } from '@/types/appointment';
import type { AppointmentPurpose, AppointmentRecord } from '@/types/appointment';
import { APPOINTMENT_PURPOSE_LABEL } from '@/components/ui/appointments/appointmentPurposeStyles';
import type { Patient } from '@/types/patient';
import {
combineLocalDateAndTime,
compareLocalDayStart,
formatTimeForInput,
isSameLocalCalendarDay,
} from '@/lib/appointmentTime';
@@ -28,6 +29,7 @@ interface AppointmentBookingModalProps {
endAt: string;
purpose: AppointmentPurpose;
}) => Promise<void>;
editingAppointment?: AppointmentRecord | null;
loading?: boolean;
}
@@ -40,6 +42,7 @@ export function AppointmentBookingModal({
initialHour,
onClose,
onSubmit,
editingAppointment = null,
loading = false,
}: AppointmentBookingModalProps) {
const [startTime, setStartTime] = useState('09:00');
@@ -61,29 +64,37 @@ export function AppointmentBookingModal({
if (!open) {
return;
}
const start = new Date(
scheduleDate.getFullYear(),
scheduleDate.getMonth(),
scheduleDate.getDate(),
initialHour,
0,
0,
0,
);
const end = new Date(
scheduleDate.getFullYear(),
scheduleDate.getMonth(),
scheduleDate.getDate(),
initialHour < 23 ? initialHour + 1 : 23,
initialHour < 23 ? 0 : 59,
0,
0,
);
setStartTime(formatTimeForInput(start));
setEndTime(formatTimeForInput(end));
setPurpose('consultation');
if (editingAppointment) {
const start = new Date(editingAppointment.startAt);
const end = new Date(editingAppointment.endAt);
setStartTime(formatTimeForInput(start));
setEndTime(formatTimeForInput(end));
setPurpose((editingAppointment.purpose as AppointmentPurpose) ?? 'consultation');
} else {
const start = new Date(
scheduleDate.getFullYear(),
scheduleDate.getMonth(),
scheduleDate.getDate(),
initialHour,
0,
0,
0,
);
const end = new Date(
scheduleDate.getFullYear(),
scheduleDate.getMonth(),
scheduleDate.getDate(),
initialHour < 23 ? initialHour + 1 : 23,
initialHour < 23 ? 0 : 59,
0,
0,
);
setStartTime(formatTimeForInput(start));
setEndTime(formatTimeForInput(end));
setPurpose('consultation');
}
setError('');
}, [open, scheduleDate, initialHour]);
}, [open, scheduleDate, initialHour, editingAppointment]);
if (!open || !providerUserId) {
return null;
@@ -97,7 +108,7 @@ export function AppointmentBookingModal({
if (!providerUserId) {
return;
}
if (!patient) {
if (!editingAppointment && !patient) {
setError('Select a patient first.');
return;
}
@@ -116,9 +127,22 @@ export function AppointmentBookingModal({
return;
}
const today = new Date();
if (compareLocalDayStart(scheduleDate, today) < 0) {
setError('Past appointments are view-only.');
return;
}
const effectivePatientId = editingAppointment?.patientId ?? patient?.id;
const effectiveProviderId = editingAppointment?.providerUserId ?? providerUserId;
if (!effectivePatientId || !effectiveProviderId) {
setError('Missing appointment details.');
return;
}
await onSubmit({
patientId: patient.id,
providerUserId,
patientId: effectivePatientId,
providerUserId: effectiveProviderId,
startAt: startAt.toISOString(),
endAt: endAt.toISOString(),
purpose,
@@ -135,16 +159,9 @@ export function AppointmentBookingModal({
>
<div className="flex items-start justify-between gap-2">
<h2 id="appointment-modal-title" className="text-lg font-semibold text-text-primary pr-2">
New appointment
{editingAppointment ? 'Edit appointment' : 'New appointment'}
</h2>
<button
type="button"
onClick={onClose}
className="rounded-[var(--radius-sm)] p-1.5 text-text-muted hover:text-text-primary hover:bg-background-secondary/80 focus:outline-none focus:ring-2 focus:ring-primary/35"
aria-label="Close"
>
<X className="h-5 w-5 icon-flat" />
</button>
<DialogCloseButton onClick={onClose} />
</div>
<p className="text-sm text-text-secondary">
@@ -154,7 +171,11 @@ export function AppointmentBookingModal({
<div>
<label className="block text-sm font-medium text-text-secondary mb-1">Patient</label>
<p className="text-sm text-text-primary rounded-[var(--radius-md)] border border-border bg-background-secondary/60 px-3 py-2">
{patient ? `${patient.firstName} ${patient.lastName}` : '—'}
{editingAppointment
? `${editingAppointment.patient.firstName} ${editingAppointment.patient.lastName}`
: patient
? `${patient.firstName} ${patient.lastName}`
: '—'}
</p>
</div>

View File

@@ -3,7 +3,10 @@
import { Trash2 } from 'lucide-react';
import type { AppointmentColumnProvider, AppointmentRecord } from '@/types/appointment';
import { formatHourLabel } from '@/lib/appointmentTime';
import { purposeDeleteIconClass, purposeStyle } from '@/components/ui/appointments/appointmentPurposeStyles';
import {
purposeDeleteIconClass,
purposeStyle,
} from '@/components/ui/appointments/appointmentPurposeStyles';
const HOUR_PX = 40;
const HOURS = Array.from({ length: 24 }, (_, i) => i);
@@ -32,6 +35,7 @@ interface AppointmentScheduleGridProps {
canDelete?: boolean;
onDeleteAppointment?: (id: string) => void;
onSlotClick: (hour: number, providerUserId: string, providerName: string) => void;
onAppointmentClick?: (appointment: AppointmentRecord) => void;
}
export function AppointmentScheduleGrid({
@@ -42,6 +46,7 @@ export function AppointmentScheduleGrid({
canDelete = false,
onDeleteAppointment,
onSlotClick,
onAppointmentClick,
}: AppointmentScheduleGridProps) {
const gridHeight = HOURS.length * HOUR_PX;
@@ -117,9 +122,11 @@ export function AppointmentScheduleGrid({
return null;
}
return (
<div
<button
type="button"
key={apt.id}
className={`absolute left-0.5 right-0.5 rounded-[var(--radius-sm)] border pointer-events-none z-10 flex flex-row items-center gap-1.5 px-1.5 py-1 min-h-[36px] ${purposeStyle(apt.purpose)}`}
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">
@@ -133,7 +140,7 @@ export function AppointmentScheduleGrid({
{canDelete && onDeleteAppointment && (
<button
type="button"
className="group pointer-events-auto shrink-0 self-center z-20 mr-2 ml-1 inline-flex cursor-pointer items-center justify-center rounded-[var(--radius-sm)] border-0 bg-transparent p-1 outline-none focus-visible:ring-2 focus-visible:ring-primary/35"
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) => {
@@ -144,7 +151,7 @@ export function AppointmentScheduleGrid({
<Trash2 className={`w-4 h-4 ${purposeDeleteIconClass(apt.purpose)}`} />
</button>
)}
</div>
</button>
);
})}
</div>

View File

@@ -10,11 +10,12 @@ export const APPOINTMENT_PURPOSE_LABEL: Record<AppointmentPurpose, string> = {
/** Background + border for blocks / legend (matches reference palette). */
export const APPOINTMENT_PURPOSE_STYLES: Record<AppointmentPurpose, string> = {
consultation: 'bg-violet-500/25 border-violet-400/50 text-violet-100',
filling: 'bg-orange-500/25 border-orange-400/50 text-orange-100',
endo: 'bg-red-500/25 border-red-400/50 text-red-100',
visit: 'bg-sky-500/25 border-sky-400/50 text-sky-100',
hygiene: 'bg-lime-500/20 border-lime-400/45 text-lime-100',
consultation:
'bg-purpose-consultation-bg border-purpose-consultation-border text-purpose-consultation-fg',
filling: 'bg-purpose-filling-bg border-purpose-filling-border text-purpose-filling-fg',
endo: 'bg-purpose-endo-bg border-purpose-endo-border text-purpose-endo-fg',
visit: 'bg-purpose-visit-bg border-purpose-visit-border text-purpose-visit-fg',
hygiene: 'bg-purpose-hygiene-bg border-purpose-hygiene-border text-purpose-hygiene-fg',
};
export function purposeStyle(purpose: string): string {
@@ -26,13 +27,13 @@ export function purposeStyle(purpose: string): string {
export function purposeDeleteIconClass(purpose: string): string {
const p = purpose as AppointmentPurpose;
const map: Record<AppointmentPurpose, string> = {
consultation: '!text-violet-400 group-hover:!text-violet-300',
filling: '!text-orange-400 group-hover:!text-orange-300',
endo: '!text-red-400 group-hover:!text-red-300',
visit: '!text-sky-400 group-hover:!text-sky-300',
hygiene: '!text-lime-600 group-hover:!text-lime-500',
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 group-hover:!text-text-secondary';
return map[p] ?? '!text-text-muted';
}
/** Small swatch for legend (background + border only). */

View File

@@ -0,0 +1,84 @@
'use client';
import { Building2, Mail } from 'lucide-react';
import type { FieldErrors, UseFormRegister, UseFormSetValue } from 'react-hook-form';
import { Input } from '@/components/ui/common/Input';
export type OrganizationDetailsFormValues = {
organizationName: string;
organizationEmail: string;
organizationType: 'CLINIC' | 'LAB';
};
type OrganizationDetailsFieldsProps = {
register: UseFormRegister<OrganizationDetailsFormValues>;
errors: FieldErrors<OrganizationDetailsFormValues>;
organizationType: 'CLINIC' | 'LAB' | undefined;
setValue: UseFormSetValue<OrganizationDetailsFormValues>;
};
export function OrganizationDetailsFields({
register,
errors,
organizationType,
setValue,
}: OrganizationDetailsFieldsProps) {
return (
<>
<Input
label="Organization name"
{...register('organizationName')}
placeholder="Sunshine Dental Clinic"
error={errors.organizationName?.message}
icon={<Building2 className="h-5 w-5 icon-flat" />}
/>
<Input
label="Organization email"
{...register('organizationEmail')}
type="email"
placeholder="contact@sunshineclinic.com"
error={errors.organizationEmail?.message}
icon={<Mail className="h-5 w-5 icon-flat" />}
/>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Organization type
</label>
<input type="hidden" {...register('organizationType')} />
<div className="grid grid-cols-2 gap-4">
<button
type="button"
onClick={() => {
setValue('organizationType', 'CLINIC', { shouldValidate: true });
}}
className={`p-4 border rounded-[var(--radius-md)] text-center transition-colors ${
organizationType === 'CLINIC'
? 'border-primary/60 bg-primary-soft text-text-primary'
: 'border-border text-text-secondary hover:border-border-strong'
}`}
>
<Building2 className="h-8 w-8 mx-auto mb-2 icon-flat" />
<span className="text-sm font-medium">Dental Clinic</span>
</button>
<button
type="button"
onClick={() => {
setValue('organizationType', 'LAB', { shouldValidate: true });
}}
className={`p-4 border rounded-[var(--radius-md)] text-center transition-colors ${
organizationType === 'LAB'
? 'border-primary/60 bg-primary-soft text-text-primary'
: 'border-border text-text-secondary hover:border-border-strong'
}`}
>
<Building2 className="h-8 w-8 mx-auto mb-2 icon-flat" />
<span className="text-sm font-medium">Dental Lab</span>
</button>
</div>
{errors.organizationType && (
<p className="mt-2 text-sm text-red-600">{errors.organizationType.message}</p>
)}
</div>
</>
);
}

View File

@@ -0,0 +1,59 @@
'use client';
import { ChevronRight } from 'lucide-react';
type RegistrationProgressStepsProps = {
step: number;
firstLabel?: string;
secondLabel?: string;
};
export function RegistrationProgressSteps({
step,
firstLabel = 'Account',
secondLabel = 'Organization',
}: RegistrationProgressStepsProps) {
return (
<div className="mb-8">
<div className="flex items-center justify-between">
<div className="flex items-center">
<div
className={`w-8 h-8 rounded-full flex items-center justify-center ${
step >= 1
? 'bg-primary text-primary-contrast'
: 'bg-background-secondary text-text-secondary border border-border'
}`}
>
1
</div>
<div
className={`ml-2 text-sm font-medium ${
step >= 1 ? 'text-primary' : 'text-text-muted'
}`}
>
{firstLabel}
</div>
</div>
<ChevronRight className="h-5 w-5 text-text-muted icon-flat" />
<div className="flex items-center">
<div
className={`w-8 h-8 rounded-full flex items-center justify-center ${
step >= 2
? 'bg-primary text-primary-contrast'
: 'bg-background-secondary text-text-secondary border border-border'
}`}
>
2
</div>
<div
className={`ml-2 text-sm font-medium ${
step >= 2 ? 'text-primary' : 'text-text-muted'
}`}
>
{secondLabel}
</div>
</div>
</div>
</div>
);
}

View File

@@ -14,10 +14,10 @@ interface BadgeProps {
}
const variantStyles: Record<BadgeVariant, string> = {
success: 'bg-emerald-900/30 text-emerald-300 border-emerald-700/60',
warning: 'bg-amber-900/30 text-amber-300 border-amber-700/60',
danger: 'bg-red-950/30 text-red-300 border-red-700/60',
default: 'bg-background-secondary text-text-secondary border-border',
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',
};
/** Explicit width + height so every row matches; flex centers label optically. */

View File

@@ -0,0 +1,36 @@
import type { ElementType, ReactNode } from 'react';
type CardPadding = 'none' | 'sm' | 'md' | 'lg';
type CardProps<T extends ElementType = 'div'> = {
children: ReactNode;
padding?: CardPadding;
as?: T;
className?: string;
} & Omit<React.ComponentPropsWithoutRef<T>, 'as' | 'children' | 'className'>;
const paddingClassMap: Record<CardPadding, string> = {
none: '',
sm: 'p-3',
md: 'p-4',
lg: 'p-6',
};
export function Card<T extends ElementType = 'div'>({
children,
as,
className = '',
padding = 'md',
...props
}: CardProps<T>) {
const Component = as ?? 'div';
return (
<Component
className={`rounded-[var(--radius-lg)] border border-card-border bg-card text-card-foreground ${paddingClassMap[padding]} ${className}`}
{...props}
>
{children}
</Component>
);
}

View File

@@ -0,0 +1,21 @@
'use client';
import { X } from 'lucide-react';
type DialogCloseButtonProps = {
onClick: () => void;
className?: string;
};
export function DialogCloseButton({ onClick, className = '' }: DialogCloseButtonProps) {
return (
<button
type="button"
onClick={onClick}
className={`shrink-0 rounded-[var(--radius-sm)] p-1.5 text-text-muted hover:text-text-primary hover:bg-background-secondary/80 focus:outline-none focus:ring-2 focus:ring-primary/35 ${className}`}
aria-label="Close"
>
<X className="h-5 w-5 icon-flat" />
</button>
);
}

View File

@@ -1,19 +1,17 @@
'use client';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { addCalendarDays, compareLocalDayStart } from '@/lib/appointmentTime';
import { addCalendarDays } from '@/lib/appointmentTime';
interface ScheduleDayPickerProps {
value: Date;
onChange: (day: Date) => void;
/** Inclusive minimum calendar day (typically today at local midnight). */
minDate: Date;
/** Optional lower bound; picker navigation is unrestricted for history browsing. */
minDate?: Date;
label?: string;
}
export function ScheduleDayPicker({ value, onChange, minDate, label = 'Schedule date' }: ScheduleDayPickerProps) {
const canGoPrev = compareLocalDayStart(value, minDate) > 0;
export function ScheduleDayPicker({ value, onChange, label = 'Schedule date' }: ScheduleDayPickerProps) {
const labelText = value.toLocaleDateString(undefined, {
weekday: 'short',
month: 'short',
@@ -27,9 +25,8 @@ export function ScheduleDayPicker({ value, onChange, minDate, label = 'Schedule
<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"
disabled={!canGoPrev}
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 disabled:opacity-35 disabled:pointer-events-none focus:outline-none focus:ring-2 focus:ring-primary/35"
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" />

View File

@@ -0,0 +1,26 @@
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>
);
}

View File

@@ -0,0 +1,144 @@
'use client';
import { Check, Copy } from 'lucide-react';
import { DialogCloseButton } from '@/components/ui/common/DialogCloseButton';
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';
function formatInvitationStatusLabel(status: OrganizationInvitationHistoryItemDto['status']): string {
if (status === 'PENDING') return 'Invitation pending';
if (status === 'ACTIVE') return 'Invitation Accepted';
if (status === 'REJECTED') return 'Invitation rejected';
if (status === 'EXPIRED') return 'Invitation expired';
return status;
}
function formatTableDate(value: string): string {
const d = new Date(value);
if (Number.isNaN(d.getTime())) return '—';
return d.toLocaleDateString();
}
type InvitationHistoryDialogProps = {
open: boolean;
onClose: () => void;
loading: boolean;
items: OrganizationInvitationHistoryItemDto[];
copiedId: string | null;
copyingInvitationId: string | null;
onCopy: (invitation: OrganizationInvitationHistoryItemDto) => void;
copyError?: string;
copySuccess?: string;
};
export function InvitationHistoryDialog({
open,
onClose,
loading,
items,
copiedId,
copyingInvitationId,
onCopy,
copyError,
copySuccess,
}: InvitationHistoryDialogProps) {
if (!open) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
<div
className="w-full max-w-[min(56rem,calc(100vw-17rem))] max-h-[90vh] overflow-y-auto rounded-[var(--radius-md)] border border-border bg-background-secondary p-6 shadow-xl space-y-4"
role="dialog"
aria-modal="true"
aria-labelledby="invitation-history-title"
>
<div className="flex items-start justify-between gap-3">
<h2 id="invitation-history-title" className="text-lg font-semibold text-text-primary pr-2">
Invitation History
</h2>
<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>
)}
{loading ? (
<p className="text-sm text-text-secondary">Loading invitation history...</p>
) : items.length === 0 ? (
<p className="text-sm text-text-secondary">No invitations yet.</p>
) : (
<Table
headers={
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
Organization
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
Owner email
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
Date
</th>
<th className="px-6 py-3 text-center text-xs font-medium text-text-muted uppercase tracking-wider">
Status
</th>
<th className="px-6 py-3 text-right text-xs font-medium text-text-muted uppercase tracking-wider">
Action
</th>
</tr>
}
body={
<>
{items.map((inv) => (
<tr key={inv.id} className="hover:bg-background-secondary/45">
<td className="px-6 py-1.5 text-sm text-text-primary">{inv.organizationName}</td>
<td className="px-6 py-1.5 text-sm text-text-secondary">{inv.ownerEmail}</td>
<td className="px-6 py-1.5 text-sm text-text-secondary">
{formatTableDate(inv.createdAt)}
</td>
<td className="px-6 py-1.5 text-center align-middle">
<Badge variant={organizationLinkStatusVariant(inv.status)} fixedWidth={false}>
{formatInvitationStatusLabel(inv.status)}
</Badge>
</td>
<td className="px-6 py-1.5 text-right align-middle">
{canShareOrganizationInviteLink(inv) ? (
<button
type="button"
className="p-2 rounded-md text-text-secondary hover:bg-background-card/80 hover:text-text-primary disabled:opacity-50"
disabled={copyingInvitationId === inv.id}
onClick={() => onCopy(inv)}
aria-label="Copy invitation link"
title="Copy invitation link (generates a new link if needed)"
>
{copiedId === inv.id ? (
<Check className="w-4 h-4" />
) : (
<Copy className="w-4 h-4" />
)}
</button>
) : (
<span className="text-xs text-text-muted"></span>
)}
</td>
</tr>
))}
</>
}
/>
)}
</div>
</div>
);
}

View File

@@ -2,6 +2,7 @@
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 type { TreatmentAppointment } from '@/types/treatment';
@@ -32,7 +33,7 @@ export function AppointmentsStrip({
}: AppointmentsStripProps) {
if (stripHidden) {
return (
<div className="surface-card p-3 flex items-center justify-between gap-3 flex-wrap">
<Card className="flex items-center justify-between gap-3 flex-wrap" padding="sm">
<p className="text-sm text-text-secondary">Appointments are hidden.</p>
<button
type="button"
@@ -41,12 +42,12 @@ export function AppointmentsStrip({
>
Show appointments
</button>
</div>
</Card>
);
}
return (
<div className="surface-card p-4 space-y-4">
<Card className="space-y-4">
<div className="flex items-center justify-between gap-3 flex-wrap">
<div className="flex items-center gap-2 min-w-0">
<CalendarDays className="w-5 h-5 text-text-muted shrink-0 icon-flat" aria-hidden />
@@ -89,12 +90,14 @@ export function AppointmentsStrip({
})}`;
const palette = purposeStyle(a.purpose);
return (
<button
<Card
as="button"
key={a.id}
type="button"
onClick={() => onSelectAppointment(a.id)}
padding="none"
className={`
text-left rounded-[var(--radius-sm)] border px-3 py-2 min-w-[200px] max-w-[280px] transition-shadow min-h-[52px]
text-left rounded-[var(--radius-sm)] px-3 py-2 min-w-[200px] max-w-[280px] transition-shadow min-h-[52px]
focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/45
${palette}
${sel ? 'ring-2 ring-primary ring-offset-2 ring-offset-background-secondary shadow-[inset_0_1px_0_rgba(255,255,255,0.06)]' : 'hover:brightness-110'}
@@ -105,10 +108,10 @@ export function AppointmentsStrip({
{a.patientFirstName} {a.patientLastName}
</p>
<p className="text-[11px] opacity-90 capitalize mt-0.5">{a.purpose}</p>
</button>
</Card>
);
})}
</div>
</div>
</Card>
);
}

View File

@@ -8,6 +8,7 @@ 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 {
fetchLinkedOrganizations,
@@ -325,7 +326,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
}
return (
<div className="space-y-6">
<div className="relative space-y-6 pb-24">
<header className="space-y-1">
<h1 className="text-2xl font-semibold text-text-primary">Treatment</h1>
<p className="text-sm text-text-secondary">
@@ -345,12 +346,6 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
loading={apptsLoading}
/>
{banner && (
<div className="rounded-[var(--radius-md)] border border-primary/40 bg-primary-soft px-4 py-2 text-sm text-text-primary">
{banner}
</div>
)}
<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 ? (
@@ -651,6 +646,14 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
</div>
</div>
</div>
{banner && (
<div className="fixed bottom-4 left-0 right-0 z-[70] px-4 pointer-events-none">
<div className="pointer-events-auto w-full">
<Toast variant="success">{banner}</Toast>
</div>
</div>
)}
</div>
);
}

View File

@@ -9,6 +9,8 @@ export interface CreateAppointmentBody {
purpose: string;
}
export type UpdateAppointmentBody = Partial<CreateAppointmentBody>;
export const appointmentsApi = {
columnProviders: async (): Promise<{ success: boolean; data: AppointmentColumnProvider[] }> => {
const response = await apiClient.get('/appointments/column-providers');
@@ -25,6 +27,14 @@ export const appointmentsApi = {
return response.data;
},
update: async (
id: string,
body: UpdateAppointmentBody,
): Promise<{ success: boolean; data: AppointmentRecord }> => {
const response = await apiClient.patch(`/appointments/${id}`, body);
return response.data;
},
remove: async (id: string): Promise<{ success: boolean }> => {
const response = await apiClient.delete(`/appointments/${id}`);
return response.data;

View File

@@ -15,6 +15,17 @@ export const apiClient = axios.create({
timeout: 10000,
});
/** Invitation preview/accept must work with no cookies (public API, no JWT). */
function isPublicInvitationRequest(url: string | undefined): boolean {
if (!url) return false;
return (
url.includes('/staff/invitations/preview') ||
url.includes('/staff/invitations/accept') ||
url.includes('/organizations/invitations/preview') ||
url.includes('/organizations/invitations/accept')
);
}
// ❌ REMOVE request interceptor completely (no Authorization header)
// ✅ Response interceptor
@@ -23,7 +34,11 @@ apiClient.interceptors.response.use(
async (error: AxiosError) => {
const originalRequest = error.config as CustomAxiosRequestConfig;
if (error.response?.status === 401 && !originalRequest._retry) {
if (
error.response?.status === 401 &&
!originalRequest._retry &&
!isPublicInvitationRequest(originalRequest.url)
) {
originalRequest._retry = true;
try {

View File

@@ -92,6 +92,7 @@ export const organizationApi = {
ownerEmail: string;
organizationName: string;
organizationType: 'CLINIC' | 'LAB';
organizationEmail?: string;
inviterOrganizationName: string;
expiresAt: string;
status: 'PENDING' | 'ACCEPTED';
@@ -106,6 +107,8 @@ export const organizationApi = {
acceptInvite: async (body: {
token: string;
organizationName: string;
organizationEmail: string;
organizationType: 'CLINIC' | 'LAB';
ownerName: string;
password: string;
}): Promise<{ success: boolean; message: string; data: { organizationId: string } }> => {

View File

@@ -63,6 +63,21 @@ export const staffApi = {
return response.data;
},
getInvitationLink: async (
membershipId: string,
): Promise<{
success: boolean;
data: {
membershipId: string;
invitationId: string;
email: string;
invitationUrl: string;
};
}> => {
const response = await apiClient.post(`/staff/members/${membershipId}/invitation-link`);
return response.data;
},
previewInvite: async (token: string): Promise<PreviewInviteResponse> => {
const response = await apiClient.get(`/staff/invitations/preview?token=${encodeURIComponent(token)}`);
return response.data;

View File

@@ -0,0 +1,107 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import {
organizationApi,
type OrganizationInvitationHistoryItemDto,
} from '@/lib/api/organization';
import {
canShareOrganizationInviteLink,
readOrganizationInviteLinks,
type StoredOrganizationInviteLink,
writeOrganizationInviteLinks,
} from '@/components/invitations/organizationInviteLinks';
export function useOrganizationInviteLinkCopy(organizationId: string | undefined) {
const [pendingInviteLinks, setPendingInviteLinks] = useState<
Record<string, StoredOrganizationInviteLink>
>({});
const [copiedId, setCopiedId] = useState<string | null>(null);
const [copyingInvitationId, setCopyingInvitationId] = useState<string | null>(null);
useEffect(() => {
if (!organizationId) return;
setPendingInviteLinks(readOrganizationInviteLinks(organizationId));
}, [organizationId]);
const storeInviteLink = useCallback(
(invitationId: string, ownerEmail: string, invitationUrl: string) => {
if (!organizationId) return;
setPendingInviteLinks((prev) => {
const next = {
...prev,
[invitationId]: {
invitationId,
ownerEmail: ownerEmail.trim().toLowerCase(),
invitationUrl,
},
};
writeOrganizationInviteLinks(organizationId, next);
return next;
});
},
[organizationId],
);
const pruneAcceptedLinks = useCallback(
(items: OrganizationInvitationHistoryItemDto[]) => {
if (!organizationId) return;
const acceptedIds = new Set(
items.filter((item) => item.acceptedAt || item.status === 'ACTIVE').map((item) => item.id),
);
setPendingInviteLinks((prev) => {
let changed = false;
const next = { ...prev };
for (const id of Object.keys(next)) {
if (acceptedIds.has(id)) {
delete next[id];
changed = true;
}
}
if (changed) {
writeOrganizationInviteLinks(organizationId, next);
}
return changed ? next : prev;
});
},
[organizationId],
);
const copyInvitationLink = useCallback(
async (
invitation: OrganizationInvitationHistoryItemDto,
options?: { onRegenerated?: () => void | Promise<void> },
): Promise<string | null> => {
if (!canShareOrganizationInviteLink(invitation)) return null;
setCopyingInvitationId(invitation.id);
try {
let invitationUrl = pendingInviteLinks[invitation.id]?.invitationUrl;
if (!invitationUrl || invitation.status === 'EXPIRED') {
const res = await organizationApi.getInvitationLink(invitation.id);
invitationUrl = res.data.invitationUrl;
storeInviteLink(invitation.id, invitation.ownerEmail, invitationUrl);
await options?.onRegenerated?.();
}
await navigator.clipboard.writeText(invitationUrl);
setCopiedId(invitation.id);
setTimeout(() => setCopiedId(null), 1500);
return invitationUrl;
} finally {
setCopyingInvitationId(null);
}
},
[pendingInviteLinks, storeInviteLink],
);
return {
pendingInviteLinks,
copiedId,
copyingInvitationId,
storeInviteLink,
copyInvitationLink,
pruneAcceptedLinks,
};
}

View File

@@ -1,7 +1,17 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const publicRoutes = ['/', '/login', '/register', '/terms', '/privacy', '/forgot-password'];
/** Routes that must work without an existing session (first-time invitees). */
const publicRoutes = [
'/',
'/login',
'/register',
'/terms',
'/privacy',
'/forgot-password',
'/accept-invite',
'/accept-organization-invite',
];
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;

View File

@@ -18,6 +18,40 @@
--color-border: #d2dcec;
--color-border-strong: #aec0de;
--color-card-background: #ffffff;
--color-card-foreground: #0f172a;
--color-card-muted: #475569;
--color-card-border: #d2dcec;
--color-badge-default-bg: #edf3fb;
--color-badge-default-fg: #1e293b;
--color-badge-default-border: #c9d8ec;
--color-badge-success-bg: #e6f7ef;
--color-badge-success-fg: #14532d;
--color-badge-success-border: #98d8b5;
--color-badge-warning-bg: #fff4df;
--color-badge-warning-fg: #92400e;
--color-badge-warning-border: #f6c88b;
--color-badge-danger-bg: #ffe8e8;
--color-badge-danger-fg: #991b1b;
--color-badge-danger-border: #f2b0b0;
--color-purpose-consultation-bg: #f1eafe;
--color-purpose-consultation-fg: #5b21b6;
--color-purpose-consultation-border: #cfb8f7;
--color-purpose-filling-bg: #fff1e5;
--color-purpose-filling-fg: #9a3412;
--color-purpose-filling-border: #f8c9a6;
--color-purpose-endo-bg: #ffe9e9;
--color-purpose-endo-fg: #991b1b;
--color-purpose-endo-border: #f4b6b6;
--color-purpose-visit-bg: #e7f4ff;
--color-purpose-visit-fg: #0c4a6e;
--color-purpose-visit-border: #abd8f3;
--color-purpose-hygiene-bg: #effadf;
--color-purpose-hygiene-fg: #3f6212;
--color-purpose-hygiene-border: #cbe9a1;
--color-primary: #009cae;
--color-primary-contrast: #031014;
--color-primary-soft: rgba(0, 156, 174, 0.16);
@@ -42,6 +76,40 @@
--color-border: #29456a;
--color-border-strong: #3b5f8f;
--color-card-background: #14253d;
--color-card-foreground: #f5f9ff;
--color-card-muted: #b6c6dd;
--color-card-border: #29456a;
--color-badge-default-bg: rgba(27, 47, 78, 0.32);
--color-badge-default-fg: #9eb1cb;
--color-badge-default-border: rgba(59, 95, 143, 0.32);
--color-badge-success-bg: rgba(6, 78, 59, 0.22);
--color-badge-success-fg: #7dd3a8;
--color-badge-success-border: rgba(34, 100, 68, 0.28);
--color-badge-warning-bg: rgba(120, 53, 15, 0.22);
--color-badge-warning-fg: #dfc06a;
--color-badge-warning-border: rgba(146, 88, 20, 0.28);
--color-badge-danger-bg: rgba(127, 29, 29, 0.22);
--color-badge-danger-fg: #e4a6a6;
--color-badge-danger-border: rgba(153, 50, 50, 0.28);
--color-purpose-consultation-bg: rgba(139, 92, 246, 0.25);
--color-purpose-consultation-fg: #ddd6fe;
--color-purpose-consultation-border: rgba(167, 139, 250, 0.5);
--color-purpose-filling-bg: rgba(249, 115, 22, 0.25);
--color-purpose-filling-fg: #fed7aa;
--color-purpose-filling-border: rgba(251, 146, 60, 0.5);
--color-purpose-endo-bg: rgba(239, 68, 68, 0.25);
--color-purpose-endo-fg: #fecaca;
--color-purpose-endo-border: rgba(248, 113, 113, 0.5);
--color-purpose-visit-bg: rgba(14, 165, 233, 0.25);
--color-purpose-visit-fg: #bae6fd;
--color-purpose-visit-border: rgba(56, 189, 248, 0.5);
--color-purpose-hygiene-bg: rgba(132, 204, 22, 0.2);
--color-purpose-hygiene-fg: #d9f99d;
--color-purpose-hygiene-border: rgba(163, 230, 53, 0.45);
--color-primary: #09a9bc;
--color-primary-contrast: #001117;
--color-primary-soft: rgba(9, 169, 188, 0.2);
@@ -66,6 +134,40 @@
--color-border: #29456a;
--color-border-strong: #3b5f8f;
--color-card-background: #14253d;
--color-card-foreground: #f5f9ff;
--color-card-muted: #b6c6dd;
--color-card-border: #29456a;
--color-badge-default-bg: rgba(27, 47, 78, 0.32);
--color-badge-default-fg: #9eb1cb;
--color-badge-default-border: rgba(59, 95, 143, 0.32);
--color-badge-success-bg: rgba(6, 78, 59, 0.22);
--color-badge-success-fg: #7dd3a8;
--color-badge-success-border: rgba(34, 100, 68, 0.28);
--color-badge-warning-bg: rgba(120, 53, 15, 0.22);
--color-badge-warning-fg: #dfc06a;
--color-badge-warning-border: rgba(146, 88, 20, 0.28);
--color-badge-danger-bg: rgba(127, 29, 29, 0.22);
--color-badge-danger-fg: #e4a6a6;
--color-badge-danger-border: rgba(153, 50, 50, 0.28);
--color-purpose-consultation-bg: rgba(139, 92, 246, 0.25);
--color-purpose-consultation-fg: #ddd6fe;
--color-purpose-consultation-border: rgba(167, 139, 250, 0.5);
--color-purpose-filling-bg: rgba(249, 115, 22, 0.25);
--color-purpose-filling-fg: #fed7aa;
--color-purpose-filling-border: rgba(251, 146, 60, 0.5);
--color-purpose-endo-bg: rgba(239, 68, 68, 0.25);
--color-purpose-endo-fg: #fecaca;
--color-purpose-endo-border: rgba(248, 113, 113, 0.5);
--color-purpose-visit-bg: rgba(14, 165, 233, 0.25);
--color-purpose-visit-fg: #bae6fd;
--color-purpose-visit-border: rgba(56, 189, 248, 0.5);
--color-purpose-hygiene-bg: rgba(132, 204, 22, 0.2);
--color-purpose-hygiene-fg: #d9f99d;
--color-purpose-hygiene-border: rgba(163, 230, 53, 0.45);
--color-primary: #09a9bc;
--color-primary-contrast: #001117;
--color-primary-soft: rgba(9, 169, 188, 0.2);
@@ -89,6 +191,37 @@
--color-border: var(--color-border);
--color-border-strong: var(--color-border-strong);
--color-card: var(--color-card-background);
--color-card-foreground: var(--color-card-foreground);
--color-card-muted: var(--color-card-muted);
--color-card-border: var(--color-card-border);
--color-badge-default-bg: var(--color-badge-default-bg);
--color-badge-default-fg: var(--color-badge-default-fg);
--color-badge-default-border: var(--color-badge-default-border);
--color-badge-success-bg: var(--color-badge-success-bg);
--color-badge-success-fg: var(--color-badge-success-fg);
--color-badge-success-border: var(--color-badge-success-border);
--color-badge-warning-bg: var(--color-badge-warning-bg);
--color-badge-warning-fg: var(--color-badge-warning-fg);
--color-badge-warning-border: var(--color-badge-warning-border);
--color-badge-danger-bg: var(--color-badge-danger-bg);
--color-badge-danger-fg: var(--color-badge-danger-fg);
--color-badge-danger-border: var(--color-badge-danger-border);
--color-purpose-consultation-bg: var(--color-purpose-consultation-bg);
--color-purpose-consultation-fg: var(--color-purpose-consultation-fg);
--color-purpose-consultation-border: var(--color-purpose-consultation-border);
--color-purpose-filling-bg: var(--color-purpose-filling-bg);
--color-purpose-filling-fg: var(--color-purpose-filling-fg);
--color-purpose-filling-border: var(--color-purpose-filling-border);
--color-purpose-endo-bg: var(--color-purpose-endo-bg);
--color-purpose-endo-fg: var(--color-purpose-endo-fg);
--color-purpose-endo-border: var(--color-purpose-endo-border);
--color-purpose-visit-bg: var(--color-purpose-visit-bg);
--color-purpose-visit-fg: var(--color-purpose-visit-fg);
--color-purpose-visit-border: var(--color-purpose-visit-border);
--color-purpose-hygiene-bg: var(--color-purpose-hygiene-bg);
--color-purpose-hygiene-fg: var(--color-purpose-hygiene-fg);
--color-purpose-hygiene-border: var(--color-purpose-hygiene-border);
--color-primary: var(--color-primary);
--color-primary-contrast: var(--color-primary-contrast);
--color-primary-soft: var(--color-primary-soft);
@@ -115,11 +248,17 @@ body {
}
.surface-card {
background: color-mix(in srgb, var(--color-background-card) 92%, transparent);
border: 1px solid var(--color-border);
background: color-mix(in srgb, var(--color-card-background) 92%, transparent);
border: 1px solid var(--color-card-border);
color: var(--color-card-foreground);
border-radius: var(--radius-lg);
}
:root[data-theme='dark'] .surface-card,
:root:not([data-theme='light']) .surface-card {
background: color-mix(in srgb, var(--color-card-background) 82%, var(--color-background-primary));
}
.surface-panel {
background: color-mix(in srgb, var(--color-background-secondary) 96%, transparent);
border: 1px solid var(--color-border);

View File

@@ -12,9 +12,13 @@ DOMAIN=dyolink.com
# Backend Environment (create backend.env from this)
# NODE_ENV=production
# JWT_SECRET=CHANGE_THIS_TO_STRONG_SECRET_32_CHARS
# PORT=3000
# DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}
# CORS_ORIGIN=https://dyolink.com
# JWT_SECRET=CHANGE_THIS_TO_STRONG_SECRET_32_CHARS
# JWT_EXPIRES_IN=15m
# JWT_REFRESH_SECRET=another_long_random_secret_different_from_JWT_SECRET
# JWT_REFRESH_EXPIRES_IN=30d
# FRONTEND_URL=https://dyolink.com
# Frontend Environment (create frontend.env from this)
# NEXT_PUBLIC_API_URL=/api

View File

@@ -9,4 +9,5 @@ JWT_EXPIRES_IN=15m
JWT_REFRESH_SECRET=another_long_random_secret_different_from_JWT_SECRET
JWT_REFRESH_EXPIRES_IN=30d
# CORS, cookies, and invite links — must match how users open the app (nginx host port)
FRONTEND_URL=http://178.131.50.201:8088