improvement/one-user-multiple-orgs #6
@@ -1,6 +1,5 @@
|
|||||||
// backend/prisma/seed.ts
|
// backend/prisma/seed.ts
|
||||||
import { PrismaClient } from '@prisma/client';
|
import { PrismaClient } from '@prisma/client';
|
||||||
import * as bcrypt from 'bcrypt';
|
|
||||||
import { config } from 'dotenv';
|
import { config } from 'dotenv';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
|
||||||
@@ -29,14 +28,14 @@ async function main() {
|
|||||||
console.log('✅ Database connected successfully');
|
console.log('✅ Database connected successfully');
|
||||||
|
|
||||||
// Create organization types
|
// Create organization types
|
||||||
const clinicType = await prisma.organizationType.upsert({
|
await prisma.organizationType.upsert({
|
||||||
where: { name: 'CLINIC' },
|
where: { name: 'CLINIC' },
|
||||||
update: {},
|
update: {},
|
||||||
create: { name: 'CLINIC' },
|
create: { name: 'CLINIC' },
|
||||||
});
|
});
|
||||||
console.log('✅ Created clinic type');
|
console.log('✅ Created clinic type');
|
||||||
|
|
||||||
const labType = await prisma.organizationType.upsert({
|
await prisma.organizationType.upsert({
|
||||||
where: { name: 'LAB' },
|
where: { name: 'LAB' },
|
||||||
update: {},
|
update: {},
|
||||||
create: { name: 'LAB' },
|
create: { name: 'LAB' },
|
||||||
@@ -61,32 +60,39 @@ async function main() {
|
|||||||
}
|
}
|
||||||
console.log('✅ Created plans');
|
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 = [
|
const features = [
|
||||||
{
|
{
|
||||||
name: 'Patient Management',
|
name: 'Today',
|
||||||
permissions: ['VIEW_PATIENTS', 'CREATE_PATIENTS', 'EDIT_PATIENTS', 'DELETE_PATIENTS']
|
permissions: ['TAB_TODAY_READ', 'TAB_TODAY_EDIT'],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'Order Management',
|
name: 'Patients',
|
||||||
permissions: ['VIEW_ORDERS', 'CREATE_ORDERS', 'EDIT_ORDERS', 'DELETE_ORDERS', 'TRACK_ORDERS']
|
permissions: ['TAB_PATIENTS_READ', 'TAB_PATIENTS_EDIT'],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'Case Management',
|
name: 'Appointments',
|
||||||
permissions: ['VIEW_CASES', 'CREATE_CASES', 'EDIT_CASES', 'DELETE_CASES']
|
permissions: ['TAB_APPOINTMENTS_READ', 'TAB_APPOINTMENTS_EDIT'],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'Reports',
|
name: 'Staff Management',
|
||||||
permissions: ['VIEW_REPORTS', 'EXPORT_REPORTS']
|
permissions: ['TAB_STAFF_READ', 'TAB_STAFF_EDIT'],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'Team Management',
|
name: 'Lab Management',
|
||||||
permissions: ['INVITE_USERS', 'REMOVE_USERS', 'MANAGE_PERMISSIONS']
|
permissions: ['TAB_LAB_READ', 'TAB_LAB_EDIT'],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'Billing',
|
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) {
|
for (const feature of features) {
|
||||||
@@ -109,7 +115,7 @@ async function main() {
|
|||||||
}
|
}
|
||||||
console.log('✅ Created features and permissions');
|
console.log('✅ Created features and permissions');
|
||||||
|
|
||||||
console.log('🌱 Seeding completed successfully!'); ``
|
console.log('🌱 Seeding completed successfully!');
|
||||||
}
|
}
|
||||||
|
|
||||||
main()
|
main()
|
||||||
|
|||||||
@@ -145,6 +145,20 @@ export class AuthController {
|
|||||||
return this.authService.getProfile(req.user.id);
|
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
|
// LOGOUT
|
||||||
// =========================
|
// =========================
|
||||||
|
|||||||
@@ -16,27 +16,20 @@ import { CreateOrganizationDto } from './dto/create-organization.dto';
|
|||||||
import { JwtPayload } from './interfaces/jwt-payload.interface';
|
import { JwtPayload } from './interfaces/jwt-payload.interface';
|
||||||
|
|
||||||
const ALL_PERMISSIONS = [
|
const ALL_PERMISSIONS = [
|
||||||
'VIEW_PATIENTS',
|
'TAB_TODAY_READ',
|
||||||
'CREATE_PATIENTS',
|
'TAB_TODAY_EDIT',
|
||||||
'EDIT_PATIENTS',
|
'TAB_PATIENTS_READ',
|
||||||
'DELETE_PATIENTS',
|
'TAB_PATIENTS_EDIT',
|
||||||
'VIEW_ORDERS',
|
'TAB_APPOINTMENTS_READ',
|
||||||
'CREATE_ORDERS',
|
'TAB_APPOINTMENTS_EDIT',
|
||||||
'EDIT_ORDERS',
|
'TAB_STAFF_READ',
|
||||||
'DELETE_ORDERS',
|
'TAB_STAFF_EDIT',
|
||||||
'TRACK_ORDERS',
|
'TAB_LAB_READ',
|
||||||
'VIEW_CASES',
|
'TAB_LAB_EDIT',
|
||||||
'CREATE_CASES',
|
'TAB_BILLING_READ',
|
||||||
'EDIT_CASES',
|
'TAB_BILLING_EDIT',
|
||||||
'DELETE_CASES',
|
'TAB_REPORTS_READ',
|
||||||
'VIEW_REPORTS',
|
'TAB_REPORTS_EDIT',
|
||||||
'EXPORT_REPORTS',
|
|
||||||
'INVITE_USERS',
|
|
||||||
'REMOVE_USERS',
|
|
||||||
'MANAGE_PERMISSIONS',
|
|
||||||
'VIEW_INVOICES',
|
|
||||||
'CREATE_INVOICES',
|
|
||||||
'MANAGE_PAYMENTS',
|
|
||||||
];
|
];
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -63,6 +56,7 @@ export class AuthService {
|
|||||||
organization: {
|
organization: {
|
||||||
include: {
|
include: {
|
||||||
type: true, // Include organization type (CLINIC/LAB)
|
type: true, // Include organization type (CLINIC/LAB)
|
||||||
|
plan: true,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
permissions: {
|
permissions: {
|
||||||
@@ -149,6 +143,12 @@ export class AuthService {
|
|||||||
permissions: membership.isOwner
|
permissions: membership.isOwner
|
||||||
? ALL_PERMISSIONS
|
? ALL_PERMISSIONS
|
||||||
: membership.permissions?.map(p => p.permission.name) || [],
|
: membership.permissions?.map(p => p.permission.name) || [],
|
||||||
|
plan: membership.organization.plan
|
||||||
|
? {
|
||||||
|
name: membership.organization.plan.name,
|
||||||
|
maxUsers: membership.organization.plan.maxUsers,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
})) || [];
|
})) || [];
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -322,6 +322,7 @@ export class AuthService {
|
|||||||
organization: {
|
organization: {
|
||||||
include: {
|
include: {
|
||||||
type: true,
|
type: true,
|
||||||
|
plan: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
permissions: {
|
permissions: {
|
||||||
@@ -346,7 +347,15 @@ export class AuthService {
|
|||||||
name: membership.organization.name,
|
name: membership.organization.name,
|
||||||
type: membership.organization.type.name,
|
type: membership.organization.type.name,
|
||||||
isOwner: membership.isOwner,
|
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 {
|
return {
|
||||||
@@ -412,6 +421,7 @@ export class AuthService {
|
|||||||
organization: {
|
organization: {
|
||||||
include: {
|
include: {
|
||||||
type: true,
|
type: true,
|
||||||
|
plan: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
permissions: {
|
permissions: {
|
||||||
@@ -457,7 +467,15 @@ export class AuthService {
|
|||||||
name: membership.organization.name,
|
name: membership.organization.name,
|
||||||
type: membership.organization.type.name,
|
type: membership.organization.type.name,
|
||||||
isOwner: membership.isOwner,
|
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 {
|
return {
|
||||||
@@ -629,6 +647,7 @@ export class AuthService {
|
|||||||
organization: {
|
organization: {
|
||||||
include: {
|
include: {
|
||||||
type: true,
|
type: true,
|
||||||
|
plan: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
permissions: {
|
permissions: {
|
||||||
@@ -654,7 +673,15 @@ export class AuthService {
|
|||||||
name: membership.organization.name,
|
name: membership.organization.name,
|
||||||
type: membership.organization.type.name,
|
type: membership.organization.type.name,
|
||||||
isOwner: membership.isOwner,
|
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 {
|
return {
|
||||||
@@ -711,7 +738,9 @@ export class AuthService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 4. Format permissions
|
// 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 {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
@@ -721,9 +750,101 @@ export class AuthService {
|
|||||||
id: membership.organization.id,
|
id: membership.organization.id,
|
||||||
name: membership.organization.name,
|
name: membership.organization.name,
|
||||||
type: membership.organization.type.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,
|
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,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,18 +1,15 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { memo, useCallback, useEffect } from 'react';
|
import { memo, useEffect } from 'react';
|
||||||
import { useRouter } from 'next/navigation';
|
import { 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/Sidebar';
|
||||||
import { ThemeToggle } from '@/components/ui/ThemeToggle';
|
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 }) {
|
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
|
||||||
const { user, currentOrganization, isAuthReady, logout } = useAuth();
|
const { user, currentOrganization, isAuthReady } = useAuth();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const handleLogout = useCallback(() => {
|
|
||||||
void logout();
|
|
||||||
}, [logout]);
|
|
||||||
|
|
||||||
// ✅ AUTH GUARD (runs once per navigation group)
|
// ✅ AUTH GUARD (runs once per navigation group)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -51,11 +48,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
|||||||
<Sidebar />
|
<Sidebar />
|
||||||
|
|
||||||
<div className="flex-1 flex flex-col">
|
<div className="flex-1 flex flex-col">
|
||||||
<DashboardHeader
|
<DashboardHeader organizationName={currentOrganization.name} />
|
||||||
organizationName={currentOrganization.name}
|
|
||||||
userName={user.name}
|
|
||||||
onLogout={handleLogout}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<main className="p-6 flex-1 overflow-y-auto">
|
<main className="p-6 flex-1 overflow-y-auto">
|
||||||
<div className="surface-panel p-6 min-h-full">
|
<div className="surface-panel p-6 min-h-full">
|
||||||
@@ -69,27 +62,16 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
|||||||
|
|
||||||
const DashboardHeader = memo(function DashboardHeader({
|
const DashboardHeader = memo(function DashboardHeader({
|
||||||
organizationName,
|
organizationName,
|
||||||
userName,
|
|
||||||
onLogout,
|
|
||||||
}: {
|
}: {
|
||||||
organizationName: string;
|
organizationName: string;
|
||||||
userName: string;
|
|
||||||
onLogout: () => void;
|
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<header className="flex justify-between px-6 py-4 border-b border-border/70 backdrop-blur-sm">
|
<header className="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">{organizationName}</h2>
|
<h2 className="text-lg font-medium truncate min-w-0">{organizationName}</h2>
|
||||||
|
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-3 shrink-0">
|
||||||
<ThemeToggle />
|
<ThemeToggle />
|
||||||
<span className="text-sm text-text-secondary">{userName}</span>
|
<DashboardAccountMenu />
|
||||||
<button
|
|
||||||
onClick={onLogout}
|
|
||||||
className="inline-flex items-center gap-2 text-sm text-text-secondary hover:text-text-primary transition-colors"
|
|
||||||
>
|
|
||||||
<LogOut className="w-4 h-4 icon-flat" />
|
|
||||||
Logout
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
|
|||||||
29
frontend/src/app/(dashboard)/settings/account/page.tsx
Normal file
29
frontend/src/app/(dashboard)/settings/account/page.tsx
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import Link from 'next/link';
|
||||||
|
|
||||||
|
export default function AccountSettingsPage() {
|
||||||
|
return (
|
||||||
|
<div className="max-w-xl space-y-6">
|
||||||
|
<div>
|
||||||
|
<Link
|
||||||
|
href="/today"
|
||||||
|
className="text-sm text-primary hover:opacity-90"
|
||||||
|
>
|
||||||
|
← Back to app
|
||||||
|
</Link>
|
||||||
|
<h1 className="text-2xl font-semibold text-text-primary mt-4">Account</h1>
|
||||||
|
<p className="text-text-secondary text-sm mt-2">
|
||||||
|
Profile and security settings for your login.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="surface-card p-6 space-y-3">
|
||||||
|
<p className="text-sm text-text-secondary">
|
||||||
|
Password change and profile editing will be wired here next (e.g. invite
|
||||||
|
flow, reset password).
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
103
frontend/src/app/(dashboard)/settings/subscriptions/page.tsx
Normal file
103
frontend/src/app/(dashboard)/settings/subscriptions/page.tsx
Normal file
@@ -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<SubscriptionAlertData | null>(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 (
|
||||||
|
<p className="text-text-secondary text-sm">Loading...</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!currentOrganization.isOwner) {
|
||||||
|
return (
|
||||||
|
<p className="text-text-secondary text-sm">Redirecting...</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const plan = currentOrganization.plan;
|
||||||
|
const maxUsers = plan?.maxUsers;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-xl space-y-6">
|
||||||
|
<div>
|
||||||
|
<Link
|
||||||
|
href="/today"
|
||||||
|
className="text-sm text-primary hover:opacity-90"
|
||||||
|
>
|
||||||
|
← Back to app
|
||||||
|
</Link>
|
||||||
|
<h1 className="text-2xl font-semibold text-text-primary mt-4">Subscriptions</h1>
|
||||||
|
<p className="text-text-secondary text-sm mt-2">
|
||||||
|
Your DyoLink workspace plan and seats for{' '}
|
||||||
|
<span className="text-text-primary font-medium">{currentOrganization.name}</span>.
|
||||||
|
Clinic and lab income tracking stays under the sidebar{' '}
|
||||||
|
<span className="text-text-primary">Billing</span> tab.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="surface-card p-6 space-y-4">
|
||||||
|
<div className="flex flex-wrap gap-4 justify-between">
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-text-muted uppercase tracking-wide">Current plan</p>
|
||||||
|
<p className="text-lg font-medium text-text-primary capitalize">
|
||||||
|
{plan?.name ?? '—'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{typeof maxUsers === 'number' && maxUsers < 999999 && (
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-text-muted uppercase tracking-wide">Seats (this org)</p>
|
||||||
|
<p className="text-lg font-medium text-text-primary">
|
||||||
|
{alert?.seatsUsed ?? '—'} / {maxUsers}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{alert?.showWarning && (
|
||||||
|
<div className="text-sm text-text-secondary space-y-1">
|
||||||
|
{alert.trialExpired && (
|
||||||
|
<p>Trial period has ended. Choose a plan when checkout is available.</p>
|
||||||
|
)}
|
||||||
|
{!alert.trialExpired && alert.trialEndingSoon && (
|
||||||
|
<p>
|
||||||
|
Trial ends in {alert.daysUntilTrialEnd ?? '—'} day(s).
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{!alert.trialExpired && !alert.trialEndingSoon && alert.seatsLow && (
|
||||||
|
<p>Seat usage is high for this organization.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<p className="text-sm text-text-secondary">
|
||||||
|
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.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
156
frontend/src/components/ui/DashboardAccountMenu.tsx
Normal file
156
frontend/src/components/ui/DashboardAccountMenu.tsx
Normal file
@@ -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<HTMLDivElement>(null);
|
||||||
|
const [alert, setAlert] = useState<SubscriptionAlertData | null>(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 (
|
||||||
|
<div className="relative" ref={menuRef}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => 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"
|
||||||
|
>
|
||||||
|
<span className="relative inline-flex shrink-0" title={showWarning ? tooltip : undefined}>
|
||||||
|
<Settings className="h-5 w-5 icon-flat" aria-hidden />
|
||||||
|
{showWarning && (
|
||||||
|
<span
|
||||||
|
className="absolute -right-1 -top-1 flex h-3.5 w-3.5 items-center justify-center rounded-full bg-amber-500 ring-2 ring-background-secondary"
|
||||||
|
aria-label={tooltip}
|
||||||
|
>
|
||||||
|
<AlertTriangle className="h-2.5 w-2.5 text-amber-950" strokeWidth={2.5} />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<span className="hidden sm:inline max-w-[160px] truncate">{user?.name}</span>
|
||||||
|
<ChevronDown className="h-4 w-4 text-text-muted shrink-0" aria-hidden />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{open && (
|
||||||
|
<div
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
<div className="px-3 py-2 border-b border-border/60">
|
||||||
|
<p className="text-xs text-text-muted">Signed in</p>
|
||||||
|
<p className="text-sm font-medium truncate">{user?.email}</p>
|
||||||
|
<p className="text-xs text-text-secondary mt-1 truncate">
|
||||||
|
{currentOrganization?.name}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="py-1">
|
||||||
|
<Link
|
||||||
|
href="/select-organization"
|
||||||
|
role="menuitem"
|
||||||
|
className="flex items-center gap-3 px-3 py-2.5 text-sm text-text-primary hover:bg-background-card/70"
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
>
|
||||||
|
<Building2 className="h-4 w-4 icon-flat shrink-0" />
|
||||||
|
Switch organization
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
{isOwner && (
|
||||||
|
<Link
|
||||||
|
href="/settings/subscriptions"
|
||||||
|
role="menuitem"
|
||||||
|
className="flex items-center gap-3 px-3 py-2.5 text-sm text-text-primary hover:bg-background-card/70"
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
>
|
||||||
|
<CreditCard className="h-4 w-4 icon-flat shrink-0" />
|
||||||
|
Subscriptions
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Link
|
||||||
|
href="/settings/account"
|
||||||
|
role="menuitem"
|
||||||
|
className="flex items-center gap-3 px-3 py-2.5 text-sm text-text-primary hover:bg-background-card/70"
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
>
|
||||||
|
<User className="h-4 w-4 icon-flat shrink-0" />
|
||||||
|
Account
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="border-t border-border/60 pt-1">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
className="flex w-full items-center gap-3 px-3 py-2.5 text-sm text-text-secondary hover:bg-background-card/70 hover:text-text-primary"
|
||||||
|
onClick={handleLogout}
|
||||||
|
>
|
||||||
|
<LogOut className="h-4 w-4 icon-flat shrink-0" />
|
||||||
|
Log out
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -11,7 +11,6 @@ import {
|
|||||||
FlaskConical,
|
FlaskConical,
|
||||||
FileText,
|
FileText,
|
||||||
CreditCard,
|
CreditCard,
|
||||||
Building2
|
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
|
|
||||||
const menu = [
|
const menu = [
|
||||||
@@ -22,19 +21,19 @@ const menu = [
|
|||||||
{ name: 'Lab Management', path: '/lab', icon: FlaskConical },
|
{ name: 'Lab Management', path: '/lab', icon: FlaskConical },
|
||||||
{ name: 'Billing', path: '/billing', icon: CreditCard },
|
{ name: 'Billing', path: '/billing', icon: CreditCard },
|
||||||
{ name: 'Reports', path: '/reports', icon: FileText },
|
{ name: 'Reports', path: '/reports', icon: FileText },
|
||||||
{ name: 'Organizations', path: '/select-organization', icon: Building2 },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
function Sidebar() {
|
function Sidebar() {
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside className="w-64 bg-background-secondary/90 border-r border-border text-text-primary flex flex-col p-4">
|
<aside className="w-64 bg-background-secondary/90 border-r border-border text-text-primary flex flex-col">
|
||||||
<div className="mb-6 pb-4 border-b border-border">
|
<div className="h-[71px] px-4 flex items-center">
|
||||||
<h1 className="text-xl font-semibold tracking-tight">DyoLink</h1>
|
<h1 className="text-lg font-medium tracking-tight">DyoLink</h1>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="mx-4 border-b border-border/70" />
|
||||||
|
|
||||||
<nav className="flex flex-col gap-2">
|
<nav className="flex flex-col gap-2 p-4">
|
||||||
{menu.map((item) => {
|
{menu.map((item) => {
|
||||||
const Icon = item.icon;
|
const Icon = item.icon;
|
||||||
const isActive = pathname === item.path;
|
const isActive = pathname === item.path;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// src/lib/api/auth.ts
|
// src/lib/api/auth.ts
|
||||||
import { apiClient } from './client';
|
import { apiClient } from './client';
|
||||||
import { AuthResponse, TrialRegistrationData, LoginData } from '@/types';
|
import { AuthResponse, TrialRegistrationData, LoginData, SubscriptionAlertData } from '@/types';
|
||||||
|
|
||||||
export const authApi = {
|
export const authApi = {
|
||||||
// Register a new trial organization
|
// Register a new trial organization
|
||||||
@@ -21,6 +21,15 @@ export const authApi = {
|
|||||||
return response.data;
|
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
|
// Select organization
|
||||||
selectOrganization: async (organizationId: string): Promise<any> => {
|
selectOrganization: async (organizationId: string): Promise<any> => {
|
||||||
const response = await apiClient.post('/auth/select-organization', { organizationId });
|
const response = await apiClient.post('/auth/select-organization', { organizationId });
|
||||||
|
|||||||
@@ -218,7 +218,13 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|||||||
|
|
||||||
localStorage.setItem('currentOrganizationId', organization.id);
|
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');
|
router.push('/today');
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ 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'];
|
||||||
const authOnlyRoutes = ['/login', '/register']; // routes that should NOT be accessed when logged in
|
|
||||||
|
|
||||||
export function middleware(request: NextRequest) {
|
export function middleware(request: NextRequest) {
|
||||||
const { pathname } = request.nextUrl;
|
const { pathname } = request.nextUrl;
|
||||||
@@ -15,12 +14,10 @@ export function middleware(request: NextRequest) {
|
|||||||
return NextResponse.redirect(new URL('/today', request.url));
|
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 (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();
|
return NextResponse.next();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,12 +10,25 @@ export interface Organization {
|
|||||||
name: string;
|
name: string;
|
||||||
type: 'CLINIC' | 'LAB';
|
type: 'CLINIC' | 'LAB';
|
||||||
isOwner: boolean;
|
isOwner: boolean;
|
||||||
|
permissions?: string[];
|
||||||
plan?: {
|
plan?: {
|
||||||
name: string;
|
name: string;
|
||||||
maxUsers: number;
|
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 {
|
export interface AuthResponse {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
Reference in New Issue
Block a user