File size: 15,115 Bytes
4949b0b
8eb1b37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
648396d
8eb1b37
 
700b192
8eb1b37
648396d
8eb1b37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c8b5da
648396d
 
8eb1b37
e52e99f
8eb1b37
 
 
 
 
 
 
 
 
 
 
 
07d35d2
7d2c997
8eb1b37
 
2262385
8eb1b37
 
 
 
 
 
 
2262385
8eb1b37
 
 
 
 
 
 
 
2262385
8eb1b37
 
 
 
 
 
 
 
4949b0b
8eb1b37
4949b0b
7d2c997
8eb1b37
 
648396d
8eb1b37
 
 
 
3c8b5da
8eb1b37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2262385
8eb1b37
 
 
 
 
 
2262385
8eb1b37
2262385
648396d
07d35d2
 
8eb1b37
07d35d2
8eb1b37
2262385
8eb1b37
2262385
648396d
8eb1b37
 
07d35d2
8eb1b37
 
 
 
 
 
 
 
 
 
 
 
 
2262385
648396d
07d35d2
8eb1b37
 
2262385
8eb1b37
2262385
648396d
07d35d2
8eb1b37
 
2262385
8eb1b37
 
 
 
 
07d35d2
8eb1b37
 
 
 
 
07d35d2
8eb1b37
 
 
 
 
 
 
 
 
 
7d2c997
8eb1b37
 
 
 
 
07d35d2
8eb1b37
2262385
8eb1b37
2262385
8eb1b37
648396d
8eb1b37
648396d
8eb1b37
2262385
8eb1b37
 
 
2262385
8eb1b37
7d2c997
8eb1b37
 
 
 
 
 
 
 
 
 
2262385
8eb1b37
7d2c997
8eb1b37
 
 
1751a72
8eb1b37
1751a72
8eb1b37
 
 
 
7d2c997
8eb1b37
 
 
 
 
 
 
 
 
 
 
 
7d2c997
8eb1b37
 
 
55081a6
8eb1b37
55081a6
8eb1b37
 
 
 
 
 
 
55081a6
8eb1b37
55081a6
8eb1b37
 
 
 
 
 
 
b4aff11
8eb1b37
b4aff11
019d28a
8eb1b37
3d889df
8eb1b37
5e8f957
8eb1b37
 
 
 
 
 
 
019d28a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287

// ... existing imports
import { User, ClassInfo, SystemConfig, Subject, School, Schedule, GameSession, StudentReward, LuckyDrawConfig, Attendance, LeaveRequest, AchievementConfig, SchoolCalendarEntry, TeacherExchangeConfig, Wish, Feedback, AIChatMessage, Todo } from '../types';

// ... existing getBaseUrl ...
const getBaseUrl = () => {
  let isProd = false;
  try {
    // @ts-ignore
    if (typeof import.meta !== 'undefined' && import.meta.env && import.meta.env.PROD) {
      isProd = true;
    }
  } catch (e) {}
  
  if (isProd || (typeof window !== 'undefined' && window.location.port === '7860')) {
    return '/api';
  }
  return 'http://localhost:7860/api';
};

const API_BASE_URL = getBaseUrl();

async function request(endpoint: string, options: RequestInit = {}) {
  const headers: any = { 'Content-Type': 'application/json', ...options.headers };
  
  if (typeof window !== 'undefined') {
    const currentUser = JSON.parse(localStorage.getItem('user') || 'null');
    const selectedSchoolId = localStorage.getItem('admin_view_school_id');
    
    if (currentUser?.role === 'ADMIN' && selectedSchoolId) {
      headers['x-school-id'] = selectedSchoolId;
    } else if (currentUser?.schoolId) {
      headers['x-school-id'] = currentUser.schoolId;
    }
    
    if (currentUser?.role) {
      headers['x-user-role'] = currentUser.role;
      headers['x-user-username'] = currentUser.username;
    }
  }

  const res = await fetch(`${API_BASE_URL}${endpoint}`, { ...options, headers });

  if (!res.ok) {
    if (res.status === 401) throw new Error('AUTH_FAILED');
    const errorData = await res.json().catch(() => ({}));
    const errorMessage = errorData.error || errorData.message || `Server Error: ${res.status}`;
    if (errorData.error === 'PENDING_APPROVAL') throw new Error('PENDING_APPROVAL');
    if (errorData.error === 'BANNED') throw new Error('BANNED');
    if (errorData.error === 'CONFLICT') throw new Error(errorData.message); 
    if (errorData.error === 'INVALID_PASSWORD') throw new Error('INVALID_PASSWORD');
    throw new Error(errorMessage);
  }
  return res.json();
}

export const api = {
  init: () => console.log('🔗 API:', API_BASE_URL),

  auth: {
    login: async (username: string, password: string): Promise<User> => {
      const user = await request('/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) });
      if (typeof window !== 'undefined') {
        localStorage.setItem('user', JSON.stringify(user));
        localStorage.removeItem('admin_view_school_id');
      }
      return user;
    },
    refreshSession: async (): Promise<User | null> => {
        try {
            const user = await request('/auth/me');
            if (typeof window !== 'undefined' && user) {
                localStorage.setItem('user', JSON.stringify(user));
            }
            return user;
        } catch (e) { return null; }
    },
    register: async (data: any): Promise<User> => {
      return await request('/auth/register', { method: 'POST', body: JSON.stringify(data) });
    },
    updateProfile: async (data: any): Promise<any> => {
      return await request('/auth/update-profile', { method: 'POST', body: JSON.stringify(data) });
    },
    logout: () => {
      if (typeof window !== 'undefined') {
        localStorage.removeItem('user');
        localStorage.removeItem('admin_view_school_id');
      }
    },
    getCurrentUser: (): User | null => {
      if (typeof window !== 'undefined') {
        try {
          const stored = localStorage.getItem('user');
          if (stored) return JSON.parse(stored);
        } catch (e) {
          localStorage.removeItem('user');
        }
      }
      return null;
    }
  },

  schools: {
    getPublic: () => request('/public/schools'),
    getAll: () => request('/schools'),
    add: (data: School) => request('/schools', { method: 'POST', body: JSON.stringify(data) }),
    update: (id: string, data: Partial<School>) => request(`/schools/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    delete: (id: string) => request(`/schools/${id}`, { method: 'DELETE' })
  },

  users: {
    getAll: (options?: { global?: boolean; role?: string }) => {
       const params = new URLSearchParams();
       if (options?.global) params.append('global', 'true');
       if (options?.role) params.append('role', options.role);
       return request(`/users?${params.toString()}`);
    },
    update: (id: string, data: Partial<User>) => request(`/users/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    delete: (id: string) => request(`/users/${id}`, { method: 'DELETE' }),
    applyClass: (data: { userId: string, type: 'CLAIM'|'RESIGN', targetClass?: string, action: 'APPLY'|'APPROVE'|'REJECT' }) => 
        request('/users/class-application', { method: 'POST', body: JSON.stringify(data) }),
    getTeachersForClass: (className: string) => request(`/classes/${encodeURIComponent(className)}/teachers`),
    saveMenuOrder: (userId: string, order: string[]) => request(`/users/${userId}/menu-order`, { method: 'PUT', body: JSON.stringify({ menuOrder: order }) }), // NEW
  },

  students: {
    getAll: () => request('/students'),
    add: (data: any) => request('/students', { method: 'POST', body: JSON.stringify(data) }),
    update: (id: string, data: any) => request(`/students/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    delete: (id: string | number) => request(`/students/${id}`, { method: 'DELETE' }),
    promote: (data: { teacherFollows: boolean }) => request('/students/promote', { method: 'POST', body: JSON.stringify(data) }),
    transfer: (data: { studentId: string, targetClass: string }) => request('/students/transfer', { method: 'POST', body: JSON.stringify(data) })
  },

  classes: {
    getAll: () => request('/classes'),
    add: (data: ClassInfo) => request('/classes', { method: 'POST', body: JSON.stringify(data) }),
    delete: (id: string | number) => request(`/classes/${id}`, { method: 'DELETE' })
  },

  subjects: {
    getAll: () => request('/subjects'),
    add: (data: Subject) => request('/subjects', { method: 'POST', body: JSON.stringify(data) }),
    update: (id: string | number, data: Partial<Subject>) => request(`/subjects/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    delete: (id: string | number) => request(`/subjects/${id}`, { method: 'DELETE' })
  },

  exams: {
    getAll: () => request('/exams'),
    save: (data: any) => request('/exams', { method: 'POST', body: JSON.stringify(data) })
  },

  courses: {
    getAll: () => request('/courses'),
    add: (data: any) => request('/courses', { method: 'POST', body: JSON.stringify(data) }),
    update: (id: string | number, data: any) => request(`/courses/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    delete: (id: string | number) => request(`/courses/${id}`, { method: 'DELETE' })
  },

  scores: {
    getAll: () => request('/scores'),
    add: (data: any) => request('/scores', { method: 'POST', body: JSON.stringify(data) }),
    update: (id: string | number, data: any) => request(`/scores/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    delete: (id: string | number) => request(`/scores/${id}`, { method: 'DELETE' })
  },
  
  schedules: {
    get: (params: { className?: string; teacherName?: string; grade?: string }) => {
       const qs = new URLSearchParams(params as any).toString();
       return request(`/schedules?${qs}`);
    },
    save: (data: Schedule) => request('/schedules', { method: 'POST', body: JSON.stringify(data) }),
    delete: (params: { className: string; dayOfWeek: number; period: number }) => {
       const qs = new URLSearchParams(params as any).toString();
       return request(`/schedules?${qs}`, { method: 'DELETE' });
    }
  },

  attendance: {
    checkIn: (data: { studentId: string, date: string, status?: string }) => request('/attendance/check-in', { method: 'POST', body: JSON.stringify(data) }),
    get: (params: { className?: string, date?: string, studentId?: string }) => {
        const qs = new URLSearchParams(params as any).toString();
        return request(`/attendance?${qs}`);
    },
    batch: (data: { className: string, date: string, status?: string }) => request('/attendance/batch', { method: 'POST', body: JSON.stringify(data) }),
    update: (data: { studentId: string, date: string, status: string }) => request('/attendance/update', { method: 'PUT', body: JSON.stringify(data) }),
    applyLeave: (data: { studentId: string, studentName: string, className: string, reason: string, startDate: string, endDate: string }) => request('/leave', { method: 'POST', body: JSON.stringify(data) }),
  },
  
  calendar: {
      get: (className: string) => request(`/attendance/calendar?className=${className}`),
      add: (data: SchoolCalendarEntry) => request('/attendance/calendar', { method: 'POST', body: JSON.stringify(data) }),
      delete: (id: string) => request(`/attendance/calendar/${id}`, { method: 'DELETE' })
  },

  stats: {
    getSummary: () => request('/stats')
  },

  config: {
    get: () => request('/config'), 
    getPublic: () => request('/public/config'),
    save: (data: SystemConfig) => request('/config', { method: 'POST', body: JSON.stringify(data) })
  },
  
  notifications: {
    getAll: (userId: string, role: string) => request(`/notifications?userId=${userId}&role=${role}`),
  },

  games: {
    getMountainSession: (className: string) => request(`/games/mountain?className=${className}`),
    saveMountainSession: (data: GameSession) => request('/games/mountain', { method: 'POST', body: JSON.stringify(data) }),
    getLuckyConfig: (className?: string, ownerId?: string) => request(`/games/lucky-config?className=${className || ''}${ownerId ? `&ownerId=${ownerId}` : ''}`),
    saveLuckyConfig: (data: LuckyDrawConfig) => request('/games/lucky-config', { method: 'POST', body: JSON.stringify(data) }),
    drawLucky: (studentId: string) => request('/games/lucky-draw', { method: 'POST', body: JSON.stringify({ studentId }) }),
    grantReward: (data: { studentId: string, count: number, rewardType: string, name?: string }) => request('/games/grant-reward', { method: 'POST', body: JSON.stringify(data) }),
    getMonsterConfig: (className: string) => request(`/games/monster-config?className=${className}`),
    saveMonsterConfig: (data: any) => request('/games/monster-config', { method: 'POST', body: JSON.stringify(data) }),
    getZenConfig: (className: string) => request(`/games/zen-config?className=${className}`),
    saveZenConfig: (data: any) => request('/games/zen-config', { method: 'POST', body: JSON.stringify(data) }),
  },
  
  achievements: {
      getConfig: (className: string) => request(`/achievements/config?className=${className}`),
      saveConfig: (data: AchievementConfig) => request('/achievements/config', { method: 'POST', body: JSON.stringify(data) }),
      getStudentAchievements: (studentId: string, semester?: string) => request(`/achievements/student?studentId=${studentId}${semester ? `&semester=${semester}` : ''}`),
      getClassHistory: (studentIds: string[]) => request(`/achievements/student?studentIds=${studentIds.join(',')}&semester=ALL`), // NEW
      grant: (data: { studentId: string, achievementId: string, semester: string }) => request('/achievements/grant', { method: 'POST', body: JSON.stringify(data) }),
      deleteRecord: (id: string) => request(`/achievements/record/${id}`, { method: 'DELETE' }), // NEW
      exchange: (data: { studentId: string, ruleId: string, teacherId?: string }) => request('/achievements/exchange', { method: 'POST', body: JSON.stringify(data) }),
      getMyRules: () => request('/achievements/teacher-rules'),
      saveMyRules: (data: TeacherExchangeConfig) => request('/achievements/teacher-rules', { method: 'POST', body: JSON.stringify(data) }),
      getRulesByTeachers: (teacherIds: string[]) => request(`/achievements/teacher-rules?teacherIds=${teacherIds.join(',')}`),
  },

  rewards: {
    getMyRewards: (studentId: string, page = 1, limit = 20) => request(`/rewards?studentId=${studentId}&page=${page}&limit=${limit}&excludeType=CONSOLATION`),
    getClassRewards: (page = 1, limit = 20, className?: string) => {
        let qs = `scope=class&page=${page}&limit=${limit}&excludeType=CONSOLATION`;
        if (className) qs += `&className=${className}`;
        return request(`/rewards?${qs}`);
    }, 
    addReward: (data: Partial<StudentReward>) => request('/rewards', { method: 'POST', body: JSON.stringify(data) }),
    update: (id: string, data: Partial<StudentReward>) => request(`/rewards/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
    delete: (id: string) => request(`/rewards/${id}`, { method: 'DELETE' }),
    redeem: (id: string) => request(`/rewards/${id}/redeem`, { method: 'POST' }),
  },

  batchDelete: (type: 'student' | 'score' | 'user', ids: string[]) => {
    return request('/batch-delete', { method: 'POST', body: JSON.stringify({ type, ids }) });
  },

  wishes: {
      getAll: (params: { teacherId?: string, studentId?: string, status?: string }) => {
          const qs = new URLSearchParams(params as any).toString();
          return request(`/wishes?${qs}`);
      },
      create: (data: Partial<Wish>) => request('/wishes', { method: 'POST', body: JSON.stringify(data) }),
      fulfill: (id: string) => request(`/wishes/${id}/fulfill`, { method: 'POST' }),
      randomFulfill: (teacherId: string) => request('/wishes/random-fulfill', { method: 'POST', body: JSON.stringify({ teacherId }) }),
  },

  feedback: {
      getAll: (params: { targetId?: string, creatorId?: string, type?: string, status?: string }) => {
          const qs = new URLSearchParams(params as any).toString();
          return request(`/feedback?${qs}`);
      },
      create: (data: Partial<Feedback>) => request('/feedback', { method: 'POST', body: JSON.stringify(data) }),
      update: (id: string, data: { status?: string, reply?: string }) => request(`/feedback/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
      ignoreAll: (targetId: string) => request('/feedback/ignore-all', { method: 'POST', body: JSON.stringify({ targetId }) }),
  },

  ai: {
      chat: (data: { text?: string, audio?: string, history?: { role: string, text?: string }[], enableThinking?: boolean, overrideSystemPrompt?: string, disableAudio?: boolean }) => request('/ai/chat', { method: 'POST', body: JSON.stringify(data) }),
      evaluate: (data: { question: string, audio?: string, image?: string }) => request('/ai/evaluate', { method: 'POST', body: JSON.stringify(data) }),
      resetPool: () => request('/ai/reset-pool', { method: 'POST' }), 
      getStats: () => request('/ai/stats'), // NEW Detailed Stats
  },

  todos: { // NEW
      getAll: () => request('/todos'),
      add: (content: string) => request('/todos', { method: 'POST', body: JSON.stringify({ content }) }),
      update: (id: string, data: Partial<Todo>) => request(`/todos/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
      delete: (id: string) => request(`/todos/${id}`, { method: 'DELETE' }),
  }
};