tam chat
This commit is contained in:
@@ -4,9 +4,12 @@ import { ClassesTab } from './components/ClassesTab';
|
||||
import { StudentsTab } from './components/StudentsTab';
|
||||
import { LearningTab } from './components/LearningTab';
|
||||
import { NetworkTab } from './components/NetworkTab';
|
||||
import { AccountsTab } from './components/AccountsTab';
|
||||
import { ChatWidget } from './components/ChatWidget';
|
||||
import { ClassWorkspace } from './components/ClassWorkspace';
|
||||
import { NavHistoryBar, useRoute } from './components/NavHistoryBar';
|
||||
import { goBack, navigate, parseRoute, pushNav, TAB_LABELS, type TabId } from './navigation';
|
||||
import { useAuth } from './auth/AuthContext';
|
||||
|
||||
const IconDashboard = () => (
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
@@ -46,8 +49,16 @@ const IconNetwork = () => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
const IconAccounts = () => (
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
|
||||
<circle cx="12" cy="7" r="4" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
function App() {
|
||||
const route = useRoute();
|
||||
const { staff, logout } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
const initial = parseRoute();
|
||||
@@ -128,14 +139,27 @@ function App() {
|
||||
Quản lý mạng
|
||||
</button>
|
||||
</li>
|
||||
|
||||
<div className="nav-header">Hệ thống</div>
|
||||
<li className="nav-item">
|
||||
<button
|
||||
className={`nav-btn ${route.tab === 'accounts' && !route.classId ? 'active' : ''}`}
|
||||
onClick={() => navigate('accounts')}
|
||||
>
|
||||
<span className="nav-icon"><IconAccounts /></span>
|
||||
Tài khoản
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<div className="sidebar-footer">
|
||||
<div style={{ fontSize: '0.75rem', color: 'var(--text-muted)', fontWeight: 500 }}>Kết nối hệ thống</div>
|
||||
<div className="token-badge" title="Token QLDT_TOKEN load từ server .env">
|
||||
QLDT_TOKEN đã kết nối
|
||||
<div style={{ fontSize: '0.75rem', color: 'var(--text-muted)', fontWeight: 500 }}>
|
||||
{staff?.email}
|
||||
</div>
|
||||
<button type="button" className="link-btn" onClick={logout} style={{ marginTop: '0.35rem' }}>
|
||||
Đăng xuất
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
@@ -157,10 +181,12 @@ function App() {
|
||||
{route.tab === 'students' && <StudentsTab />}
|
||||
{route.tab === 'learning' && <LearningTab />}
|
||||
{route.tab === 'network' && <NetworkTab />}
|
||||
{route.tab === 'accounts' && <AccountsTab />}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
<ChatWidget />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,161 @@
|
||||
const API_BASE = 'http://127.0.0.1:8080/api';
|
||||
|
||||
function getToken(): string | null {
|
||||
return localStorage.getItem('sc_staff_token');
|
||||
}
|
||||
|
||||
async function staffFetch(path: string, init: RequestInit = {}): Promise<Response> {
|
||||
const headers = new Headers(init.headers);
|
||||
const token = getToken();
|
||||
if (token) headers.set('Authorization', `Bearer ${token}`);
|
||||
if (init.body && !headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
return fetch(`${API_BASE}${path}`, { ...init, headers });
|
||||
}
|
||||
|
||||
async function parseError(res: Response, fallback: string): Promise<never> {
|
||||
const errData = await res.json().catch(() => ({}));
|
||||
throw new Error((errData as { error?: string }).error || fallback);
|
||||
}
|
||||
|
||||
export interface StaffUser {
|
||||
id: number;
|
||||
email: string;
|
||||
fullName: string;
|
||||
mustChangePassword: boolean;
|
||||
}
|
||||
|
||||
export const apiAuth = {
|
||||
provision: async (email: string): Promise<{ ok: boolean; message: string }> => {
|
||||
const res = await fetch(`${API_BASE}/auth/provision`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email }),
|
||||
});
|
||||
if (!res.ok) await parseError(res, 'Provision failed');
|
||||
return res.json();
|
||||
},
|
||||
login: async (email: string, password: string): Promise<{ token: string; staff: StaffUser; mustChangePassword: boolean }> => {
|
||||
const res = await fetch(`${API_BASE}/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
if (!res.ok) await parseError(res, 'Đăng nhập thất bại');
|
||||
return res.json();
|
||||
},
|
||||
me: async (): Promise<{ staff: StaffUser }> => {
|
||||
const res = await staffFetch('/auth/me');
|
||||
if (!res.ok) await parseError(res, 'Unauthorized');
|
||||
return res.json();
|
||||
},
|
||||
changePassword: async (oldPassword: string, newPassword: string): Promise<{ ok: boolean; token: string; staff: StaffUser }> => {
|
||||
const res = await staffFetch('/auth/change-password', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ oldPassword, newPassword }),
|
||||
});
|
||||
if (!res.ok) await parseError(res, 'Đổi mật khẩu thất bại');
|
||||
return res.json();
|
||||
},
|
||||
forgotPassword: async (email: string): Promise<{ ok: boolean; message: string }> => {
|
||||
const res = await fetch(`${API_BASE}/auth/forgot-password`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email }),
|
||||
});
|
||||
if (!res.ok) await parseError(res, 'Gửi mail thất bại');
|
||||
return res.json();
|
||||
},
|
||||
resetPassword: async (token: string, newPassword: string): Promise<{ ok: boolean; message: string }> => {
|
||||
const res = await fetch(`${API_BASE}/auth/reset-password`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token, newPassword }),
|
||||
});
|
||||
if (!res.ok) await parseError(res, 'Đặt lại mật khẩu thất bại');
|
||||
return res.json();
|
||||
},
|
||||
};
|
||||
|
||||
export interface EmailDomainItem {
|
||||
id: number;
|
||||
domain: string;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
export const apiAdmin = {
|
||||
listEmailDomains: async (): Promise<{ data: EmailDomainItem[] }> => {
|
||||
const res = await staffFetch('/admin/email-domains');
|
||||
if (!res.ok) await parseError(res, 'Failed');
|
||||
return res.json();
|
||||
},
|
||||
addEmailDomain: async (domain: string) => {
|
||||
const res = await staffFetch('/admin/email-domains', { method: 'POST', body: JSON.stringify({ domain }) });
|
||||
if (!res.ok) await parseError(res, 'Failed');
|
||||
return res.json();
|
||||
},
|
||||
deleteEmailDomain: async (id: number) => {
|
||||
const res = await staffFetch(`/admin/email-domains/${id}`, { method: 'DELETE' });
|
||||
if (!res.ok) await parseError(res, 'Failed');
|
||||
return res.json();
|
||||
},
|
||||
};
|
||||
|
||||
export interface ChatStudent {
|
||||
studentRkId: number;
|
||||
fullName: string;
|
||||
studentCode: string;
|
||||
email: string;
|
||||
online: boolean;
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
id: number;
|
||||
staffId: number;
|
||||
studentRkId: number;
|
||||
senderRole: 'staff' | 'student';
|
||||
body: string;
|
||||
createdAt: string;
|
||||
staffName?: string;
|
||||
}
|
||||
|
||||
export interface ChatConversation {
|
||||
studentRkId: number;
|
||||
fullName: string;
|
||||
studentCode: string;
|
||||
lastMessage: string;
|
||||
lastAt: string;
|
||||
unread: number;
|
||||
}
|
||||
|
||||
export const apiChat = {
|
||||
listConversations: async (): Promise<{ data: ChatConversation[] }> => {
|
||||
const res = await staffFetch('/chat/conversations');
|
||||
if (!res.ok) await parseError(res, 'Failed');
|
||||
return res.json();
|
||||
},
|
||||
searchStudents: async (q = ''): Promise<{ data: ChatStudent[] }> => {
|
||||
const params = q ? `?q=${encodeURIComponent(q)}` : '';
|
||||
const res = await staffFetch(`/chat/students${params}`);
|
||||
if (!res.ok) await parseError(res, 'Failed');
|
||||
return res.json();
|
||||
},
|
||||
listMessages: async (studentRkId: number): Promise<{ data: ChatMessage[] }> => {
|
||||
const res = await staffFetch(`/chat/messages/${studentRkId}`);
|
||||
if (!res.ok) await parseError(res, 'Failed');
|
||||
return res.json();
|
||||
},
|
||||
sendMessage: async (studentRkId: number, body: string): Promise<{ ok: boolean; data: ChatMessage }> => {
|
||||
const res = await staffFetch('/chat/messages', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ studentRkId, body }),
|
||||
});
|
||||
if (!res.ok) await parseError(res, 'Failed');
|
||||
return res.json();
|
||||
},
|
||||
};
|
||||
|
||||
export interface ClassItem {
|
||||
rkId: number;
|
||||
name: string;
|
||||
@@ -125,7 +281,7 @@ export interface StudentSessionLogItem {
|
||||
|
||||
export const api = {
|
||||
getStats: async (): Promise<StatsResponse> => {
|
||||
const res = await fetch(`${API_BASE}/stats`);
|
||||
const res = await staffFetch('/stats');
|
||||
if (!res.ok) throw new Error('Failed to fetch dashboard stats');
|
||||
return res.json();
|
||||
},
|
||||
@@ -145,15 +301,14 @@ export const api = {
|
||||
if (params.systemRkId) query.set('systemRkId', String(params.systemRkId));
|
||||
if (params.studyingOnly) query.set('studyingOnly', 'true');
|
||||
|
||||
const res = await fetch(`${API_BASE}/classes?${query}`);
|
||||
const res = await staffFetch(`/classes?${query}`);
|
||||
if (!res.ok) throw new Error('Failed to fetch classes');
|
||||
return res.json();
|
||||
},
|
||||
|
||||
updateClassStudying: async (rkId: number, isStudying: boolean): Promise<any> => {
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/studying`, {
|
||||
const res = await staffFetch(`/classes/${rkId}/studying`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ isStudying }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
@@ -164,11 +319,17 @@ export const api = {
|
||||
},
|
||||
|
||||
getClassStudents: async (rkId: number): Promise<{ data: StudentItem[]; total: number }> => {
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/students`);
|
||||
const res = await staffFetch(`/classes/${rkId}/students`);
|
||||
if (!res.ok) throw new Error('Failed to fetch class students roster');
|
||||
return res.json();
|
||||
},
|
||||
|
||||
getClass: async (rkId: number): Promise<ClassItem> => {
|
||||
const res = await staffFetch(`/classes/${rkId}`);
|
||||
if (!res.ok) throw new Error('Failed to fetch class');
|
||||
return res.json();
|
||||
},
|
||||
|
||||
getStudents: async (params: {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
@@ -180,13 +341,13 @@ export const api = {
|
||||
});
|
||||
if (params.q) query.set('q', params.q);
|
||||
|
||||
const res = await fetch(`${API_BASE}/students?${query}`);
|
||||
const res = await staffFetch(`/students?${query}`);
|
||||
if (!res.ok) throw new Error('Failed to fetch students');
|
||||
return res.json();
|
||||
},
|
||||
|
||||
startClassesSync: async (): Promise<{ ok: boolean; message: string }> => {
|
||||
const res = await fetch(`${API_BASE}/sync/classes/start`, { method: 'POST' });
|
||||
const res = await staffFetch('/sync/classes/start', { method: 'POST' });
|
||||
if (!res.ok) {
|
||||
const errData = await res.json().catch(() => ({}));
|
||||
throw new Error(errData.error || 'Failed to start classes sync');
|
||||
@@ -195,13 +356,13 @@ export const api = {
|
||||
},
|
||||
|
||||
getClassesSyncStatus: async (): Promise<SyncStatus> => {
|
||||
const res = await fetch(`${API_BASE}/sync/classes/status`);
|
||||
const res = await staffFetch('/sync/classes/status');
|
||||
if (!res.ok) throw new Error('Failed to get classes sync status');
|
||||
return res.json();
|
||||
},
|
||||
|
||||
startStudentsSync: async (): Promise<{ ok: boolean; message: string }> => {
|
||||
const res = await fetch(`${API_BASE}/sync/students/start`, { method: 'POST' });
|
||||
const res = await staffFetch('/sync/students/start', { method: 'POST' });
|
||||
if (!res.ok) {
|
||||
const errData = await res.json().catch(() => ({}));
|
||||
throw new Error(errData.error || 'Failed to start students sync');
|
||||
@@ -210,7 +371,7 @@ export const api = {
|
||||
},
|
||||
|
||||
getStudentsSyncStatus: async (): Promise<SyncStatus> => {
|
||||
const res = await fetch(`${API_BASE}/sync/students/status`);
|
||||
const res = await staffFetch('/sync/students/status');
|
||||
if (!res.ok) throw new Error('Failed to get students sync status');
|
||||
return res.json();
|
||||
},
|
||||
@@ -218,21 +379,20 @@ export const api = {
|
||||
|
||||
// Export individual learning functions to simplify imports in components
|
||||
export const apiFetchActiveSchedules = async (): Promise<{ data: any[] }> => {
|
||||
const res = await fetch(`${API_BASE}/classes/schedules`);
|
||||
const res = await staffFetch('/classes/schedules');
|
||||
if (!res.ok) throw new Error('Failed to fetch active schedules');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const apiFetchClassSchedule = async (rkId: number): Promise<{ data: ClassScheduleItem[] }> => {
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/schedule`);
|
||||
const res = await staffFetch(`/classes/${rkId}/schedule`);
|
||||
if (!res.ok) throw new Error('Failed to fetch class schedule');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const apiSaveClassSchedule = async (rkId: number, schedules: ClassScheduleItem[]): Promise<any> => {
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/schedule`, {
|
||||
const res = await staffFetch(`/classes/${rkId}/schedule`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ schedules }),
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to save class schedule');
|
||||
@@ -240,21 +400,20 @@ export const apiSaveClassSchedule = async (rkId: number, schedules: ClassSchedul
|
||||
};
|
||||
|
||||
export const apiDeleteClassSchedule = async (rkId: number): Promise<any> => {
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/schedule`, { method: 'DELETE' });
|
||||
const res = await staffFetch(`/classes/${rkId}/schedule`, { method: 'DELETE' });
|
||||
if (!res.ok) throw new Error('Failed to delete class schedule');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const apiFetchAllowedApps = async (rkId: number): Promise<{ classRkId: number; keywords: string }> => {
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/allowed-apps`);
|
||||
const res = await staffFetch(`/classes/${rkId}/allowed-apps`);
|
||||
if (!res.ok) throw new Error('Failed to fetch allowed apps keywords');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const apiSaveAllowedApps = async (rkId: number, keywords: string): Promise<any> => {
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/allowed-apps`, {
|
||||
const res = await staffFetch(`/classes/${rkId}/allowed-apps`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ keywords }),
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to save allowed apps keywords');
|
||||
@@ -277,7 +436,7 @@ export const apiFetchAppPool = async (q = '', limit = 50): Promise<{ data: AppPo
|
||||
if (q.trim()) params.set('q', q.trim());
|
||||
params.set('limit', String(limit));
|
||||
const query = params.toString() ? `?${params.toString()}` : '';
|
||||
const res = await fetch(`${API_BASE}/app-pool${query}`);
|
||||
const res = await staffFetch(`/app-pool${query}`);
|
||||
if (!res.ok) throw new Error('Failed to fetch app pool');
|
||||
return res.json();
|
||||
};
|
||||
@@ -305,21 +464,20 @@ export const apiFetchWifiPool = async (q = '', limit = 50): Promise<{ data: Wifi
|
||||
if (q.trim()) params.set('q', q.trim());
|
||||
params.set('limit', String(limit));
|
||||
const query = params.toString() ? `?${params.toString()}` : '';
|
||||
const res = await fetch(`${API_BASE}/wifi-pool${query}`);
|
||||
const res = await staffFetch(`/wifi-pool${query}`);
|
||||
if (!res.ok) throw new Error('Failed to fetch wifi pool');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const apiFetchAcceptedWifis = async (): Promise<{ data: AcceptedWifiItem[] }> => {
|
||||
const res = await fetch(`${API_BASE}/network/accepted-wifis`);
|
||||
const res = await staffFetch('/network/accepted-wifis');
|
||||
if (!res.ok) throw new Error('Failed to fetch accepted wifis');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const apiSaveAcceptedWifis = async (items: WifiAcceptItem[]): Promise<any> => {
|
||||
const res = await fetch(`${API_BASE}/network/accepted-wifis`, {
|
||||
const res = await staffFetch('/network/accepted-wifis', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ items }),
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to save accepted wifis');
|
||||
@@ -338,13 +496,13 @@ export const apiFetchClassSessionLogs = async (
|
||||
if (date) params.set('date', date);
|
||||
if (period) params.set('period', String(period));
|
||||
const query = params.toString() ? `?${params.toString()}` : '';
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/session-logs${query}`);
|
||||
const res = await staffFetch(`/classes/${rkId}/session-logs${query}`);
|
||||
if (!res.ok) throw new Error('Failed to fetch class session logs');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const apiFetchOnlineStudents = async (rkId: number): Promise<{ onlineStudentIds: number[] }> => {
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/online-students`);
|
||||
const res = await staffFetch(`/classes/${rkId}/online-students`);
|
||||
if (!res.ok) throw new Error('Failed to fetch online students list');
|
||||
return res.json();
|
||||
};
|
||||
@@ -356,7 +514,7 @@ export const apiFetchClassCourses = async (rkId: number): Promise<{
|
||||
warning?: string;
|
||||
hint?: string;
|
||||
}> => {
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/courses`);
|
||||
const res = await staffFetch(`/classes/${rkId}/courses`);
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
throw new Error(body.error || body.hint || 'Không tải được danh sách môn học từ QLĐT');
|
||||
@@ -365,20 +523,20 @@ export const apiFetchClassCourses = async (rkId: number): Promise<{
|
||||
};
|
||||
|
||||
export const apiApplyScheduleTemplate = async (rkId: number): Promise<{ created: number; skipped: number }> => {
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/schedule/apply-template`, { method: 'POST' });
|
||||
const res = await staffFetch(`/classes/${rkId}/schedule/apply-template`, { method: 'POST' });
|
||||
if (!res.ok) throw new Error('Failed to apply schedule template');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const apiFetchAttendanceShifts = async (rkId: number, date?: string) => {
|
||||
const q = date ? `?date=${date}` : '';
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/attendance/shifts${q}`);
|
||||
const res = await staffFetch(`/classes/${rkId}/attendance/shifts${q}`);
|
||||
if (!res.ok) throw new Error('Failed to fetch attendance shifts');
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const apiFetchAttendance = async (rkId: number, date: string, period: number) => {
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/attendance?date=${date}&period=${period}`);
|
||||
const res = await staffFetch(`/classes/${rkId}/attendance?date=${date}&period=${period}`);
|
||||
if (!res.ok) throw new Error('Failed to fetch attendance');
|
||||
return res.json();
|
||||
};
|
||||
@@ -387,9 +545,8 @@ export const apiUpdateAttendanceStatus = async (
|
||||
rkId: number,
|
||||
payload: { date: string; period: number; studentRkId: number; status: number }
|
||||
) => {
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/attendance/status`, {
|
||||
const res = await staffFetch(`/classes/${rkId}/attendance/status`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
@@ -400,9 +557,8 @@ export const apiUpdateAttendanceStatus = async (
|
||||
};
|
||||
|
||||
export const apiPushAttendanceQLDT = async (rkId: number, date: string, period: number) => {
|
||||
const res = await fetch(`${API_BASE}/classes/${rkId}/attendance/push-qldt`, {
|
||||
const res = await staffFetch(`/classes/${rkId}/attendance/push-qldt`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ date, period }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
|
||||
114
management/src/auth/AuthContext.tsx
Normal file
114
management/src/auth/AuthContext.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import { apiAuth } from '../api';
|
||||
|
||||
export interface StaffUser {
|
||||
id: number;
|
||||
email: string;
|
||||
fullName: string;
|
||||
mustChangePassword: boolean;
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
token: string | null;
|
||||
staff: StaffUser | null;
|
||||
loading: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
provision: (email: string) => Promise<string>;
|
||||
logout: () => void;
|
||||
changePassword: (oldPassword: string, newPassword: string) => Promise<void>;
|
||||
forgotPassword: (email: string) => Promise<string>;
|
||||
resetPassword: (token: string, newPassword: string) => Promise<void>;
|
||||
refreshMe: () => Promise<void>;
|
||||
}
|
||||
|
||||
const TOKEN_KEY = 'sc_staff_token';
|
||||
const AuthContext = createContext<AuthState | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [token, setToken] = useState<string | null>(() => localStorage.getItem(TOKEN_KEY));
|
||||
const [staff, setStaff] = useState<StaffUser | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const applySession = useCallback((nextToken: string | null, nextStaff: StaffUser | null) => {
|
||||
setToken(nextToken);
|
||||
setStaff(nextStaff);
|
||||
if (nextToken) {
|
||||
localStorage.setItem(TOKEN_KEY, nextToken);
|
||||
} else {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const refreshMe = useCallback(async () => {
|
||||
if (!token) {
|
||||
setStaff(null);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await apiAuth.me();
|
||||
setStaff(res.staff);
|
||||
} catch {
|
||||
applySession(null, null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [token, applySession]);
|
||||
|
||||
useEffect(() => {
|
||||
refreshMe();
|
||||
}, [refreshMe]);
|
||||
|
||||
const login = useCallback(async (email: string, password: string) => {
|
||||
const res = await apiAuth.login(email, password);
|
||||
applySession(res.token, res.staff);
|
||||
}, [applySession]);
|
||||
|
||||
const provision = useCallback(async (email: string) => {
|
||||
const res = await apiAuth.provision(email);
|
||||
return res.message;
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
applySession(null, null);
|
||||
}, [applySession]);
|
||||
|
||||
const changePassword = useCallback(async (oldPassword: string, newPassword: string) => {
|
||||
const res = await apiAuth.changePassword(oldPassword, newPassword);
|
||||
applySession(res.token, res.staff);
|
||||
}, [applySession]);
|
||||
|
||||
const forgotPassword = useCallback(async (email: string) => {
|
||||
const res = await apiAuth.forgotPassword(email);
|
||||
return res.message;
|
||||
}, []);
|
||||
|
||||
const resetPassword = useCallback(async (resetToken: string, newPassword: string) => {
|
||||
await apiAuth.resetPassword(resetToken, newPassword);
|
||||
}, []);
|
||||
|
||||
const value = useMemo<AuthState>(() => ({
|
||||
token,
|
||||
staff,
|
||||
loading,
|
||||
login,
|
||||
provision,
|
||||
logout,
|
||||
changePassword,
|
||||
forgotPassword,
|
||||
resetPassword,
|
||||
refreshMe,
|
||||
}), [token, staff, loading, login, provision, logout, changePassword, forgotPassword, resetPassword, refreshMe]);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export function getStoredToken(): string | null {
|
||||
return localStorage.getItem(TOKEN_KEY);
|
||||
}
|
||||
167
management/src/components/AccountsTab.tsx
Normal file
167
management/src/components/AccountsTab.tsx
Normal file
@@ -0,0 +1,167 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useAuth } from '../auth/AuthContext';
|
||||
import { apiAdmin, type EmailDomainItem } from '../api';
|
||||
|
||||
export function ChangePasswordPage({ forced }: { forced?: boolean }) {
|
||||
const { changePassword, logout } = useAuth();
|
||||
const [oldPassword, setOldPassword] = useState('');
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [confirm, setConfirm] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
if (newPassword.length < 8) {
|
||||
setError('Mật khẩu mới tối thiểu 8 ký tự');
|
||||
return;
|
||||
}
|
||||
if (newPassword !== confirm) {
|
||||
setError('Xác nhận mật khẩu không khớp');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await changePassword(oldPassword, newPassword);
|
||||
} catch (err: any) {
|
||||
setError(err?.message || 'Đổi mật khẩu thất bại');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="login-screen">
|
||||
<div className="login-card">
|
||||
<h1 className="login-heading">{forced ? 'Đổi mật khẩu bắt buộc' : 'Đổi mật khẩu'}</h1>
|
||||
{forced && <p className="login-hint">Lần đăng nhập đầu tiên — vui lòng đặt mật khẩu mới trước khi tiếp tục.</p>}
|
||||
<form onSubmit={submit} className="login-form">
|
||||
<label className="login-field">
|
||||
<span>Mật khẩu hiện tại</span>
|
||||
<input type="password" value={oldPassword} onChange={(e) => setOldPassword(e.target.value)} required />
|
||||
</label>
|
||||
<label className="login-field">
|
||||
<span>Mật khẩu mới</span>
|
||||
<input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} required minLength={8} />
|
||||
</label>
|
||||
<label className="login-field">
|
||||
<span>Xác nhận mật khẩu mới</span>
|
||||
<input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)} required minLength={8} />
|
||||
</label>
|
||||
{error && <div className="login-error">{error}</div>}
|
||||
<button type="submit" className="btn btn-primary login-submit" disabled={busy}>
|
||||
{busy ? 'Đang lưu...' : 'Lưu mật khẩu'}
|
||||
</button>
|
||||
{!forced && (
|
||||
<button type="button" className="link-btn" style={{ marginTop: '0.5rem' }} onClick={logout}>
|
||||
Đăng xuất
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AccountsTab() {
|
||||
const { staff, changePassword } = useAuth();
|
||||
const [domains, setDomains] = useState<EmailDomainItem[]>([]);
|
||||
const [newDomain, setNewDomain] = useState('');
|
||||
const [oldPw, setOldPw] = useState('');
|
||||
const [newPw, setNewPw] = useState('');
|
||||
const [msg, setMsg] = useState('');
|
||||
const [err, setErr] = useState('');
|
||||
|
||||
const load = async () => {
|
||||
const res = await apiAdmin.listEmailDomains();
|
||||
setDomains(res.data);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
load().catch(console.error);
|
||||
}, []);
|
||||
|
||||
const addDomain = async () => {
|
||||
if (!newDomain.trim()) return;
|
||||
await apiAdmin.addEmailDomain(newDomain.trim());
|
||||
setNewDomain('');
|
||||
await load();
|
||||
};
|
||||
|
||||
const removeDomain = async (id: number) => {
|
||||
if (!confirm('Xóa đuôi email này?')) return;
|
||||
await apiAdmin.deleteEmailDomain(id);
|
||||
await load();
|
||||
};
|
||||
|
||||
const submitPw = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setErr('');
|
||||
setMsg('');
|
||||
try {
|
||||
await changePassword(oldPw, newPw);
|
||||
setMsg('Đã đổi mật khẩu');
|
||||
setOldPw('');
|
||||
setNewPw('');
|
||||
} catch (e: any) {
|
||||
setErr(e?.message || 'Lỗi');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-stack">
|
||||
<header className="page-header">
|
||||
<h1 className="page-title">Tài khoản & bảo mật</h1>
|
||||
<p className="page-desc">Quản lý đuôi email được phép và đổi mật khẩu.</p>
|
||||
</header>
|
||||
|
||||
<div className="card" style={{ padding: '1.25rem' }}>
|
||||
<h2 className="section-title">Tài khoản hiện tại</h2>
|
||||
<p style={{ margin: 0, color: 'var(--text-muted)' }}>{staff?.email}</p>
|
||||
</div>
|
||||
|
||||
<div className="card" style={{ padding: '1.25rem' }}>
|
||||
<h2 className="section-title">Đuôi email được phép</h2>
|
||||
<p className="page-desc" style={{ marginTop: 0 }}>
|
||||
Nếu chưa có bản ghi nào, hệ thống chấp nhận mọi đuôi email. Thêm đuôi để giới hạn truy cập.
|
||||
</p>
|
||||
<div style={{ display: 'flex', gap: '0.5rem', marginBottom: '1rem' }}>
|
||||
<input
|
||||
placeholder="vd: rikkeiacademy.com"
|
||||
value={newDomain}
|
||||
onChange={(e) => setNewDomain(e.target.value)}
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
<button type="button" className="btn btn-primary" onClick={addDomain}>Thêm</button>
|
||||
</div>
|
||||
<ul className="domain-list">
|
||||
{domains.length === 0 && <li className="domain-empty">Chưa cấu hình — chấp nhận tất cả đuôi email</li>}
|
||||
{domains.map((d) => (
|
||||
<li key={d.id} className="domain-item">
|
||||
<span>@{d.domain}</span>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => removeDomain(d.id)}>Xóa</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="card" style={{ padding: '1.25rem' }}>
|
||||
<h2 className="section-title">Đổi mật khẩu</h2>
|
||||
<form onSubmit={submitPw} className="login-form" style={{ maxWidth: 400 }}>
|
||||
<label className="login-field">
|
||||
<span>Mật khẩu hiện tại</span>
|
||||
<input type="password" value={oldPw} onChange={(e) => setOldPw(e.target.value)} required />
|
||||
</label>
|
||||
<label className="login-field">
|
||||
<span>Mật khẩu mới</span>
|
||||
<input type="password" value={newPw} onChange={(e) => setNewPw(e.target.value)} required minLength={8} />
|
||||
</label>
|
||||
{err && <div className="login-error">{err}</div>}
|
||||
{msg && <div className="login-success">{msg}</div>}
|
||||
<button type="submit" className="btn btn-primary">Lưu</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
231
management/src/components/ChatWidget.tsx
Normal file
231
management/src/components/ChatWidget.tsx
Normal file
@@ -0,0 +1,231 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { apiChat, type ChatConversation, type ChatMessage, type ChatStudent } from '../api';
|
||||
import { useAuth } from '../auth/AuthContext';
|
||||
|
||||
export function ChatWidget() {
|
||||
const { staff } = useAuth();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [query, setQuery] = useState('');
|
||||
const [students, setStudents] = useState<ChatStudent[]>([]);
|
||||
const [conversations, setConversations] = useState<ChatConversation[]>([]);
|
||||
const [active, setActive] = useState<ChatStudent | null>(null);
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [draft, setDraft] = useState('');
|
||||
const [sending, setSending] = useState(false);
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const activeRef = useRef<ChatStudent | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
activeRef.current = active;
|
||||
}, [active]);
|
||||
|
||||
const scrollBottom = () => {
|
||||
requestAnimationFrame(() => {
|
||||
if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
|
||||
});
|
||||
};
|
||||
|
||||
const totalUnread = conversations.reduce((n, c) => n + (c.unread || 0), 0);
|
||||
|
||||
const loadConversations = useCallback(async () => {
|
||||
const res = await apiChat.listConversations();
|
||||
setConversations(res.data);
|
||||
}, []);
|
||||
|
||||
const loadMessages = useCallback(async (studentRkId: number) => {
|
||||
const res = await apiChat.listMessages(studentRkId);
|
||||
setMessages(res.data);
|
||||
scrollBottom();
|
||||
await loadConversations();
|
||||
}, [loadConversations]);
|
||||
|
||||
const searchStudents = useCallback(async (q: string) => {
|
||||
const res = await apiChat.searchStudents(q);
|
||||
setStudents(res.data);
|
||||
}, []);
|
||||
|
||||
const pickStudent = async (s: ChatStudent) => {
|
||||
setActive(s);
|
||||
setPickerOpen(false);
|
||||
setQuery('');
|
||||
await loadMessages(s.studentRkId);
|
||||
};
|
||||
|
||||
const pickFromConversation = async (c: ChatConversation) => {
|
||||
await pickStudent({
|
||||
studentRkId: c.studentRkId,
|
||||
fullName: c.fullName,
|
||||
studentCode: c.studentCode,
|
||||
email: '',
|
||||
online: false,
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !staff?.id) return;
|
||||
loadConversations().catch(console.error);
|
||||
searchStudents('').catch(console.error);
|
||||
}, [open, staff?.id, loadConversations, searchStudents]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!staff?.id) return;
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const wsUrl = `${protocol}//${window.location.hostname}:8080/ws?role=teacher&staffId=${staff.id}`;
|
||||
const ws = new WebSocket(wsUrl);
|
||||
ws.onmessage = (ev) => {
|
||||
try {
|
||||
const payload = JSON.parse(ev.data);
|
||||
if (payload.event !== 'chat:message') return;
|
||||
const msg = payload.data as ChatMessage;
|
||||
loadConversations().catch(console.error);
|
||||
const current = activeRef.current;
|
||||
if (current && msg.studentRkId === current.studentRkId) {
|
||||
setMessages((prev) => {
|
||||
if (prev.some((m) => m.id === msg.id)) return prev;
|
||||
return [...prev, msg];
|
||||
});
|
||||
scrollBottom();
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
return () => ws.close();
|
||||
}, [staff?.id, loadConversations]);
|
||||
|
||||
const send = async () => {
|
||||
if (!active || !draft.trim()) return;
|
||||
setSending(true);
|
||||
try {
|
||||
const res = await apiChat.sendMessage(active.studentRkId, draft.trim());
|
||||
setMessages((prev) => [...prev, res.data]);
|
||||
setDraft('');
|
||||
scrollBottom();
|
||||
await loadConversations();
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!staff) return null;
|
||||
|
||||
const dock = (
|
||||
<div className="chat-dock">
|
||||
{!open ? (
|
||||
<button type="button" className="chat-fab" onClick={() => setOpen(true)} title="Tin nhắn">
|
||||
💬
|
||||
{totalUnread > 0 && (
|
||||
<span className="chat-fab-badge">{totalUnread > 9 ? '9+' : totalUnread}</span>
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<div className="chat-messenger">
|
||||
<header className="chat-messenger-head">
|
||||
<strong>Tin nhắn</strong>
|
||||
<div className="chat-head-actions">
|
||||
<button type="button" className="chat-icon-btn" onClick={() => setPickerOpen((v) => !v)} title="Tin mới">
|
||||
✏️
|
||||
</button>
|
||||
<button type="button" className="chat-icon-btn" onClick={() => { setOpen(false); setActive(null); setPickerOpen(false); }} title="Đóng">
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="chat-messenger-body">
|
||||
<aside className="chat-sidebar">
|
||||
<div className="chat-sidebar-search">
|
||||
<input
|
||||
placeholder="Tìm sinh viên..."
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
searchStudents(e.target.value).catch(console.error);
|
||||
}}
|
||||
onFocus={() => setPickerOpen(true)}
|
||||
/>
|
||||
</div>
|
||||
{pickerOpen && (
|
||||
<ul className="chat-picker-list">
|
||||
{students.map((s) => (
|
||||
<li key={s.studentRkId}>
|
||||
<button type="button" onClick={() => pickStudent(s)}>
|
||||
<span className="chat-conv-name">{s.fullName}</span>
|
||||
<span className="chat-conv-meta">{s.studentCode}{s.online ? ' · online' : ''}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{students.length === 0 && <li className="chat-empty-hint">Không tìm thấy sinh viên</li>}
|
||||
</ul>
|
||||
)}
|
||||
<ul className="chat-conv-list">
|
||||
{conversations.map((c) => (
|
||||
<li key={c.studentRkId}>
|
||||
<button
|
||||
type="button"
|
||||
className={active?.studentRkId === c.studentRkId ? 'active' : ''}
|
||||
onClick={() => pickFromConversation(c)}
|
||||
>
|
||||
<div className="chat-conv-row">
|
||||
<span className="chat-conv-name">{c.fullName}</span>
|
||||
{c.unread > 0 && <span className="chat-conv-unread">{c.unread}</span>}
|
||||
</div>
|
||||
<span className="chat-conv-preview">{c.lastMessage || '—'}</span>
|
||||
<span className="chat-conv-meta">{c.studentCode}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{conversations.length === 0 && !pickerOpen && (
|
||||
<li className="chat-empty-hint">Chưa có hội thoại — bấm ✏️ để nhắn sinh viên</li>
|
||||
)}
|
||||
</ul>
|
||||
</aside>
|
||||
|
||||
<section className="chat-thread">
|
||||
{!active ? (
|
||||
<div className="chat-thread-empty">
|
||||
<p>Chọn hội thoại bên trái hoặc tìm sinh viên để bắt đầu chat</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="chat-thread-head">
|
||||
<div>
|
||||
<strong>{active.fullName}</strong>
|
||||
<div className="chat-sub">{active.studentCode}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="chat-messages" ref={listRef}>
|
||||
{messages.map((m) => (
|
||||
<div key={m.id} className={`chat-bubble chat-bubble--${m.senderRole}`}>
|
||||
<div className="chat-bubble-body">{m.body}</div>
|
||||
<div className="chat-bubble-time">
|
||||
{new Date(m.createdAt).toLocaleString('vi-VN', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{messages.length === 0 && <div className="chat-empty-hint">Chưa có tin nhắn</div>}
|
||||
</div>
|
||||
<div className="chat-compose">
|
||||
<input
|
||||
placeholder="Nhập tin nhắn..."
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
|
||||
/>
|
||||
<button type="button" className="btn btn-primary btn-sm" disabled={sending || !draft.trim()} onClick={send}>
|
||||
Gửi
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
return createPortal(dock, document.body);
|
||||
}
|
||||
@@ -58,17 +58,14 @@ export const ClassWorkspace: React.FC<ClassWorkspaceProps> = ({ classId, sourceT
|
||||
setLoading(true);
|
||||
|
||||
// Fetch specific class detail directly
|
||||
const targetClassRes = await fetch(`http://127.0.0.1:8080/api/classes/${classId}`);
|
||||
if (targetClassRes.ok) {
|
||||
const classData = await targetClassRes.json();
|
||||
setClassInfo(classData);
|
||||
pushNav({
|
||||
kind: 'class',
|
||||
tab: sourceTab,
|
||||
classId,
|
||||
label: classData.name || `Lớp ${classId}`,
|
||||
});
|
||||
}
|
||||
const classData = await api.getClass(classId);
|
||||
setClassInfo(classData);
|
||||
pushNav({
|
||||
kind: 'class',
|
||||
tab: sourceTab,
|
||||
classId,
|
||||
label: classData.name || `Lớp ${classId}`,
|
||||
});
|
||||
|
||||
// Fetch students roster
|
||||
const studentsRes = await apiFetchClassStudents(classId);
|
||||
|
||||
114
management/src/components/LoginPage.tsx
Normal file
114
management/src/components/LoginPage.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
import { useState } from 'react';
|
||||
import { useAuth } from '../auth/AuthContext';
|
||||
|
||||
type Mode = 'login' | 'provision' | 'forgot' | 'reset';
|
||||
|
||||
export function LoginPage() {
|
||||
const { login, provision, forgotPassword, resetPassword } = useAuth();
|
||||
const [mode, setMode] = useState<Mode>('login');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [resetToken, setResetToken] = useState('');
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [message, setMessage] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const submit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setMessage('');
|
||||
setBusy(true);
|
||||
try {
|
||||
if (mode === 'login') {
|
||||
await login(email, password);
|
||||
} else if (mode === 'provision') {
|
||||
const msg = await provision(email);
|
||||
setMessage(msg);
|
||||
setMode('login');
|
||||
} else if (mode === 'forgot') {
|
||||
const msg = await forgotPassword(email);
|
||||
setMessage(msg);
|
||||
setMode('reset');
|
||||
} else if (mode === 'reset') {
|
||||
await resetPassword(resetToken, newPassword);
|
||||
setMessage('Đã đặt lại mật khẩu. Vui lòng đăng nhập.');
|
||||
setMode('login');
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err?.message || 'Có lỗi xảy ra');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="login-screen">
|
||||
<div className="login-card">
|
||||
<div className="login-brand">
|
||||
<img src="/logo.jpeg" alt="Simple Care" className="brand-logo-img" />
|
||||
<div>
|
||||
<div className="login-brand-title">Simple Care</div>
|
||||
<div className="login-brand-sub">Quản lý giám sát — Rikkei Education</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h1 className="login-heading">
|
||||
{mode === 'login' && 'Đăng nhập'}
|
||||
{mode === 'provision' && 'Truy cập lần đầu'}
|
||||
{mode === 'forgot' && 'Quên mật khẩu'}
|
||||
{mode === 'reset' && 'Đặt lại mật khẩu'}
|
||||
</h1>
|
||||
<p className="login-hint">
|
||||
{mode === 'provision'
|
||||
? 'Nhập email tổ chức. Hệ thống gửi mật khẩu tạm nếu đuôi email được phép.'
|
||||
: 'Chỉ email có đuôi tổ chức được phép truy cập.'}
|
||||
</p>
|
||||
|
||||
<form onSubmit={submit} className="login-form">
|
||||
{(mode === 'login' || mode === 'provision' || mode === 'forgot') && (
|
||||
<label className="login-field">
|
||||
<span>Email</span>
|
||||
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required autoComplete="email" />
|
||||
</label>
|
||||
)}
|
||||
{mode === 'login' && (
|
||||
<label className="login-field">
|
||||
<span>Mật khẩu</span>
|
||||
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required autoComplete="current-password" />
|
||||
</label>
|
||||
)}
|
||||
{mode === 'reset' && (
|
||||
<>
|
||||
<label className="login-field">
|
||||
<span>Mã từ email</span>
|
||||
<input value={resetToken} onChange={(e) => setResetToken(e.target.value)} required />
|
||||
</label>
|
||||
<label className="login-field">
|
||||
<span>Mật khẩu mới</span>
|
||||
<input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} required minLength={8} />
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
{error && <div className="login-error">{error}</div>}
|
||||
{message && <div className="login-success">{message}</div>}
|
||||
<button type="submit" className="btn btn-primary login-submit" disabled={busy}>
|
||||
{busy ? 'Đang xử lý...' : mode === 'login' ? 'Đăng nhập' : mode === 'provision' ? 'Gửi mật khẩu' : mode === 'forgot' ? 'Gửi mã' : 'Đặt lại mật khẩu'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="login-links">
|
||||
{mode === 'login' && (
|
||||
<>
|
||||
<button type="button" className="link-btn" onClick={() => setMode('provision')}>Truy cập lần đầu</button>
|
||||
<button type="button" className="link-btn" onClick={() => setMode('forgot')}>Quên mật khẩu?</button>
|
||||
</>
|
||||
)}
|
||||
{mode !== 'login' && (
|
||||
<button type="button" className="link-btn" onClick={() => setMode('login')}>← Quay lại đăng nhập</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3233,3 +3233,427 @@ input:checked + .slider:before {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Login ── */
|
||||
.auth-shell {
|
||||
width: 100%;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1.5rem;
|
||||
background: var(--bg-app);
|
||||
}
|
||||
|
||||
.login-screen {
|
||||
width: 100%;
|
||||
max-width: 440px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.login-card {
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
padding: 1.75rem;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: var(--shadow-lg);
|
||||
}
|
||||
|
||||
.login-brand {
|
||||
display: flex;
|
||||
gap: 0.85rem;
|
||||
align-items: center;
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
.login-brand-title {
|
||||
font-weight: 800;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.login-brand-sub {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.login-heading {
|
||||
margin: 0 0 0.35rem;
|
||||
font-size: 1.35rem;
|
||||
}
|
||||
|
||||
.login-hint {
|
||||
margin: 0 0 1rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.login-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.login-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.login-field input {
|
||||
padding: 0.55rem 0.65rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-color);
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.login-submit {
|
||||
width: 100%;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
.login-error {
|
||||
color: #ef4444;
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.login-success {
|
||||
color: #22c55e;
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.login-links {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.link-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--accent);
|
||||
cursor: pointer;
|
||||
font-size: 0.82rem;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.domain-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.domain-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.5rem 0;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.domain-empty {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.85rem;
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
|
||||
/* ── Chat messenger dock ── */
|
||||
.chat-dock {
|
||||
position: fixed;
|
||||
right: 20px;
|
||||
bottom: 20px;
|
||||
z-index: 10000;
|
||||
font-family: var(--font-sans);
|
||||
}
|
||||
|
||||
.chat-fab {
|
||||
position: relative;
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
border-radius: 50%;
|
||||
border: none;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
font-size: 1.4rem;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 8px 28px rgba(0, 0, 0, 0.22);
|
||||
}
|
||||
|
||||
.chat-fab-badge {
|
||||
position: absolute;
|
||||
top: -4px;
|
||||
right: -4px;
|
||||
min-width: 18px;
|
||||
height: 18px;
|
||||
padding: 0 5px;
|
||||
border-radius: 9px;
|
||||
background: #ef4444;
|
||||
color: #fff;
|
||||
font-size: 0.65rem;
|
||||
font-weight: 700;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.chat-messenger {
|
||||
width: min(720px, calc(100vw - 40px));
|
||||
height: min(520px, calc(100vh - 100px));
|
||||
background: #fff;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 14px;
|
||||
box-shadow: 0 16px 48px rgba(0, 0, 0, 0.2);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.chat-messenger-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0.75rem 1rem;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
background: #fff;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.chat-messenger-body {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.chat-sidebar {
|
||||
width: 260px;
|
||||
flex-shrink: 0;
|
||||
border-right: 1px solid var(--border-color);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.chat-sidebar-search {
|
||||
padding: 0.6rem;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.chat-sidebar-search input {
|
||||
width: 100%;
|
||||
padding: 0.5rem 0.65rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-color);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.chat-picker-list,
|
||||
.chat-conv-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.chat-picker-list {
|
||||
max-height: 160px;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.chat-conv-list {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.chat-picker-list button,
|
||||
.chat-conv-list button {
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 0.65rem 0.75rem;
|
||||
cursor: pointer;
|
||||
border-bottom: 1px solid var(--border-light);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.chat-conv-list button:hover,
|
||||
.chat-picker-list button:hover {
|
||||
background: #eef2f7;
|
||||
}
|
||||
|
||||
.chat-conv-list button.active {
|
||||
background: var(--accent-light);
|
||||
border-left: 3px solid var(--accent);
|
||||
}
|
||||
|
||||
.chat-conv-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.chat-conv-name {
|
||||
font-size: 0.84rem;
|
||||
font-weight: 600;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.chat-conv-preview {
|
||||
display: block;
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
margin-top: 0.15rem;
|
||||
}
|
||||
|
||||
.chat-conv-meta {
|
||||
font-size: 0.68rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.chat-conv-unread {
|
||||
min-width: 18px;
|
||||
height: 18px;
|
||||
padding: 0 5px;
|
||||
border-radius: 9px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
font-size: 0.62rem;
|
||||
font-weight: 700;
|
||||
line-height: 18px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.chat-empty-hint {
|
||||
padding: 1rem 0.75rem;
|
||||
font-size: 0.78rem;
|
||||
color: var(--text-muted);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.chat-thread {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.chat-thread-empty {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1.5rem;
|
||||
color: var(--text-muted);
|
||||
font-size: 0.85rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.chat-thread-head {
|
||||
padding: 0.65rem 1rem;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
background: #fff;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.chat-sub {
|
||||
font-size: 0.72rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.chat-head-actions {
|
||||
display: flex;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.chat-icon-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.chat-icon-btn:hover {
|
||||
background: var(--bg-subtle);
|
||||
}
|
||||
|
||||
.chat-messages {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 0.75rem 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
background: #f5f7fa;
|
||||
}
|
||||
|
||||
.chat-bubble {
|
||||
max-width: 78%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.15rem;
|
||||
}
|
||||
|
||||
.chat-bubble--staff {
|
||||
align-self: flex-start;
|
||||
}
|
||||
|
||||
.chat-bubble--student {
|
||||
align-self: flex-end;
|
||||
}
|
||||
|
||||
.chat-bubble-body {
|
||||
padding: 0.5rem 0.7rem;
|
||||
border-radius: 14px;
|
||||
font-size: 0.84rem;
|
||||
line-height: 1.4;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.chat-bubble--staff .chat-bubble-body {
|
||||
background: #fff;
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.chat-bubble--student .chat-bubble-body {
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.chat-bubble-time {
|
||||
font-size: 0.62rem;
|
||||
color: var(--text-muted);
|
||||
padding: 0 0.25rem;
|
||||
}
|
||||
|
||||
.chat-compose {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
padding: 0.65rem 0.85rem;
|
||||
border-top: 1px solid var(--border-color);
|
||||
background: #fff;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.chat-compose input {
|
||||
flex: 1;
|
||||
padding: 0.55rem 0.7rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-color);
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
|
||||
@@ -2,9 +2,40 @@ import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
import { AuthProvider, useAuth } from './auth/AuthContext'
|
||||
import { LoginPage } from './components/LoginPage'
|
||||
import { ChangePasswordPage } from './components/AccountsTab'
|
||||
|
||||
function AppGate() {
|
||||
const { token, staff, loading } = useAuth();
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="auth-shell">
|
||||
<div className="login-card card">Đang tải...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!token) {
|
||||
return (
|
||||
<div className="auth-shell">
|
||||
<LoginPage />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (staff?.mustChangePassword) {
|
||||
return (
|
||||
<div className="auth-shell">
|
||||
<ChangePasswordPage forced />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <App />;
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
<AuthProvider>
|
||||
<AppGate />
|
||||
</AuthProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type TabId = 'dashboard' | 'classes' | 'students' | 'learning' | 'network';
|
||||
export type TabId = 'dashboard' | 'classes' | 'students' | 'learning' | 'network' | 'accounts';
|
||||
|
||||
export interface NavEntry {
|
||||
id: string;
|
||||
@@ -15,13 +15,14 @@ export const TAB_LABELS: Record<TabId, string> = {
|
||||
students: 'Sinh viên',
|
||||
learning: 'Giám sát & Lịch học',
|
||||
network: 'Quản lý mạng',
|
||||
accounts: 'Tài khoản',
|
||||
};
|
||||
|
||||
const HISTORY_KEY = 'sc_nav_history';
|
||||
const MAX_HISTORY = 10;
|
||||
|
||||
function isTabId(value: string | null): value is TabId {
|
||||
return value === 'dashboard' || value === 'classes' || value === 'students' || value === 'learning' || value === 'network';
|
||||
return value === 'dashboard' || value === 'classes' || value === 'students' || value === 'learning' || value === 'network' || value === 'accounts';
|
||||
}
|
||||
|
||||
export function parseRoute(): { tab: TabId; classId: number | null } {
|
||||
|
||||
Reference in New Issue
Block a user