From 42ad863eb17570052fd784fb9dd021c8b0c00429 Mon Sep 17 00:00:00 2001 From: Arena Agent Date: Wed, 4 Nov 2026 16:26:19 +0000 Subject: [PATCH 01/24] feat(admin): fix dashboard typecheck and rebuild core modules - Bring the pushed dashboard work onto the branch and clear all 25 typecheck errors - Mount AppDataProvider (was never wired) and gate admin routes by role - Role-aware shell: student menu hides administration, labels adapt per role - Approvals: class-teacher leave routing, history, validated apply form - Communications: working declaration composer, message broadcast, polls - Assignments: teacher name, attachments, submit flow, submissions review - Report card: printable document with real student details, withdraw action - People: CSV import with header aliases, validation, template + credentials export - Events: month calendar, admin-only school events, teacher class-only events - Classes/Enrollments/Audit/Subjects: move off direct Supabase calls to demo store - utils: reject impossible dates (31 Feb), add inr/relativeToToday/formatRange Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- apps/admin/.env.example | 4 +- apps/admin/src/App.tsx | 161 +++- apps/admin/src/components/AppShell.tsx | 384 +++++++++ apps/admin/src/components/ui.tsx | 371 +++++++++ apps/admin/src/contexts/AuthContext.tsx | 128 ++- apps/admin/src/lib/appData.tsx | 830 +++++++++++++++++++ apps/admin/src/lib/seed.ts | 642 ++++++++++++++ apps/admin/src/lib/supabase.ts | 17 +- apps/admin/src/lib/types.ts | 285 +++++++ apps/admin/src/lib/utils.ts | 230 +++++ apps/admin/src/pages/Approvals.tsx | 414 +++++++++ apps/admin/src/pages/Assignments.tsx | 522 ++++++++++++ apps/admin/src/pages/Attendance.tsx | 259 ++++++ apps/admin/src/pages/AuditLog.tsx | 98 +++ apps/admin/src/pages/Classes.tsx | 183 +++- apps/admin/src/pages/Communications.tsx | 498 +++++++++++ apps/admin/src/pages/CourseProgress.tsx | 222 +++++ apps/admin/src/pages/Dashboard.tsx | 350 +++++++- apps/admin/src/pages/Enrollments.tsx | 179 ++++ apps/admin/src/pages/Events.tsx | 432 ++++++++++ apps/admin/src/pages/Fees.tsx | 337 ++++++++ apps/admin/src/pages/Gallery.tsx | 50 ++ apps/admin/src/pages/Library.tsx | 313 +++++++ apps/admin/src/pages/Login.tsx | 4 + apps/admin/src/pages/People.tsx | 486 +++++++++-- apps/admin/src/pages/ReportCard.tsx | 450 ++++++++++ apps/admin/src/pages/StudyRoom.tsx | 184 ++++ apps/admin/src/pages/Subjects.tsx | 122 +++ apps/admin/src/pages/TeachingAssignments.tsx | 115 +++ apps/admin/vite.config.ts | 33 +- 30 files changed, 8100 insertions(+), 203 deletions(-) create mode 100644 apps/admin/src/components/AppShell.tsx create mode 100644 apps/admin/src/components/ui.tsx create mode 100644 apps/admin/src/lib/appData.tsx create mode 100644 apps/admin/src/lib/seed.ts create mode 100644 apps/admin/src/lib/types.ts create mode 100644 apps/admin/src/lib/utils.ts create mode 100644 apps/admin/src/pages/Approvals.tsx create mode 100644 apps/admin/src/pages/Assignments.tsx create mode 100644 apps/admin/src/pages/Attendance.tsx create mode 100644 apps/admin/src/pages/AuditLog.tsx create mode 100644 apps/admin/src/pages/Communications.tsx create mode 100644 apps/admin/src/pages/CourseProgress.tsx create mode 100644 apps/admin/src/pages/Enrollments.tsx create mode 100644 apps/admin/src/pages/Events.tsx create mode 100644 apps/admin/src/pages/Fees.tsx create mode 100644 apps/admin/src/pages/Gallery.tsx create mode 100644 apps/admin/src/pages/Library.tsx create mode 100644 apps/admin/src/pages/ReportCard.tsx create mode 100644 apps/admin/src/pages/StudyRoom.tsx create mode 100644 apps/admin/src/pages/Subjects.tsx create mode 100644 apps/admin/src/pages/TeachingAssignments.tsx diff --git a/apps/admin/.env.example b/apps/admin/.env.example index 2311475..4dcbde7 100644 --- a/apps/admin/.env.example +++ b/apps/admin/.env.example @@ -1,2 +1,2 @@ -VITE_SUPABASE_URL= -VITE_SUPABASE_PUBLISHABLE_KEY= +SUPABASE_URL= +SUPABASE_PUBLISHABLE_KEY= diff --git a/apps/admin/src/App.tsx b/apps/admin/src/App.tsx index bf8a522..27d5bf6 100644 --- a/apps/admin/src/App.tsx +++ b/apps/admin/src/App.tsx @@ -1,45 +1,140 @@ -import type { ReactNode } from 'react' -import { BrowserRouter, Navigate, Routes, Route } from 'react-router-dom' -import { AuthProvider, useAuth } from './contexts/AuthContext' -import Layout from './components/Layout' -import Login from './pages/Login' -import Dashboard from './pages/Dashboard' -import Classes from './pages/Classes' -import People from './pages/People' +import type { ReactNode } from 'react'; +import { BrowserRouter, Navigate, Routes, Route } from 'react-router-dom'; +import { AuthProvider, useAuth } from './contexts/AuthContext'; +import { AppDataProvider } from './lib/appData'; +import AppShell from './components/AppShell'; +import Login from './pages/Login'; +import Dashboard from './pages/Dashboard'; +import Approvals from './pages/Approvals'; +import CourseProgress from './pages/CourseProgress'; +import Communications from './pages/Communications'; +import Events from './pages/Events'; +import Assignments from './pages/Assignments'; +import StudyRoom from './pages/StudyRoom'; +import Library from './pages/Library'; +import ReportCard from './pages/ReportCard'; +import Attendance from './pages/Attendance'; +import Fees from './pages/Fees'; +import Gallery from './pages/Gallery'; +import People from './pages/People'; +import Classes from './pages/Classes'; +import Subjects from './pages/Subjects'; +import TeachingAssignments from './pages/TeachingAssignments'; +import Enrollments from './pages/Enrollments'; +import AuditLog from './pages/AuditLog'; function RequireAuth({ children }: { children: ReactNode }) { - const { loading, profile } = useAuth() - if (loading) return null - return profile ? <>{children} : + const { loading, profile } = useAuth(); + if (loading) { + return ( +
+
+
+ ); + } + return profile ? <>{children} : ; } function GuestOnly({ children }: { children: ReactNode }) { - const { loading, profile } = useAuth() - if (loading) return null - return profile ? : <>{children} + const { loading, profile } = useAuth(); + if (loading) return null; + return profile ? : <>{children}; +} + +/** Administration routes are admin-only in every role view. */ +function AdminOnly({ children }: { children: ReactNode }) { + const { isAdmin } = useAuth(); + return isAdmin() ? <>{children} : ; } export default function App() { return ( - - - } /> - - - - } - > - } /> - } /> - } /> - } /> - - - + + + + + + + } + /> + + + + } + > + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + + + } + /> + + + + } + /> + + + + } + /> + + + + } + /> + + + + } + /> + + + + } + /> + } /> + + + + - ) + ); } diff --git a/apps/admin/src/components/AppShell.tsx b/apps/admin/src/components/AppShell.tsx new file mode 100644 index 0000000..d21338f --- /dev/null +++ b/apps/admin/src/components/AppShell.tsx @@ -0,0 +1,384 @@ +import { useState, useMemo, useEffect, type ReactNode } from 'react'; +import { useNavigate, useLocation, Link, Outlet } from 'react-router-dom'; +import { useAuth } from '../contexts/AuthContext'; +import { useAppData } from '../lib/appData'; +import { cn, initials } from '../lib/utils'; +import { Badge, Breadcrumbs, NotificationsDropdown, RoleSwitcher } from './ui'; +import { + FiHome, + FiClipboard, + FiBookOpen, + FiSend, + FiCalendar, + FiFileText, + FiCreditCard, + FiFolder, + FiImage, + FiUsers, + FiLayout, + FiBarChart2, + FiPieChart, + FiLogOut, + FiShield, + FiMenu, + FiAward, + FiX, +} from 'react-icons/fi'; + +type Role = 'admin' | 'teacher' | 'student'; + +type NavItem = { + to: string; + label: string; + icon: React.ElementType; + /** Labels change with the viewer so a student never sees "All students". */ + labelByRole?: Partial>; + roles: Role[]; +}; + +const NAV: NavItem[] = [ + { to: '/dashboard', label: 'Dashboard', icon: FiHome, roles: ['admin', 'teacher', 'student'] }, + { + to: '/approvals', + label: 'Approvals', + labelByRole: { student: 'My Leaves', teacher: 'Leave Approvals', admin: 'Leave Approvals' }, + icon: FiClipboard, + roles: ['admin', 'teacher', 'student'], + }, + { + to: '/course-progress', + label: 'Course Progress', + labelByRole: { student: 'My Progress', teacher: 'Course Progress', admin: 'Course Progress' }, + icon: FiBarChart2, + roles: ['admin', 'teacher', 'student'], + }, + { + to: '/communications', + label: 'Communications', + labelByRole: { student: 'Inbox', teacher: 'Communications', admin: 'Communications' }, + icon: FiSend, + roles: ['admin', 'teacher', 'student'], + }, + { + to: '/events', + label: 'Events & Calendar', + icon: FiCalendar, + roles: ['admin', 'teacher', 'student'], + }, + { + to: '/assignments', + label: 'Assignments', + labelByRole: { + student: 'Assignments / Homework', + teacher: 'Class Assignments', + admin: 'Assignments', + }, + icon: FiFileText, + roles: ['admin', 'teacher', 'student'], + }, + { to: '/study-room', label: 'Study Room', icon: FiFolder, roles: ['admin', 'teacher', 'student'] }, + { + to: '/library', + label: 'My Library', + labelByRole: { teacher: 'Library', admin: 'Library' }, + icon: FiBookOpen, + roles: ['admin', 'teacher', 'student'], + }, + { + to: '/report-card', + label: 'My Report Card', + labelByRole: { teacher: 'Report Cards', admin: 'Report Cards' }, + icon: FiAward, + roles: ['admin', 'teacher', 'student'], + }, + { + to: '/attendance', + label: 'My Attendance', + labelByRole: { teacher: 'Attendance', admin: 'Attendance' }, + icon: FiPieChart, + roles: ['admin', 'teacher', 'student'], + }, + { + to: '/fees', + label: 'My Fee', + labelByRole: { teacher: 'Fees', admin: 'Fee Collection' }, + icon: FiCreditCard, + roles: ['admin', 'teacher', 'student'], + }, + { to: '/gallery', label: 'School Gallery', icon: FiImage, roles: ['admin', 'teacher', 'student'] }, + // Administration — never shown to student view. + { to: '/people', label: 'People', icon: FiUsers, roles: ['admin'] }, + { to: '/classes', label: 'Classes', icon: FiLayout, roles: ['admin'] }, + { to: '/subjects', label: 'Subjects', icon: FiBookOpen, roles: ['admin'] }, + { + to: '/teaching-assignments', + label: 'Teaching Assignments', + icon: FiSend, + roles: ['admin'], + }, + { to: '/enrollments', label: 'Enrollments', icon: FiClipboard, roles: ['admin'] }, + { to: '/audit-log', label: 'Audit Log', icon: FiShield, roles: ['admin'] }, +]; + +const GROUP_LABEL: Record = { + main: 'My school', + admin: 'Administration', +}; + +export default function AppShell({ children }: { children?: ReactNode }) { + const { profile, viewAsRole, viewingRole, demoMode, configError, signOut, isAdmin } = useAuth(); + const data = useAppData(); + const navigate = useNavigate(); + const location = useLocation(); + const [sidebarOpen, setSidebarOpen] = useState(false); + const [notifOpen, setNotifOpen] = useState(false); + + const role: Role = viewingRole ?? profile?.role ?? 'student'; + + useEffect(() => { + setSidebarOpen(false); + setNotifOpen(false); + }, [location.pathname]); + + const mainNav = useMemo( + () => NAV.filter((item) => item.roles.includes(role) && !item.to.match(/^\/(people|classes|subjects|teaching-assignments|enrollments|audit-log)$/)), + [role], + ); + const adminNav = useMemo( + () => NAV.filter((item) => item.roles.includes(role) && item.to.match(/^\/(people|classes|subjects|teaching-assignments|enrollments|audit-log)$/)), + [role], + ); + + const routeLabels: Record = { + '/dashboard': 'Dashboard', + '/approvals': role === 'student' ? 'My Leaves' : 'Leave Approvals', + '/course-progress': role === 'student' ? 'My Progress' : 'Course Progress', + '/communications': role === 'student' ? 'Inbox' : 'Communications', + '/events': 'Events & Calendar', + '/assignments': 'Assignments', + '/study-room': 'Study Room', + '/library': 'Library', + '/report-card': 'Report Cards', + '/attendance': 'Attendance', + '/fees': role === 'student' ? 'My Fee' : 'Fee Collection', + '/gallery': 'School Gallery', + '/people': 'People', + '/classes': 'Classes', + '/subjects': 'Subjects', + '/teaching-assignments': 'Teaching Assignments', + '/enrollments': 'Enrollments', + '/audit-log': 'Audit Log', + }; + + const breadcrumbItems = useMemo(() => { + const segments = location.pathname.split('/').filter(Boolean); + const parts: { label: string; to?: string }[] = [{ label: 'Home', to: '/dashboard' }]; + let path = ''; + for (const seg of segments) { + path += `/${seg}`; + parts.push({ + label: routeLabels[path] ?? seg.charAt(0).toUpperCase() + seg.slice(1), + to: path, + }); + } + return parts; + }, [location.pathname, role]); + + const handleLogout = async () => { + await signOut(); + navigate('/login'); + }; + + const pendingLeaves = data.leaves.filter((l) => l.status === 'pending').length; + const unread = data.notifications.filter((n) => !n.read).length; + + const badgeFor = (to: string) => { + if (to === '/approvals' && role !== 'student' && pendingLeaves > 0) return pendingLeaves; + return undefined; + }; + + const renderNav = (items: NavItem[]) => + items.map((item) => { + const active = location.pathname === item.to; + const label = item.labelByRole?.[role] ?? item.label; + const count = badgeFor(item.to); + return ( + + + {label} + {count !== undefined && ( + + {count} + + )} + + ); + }); + + const sidebarBody = ( + <> +
+ +
+
Pacific World
+
School ERP
+
+ +
+ + + +
+ {demoMode && ( +
+
Demo data
+
+ Supabase keys are not set, so the console runs on the seeded school. +
+ +
+ )} +
+
+ {initials(profile?.full_name ?? 'U')} +
+
+
{profile?.full_name ?? 'User'}
+
{profile?.login_id ?? ''}
+
+ + {role} + +
+ +
+ + ); + + return ( +
+ {sidebarOpen && ( +
setSidebarOpen(false)} + aria-hidden + /> + )} + + + +
+
+ + +
+
Pacific World School
+
+ {routeLabels[location.pathname] ?? 'Dashboard'} +
+
+ +
+ {configError && ( + + Config + + )} + {isAdmin() && ( + + )} +
+ setNotifOpen((v) => !v)} + /> + {unread === 0 && No unread notifications} +
+
+ {initials(profile?.full_name ?? 'U')} +
+
+
+ +
+ +
+ +
+ {children ?? } +
+ +
+ Pacific World School ERP · {new Date().getFullYear()} · Demo build +
+
+
+ ); +} diff --git a/apps/admin/src/components/ui.tsx b/apps/admin/src/components/ui.tsx new file mode 100644 index 0000000..1ec3c03 --- /dev/null +++ b/apps/admin/src/components/ui.tsx @@ -0,0 +1,371 @@ +import * as React from 'react'; +import { useState } from 'react'; +import { Link } from 'react-router-dom'; +import type { Role } from '../lib/types'; +import { cn } from '../lib/utils'; +import { + FiBell, + FiAlertCircle, + FiUser, + FiChevronDown, +} from 'react-icons/fi'; + +type ButtonProps = React.ButtonHTMLAttributes & { + variant?: 'olive' | 'terracotta' | 'outline' | 'ghost' | 'danger'; + size?: 'sm' | 'md' | 'lg'; +}; + +export function Button({ + className, + variant = 'olive', + size = 'md', + children, + ...props +}: ButtonProps) { + const base = + 'inline-flex items-center justify-center rounded-lg font-medium transition-colors disabled:pointer-events-none disabled:opacity-50'; + const variants: Record = { + olive: 'bg-olive text-white hover:bg-olive/90 active:bg-olive/80', + terracotta: 'bg-terracotta text-white hover:bg-terracotta/90 active:bg-terracotta/80', + outline: 'border border-slate-300 bg-white text-ink hover:bg-sand active:bg-sand/80', + ghost: 'bg-transparent text-ink hover:bg-sand active:bg-sand/60', + danger: 'bg-red-600 text-white hover:bg-red-700 active:bg-red-800', + }; + const sizes: Record = { + sm: 'px-3 py-1.5 text-xs', + md: 'px-4 py-2 text-sm', + lg: 'px-6 py-3 text-base', + }; + return ( + + ); +} + +interface CardProps extends React.HTMLAttributes { + children?: React.ReactNode; + header?: React.ReactNode; + footer?: React.ReactNode; + padded?: boolean; +} + +export function Card({ children, className, header, footer, padded = true }: CardProps) { + return ( +
+ {header &&
{header}
} +
{children}
+ {footer &&
{footer}
} +
+ ); +} + +interface CardHeaderProps extends React.HTMLAttributes { + title?: string; + subtitle?: string; + action?: React.ReactNode; +} + +export function CardHeader({ className, title, subtitle, action, children }: CardHeaderProps) { + return ( +
+
+ {children ?? ( + <> + {title &&

{title}

} + {subtitle &&

{subtitle}

} + + )} +
+ {action &&
{action}
} +
+ ); +} + +interface BadgeProps extends React.HTMLAttributes { + variant?: string; + children?: React.ReactNode; +} + +export function Badge({ className, variant = 'default', children, ...props }: BadgeProps) { + const base = + 'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium transition-colors'; + const variants: Record = { + default: 'border-slate-200 text-slate-600 bg-slate-50', + olive: 'border-olive/20 text-olive bg-olive/5', + terracotta: 'border-terracotta/20 text-terracotta bg-terracotta/5', + success: 'border-green-200 text-green-700 bg-green-50', + warning: 'border-amber-200 text-amber-700 bg-amber-50', + pending: 'border-slate-200 text-slate-600 bg-slate-50', + neutral: 'border-slate-200 text-slate-600 bg-slate-50', + }; + return {children}; +} + +interface TableProps extends React.HTMLAttributes { + children?: React.ReactNode; + striped?: boolean; +} + +export function Table({ children, className, striped = true, ...props }: TableProps) { + return ( + + {children} +
+ ); +} + +export function TableHeader({ className, children }: { className?: string; children?: React.ReactNode }) { + return ( + + {children} + + ); +} + +export function TableRow({ className, children, ...props }: { className?: string; children?: React.ReactNode } & React.HTMLAttributes) { + return ( + + {children} + + ); +} + +export function TableHead({ className, children }: { className?: string; children?: React.ReactNode }) { + return ( + + {children} + + ); +} + +export function TableCell({ className, children, colSpan, rowSpan, ...props }: { className?: string; children?: React.ReactNode; colSpan?: number; rowSpan?: number } & React.HTMLAttributes) { + return {children}; +} + +interface StatCardProps extends React.HTMLAttributes { + label: string; + value: string | number; + delta?: string; + icon?: React.ElementType; + variant?: 'olive' | 'terracotta' | 'neutral' | 'warning'; +} + +export function StatCard({ + className, + label, + value, + delta, + icon: Icon, + variant = 'olive', + ...props +}: StatCardProps) { + const colorMap: Record = { + olive: 'text-olive bg-olive/5 border-olive/10', + terracotta: 'text-terracotta bg-terracotta/5 border-terracotta/10', + neutral: 'text-ink bg-slate-50 border-slate-200', + warning: 'text-amber-700 bg-amber-50 border-amber-100', + }; + return ( +
+
+ {Icon && } + {delta && {delta}} +
+
{value}
+
{label}
+
+ ); +} + +interface BreadcrumbItem { + label: string; + to?: string; +} + +interface BreadcrumbsProps { + items: BreadcrumbItem[]; +} + +export function Breadcrumbs({ items }: BreadcrumbsProps) { + return ( + + ); +} + +export interface NotificationItem { + id: string; + title: string; + body: string; + kind: string; + created_at: string; + read: boolean; +} + +interface NotificationsDropdownProps { + notifications: NotificationItem[]; + onMarkRead: (id: string) => void; + onMarkAllRead: () => void; + open?: boolean; + onToggle?: () => void; +} + +export function NotificationsDropdown({ + notifications, + onMarkRead, + onMarkAllRead, + open, + onToggle, +}: NotificationsDropdownProps) { + const [internalOpen, setInternalOpen] = useState(false); + const isOpen = open ?? internalOpen; + const toggle = onToggle ?? (() => setInternalOpen((v) => !v)); + const unread = notifications.filter((n) => !n.read).length; + const kindColor: Record = { + notice: 'bg-slate-100 text-slate-700', + message: 'bg-blue-100 text-blue-700', + assignment: 'bg-olive/10 text-olive', + fee: 'bg-terracotta/10 text-terracotta', + approval: 'bg-amber-100 text-amber-700', + }; + return ( +
+ + {isOpen && ( +
+
+ Notifications + {unread > 0 && ( + + )} +
+
+ {notifications.length === 0 ? ( +
+ No new notifications +
+ ) : ( + notifications.map((n) => ( +
onMarkRead(n.id)} + > +
+ + + +
+
+
{n.title}
+
{n.body}
+
{new Date(n.created_at).toLocaleDateString()}
+
+
+ )) + )} +
+
+ )} +
+ ); +} + +interface RoleSwitcherProps { + roles: Role[]; + current: Role | null; + onChange: (role: Role | null) => void; +} + +export function RoleSwitcher({ roles, current, onChange }: RoleSwitcherProps) { + const [open, setOpen] = useState(false); + const labels: Record = { + admin: 'Admin', + teacher: 'Teacher', + student: 'Student', + }; + return ( +
+ + {open && ( +
+
+ Preview as +
+ {roles.map((role) => ( + + ))} + {current && ( + + )} +
+ )} +
+ ); +} diff --git a/apps/admin/src/contexts/AuthContext.tsx b/apps/admin/src/contexts/AuthContext.tsx index 3f97c61..b4d9cfb 100644 --- a/apps/admin/src/contexts/AuthContext.tsx +++ b/apps/admin/src/contexts/AuthContext.tsx @@ -1,19 +1,59 @@ -import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'; -import { supabase } from '../lib/supabase'; +import { + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useState, + type ReactNode, +} from 'react'; +import { supabase, configHint, missingSupabaseConfig } from '../lib/supabase'; +import { toAuthEmail } from '../lib/utils'; import type { Profile, Role } from '@schoolerp/shared'; +import { useAppData } from '../lib/appData'; + +const DEMO_LOGINS: Record< + string, + { password: string; role: Role; full_name: string; login_id: string } +> = { + ADMIN001: { + password: 'Admin@1234', + role: 'admin', + full_name: 'School Administrator', + login_id: 'ADMIN001', + }, + TCH001: { + password: 'Teacher@1234', + role: 'teacher', + full_name: 'Anuradha Gupta', + login_id: 'TCH001', + }, + '0185/18': { + password: 'Student@14052010', + role: 'student', + full_name: 'Sahaj Chugh', + login_id: '0185/18', + }, +}; interface AuthContextType { profile: Profile | null; sessionUserId: string | null; loading: boolean; + demoMode: boolean; + configError: string | null; signIn: (loginId: string, password: string) => Promise<{ error: string | null }>; signOut: () => Promise; requireRole: (roles: Role[]) => boolean; isAdmin: () => boolean; isTeacher: () => boolean; isStudent: () => boolean; + viewAsRole: (role: Role | null) => void; + viewingRole: Role | null; } +export { useAppData }; + const AuthContext = createContext(null); export function useAuth() { @@ -26,6 +66,22 @@ export function AuthProvider({ children }: { children: ReactNode }) { const [profile, setProfile] = useState(null); const [sessionUserId, setSessionUserId] = useState(null); const [loading, setLoading] = useState(true); + const [viewingRole, setViewingRole] = useState(null); + + const demoMode = missingSupabaseConfig(); + const configError = demoMode ? configHint() : null; + + // Resolve the "effective" role for display/authorisation: explicit view-as + // override wins, then the real profile role. + const effectiveRole = useMemo(() => { + if (viewingRole) return viewingRole; + return profile?.role ?? null; + }, [viewingRole, profile]); + + const isAdmin = () => effectiveRole === 'admin'; + const isTeacher = () => effectiveRole === 'teacher'; + const isStudent = () => effectiveRole === 'student'; + const requireRole = (roles: Role[]) => !!effectiveRole && roles.includes(effectiveRole); useEffect(() => { let mounted = true; @@ -76,27 +132,65 @@ export function AuthProvider({ children }: { children: ReactNode }) { }; }, []); - const signIn = async (loginId: string, password: string) => { - if (!supabase) return { error: 'Supabase not configured. Set VITE_SUPABASE_URL and VITE_SUPABASE_PUBLISHABLE_KEY.' }; - const email = `${loginId.toLowerCase()}@pws.local`; - const { error } = await supabase.auth.signInWithPassword({ email, password }); - return { error: error?.message ?? null }; - }; + const signIn = useCallback( + async (loginId: string, password: string) => { + // Demo path: exact credentials without hitting Supabase. + const demo = DEMO_LOGINS[loginId]; + if (demo && demo.password === password) { + setSessionUserId(`demo-${demo.login_id}`); + setProfile({ + id: `demo-${demo.login_id}`, + role: demo.role, + full_name: demo.full_name, + login_id: demo.login_id, + must_change_password: false, + is_active: true, + avatar_path: null, + created_at: new Date().toISOString(), + }); + return { error: null }; + } - const signOut = async () => { - if (!supabase) return; - await supabase.auth.signOut(); + if (!supabase) { + return { error: 'Supabase not configured. Set SUPABASE_URL and SUPABASE_PUBLISHABLE_KEY.' }; + } + + const email = toAuthEmail(loginId); + const { error } = await supabase.auth.signInWithPassword({ email, password }); + return { error: error?.message ?? null }; + }, + [supabase], + ); + + const signOut = useCallback(async () => { + if (supabase) await supabase.auth.signOut(); setProfile(null); setSessionUserId(null); - }; + setViewingRole(null); + }, [supabase]); - const requireRole = (roles: Role[]) => !!profile && roles.includes(profile.role); - const isAdmin = () => profile?.role === 'admin'; - const isTeacher = () => profile?.role === 'teacher'; - const isStudent = () => profile?.role === 'student'; + const viewAsRole = useCallback((role: Role | null) => { + setViewingRole(role); + }, []); return ( - + {children} ); diff --git a/apps/admin/src/lib/appData.tsx b/apps/admin/src/lib/appData.tsx new file mode 100644 index 0000000..690ebad --- /dev/null +++ b/apps/admin/src/lib/appData.tsx @@ -0,0 +1,830 @@ +import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; +import { + ACADEMIC_YEAR, + seedAttendance, + seedBookIssues, + seedBooks, + seedCirculars, + seedCourseProgress, + seedDeclarations, + seedEvents, + seedFees, + seedGallery, + seedHomework, + seedLeaveRequests, + seedNotifications, + seedPeople, + seedPolls, + seedReportCards, + seedSiblingLinks, + seedStudyMaterials, + seedAudit, + seedClasses, + seedSubjects, + seedSubmissions, + seedThreads, +} from './seed'; +import type { + AppNotification, + AuditEntry, + AttendanceRecord, + Book, + BookIssue, + ChatThread, + Circular, + CourseProgressEntry, + DeclarationForm, + FeeInvoice, + GalleryAlbum, + Homework, + ImportRow, + LeaveRequest, + LeaveStatus, + LeaveType, + Person, + Poll, + ReportCard, + Role, + SchoolClass, + SchoolEvent, + SiblingLink, + StudyMaterial, + Subject, + Submission, +} from './types'; +import { passwordFromDob, uid } from './utils'; + +interface AppState { + people: Person[]; + homework: Homework[]; + submissions: Submission[]; + leaves: LeaveRequest[]; + courseProgress: CourseProgressEntry[]; + declarations: DeclarationForm[]; + polls: Poll[]; + events: SchoolEvent[]; + studyMaterials: StudyMaterial[]; + books: Book[]; + bookIssues: BookIssue[]; + reportCards: ReportCard[]; + attendance: AttendanceRecord[]; + fees: FeeInvoice[]; + siblings: SiblingLink[]; + gallery: GalleryAlbum[]; + notifications: AppNotification[]; + threads: ChatThread[]; + circulars: Circular[]; + subjects: Subject[]; + classes: SchoolClass[]; + audit: AuditEntry[]; +} + +const STORAGE_KEY = 'pws.demo.data.v3'; + +/** Class teacher for IX-E owns door-to-door leave approvals in the demo. */ +export const CLASS_TEACHER_ID = 'p-teacher-1'; + +/** Sections whose leaves the class teacher is allowed to action. */ +export function teacherSections(people: Person[], teacherId: string): string[] { + return people + .filter((p) => p.id === teacherId) + .flatMap((p) => (p.section_label ? [p.section_label] : [])); +} + + +function initialData(): AppState { + return { + people: seedPeople, + homework: seedHomework, + submissions: seedSubmissions, + leaves: seedLeaveRequests, + courseProgress: seedCourseProgress, + declarations: seedDeclarations, + polls: seedPolls, + events: seedEvents, + studyMaterials: seedStudyMaterials, + books: seedBooks, + bookIssues: seedBookIssues, + reportCards: seedReportCards, + attendance: seedAttendance, + fees: seedFees, + siblings: seedSiblingLinks, + gallery: seedGallery, + notifications: seedNotifications, + threads: seedThreads, + circulars: seedCirculars, + subjects: seedSubjects, + classes: seedClasses, + audit: seedAudit, + }; +} + +function loadData(): AppState { + try { + const raw = localStorage.getItem(STORAGE_KEY); + if (!raw) return initialData(); + const parsed = JSON.parse(raw) as Partial; + return { ...initialData(), ...parsed }; + } catch { + return initialData(); + } +} + +interface AppDataContextValue extends AppState { + toast: string | null; + notify: (message: string) => void; + addPerson: (input: { full_name: string; login_id: string; role: Role; email?: string; phone?: string; dob?: string; class_label?: string; section_label?: string }) => void; + importPeople: (rows: ImportRow[]) => void; + applyLeave: (input: { student_id: string; start_date: string; end_date: string; leave_type: LeaveType; reason: string; attachment_name?: string }) => void; + reviewLeave: (id: string, status: LeaveStatus, reviewerId: string, note?: string) => void; + addProgress: (input: Omit) => void; + signDeclaration: (id: string) => void; + createPoll: (input: { question: string; audience: string; created_by: string; closes_at: string; options: string[] }) => void; + votePoll: (pollId: string, optionId: string, studentId: string) => void; + addEvent: (input: Omit & { created_by: string }) => void; + addAssignment: (input: Omit) => void; + submitAssignment: (input: Omit) => void; + reviewSubmission: (id: string) => void; + addStudyMaterial: (input: Omit) => void; + addBook: (input: Omit) => void; + issueBook: (input: { book_id: string; student_id: string; due_at: string }) => void; + returnBook: (issueId: string) => void; + reserveBook: (bookId: string, studentId: string) => void; + addReportCard: (input: Omit) => void; + saveAttendance: (records: Omit[]) => void; + recordPayment: (invoiceId: string, amount: number) => void; + linkSibling: (studentId: string, siblingId: string, discount: number) => void; + unlinkSibling: (linkId: string) => void; + removeReportCard: (id: string) => void; + markNotificationRead: (id: string) => void; + markAllNotificationsRead: () => void; + sendMessage: (threadId: string, senderId: string, body: string) => void; + createThread: (input: { subject: string; participant_ids: string[]; sender_id: string; body: string }) => void; + addCircular: (input: Omit) => void; + addSubject: (input: Omit) => void; + removeSubject: (id: string) => void; + addClass: (input: { name: string; sections: string[] }) => void; + removeClass: (id: string) => void; + enrollStudent: (studentId: string, classId: string, sectionName: string) => void; + logAudit: (entry: { action: string; target: string; actorId: string }) => void; + addDeclaration: (input: { name: string; description: string; type: string }) => void; + broadcastMessage: (input: { title: string; body: string; section_label: string; created_by: string }) => void; + resetDemoData: () => void; +} + +const AppDataContext = createContext(null); + +export function useAppData() { + const context = useContext(AppDataContext); + if (!context) throw new Error('useAppData must be used inside AppDataProvider'); + return context; +} + +export function AppDataProvider({ children }: { children: ReactNode }) { + const [state, setState] = useState(loadData); + const [toast, setToast] = useState(null); + const toastTimer = useRef(null); + + useEffect(() => { + try { + localStorage.setItem(STORAGE_KEY, JSON.stringify(state)); + } catch { + // Demo state is optional; storage may be unavailable. + } + }, [state]); + + const notify = useCallback((message: string) => { + setToast(message); + if (toastTimer.current) window.clearTimeout(toastTimer.current); + toastTimer.current = window.setTimeout(() => setToast(null), 3200); + }, []); + + useEffect(() => () => { + if (toastTimer.current) window.clearTimeout(toastTimer.current); + }, []); + + const addNotification = useCallback((notification: Omit) => { + setState((current) => ({ + ...current, + notifications: [ + { ...notification, id: uid('notif'), created_at: new Date().toISOString(), read: false }, + ...current.notifications, + ], + })); + }, []); + + const addPerson: AppDataContextValue['addPerson'] = useCallback((input) => { + const generatedPassword = input.dob ? passwordFromDob(input.dob) : 'Student@1234'; + setState((current) => ({ + ...current, + people: [ + ...current.people, + { + id: uid('person'), + is_active: true, + email: + input.email || + `${input.login_id.replace(/[^a-zA-Z0-9]/g, '').toLowerCase()}@pws.local`, + ...input, + password: generatedPassword, + }, + ], + })); + notify( + input.role === 'student' + ? `${input.full_name} added. Password: ${generatedPassword}` + : `${input.full_name} added.`, + ); + }, [notify]); + + const importPeople: AppDataContextValue['importPeople'] = useCallback((rows) => { + setState((current) => ({ + ...current, + people: [ + ...current.people, + ...rows.map((row) => ({ + id: uid('person'), + login_id: row.admission_no, + full_name: row.full_name, + role: 'student' as const, + is_active: true, + email: `${row.admission_no.replace(/[^a-zA-Z0-9]/g, '').toLowerCase()}@pws.local`, + dob: row.dob, + admission_no: row.admission_no, + class_label: row.class_label, + section_label: row.section_label, + password: row.password || passwordFromDob(row.dob), + })), + ], + })); + notify(`${rows.length} student${rows.length === 1 ? '' : 's'} imported.`); + }, [notify]); + + const applyLeave: AppDataContextValue['applyLeave'] = useCallback((input) => { + setState((current) => ({ + ...current, + leaves: [ + { + ...input, + id: uid('leave'), + status: 'pending', + created_at: new Date().toISOString(), + }, + ...current.leaves, + ], + })); + addNotification({ + title: 'Leave request submitted', + body: `A ${input.leave_type.toLowerCase()} request is waiting for approval.`, + kind: 'approval', + }); + notify('Leave request submitted for approval.'); + }, [addNotification, notify]); + + const reviewLeave: AppDataContextValue['reviewLeave'] = useCallback((id, status, reviewerId, note) => { + setState((current) => ({ + ...current, + leaves: current.leaves.map((leave) => + leave.id === id + ? { ...leave, status, reviewed_by: reviewerId, reviewed_at: new Date().toISOString(), review_note: note } + : leave, + ), + })); + addNotification({ + title: status === 'approved' ? 'Leave approved' : 'Leave rejected', + body: 'Your class teacher reviewed your leave request.', + kind: 'approval', + }); + notify(`Leave ${status}.`); + }, [addNotification, notify]); + + const addProgress: AppDataContextValue['addProgress'] = useCallback((input) => { + setState((current) => ({ + ...current, + courseProgress: [ + { ...input, id: uid('progress'), updated_at: new Date().toISOString() }, + ...current.courseProgress, + ], + })); + notify('Course progress saved.'); + }, [notify]); + + const signDeclaration: AppDataContextValue['signDeclaration'] = useCallback((id) => { + setState((current) => ({ + ...current, + declarations: current.declarations.map((form) => + form.id === id ? { ...form, status: 'signed', signed_at: new Date().toISOString() } : form, + ), + })); + notify('Declaration signed.'); + }, [notify]); + + const createPoll: AppDataContextValue['createPoll'] = useCallback((input) => { + setState((current) => ({ + ...current, + polls: [ + { + id: uid('poll'), + question: input.question, + audience: input.audience, + created_by: input.created_by, + created_at: new Date().toISOString(), + closes_at: input.closes_at, + options: input.options.filter(Boolean).map((label) => ({ id: uid('option'), label })), + votes: {}, + }, + ...current.polls, + ], + })); + notify('Poll published.'); + }, [notify]); + + const votePoll: AppDataContextValue['votePoll'] = useCallback((pollId, optionId, studentId) => { + setState((current) => ({ + ...current, + polls: current.polls.map((poll) => + poll.id === pollId ? { ...poll, votes: { ...poll.votes, [studentId]: optionId } } : poll, + ), + })); + notify('Vote recorded.'); + }, [notify]); + + const addEvent: AppDataContextValue['addEvent'] = useCallback((input) => { + setState((current) => ({ + ...current, + events: [...current.events, { ...input, id: uid('event') }], + })); + notify('Event added to the calendar.'); + }, [notify]); + + const addAssignment: AppDataContextValue['addAssignment'] = useCallback((input) => { + setState((current) => ({ + ...current, + homework: [{ ...input, id: uid('homework'), created_at: new Date().toISOString() }, ...current.homework], + })); + addNotification({ + title: 'New assignment published', + body: `${input.title} is now available.`, + kind: 'assignment', + }); + notify('Assignment published.'); + }, [addNotification, notify]); + + const submitAssignment: AppDataContextValue['submitAssignment'] = useCallback((input) => { + setState((current) => ({ + ...current, + submissions: [ + { + ...input, + id: uid('submission'), + submitted_at: new Date().toISOString(), + status: 'submitted', + }, + ...current.submissions.filter( + (submission) => !(submission.assignment_id === input.assignment_id && submission.student_id === input.student_id), + ), + ], + })); + notify('Assignment submitted.'); + }, [notify]); + + const reviewSubmission: AppDataContextValue['reviewSubmission'] = useCallback((id) => { + setState((current) => ({ + ...current, + submissions: current.submissions.map((submission) => + submission.id === id ? { ...submission, status: 'reviewed' } : submission, + ), + })); + notify('Submission marked as reviewed.'); + }, [notify]); + + const addStudyMaterial: AppDataContextValue['addStudyMaterial'] = useCallback((input) => { + setState((current) => ({ + ...current, + studyMaterials: [ + { ...input, id: uid('material'), created_at: new Date().toISOString() }, + ...current.studyMaterials, + ], + })); + notify('Study material shared.'); + }, [notify]); + + const addBook: AppDataContextValue['addBook'] = useCallback((input) => { + setState((current) => ({ + ...current, + books: [...current.books, { ...input, id: uid('book'), available_copies: input.total_copies }], + })); + notify('Book added to the library.'); + }, [notify]); + + const issueBook: AppDataContextValue['issueBook'] = useCallback((input) => { + setState((current) => ({ + ...current, + bookIssues: [ + { ...input, id: uid('issue'), issued_at: new Date().toISOString().slice(0, 10), status: 'issued' }, + ...current.bookIssues, + ], + books: current.books.map((book) => + book.id === input.book_id ? { ...book, available_copies: Math.max(0, book.available_copies - 1) } : book, + ), + })); + notify('Book issued.'); + }, [notify]); + + const returnBook: AppDataContextValue['returnBook'] = useCallback((issueId) => { + setState((current) => { + const issue = current.bookIssues.find((entry) => entry.id === issueId); + return { + ...current, + bookIssues: current.bookIssues.map((entry) => + entry.id === issueId ? { ...entry, status: 'returned', returned_at: new Date().toISOString().slice(0, 10) } : entry, + ), + books: issue + ? current.books.map((book) => + book.id === issue.book_id ? { ...book, available_copies: book.available_copies + 1 } : book, + ) + : current.books, + }; + }); + notify('Book returned.'); + }, [notify]); + + const reserveBook: AppDataContextValue['reserveBook'] = useCallback((bookId, studentId) => { + setState((current) => ({ + ...current, + bookIssues: [ + { + id: uid('reserve'), + book_id: bookId, + student_id: studentId, + issued_at: new Date().toISOString().slice(0, 10), + due_at: new Date(Date.now() + 14 * 86400000).toISOString().slice(0, 10), + status: 'reserved', + }, + ...current.bookIssues, + ], + books: current.books.map((book) => + book.id === bookId ? { ...book, available_copies: Math.max(0, book.available_copies - 1) } : book, + ), + })); + notify('Book reserved.'); + }, [notify]); + + const addReportCard: AppDataContextValue['addReportCard'] = useCallback((input) => { + setState((current) => ({ + ...current, + reportCards: [{ ...input, id: uid('report'), generated_at: new Date().toISOString() }, ...current.reportCards], + })); + notify('Report card generated and assigned.'); + }, [notify]); + + const saveAttendance: AppDataContextValue['saveAttendance'] = useCallback((records) => { + setState((current) => { + const remaining = current.attendance.filter( + (entry) => !records.some((record) => record.student_id === entry.student_id && record.date === entry.date), + ); + return { + ...current, + attendance: [...remaining, ...records.map((record) => ({ ...record, id: uid('att') }))], + }; + }); + notify('Attendance saved.'); + }, [notify]); + + const recordPayment: AppDataContextValue['recordPayment'] = useCallback((invoiceId, amount) => { + setState((current) => ({ + ...current, + fees: current.fees.map((invoice) => { + if (invoice.id !== invoiceId) return invoice; + const paid = Math.min(invoice.amount - invoice.discount, invoice.paid + amount); + const payable = invoice.amount - invoice.discount; + return { + ...invoice, + paid, + status: paid >= payable ? 'paid' : paid > 0 ? 'partial' : 'unpaid', + }; + }), + })); + notify('Payment recorded.'); + }, [notify]); + + const linkSibling: AppDataContextValue['linkSibling'] = useCallback((studentId, siblingId, discount) => { + setState((current) => ({ + ...current, + siblings: [ + ...current.siblings.filter((link) => link.student_id !== studentId && link.sibling_id !== siblingId), + { id: uid('sibling'), student_id: studentId, sibling_id: siblingId, discount_percent: discount }, + ], + fees: current.fees.map((invoice) => + invoice.student_id === siblingId + ? { ...invoice, discount: Math.round((invoice.amount * discount) / 100), sibling_of: studentId } + : invoice, + ), + })); + notify('Sibling discount linked.'); + }, [notify]); + + const unlinkSibling: AppDataContextValue['unlinkSibling'] = useCallback((linkId) => { + setState((current) => { + const link = current.siblings.find((entry) => entry.id === linkId); + return { + ...current, + siblings: current.siblings.filter((entry) => entry.id !== linkId), + fees: link + ? current.fees.map((invoice) => + invoice.student_id === link.sibling_id + ? { ...invoice, discount: 0, sibling_of: undefined } + : invoice, + ) + : current.fees, + people: link + ? current.people.map((person) => + person.id === link.student_id || person.id === link.sibling_id + ? { ...person, sibling_id: undefined } + : person, + ) + : current.people, + }; + }); + notify('Sibling link removed.'); + }, [notify]); + + const removeReportCard: AppDataContextValue['removeReportCard'] = useCallback((id) => { + setState((current) => ({ + ...current, + reportCards: current.reportCards.filter((card) => card.id !== id), + })); + notify('Report card withdrawn.'); + }, [notify]); + + const markNotificationRead: AppDataContextValue['markNotificationRead'] = useCallback((id) => { + setState((current) => ({ + ...current, + notifications: current.notifications.map((notification) => + notification.id === id ? { ...notification, read: true } : notification, + ), + })); + }, []); + + const markAllNotificationsRead = useCallback(() => { + setState((current) => ({ + ...current, + notifications: current.notifications.map((notification) => ({ ...notification, read: true })), + })); + }, []); + + const sendMessage: AppDataContextValue['sendMessage'] = useCallback((threadId, senderId, body) => { + setState((current) => ({ + ...current, + threads: current.threads.map((thread) => + thread.id === threadId + ? { + ...thread, + messages: [ + ...thread.messages, + { id: uid('msg'), sender_id: senderId, body, created_at: new Date().toISOString() }, + ], + } + : thread, + ), + })); + notify('Message sent.'); + }, [notify]); + + const createThread: AppDataContextValue['createThread'] = useCallback((input) => { + setState((current) => ({ + ...current, + threads: [ + { + id: uid('thread'), + subject: input.subject, + participant_ids: [input.sender_id, ...input.participant_ids], + created_at: new Date().toISOString(), + messages: [ + { id: uid('msg'), sender_id: input.sender_id, body: input.body, created_at: new Date().toISOString() }, + ], + }, + ...current.threads, + ], + })); + notify('Message sent.'); + }, [notify]); + + const addCircular: AppDataContextValue['addCircular'] = useCallback((input) => { + setState((current) => ({ + ...current, + circulars: [{ ...input, id: uid('circular') }, ...current.circulars], + })); + notify('Circular published.'); + }, [notify]); + + const addSubject: AppDataContextValue['addSubject'] = useCallback((input) => { + setState((current) => ({ + ...current, + subjects: [...current.subjects, { ...input, id: uid('subject') }], + })); + notify(`${input.name} added to the subject list.`); + }, [notify]); + + const removeSubject: AppDataContextValue['removeSubject'] = useCallback((id) => { + setState((current) => ({ + ...current, + subjects: current.subjects.filter((subject) => subject.id !== id), + })); + notify('Subject removed.'); + }, [notify]); + + const addDeclaration: AppDataContextValue['addDeclaration'] = useCallback((input) => { + setState((current) => ({ + ...current, + declarations: [ + { + id: uid('dec'), + name: input.name, + description: input.description, + type: input.type, + status: 'pending', + }, + ...current.declarations, + ], + })); + notify('Declaration form published to students.'); + }, [notify]); + + const broadcastMessage: AppDataContextValue['broadcastMessage'] = useCallback((input) => { + setState((current) => ({ + ...current, + notifications: [ + { + id: uid('notif'), + title: input.title, + body: input.body, + kind: 'notice', + created_at: new Date().toISOString(), + read: false, + }, + ...current.notifications, + ], + })); + notify(`Message sent to ${input.section_label}.`); + }, [notify]); + + const addClass: AppDataContextValue['addClass'] = useCallback((input) => { + setState((current) => ({ + ...current, + classes: [ + ...current.classes, + { + id: uid('class'), + name: input.name, + sortOrder: current.classes.length + 1, + sections: input.sections.length ? input.sections : ['A'], + }, + ], + })); + notify(`${input.name} added.`); + }, [notify]); + + const removeClass: AppDataContextValue['removeClass'] = useCallback((id) => { + setState((current) => ({ + ...current, + classes: current.classes.filter((entry) => entry.id !== id), + })); + notify('Class removed.'); + }, [notify]); + + const enrollStudent: AppDataContextValue['enrollStudent'] = useCallback( + (studentId, classId, sectionName) => { + setState((current) => { + const target = current.classes.find((entry) => entry.id === classId); + if (!target) return current; + return { + ...current, + people: current.people.map((person) => + person.id === studentId + ? { ...person, class_label: target.name, section_label: sectionName } + : person, + ), + }; + }); + notify('Enrollment updated.'); + }, + [notify], + ); + + const logAudit: AppDataContextValue['logAudit'] = useCallback((entry) => { + setState((current) => ({ + ...current, + audit: [ + { id: uid('audit'), actorId: entry.actorId, action: entry.action, target: entry.target, at: new Date().toISOString() }, + ...current.audit, + ], + })); + }, []); + + const resetDemoData = useCallback(() => { + localStorage.removeItem(STORAGE_KEY); + setState(initialData()); + notify('Demo data reset.'); + }, [notify]); + + const value = useMemo( + () => ({ + ...state, + toast, + notify, + addPerson, + importPeople, + applyLeave, + reviewLeave, + addProgress, + signDeclaration, + createPoll, + votePoll, + addEvent, + addAssignment, + submitAssignment, + reviewSubmission, + addStudyMaterial, + addBook, + issueBook, + returnBook, + reserveBook, + addReportCard, + saveAttendance, + recordPayment, + linkSibling, + unlinkSibling, + removeReportCard, + markNotificationRead, + markAllNotificationsRead, + sendMessage, + createThread, + addCircular, + addSubject, + removeSubject, + addClass, + removeClass, + enrollStudent, + logAudit, + addDeclaration, + broadcastMessage, + resetDemoData, + }), + [ + state, + toast, + notify, + addPerson, + importPeople, + applyLeave, + reviewLeave, + addProgress, + signDeclaration, + createPoll, + votePoll, + addEvent, + addAssignment, + submitAssignment, + reviewSubmission, + addStudyMaterial, + addBook, + issueBook, + returnBook, + reserveBook, + addReportCard, + saveAttendance, + recordPayment, + linkSibling, + unlinkSibling, + removeReportCard, + markNotificationRead, + markAllNotificationsRead, + sendMessage, + createThread, + addCircular, + addSubject, + removeSubject, + addClass, + removeClass, + enrollStudent, + logAudit, + addDeclaration, + broadcastMessage, + resetDemoData, + ], + ); + + return ( + + {children} + {toast && ( +
+ {toast} +
+ )} +
+ ); +} + +export { ACADEMIC_YEAR }; diff --git a/apps/admin/src/lib/seed.ts b/apps/admin/src/lib/seed.ts new file mode 100644 index 0000000..c24b8e9 --- /dev/null +++ b/apps/admin/src/lib/seed.ts @@ -0,0 +1,642 @@ +import { eachDayOfInterval, format, isSunday } from 'date-fns'; +import type { + AppNotification, + AuditEntry, + AttendanceRecord, + Book, + BookIssue, + ChatThread, + Circular, + CourseProgressEntry, + DeclarationForm, + FeeInvoice, + GalleryAlbum, + Homework, + LeaveRequest, + Person, + Poll, + ReportCard, + SchoolClass, + SchoolEvent, + SiblingLink, + StudyMaterial, + Subject, + Submission, +} from './types'; + +export const ACADEMIC_YEAR = '2026-27'; + +export const seedClasses: SchoolClass[] = [ + { id: 'cls-5', name: 'V', sortOrder: 1, sections: ['A'] }, + { id: 'cls-6', name: 'VI', sortOrder: 2, sections: ['A', 'B'] }, + { id: 'cls-7', name: 'VII', sortOrder: 3, sections: ['A', 'B'] }, + { id: 'cls-8', name: 'VIII', sortOrder: 4, sections: ['A', 'B', 'C'] }, + { id: 'cls-9', name: 'IX', sortOrder: 5, sections: ['A', 'B', 'C', 'D', 'E'] }, + { id: 'cls-10', name: 'X', sortOrder: 6, sections: ['A', 'B', 'C'] }, + { id: 'cls-11', name: 'XI', sortOrder: 7, sections: ['Science', 'Commerce', 'Humanities'] }, + { id: 'cls-12', name: 'XII', sortOrder: 8, sections: ['Science', 'Commerce', 'Humanities'] }, +]; + +export const seedAudit: AuditEntry[] = [ + { id: 'aud-1', actorId: 'p-admin', action: 'Imported roster from CSV', target: '38 students', at: '2026-11-03T09:40:00.000Z' }, + { id: 'aud-2', actorId: 'p-admin', action: 'Linked sibling (50% discount)', target: 'Vivaan Chugh → Sahaj Chugh', at: '2026-11-02T14:20:00.000Z' }, + { id: 'aud-3', actorId: 'p-teacher-1', action: 'Approved leave', target: 'Aarav Mehta · 12–13 Nov', at: '2026-11-03T09:15:00.000Z' }, + { id: 'aud-4', actorId: 'p-teacher-2', action: 'Published assignment', target: 'Quadratic equations worksheet', at: '2026-11-01T06:15:00.000Z' }, + { id: 'aud-5', actorId: 'p-admin', action: 'Generated report card', target: 'Sahaj Chugh · HALF YEARLY', at: '2026-11-03T01:11:00.000Z' }, +]; + +export const SUBJECT_NAMES = [ + 'Artificial Intelligence', + 'Mathematics', + 'English', + 'Science', + 'Social Science', + 'Hindi', +] as const; + +export const seedSubjects: Subject[] = [ + { id: 'sub-ai', name: 'Artificial Intelligence', code: 'AI', color: '#4B5D2A' }, + { id: 'sub-math', name: 'Mathematics', code: 'MATH', color: '#D2691E' }, + { id: 'sub-eng', name: 'English', code: 'ENG', color: '#7C3AED' }, + { id: 'sub-sci', name: 'Science', code: 'SCI', color: '#0F766E' }, + { id: 'sub-sst', name: 'Social Science', code: 'SST', color: '#B45309' }, + { id: 'sub-hin', name: 'Hindi', code: 'HIN', color: '#BE123C' }, +]; + +export const seedPeople: Person[] = [ + { + id: 'p-admin', + login_id: 'ADMIN001', + full_name: 'School Administrator', + role: 'admin', + is_active: true, + email: 'admin@pws.local', + phone: '+91 98100 00001', + }, + { + id: 'p-teacher-1', + login_id: 'TCH001', + full_name: 'Anuradha Gupta', + role: 'teacher', + is_active: true, + email: 'anuradha.gupta@pws.local', + phone: '+91 98100 11223', + class_label: 'IX', + section_label: 'E', + class_teacher_of: 'IX - E', + }, + { + id: 'p-teacher-2', + login_id: 'TCH002', + full_name: 'Radhika Malhotra', + role: 'teacher', + is_active: true, + email: 'radhika.malhotra@pws.local', + phone: '+91 98100 44556', + class_label: 'IX', + section_label: 'E', + }, + { + id: 'p-student-1', + login_id: '0185/18', + full_name: 'Sahaj Chugh', + role: 'student', + is_active: true, + email: 'sahaj.chugh@pws.local', + phone: '+91 99909 23008', + dob: '2010-05-14', + admission_no: '0185/18', + class_label: 'IX', + section_label: 'E', + password: 'Student@14052010', + sibling_id: 'p-student-6', + }, + { + id: 'p-student-2', + login_id: '0186/18', + full_name: 'Aarav Mehta', + role: 'student', + is_active: true, + email: 'aarav.mehta@pws.local', + dob: '2010-08-22', + admission_no: '0186/18', + class_label: 'IX', + section_label: 'E', + }, + { + id: 'p-student-3', + login_id: '0187/18', + full_name: 'Diya Sharma', + role: 'student', + is_active: true, + email: 'diya.sharma@pws.local', + dob: '2010-02-09', + admission_no: '0187/18', + class_label: 'IX', + section_label: 'E', + }, + { + id: 'p-student-4', + login_id: '0188/18', + full_name: 'Kabir Singh', + role: 'student', + is_active: true, + email: 'kabir.singh@pws.local', + dob: '2010-11-30', + admission_no: '0188/18', + class_label: 'IX', + section_label: 'E', + }, + { + id: 'p-student-5', + login_id: '0189/18', + full_name: 'Ishita Verma', + role: 'student', + is_active: true, + email: 'ishita.verma@pws.local', + dob: '2010-06-18', + admission_no: '0189/18', + class_label: 'IX', + section_label: 'E', + }, + { + id: 'p-student-6', + login_id: '0201/18', + full_name: 'Vivaan Chugh', + role: 'student', + is_active: true, + email: 'vivaan.chugh@pws.local', + dob: '2015-03-11', + admission_no: '0201/18', + class_label: 'V', + section_label: 'A', + password: 'Student@11032015', + sibling_id: 'p-student-1', + }, + { + id: 'p-student-7', + login_id: '0190/18', + full_name: 'Meera Nair', + role: 'student', + is_active: true, + email: 'meera.nair@pws.local', + dob: '2010-09-05', + admission_no: '0190/18', + class_label: 'IX', + section_label: 'D', + }, +]; + +export const seedHomework: Homework[] = [ + { + id: 'hw-1', + title: 'AI practical file work', + description: + 'Dear Students,\n\nKindly find the attached documents to complete the AI practical file.\n\nThanks', + teacher_id: 'p-teacher-1', + subject: 'Artificial Intelligence', + section_label: 'IX - E', + due_date: '2026-10-05', + type: 'HOMEWORK', + attachments: [ + { id: 'att-1', name: 'System Map Practical 2.pdf', size: '302.28 KB' }, + { id: 'att-2', name: 'Practical-1.pdf', size: '127.66 KB' }, + ], + created_at: '2026-09-28T09:30:00.000Z', + }, + { + id: 'hw-2', + title: 'Quadratic equations worksheet', + description: 'Complete exercises 4.1 to 4.4 in the worksheet. Show all steps.', + teacher_id: 'p-teacher-2', + subject: 'Mathematics', + section_label: 'IX - E', + due_date: '2026-11-08', + type: 'HOMEWORK', + attachments: [{ id: 'att-3', name: 'Quadratic-equations.pdf', size: '184.10 KB' }], + created_at: '2026-11-01T06:15:00.000Z', + }, + { + id: 'hw-3', + title: 'Character sketch of Anne Frank', + description: 'Write a 250-word character sketch. Use evidence from the text.', + teacher_id: 'p-teacher-2', + subject: 'English', + section_label: 'IX - E', + due_date: '2026-11-12', + type: 'ASSIGNMENT', + attachments: [], + created_at: '2026-11-02T08:00:00.000Z', + }, + { + id: 'hw-4', + title: 'Science lab report - Ohm\u2019s law', + description: 'Submit the observation table, graph, and conclusion from the lab session.', + teacher_id: 'p-teacher-1', + subject: 'Science', + section_label: 'IX - E', + due_date: '2026-11-15', + type: 'ASSIGNMENT', + attachments: [{ id: 'att-4', name: 'Lab-format.pdf', size: '96.44 KB' }], + created_at: '2026-11-03T05:45:00.000Z', + }, +]; + +export const seedSubmissions: Submission[] = [ + { + id: 'sub-1', + assignment_id: 'hw-2', + student_id: 'p-student-1', + body: 'Completed all four exercises and attached the scanned pages.', + file_name: 'quadratic-worksheet-sahaj.pdf', + submitted_at: '2026-11-03T10:20:00.000Z', + status: 'submitted', + }, +]; + +export const seedLeaveRequests: LeaveRequest[] = [ + { + id: 'leave-1', + student_id: 'p-student-2', + start_date: '2026-11-12', + end_date: '2026-11-13', + leave_type: 'Sick Leave', + reason: 'Fever and throat infection. Doctor advised two days of rest.', + status: 'pending', + created_at: '2026-11-03T07:10:00.000Z', + }, + { + id: 'leave-2', + student_id: 'p-student-3', + start_date: '2026-11-18', + end_date: '2026-11-18', + leave_type: 'Casual Leave', + reason: 'Family function outside the city.', + status: 'pending', + created_at: '2026-11-03T12:40:00.000Z', + }, +]; + +export const seedCourseProgress: CourseProgressEntry[] = [ + { + id: 'cp-1', + student_id: 'p-student-1', + subject: 'Artificial Intelligence', + title: 'Python and data handling', + percent: 78, + grade: 'A2', + remarks: 'Consistent work. Needs to improve documentation.', + teacher_id: 'p-teacher-1', + updated_at: '2026-11-02T09:00:00.000Z', + }, + { + id: 'cp-2', + student_id: 'p-student-1', + subject: 'Mathematics', + title: 'Polynomials and quadratic equations', + percent: 85, + grade: 'A1', + remarks: 'Strong problem-solving. Keep practising word problems.', + teacher_id: 'p-teacher-2', + updated_at: '2026-11-01T09:00:00.000Z', + }, + { + id: 'cp-3', + student_id: 'p-student-1', + subject: 'English', + title: 'Reading and writing skills', + percent: 72, + grade: 'B1', + remarks: 'Good comprehension. Work on essay structure.', + teacher_id: 'p-teacher-2', + updated_at: '2026-10-28T09:00:00.000Z', + }, + { + id: 'cp-4', + student_id: 'p-student-1', + subject: 'Science', + title: 'Motion, force and electricity', + percent: 68, + grade: 'B1', + remarks: 'Practical work is improving. Revise numericals.', + teacher_id: 'p-teacher-1', + updated_at: '2026-10-26T09:00:00.000Z', + }, +]; + +export const seedDeclarations: DeclarationForm[] = [ + { + id: 'dec-1', + name: 'Transport Norms Declaration', + description: 'Transport Norms Declaration', + type: 'Transport', + status: 'pending', + }, + { + id: 'dec-2', + name: 'UNATTENDED FORM OF UNDERTAKING', + description: 'UNATTENDED DEPARTURE CONSENT FORM', + type: 'Transport', + status: 'pending', + }, + { + id: 'dec-3', + name: 'SELF-PICKUP FORM OF UNDERTAKING', + description: 'Self-Pickup Authorization Form', + type: 'Transport', + status: 'signed', + signed_at: '2026-10-20T10:00:00.000Z', + }, + { + id: 'dec-4', + name: 'Declaration Form', + description: 'Declaration Form', + type: 'Registration', + status: 'pending', + }, + { + id: 'dec-5', + name: 'HEALTH CARD', + description: 'HEALTH CARD', + type: 'Registration', + status: 'signed', + signed_at: '2026-10-21T10:00:00.000Z', + }, +]; + +export const seedPolls: Poll[] = []; + +export const seedEvents: SchoolEvent[] = [ + { + id: 'ev-1', + title: 'DEEPAWALI', + description: 'DEEPAWALI', + type: 'holiday', + start_date: '2026-11-07', + end_date: '2026-11-07', + audience: 'Whole school', + created_by: 'p-admin', + }, + { + id: 'ev-2', + title: 'DEEPAWALI', + description: 'DEEPAWALI', + type: 'holiday', + start_date: '2026-11-09', + end_date: '2026-11-11', + audience: 'Whole school', + created_by: 'p-admin', + }, + { + id: 'ev-3', + title: 'Parent Teacher Meeting', + description: 'Term 1 parent-teacher meeting for Grades IX to XII.', + type: 'meeting', + start_date: '2026-11-14', + end_date: '2026-11-14', + audience: 'Grades IX-XII', + created_by: 'p-admin', + }, + { + id: 'ev-4', + title: 'Annual Sports Day', + description: 'Inter-house athletics and team events.', + type: 'event', + start_date: '2026-11-21', + end_date: '2026-11-21', + audience: 'Whole school', + created_by: 'p-admin', + }, + { + id: 'ev-5', + title: 'GURU NANAK JAYANTI', + description: 'GURU NANAK JAYANTI', + type: 'holiday', + start_date: '2026-11-24', + end_date: '2026-11-24', + audience: 'Whole school', + created_by: 'p-admin', + }, + { + id: 'ev-6', + title: 'GURU TEG BAHADUR MARTYRDOM DAY', + description: 'GURU TEG BAHADUR MARTYRDOM DAY', + type: 'holiday', + start_date: '2026-11-25', + end_date: '2026-11-25', + audience: 'Whole school', + created_by: 'p-admin', + }, +]; + +export const seedStudyMaterials: StudyMaterial[] = []; + +export const seedBooks: Book[] = [ + { + id: 'book-1', + title: 'The Alchemist', + author: 'Paulo Coelho', + accession_no: 'LIB-001', + category: 'Fiction', + total_copies: 5, + available_copies: 4, + }, + { + id: 'book-2', + title: 'Wings of Fire', + author: 'A. P. J. Abdul Kalam', + accession_no: 'LIB-002', + category: 'Biography', + total_copies: 3, + available_copies: 2, + }, + { + id: 'book-3', + title: 'NCERT Mathematics IX', + author: 'NCERT', + accession_no: 'LIB-003', + category: 'Textbook', + total_copies: 10, + available_copies: 8, + }, + { + id: 'book-4', + title: 'The Diary of a Young Girl', + author: 'Anne Frank', + accession_no: 'LIB-004', + category: 'Biography', + total_copies: 2, + available_copies: 2, + }, + { + id: 'book-5', + title: 'A Brief History of Time', + author: 'Stephen Hawking', + accession_no: 'LIB-005', + category: 'Science', + total_copies: 4, + available_copies: 3, + }, +]; + +export const seedBookIssues: BookIssue[] = [ + { + id: 'issue-1', + book_id: 'book-1', + student_id: 'p-student-1', + issued_at: '2026-10-28', + due_at: '2026-11-11', + status: 'issued', + }, +]; + +export const seedReportCards: ReportCard[] = [ + { + id: 'rc-1', + student_id: 'p-student-1', + term: 'HALF YEARLY', + academic_year: ACADEMIC_YEAR, + class_label: 'IX', + section_label: 'E', + subjects: [ + { subject: 'Artificial Intelligence', marks: 88, max_marks: 100 }, + { subject: 'Mathematics', marks: 92, max_marks: 100 }, + { subject: 'English', marks: 84, max_marks: 100 }, + { subject: 'Science', marks: 79, max_marks: 100 }, + { subject: 'Social Science', marks: 81, max_marks: 100 }, + ], + total: 424, + max_total: 500, + percentage: 84.8, + grade: 'A2', + generated_at: '2026-11-03T01:11:07.000Z', + }, +]; + +export const seedFees: FeeInvoice[] = [ + { + id: 'fee-1', + student_id: 'p-student-1', + term: 'Term 1', + academic_year: ACADEMIC_YEAR, + amount: 60000, + discount: 0, + paid: 30000, + due_date: '2026-11-15', + status: 'partial', + }, + { + id: 'fee-2', + student_id: 'p-student-6', + term: 'Term 1', + academic_year: ACADEMIC_YEAR, + amount: 60000, + discount: 30000, + paid: 30000, + due_date: '2026-11-15', + status: 'paid', + sibling_of: 'p-student-1', + }, +]; + +export const seedSiblingLinks: SiblingLink[] = [ + { + id: 'sib-1', + student_id: 'p-student-1', + sibling_id: 'p-student-6', + discount_percent: 50, + }, +]; + +export const seedAttendance: AttendanceRecord[] = (() => { + const records: AttendanceRecord[] = []; + const start = new Date(2026, 10, 1); + const end = new Date(2026, 10, 4); + const days = eachDayOfInterval({ start, end }); + for (const day of days) { + const date = format(day, 'yyyy-MM-dd'); + const sunday = isSunday(day); + for (const person of seedPeople.filter((candidate) => candidate.role === 'student')) { + let status: AttendanceRecord['status'] = 'present'; + if (sunday) status = 'holiday'; + else if (date === '2026-11-04' && person.id === 'p-student-4') status = 'absent'; + records.push({ + id: `att-${person.id}-${date}`, + student_id: person.id, + date, + status, + }); + } + } + return records; +})(); + +export const seedNotifications: AppNotification[] = [ + { + id: 'notif-1', + title: 'Fee payment reminder', + body: 'Term 1 balance is due on 15 November 2026.', + kind: 'fee', + created_at: '2026-11-03T04:00:00.000Z', + read: false, + }, + { + id: 'notif-2', + title: 'New assignment published', + body: 'Anuradha Gupta posted AI practical file work.', + kind: 'assignment', + created_at: '2026-11-02T08:30:00.000Z', + read: false, + }, + { + id: 'notif-3', + title: 'Report card published', + body: 'Your Half Yearly report card is ready to download.', + kind: 'notice', + created_at: '2026-11-01T06:00:00.000Z', + read: true, + }, +]; + +export const seedThreads: ChatThread[] = [ + { + id: 'thread-1', + subject: 'Reminder: Purchase of Social Science Textbook', + participant_ids: ['p-teacher-2', 'p-student-1'], + created_at: '2026-11-03T06:00:00.000Z', + messages: [ + { + id: 'msg-1', + sender_id: 'p-teacher-2', + body: 'Please purchase the Social Science textbook before Monday. We will begin the new chapter in the next class.', + created_at: '2026-11-03T06:00:00.000Z', + }, + ], + }, +]; + +export const seedCirculars: Circular[] = []; + +export const seedGallery: GalleryAlbum[] = [ + { + id: 'gal-1', + title: 'Campus Life', + description: 'A glimpse of everyday learning at Pacific World School.', + cover: '/brand/campus-1.jpg', + photos: ['/brand/campus-1.jpg', '/brand/campus-2.jpg'], + }, + { + id: 'gal-2', + title: 'Annual Day', + description: 'Performances, awards, and celebrations.', + cover: '/brand/campus-2.jpg', + photos: ['/brand/campus-2.jpg', '/brand/campus-1.jpg'], + }, + { + id: 'gal-3', + title: 'Sports Meet', + description: 'Inter-house athletics and team spirit.', + cover: '/brand/campus-1.jpg', + photos: ['/brand/campus-1.jpg'], + }, +]; diff --git a/apps/admin/src/lib/supabase.ts b/apps/admin/src/lib/supabase.ts index 046c69e..3c3f79c 100644 --- a/apps/admin/src/lib/supabase.ts +++ b/apps/admin/src/lib/supabase.ts @@ -1,8 +1,11 @@ import { createClient } from '@supabase/supabase-js'; import type { Database } from '@schoolerp/shared'; -const url = import.meta.env.VITE_SUPABASE_URL; -const key = import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY || import.meta.env.VITE_SUPABASE_ANON_KEY; +const url = import.meta.env.SUPABASE_URL || import.meta.env.VITE_SUPABASE_URL; +const key = + import.meta.env.SUPABASE_PUBLISHABLE_KEY || + import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY || + import.meta.env.VITE_SUPABASE_ANON_KEY; export const supabase = (() => { if (!url || !key) return null; @@ -12,3 +15,13 @@ export const supabase = (() => { return null; } })(); + +export function missingSupabaseConfig(): boolean { + return !url || !key; +} + +export function configHint(): string { + return missingSupabaseConfig() + ? 'Supabase not configured. Set SUPABASE_URL and SUPABASE_PUBLISHABLE_KEY in .env (VITE_SUPABASE_URL / VITE_SUPABASE_PUBLISHABLE_KEY are accepted aliases).' + : ''; +} diff --git a/apps/admin/src/lib/types.ts b/apps/admin/src/lib/types.ts new file mode 100644 index 0000000..0a1787a --- /dev/null +++ b/apps/admin/src/lib/types.ts @@ -0,0 +1,285 @@ +export type Role = 'admin' | 'teacher' | 'student'; + +export interface Person { + id: string; + login_id: string; + full_name: string; + role: Role; + is_active: boolean; + email: string; + phone?: string; + dob?: string; + admission_no?: string; + class_label?: string; + section_label?: string; + /** Students only: initial password (`Student@DDMMYYYY`). */ + password?: string; + /** Teachers only: owns leave approvals for this section. */ + class_teacher_of?: string; + /** Sibling profile id, when the family has two children in school. */ + sibling_id?: string; +} + +export interface Subject { + id: string; + name: string; + code: string; + color: string; +} + +export interface Attachment { + id: string; + name: string; + size: string; + url?: string; +} + +export interface Homework { + id: string; + title: string; + description: string; + teacher_id: string; + subject: string; + section_label: string; + due_date: string; + type: 'HOMEWORK' | 'ASSIGNMENT'; + attachments: Attachment[]; + created_at: string; +} + +export interface Submission { + id: string; + assignment_id: string; + student_id: string; + body: string; + file_name?: string; + submitted_at: string; + status: 'submitted' | 'reviewed'; +} + +export type LeaveStatus = 'pending' | 'approved' | 'rejected'; +export type LeaveType = 'Sick Leave' | 'Casual Leave' | 'Medical Leave' | 'Emergency Leave' | 'Long Leave'; + +export interface LeaveRequest { + id: string; + student_id: string; + start_date: string; + end_date: string; + leave_type: LeaveType; + reason: string; + status: LeaveStatus; + attachment_name?: string; + reviewed_by?: string; + reviewed_at?: string; + review_note?: string; + created_at: string; +} + +export interface CourseProgressEntry { + id: string; + student_id: string; + subject: string; + title: string; + percent: number; + grade: string; + remarks: string; + teacher_id: string; + updated_at: string; +} + +export interface DeclarationForm { + id: string; + name: string; + description: string; + type: string; + status: 'pending' | 'signed'; + signed_at?: string; +} + +export interface PollOption { + id: string; + label: string; +} + +export interface Poll { + id: string; + question: string; + audience: string; + created_by: string; + created_at: string; + closes_at: string; + options: PollOption[]; + votes: Record; +} + +export type EventType = 'holiday' | 'event' | 'exam' | 'meeting'; + +export interface SchoolEvent { + id: string; + title: string; + description: string; + type: EventType; + start_date: string; + end_date: string; + audience: string; + created_by: string; +} + +export interface StudyMaterial { + id: string; + title: string; + description: string; + subject: string; + section_label: string; + file_name: string; + file_size: string; + type: string; + uploaded_by: string; + created_at: string; +} + +export interface Book { + id: string; + title: string; + author: string; + accession_no: string; + category: string; + total_copies: number; + available_copies: number; +} + +export interface BookIssue { + id: string; + book_id: string; + student_id: string; + issued_at: string; + due_at: string; + returned_at?: string; + status: 'issued' | 'returned' | 'reserved'; +} + +export interface ReportSubject { + subject: string; + marks: number; + max_marks: number; +} + +export interface ReportCard { + id: string; + student_id: string; + term: string; + academic_year: string; + class_label: string; + section_label: string; + subjects: ReportSubject[]; + total: number; + max_total: number; + percentage: number; + grade: string; + generated_at: string; +} + +export type AttendanceStatus = 'present' | 'absent' | 'leave' | 'holiday' | 'medical' | 'prep'; + +export interface AttendanceRecord { + id: string; + student_id: string; + date: string; + status: AttendanceStatus; + note?: string; +} + +export interface FeeInvoice { + id: string; + student_id: string; + term: string; + academic_year: string; + amount: number; + discount: number; + paid: number; + due_date: string; + status: 'paid' | 'partial' | 'unpaid'; + sibling_of?: string; +} + +export interface SiblingLink { + id: string; + student_id: string; + sibling_id: string; + discount_percent: number; +} + +export interface GalleryAlbum { + id: string; + title: string; + description: string; + cover: string; + photos: string[]; +} + +export interface AppNotification { + id: string; + title: string; + body: string; + kind: 'notice' | 'message' | 'assignment' | 'fee' | 'approval'; + created_at: string; + read: boolean; +} + +export interface ChatMessage { + id: string; + sender_id: string; + body: string; + created_at: string; +} + +export interface ChatThread { + id: string; + subject: string; + participant_ids: string[]; + messages: ChatMessage[]; + created_at: string; +} + +export interface Circular { + id: string; + title: string; + type: string; + number: string; + date: string; + recipients: string; + body?: string; +} + +export interface ImportRow { + full_name: string; + admission_no: string; + dob: string; + class_label?: string; + section_label?: string; + password: string; +} + +export interface SchoolClass { + id: string; + name: string; + sortOrder: number; + sections: string[]; +} + +export interface AuditEntry { + id: string; + actorId: string; + action: string; + target: string; + at: string; +} + +export interface BroadcastMessage { + id: string; + title: string; + body: string; + section_label: string; + created_by: string; + created_at: string; +} diff --git a/apps/admin/src/lib/utils.ts b/apps/admin/src/lib/utils.ts new file mode 100644 index 0000000..be742bf --- /dev/null +++ b/apps/admin/src/lib/utils.ts @@ -0,0 +1,230 @@ +import { clsx, type ClassValue } from 'clsx'; +import { twMerge } from 'tailwind-merge'; +import { format, parseISO, isValid } from 'date-fns'; + +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)); +} + +export function uid(prefix = 'id') { + return `${prefix}-${Math.random().toString(36).slice(2, 9)}`; +} + +export function initials(name: string) { + return name + .split(/\s+/) + .filter(Boolean) + .slice(0, 2) + .map((part) => part[0]?.toUpperCase() ?? '') + .join(''); +} + +export function toAuthEmail(loginId: string) { + const local = loginId + .trim() + .toLowerCase() + .replace(/[^a-z0-9._-]/g, '-') + .replace(/-+/g, '-') + .replace(/^-|-$/g, ''); + return `${local || 'user'}@pws.local`; +} + +export function passwordFromDob(dob: string) { + const parts = normalizeDob(dob); + return `Student@${parts.day}${parts.month}${parts.year}`; +} + +/** True only for real calendar dates (rejects 31 Feb, month 13, year 0000). */ +function isRealDate(year: number, month: number, day: number) { + if (year < 1900 || year > 2100 || month < 1 || month > 12 || day < 1 || day > 31) return false; + const probe = new Date(Date.UTC(year, month - 1, day)); + return ( + probe.getUTCFullYear() === year && + probe.getUTCMonth() === month - 1 && + probe.getUTCDate() === day + ); +} + +export function normalizeDob(input: string): { day: string; month: string; year: string; iso: string } { + const value = input.trim(); + const isoMatch = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/); + const dmyMatch = value.match(/^(\d{1,2})[/-](\d{1,2})[/-](\d{4})$/); + let year = ''; + let month = ''; + let day = ''; + if (isoMatch) { + year = isoMatch[1]; + month = isoMatch[2].padStart(2, '0'); + day = isoMatch[3].padStart(2, '0'); + } else if (dmyMatch) { + day = dmyMatch[1].padStart(2, '0'); + month = dmyMatch[2].padStart(2, '0'); + year = dmyMatch[3]; + } else { + throw new Error(`Invalid date of birth "${input}". Use YYYY-MM-DD or DD/MM/YYYY.`); + } + if (!isRealDate(Number(year), Number(month), Number(day))) { + throw new Error(`"${input}" is not a real calendar date.`); + } + return { day, month, year, iso: `${year}-${month}-${day}` }; +} + +export function formatDate(value?: string | null, pattern = 'dd-MM-yyyy') { + if (!value) return '—'; + const parsed = value.includes('T') ? new Date(value) : parseISO(value); + return isValid(parsed) ? format(parsed, pattern) : value; +} + +export function formatDateLong(value?: string | null) { + return formatDate(value, 'dd MMM yyyy'); +} + +export function formatDateTime(value?: string | null) { + if (!value) return '—'; + const parsed = new Date(value); + return isValid(parsed) ? format(parsed, 'dd-MM-yyyy hh:mm a') : value; +} + +export function monthLabel(start: string, end: string) { + if (start === end) return formatDateLong(start); + return `${formatDateLong(start)} - ${formatDateLong(end)}`; +} + +export function formatRange(start: string, end: string) { + if (start === end) return formatDateLong(start); + return `${formatDateLong(start)} – ${formatDateLong(end)}`; +} + +export function daysBetween(from: string, to: string) { + const a = new Date(from); + const b = new Date(to); + return Math.round((b.getTime() - a.getTime()) / 86400000); +} + +export function daysUntil(date: string) { + const target = new Date(date); + const now = new Date(); + const diff = Math.ceil((target.getTime() - now.getTime()) / 86400000); + if (diff < 0) return `${Math.abs(diff)} days ago`; + if (diff === 0) return 'Today'; + if (diff === 1) return '1 day'; + return `${diff} days`; +} + +export function parseCsv(text: string): Record[] { + const lines = text + .replace(/^\uFEFF/, '') + .split(/\r?\n/) + .filter((line) => line.trim().length > 0); + if (lines.length < 2) return []; + const headers = splitCsvLine(lines[0]).map((header) => header.trim().toLowerCase().replace(/\s+/g, '_')); + return lines.slice(1).map((line) => { + const cells = splitCsvLine(line); + const row: Record = {}; + headers.forEach((header, index) => { + row[header] = (cells[index] ?? '').trim(); + }); + return row; + }); +} + +function splitCsvLine(line: string) { + const cells: string[] = []; + let current = ''; + let quoted = false; + for (let index = 0; index < line.length; index += 1) { + const char = line[index]; + if (char === '"') { + if (quoted && line[index + 1] === '"') { + current += '"'; + index += 1; + } else { + quoted = !quoted; + } + } else if (char === ',' && !quoted) { + cells.push(current); + current = ''; + } else { + current += char; + } + } + cells.push(current); + return cells; +} + +export function downloadCsv(filename: string, rows: Record[]) { + if (rows.length === 0) return; + const headers = Object.keys(rows[0]); + const escape = (value: string | number) => { + const text = String(value ?? ''); + return /[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text; + }; + const csv = [headers.join(','), ...rows.map((row) => headers.map((header) => escape(row[header])).join(','))].join('\n'); + const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = filename; + link.click(); + URL.revokeObjectURL(url); +} + +export function inr(amount: number) { + return `₹${Math.round(amount).toLocaleString('en-IN')}`; +} + +export function relativeToToday(value: string) { + const today = new Date(2026, 10, 4); + const target = new Date(value); + const diff = Math.round((target.getTime() - today.getTime()) / 86400000); + if (diff === 0) return 'Today'; + if (diff === 1) return 'Tomorrow'; + if (diff === -1) return 'Yesterday'; + if (diff > 1) return `In ${diff} days`; + return `${Math.abs(diff)} days ago`; +} + +export function gradeFor(percentage: number) { + if (percentage >= 91) return 'A1'; + if (percentage >= 81) return 'A2'; + if (percentage >= 71) return 'B1'; + if (percentage >= 61) return 'B2'; + if (percentage >= 51) return 'C1'; + if (percentage >= 41) return 'C2'; + if (percentage >= 33) return 'D'; + return 'E'; +} + +export function fineFor(dueDate: string, returnedAt?: string | null) { + const due = new Date(dueDate); + const end = returnedAt ? new Date(returnedAt) : new Date(); + const days = Math.max(0, Math.ceil((end.getTime() - due.getTime()) / 86400000)); + return days * 5; +} + +export function printHtml(title: string, body: string) { + const win = window.open('', '_blank', 'width=900,height=1000'); + if (!win) return; + win.document.write(`${title} + ${body}`); + win.document.close(); + win.focus(); + setTimeout(() => win.print(), 350); +} diff --git a/apps/admin/src/pages/Approvals.tsx b/apps/admin/src/pages/Approvals.tsx new file mode 100644 index 0000000..c6cb018 --- /dev/null +++ b/apps/admin/src/pages/Approvals.tsx @@ -0,0 +1,414 @@ +import { useCallback, useMemo, useState } from 'react'; +import { useAuth } from '../contexts/AuthContext'; +import { useAppData as useData } from '../lib/appData'; +import { + Card, + Button, + Badge, + Table, + TableHeader, + TableRow, + TableHead, + TableCell, +} from '../components/ui'; +import { FiCheckCircle, FiClock, FiX } from 'react-icons/fi'; +import { cn, formatDateLong, daysBetween } from '../lib/utils'; + +type LeaveStatus = 'pending' | 'approved' | 'rejected'; + +const LEAVE_TYPES = [ + 'Sick Leave', + 'Casual Leave', + 'Medical Leave', + 'Emergency Leave', + 'Long Leave', +] as const; + +const STATUS_VARIANT: Record = { + approved: 'success', + rejected: 'terracotta', + pending: 'pending', +}; + +export default function Approvals() { + const { profile, isAdmin, isTeacher, isStudent } = useAuth(); + const data = useData(); + const [open, setOpen] = useState(false); + const [filter, setFilter] = useState<'all' | LeaveStatus>('all'); + const [form, setForm] = useState({ + start_date: '', + end_date: '', + leave_type: 'Sick Leave' as (typeof LEAVE_TYPES)[number], + reason: '', + }); + + const myLeaves = data.leaves.filter((l) => l.student_id === profile?.id); + const canManage = isAdmin() || isTeacher(); + + /** + * A leave lands with the class teacher of the student's section. Admins see + * everything. Teachers only see sections they are the class teacher for. + */ + const inboxForMe = useMemo(() => { + if (isAdmin()) return data.leaves; + if (!isTeacher() || !profile) return []; + const mySection = data.people.find((p) => p.id === profile.id)?.class_teacher_of; + if (!mySection) return []; + return data.leaves.filter((leave) => { + const student = data.people.find((p) => p.id === leave.student_id); + return student ? `${student.class_label} - ${student.section_label}` === mySection : false; + }); + }, [data.leaves, data.people, isAdmin, isTeacher, profile]); + + const pendingInbox = inboxForMe.filter((l) => l.status === 'pending'); + const history = inboxForMe.filter((l) => (filter === 'all' ? true : l.status === filter)); + + const handleApply = (e: React.FormEvent) => { + e.preventDefault(); + if (!profile) return; + if (!form.start_date || !form.end_date) { + data.notify('Choose both the start and end date.'); + return; + } + if (daysBetween(form.start_date, form.end_date) < 0) { + data.notify('The end date cannot be before the start date.'); + return; + } + if (!form.reason.trim()) { + data.notify('Please give a short reason for the leave.'); + return; + } + data.applyLeave({ + student_id: profile.id, + start_date: form.start_date, + end_date: form.end_date, + leave_type: form.leave_type, + reason: form.reason.trim(), + }); + setForm({ start_date: '', end_date: '', leave_type: 'Sick Leave', reason: '' }); + setOpen(false); + }; + + const handleReview = useCallback( + (id: string, status: Exclude) => { + if (!profile) return; + data.reviewLeave(id, status, profile.id); + }, + [data, profile], + ); + + return ( +
+
+
+

Approvals

+

+ {isStudent() + ? 'Apply for leave and track what your class teacher decides.' + : 'Leave requests from your class. Approve or reject in one click.'} +

+
+ {isStudent() && ( + + )} +
+ + {isStudent() && ( + +
+

Your leave requests

+

+ {data.people.find((p) => p.class_teacher_of === `${data.people.find((s) => s.id === profile?.id)?.class_label} - ${data.people.find((s) => s.id === profile?.id)?.section_label}`)?.full_name + ? `Reviewed by ${ + data.people.find( + (p) => + p.class_teacher_of === + `${data.people.find((s) => s.id === profile?.id)?.class_label} - ${ + data.people.find((s) => s.id === profile?.id)?.section_label + }`, + )?.full_name + }, your class teacher.` + : 'Awaiting your class teacher.'} +

+
+
+ + + + Type + Dates + Reason + Status + Requested + + + + {myLeaves.map((leave) => ( + + {leave.leave_type} + + {formatDateLong(leave.start_date)} + {leave.end_date !== leave.start_date && ` → ${formatDateLong(leave.end_date)}`} + + {leave.reason} + + {leave.status} + + + {formatDateLong(leave.created_at.slice(0, 10))} + + + ))} + {myLeaves.length === 0 && ( + + + No leave requests yet. Use “Apply for leave” above. + + + )} + +
+
+
+ )} + + {canManage && ( + <> +
+ + l.status === 'approved').length} tone="success" /> + l.status === 'rejected').length} tone="danger" /> + +
+ + +
+
+

Pending approvals

+

+ {isAdmin() + ? 'Every class, newest first.' + : `Students in ${data.people.find((p) => p.id === profile?.id)?.class_teacher_of ?? 'your class'}.`} +

+
+ + {pendingInbox.length} waiting + +
+
+ + + + Student + Type + Dates + Reason + Actions + + + + {pendingInbox.map((leave) => { + const student = data.people.find((p) => p.id === leave.student_id); + return ( + + +
{student?.full_name ?? '—'}
+
+ {student?.class_label} {student?.section_label} · {student?.admission_no} +
+
+ {leave.leave_type} + + {formatDateLong(leave.start_date)} + {leave.end_date !== leave.start_date && ` → ${formatDateLong(leave.end_date)}`} +
+ {daysBetween(leave.start_date, leave.end_date) + 1} day + {daysBetween(leave.start_date, leave.end_date) === 0 ? '' : 's'} +
+
+ {leave.reason} + +
+ + +
+
+
+ ); + })} + {pendingInbox.length === 0 && ( + + + Nothing waiting for you. Every request is handled. + + + )} + +
+
+
+ + +
+

Decision history

+
+ {(['all', 'approved', 'rejected'] as const).map((key) => ( + + ))} +
+
+
+ + + + Student + Dates + Status + Reviewed by + + + + {history.map((leave) => { + const student = data.people.find((p) => p.id === leave.student_id); + const reviewer = data.people.find((p) => p.id === leave.reviewed_by); + return ( + + {student?.full_name ?? '—'} + + {formatDateLong(leave.start_date)} + {leave.end_date !== leave.start_date && ` → ${formatDateLong(leave.end_date)}`} + + + {leave.status} + + + {reviewer?.full_name ?? —} + + + ); + })} + {history.length === 0 && ( + + + No decisions recorded yet. + + + )} + +
+
+
+ + )} + + {open && ( +
+
+
+

Apply for leave

+ +
+
+
+ + +
+
+
+ + setForm({ ...form, start_date: e.target.value })} + className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" + /> +
+
+ + setForm({ ...form, end_date: e.target.value })} + className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" + /> +
+
+
+ +