Initial commit: Full project structure

- Backend: NestJS with Docker
- Frontend: Next.js with Docker
- Nginx configuration for reverse proxy
- PostgreSQL setup
- Docker compose for orchestration
- Development environment configuration
This commit is contained in:
2026-04-23 15:33:11 +03:30
commit 26bd35ae3c
94 changed files with 5627 additions and 0 deletions

View File

@@ -0,0 +1,202 @@
// src/app/(dashboard)/billing/page.tsx
'use client';
import { useState } from 'react';
import { Search, Filter, Plus } from 'lucide-react';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Badge } from '@/components/ui/Badge';
// Mock data matching your design
const invoices = [
{ id: '#123456', patient: 'Ali Rahmani', date: '24/9/2026', service: 'Hygiene', amount: 300, paid: 0, status: 'unpaid' },
{ id: '#123457', patient: 'Neda Akbari', date: '01/10/2026', service: 'Filling', amount: 700, paid: 400, status: 'overdue' },
{ id: '#123458', patient: 'Nima Haghi', date: '09/12/2026', service: 'Extraction', amount: 450, paid: 450, status: 'paid' },
];
const statusColors = {
paid: 'success',
unpaid: 'warning',
overdue: 'danger',
} as const;
type StatCardColor = 'blue' | 'yellow' | 'green' | 'red';
interface StatCardProps {
title: string;
count: number;
amount: number;
color: StatCardColor;
}
export default function BillingPage() {
const [search, setSearch] = useState('');
const [statusFilter, setStatusFilter] = useState('all');
const stats = {
total: { count: 235, amount: 80900 },
unpaid: { count: 30, amount: 2800 },
paid: { count: 190, amount: 80900 },
overdue: { count: 235, amount: 80900 },
};
return (
<div className="space-y-6">
{/* Header */}
<div className="flex justify-between items-center">
<h1 className="text-2xl font-bold text-gray-900">Billing</h1>
<Button variant="primary" className="flex items-center gap-2">
<Plus className="h-4 w-4" />
New Invoice
</Button>
</div>
{/* Stats Cards - Matching your design */}
<div className="grid grid-cols-4 gap-4">
<StatCard
title="Total Invoices"
count={stats.total.count}
amount={stats.total.amount}
color="blue"
/>
<StatCard
title="Unpaid Invoices"
count={stats.unpaid.count}
amount={stats.unpaid.amount}
color="yellow"
/>
<StatCard
title="Paid Invoices"
count={stats.paid.count}
amount={stats.paid.amount}
color="green"
/>
<StatCard
title="Overdue Invoices"
count={stats.overdue.count}
amount={stats.overdue.amount}
color="red"
/>
</div>
{/* Filters */}
<div className="bg-white p-4 rounded-xl shadow-sm border">
<div className="flex gap-4 items-center">
<div className="flex-1">
<Input
placeholder="Search patients..."
value={search}
onChange={(e) => setSearch(e.target.value)}
icon={<Search className="h-4 w-4 text-gray-400" />}
/>
</div>
<div className="flex gap-2">
{['all', 'paid', 'unpaid', 'overdue'].map((status) => (
<button
key={status}
onClick={() => setStatusFilter(status)}
className={`px-4 py-2 rounded-lg text-sm font-medium capitalize ${statusFilter === status
? 'bg-primary-50 text-primary-700 border border-primary-200'
: 'text-gray-600 hover:bg-gray-50'
}`}
>
{status}
</button>
))}
</div>
</div>
</div>
{/* Invoices Table - Matching your design */}
<div className="bg-white rounded-xl shadow-sm border overflow-hidden">
<table className="w-full">
<thead className="bg-gray-50 border-b">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Invoice ID
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Patient name
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Date
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Service
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Total amount
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Paid
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Status
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Action
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{invoices.map((invoice) => (
<tr key={invoice.id} className="hover:bg-gray-50">
<td className="px-6 py-4 text-sm font-medium text-gray-900">
{invoice.id}
</td>
<td className="px-6 py-4 text-sm text-gray-900">
{invoice.patient}
</td>
<td className="px-6 py-4 text-sm text-gray-500">
{invoice.date}
</td>
<td className="px-6 py-4 text-sm text-gray-900">
{invoice.service}
</td>
<td className="px-6 py-4 text-sm text-gray-900">
${invoice.amount}
</td>
<td className="px-6 py-4 text-sm text-gray-900">
${invoice.paid}
</td>
<td className="px-6 py-4">
<Badge
variant={statusColors[invoice.status as keyof typeof statusColors]}
className="capitalize"
>
{invoice.status}
</Badge>
</td>
<td className="px-6 py-4">
<button className="text-primary-600 hover:text-primary-800 text-sm">
Edit
</button>
</td>
</tr>
))}
</tbody>
</table>
{/* Pagination - Matching your design */}
<div className="px-6 py-4 border-t flex justify-between items-center bg-gray-50">
<button className="text-sm text-gray-600 hover:text-gray-900">
Previous
</button>
<div className="text-sm text-gray-600">
Page 1 of 10
</div>
<button className="text-sm text-gray-600 hover:text-gray-900">
Next
</button>
</div>
</div>
</div>
);
}
function StatCard({ title, count, amount, color }: StatCardProps) {
const colors: Record<StatCardColor, string> = {
blue: 'bg-blue-50 text-blue-700 border-blue-200',
yellow: 'bg-yellow-50 text-yellow-700 border-yellow-200',
green: 'bg-green-50 text-green-700 border-green-200',
red: 'bg-red-50 text-red-700 border-red-200',
};
return (
<div className={`p-4 rounded-xl border ${colors[color]}`}>
<p className="text-sm font-medium opacity-80">{title}</p>
<p className="text-2xl font-bold mt-1">{count}</p>
<p className="text-sm font-medium mt-1">
${amount.toLocaleString()}
</p>
</div>
);
}

View File

@@ -0,0 +1,73 @@
'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/hooks/useAuth';
import Sidebar from '@/components/ui/Sidebar';
import { LogOut } from 'lucide-react';
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
const { user, currentOrganization, isAuthReady, logout } = useAuth();
const router = useRouter();
console.log('LAYOUT STATE:', {
user,
currentOrganization,
isAuthReady
});
// ✅ AUTH GUARD (runs once per navigation group)
useEffect(() => {
if (!isAuthReady) return;
if (!user) {
router.replace('/login');
return;
}
if (!currentOrganization) {
router.replace('/select-organization');
return;
}
}, [isAuthReady, user, currentOrganization, router]);
// ✅ LOADING ONLY FOR INITIAL LOAD
if (!isAuthReady) {
return (
<div className="h-screen flex items-center justify-center">
Loading app...
</div>
);
}
if (!user || !currentOrganization) {
return (
<div className="h-screen flex items-center justify-center">
Loading workspace...
</div>
);
}
return (
<div className="flex h-screen bg-[#020d1a] text-white">
<Sidebar />
<div className="flex-1 flex flex-col">
<header className="flex justify-between px-6 py-4 border-b border-white/10">
<h2>{currentOrganization.name}</h2>
<div className="flex gap-4">
<span>{user.name}</span>
<button onClick={logout}>
<LogOut />
</button>
</div>
</header>
<main className="p-6 flex-1 overflow-y-auto">
{children} {/* 🔥 THIS CHANGES */}
</main>
</div>
</div>
);
}

View File

@@ -0,0 +1,36 @@
export default function TodayPage() {
return (
<div>
<h1 className="text-2xl font-bold mb-6">
Welcome back Babak !!
</h1>
<div className="grid grid-cols-4 gap-4">
<Card title="Today's Appointments" value="12" sub="Monday 2/5/2026" />
<Card title="Active Patients" value="675" />
<Card title="New Lab Case" value="5" sub="35 ↑" />
<Card title="Today invoices" value="1200$" sub="21,300 $" />
</div>
</div>
);
}
function Card({
title,
value,
sub,
}: {
title: string;
value: string;
sub?: string;
}) {
return (
<div className="bg-white/5 border border-white/10 p-4 rounded-xl">
<p className="text-sm text-gray-300">{title}</p>
<p className="text-2xl font-bold mt-2">{value}</p>
{sub && <p className="text-xs text-gray-400 mt-1">{sub}</p>}
</div>
);
}

View File

@@ -0,0 +1,243 @@
// src/app/login/page.tsx
// 'use client';
// import { useState } from 'react';
// import { useForm } from 'react-hook-form';
// import { zodResolver } from '@hookform/resolvers/zod';
// import * as z from 'zod';
// import Link from 'next/link';
// import { Mail, Lock } from 'lucide-react';
// import { useAuth } from '@/lib/hooks/useAuth';
// import { Button } from '@/components/ui/Button';
// import { Input } from '@/components/ui/Input';
// const loginSchema = z.object({
// email: z.string().email('Please enter a valid email address'),
// password: z.string().min(1, 'Password is required'),
// });
// type LoginForm = z.infer<typeof loginSchema>;
// export default function LoginPage() {
// const { login, isLoading } = useAuth();
// const [error, setError] = useState<string | null>(null);
// const {
// register,
// handleSubmit,
// formState: { errors },
// } = useForm<LoginForm>({
// resolver: zodResolver(loginSchema),
// });
// const onSubmit = async (data: LoginForm) => {
// try {
// setError(null);
// await login(data.email, data.password);
// } catch (err: any) {
// setError(err.message || 'Invalid email or password');
// }
// };
// return (
// <div className="min-h-screen bg-gray-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
// <div className="sm:mx-auto sm:w-full sm:max-w-md">
// <Link href="/" className="flex justify-center">
// <span className="text-3xl font-bold text-primary-600">DyoLink</span>
// </Link>
// <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
// Sign in to your account
// </h2>
// <p className="mt-2 text-center text-sm text-gray-600">
// Or{' '}
// <Link href="/register" className="font-medium text-primary-600 hover:text-primary-500">
// start your free trial
// </Link>
// </p>
// </div>
// <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
// <div className="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
// <form className="space-y-6" onSubmit={handleSubmit(onSubmit)}>
// <Input
// label="Email address"
// {...register('email')}
// type="email"
// placeholder="you@example.com"
// error={errors.email?.message}
// icon={<Mail className="h-5 w-5 text-gray-400" />}
// />
// <Input
// label="Password"
// {...register('password')}
// type="password"
// placeholder="••••••••"
// error={errors.password?.message}
// icon={<Lock className="h-5 w-5 text-gray-400" />}
// />
// <div className="flex items-center justify-between">
// <div className="flex items-center">
// <input
// id="remember-me"
// name="remember-me"
// type="checkbox"
// className="h-4 w-4 text-primary-600 focus:ring-primary-500border-gray-300 rounded"
// />
// <label htmlFor="remember-me" className="ml-2 block text-sm text-gray-900">
// Remember me
// </label>
// </div>
// <div className="text-sm">
// <Link href="/forgot-password" className="font-medium text-primary-600 hover:text-primary-500">
// Forgot your password?
// </Link>
// </div>
// </div>
// {error && (
// <div className="p-3 bg-red-50 border border-red-200 rounded-lg">
// <p className="text-sm text-red-600">{error}</p>
// </div>
// )}
// <Button
// type="submit"
// variant="primary"
// isLoading={isLoading}
// fullWidth
// >
// Sign in
// </Button>
// </form>
// </div>
// </div>
// </div>
// );
// }
'use client';
import { useState, useEffect } from 'react'; // ← added useEffect
import { useRouter } from 'next/navigation'; // ← added this
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import Link from 'next/link';
import { Mail, Lock } from 'lucide-react';
import { useAuth } from '@/lib/hooks/useAuth';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
const loginSchema = z.object({
email: z.string().email('Please enter a valid email address'),
password: z.string().min(1, 'Password is required'),
});
type LoginForm = z.infer<typeof loginSchema>;
export default function LoginPage() {
const { login, isLoading, user, isAuthReady } = useAuth(); // ← added user + isAuthReady
const router = useRouter(); // ← added
const [error, setError] = useState<string | null>(null);
// ✅ Redirect if user is already logged in (prevents loop & improves UX)
useEffect(() => {
if (isAuthReady && user) {
router.push('/today'); // Change to '/select-organization' if you want
}
}, [user, isAuthReady, router]);
const {
register,
handleSubmit,
formState: { errors },
} = useForm<LoginForm>({
resolver: zodResolver(loginSchema),
});
const onSubmit = async (data: LoginForm) => {
try {
setError(null);
await login(data.email, data.password);
} catch (err: any) {
setError(err.message || 'Invalid email or password');
}
};
// Optional: Show loading state while checking auth
if (!isAuthReady) {
return (
<div className="min-h-screen flex items-center justify-center">
<p>Loading...</p>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
<div className="sm:mx-auto sm:w-full sm:max-w-md">
<Link href="/" className="flex justify-center">
<span className="text-3xl font-bold text-primary-600">DyoLink</span>
</Link>
<h2 className="mt-6 text-center text-3xl font-exbol text-gray-900">
Sign in to your account
</h2>
<p className="mt-2 text-center text-sm text-gray-600">
Or{' '}
<Link href="/register" className="font-medium text-primary-600 hover:text-primary-500">
start your free trial
</Link>
</p>
</div>
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
<div className="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
<form className="space-y-6" onSubmit={handleSubmit(onSubmit)}>
<Input
label="Email address"
{...register('email')}
type="email"
placeholder="you@example.com"
error={errors.email?.message}
icon={<Mail className="h-5 w-5 text-gray-400" />}
/>
<Input
label="Password"
{...register('password')}
type="password"
placeholder="••••••••"
error={errors.password?.message}
icon={<Lock className="h-5 w-5 text-gray-400" />}
/>
<div className="flex items-center justify-between">
<div className="flex items-center">
<input
id="remember-me"
name="remember-me"
type="checkbox"
className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
/>
<label htmlFor="remember-me" className="ml-2 block text-sm text-gray-900">
Remember me
</label>
</div>
<div className="text-sm">
<Link href="/forgot-password" className="font-medium text-primary-600 hover:text-primary-500">
Forgot your password?
</Link>
</div>
</div>
{error && (
<div className="p-3 bg-red-50 border border-red-200 rounded-lg">
<p className="text-sm text-red-600">{error}</p>
</div>
)}
<Button
type="submit"
variant="primary"
isLoading={isLoading}
fullWidth
>
Sign in
</Button>
</form>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,149 @@
'use client';
import Link from 'next/link';
import { useAuth } from '@/lib/hooks/useAuth';
import { Button } from '@/components/ui/Button';
import { Building2, Beaker, Calendar, Shield, Clock, Users } from 'lucide-react';
export default function HomePage() {
const { user } = useAuth();
return (
<div className="min-h-screen bg-background-primary">
{/* Header */}
<header className="border-b border-border bg-background-secondary/80 backdrop-blur-sm fixed top-0 w-full z-10">
<div className="container mx-auto px-4 py-4 flex justify-between items-center">
<div className="text-2xl font-semibold text-primary">
DyoLink
</div>
<div className="flex gap-3">
{user ? (
<Link href="/today">
<Button variant="primary">Dashboard</Button>
</Link>
) : (
<>
<Link href="/login">
<Button variant="outline">Login</Button>
</Link>
<Link href="/register">
<Button variant="primary">Start Trial</Button>
</Link>
</>
)}
</div>
</div>
</header>
{/* Hero Section */}
<main className="container mx-auto px-4 pt-32 pb-20">
<div className="max-w-4xl mx-auto text-center">
<h1 className="text-5xl md:text-6xl font-semibold text-text-primary mb-6 leading-tight">
Connect Dental Clinics & Labs
<span className="text-primary"> Seamlessly</span>
</h1>
<p className="text-lg text-text-secondary mb-8 max-w-2xl mx-auto">
Streamline communication between dental professionals. Start with
a 30-day free trial, no credit card required.
</p>
{!user && (
<Link href="/register">
<Button size="lg" variant="primary" className="px-8">
Start Free Trial
</Button>
</Link>
)}
</div>
{/* Features */}
<div className="mt-20 grid md:grid-cols-3 gap-6">
<FeatureCard
icon={<Building2 className="h-6 w-6" />}
title="For Clinics"
description="Manage patients, appointments, and send cases to labs instantly."
/>
<FeatureCard
icon={<Beaker className="h-6 w-6" />}
title="For Labs"
description="Receive cases, track progress, and communicate with clinics."
/>
<FeatureCard
icon={<Users className="h-6 w-6" />}
title="Team Management"
description="Add up to 5 team members during trial. Scale as you grow."
/>
<FeatureCard
icon={<Calendar className="h-6 w-6" />}
title="30-Day Trial"
description="Full access to all features. No credit card required."
/>
<FeatureCard
icon={<Clock className="h-6 w-6" />}
title="Real-time Updates"
description="Get instant notifications on case status changes."
/>
<FeatureCard
icon={<Shield className="h-6 w-6" />}
title="Secure & Compliant"
description="HIPAA-compliant with enterprise-grade security."
/>
</div>
</main>
{/* Footer */}
<footer className="border-t border-border bg-background-secondary">
<div className="container mx-auto px-4 py-8 flex flex-col md:flex-row justify-between items-center text-sm text-text-secondary">
<div>© 2026 DyoLink. All rights reserved.</div>
<div className="flex gap-6 mt-4 md:mt-0">
<Link href="/terms" className="hover:text-primary transition-colors">
Terms & Conditions
</Link>
<Link href="/privacy" className="hover:text-primary transition-colors">
Privacy Policy
</Link>
</div>
</div>
</footer>
</div>
);
}
function FeatureCard({
icon,
title,
description,
}: {
icon: React.ReactNode;
title: string;
description: string;
}) {
return (
<div className="bg-background-card border border-border rounded-2xl p-5 transition-all hover:border-primary hover:shadow-[0_0_20px_rgba(0,194,255,0.15)]">
<div className="text-primary mb-4">
{icon}
</div>
<h3 className="text-base font-medium text-text-primary mb-2">
{title}
</h3>
<p className="text-sm text-text-secondary">
{description}
</p>
</div>
);
}

View File

@@ -0,0 +1,265 @@
// src/app/register/page.tsx\
'use client';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Building2, Mail, Lock, User, ChevronRight } from 'lucide-react';
import { useAuth } from '@/lib/hooks/useAuth';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
const registerSchema = z.object({
name: z.string().min(2, 'Name must be at least 2 characters'),
email: z.string().email('Please enter a valid email address'),
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'),
organizationType: z.enum(['CLINIC', 'LAB'], {
message: 'Please select organization type',
}),
}).refine((data) => data.password === data.confirmPassword, {
message: "Passwords don't match",
path: ['confirmPassword'],
});
type RegisterForm = z.infer<typeof registerSchema>;
export default function RegisterPage() {
const { registerTrial, isLoading } = useAuth();
const router = useRouter();
const [step, setStep] = useState(1);
const [error, setError] = useState<string | null>(null);
const {
register,
handleSubmit,
watch,
formState: { errors },
trigger,
setValue,
} = useForm<RegisterForm>({
resolver: zodResolver(registerSchema),
mode: 'onChange',
});
const organizationType = watch('organizationType');
const handleNext = async () => {
const fieldsToValidate = step === 1
? ['name', 'email', 'password', 'confirmPassword']
: ['organizationName', 'organizationType'];
const isValid = await trigger(fieldsToValidate as any);
if (isValid) {
setStep(step + 1);
}
};
const onSubmit = async (data: RegisterForm) => {
try {
setError(null);
await registerTrial(
data.email,
data.password,
data.name,
data.organizationName,
data.organizationType
);
// No need to redirect - auth context will handle it
} catch (err: any) {
setError(err.message || 'Registration failed. Please try again.');
}
};
return (
<div className="min-h-screen bg-gray-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
<div className="sm:mx-auto sm:w-full sm:max-w-md">
<Link href="/" className="flex justify-center">
<span className="text-3xl font-bold text-primary-600">DyoLink</span>
</Link>
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
Start your 30-day free trial
</h2>
<p className="mt-2 text-center text-sm text-gray-600">
Already have an account?{' '}
<Link href="/login" className="font-medium text-primary-600 hover:text-primary-500">
Sign in
</Link>
</p>
</div>
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
<div className="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
{/* Progress Steps */}
<div className="mb-8">
<div className="flex items-center justify-between">
<div className="flex items-center">
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${step >= 1 ? 'bg-primary-600 text-white' : 'bg-gray-200 text-gray-600'}`}>
1
</div>
<div className={`ml-2 text-sm font-medium ${step >= 1 ? 'text-primary-600' : 'text-gray-500'
}`}>
Account
</div>
</div>
<ChevronRight className="h-5 w-5 text-gray-400" />
<div className="flex items-center">
<div className={`w-8 h-8 rounded-full flex items-center justify-center ${step >= 2 ? 'bg-primary-600 text-white' : 'bg-gray-200 text-gray-600'}`}>
2
</div>
<div className={`ml-2 text-sm font-medium ${step >= 2 ? 'text-primary-600' : 'text-gray-500'
}`}>
Organization
</div>
</div>
</div>
</div>
{/* Trial Info Banner */}
<div className="mb-6 p-4 bg-blue-50 rounded-lg border border-blue-100">
<h3 className="text-sm font-medium text-blue-800 mb-2">Your trial
includes:</h3>
<ul className="text-sm text-blue-700 space-y-1">
<li className="flex items-center">
<span className="mr-2"></span> Up to 5 team members
</li>
<li className="flex items-center">
<span className="mr-2"></span> Full access to all features
</li>
<li className="flex items-center">
<span className="mr-2"></span> 30 days free, no credit card
required
</li>
</ul>
</div>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
{step === 1 && (
<>
<Input
label="Full name"
{...register('name')}
placeholder="John Doe"
error={errors.name?.message}
icon={<User className="h-5 w-5 text-gray-400" />}
/>
<Input
label="Email address"
{...register('email')}
type="email"
placeholder="you@example.com"
error={errors.email?.message}
icon={<Mail className="h-5 w-5 text-gray-400" />}
/>
<Input
label="Password"
{...register('password')}
type="password"
placeholder="••••••••"
error={errors.password?.message}
icon={<Lock className="h-5 w-5 text-gray-400" />}
/>
<Input
label="Confirm password"
{...register('confirmPassword')}
type="password"
placeholder="••••••••"
error={errors.confirmPassword?.message}
icon={<Lock className="h-5 w-5 text-gray-400" />}
/>
<Button
type="button"
variant="primary"
onClick={handleNext}
fullWidth
>
Continue
</Button>
</>
)}
{step === 2 && (
<>
<Input
label="Organization name"
{...register('organizationName')}
placeholder="Sunshine Dental Clinic"
error={errors.organizationName?.message}
icon={<Building2 className="h-5 w-5 text-gray-400" />}
/>
<div>
<label className="block text-sm font-medium text-gray-700 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-lg text-center transition-colors ${organizationType === 'CLINIC' ? 'border-primary-600 bg-primary-50 text-primary-700'
: 'border-gray-300 hover:border-gray-400'
}`}
>
<Building2 className="h-8 w-8 mx-auto mb-2" />
<span className="text-sm font-medium">Dental Clinic</span>
</button>
<button
type="button"
onClick={() => {
setValue('organizationType', 'LAB', { shouldValidate: true });
}}
className={`p-4 border rounded-lg text-center transition-colors ${organizationType === 'LAB'
? 'border-primary-600 bg-primary-50 text-primary-700'
: 'border-gray-300 hover:border-gray-400'
}`}
>
<Building2 className="h-8 w-8 mx-auto mb-2" />
<span className="text-sm font-medium">Dental Lab</span>
</button>
</div>
{errors.organizationType && (
<p className="mt-2 text-sm text-red-600">{errors.organizationType.message}</p>
)}
</div>
{error && (
<div className="p-3 bg-red-50 border border-red-200 rounded-lg">
<p className="text-sm text-red-600">{error}</p>
</div>
)}
<div className="flex gap-3">
<Button
type="button"
variant="outline"
onClick={() => setStep(1)}
>
Back
</Button>
<Button
type="submit"
variant="primary"
isLoading={isLoading}
fullWidth
>
Start my free trial
</Button>
</div>
</>
)}
</form>
<p className="mt-6 text-xs text-center text-gray-500">
By signing up, you agree to our{' '}
<Link href="/terms" className="text-primary-600 hover:text-primary-500">
Terms of Service
</Link>{' '}
and{' '}
<Link href="/privacy" className="text-primary-600 hover:text-primary-500">
Privacy Policy
</Link>
</p>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,82 @@
'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/hooks/useAuth';
import { Building2, Beaker } from 'lucide-react';
export default function SelectOrganizationPage() {
const { organizations, selectOrganization, isLoading } = useAuth();
const router = useRouter();
// ✅ Auto-redirect if only one organization
useEffect(() => {
if (!isLoading && organizations.length === 1) {
selectOrganization(organizations[0].id);
}
}, [organizations, isLoading]);
const getIcon = (type: string) => {
return type === 'CLINIC'
? <Building2 className="h-8 w-8" />
: <Beaker className="h-8 w-8" />;
};
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<p className="text-text-secondary">Loading organizations...</p>
</div>
);
}
if (!organizations.length) {
return (
<div className="min-h-screen flex items-center justify-center">
<p className="text-text-secondary">No organizations found.</p>
</div>
);
}
return (
<div className="min-h-screen bg-background-secondary flex items-center justify-center p-4">
<div className="max-w-2xl w-full">
<div className="text-center mb-8">
<h1 className="text-3xl font-bold text-text-primary">
Choose Organization
</h1>
<p className="text-text-secondary mt-2">
You have access to multiple organizations. Select one to continue.
</p>
</div>
<div className="grid gap-4">
{organizations.map((org) => (
<button
key={org.id}
onClick={() => selectOrganization(org.id)}
className="bg-white p-6 rounded-xl shadow-sm border border-border hover:border-primary-300 hover:shadow-md transition-all text-left flex items-center gap-4"
>
<div className="p-3 bg-primary-50 rounded-lg text-primary-600">
{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-600 text-sm">
Continue
</div>
</button>
))}
</div>
</div>
</div>
);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -0,0 +1,25 @@
// src/app/layout.tsx
import type { Metadata } from 'next';
import '@/styles/globals.css';
import { AuthProvider } from '@/lib/hooks/useAuth';
export const metadata: Metadata = {
title: 'DyoLink - Dental Clinic & Lab Communication Hub',
description: 'Connect dental clinics and laboratories seamlessly',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<AuthProvider>
{children}
</AuthProvider>
</body>
</html>
);
}

View File

@@ -0,0 +1,31 @@
//src/components/ui/Badge.tsx
import React from 'react';
type BadgeVariant = 'success' | 'warning' | 'danger' | 'default';
interface BadgeProps {
children: React.ReactNode;
variant?: BadgeVariant;
className?: string;
}
const variantStyles: Record<BadgeVariant, string> = {
success: 'bg-green-50 text-green-700 border-green-200',
warning: 'bg-yellow-50 text-yellow-700 border-yellow-200',
danger: 'bg-red-50 text-red-700 border-red-200',
default: 'bg-gray-50 text-gray-700 border-gray-200',
};
export function Badge({
children,
variant = 'default',
className,
}: BadgeProps) {
return (
<span
className={`px-2 py-1 text-xs font-medium rounded-lg border inline-block ${variantStyles[variant]} ${className || ''}`}
>
{children}
</span>
);
}

View File

@@ -0,0 +1,67 @@
// src/components/ui/Button.tsx
import React from 'react';
import { Loader2 } from 'lucide-react';
type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'danger' | 'ghost';
type ButtonSize = 'sm' | 'md' | 'lg';
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: ButtonVariant;
size?: ButtonSize;
isLoading?: boolean;
fullWidth?: boolean;
children: React.ReactNode;
}
export const Button: React.FC<ButtonProps> = ({
variant = 'primary',
size = 'md',
isLoading = false,
fullWidth = false,
children,
className = '',
disabled,
...props
}) => {
const baseClasses =
'inline-flex items-center justify-center rounded-lg font-medium transition-all duration-200 ' +
'focus:outline-none focus:ring-2 focus:ring-primary disabled:opacity-50 disabled:cursor-not-allowed';
const variantClasses: Record<ButtonVariant, string> = {
primary:
'bg-primary text-black hover:opacity-90',
secondary:
'bg-background-secondary text-text-primary hover:bg-background-card',
outline:
'border border-border text-text-primary hover:bg-background-card',
danger:
'bg-red-600 text-white hover:bg-red-700',
ghost:
'text-text-secondary hover:bg-background-card',
};
const sizeClasses: Record<ButtonSize, string> = {
sm: 'px-3 py-1.5 text-sm',
md: 'px-4 py-2 text-sm',
lg: 'px-6 py-3 text-base',
};
const widthClass = fullWidth ? 'w-full' : '';
return (
<button
className={`${baseClasses} ${variantClasses[variant]} ${sizeClasses[size]} ${widthClass} ${className}`}
disabled={disabled || isLoading}
{...props}
>
{isLoading && (
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
)}
{children}
</button>
);
};

View File

@@ -0,0 +1,67 @@
// src/components/ui/Input.tsx
import React, { forwardRef } from 'react';
interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
label?: string;
error?: string;
icon?: React.ReactNode;
}
export const Input = forwardRef<HTMLInputElement, InputProps>(
({ label, error, icon, className = '', id, ...props }, ref) => {
const inputId =
id || `input-${Math.random().toString(36).slice(2, 9)}`;
return (
<div className="w-full">
{label && (
<label
htmlFor={inputId}
className="block text-sm font-medium text-text-secondary mb-1"
>
{label}
</label>
)}
<div className="relative">
{icon && (
<div className="absolute inset-y-0 left-0 pl-3 flex items-center text-text-secondary pointer-events-none">
{icon}
</div>
)}
<input
ref={ref}
id={inputId}
className={`
w-full rounded-lg border
${error ? 'border-red-500' : 'border-border'}
bg-background-secondary text-text-primary
${icon ? 'pl-10' : 'pl-4'} pr-4 py-2
placeholder:text-text-secondary
focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent
disabled:opacity-50 disabled:cursor-not-allowed
transition-all duration-200
${className}
`}
{...props}
/>
</div>
{error && (
<p className="mt-1 text-sm text-red-500">
{error}
</p>
)}
</div>
);
}
);
Input.displayName = 'Input';

View File

@@ -0,0 +1,38 @@
// src/components/ui/OrganizationCard.tsx
import React from 'react';
import { Building2, Beaker, ChevronRight } from 'lucide-react';
import { Organization } from '@/types';
interface OrganizationCardProps {
organization: Organization;
onSelect: (id: string) => void;
}
export const OrganizationCard: React.FC<OrganizationCardProps> = ({
organization,
onSelect,
}) => {
const Icon = organization.type === 'CLINIC' ? Building2 : Beaker;
const typeText = organization.type === 'CLINIC' ? 'Dental Clinic' : 'Dental Lab';
return (
<button
onClick={() => onSelect(organization.id)}
className="w-full bg-white p-6 rounded-xl shadow-sm border border-gray-200 hover:border-primary-300 hover:shadow-md transition-all text-left flex items-center gap-4 group"
>
<div className="p-3 bg-primary-50 rounded-lg text-primary-600">
<Icon className="h-8 w-8" />
</div>
<div className="flex-1">
<h3 className="text-lg font-semibold text-gray-900">{organization.name}</h3>
<p className="text-sm text-gray-500">{typeText}</p>
{organization.plan && (
<p className="text-xs text-gray-400 mt-1">
Plan: {organization.plan.name} {organization.plan.maxUsers} users
</p>
)}
</div>
<ChevronRight className="h-5 w-5 text-gray-400 group-hover:text-primary-600 transition-colors" />
</button>
);
};

View File

@@ -0,0 +1,57 @@
'use client';
import { usePathname, useRouter } from 'next/navigation';
import {
LayoutDashboard,
Users,
Calendar,
UserCog,
FlaskConical,
FileText,
CreditCard
} from 'lucide-react';
const menu = [
{ name: 'Today', path: '/today', icon: LayoutDashboard },
{ name: 'Patients', path: '/patients', icon: Users },
{ name: 'Appointments', path: '/appointments', icon: Calendar },
{ name: 'Staff Management', path: '/staff', icon: UserCog },
{ name: 'Lab Management', path: '/lab', icon: FlaskConical },
{ name: 'Billing', path: '/billing', icon: CreditCard },
{ name: 'Reports', path: '/reports', icon: FileText },
];
export default function Sidebar() {
const pathname = usePathname();
const router = useRouter();
return (
<aside className="w-64 bg-[#071a2f] text-white flex flex-col p-4">
<div className="mb-8">
<h1 className="text-xl font-bold">DyoLink</h1>
</div>
<nav className="flex flex-col gap-2">
{menu.map((item) => {
const Icon = item.icon;
const isActive = pathname === item.path;
return (
<button
key={item.name}
onClick={() => router.push(item.path)}
className={`flex items-center gap-3 p-3 rounded-lg transition ${
isActive
? 'bg-primary-600'
: 'hover:bg-white/10'
}`}
>
<Icon className="w-5 h-5" />
<span>{item.name}</span>
</button>
);
})}
</nav>
</aside>
);
}

View File

@@ -0,0 +1,40 @@
// src/lib/api/auth.ts
import { apiClient } from './client';
import { AuthResponse, TrialRegistrationData, LoginData } from '@/types';
export const authApi = {
// Register a new trial organization
registerTrial: async (data: TrialRegistrationData): Promise<AuthResponse> => {
const response = await apiClient.post('/auth/register', data);
return response.data;
},
// Login user
login: async (data: LoginData): Promise<AuthResponse> => {
const response = await apiClient.post('/auth/login', data);
return response.data;
},
// Get user profile
getProfile: async (): Promise<AuthResponse> => {
const response = await apiClient.get('/auth/profile');
return response.data;
},
// Select organization
selectOrganization: async (organizationId: string): Promise<any> => {
const response = await apiClient.post('/auth/select-organization', { organizationId });
return response.data;
},
// Logout
logout: async (): Promise<void> => {
await apiClient.post('/auth/logout');
},
// Refresh token
refreshToken: async (refreshToken: string): Promise<{ accessToken: string }> => {
const response = await apiClient.post('/auth/refresh', { refreshToken });
return response.data;
},
};

View File

@@ -0,0 +1,57 @@
// src/lib/api/client.ts
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
import { ApiError } from '@/types';
interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
_retry?: boolean;
}
export const apiClient = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
withCredentials: true, // ✅ REQUIRED FOR COOKIES
headers: {
'Content-Type': 'application/json',
},
timeout: 10000,
});
// ❌ REMOVE request interceptor completely (no Authorization header)
// ✅ Response interceptor
apiClient.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const originalRequest = error.config as CustomAxiosRequestConfig;
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
try {
// ✅ refresh via cookie (no body needed ideally)
await axios.post(
`${process.env.NEXT_PUBLIC_API_URL}/auth/refresh`,
{},
{ withCredentials: true }
);
return apiClient(originalRequest);
} catch (refreshError) {
if (typeof window !== 'undefined') {
return Promise.reject(error); // ✅ just fail silently
}
return Promise.reject(refreshError);
}
}
const apiError: ApiError = {
statusCode: error.response?.status || 500,
message:
(error.response?.data as any)?.message ||
error.message ||
'An unexpected error occurred',
error: (error.response?.data as any)?.error,
};
return Promise.reject(apiError);
}
);

View File

@@ -0,0 +1,215 @@
'use client';
import React, { createContext, useContext, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { authApi } from '@/lib/api/auth';
import { User, Organization } from '@/types';
interface AuthContextType {
user: User | null;
organizations: Organization[];
currentOrganization: Organization | null;
isLoading: boolean;
isAuthReady: boolean; // ✅ NEW
error: string | null;
registerTrial: (
email: string,
password: string,
name: string,
organizationName: string,
organizationType: 'CLINIC' | 'LAB'
) => Promise<void>;
login: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
selectOrganization: (orgId: string) => Promise<void>;
clearError: () => void;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [organizations, setOrganizations] = useState<Organization[]>([]);
const [currentOrganization, setCurrentOrganization] = useState<Organization | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isAuthReady, setIsAuthReady] = useState(false); // ✅ KEY FIX
const [error, setError] = useState<string | null>(null);
const router = useRouter();
useEffect(() => {
checkAuth();
}, []);
const checkAuth = async () => {
try {
setIsLoading(true);
const hasSession = document.cookie.includes('accessToken');
if (!hasSession) {
console.log('No session → skipping auth check');
return;
}
const response = await authApi.getProfile();
if (response.success) {
const userData = response.data.user;
const orgs = response.data.organizations || [];
setUser(userData);
setOrganizations(orgs);
const storedOrgId = localStorage.getItem('currentOrganizationId');
if (storedOrgId && orgs.length > 0) {
const org = orgs.find(o => o.id === storedOrgId);
if (org) setCurrentOrganization(org);
} else if (orgs.length === 1) {
setCurrentOrganization(orgs[0]);
localStorage.setItem('currentOrganizationId', orgs[0].id);
}
}
} catch (err) {
console.error('Auth check failed:', err);
// Only clear state — DO NOT redirect here
setUser(null);
setOrganizations([]);
setCurrentOrganization(null);
} finally {
setIsLoading(false);
setIsAuthReady(true);
}
};
// ✅ REGISTER
const registerTrial = async (
email: string,
password: string,
name: string,
organizationName: string,
organizationType: 'CLINIC' | 'LAB'
) => {
try {
setIsLoading(true);
setError(null);
const response = await authApi.registerTrial({
email,
password,
name,
organizationName,
organizationType,
});
setUser(response.data.user);
setOrganizations(response.data.organizations);
const orgs = response.data.organizations;
if (orgs.length === 1) {
const org = orgs[0];
setCurrentOrganization(org);
localStorage.setItem('currentOrganizationId', org.id);
router.push('/today');
} else {
router.push('/select-organization');
}
} catch (err: any) {
setError(err.message || 'Registration failed');
throw err;
} finally {
setIsLoading(false);
}
};
// ✅ LOGIN
const login = async (email: string, password: string) => {
try {
setIsLoading(true);
setError(null);
const response = await authApi.login({ email, password });
setUser(response.data.user);
setOrganizations(response.data.organizations);
const orgs = response.data.organizations;
if (orgs.length === 1) {
const org = orgs[0];
setCurrentOrganization(org);
localStorage.setItem('currentOrganizationId', org.id);
router.push('/today');
} else {
router.push('/select-organization');
}
} catch (err: any) {
setError(err.message || 'Login failed');
throw err;
} finally {
setIsLoading(false);
}
};
const logout = async () => {
localStorage.clear();
setUser(null);
setOrganizations([]);
setCurrentOrganization(null);
router.push('/');
};
const selectOrganization = async (orgId: string) => {
try {
setIsLoading(true);
const response = await authApi.selectOrganization(orgId);
const { organization } = response.data;
localStorage.setItem('currentOrganizationId', organization.id);
setCurrentOrganization(organization);
router.push('/today');
} catch (err: any) {
setError(err.message);
throw err;
} finally {
setIsLoading(false);
}
};
const clearError = () => setError(null);
return (
<AuthContext.Provider
value={{
user,
organizations,
currentOrganization,
isLoading,
isAuthReady, // ✅ expose it
error,
registerTrial,
login,
logout,
selectOrganization,
clearError,
}}
>
{children}
</AuthContext.Provider>
);
}
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) throw new Error('useAuth must be used within AuthProvider');
return context;
};

View File

@@ -0,0 +1,41 @@
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;
const token = request.cookies.get('accessToken')?.value;
const isAuthenticated = !!token;
// Always allow public routes first
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();
}
// Protected routes: redirect to login if no token
if (!isAuthenticated) {
// Prevent loop: if somehow redirecting to login from login, just continue
if (pathname === '/login') {
return NextResponse.next();
}
const loginUrl = new URL('/login', request.url);
loginUrl.searchParams.set('from', pathname);
return NextResponse.redirect(loginUrl);
}
return NextResponse.next();
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
};

View File

@@ -0,0 +1,40 @@
@import "tailwindcss";
/* 🎨 Design Tokens (CSS-based, no JS dependency) */
:root {
--color-background-primary: #0B1A2B;
--color-background-secondary: #0F2236;
--color-background-card: #132A42;
--color-text-primary: #FFFFFF;
--color-text-secondary: #A0AEC0;
--color-border: #1F3A5F;
--color-primary: #009CAE;
}
/* Tailwind theme mapping */
@theme inline {
--color-background-primary: var(--color-background-primary);
--color-background-secondary: var(--color-background-secondary);
--color-background-card: var(--color-background-card);
--color-text-primary: var(--color-text-primary);
--color-text-secondary: var(--color-text-secondary);
--color-border: var(--color-border);
--color-primary: var(--color-primary);
}
/* Base styles */
html, body {
padding: 0;
margin: 0;
}
body {
background-color: #f9fafb; /* light gray */
color: #111827; /* dark text */
font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
}

View File

@@ -0,0 +1,15 @@
export const colors = {
primary: {
DEFAULT: '#00C2FF',
},
background: {
primary: '#0B1A2B',
secondary: '#0F2236',
card: '#132A42',
},
text: {
primary: '#FFFFFF',
secondary: '#A0AEC0',
},
border: '#1F3A5F',
};

View File

@@ -0,0 +1,46 @@
// src/types/index.ts
export interface User {
id: string;
email: string;
name: string;
}
export interface Organization {
id: string;
name: string;
type: 'CLINIC' | 'LAB';
isOwner: boolean;
plan?: {
name: string;
maxUsers: number;
};
}
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;
organizationType: 'CLINIC' | 'LAB';
}
export interface LoginData {
email: string;
password: string;
}
export interface ApiError {
statusCode: number;
message: string | string[];
error?: string;
}