feature/staff-management #7

Merged
admin merged 3 commits from feature/staff-management into master 2026-04-30 14:09:33 +03:30
38 changed files with 375 additions and 362 deletions
Showing only changes of commit 1387e4cb5e - Show all commits

View File

@@ -48,8 +48,9 @@ export class AuthService {
*/ */
async validateUser(email: string, password: string): Promise<any> { async validateUser(email: string, password: string): Promise<any> {
try { try {
const normalizedEmail = email.trim().toLowerCase();
const user = await this.prisma.user.findUnique({ const user = await this.prisma.user.findUnique({
where: { email }, where: { email: normalizedEmail },
include: { include: {
memberships: { memberships: {
include: { include: {
@@ -147,6 +148,7 @@ export class AuthService {
? { ? {
name: membership.organization.plan.name, name: membership.organization.plan.name,
maxUsers: membership.organization.plan.maxUsers, maxUsers: membership.organization.plan.maxUsers,
price: membership.organization.plan.price,
} }
: undefined, : undefined,
})); }));
@@ -177,7 +179,8 @@ export class AuthService {
* @returns Created user info without password * @returns Created user info without password
*/ */
async register(registerDto: RegisterDto) { async register(registerDto: RegisterDto) {
const { email, password, name, organizationName, organizationEmail, organizationType } = registerDto; const { password, name, organizationName, organizationEmail, organizationType } = registerDto;
const email = registerDto.email.trim().toLowerCase();
// 1. Check existing user // 1. Check existing user
const existingUser = await this.prisma.user.findUnique({ const existingUser = await this.prisma.user.findUnique({
@@ -354,6 +357,7 @@ export class AuthService {
? { ? {
name: membership.organization.plan.name, name: membership.organization.plan.name,
maxUsers: membership.organization.plan.maxUsers, maxUsers: membership.organization.plan.maxUsers,
price: membership.organization.plan.price,
} }
: undefined, : undefined,
})); }));
@@ -474,6 +478,7 @@ export class AuthService {
? { ? {
name: membership.organization.plan.name, name: membership.organization.plan.name,
maxUsers: membership.organization.plan.maxUsers, maxUsers: membership.organization.plan.maxUsers,
price: membership.organization.plan.price,
} }
: undefined, : undefined,
})); }));
@@ -680,6 +685,7 @@ export class AuthService {
? { ? {
name: membership.organization.plan.name, name: membership.organization.plan.name,
maxUsers: membership.organization.plan.maxUsers, maxUsers: membership.organization.plan.maxUsers,
price: membership.organization.plan.price,
} }
: undefined, : undefined,
})); }));
@@ -759,6 +765,7 @@ export class AuthService {
? { ? {
name: membership.organization.plan.name, name: membership.organization.plan.name,
maxUsers: membership.organization.plan.maxUsers, maxUsers: membership.organization.plan.maxUsers,
price: membership.organization.plan.price,
} }
: undefined, : undefined,
}, },
@@ -770,7 +777,12 @@ export class AuthService {
memberships: Array<{ memberships: Array<{
isOwner: boolean; isOwner: boolean;
isActive: boolean; isActive: boolean;
organization: { id: string; name: string; type: { name: string }; plan?: { name: string; maxUsers: number } | null }; organization: {
id: string;
name: string;
type: { name: string };
plan?: { name: string; maxUsers: number; price: number } | null;
};
permissions?: Array<{ permission: { name: string } }>; permissions?: Array<{ permission: { name: string } }>;
}> = [], }> = [],
) { ) {
@@ -790,6 +802,8 @@ export class AuthService {
seatsLow: false, seatsLow: false,
trialEndingSoon: false, trialEndingSoon: false,
trialExpired: false, trialExpired: false,
daysUntilPlanEnd: null,
planEndsAt: null,
}, },
}; };
} }
@@ -811,6 +825,8 @@ export class AuthService {
seatsLow: false, seatsLow: false,
trialEndingSoon: false, trialEndingSoon: false,
trialExpired: false, trialExpired: false,
daysUntilPlanEnd: null,
planEndsAt: null,
}, },
}; };
} }
@@ -830,23 +846,16 @@ export class AuthService {
const seatsLow = const seatsLow =
!unlimited && remaining >= 0 && remaining <= 2 && maxUsers > 0; !unlimited && remaining >= 0 && remaining <= 2 && maxUsers > 0;
let trialEndingSoon = false; // Current pricing model: trial lasts 30 days; paid plans last 90 days.
let trialExpired = false; const durationDays = plan.name === 'trial' ? 30 : 90;
let daysUntilTrialEnd: number | null = null; const end = new Date(org.createdAt);
let trialEndsAt: string | null = null; end.setDate(end.getDate() + durationDays);
const planEndsAt = end.toISOString();
const ms = end.getTime() - Date.now();
const daysUntilPlanEnd = Math.ceil(ms / (1000 * 60 * 60 * 24));
if (plan.name === 'trial') { const trialExpired = plan.name === 'trial' && daysUntilPlanEnd <= 0;
const end = new Date(org.createdAt); const trialEndingSoon = plan.name === 'trial' && daysUntilPlanEnd > 0 && daysUntilPlanEnd <= 7;
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; const showWarning = seatsLow || trialEndingSoon || trialExpired;
@@ -859,8 +868,10 @@ export class AuthService {
trialExpired, trialExpired,
seatsUsed, seatsUsed,
seatsLimit: maxUsers, seatsLimit: maxUsers,
daysUntilTrialEnd, daysUntilTrialEnd: plan.name === 'trial' ? daysUntilPlanEnd : null,
trialEndsAt, trialEndsAt: plan.name === 'trial' ? planEndsAt : null,
daysUntilPlanEnd,
planEndsAt,
}, },
}; };
} }

View File

@@ -9,11 +9,12 @@ const nextConfig = {
// Disable x-powered-by header for security // Disable x-powered-by header for security
poweredByHeader: false, poweredByHeader: false,
// Configure image domains if needed // Configure allowed remote image sources
images: { images: {
domains: process.env.NODE_ENV === 'production' remotePatterns:
? ['yourdomain.com'] process.env.NODE_ENV === 'production'
: ['localhost'], ? [{ protocol: 'https', hostname: 'yourdomain.com' }]
: [{ protocol: 'http', hostname: 'localhost' }],
}, },
// Environment variables that will be available at build time // Environment variables that will be available at build time

View File

@@ -1,56 +0,0 @@
/**
* Dashboard route ↔ TAB_* READ permission mapping and helpers used by the shell
* (Sidebar, layout guard). Cross-cutting access logic lives here — not in `lib`,
* which remains for generic utilities (API client, hooks, etc.).
*/
import type { Organization } from '@/types';
const ROUTE_TAB_READ: { prefix: string; permission: string }[] = [
{ prefix: '/today', permission: 'TAB_TODAY_READ' },
{ prefix: '/patients', permission: 'TAB_PATIENTS_READ' },
{ prefix: '/appointments', permission: 'TAB_APPOINTMENTS_READ' },
{ prefix: '/staff', permission: 'TAB_STAFF_READ' },
{ prefix: '/lab', permission: 'TAB_LAB_READ' },
{ prefix: '/billing', permission: 'TAB_BILLING_READ' },
{ prefix: '/reports', permission: 'TAB_REPORTS_READ' },
];
export function hasPermission(org: Organization | null, permission: string): boolean {
if (!org) return false;
if (org.isOwner) return true;
return Boolean(org.permissions?.includes(permission));
}
/** Sidebar / route guard: READ access to a tab */
export function canViewTab(org: Organization | null, readPermission: string): boolean {
return hasPermission(org, readPermission);
}
export function getRequiredReadPermissionForPath(pathname: string): string | null {
for (const { prefix, permission } of ROUTE_TAB_READ) {
if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {
return permission;
}
}
return null;
}
/** First dashboard route the user may open (ordered). Fallback: account settings. */
export function firstAccessibleDashboardPath(org: Organization | null): string {
if (!org) return '/today';
if (org.isOwner) return '/today';
for (const { prefix, permission } of ROUTE_TAB_READ) {
if (hasPermission(org, permission)) return prefix;
}
return '/settings/account';
}
export function canEditStaff(org: Organization | null): boolean {
return hasPermission(org, 'TAB_STAFF_EDIT');
}
export function canViewStaff(org: Organization | null): boolean {
return (
hasPermission(org, 'TAB_STAFF_READ') || hasPermission(org, 'TAB_STAFF_EDIT')
);
}

View File

@@ -1 +0,0 @@
export * from './dashboard-tab-access';

View File

@@ -2,9 +2,9 @@
'use client'; 'use client';
import { useState } from 'react'; import { useState } from 'react';
import { Search, Filter, Plus } from 'lucide-react'; import { Search, Filter, Plus } from 'lucide-react';
import { Button } from '@/components/ui/Button'; import { Button } from '@/components/ui/common/Button';
import { Input } from '@/components/ui/Input'; import { Input } from '@/components/ui/common/Input';
import { Badge } from '@/components/ui/Badge'; import { Badge } from '@/components/ui/common/Badge';
// Mock data matching your design // Mock data matching your design
const invoices = [ const invoices = [
{ id: '#123456', patient: 'Ali Rahmani', date: '24/9/2026', service: 'Hygiene', amount: 300, paid: 0, status: 'unpaid' }, { id: '#123456', patient: 'Ali Rahmani', date: '24/9/2026', service: 'Hygiene', amount: 300, paid: 0, status: 'unpaid' },

View File

@@ -3,14 +3,14 @@
import { memo, useEffect } from 'react'; import { memo, useEffect } from 'react';
import { usePathname, useRouter } from 'next/navigation'; import { usePathname, useRouter } from 'next/navigation';
import { useAuth } from '@/lib/hooks/useAuth'; import { useAuth } from '@/lib/hooks/useAuth';
import Sidebar from '@/components/ui/Sidebar'; import Sidebar from '@/components/ui/common/Sidebar';
import { ThemeToggle } from '@/components/ui/ThemeToggle'; import { ThemeToggle } from '@/components/ui/common/ThemeToggle';
import { DashboardAccountMenu } from '@/components/ui/DashboardAccountMenu'; import { DashboardAccountMenu } from '@/components/ui/dashboard/DashboardAccountMenu';
import { import {
firstAccessibleDashboardPath, firstAccessibleDashboardPath,
getRequiredReadPermissionForPath, getRequiredReadPermissionForPath,
hasPermission, hasPermission,
} from '@/access'; } from '@/shared/permissions';
export default function DashboardLayout({ children }: { children: React.ReactNode }) { export default function DashboardLayout({ children }: { children: React.ReactNode }) {
const { user, currentOrganization, isAuthReady } = useAuth(); const { user, currentOrganization, isAuthReady } = useAuth();
@@ -77,7 +77,7 @@ const DashboardHeader = memo(function DashboardHeader({
organizationName: string; organizationName: string;
}) { }) {
return ( return (
<header className="h-[71px] flex justify-between items-center gap-4 px-6 border-b border-border/70 backdrop-blur-sm"> <header className="relative z-40 h-[71px] flex justify-between items-center gap-4 px-6 border-b border-border/70 backdrop-blur-sm">
<h2 className="text-lg font-medium truncate min-w-0">{organizationName}</h2> <h2 className="text-lg font-medium truncate min-w-0">{organizationName}</h2>
<div className="flex items-center gap-3 shrink-0"> <div className="flex items-center gap-3 shrink-0">

View File

@@ -2,7 +2,7 @@
import { useEffect, useMemo, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import { Plus } from 'lucide-react'; import { Plus } from 'lucide-react';
import { Button } from '@/components/ui/Button'; import { Button } from '@/components/ui/common/Button';
import { patientsApi } from '@/lib/api/patients'; import { patientsApi } from '@/lib/api/patients';
import { import {
CreatePatientInput, CreatePatientInput,
@@ -10,10 +10,10 @@ import {
Patient, Patient,
TreatmentHistoryItem, TreatmentHistoryItem,
} from '@/types/patient'; } from '@/types/patient';
import { PatientSearchSelect } from './components/PatientSearchSelect'; import { PatientSearchSelect } from '../../../components/ui/patient/PatientSearchSelect';
import { CreatePatientModal } from './components/CreatePatientModal'; import { CreatePatientModal } from '../../../components/ui/patient/CreatePatientModal';
import { PatientSummaryCard } from './components/PatientSummaryCard'; import { PatientSummaryCard } from '../../../components/ui/patient/PatientSummaryCard';
import { TreatmentHistoryPreview } from './components/TreatmentHistoryPreview'; import { TreatmentHistoryPreview } from '../../../components/ui/patient/TreatmentHistoryPreview';
const EMPTY_PATIENT_FORM: CreatePatientInput = { const EMPTY_PATIENT_FORM: CreatePatientInput = {
firstName: '', firstName: '',
@@ -201,7 +201,7 @@ export default function PatientsPage() {
</div> </div>
{(errorMessage || successMessage) && ( {(errorMessage || successMessage) && (
<div className="absolute bottom-0 left-0 right-0 z-50 w-full"> <div className="absolute bottom-0 left-0 right-0 z-10 w-full">
{errorMessage && ( {errorMessage && (
<div className="rounded-[var(--radius-sm)] border border-red-500/50 bg-red-500/10 px-3 py-2 text-sm text-red-300 shadow-lg"> <div className="rounded-[var(--radius-sm)] border border-red-500/50 bg-red-500/10 px-3 py-2 text-sm text-red-300 shadow-lg">
{errorMessage} {errorMessage}

View File

@@ -0,0 +1,20 @@
'use client';
import Link from 'next/link';
import { OrganizationSelectorContent } from '@/components/ui/organization/OrganizationSelectorContent';
export default function DashboardOrganizationsSettingsPage() {
return (
<div className="max-w-3xl space-y-6">
<div>
<Link
href="/today"
className="text-sm text-primary hover:opacity-90"
>
Back to app
</Link>
</div>
<OrganizationSelectorContent />
</div>
);
}

View File

@@ -5,7 +5,7 @@ import Link from 'next/link';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/hooks/useAuth'; import { useAuth } from '@/lib/hooks/useAuth';
import { authApi } from '@/lib/api/auth'; import { authApi } from '@/lib/api/auth';
import type { SubscriptionAlertData } from '@/types'; import type { SubscriptionAlertData } from '@/types/subscription';
export default function SubscriptionsSettingsPage() { export default function SubscriptionsSettingsPage() {
const { currentOrganization } = useAuth(); const { currentOrganization } = useAuth();
@@ -39,9 +39,24 @@ export default function SubscriptionsSettingsPage() {
const plan = currentOrganization.plan; const plan = currentOrganization.plan;
const maxUsers = plan?.maxUsers; const maxUsers = plan?.maxUsers;
const isUnlimited = typeof maxUsers === 'number' && maxUsers >= 999999;
const seatsUsed = alert?.seatsUsed;
const seatsRemaining =
typeof seatsUsed === 'number' && typeof maxUsers === 'number' && !isUnlimited
? Math.max(0, maxUsers - seatsUsed)
: null;
const daysUntilPlanEnd = alert?.daysUntilPlanEnd ?? null;
const planDayTone =
daysUntilPlanEnd == null
? 'text-text-primary'
: daysUntilPlanEnd > 20
? 'text-emerald-400'
: daysUntilPlanEnd >= 10
? 'text-amber-300'
: 'text-red-400';
return ( return (
<div className="max-w-xl space-y-6"> <div className="max-w-4xl space-y-6">
<div> <div>
<Link <Link
href="/today" href="/today"
@@ -59,21 +74,38 @@ export default function SubscriptionsSettingsPage() {
</div> </div>
<div className="surface-card p-6 space-y-4"> <div className="surface-card p-6 space-y-4">
<div className="flex flex-wrap gap-4 justify-between"> <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
<div> <div>
<p className="text-xs text-text-muted uppercase tracking-wide">Current plan</p> <p className="text-xs text-text-muted uppercase tracking-wide">Current plan</p>
<p className="text-lg font-medium text-text-primary capitalize"> <p className="text-lg font-medium text-text-primary capitalize">
{plan?.name ?? '—'} {plan?.name ?? '—'}
</p> </p>
</div> </div>
{typeof maxUsers === 'number' && maxUsers < 999999 && ( <div>
<div> <p className="text-xs text-text-muted uppercase tracking-wide">Plan price</p>
<p className="text-xs text-text-muted uppercase tracking-wide">Seats (this org)</p> <p className="text-lg font-medium text-text-primary">
<p className="text-lg font-medium text-text-primary"> {typeof plan?.price === 'number' ? `$${plan.price}` : '—'}
{alert?.seatsUsed ?? '—'} / {maxUsers} </p>
</p> </div>
</div> <div>
)} <p className="text-xs text-text-muted uppercase tracking-wide">Seats used</p>
<p className="text-lg font-medium text-text-primary">
{typeof seatsUsed === 'number' ? seatsUsed : '—'}
{typeof maxUsers === 'number' ? ` / ${isUnlimited ? 'Unlimited' : maxUsers}` : ''}
</p>
</div>
<div>
<p className="text-xs text-text-muted uppercase tracking-wide">Seats remaining</p>
<p className="text-lg font-medium text-text-primary">
{isUnlimited ? 'Unlimited' : seatsRemaining ?? '—'}
</p>
</div>
<div>
<p className="text-xs text-text-muted uppercase tracking-wide">Days remaining</p>
<p className={`text-lg font-medium ${planDayTone}`}>
{daysUntilPlanEnd ?? '—'}
</p>
</div>
</div> </div>
{alert?.showWarning && ( {alert?.showWarning && (

View File

@@ -6,7 +6,7 @@ import {
firstAccessibleDashboardPath, firstAccessibleDashboardPath,
canEditStaff, canEditStaff,
canViewStaff, canViewStaff,
} from '@/access'; } from '@/shared/permissions';
import { import {
STAFF_FEATURE_GROUPS, STAFF_FEATURE_GROUPS,
permissionNamesFromFeatureState, permissionNamesFromFeatureState,
@@ -18,10 +18,10 @@ import {
import { UserPlus, Pencil, Trash2, Copy, Check, X, Clock3 } from 'lucide-react'; import { UserPlus, Pencil, Trash2, Copy, Check, X, Clock3 } from 'lucide-react';
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/Button'; import { Button } from '@/components/ui/common/Button';
import { Input } from '@/components/ui/Input'; import { Input } from '@/components/ui/common/Input';
import { Checkbox } from '@/components/ui/Checkbox'; import { Checkbox } from '@/components/ui/common/Checkbox';
import { ApiError } from '@/types'; import type { ApiError } from '@/types/api';
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';

View File

@@ -4,8 +4,8 @@ import { useEffect, useMemo, useState } from 'react';
import { Suspense } from 'react'; import { Suspense } 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 { Button } from '@/components/ui/Button'; import { Button } from '@/components/ui/common/Button';
import { Input } from '@/components/ui/Input'; import { Input } from '@/components/ui/common/Input';
import { staffApi } from '@/lib/api/staff'; import { staffApi } from '@/lib/api/staff';
function AcceptInviteContent() { function AcceptInviteContent() {

View File

@@ -116,8 +116,8 @@ import Link from 'next/link';
import { Mail, Lock } from 'lucide-react'; import { Mail, Lock } from 'lucide-react';
import { useAuth } from '@/lib/hooks/useAuth'; import { useAuth } from '@/lib/hooks/useAuth';
import { Button } from '@/components/ui/Button'; import { Button } from '@/components/ui/common/Button';
import { Input } from '@/components/ui/Input'; import { Input } from '@/components/ui/common/Input';
const loginSchema = z.object({ const loginSchema = z.object({
email: z.string().email('Please enter a valid email address'), email: z.string().email('Please enter a valid email address'),

View File

@@ -2,8 +2,8 @@
import Link from 'next/link'; import Link from 'next/link';
import { useAuth } from '@/lib/hooks/useAuth'; import { useAuth } from '@/lib/hooks/useAuth';
import { Button } from '@/components/ui/Button'; import { Button } from '@/components/ui/common/Button';
import { ThemeToggle } from '@/components/ui/ThemeToggle'; import { ThemeToggle } from '@/components/ui/common/ThemeToggle';
import { Building2, Beaker, Calendar, Shield, Clock, Users } from 'lucide-react'; import { Building2, Beaker, Calendar, Shield, Clock, Users } from 'lucide-react';
export default function HomePage() { export default function HomePage() {

View File

@@ -7,8 +7,8 @@ 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 { Building2, Mail, Lock, User, ChevronRight } from 'lucide-react';
import { useAuth } from '@/lib/hooks/useAuth'; import { useAuth } from '@/lib/hooks/useAuth';
import { Button } from '@/components/ui/Button'; import { Button } from '@/components/ui/common/Button';
import { Input } from '@/components/ui/Input'; import { Input } from '@/components/ui/common/Input';
const registerSchema = z.object({ const registerSchema = z.object({
name: z.string().min(2, 'Name must be at least 2 characters'), name: z.string().min(2, 'Name must be at least 2 characters'),
email: z.string().email('Please enter a valid email address'), email: z.string().email('Please enter a valid email address'),

View File

@@ -1,170 +1,12 @@
'use client'; 'use client';
import { useState } from 'react'; import { OrganizationSelectorContent } from '@/components/ui/organization/OrganizationSelectorContent';
import { useAuth } from '@/lib/hooks/useAuth';
import { Building2, Beaker, Mail, Plus } from 'lucide-react';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
export default function SelectOrganizationPage() { export default function SelectOrganizationPage() {
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'
? <Building2 className="h-8 w-8 icon-flat" />
: <Beaker className="h-8 w-8 icon-flat" />;
};
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 (
<div className="min-h-screen app-web-bg flex items-center justify-center">
<p className="text-text-secondary">Loading...</p>
</div>
);
}
return ( return (
<div className="min-h-screen app-web-bg p-4 sm:p-8"> <div className="min-h-screen app-web-bg p-4 sm:p-8">
<div className="max-w-3xl mx-auto"> <div className="max-w-3xl mx-auto">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8"> <OrganizationSelectorContent />
<div>
<h1 className="text-3xl font-semibold text-text-primary">Organizations</h1>
<p className="text-text-secondary mt-2">
Select an organization to continue, or create a new one.
</p>
</div>
<Button
type="button"
variant={isCreateOpen ? 'outline' : 'primary'}
onClick={() => {
clearError();
setIsCreateOpen(prev => !prev);
}}
>
<Plus className="h-4 w-4 mr-2 icon-flat" />
{isCreateOpen ? 'Cancel' : 'Create Organization'}
</Button>
</div>
{isCreateOpen && (
<div className="surface-card p-6 mb-6 space-y-4">
<Input
label="Organization name"
value={organizationName}
onChange={(event) => setOrganizationName(event.target.value)}
placeholder="Sunshine Dental Clinic"
icon={<Building2 className="h-5 w-5 icon-flat" />}
/>
<Input
label="Organization email"
value={organizationEmail}
onChange={(event) => setOrganizationEmail(event.target.value)}
placeholder="contact@sunshineclinic.com"
type="email"
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>
<div className="grid grid-cols-2 gap-3">
<button
type="button"
onClick={() => 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
</button>
<button
type="button"
onClick={() => 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
</button>
</div>
</div>
{error && (
<div className="p-3 bg-red-950/30 border border-red-600/40 rounded-[var(--radius-md)]">
<p className="text-sm text-red-600">{error}</p>
</div>
)}
<div className="flex justify-end">
<Button
type="button"
variant="primary"
onClick={handleCreateOrganization}
isLoading={isLoading}
disabled={!organizationName.trim() || !organizationEmail.trim()}
>
Create and Continue
</Button>
</div>
</div>
)}
{!organizations.length ? (
<div className="surface-card p-8 text-center">
<p className="text-text-secondary">No organizations found. Create your first one to continue.</p>
</div>
) : (
<div className="grid gap-4">
{organizations.map((org) => (
<button
key={org.id}
onClick={() => selectOrganization(org.id)}
className="surface-card p-6 transition-all text-left flex items-center gap-4 hover:border-primary/60"
>
<div className="p-3 bg-primary-soft rounded-[var(--radius-sm)] text-primary">
{getIcon(org.type)}
</div>
<div className="flex-1">
<h3 className="text-lg font-semibold text-text-primary">
{org.name}
</h3>
<p className="text-sm text-text-secondary">
{org.type === 'CLINIC' ? 'Dental Clinic' : 'Dental Lab'}
</p>
</div>
<div className="text-primary text-sm">
Continue
</div>
</button>
))}
</div>
)}
</div> </div>
</div> </div>
); );

View File

@@ -1,7 +1,7 @@
// src/components/ui/OrganizationCard.tsx // src/components/ui/OrganizationCard.tsx
import React from 'react'; import React from 'react';
import { Building2, Beaker, ChevronRight } from 'lucide-react'; import { Building2, Beaker, ChevronRight } from 'lucide-react';
import { Organization } from '@/types'; import type { Organization } from '@/types/organization';
interface OrganizationCardProps { interface OrganizationCardProps {
organization: Organization; organization: Organization;

View File

@@ -13,7 +13,7 @@ import {
CreditCard, CreditCard,
} from 'lucide-react'; } from 'lucide-react';
import { useAuth } from '@/lib/hooks/useAuth'; import { useAuth } from '@/lib/hooks/useAuth';
import { canViewTab } from '@/access'; import { canViewTab } from '@/shared/permissions';
const menu = [ const menu = [
{ name: 'Today', path: '/today', icon: LayoutDashboard, read: 'TAB_TODAY_READ' as const }, { name: 'Today', path: '/today', icon: LayoutDashboard, read: 'TAB_TODAY_READ' as const },

View File

@@ -13,7 +13,7 @@ import {
} from 'lucide-react'; } from 'lucide-react';
import { useAuth } from '@/lib/hooks/useAuth'; import { useAuth } from '@/lib/hooks/useAuth';
import { authApi } from '@/lib/api/auth'; import { authApi } from '@/lib/api/auth';
import type { SubscriptionAlertData } from '@/types'; import type { SubscriptionAlertData } from '@/types/subscription';
function warningTooltip(data: SubscriptionAlertData | null): string { function warningTooltip(data: SubscriptionAlertData | null): string {
if (!data?.showWarning) return ''; if (!data?.showWarning) return '';
@@ -68,7 +68,7 @@ export function DashboardAccountMenu() {
}, [logout]); }, [logout]);
return ( return (
<div className="relative" ref={menuRef}> <div className="relative z-[120]" ref={menuRef}>
<button <button
type="button" type="button"
onClick={() => setOpen((v) => !v)} onClick={() => setOpen((v) => !v)}
@@ -94,7 +94,7 @@ export function DashboardAccountMenu() {
{open && ( {open && (
<div <div
role="menu" role="menu"
className="absolute right-0 mt-2 w-72 rounded-[var(--radius-md)] border border-border bg-background-secondary/95 py-2 shadow-lg z-50 backdrop-blur-sm" className="absolute right-0 mt-2 w-72 rounded-[var(--radius-md)] border border-border bg-background-secondary/95 py-2 shadow-lg z-[200] backdrop-blur-sm"
> >
<div className="px-3 py-2 border-b border-border/60"> <div className="px-3 py-2 border-b border-border/60">
<p className="text-xs text-text-muted">Signed in</p> <p className="text-xs text-text-muted">Signed in</p>
@@ -106,7 +106,7 @@ export function DashboardAccountMenu() {
<div className="py-1"> <div className="py-1">
<Link <Link
href="/select-organization" href="/settings/organizations"
role="menuitem" role="menuitem"
className="flex items-center gap-3 px-3 py-2.5 text-sm text-text-primary hover:bg-background-card/70" className="flex items-center gap-3 px-3 py-2.5 text-sm text-text-primary hover:bg-background-card/70"
onClick={() => setOpen(false)} onClick={() => setOpen(false)}

View File

@@ -0,0 +1,162 @@
'use client';
import { useState } from 'react';
import { useAuth } from '@/lib/hooks/useAuth';
import { Building2, Beaker, Mail, Plus } from 'lucide-react';
import { Input } from '@/components/ui/common/Input';
import { Button } from '@/components/ui/common/Button';
export function OrganizationSelectorContent() {
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) =>
type === 'CLINIC' ? <Building2 className="h-8 w-8 icon-flat" /> : <Beaker className="h-8 w-8 icon-flat" />;
const handleCreateOrganization = async () => {
try {
clearError();
const createdId = await createOrganization(
organizationName.trim(),
organizationEmail.trim(),
organizationType,
);
setOrganizationName('');
setOrganizationEmail('');
setOrganizationType('CLINIC');
setIsCreateOpen(false);
await selectOrganization(createdId);
} catch {
// handled by auth context
}
};
if (isLoading) {
return <p className="text-text-secondary">Loading...</p>;
}
return (
<div className="space-y-6">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h1 className="text-3xl font-semibold text-text-primary">Organizations</h1>
<p className="text-text-secondary mt-2">
Select an organization to continue, or create a new one.
</p>
</div>
<Button
type="button"
variant={isCreateOpen ? 'outline' : 'primary'}
onClick={() => {
clearError();
setIsCreateOpen((prev) => !prev);
}}
>
<Plus className="h-4 w-4 mr-2 icon-flat" />
{isCreateOpen ? 'Cancel' : 'Create Organization'}
</Button>
</div>
{isCreateOpen && (
<div className="surface-card p-6 space-y-4">
<Input
label="Organization name"
value={organizationName}
onChange={(event) => setOrganizationName(event.target.value)}
placeholder="Sunshine Dental Clinic"
icon={<Building2 className="h-5 w-5 icon-flat" />}
/>
<Input
label="Organization email"
value={organizationEmail}
onChange={(event) => setOrganizationEmail(event.target.value)}
placeholder="contact@sunshineclinic.com"
type="email"
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>
<div className="grid grid-cols-2 gap-3">
<button
type="button"
onClick={() => 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
</button>
<button
type="button"
onClick={() => 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
</button>
</div>
</div>
{error && (
<div className="p-3 bg-red-950/30 border border-red-600/40 rounded-[var(--radius-md)]">
<p className="text-sm text-red-600">{error}</p>
</div>
)}
<div className="flex justify-end">
<Button
type="button"
variant="primary"
onClick={handleCreateOrganization}
isLoading={isLoading}
disabled={!organizationName.trim() || !organizationEmail.trim()}
>
Create and Continue
</Button>
</div>
</div>
)}
{!organizations.length ? (
<div className="surface-card p-8 text-center">
<p className="text-text-secondary">No organizations found. Create your first one to continue.</p>
</div>
) : (
<div className="grid gap-4">
{organizations.map((org) => (
<button
key={org.id}
onClick={() => selectOrganization(org.id)}
className="surface-card p-6 transition-all text-left flex items-center gap-4 hover:border-primary/60"
>
<div className="p-3 bg-primary-soft rounded-[var(--radius-sm)] text-primary">
{getIcon(org.type)}
</div>
<div className="flex-1">
<h3 className="text-lg font-semibold text-text-primary">
{org.name}
</h3>
<p className="text-sm text-text-secondary">
{org.type === 'CLINIC' ? 'Dental Clinic' : 'Dental Lab'}
</p>
</div>
<div className="text-primary text-sm">
Continue
</div>
</button>
))}
</div>
)}
</div>
);
}

View File

@@ -1,7 +1,7 @@
'use client'; 'use client';
import { Button } from '@/components/ui/Button'; import { Button } from '@/components/ui/common/Button';
import { Input } from '@/components/ui/Input'; import { Input } from '@/components/ui/common/Input';
import { CreatePatientInput } from '@/types/patient'; import { CreatePatientInput } from '@/types/patient';
interface CreatePatientModalProps { interface CreatePatientModalProps {

View File

@@ -1,7 +1,7 @@
'use client'; 'use client';
import { Search } from 'lucide-react'; import { Search } from 'lucide-react';
import { Input } from '@/components/ui/Input'; import { Input } from '@/components/ui/common/Input';
import { Patient } from '@/types/patient'; import { Patient } from '@/types/patient';
interface PatientSearchSelectProps { interface PatientSearchSelectProps {

View File

@@ -1,6 +1,7 @@
// src/lib/api/auth.ts // src/lib/api/auth.ts
import { apiClient } from './client'; import { apiClient } from './client';
import { AuthResponse, TrialRegistrationData, LoginData, SubscriptionAlertData } from '@/types'; import type { AuthResponse, TrialRegistrationData, LoginData } from '@/types/auth';
import type { SubscriptionAlertData } from '@/types/subscription';
export const authApi = { export const authApi = {
// Register a new trial organization // Register a new trial organization

View File

@@ -1,6 +1,6 @@
// src/lib/api/client.ts // src/lib/api/client.ts
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios'; import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
import { ApiError } from '@/types'; import type { ApiError } from '@/types/api';
interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig { interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
_retry?: boolean; _retry?: boolean;

View File

@@ -3,7 +3,7 @@
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'; import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { authApi } from '@/lib/api/auth'; import { authApi } from '@/lib/api/auth';
import { User, Organization } from '@/types'; import { User, Organization } from '@/types/organization';
interface AuthContextType { interface AuthContextType {
user: User | null; user: User | null;

View File

@@ -1,29 +1,22 @@
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']; const publicRoutes = ['/', '/login', '/register', '/terms', '/privacy', '/forgot-password'];
export function middleware(request: NextRequest) { export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl; const { pathname } = request.nextUrl;
const token = request.cookies.get('accessToken')?.value; const token = request.cookies.get('accessToken')?.value;
const isAuthenticated = !!token; const isAuthenticated = !!token;
// If a logged-in user opens home, send them to dashboard.
if (isAuthenticated && pathname === '/') { if (isAuthenticated && pathname === '/') {
return NextResponse.redirect(new URL('/today', request.url)); return NextResponse.redirect(new URL('/today', request.url));
} }
// 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 (publicRoutes.includes(pathname)) {
return NextResponse.next(); return NextResponse.next();
} }
// Protected routes: redirect to login if no token
if (!isAuthenticated) { if (!isAuthenticated) {
// Prevent loop: if somehow redirecting to login from login, just continue
if (pathname === '/login') { if (pathname === '/login') {
return NextResponse.next(); return NextResponse.next();
} }
@@ -40,4 +33,4 @@ export const config = {
matcher: [ matcher: [
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)', '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
], ],
}; };

View File

@@ -1,4 +1,4 @@
import type { Organization } from '@/types'; import type { Organization } from '@/types/organization';
const ROUTE_TAB_READ: { prefix: string; permission: string }[] = [ const ROUTE_TAB_READ: { prefix: string; permission: string }[] = [
{ prefix: '/today', permission: 'TAB_TODAY_READ' }, { prefix: '/today', permission: 'TAB_TODAY_READ' },

View File

@@ -0,0 +1,5 @@
export interface ApiError {
statusCode: number;
message: string | string[];
error?: string;
}

View File

@@ -0,0 +1,25 @@
import type { Organization, User } from './organization';
export interface AuthResponse {
success: boolean;
data: {
accessToken: string;
refreshToken: string;
user: User;
organizations: Organization[];
};
}
export interface TrialRegistrationData {
email: string;
password: string;
name: string;
organizationName: string;
organizationEmail: string;
organizationType: 'CLINIC' | 'LAB';
}
export interface LoginData {
email: string;
password: string;
}

View File

@@ -1,60 +1,5 @@
// src/types/index.ts export * from './organization';
export interface User { export * from './subscription';
id: string; export * from './auth';
email: string; export * from './api';
name: string; export * from './patient';
}
export interface Organization {
id: string;
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: {
accessToken: string;
refreshToken: string;
user: User;
organizations: Organization[];
};
}
export interface TrialRegistrationData {
email: string;
password: string;
name: string;
organizationName: string;
organizationEmail: string;
organizationType: 'CLINIC' | 'LAB';
}
export interface LoginData {
email: string;
password: string;
}
export interface ApiError {
statusCode: number;
message: string | string[];
error?: string;
}

View File

@@ -0,0 +1,20 @@
export interface User {
id: string;
email: string;
name: string;
}
export interface OrganizationPlan {
name: string;
maxUsers: number;
price?: number;
}
export interface Organization {
id: string;
name: string;
type: 'CLINIC' | 'LAB';
isOwner: boolean;
permissions?: string[];
plan?: OrganizationPlan;
}

View File

@@ -0,0 +1,13 @@
/** 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;
daysUntilPlanEnd?: number | null;
planEndsAt?: string | null;
}