dvc890 commited on
Commit
61db43c
·
verified ·
1 Parent(s): d319f40

Upload 62 files

Browse files
Files changed (3) hide show
  1. models.js +8 -2
  2. pages/Login.tsx +83 -24
  3. routes/auth.js +47 -3
models.js CHANGED
@@ -31,7 +31,13 @@ const UserSchema = new mongoose.Schema({
31
  type: { type: String },
32
  targetClass: String,
33
  status: String
34
- }
 
 
 
 
 
 
35
  });
36
  const User = mongoose.model('User', UserSchema);
37
 
@@ -277,4 +283,4 @@ module.exports = {
277
  ConfigModel, NotificationModel, GameSessionModel, StudentRewardModel, LuckyDrawConfigModel, GameMonsterConfigModel, GameZenConfigModel,
278
  AchievementConfigModel, TeacherExchangeConfigModel, StudentAchievementModel, AttendanceModel, LeaveRequestModel, SchoolCalendarModel,
279
  WishModel, FeedbackModel, TodoModel, AIUsageModel
280
- };
 
31
  type: { type: String },
32
  targetClass: String,
33
  status: String
34
+ },
35
+ // NEW: For Principal creating a new school
36
+ pendingSchoolData: {
37
+ name: String,
38
+ code: String,
39
+ type: String // e.g., Primary, Middle
40
+ }
41
  });
42
  const User = mongoose.model('User', UserSchema);
43
 
 
283
  ConfigModel, NotificationModel, GameSessionModel, StudentRewardModel, LuckyDrawConfigModel, GameMonsterConfigModel, GameZenConfigModel,
284
  AchievementConfigModel, TeacherExchangeConfigModel, StudentAchievementModel, AttendanceModel, LeaveRequestModel, SchoolCalendarModel,
285
  WishModel, FeedbackModel, TodoModel, AIUsageModel
286
+ };
pages/Login.tsx CHANGED
@@ -1,6 +1,6 @@
1
 
2
  import React, { useState, useEffect } from 'react';
3
- import { GraduationCap, Lock, User as UserIcon, AlertCircle, ArrowRight, Loader2, ArrowLeft, School as SchoolIcon, Mail, Phone, Smile, BookOpen, Users, Clipboard } from 'lucide-react';
4
  import { User, UserRole, School, ClassInfo, Subject } from '../types';
5
  import { api } from '../services/api';
6
 
@@ -49,7 +49,11 @@ export const Login: React.FC<LoginProps> = ({ onLogin }) => {
49
  schoolId: '', trueName: '', phone: '', email: '', avatar: '',
50
  teachingSubject: '', homeroomClass: '',
51
  // Student specific
52
- seatNo: '', parentName: '', parentPhone: '', address: '', gender: 'Male', idCard: ''
 
 
 
 
53
  });
54
 
55
  const [schools, setSchools] = useState<School[]>([]);
@@ -77,7 +81,7 @@ export const Login: React.FC<LoginProps> = ({ onLogin }) => {
77
 
78
  // When School ID changes, fetch meta data
79
  useEffect(() => {
80
- if (regForm.schoolId) {
81
  fetch(`${location.origin}/api/public/meta?schoolId=${regForm.schoolId}`)
82
  .then(res => res.json())
83
  .then(data => {
@@ -87,7 +91,7 @@ export const Login: React.FC<LoginProps> = ({ onLogin }) => {
87
  })
88
  .catch(console.error);
89
  }
90
- }, [regForm.schoolId]);
91
 
92
  const handleLogin = async (e: React.FormEvent) => {
93
  e.preventDefault();
@@ -123,7 +127,11 @@ export const Login: React.FC<LoginProps> = ({ onLogin }) => {
123
  setStep(1);
124
  }
125
  } catch (err: any) {
126
- setError(err.message || '注册失败');
 
 
 
 
127
  } finally { setLoading(false); }
128
  };
129
 
@@ -142,6 +150,7 @@ export const Login: React.FC<LoginProps> = ({ onLogin }) => {
142
  setRegForm(prev => ({
143
  ...prev,
144
  role: newRole,
 
145
  // If Admin, clear school ID immediately
146
  schoolId: newRole === UserRole.ADMIN ? '' : prev.schoolId
147
  }));
@@ -157,28 +166,78 @@ export const Login: React.FC<LoginProps> = ({ onLogin }) => {
157
  )}
158
  </div>
159
 
160
- <div>
161
- <label className="text-sm font-medium text-gray-700">所属学校</label>
162
- {regForm.role === UserRole.ADMIN ? (
163
- <div className="w-full mt-1 p-2 border rounded-lg bg-gray-100 text-gray-500 text-sm h-10 flex items-center">
164
- 全局权限 (无需指定学校)
165
- </div>
166
- ) : (
167
- <select
168
- className="w-full mt-1 p-2 border rounded-lg focus:ring-2 focus:ring-blue-500 h-10 bg-white"
169
- value={regForm.schoolId}
170
- onChange={e => setRegForm({...regForm, schoolId: e.target.value})}
171
- >
172
- <option value="">-- 请选择 --</option>
173
- {schools.map(s => <option key={s._id} value={s._id}>{s.name}</option>)}
174
- </select>
175
- )}
176
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
 
178
  <button
179
  type="button"
180
- // Only require school ID if NOT admin
181
- disabled={regForm.role !== UserRole.ADMIN && !regForm.schoolId}
 
 
 
 
 
 
 
182
  onClick={() => setStep(2)}
183
  className="w-full bg-blue-600 text-white py-2 rounded-lg disabled:opacity-50"
184
  >
 
1
 
2
  import React, { useState, useEffect } from 'react';
3
+ import { GraduationCap, Lock, User as UserIcon, AlertCircle, ArrowRight, Loader2, ArrowLeft, School as SchoolIcon, Mail, Phone, Smile, BookOpen, Users, Clipboard, PlusCircle, LogIn } from 'lucide-react';
4
  import { User, UserRole, School, ClassInfo, Subject } from '../types';
5
  import { api } from '../services/api';
6
 
 
49
  schoolId: '', trueName: '', phone: '', email: '', avatar: '',
50
  teachingSubject: '', homeroomClass: '',
51
  // Student specific
52
+ seatNo: '', parentName: '', parentPhone: '', address: '', gender: 'Male', idCard: '',
53
+ // Principal specific (Create School)
54
+ isCreatingSchool: false,
55
+ newSchoolName: '',
56
+ newSchoolCode: ''
57
  });
58
 
59
  const [schools, setSchools] = useState<School[]>([]);
 
81
 
82
  // When School ID changes, fetch meta data
83
  useEffect(() => {
84
+ if (regForm.schoolId && !regForm.isCreatingSchool) {
85
  fetch(`${location.origin}/api/public/meta?schoolId=${regForm.schoolId}`)
86
  .then(res => res.json())
87
  .then(data => {
 
91
  })
92
  .catch(console.error);
93
  }
94
+ }, [regForm.schoolId, regForm.isCreatingSchool]);
95
 
96
  const handleLogin = async (e: React.FormEvent) => {
97
  e.preventDefault();
 
127
  setStep(1);
128
  }
129
  } catch (err: any) {
130
+ if (err.message === 'SCHOOL_EXISTS') {
131
+ setError('学校已存在!请选择“加入学校”模式进行注册。');
132
+ } else {
133
+ setError(err.message || '注册失败');
134
+ }
135
  } finally { setLoading(false); }
136
  };
137
 
 
150
  setRegForm(prev => ({
151
  ...prev,
152
  role: newRole,
153
+ isCreatingSchool: false,
154
  // If Admin, clear school ID immediately
155
  schoolId: newRole === UserRole.ADMIN ? '' : prev.schoolId
156
  }));
 
166
  )}
167
  </div>
168
 
169
+ {regForm.role === UserRole.PRINCIPAL && (
170
+ <div className="flex bg-gray-100 p-1 rounded-lg">
171
+ <button
172
+ onClick={() => setRegForm({...regForm, isCreatingSchool: false, newSchoolName: '', newSchoolCode: ''})}
173
+ className={`flex-1 py-1.5 text-xs font-bold rounded-md flex items-center justify-center gap-1 transition-all ${!regForm.isCreatingSchool ? 'bg-white shadow text-blue-600' : 'text-gray-500'}`}
174
+ >
175
+ <LogIn size={14}/> 加入学校
176
+ </button>
177
+ <button
178
+ onClick={() => setRegForm({...regForm, isCreatingSchool: true, schoolId: ''})}
179
+ className={`flex-1 py-1.5 text-xs font-bold rounded-md flex items-center justify-center gap-1 transition-all ${regForm.isCreatingSchool ? 'bg-white shadow text-green-600' : 'text-gray-500'}`}
180
+ >
181
+ <PlusCircle size={14}/> 创建学校
182
+ </button>
183
+ </div>
184
+ )}
185
+
186
+ {regForm.isCreatingSchool && regForm.role === UserRole.PRINCIPAL ? (
187
+ <div className="space-y-3 bg-green-50 p-3 rounded-lg border border-green-100">
188
+ <div>
189
+ <label className="text-xs font-bold text-green-700 block mb-1">学校名称 (创建)</label>
190
+ <input
191
+ className="w-full p-2 border border-green-200 rounded text-sm focus:ring-2 focus:ring-green-500 outline-none"
192
+ placeholder="请输入完整的学校名称"
193
+ value={regForm.newSchoolName}
194
+ onChange={e => setRegForm({...regForm, newSchoolName: e.target.value})}
195
+ />
196
+ </div>
197
+ <div>
198
+ <label className="text-xs font-bold text-green-700 block mb-1">学校代码 (创建)</label>
199
+ <input
200
+ className="w-full p-2 border border-green-200 rounded text-sm focus:ring-2 focus:ring-green-500 outline-none"
201
+ placeholder="唯一代码 (如: SCH2024)"
202
+ value={regForm.newSchoolCode}
203
+ onChange={e => setRegForm({...regForm, newSchoolCode: e.target.value})}
204
+ />
205
+ </div>
206
+ <p className="text-[10px] text-green-600">
207
+ 提交后需等待平台管理员审核。审核通过后,该学校将被创建,您将成为该校校长。
208
+ </p>
209
+ </div>
210
+ ) : (
211
+ <div>
212
+ <label className="text-sm font-medium text-gray-700">所属学校</label>
213
+ {regForm.role === UserRole.ADMIN ? (
214
+ <div className="w-full mt-1 p-2 border rounded-lg bg-gray-100 text-gray-500 text-sm h-10 flex items-center">
215
+ 全局权限 (无需指定学校)
216
+ </div>
217
+ ) : (
218
+ <select
219
+ className="w-full mt-1 p-2 border rounded-lg focus:ring-2 focus:ring-blue-500 h-10 bg-white"
220
+ value={regForm.schoolId}
221
+ onChange={e => setRegForm({...regForm, schoolId: e.target.value})}
222
+ >
223
+ <option value="">-- 请选择 --</option>
224
+ {schools.map(s => <option key={s._id} value={s._id}>{s.name}</option>)}
225
+ </select>
226
+ )}
227
+ </div>
228
+ )}
229
 
230
  <button
231
  type="button"
232
+ // Logic:
233
+ // 1. Admin: OK
234
+ // 2. Principal Create: Needs Name & Code
235
+ // 3. Principal Join / Others: Needs SchoolID
236
+ disabled={
237
+ (regForm.role === UserRole.ADMIN ? false :
238
+ (regForm.isCreatingSchool ? (!regForm.newSchoolName || !regForm.newSchoolCode) : !regForm.schoolId)
239
+ )
240
+ }
241
  onClick={() => setStep(2)}
242
  className="w-full bg-blue-600 text-white py-2 rounded-lg disabled:opacity-50"
243
  >
routes/auth.js CHANGED
@@ -1,7 +1,7 @@
1
 
2
  const express = require('express');
3
  const router = express.Router();
4
- const { User, Student, ClassModel, NotificationModel } = require('../models');
5
 
6
  // Helpers
7
  const getQueryFilter = (req) => {
@@ -45,7 +45,7 @@ router.get('/me', async (req, res) => {
45
  });
46
 
47
  router.post('/register', async (req, res) => {
48
- const { role, username, password, schoolId, trueName, seatNo } = req.body;
49
  const className = req.body.className || req.body.homeroomClass;
50
  try {
51
  if (role === 'STUDENT') {
@@ -62,9 +62,30 @@ router.post('/register', async (req, res) => {
62
  await User.create({ username: finalUsername, password, role: 'STUDENT', trueName: cleanName, schoolId, status: 'pending', homeroomClass: cleanClass, studentNo: finalUsername, seatNo: seatNo || '', parentName: req.body.parentName, parentPhone: req.body.parentPhone, address: req.body.address, idCard: req.body.idCard, gender: req.body.gender || 'Male', createTime: new Date() });
63
  return res.json({ username: finalUsername });
64
  }
 
 
65
  const existing = await User.findOne({ username });
66
  if (existing) return res.status(409).json({ error: 'USERNAME_EXISTS', message: '用户名已存在' });
67
- await User.create({...req.body, status: 'pending', createTime: new Date()});
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  res.json({ username });
69
  } catch(e) { res.status(500).json({ error: e.message }); }
70
  });
@@ -95,9 +116,32 @@ router.put('/:id', async (req, res) => {
95
  try {
96
  const user = await User.findById(userId);
97
  if (!user) return res.status(404).json({ error: 'User not found' });
 
 
98
  if (user.status !== 'active' && updates.status === 'active' && user.role === 'STUDENT') {
99
  await Student.findOneAndUpdate({ studentNo: user.studentNo, schoolId: user.schoolId }, { $set: { schoolId: user.schoolId, studentNo: user.studentNo, seatNo: user.seatNo, name: user.trueName, className: user.homeroomClass, gender: user.gender || 'Male', parentName: user.parentName, parentPhone: user.parentPhone, address: user.address, idCard: user.idCard, status: 'Enrolled', birthday: '2015-01-01' } }, { upsert: true, new: true });
100
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  await User.findByIdAndUpdate(userId, updates);
102
  res.json({});
103
  } catch (e) { res.status(500).json({ error: e.message }); }
 
1
 
2
  const express = require('express');
3
  const router = express.Router();
4
+ const { User, Student, ClassModel, NotificationModel, School } = require('../models');
5
 
6
  // Helpers
7
  const getQueryFilter = (req) => {
 
45
  });
46
 
47
  router.post('/register', async (req, res) => {
48
+ const { role, username, password, schoolId, trueName, seatNo, isCreatingSchool, newSchoolName, newSchoolCode } = req.body;
49
  const className = req.body.className || req.body.homeroomClass;
50
  try {
51
  if (role === 'STUDENT') {
 
62
  await User.create({ username: finalUsername, password, role: 'STUDENT', trueName: cleanName, schoolId, status: 'pending', homeroomClass: cleanClass, studentNo: finalUsername, seatNo: seatNo || '', parentName: req.body.parentName, parentPhone: req.body.parentPhone, address: req.body.address, idCard: req.body.idCard, gender: req.body.gender || 'Male', createTime: new Date() });
63
  return res.json({ username: finalUsername });
64
  }
65
+
66
+ // Check Username Duplication
67
  const existing = await User.findOne({ username });
68
  if (existing) return res.status(409).json({ error: 'USERNAME_EXISTS', message: '用户名已存在' });
69
+
70
+ // Handle Principal creating a school
71
+ let pendingSchoolData = null;
72
+ let finalSchoolId = schoolId;
73
+
74
+ if (role === 'PRINCIPAL' && isCreatingSchool) {
75
+ if (!newSchoolName || !newSchoolCode) return res.status(400).json({ error: 'MISSING_SCHOOL_INFO', message: '请输入学校名称和代码' });
76
+
77
+ // Check if school already exists
78
+ const schoolExists = await School.findOne({ $or: [{ name: newSchoolName }, { code: newSchoolCode }] });
79
+ if (schoolExists) return res.status(409).json({ error: 'SCHOOL_EXISTS', message: '该学校名称或代码已存在,请选择“加入学校”' });
80
+
81
+ pendingSchoolData = {
82
+ name: newSchoolName,
83
+ code: newSchoolCode
84
+ };
85
+ finalSchoolId = ''; // No school ID yet
86
+ }
87
+
88
+ await User.create({...req.body, schoolId: finalSchoolId, pendingSchoolData, status: 'pending', createTime: new Date()});
89
  res.json({ username });
90
  } catch(e) { res.status(500).json({ error: e.message }); }
91
  });
 
116
  try {
117
  const user = await User.findById(userId);
118
  if (!user) return res.status(404).json({ error: 'User not found' });
119
+
120
+ // Handle Student activation logic (existing)
121
  if (user.status !== 'active' && updates.status === 'active' && user.role === 'STUDENT') {
122
  await Student.findOneAndUpdate({ studentNo: user.studentNo, schoolId: user.schoolId }, { $set: { schoolId: user.schoolId, studentNo: user.studentNo, seatNo: user.seatNo, name: user.trueName, className: user.homeroomClass, gender: user.gender || 'Male', parentName: user.parentName, parentPhone: user.parentPhone, address: user.address, idCard: user.idCard, status: 'Enrolled', birthday: '2015-01-01' } }, { upsert: true, new: true });
123
  }
124
+
125
+ // NEW: Handle Principal School Creation on Activation
126
+ if (user.status !== 'active' && updates.status === 'active' && user.role === 'PRINCIPAL' && user.pendingSchoolData && user.pendingSchoolData.name) {
127
+ // Check again if school exists (double safety)
128
+ const exists = await School.findOne({ $or: [{ name: user.pendingSchoolData.name }, { code: user.pendingSchoolData.code }] });
129
+ if (exists) {
130
+ // Conflict! Just link to existing school? Or fail?
131
+ // Let's link to existing to allow approval, but clear creation data.
132
+ updates.schoolId = exists._id;
133
+ updates.pendingSchoolData = null;
134
+ } else {
135
+ // Create New School
136
+ const newSchool = await School.create({
137
+ name: user.pendingSchoolData.name,
138
+ code: user.pendingSchoolData.code
139
+ });
140
+ updates.schoolId = newSchool._id;
141
+ updates.pendingSchoolData = null;
142
+ }
143
+ }
144
+
145
  await User.findByIdAndUpdate(userId, updates);
146
  res.json({});
147
  } catch (e) { res.status(500).json({ error: e.message }); }