diff --git a/backend/prisma/migrations/20260429134000_add_user_trial_used_at/migration.sql b/backend/prisma/migrations/20260429134000_add_user_trial_used_at/migration.sql
new file mode 100644
index 0000000..023adfc
--- /dev/null
+++ b/backend/prisma/migrations/20260429134000_add_user_trial_used_at/migration.sql
@@ -0,0 +1,2 @@
+ALTER TABLE "users"
+ADD COLUMN "trialUsedAt" TIMESTAMP(3);
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index f6517c6..db7b5fa 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -15,6 +15,7 @@ model User {
googleId String? @unique
facebookId String? @unique
name String
+ trialUsedAt DateTime?
memberships Membership[]
ownedOrganizations Organization[] @relation("OrganizationOwner")
diff --git a/backend/prisma/seed.ts b/backend/prisma/seed.ts
index 73d51d8..532c14d 100644
--- a/backend/prisma/seed.ts
+++ b/backend/prisma/seed.ts
@@ -1,6 +1,5 @@
// backend/prisma/seed.ts
import { PrismaClient } from '@prisma/client';
-import * as bcrypt from 'bcrypt';
import { config } from 'dotenv';
import path from 'path';
@@ -29,14 +28,14 @@ async function main() {
console.log('✅ Database connected successfully');
// Create organization types
- const clinicType = await prisma.organizationType.upsert({
+ await prisma.organizationType.upsert({
where: { name: 'CLINIC' },
update: {},
create: { name: 'CLINIC' },
});
console.log('✅ Created clinic type');
- const labType = await prisma.organizationType.upsert({
+ await prisma.organizationType.upsert({
where: { name: 'LAB' },
update: {},
create: { name: 'LAB' },
@@ -61,32 +60,39 @@ async function main() {
}
console.log('✅ Created plans');
- // Create features and permissions
+ // Minimal permission model (confirmed):
+ // - Sidebar tabs use READ/EDIT
+ // - EDIT implies READ in app logic
+ // - Owners effectively get all permissions
const features = [
{
- name: 'Patient Management',
- permissions: ['VIEW_PATIENTS', 'CREATE_PATIENTS', 'EDIT_PATIENTS', 'DELETE_PATIENTS']
+ name: 'Today',
+ permissions: ['TAB_TODAY_READ', 'TAB_TODAY_EDIT'],
},
{
- name: 'Order Management',
- permissions: ['VIEW_ORDERS', 'CREATE_ORDERS', 'EDIT_ORDERS', 'DELETE_ORDERS', 'TRACK_ORDERS']
+ name: 'Patients',
+ permissions: ['TAB_PATIENTS_READ', 'TAB_PATIENTS_EDIT'],
},
{
- name: 'Case Management',
- permissions: ['VIEW_CASES', 'CREATE_CASES', 'EDIT_CASES', 'DELETE_CASES']
+ name: 'Appointments',
+ permissions: ['TAB_APPOINTMENTS_READ', 'TAB_APPOINTMENTS_EDIT'],
},
{
- name: 'Reports',
- permissions: ['VIEW_REPORTS', 'EXPORT_REPORTS']
+ name: 'Staff Management',
+ permissions: ['TAB_STAFF_READ', 'TAB_STAFF_EDIT'],
},
{
- name: 'Team Management',
- permissions: ['INVITE_USERS', 'REMOVE_USERS', 'MANAGE_PERMISSIONS']
+ name: 'Lab Management',
+ permissions: ['TAB_LAB_READ', 'TAB_LAB_EDIT'],
},
{
name: 'Billing',
- permissions: ['VIEW_INVOICES', 'CREATE_INVOICES', 'MANAGE_PAYMENTS']
- }
+ permissions: ['TAB_BILLING_READ', 'TAB_BILLING_EDIT'],
+ },
+ {
+ name: 'Reports',
+ permissions: ['TAB_REPORTS_READ', 'TAB_REPORTS_EDIT'],
+ },
];
for (const feature of features) {
@@ -109,7 +115,7 @@ async function main() {
}
console.log('✅ Created features and permissions');
- console.log('🌱 Seeding completed successfully!'); ``
+ console.log('🌱 Seeding completed successfully!');
}
main()
diff --git a/backend/src/modules/auth/auth.controller.ts b/backend/src/modules/auth/auth.controller.ts
index afc0b62..860aade 100644
--- a/backend/src/modules/auth/auth.controller.ts
+++ b/backend/src/modules/auth/auth.controller.ts
@@ -25,6 +25,7 @@ import {
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';
import { RegisterDto } from './dto/register.dto';
+import { CreateOrganizationDto } from './dto/create-organization.dto';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { LocalAuthGuard } from './guards/local-auth.guard';
@@ -120,6 +121,14 @@ export class AuthController {
};
}
+ @Post('organizations')
+ @UseGuards(JwtAuthGuard)
+ @ApiBearerAuth('JWT-auth')
+ @ApiOperation({ summary: 'Create organization for current user' })
+ async createOrganization(@Req() req, @Body() dto: CreateOrganizationDto) {
+ return this.authService.createOrganization(req.user.id, dto);
+ }
+
// =========================
// PROFILE
// =========================
@@ -136,6 +145,20 @@ export class AuthController {
return this.authService.getProfile(req.user.id);
}
+ @Get('subscription-alert')
+ @UseGuards(JwtAuthGuard)
+ @ApiBearerAuth('JWT-auth')
+ @ApiOperation({
+ summary:
+ 'Owner-only: seat / trial status for warning indicator (current org from JWT)',
+ })
+ async getSubscriptionAlert(@Req() req) {
+ return this.authService.getOwnerSubscriptionAlert(
+ req.user.id,
+ req.user.organizationId,
+ );
+ }
+
// =========================
// LOGOUT
// =========================
diff --git a/backend/src/modules/auth/auth.service.ts b/backend/src/modules/auth/auth.service.ts
index 9b23699..e041323 100644
--- a/backend/src/modules/auth/auth.service.ts
+++ b/backend/src/modules/auth/auth.service.ts
@@ -12,30 +12,24 @@ import * as bcrypt from 'bcrypt';
import { PrismaService } from '../../../prisma/prisma.service';
import { LoginDto } from './dto/login.dto';
import { RegisterDto } from './dto/register.dto';
+import { CreateOrganizationDto } from './dto/create-organization.dto';
import { JwtPayload } from './interfaces/jwt-payload.interface';
const ALL_PERMISSIONS = [
- 'VIEW_PATIENTS',
- 'CREATE_PATIENTS',
- 'EDIT_PATIENTS',
- 'DELETE_PATIENTS',
- 'VIEW_ORDERS',
- 'CREATE_ORDERS',
- 'EDIT_ORDERS',
- 'DELETE_ORDERS',
- 'TRACK_ORDERS',
- 'VIEW_CASES',
- 'CREATE_CASES',
- 'EDIT_CASES',
- 'DELETE_CASES',
- 'VIEW_REPORTS',
- 'EXPORT_REPORTS',
- 'INVITE_USERS',
- 'REMOVE_USERS',
- 'MANAGE_PERMISSIONS',
- 'VIEW_INVOICES',
- 'CREATE_INVOICES',
- 'MANAGE_PAYMENTS',
+ 'TAB_TODAY_READ',
+ 'TAB_TODAY_EDIT',
+ 'TAB_PATIENTS_READ',
+ 'TAB_PATIENTS_EDIT',
+ 'TAB_APPOINTMENTS_READ',
+ 'TAB_APPOINTMENTS_EDIT',
+ 'TAB_STAFF_READ',
+ 'TAB_STAFF_EDIT',
+ 'TAB_LAB_READ',
+ 'TAB_LAB_EDIT',
+ 'TAB_BILLING_READ',
+ 'TAB_BILLING_EDIT',
+ 'TAB_REPORTS_READ',
+ 'TAB_REPORTS_EDIT',
];
@Injectable()
@@ -62,6 +56,7 @@ export class AuthService {
organization: {
include: {
type: true, // Include organization type (CLINIC/LAB)
+ plan: true,
}
},
permissions: {
@@ -148,6 +143,12 @@ export class AuthService {
permissions: membership.isOwner
? ALL_PERMISSIONS
: membership.permissions?.map(p => p.permission.name) || [],
+ plan: membership.organization.plan
+ ? {
+ name: membership.organization.plan.name,
+ maxUsers: membership.organization.plan.maxUsers,
+ }
+ : undefined,
})) || [];
return {
@@ -176,7 +177,7 @@ export class AuthService {
* @returns Created user info without password
*/
async register(registerDto: RegisterDto) {
- const { email, password, name, organizationName, organizationType } = registerDto;
+ const { email, password, name, organizationName, organizationEmail, organizationType } = registerDto;
// 1. Check existing user
const existingUser = await this.prisma.user.findUnique({
@@ -184,7 +185,7 @@ export class AuthService {
});
if (existingUser) {
- throw new ConflictException('User already exists');
+ throw new ConflictException('User already exists. Please login and create a new organization from your account.');
}
// 2. Hash password
@@ -198,16 +199,15 @@ export class AuthService {
email,
passwordHash: hashedPassword,
name,
+ trialUsedAt: new Date(),
},
});
// Create organization
const organization = await tx.organization.create({
data: {
- name: registerDto.organizationName,
-
- // REQUIRED FIELDS 👇
- email: registerDto.email, // or separate org email if you have one
+ name: organizationName,
+ email: organizationEmail,
owner: {
connect: { id: user.id },
@@ -219,7 +219,7 @@ export class AuthService {
type: {
connect: {
- name: registerDto.organizationType, // 'CLINIC' | 'LAB'
+ name: organizationType, // 'CLINIC' | 'LAB'
},
},
},
@@ -247,6 +247,66 @@ export class AuthService {
return this.login({ email, password } as any, validatedUser);
}
+ async createOrganization(userId: string, dto: CreateOrganizationDto) {
+ const owner = await this.prisma.user.findUnique({
+ where: { id: userId },
+ select: { id: true, trialUsedAt: true },
+ });
+
+ if (!owner) {
+ throw new UnauthorizedException('User not found');
+ }
+
+ const planName = dto.planName?.trim() || 'Small';
+ const effectivePlanName = owner.trialUsedAt ? planName : 'trial';
+
+ const organization = await this.prisma.$transaction(async (tx) => {
+ const createdOrganization = await tx.organization.create({
+ data: {
+ name: dto.organizationName,
+ email: dto.organizationEmail,
+ owner: {
+ connect: { id: userId },
+ },
+ plan: {
+ connect: { name: effectivePlanName },
+ },
+ type: {
+ connect: { name: dto.organizationType },
+ },
+ },
+ });
+
+ await tx.membership.create({
+ data: {
+ userId,
+ organizationId: createdOrganization.id,
+ isOwner: true,
+ },
+ });
+
+ if (!owner.trialUsedAt) {
+ await tx.user.update({
+ where: { id: userId },
+ data: { trialUsedAt: new Date() },
+ });
+ }
+
+ return createdOrganization;
+ });
+
+ return {
+ success: true,
+ data: {
+ organization: {
+ id: organization.id,
+ name: organization.name,
+ email: organization.email,
+ },
+ },
+ };
+ }
+
/**
* Get user profile with all memberships and permissions
* @param userId - User ID from JWT token
@@ -262,6 +322,7 @@ export class AuthService {
organization: {
include: {
type: true,
+ plan: true,
},
},
permissions: {
@@ -286,7 +347,15 @@ export class AuthService {
name: membership.organization.name,
type: membership.organization.type.name,
isOwner: membership.isOwner,
- permissions: membership.permissions?.map(p => p.permission.name) || [],
+ permissions: membership.isOwner
+ ? ALL_PERMISSIONS
+ : membership.permissions?.map(p => p.permission.name) || [],
+ plan: membership.organization.plan
+ ? {
+ name: membership.organization.plan.name,
+ maxUsers: membership.organization.plan.maxUsers,
+ }
+ : undefined,
})) || [];
return {
@@ -352,6 +421,7 @@ export class AuthService {
organization: {
include: {
type: true,
+ plan: true,
},
},
permissions: {
@@ -397,7 +467,15 @@ export class AuthService {
name: membership.organization.name,
type: membership.organization.type.name,
isOwner: membership.isOwner,
- permissions: membership.permissions?.map(p => p.permission.name) || [],
+ permissions: membership.isOwner
+ ? ALL_PERMISSIONS
+ : membership.permissions?.map(p => p.permission.name) || [],
+ plan: membership.organization.plan
+ ? {
+ name: membership.organization.plan.name,
+ maxUsers: membership.organization.plan.maxUsers,
+ }
+ : undefined,
})) || [];
return {
@@ -569,6 +647,7 @@ export class AuthService {
organization: {
include: {
type: true,
+ plan: true,
},
},
permissions: {
@@ -594,7 +673,15 @@ export class AuthService {
name: membership.organization.name,
type: membership.organization.type.name,
isOwner: membership.isOwner,
- permissions: membership.permissions?.map(p => p.permission.name) || [],
+ permissions: membership.isOwner
+ ? ALL_PERMISSIONS
+ : membership.permissions?.map(p => p.permission.name) || [],
+ plan: membership.organization.plan
+ ? {
+ name: membership.organization.plan.name,
+ maxUsers: membership.organization.plan.maxUsers,
+ }
+ : undefined,
})) || [];
return {
@@ -617,6 +704,7 @@ export class AuthService {
organizationId,
},
include: {
+ user: true,
organization: {
include: {
type: true,
@@ -638,7 +726,7 @@ export class AuthService {
// 2. Build payload WITH org context
const payload = {
sub: userId,
- email: membership.organization.email,
+ email: membership.user.email,
organizationId: membership.organizationId,
type: 'access',
};
@@ -650,7 +738,9 @@ export class AuthService {
});
// 4. Format permissions
- const permissions = membership.permissions.map(p => p.permission.name);
+ const permissions = membership.isOwner
+ ? ALL_PERMISSIONS
+ : membership.permissions.map(p => p.permission.name);
return {
success: true,
@@ -660,9 +750,101 @@ export class AuthService {
id: membership.organization.id,
name: membership.organization.name,
type: membership.organization.type.name,
+ isOwner: membership.isOwner,
+ plan: membership.organization.plan
+ ? {
+ name: membership.organization.plan.name,
+ maxUsers: membership.organization.plan.maxUsers,
+ }
+ : undefined,
},
permissions,
},
};
}
+
+ /**
+ * Owner-only subscription / seat alerts for the current org (from JWT).
+ * Used for a subtle warning indicator in the app shell (not staff-facing banners).
+ */
+ async getOwnerSubscriptionAlert(userId: string, organizationId: string | undefined) {
+ if (!organizationId) {
+ return {
+ success: true,
+ data: {
+ showWarning: false,
+ seatsLow: false,
+ trialEndingSoon: false,
+ trialExpired: false,
+ },
+ };
+ }
+
+ const membership = await this.prisma.membership.findFirst({
+ where: { userId, organizationId },
+ include: {
+ organization: {
+ include: { plan: true },
+ },
+ },
+ });
+
+ if (!membership || !membership.isOwner) {
+ return {
+ success: true,
+ data: {
+ showWarning: false,
+ seatsLow: false,
+ trialEndingSoon: false,
+ trialExpired: false,
+ },
+ };
+ }
+
+ const org = membership.organization;
+ const plan = org.plan;
+ const maxUsers = plan.maxUsers;
+ const seatsUsed = await this.prisma.membership.count({
+ where: { organizationId: org.id },
+ });
+
+ const unlimited = maxUsers >= 999999;
+ const remaining = unlimited ? Infinity : maxUsers - seatsUsed;
+ const seatsLow =
+ !unlimited && remaining >= 0 && remaining <= 2 && maxUsers > 0;
+
+ let trialEndingSoon = false;
+ let trialExpired = false;
+ let daysUntilTrialEnd: number | null = null;
+ let trialEndsAt: string | null = null;
+
+ if (plan.name === 'trial') {
+ const end = new Date(org.createdAt);
+ end.setDate(end.getDate() + 30);
+ trialEndsAt = end.toISOString();
+ const ms = end.getTime() - Date.now();
+ daysUntilTrialEnd = Math.ceil(ms / (1000 * 60 * 60 * 24));
+ if (daysUntilTrialEnd <= 0) {
+ trialExpired = true;
+ } else if (daysUntilTrialEnd <= 7) {
+ trialEndingSoon = true;
+ }
+ }
+
+ const showWarning = seatsLow || trialEndingSoon || trialExpired;
+
+ return {
+ success: true,
+ data: {
+ showWarning,
+ seatsLow,
+ trialEndingSoon,
+ trialExpired,
+ seatsUsed,
+ seatsLimit: maxUsers,
+ daysUntilTrialEnd,
+ trialEndsAt,
+ },
+ };
+ }
}
\ No newline at end of file
diff --git a/backend/src/modules/auth/dto/create-organization.dto.ts b/backend/src/modules/auth/dto/create-organization.dto.ts
new file mode 100644
index 0000000..716744d
--- /dev/null
+++ b/backend/src/modules/auth/dto/create-organization.dto.ts
@@ -0,0 +1,16 @@
+import { IsEmail, IsEnum, IsOptional, IsString } from 'class-validator';
+
+export class CreateOrganizationDto {
+ @IsString()
+ organizationName: string;
+
+ @IsEmail()
+ organizationEmail: string;
+
+ @IsEnum(['CLINIC', 'LAB'])
+ organizationType: 'CLINIC' | 'LAB';
+
+ @IsOptional()
+ @IsString()
+ planName?: string;
+}
diff --git a/backend/src/modules/auth/dto/register.dto.ts b/backend/src/modules/auth/dto/register.dto.ts
index ed11b46..3556870 100644
--- a/backend/src/modules/auth/dto/register.dto.ts
+++ b/backend/src/modules/auth/dto/register.dto.ts
@@ -14,6 +14,9 @@ export class RegisterDto {
@IsString()
organizationName: string;
+ @IsEmail()
+ organizationEmail: string;
+
@IsEnum(['CLINIC', 'LAB'])
organizationType: 'CLINIC' | 'LAB';
}
\ No newline at end of file
diff --git a/backend/src/modules/auth/interfaces/jwt-payload.interface.ts b/backend/src/modules/auth/interfaces/jwt-payload.interface.ts
index ab2f27c..6182b3e 100644
--- a/backend/src/modules/auth/interfaces/jwt-payload.interface.ts
+++ b/backend/src/modules/auth/interfaces/jwt-payload.interface.ts
@@ -2,6 +2,7 @@
export interface JwtPayload {
sub: string; // user id
email: string;
+ organizationId?: string;
type?: 'access' | 'refresh';
}
diff --git a/frontend/src/app/(dashboard)/layout.tsx b/frontend/src/app/(dashboard)/layout.tsx
index 62735b2..c23c6d9 100644
--- a/frontend/src/app/(dashboard)/layout.tsx
+++ b/frontend/src/app/(dashboard)/layout.tsx
@@ -1,18 +1,15 @@
'use client';
-import { memo, useCallback, useEffect } from 'react';
+import { memo, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/hooks/useAuth';
import Sidebar from '@/components/ui/Sidebar';
import { ThemeToggle } from '@/components/ui/ThemeToggle';
-import { LogOut } from 'lucide-react';
+import { DashboardAccountMenu } from '@/components/ui/DashboardAccountMenu';
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
- const { user, currentOrganization, isAuthReady, logout } = useAuth();
+ const { user, currentOrganization, isAuthReady } = useAuth();
const router = useRouter();
- const handleLogout = useCallback(() => {
- void logout();
- }, [logout]);
// ✅ AUTH GUARD (runs once per navigation group)
useEffect(() => {
@@ -51,11 +48,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
-
+
@@ -69,27 +62,16 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
const DashboardHeader = memo(function DashboardHeader({
organizationName,
- userName,
- onLogout,
}: {
organizationName: string;
- userName: string;
- onLogout: () => void;
}) {
return (
-
- {organizationName}
+
+ {organizationName}
-
+
- {userName}
-
-
- Logout
-
+
);
diff --git a/frontend/src/app/(dashboard)/settings/account/page.tsx b/frontend/src/app/(dashboard)/settings/account/page.tsx
new file mode 100644
index 0000000..e7379bb
--- /dev/null
+++ b/frontend/src/app/(dashboard)/settings/account/page.tsx
@@ -0,0 +1,29 @@
+'use client';
+
+import Link from 'next/link';
+
+export default function AccountSettingsPage() {
+ return (
+
+
+
+ ← Back to app
+
+
Account
+
+ Profile and security settings for your login.
+
+
+
+
+
+ Password change and profile editing will be wired here next (e.g. invite
+ flow, reset password).
+
+
+
+ );
+}
diff --git a/frontend/src/app/(dashboard)/settings/subscriptions/page.tsx b/frontend/src/app/(dashboard)/settings/subscriptions/page.tsx
new file mode 100644
index 0000000..7ac3bb3
--- /dev/null
+++ b/frontend/src/app/(dashboard)/settings/subscriptions/page.tsx
@@ -0,0 +1,103 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import Link from 'next/link';
+import { useRouter } from 'next/navigation';
+import { useAuth } from '@/lib/hooks/useAuth';
+import { authApi } from '@/lib/api/auth';
+import type { SubscriptionAlertData } from '@/types';
+
+export default function SubscriptionsSettingsPage() {
+ const { currentOrganization } = useAuth();
+ const router = useRouter();
+ const [alert, setAlert] = useState
(null);
+
+ useEffect(() => {
+ if (currentOrganization && !currentOrganization.isOwner) {
+ router.replace('/today');
+ }
+ }, [currentOrganization, router]);
+
+ useEffect(() => {
+ if (!currentOrganization?.isOwner) return;
+ void authApi.getSubscriptionAlert().then((r) => {
+ if (r.success) setAlert(r.data);
+ });
+ }, [currentOrganization?.id, currentOrganization?.isOwner]);
+
+ if (!currentOrganization) {
+ return (
+ Loading...
+ );
+ }
+
+ if (!currentOrganization.isOwner) {
+ return (
+ Redirecting...
+ );
+ }
+
+ const plan = currentOrganization.plan;
+ const maxUsers = plan?.maxUsers;
+
+ return (
+
+
+
+ ← Back to app
+
+
Subscriptions
+
+ Your DyoLink workspace plan and seats for{' '}
+ {currentOrganization.name} .
+ Clinic and lab income tracking stays under the sidebar{' '}
+ Billing tab.
+
+
+
+
+
+
+
Current plan
+
+ {plan?.name ?? '—'}
+
+
+ {typeof maxUsers === 'number' && maxUsers < 999999 && (
+
+
Seats (this org)
+
+ {alert?.seatsUsed ?? '—'} / {maxUsers}
+
+
+ )}
+
+
+ {alert?.showWarning && (
+
+ {alert.trialExpired && (
+
Trial period has ended. Choose a plan when checkout is available.
+ )}
+ {!alert.trialExpired && alert.trialEndingSoon && (
+
+ Trial ends in {alert.daysUntilTrialEnd ?? '—'} day(s).
+
+ )}
+ {!alert.trialExpired && !alert.trialEndingSoon && alert.seatsLow && (
+
Seat usage is high for this organization.
+ )}
+
+ )}
+
+
+ Payment and plan upgrades will connect here. The warning on the settings
+ icon is only shown to workspace owners when seats are low or the trial window
+ is ending.
+
+
+
+ );
+}
diff --git a/frontend/src/app/(public)/register/page.tsx b/frontend/src/app/(public)/register/page.tsx
index b37192e..03fc30b 100644
--- a/frontend/src/app/(public)/register/page.tsx
+++ b/frontend/src/app/(public)/register/page.tsx
@@ -18,6 +18,7 @@ const registerSchema = z.object({
.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',
}),
@@ -47,7 +48,7 @@ export default function RegisterPage() {
const handleNext = async () => {
const fieldsToValidate = step === 1
? ['name', 'email', 'password', 'confirmPassword']
- : ['organizationName', 'organizationType'];
+ : ['organizationName', 'organizationEmail', 'organizationType'];
const isValid = await trigger(fieldsToValidate as any);
if (isValid) {
@@ -62,6 +63,7 @@ export default function RegisterPage() {
data.password,
data.name,
data.organizationName,
+ data.organizationEmail,
data.organizationType
);
// No need to redirect - auth context will handle it
@@ -182,6 +184,14 @@ export default function RegisterPage() {
error={errors.organizationName?.message}
icon={ }
/>
+ }
+ />
Organization type
diff --git a/frontend/src/app/(public)/select-organization/page.tsx b/frontend/src/app/(public)/select-organization/page.tsx
index 125c747..4e9f86d 100644
--- a/frontend/src/app/(public)/select-organization/page.tsx
+++ b/frontend/src/app/(public)/select-organization/page.tsx
@@ -1,18 +1,17 @@
'use client';
-import { useEffect } from 'react';
+import { useState } from 'react';
import { useAuth } from '@/lib/hooks/useAuth';
-import { Building2, Beaker } from 'lucide-react';
+import { Building2, Beaker, Mail, Plus } from 'lucide-react';
+import { Input } from '@/components/ui/Input';
+import { Button } from '@/components/ui/Button';
export default function SelectOrganizationPage() {
- const { organizations, selectOrganization, isLoading } = useAuth();
-
- // ✅ Auto-redirect if only one organization
- useEffect(() => {
- if (!isLoading && organizations.length === 1) {
- selectOrganization(organizations[0].id);
- }
- }, [organizations, isLoading]);
+ const { organizations, selectOrganization, createOrganization, isLoading, error, clearError } = useAuth();
+ const [isCreateOpen, setIsCreateOpen] = useState(false);
+ const [organizationName, setOrganizationName] = useState('');
+ const [organizationEmail, setOrganizationEmail] = useState('');
+ const [organizationType, setOrganizationType] = useState<'CLINIC' | 'LAB'>('CLINIC');
const getIcon = (type: string) => {
return type === 'CLINIC'
@@ -20,60 +19,152 @@ export default function SelectOrganizationPage() {
: ;
};
+ const handleCreateOrganization = async () => {
+ try {
+ clearError();
+ const createdId = await createOrganization(
+ organizationName.trim(),
+ organizationEmail.trim(),
+ organizationType,
+ );
+ setOrganizationName('');
+ setOrganizationEmail('');
+ setOrganizationType('CLINIC');
+ setIsCreateOpen(false);
+ await selectOrganization(createdId);
+ } catch {
+ // Error is already handled in auth context.
+ }
+ };
+
if (isLoading) {
return (
-
Loading organizations...
-
- );
- }
-
- if (!organizations.length) {
- return (
-
-
No organizations found.
+
Loading...
);
}
return (
-
-
-
-
- Choose Organization
-
-
- You have access to multiple organizations. Select one to continue.
-
+
+
+
+
+
Organizations
+
+ Select an organization to continue, or create a new one.
+
+
+
{
+ clearError();
+ setIsCreateOpen(prev => !prev);
+ }}
+ >
+
+ {isCreateOpen ? 'Cancel' : 'Create Organization'}
+
-
- {organizations.map((org) => (
-
selectOrganization(org.id)}
- className="surface-card p-6 transition-all text-left flex items-center gap-4 hover:border-primary/60"
- >
-
- {getIcon(org.type)}
+ {isCreateOpen && (
+
+
setOrganizationName(event.target.value)}
+ placeholder="Sunshine Dental Clinic"
+ icon={
}
+ />
+
setOrganizationEmail(event.target.value)}
+ placeholder="contact@sunshineclinic.com"
+ type="email"
+ icon={
}
+ />
+
+
+ Organization type
+
+
+ setOrganizationType('CLINIC')}
+ className={`p-3 border rounded-[var(--radius-md)] text-sm ${
+ organizationType === 'CLINIC'
+ ? 'border-primary/60 bg-primary-soft text-text-primary'
+ : 'border-border text-text-secondary hover:border-border-strong'
+ }`}
+ >
+ Dental Clinic
+
+ setOrganizationType('LAB')}
+ className={`p-3 border rounded-[var(--radius-md)] text-sm ${
+ organizationType === 'LAB'
+ ? 'border-primary/60 bg-primary-soft text-text-primary'
+ : 'border-border text-text-secondary hover:border-border-strong'
+ }`}
+ >
+ Dental Lab
+
+
+ {error && (
+
+ )}
+
+
+ Create and Continue
+
+
+
+ )}
-
-
- {org.name}
-
-
- {org.type === 'CLINIC' ? 'Dental Clinic' : 'Dental Lab'}
-
-
+ {!organizations.length ? (
+
+
No organizations found. Create your first one to continue.
+
+ ) : (
+
+ {organizations.map((org) => (
+
selectOrganization(org.id)}
+ className="surface-card p-6 transition-all text-left flex items-center gap-4 hover:border-primary/60"
+ >
+
+ {getIcon(org.type)}
+
-
- Continue →
-
-
- ))}
-
+
+
+ {org.name}
+
+
+ {org.type === 'CLINIC' ? 'Dental Clinic' : 'Dental Lab'}
+
+
+
+
+ Continue →
+
+
+ ))}
+
+ )}
);
diff --git a/frontend/src/components/ui/DashboardAccountMenu.tsx b/frontend/src/components/ui/DashboardAccountMenu.tsx
new file mode 100644
index 0000000..ec0f9ec
--- /dev/null
+++ b/frontend/src/components/ui/DashboardAccountMenu.tsx
@@ -0,0 +1,156 @@
+'use client';
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import Link from 'next/link';
+import {
+ Settings,
+ AlertTriangle,
+ Building2,
+ CreditCard,
+ User,
+ LogOut,
+ ChevronDown,
+} from 'lucide-react';
+import { useAuth } from '@/lib/hooks/useAuth';
+import { authApi } from '@/lib/api/auth';
+import type { SubscriptionAlertData } from '@/types';
+
+function warningTooltip(data: SubscriptionAlertData | null): string {
+ if (!data?.showWarning) return '';
+ if (data.trialExpired) return 'Trial ended — review Subscriptions';
+ if (data.trialEndingSoon) return 'Trial ending soon — review Subscriptions';
+ if (data.seatsLow) return 'Seats running low — review Subscriptions';
+ return 'Review Subscriptions';
+}
+
+export function DashboardAccountMenu() {
+ const { user, currentOrganization, logout } = useAuth();
+ const [open, setOpen] = useState(false);
+ const menuRef = useRef
(null);
+ const [alert, setAlert] = useState(null);
+ const isOwner = currentOrganization?.isOwner ?? false;
+
+ useEffect(() => {
+ const onDocClick = (e: MouseEvent) => {
+ if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
+ setOpen(false);
+ }
+ };
+ document.addEventListener('mousedown', onDocClick);
+ return () => document.removeEventListener('mousedown', onDocClick);
+ }, []);
+
+ useEffect(() => {
+ if (!isOwner || !currentOrganization) {
+ setAlert(null);
+ return;
+ }
+ let cancelled = false;
+ void (async () => {
+ try {
+ const res = await authApi.getSubscriptionAlert();
+ if (!cancelled && res.success) setAlert(res.data);
+ } catch {
+ if (!cancelled) setAlert(null);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [isOwner, currentOrganization?.id]);
+
+ const showWarning = Boolean(isOwner && alert?.showWarning);
+ const tooltip = useMemo(() => warningTooltip(alert), [alert]);
+
+ const handleLogout = useCallback(() => {
+ setOpen(false);
+ void logout();
+ }, [logout]);
+
+ return (
+
+
setOpen((v) => !v)}
+ className="inline-flex items-center gap-2 rounded-[var(--radius-md)] border border-border/70 px-3 py-2 text-sm text-text-primary hover:bg-background-card/80 transition-colors"
+ aria-expanded={open}
+ aria-haspopup="menu"
+ >
+
+
+ {showWarning && (
+
+
+
+ )}
+
+ {user?.name}
+
+
+
+ {open && (
+
+
+
Signed in
+
{user?.email}
+
+ {currentOrganization?.name}
+
+
+
+
+ setOpen(false)}
+ >
+
+ Switch organization
+
+
+ {isOwner && (
+ setOpen(false)}
+ >
+
+ Subscriptions
+
+ )}
+
+ setOpen(false)}
+ >
+
+ Account
+
+
+
+
+
+
+ Log out
+
+
+
+ )}
+
+ );
+}
diff --git a/frontend/src/components/ui/Sidebar.tsx b/frontend/src/components/ui/Sidebar.tsx
index f3c59d3..79d8d82 100644
--- a/frontend/src/components/ui/Sidebar.tsx
+++ b/frontend/src/components/ui/Sidebar.tsx
@@ -10,7 +10,7 @@ import {
UserCog,
FlaskConical,
FileText,
- CreditCard
+ CreditCard,
} from 'lucide-react';
const menu = [
@@ -27,12 +27,13 @@ function Sidebar() {
const pathname = usePathname();
return (
-
-
-
DyoLink
+
+
+
DyoLink
+
-
+
{menu.map((item) => {
const Icon = item.icon;
const isActive = pathname === item.path;
diff --git a/frontend/src/lib/api/auth.ts b/frontend/src/lib/api/auth.ts
index 89d18c3..fae6744 100644
--- a/frontend/src/lib/api/auth.ts
+++ b/frontend/src/lib/api/auth.ts
@@ -1,6 +1,6 @@
// src/lib/api/auth.ts
import { apiClient } from './client';
-import { AuthResponse, TrialRegistrationData, LoginData } from '@/types';
+import { AuthResponse, TrialRegistrationData, LoginData, SubscriptionAlertData } from '@/types';
export const authApi = {
// Register a new trial organization
@@ -21,12 +21,32 @@ export const authApi = {
return response.data;
},
+ /** Owner-only meaningful data; staff always gets showWarning: false */
+ getSubscriptionAlert: async (): Promise<{
+ success: boolean;
+ data: SubscriptionAlertData;
+ }> => {
+ const response = await apiClient.get('/auth/subscription-alert');
+ return response.data;
+ },
+
// Select organization
selectOrganization: async (organizationId: string): Promise => {
const response = await apiClient.post('/auth/select-organization', { organizationId });
return response.data;
},
+ // Create organization for current user
+ createOrganization: async (data: {
+ organizationName: string;
+ organizationEmail: string;
+ organizationType: 'CLINIC' | 'LAB';
+ planName?: string;
+ }): Promise => {
+ const response = await apiClient.post('/auth/organizations', data);
+ return response.data;
+ },
+
// Logout
logout: async (): Promise => {
await apiClient.post('/auth/logout');
diff --git a/frontend/src/lib/hooks/useAuth.tsx b/frontend/src/lib/hooks/useAuth.tsx
index 58be0ac..852e442 100644
--- a/frontend/src/lib/hooks/useAuth.tsx
+++ b/frontend/src/lib/hooks/useAuth.tsx
@@ -17,11 +17,18 @@ interface AuthContextType {
password: string,
name: string,
organizationName: string,
+ organizationEmail: string,
organizationType: 'CLINIC' | 'LAB'
) => Promise;
login: (email: string, password: string) => Promise;
logout: () => Promise;
selectOrganization: (orgId: string) => Promise;
+ createOrganization: (
+ organizationName: string,
+ organizationEmail: string,
+ organizationType: 'CLINIC' | 'LAB',
+ planName?: string,
+ ) => Promise;
clearError: () => void;
}
@@ -111,6 +118,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
password: string,
name: string,
organizationName: string,
+ organizationEmail: string,
organizationType: 'CLINIC' | 'LAB'
) => {
try {
@@ -122,6 +130,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
password,
name,
organizationName,
+ organizationEmail,
organizationType,
});
@@ -209,7 +218,13 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
localStorage.setItem('currentOrganizationId', organization.id);
- setCurrentOrganization(organization);
+ setCurrentOrganization({
+ id: organization.id,
+ name: organization.name,
+ type: organization.type as Organization['type'],
+ isOwner: Boolean((organization as { isOwner?: boolean }).isOwner),
+ plan: (organization as { plan?: Organization['plan'] }).plan,
+ });
router.push('/today');
@@ -221,6 +236,39 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
}
}, [router]);
+ const createOrganization = useCallback(async (
+ organizationName: string,
+ organizationEmail: string,
+ organizationType: 'CLINIC' | 'LAB',
+ planName?: string,
+ ) => {
+ try {
+ setIsLoading(true);
+ setError(null);
+
+ const createResponse = await authApi.createOrganization({
+ organizationName,
+ organizationEmail,
+ organizationType,
+ planName,
+ });
+
+ const profileResponse = await authApi.getProfile();
+ if (profileResponse.success) {
+ const { user: userData, organizations: orgs } = normalizeProfilePayload(profileResponse.data);
+ setUser(userData);
+ setOrganizations(orgs);
+ }
+
+ return createResponse.data.organization.id as string;
+ } catch (err: any) {
+ setError(err.message || 'Failed to create organization');
+ throw err;
+ } finally {
+ setIsLoading(false);
+ }
+ }, [normalizeProfilePayload]);
+
const clearError = useCallback(() => setError(null), []);
const contextValue = useMemo(
@@ -235,6 +283,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
login,
logout,
selectOrganization,
+ createOrganization,
clearError,
}),
[
@@ -248,6 +297,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
login,
logout,
selectOrganization,
+ createOrganization,
clearError,
],
);
diff --git a/frontend/src/middleware.ts b/frontend/src/middleware.ts
index d067010..27b6361 100644
--- a/frontend/src/middleware.ts
+++ b/frontend/src/middleware.ts
@@ -3,7 +3,6 @@ import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const publicRoutes = ['/', '/login', '/register', '/terms', '/privacy', '/forgot-password'];
-const authOnlyRoutes = ['/login', '/register']; // routes that should NOT be accessed when logged in
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
@@ -15,12 +14,10 @@ export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/today', request.url));
}
- // Always allow public routes first
+ // Always allow public routes first. We intentionally do not block /login or /register
+ // when a cookie exists, because the cookie might be stale/invalid and the client
+ // auth check needs to recover gracefully.
if (publicRoutes.includes(pathname)) {
- // If user is already logged in and tries to access login/register → redirect to dashboard
- if (isAuthenticated && authOnlyRoutes.includes(pathname)) {
- return NextResponse.redirect(new URL('/today', request.url));
- }
return NextResponse.next();
}
diff --git a/frontend/src/styles/globals.css b/frontend/src/styles/globals.css
index 33b62ff..27dc929 100644
--- a/frontend/src/styles/globals.css
+++ b/frontend/src/styles/globals.css
@@ -2,9 +2,9 @@
/* Light theme tokens (future-ready) */
:root[data-theme="light"] {
- --radius-sm: 6px;
- --radius-md: 8px;
- --radius-lg: 12px;
+ --radius-sm: 4px;
+ --radius-md: 6px;
+ --radius-lg: 8px;
--color-background-primary: #f6f9fc;
--color-background-secondary: #ffffff;
@@ -45,7 +45,7 @@
--color-primary: #09a9bc;
--color-primary-contrast: #001117;
--color-primary-soft: rgba(9, 169, 188, 0.2);
- --color-icon: #f3bb4b;
+ --color-icon: #e1bc72;
}
/* Default theme = dark */
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index b3743f9..3100c77 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -10,12 +10,25 @@ export interface Organization {
name: string;
type: 'CLINIC' | 'LAB';
isOwner: boolean;
+ permissions?: string[];
plan?: {
name: string;
maxUsers: number;
};
}
+/** GET /auth/subscription-alert — owners only get meaningful flags */
+export interface SubscriptionAlertData {
+ showWarning: boolean;
+ seatsLow: boolean;
+ trialEndingSoon: boolean;
+ trialExpired: boolean;
+ seatsUsed?: number;
+ seatsLimit?: number;
+ daysUntilTrialEnd?: number | null;
+ trialEndsAt?: string | null;
+}
+
export interface AuthResponse {
success: boolean;
data: {
@@ -31,6 +44,7 @@ export interface TrialRegistrationData {
password: string;
name: string;
organizationName: string;
+ organizationEmail: string;
organizationType: 'CLINIC' | 'LAB';
}