Compare commits

..

4 Commits

34 changed files with 1204 additions and 439 deletions

View File

@@ -1,23 +1,41 @@
# Database # 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_PORT=5432
POSTGRES_USER=dyolink_user POSTGRES_USER=dyolink_user
POSTGRES_PASSWORD=CHANGE_ME_IN_PRODUCTION POSTGRES_PASSWORD=password
POSTGRES_DB=dyolink_db 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_SECRET=CHANGE_ME_TO_A_STRONG_SECRET_32_CHARS_MIN
JWT_EXPIRES_IN=7d JWT_EXPIRES_IN=7d
JWT_REFRESH_SECRET=CHANGE_ME_TO_ANOTHER_STRONG_SECRET
JWT_REFRESH_EXPIRES_IN=30d
# Application # Application
PORT=3000 PORT=3000
NODE_ENV=development NODE_ENV=development
API_PREFIX=/api 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) # Email (configure for production)
SMTP_HOST=smtp.gmail.com SMTP_HOST=smtp.gmail.com
SMTP_PORT=587 SMTP_PORT=587
SMTP_USER=your_email@gmail.com SMTP_USER=your_email@gmail.com
SMTP_PASSWORD=your_app_password SMTP_PASSWORD=your_app_password

View File

@@ -3,7 +3,7 @@
## Prerequisites ## Prerequisites
- **Node.js 20+** and **npm** - **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 ## First-time setup
@@ -28,9 +28,23 @@
- `JWT_SECRET` — strong secret for signing tokens - `JWT_SECRET` — strong secret for signing tokens
Do not commit `.env`. 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** 5. **Generate Prisma Client**
@@ -46,12 +60,43 @@
This runs `prisma migrate dev`. Use it during development when the schema changes. 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 ```bash
npm run prisma:seed 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) ## Run (development)
```bash ```bash
@@ -60,7 +105,7 @@ npm run start:dev
API listens on **`http://localhost:3000`** by default (`PORT` in `.env`). 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` ## After pulling latest `main`
@@ -71,7 +116,7 @@ npm run prisma:generate
npm run prisma:migrate 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 ## 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:generate` | Regenerate client after `schema.prisma` changes |
| `npm run prisma:migrate` | Dev migrations (`migrate dev`) | | `npm run prisma:migrate` | Dev migrations (`migrate dev`) |
| `npm run prisma:deploy` | Production-style apply (`migrate deploy`) — e.g. CI/containers | | `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 build` | Compile Nest app |
| `npm run start:prod` | Run compiled app (`node dist/main`) | | `npm run start:prod` | Run compiled app (`node dist/main`) |
## Docker ## 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 // 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 { export interface Config {
port: number; port: number;
database: { database: {
@@ -7,6 +39,8 @@ export interface Config {
jwt: { jwt: {
secret: string; secret: string;
expiresIn: string; expiresIn: string;
refreshSecret: string;
refreshExpiresIn: string;
}; };
throttle: { throttle: {
ttl: number; ttl: number;
@@ -24,9 +58,10 @@ export default (): Config => {
return value; 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 => { 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 => { const getEnvVarAsNumber = (key: string, defaultValue: number): number => {
@@ -36,14 +71,30 @@ export default (): Config => {
return isNaN(parsed) ? defaultValue : parsed; 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 { return {
port: getEnvVarAsNumber('PORT', 3000), port: getEnvVarAsNumber('PORT', 3000),
database: { database: {
url: getEnvVar('DATABASE_URL'), url: getEnvVar('DATABASE_URL'),
}, },
jwt: { jwt: {
secret: getEnvVar('JWT_SECRET'), secret: jwtSecret,
expiresIn: getEnvVarWithDefault('JWT_EXPIRES_IN', '7d'), expiresIn: jwtExpiresIn,
refreshSecret: jwtRefreshSecret,
refreshExpiresIn: jwtRefreshExpiresIn,
}, },
throttle: { throttle: {
ttl: getEnvVarAsNumber('THROTTLE_TTL', 60), ttl: getEnvVarAsNumber('THROTTLE_TTL', 60),

View File

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

View File

@@ -17,7 +17,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
return req?.cookies?.accessToken; // ✅ READ FROM COOKIE return req?.cookies?.accessToken; // ✅ READ FROM COOKIE
}, },
ignoreExpiration: false, 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 { export class AcceptOrganizationInviteDto {
@IsString() @IsString()
@@ -9,6 +9,12 @@ export class AcceptOrganizationInviteDto {
@MinLength(1) @MinLength(1)
organizationName: string; organizationName: string;
@IsEmail()
organizationEmail: string;
@IsEnum(['CLINIC', 'LAB'])
organizationType: 'CLINIC' | 'LAB';
@IsString() @IsString()
@MinLength(1) @MinLength(1)
ownerName: string; ownerName: string;

View File

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

View File

@@ -55,6 +55,19 @@ export class StaffController {
return this.staffService.invite(req.user.id, organizationId, dto); 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') @Patch('members/:membershipId')
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@ApiOperation({ summary: 'Update staff member name and/or permissions' }) @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) { async previewInvite(token: string) {
const invitation = await this.findValidInvitation(token); const invitation = await this.findValidInvitation(token);
const org = invitation.membership.organization; const org = invitation.membership.organization;
@@ -383,7 +439,8 @@ export class StaffService {
if (m.isOwner || m.isActive) return 'ACTIVE'; if (m.isOwner || m.isActive) return 'ACTIVE';
const invitation = m.invitations[0]; const invitation = m.invitations[0];
if (!invitation) return 'EXPIRED'; 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'; 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* .pnpm-debug.log*
# env files (can opt-in for committing if needed) # env files (can opt-in for committing if needed)
.env* .env
.env.*
!.env.example
# vercel # vercel
.vercel .vercel

View File

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

View File

@@ -1,14 +1,16 @@
'use client'; 'use client';
import { useEffect, useState } from 'react'; 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 { useAuth } from '@/lib/hooks/useAuth';
import { useOrganizationInviteLinkCopy } from '@/lib/hooks/useOrganizationInviteLinkCopy';
import { import {
organizationApi, organizationApi,
type CounterpartItemDto, type CounterpartItemDto,
type CounterpartSearchResultDto, type CounterpartSearchResultDto,
type OrganizationInvitationHistoryItemDto, type OrganizationInvitationHistoryItemDto,
} from '@/lib/api/organization'; } from '@/lib/api/organization';
import { InvitationHistoryDialog } from '@/components/ui/organizations/InvitationHistoryDialog';
import { Button } from '@/components/ui/common/Button'; import { Button } from '@/components/ui/common/Button';
import { Badge, organizationLinkStatusVariant } from '@/components/ui/common/Badge'; import { Badge, organizationLinkStatusVariant } from '@/components/ui/common/Badge';
import { Input } from '@/components/ui/common/Input'; 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 { Table } from '@/components/ui/common/Table';
import type { ApiError } from '@/types/api'; 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 { function formatOrganizationStatusLabel(status: string): string {
if (!status) return status; if (!status) return status;
const lower = status.toLowerCase(); const lower = status.toLowerCase();
@@ -56,13 +31,6 @@ function formatLinkStatusLabel(status: CounterpartItemDto['status']): string {
return formatOrganizationStatusLabel(status); return formatOrganizationStatusLabel(status);
} }
function formatInvitationStatusLabel(status: OrganizationInvitationHistoryItemDto['status']): string {
if (status === 'PENDING') return 'Invitation pending';
if (status === 'ACTIVE') return 'Invitation Accepted';
if (status === 'REJECTED') return 'Invitation rejected';
return formatOrganizationStatusLabel(status);
}
function formatApiMessage(err: unknown): string { function formatApiMessage(err: unknown): string {
if (!err || typeof err !== 'object') return 'Something went wrong'; if (!err || typeof err !== 'object') return 'Something went wrong';
const m = (err as ApiError).message; const m = (err as ApiError).message;
@@ -73,7 +41,7 @@ function formatApiMessage(err: unknown): string {
function formatTableDate(value: string): string { function formatTableDate(value: string): string {
const d = new Date(value); const d = new Date(value);
if (Number.isNaN(d.getTime())) return ''; if (Number.isNaN(d.getTime())) return '—';
return d.toLocaleDateString(); return d.toLocaleDateString();
} }
@@ -96,12 +64,20 @@ export default function OrganizationsPage() {
const [manualOrganizationName, setManualOrganizationName] = useState(''); const [manualOrganizationName, setManualOrganizationName] = useState('');
const [manualOwnerEmail, setManualOwnerEmail] = useState(''); const [manualOwnerEmail, setManualOwnerEmail] = useState('');
const [inviteLoading, setInviteLoading] = useState(false); 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 [showInviteForm, setShowInviteForm] = useState(false);
const [historyOpen, setHistoryOpen] = useState(false); const [historyOpen, setHistoryOpen] = useState(false);
const [historyLoading, setHistoryLoading] = useState(false); const [historyLoading, setHistoryLoading] = useState(false);
const [historyItems, setHistoryItems] = useState<OrganizationInvitationHistoryItemDto[]>([]); 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 counterpartLabel = currentOrganization?.type === 'LAB' ? 'Clinic' : 'Lab';
const tabLabel = currentOrganization?.type === 'LAB' ? 'Clinics' : 'Labs'; 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(() => { useEffect(() => {
void loadList(); void loadList();
}, []); }, []);
@@ -185,18 +156,7 @@ export default function OrganizationsPage() {
organizationName: manualOrganizationName.trim(), organizationName: manualOrganizationName.trim(),
ownerEmail: manualOwnerEmail.trim(), ownerEmail: manualOwnerEmail.trim(),
}); });
if (currentOrganization?.id) { storeInviteLink(res.data.invitationId, manualOwnerEmail, res.data.invitationUrl);
const nextLinks = {
...pendingInviteLinks,
[res.data.invitationId]: {
invitationId: res.data.invitationId,
ownerEmail: manualOwnerEmail.trim().toLowerCase(),
invitationUrl: res.data.invitationUrl,
},
};
setPendingInviteLinks(nextLinks);
writeStoredInviteLinks(currentOrganization.id, nextLinks);
}
setSuccess(`Invitation link created for ${manualOwnerEmail.trim()}`); setSuccess(`Invitation link created for ${manualOwnerEmail.trim()}`);
setManualOrganizationName(''); setManualOrganizationName('');
setManualOwnerEmail(''); 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() { async function openInvitationHistory() {
setHistoryOpen(true); setHistoryOpen(true);
setHistoryLoading(true); setHistoryLoading(true);
setHistoryCopyError('');
setHistoryCopySuccess('');
setError(''); setError('');
try { try {
const res = await organizationApi.listInvitations(); await loadInvitationHistory();
setHistoryItems(res.data.items);
} catch (e) { } catch (e) {
setError(formatApiMessage(e)); setError(formatApiMessage(e));
} finally { } 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') { async function respondToPendingLink(linkId: string, action: 'ACCEPT' | 'REJECT') {
setRequestLinkRowId(linkId); setRequestLinkRowId(linkId);
setError(''); 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() { function clearSearchView() {
setMode('existing'); setMode('existing');
setQuery(''); setQuery('');
@@ -516,87 +471,21 @@ export default function OrganizationsPage() {
} }
/> />
{historyOpen && ( <InvitationHistoryDialog
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50"> open={historyOpen}
<div onClose={() => {
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" setHistoryOpen(false);
role="dialog" setHistoryCopyError('');
aria-modal="true" setHistoryCopySuccess('');
> }}
<div className="flex items-center justify-between"> loading={historyLoading}
<h2 className="text-lg font-semibold text-text-primary">Invitation History</h2> items={historyItems}
<Button type="button" size="sm" onClick={() => setHistoryOpen(false)}> copiedId={copiedId}
Close copyingInvitationId={copyingInvitationId}
</Button> onCopy={(invitation) => void handleHistoryCopy(invitation)}
</div> copyError={historyCopyError}
copySuccess={historyCopySuccess}
{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>
)}
</div> </div>
); );
} }

View File

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

View File

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

View File

@@ -3,15 +3,45 @@
import { Suspense, useEffect, useMemo, useState } from 'react'; import { Suspense, useEffect, useMemo, useState } from 'react';
import Link from 'next/link'; import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation'; 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 { Button } from '@/components/ui/common/Button';
import { Input } from '@/components/ui/common/Input'; 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'; 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() { function AcceptOrganizationInviteContent() {
const params = useSearchParams(); const params = useSearchParams();
const router = useRouter(); const router = useRouter();
const token = useMemo(() => params.get('token') || '', [params]); const token = useMemo(() => params.get('token') || '', [params]);
const [step, setStep] = useState(1);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState(''); const [error, setError] = useState('');
@@ -20,15 +50,29 @@ function AcceptOrganizationInviteContent() {
ownerEmail: string; ownerEmail: string;
organizationName: string; organizationName: string;
organizationType: 'CLINIC' | 'LAB'; organizationType: 'CLINIC' | 'LAB';
organizationEmail?: string;
inviterOrganizationName: string; inviterOrganizationName: string;
expiresAt: string; expiresAt: string;
status: 'PENDING' | 'ACCEPTED'; status: 'PENDING' | 'ACCEPTED';
} | null>(null); } | null>(null);
const [ownerName, setOwnerName] = useState(''); const {
const [organizationName, setOrganizationName] = useState(''); register,
const [password, setPassword] = useState(''); handleSubmit,
const [confirmPassword, setConfirmPassword] = useState(''); watch,
trigger,
setValue,
reset,
formState: { errors },
} = useForm<AcceptOrganizationInviteForm>({
resolver: zodResolver(acceptOrganizationInviteSchema),
mode: 'onChange',
defaultValues: {
organizationType: undefined,
},
});
const organizationType = watch('organizationType');
useEffect(() => { useEffect(() => {
if (!token) { if (!token) {
@@ -43,102 +87,168 @@ function AcceptOrganizationInviteContent() {
try { try {
const res = await organizationApi.previewInvite(token); const res = await organizationApi.previewInvite(token);
setInviteInfo(res.data); 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') { if (res.data.status === 'ACCEPTED') {
setSuccess('This invitation is already accepted. You can log in now.'); setSuccess('This invitation is already accepted. You can log in now.');
} }
} catch (e: any) { } catch (e: unknown) {
setError(e?.message || 'Could not load invitation'); const message = e && typeof e === 'object' && 'message' in e ? String(e.message) : '';
setError(message || 'Could not load invitation');
} finally { } finally {
setLoading(false); 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; if (!token) return;
setError(''); setError('');
setSuccess(''); 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); setSubmitting(true);
try { try {
await organizationApi.acceptInvite({ await organizationApi.acceptInvite({
token, token,
ownerName: ownerName.trim(), ownerName: data.ownerName.trim(),
organizationName: organizationName.trim(), password: data.password,
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); setTimeout(() => router.replace('/login'), 1000);
} catch (e: any) { } catch (e: unknown) {
setError(e?.message || 'Could not accept invitation'); const message = e && typeof e === 'object' && 'message' in e ? String(e.message) : '';
setError(message || 'Could not accept invitation');
} finally { } finally {
setSubmitting(false); setSubmitting(false);
} }
} };
return ( return (
<div className="min-h-screen app-web-bg flex items-center justify-center p-4"> <div className="min-h-screen app-web-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8">
<div className="w-full max-w-md surface-card p-6 space-y-5"> <div className="sm:mx-auto sm:w-full sm:max-w-md">
<h1 className="text-xl font-semibold text-text-primary">Accept organization invitation</h1> <Link href="/" className="flex justify-center">
{loading ? ( <span className="text-3xl font-semibold text-text-primary">DyoLink</span>
<p className="text-sm text-text-secondary">Loading invitation...</p> </Link>
) : ( <h2 className="mt-6 text-center text-2xl font-semibold text-text-primary">
<> Accept organization invitation
{inviteInfo && ( </h2>
<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 className="mt-2 text-center text-sm text-text-secondary">
<p> Already have an account?{' '}
Invited by: <span className="text-text-primary">{inviteInfo.inviterOrganizationName}</span> <Link href="/login" className="font-medium text-primary hover:opacity-90">
</p> Sign in
<p> </Link>
Owner email: <span className="text-text-primary">{inviteInfo.ownerEmail}</span> </p>
</p> </div>
</div>
)} <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
{error && ( <div className="surface-card py-8 px-4 sm:px-10">
<div className="rounded-[var(--radius-md)] border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300"> {loading ? (
{error} <p className="text-sm text-text-secondary">Loading invitation...</p>
</div> ) : (
)} <>
{success && ( {inviteInfo && (
<div className="rounded-[var(--radius-md)] border border-primary/30 bg-primary-soft/40 px-3 py-2 text-sm text-text-primary"> <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">
{success} <p>
</div> Invited by:{' '}
)} <span className="text-text-primary">{inviteInfo.inviterOrganizationName}</span>
{inviteInfo?.status !== 'ACCEPTED' && ( </p>
<div className="space-y-3"> </div>
<Input label="Owner name" value={ownerName} onChange={(e) => setOwnerName(e.target.value)} /> )}
<Input
label="Organization name" {inviteInfo?.status !== 'ACCEPTED' && (
value={organizationName} <RegistrationProgressSteps step={step} />
onChange={(e) => setOrganizationName(e.target.value)} )}
/>
<Input {error && (
label="Create password" <div className="mb-4 p-3 bg-red-950/30 border border-red-600/40 rounded-[var(--radius-md)]">
type="password" <p className="text-sm text-red-600">{error}</p>
value={password} </div>
onChange={(e) => setPassword(e.target.value)} )}
/> {success && (
<Input <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">
label="Confirm password" {success}
type="password" </div>
value={confirmPassword} )}
onChange={(e) => setConfirmPassword(e.target.value)}
/> {inviteInfo?.status !== 'ACCEPTED' && (
<Button type="button" fullWidth isLoading={submitting} onClick={() => void onAccept()}> <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
Activate organization {step === 1 && (
</Button> <>
</div> <Input
)} label="Owner email"
<p className="text-xs text-text-muted"> value={inviteInfo?.ownerEmail ?? ''}
Already have access? <Link href="/login" className="text-primary">Go to login</Link> readOnly
</p> 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>
</div> </div>
); );

View File

@@ -5,8 +5,10 @@ import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod'; import * as z from 'zod';
import Link from 'next/link'; 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 { 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 { Button } from '@/components/ui/common/Button';
import { Input } from '@/components/ui/common/Input'; import { Input } from '@/components/ui/common/Input';
const registerSchema = z.object({ const registerSchema = z.object({
@@ -89,31 +91,7 @@ export default function RegisterPage() {
</div> </div>
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md"> <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"> <div className="surface-card py-8 px-4 sm:px-10">
{/* Progress Steps */} <RegistrationProgressSteps step={step} />
<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>
{/* Trial Info Banner */} {/* Trial Info Banner */}
<div className="mb-6 p-4 bg-primary-soft rounded-[var(--radius-md)] border border-primary/35"> <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 <h3 className="text-sm font-medium text-text-primary mb-2">Your trial
@@ -177,57 +155,12 @@ export default function RegisterPage() {
)} )}
{step === 2 && ( {step === 2 && (
<> <>
<Input <OrganizationDetailsFields
label="Organization name" register={register as never}
{...register('organizationName')} errors={errors as never}
placeholder="Sunshine Dental Clinic" organizationType={organizationType}
error={errors.organizationName?.message} setValue={setValue as never}
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>
{error && ( {error && (
<div className="p-3 bg-red-950/30 border border-red-600/40 rounded-[var(--radius-md)]"> <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> <p className="text-sm text-red-600">{error}</p>

View File

@@ -1,6 +1,6 @@
'use client'; 'use client';
import { OrganizationSelectorContent } from '@/components/ui/organization/OrganizationSelectorContent'; import { OrganizationSelectorContent } from '@/components/ui/organizations/OrganizationSelectorContent';
export default function SelectOrganizationPage() { export default function SelectOrganizationPage() {
return ( 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,8 +1,8 @@
'use client'; 'use client';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { X } from 'lucide-react';
import { Button } from '@/components/ui/common/Button'; import { Button } from '@/components/ui/common/Button';
import { DialogCloseButton } from '@/components/ui/common/DialogCloseButton';
import { Dropdown } from '@/components/ui/common/Dropdown'; import { Dropdown } from '@/components/ui/common/Dropdown';
import type { AppointmentPurpose, AppointmentRecord } from '@/types/appointment'; import type { AppointmentPurpose, AppointmentRecord } from '@/types/appointment';
import { APPOINTMENT_PURPOSE_LABEL } from '@/components/ui/appointments/appointmentPurposeStyles'; import { APPOINTMENT_PURPOSE_LABEL } from '@/components/ui/appointments/appointmentPurposeStyles';
@@ -161,14 +161,7 @@ export function AppointmentBookingModal({
<h2 id="appointment-modal-title" className="text-lg font-semibold text-text-primary pr-2"> <h2 id="appointment-modal-title" className="text-lg font-semibold text-text-primary pr-2">
{editingAppointment ? 'Edit appointment' : 'New appointment'} {editingAppointment ? 'Edit appointment' : 'New appointment'}
</h2> </h2>
<button <DialogCloseButton onClick={onClose} />
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>
</div> </div>
<p className="text-sm text-text-secondary"> <p className="text-sm text-text-secondary">

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

@@ -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

@@ -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

@@ -15,6 +15,17 @@ export const apiClient = axios.create({
timeout: 10000, 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) // ❌ REMOVE request interceptor completely (no Authorization header)
// ✅ Response interceptor // ✅ Response interceptor
@@ -23,7 +34,11 @@ apiClient.interceptors.response.use(
async (error: AxiosError) => { async (error: AxiosError) => {
const originalRequest = error.config as CustomAxiosRequestConfig; 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; originalRequest._retry = true;
try { try {

View File

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

View File

@@ -63,6 +63,21 @@ export const staffApi = {
return response.data; 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> => { previewInvite: async (token: string): Promise<PreviewInviteResponse> => {
const response = await apiClient.get(`/staff/invitations/preview?token=${encodeURIComponent(token)}`); const response = await apiClient.get(`/staff/invitations/preview?token=${encodeURIComponent(token)}`);
return response.data; 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 { NextResponse } from 'next/server';
import type { NextRequest } 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) { export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl; const { pathname } = request.nextUrl;

View File

@@ -81,18 +81,18 @@
--color-card-muted: #b6c6dd; --color-card-muted: #b6c6dd;
--color-card-border: #29456a; --color-card-border: #29456a;
--color-badge-default-bg: #1b2f4e; --color-badge-default-bg: rgba(27, 47, 78, 0.32);
--color-badge-default-fg: #b6c6dd; --color-badge-default-fg: #9eb1cb;
--color-badge-default-border: #3b5f8f; --color-badge-default-border: rgba(59, 95, 143, 0.32);
--color-badge-success-bg: rgba(6, 78, 59, 0.45); --color-badge-success-bg: rgba(6, 78, 59, 0.22);
--color-badge-success-fg: #86efac; --color-badge-success-fg: #7dd3a8;
--color-badge-success-border: rgba(21, 128, 61, 0.5); --color-badge-success-border: rgba(34, 100, 68, 0.28);
--color-badge-warning-bg: rgba(120, 53, 15, 0.48); --color-badge-warning-bg: rgba(120, 53, 15, 0.22);
--color-badge-warning-fg: #fcd34d; --color-badge-warning-fg: #dfc06a;
--color-badge-warning-border: rgba(180, 83, 9, 0.55); --color-badge-warning-border: rgba(146, 88, 20, 0.28);
--color-badge-danger-bg: rgba(127, 29, 29, 0.42); --color-badge-danger-bg: rgba(127, 29, 29, 0.22);
--color-badge-danger-fg: #fca5a5; --color-badge-danger-fg: #e4a6a6;
--color-badge-danger-border: rgba(185, 28, 28, 0.52); --color-badge-danger-border: rgba(153, 50, 50, 0.28);
--color-purpose-consultation-bg: rgba(139, 92, 246, 0.25); --color-purpose-consultation-bg: rgba(139, 92, 246, 0.25);
--color-purpose-consultation-fg: #ddd6fe; --color-purpose-consultation-fg: #ddd6fe;
@@ -139,18 +139,18 @@
--color-card-muted: #b6c6dd; --color-card-muted: #b6c6dd;
--color-card-border: #29456a; --color-card-border: #29456a;
--color-badge-default-bg: #1b2f4e; --color-badge-default-bg: rgba(27, 47, 78, 0.32);
--color-badge-default-fg: #b6c6dd; --color-badge-default-fg: #9eb1cb;
--color-badge-default-border: #3b5f8f; --color-badge-default-border: rgba(59, 95, 143, 0.32);
--color-badge-success-bg: rgba(6, 78, 59, 0.45); --color-badge-success-bg: rgba(6, 78, 59, 0.22);
--color-badge-success-fg: #86efac; --color-badge-success-fg: #7dd3a8;
--color-badge-success-border: rgba(21, 128, 61, 0.5); --color-badge-success-border: rgba(34, 100, 68, 0.28);
--color-badge-warning-bg: rgba(120, 53, 15, 0.48); --color-badge-warning-bg: rgba(120, 53, 15, 0.22);
--color-badge-warning-fg: #fcd34d; --color-badge-warning-fg: #dfc06a;
--color-badge-warning-border: rgba(180, 83, 9, 0.55); --color-badge-warning-border: rgba(146, 88, 20, 0.28);
--color-badge-danger-bg: rgba(127, 29, 29, 0.42); --color-badge-danger-bg: rgba(127, 29, 29, 0.22);
--color-badge-danger-fg: #fca5a5; --color-badge-danger-fg: #e4a6a6;
--color-badge-danger-border: rgba(185, 28, 28, 0.52); --color-badge-danger-border: rgba(153, 50, 50, 0.28);
--color-purpose-consultation-bg: rgba(139, 92, 246, 0.25); --color-purpose-consultation-bg: rgba(139, 92, 246, 0.25);
--color-purpose-consultation-fg: #ddd6fe; --color-purpose-consultation-fg: #ddd6fe;
@@ -254,6 +254,11 @@ body {
border-radius: var(--radius-lg); 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 { .surface-panel {
background: color-mix(in srgb, var(--color-background-secondary) 96%, transparent); background: color-mix(in srgb, var(--color-background-secondary) 96%, transparent);
border: 1px solid var(--color-border); border: 1px solid var(--color-border);

View File

@@ -12,9 +12,13 @@ DOMAIN=dyolink.com
# Backend Environment (create backend.env from this) # Backend Environment (create backend.env from this)
# NODE_ENV=production # 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} # 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) # Frontend Environment (create frontend.env from this)
# NEXT_PUBLIC_API_URL=/api # 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_SECRET=another_long_random_secret_different_from_JWT_SECRET
JWT_REFRESH_EXPIRES_IN=30d 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 FRONTEND_URL=http://178.131.50.201:8088