File size: 9,970 Bytes
fc99396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
288
289
290
// rfid-handler.js - RFID Integration for WASTE-LESS
// Uses GITHUB_CONFIG from config.js for all GitHub operations

const RFID_CONFIG = {
    SCANNER: {
        INPUT_TIMEOUT: 500,
        ID_LENGTH: 10,
        PREFIX: '',
        SUFFIX: '\n'
    }
};

function parseStudentEntry(entry) {
    if (typeof entry === 'string') {
        const parts = entry.split('|');
        return { name: parts[0], rfid: parts[1] || null };
    }
    return entry;
}

class RFIDScanner {
    constructor() {
        this.buffer = '';
        this.lastKeyTime = 0;
        this.onScanCallback = null;
    }

    init(onScan) {
        this.onScanCallback = onScan;
        document.addEventListener('keydown', this.handleKeyDown.bind(this));
        console.log('RFID Scanner ready');
    }

    handleKeyDown(event) {
        const now = Date.now();
        const timeDiff = now - this.lastKeyTime;
        this.lastKeyTime = now;

        if (timeDiff > RFID_CONFIG.SCANNER.INPUT_TIMEOUT && this.buffer.length > 0) {
            this.buffer = '';
        }

        if (event.ctrlKey || event.altKey || event.metaKey) return;

        if (event.key === 'Enter') {
            if (this.buffer.length >= 4) {
                this.processScan(this.buffer);
            }
            this.buffer = '';
            event.preventDefault();
            return;
        }

        if (event.key.length === 1) {
            this.buffer += event.key;
        }

        if (this.buffer.length >= RFID_CONFIG.SCANNER.ID_LENGTH) {
            this.processScan(this.buffer);
            this.buffer = '';
        }
    }

    processScan(rawId) {
        let cleanId = rawId.trim().toUpperCase();
        const prefixes = ['CARD:', 'ID:', 'RFID:', 'UID:'];
        prefixes.forEach(p => {
            if (cleanId.startsWith(p)) cleanId = cleanId.substring(p.length);
        });
        cleanId = cleanId.replace(/[^A-Z0-9]/g, '');
        this.onScanCallback?.(cleanId);
    }

    simulateScan(rfidId) {
        this.processScan(rfidId);
    }
}

class StudentRFIDManager {
    constructor() {
        this.scanner = new RFIDScanner();
        this.students = {};
        this.availableClasses = [];
        this.repo = GITHUB_CONFIG.REPOS.STUDENT_LIST;
        this.token = GITHUB_CONFIG.TOKEN;
        this.filePath = GITHUB_CONFIG.PATHS.STUDENTS;
    }

    async loadStudentList() {
        try {
            const response = await fetch(
                `https://api.github.com/repos/${this.repo}/contents/${this.filePath}`,
                {
                    headers: {
                        'Authorization': `token ${this.token}`,
                        'Accept': 'application/vnd.github.v3+json'
                    }
                }
            );

            if (response.status === 404) {
                this.students = {};
                this.availableClasses = [];
                return false;
            }

            if (!response.ok) throw new Error('Failed to load student list');

            const data = await response.json();
            this.students = JSON.parse(atob(data.content));
            this.migrateFormat();
            this.availableClasses = [...new Set(Object.keys(this.students).map(k => k.split('-')[0]))].sort();
            return true;
        } catch (error) {
            console.error('Error loading student list:', error);
            const local = localStorage.getItem('student-list-backup');
            if (local) {
                this.students = JSON.parse(local);
                this.migrateFormat();
                this.availableClasses = [...new Set(Object.keys(this.students).map(k => k.split('-')[0]))].sort();
            }
            return false;
        }
    }

    migrateFormat() {
        for (const key in this.students) {
            if (Array.isArray(this.students[key]) && this.students[key].length > 0) {
                if (typeof this.students[key][0] === 'string') {
                    this.students[key] = this.students[key].map(entry => {
                        if (typeof entry === 'string') {
                            const parts = entry.split('|');
                            return { name: parts[0], rfid: parts[1] || null };
                        }
                        return entry;
                    });
                }
            }
        }
    }

    getStudentNames(classVal, formVal) {
        const key = `${classVal}-${formVal}`;
        if (!this.students[key]) return [];
        return this.students[key].map(s => s.name || s);
    }

    getStudentData(classVal, formVal, studentName) {
        const key = `${classVal}-${formVal}`;
        if (!this.students[key]) return null;
        return this.students[key].find(s => (s.name || s) === studentName) || null;
    }

    getRFIDByStudent(classVal, formVal, studentName) {
        const student = this.getStudentData(classVal, formVal, studentName);
        if (!student) return null;
        return student.rfid || null;
    }

    findStudentByRFID(rfidId) {
        const cleanId = rfidId.toUpperCase().replace(/[^A-Z0-9]/g, '');
        for (const [key, studentList] of Object.entries(this.students)) {
            const [cls, form] = key.split('-');
            for (const student of studentList) {
                const studentRfid = (student.rfid || '').toUpperCase().replace(/[^A-Z0-9]/g, '');
                if (studentRfid === cleanId) {
                    return {
                        rfidId: cleanId,
                        studentName: student.name || student,
                        class: cls,
                        form: form,
                        rawData: student
                    };
                }
            }
        }
        return null;
    }

    async setStudentRFID(classVal, formVal, studentName, rfidId) {
        const key = `${classVal}-${formVal}`;
        if (!this.students[key]) return false;

        const idx = this.students[key].findIndex(s => (s.name || s) === studentName);
        if (idx === -1) return false;

        const existing = this.students[key][idx];
        if (typeof existing === 'string') {
            this.students[key][idx] = { name: existing, rfid: rfidId };
        } else {
            this.students[key][idx].rfid = rfidId;
        }

        return await this.saveStudentList();
    }

    async removeStudentRFID(classVal, formVal, studentName) {
        return await this.setStudentRFID(classVal, formVal, studentName, null);
    }

    async saveStudentList() {
        try {
            let sha = null;
            const res = await fetch(
                `https://api.github.com/repos/${this.repo}/contents/${this.filePath}`,
                { headers: { 'Authorization': `token ${this.token}` } }
            );
            if (res.ok) sha = (await res.json()).sha;

            const putRes = await fetch(
                `https://api.github.com/repos/${this.repo}/contents/${this.filePath}`,
                {
                    method: 'PUT',
                    headers: {
                        'Authorization': `token ${this.token}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        message: `Update student RFID data - ${new Date().toISOString()}`,
                        content: btoa(JSON.stringify(this.students, null, 2)),
                        sha,
                        branch: 'main'
                    })
                }
            );

            if (!putRes.ok) throw new Error('Save failed');
            localStorage.setItem('student-list-backup', JSON.stringify(this.students));
            return true;
        } catch (err) {
            console.error('Save error:', err);
            localStorage.setItem('student-list-backup', JSON.stringify(this.students));
            return false;
        }
    }

    exportToCSV() {
        let csv = 'Class,Form,StudentName,RFID_Card_ID\n';
        for (const [key, studentList] of Object.entries(this.students)) {
            const [cls, form] = key.split('-');
            studentList.forEach(student => {
                const name = student.name || student;
                const rfid = student.rfid || '';
                csv += `${cls},${form},"${name.replace(/"/g, '""')}",${rfid}\n`;
            });
        }
        return csv;
    }

    importFromCSV(csvText) {
        const lines = csvText.split('\n').map(l => l.trim()).filter(l => l);
        if (lines.length < 2) throw new Error('Empty or invalid CSV');

        const headers = lines[0].toLowerCase().split(',');
        const hasRfid = headers.includes('rfid_card_id') || headers.includes('rfid');
        const rfidCol = headers.indexOf('rfid_card_id') !== -1 ? 
            headers.indexOf('rfid_card_id') : 
            headers.indexOf('rfid');

        const newStudents = {};
        for (let i = 1; i < lines.length; i++) {
            const match = lines[i].match(/([^,]*),([^,]*),([^,]*)(?:,(.*))?/);
            if (!match) continue;

            let cls = match[1].trim().toUpperCase();
            let form = match[2].trim();
            let name = match[3].trim().replace(/^"|"$/g, '').replace(/"""/g, '"');
            let rfid = hasRfid && match[4] ? match[4].trim().replace(/^"|"$/g, '') : null;

            if (!cls || !form || !name) continue;

            const key = `${cls}-${form}`;
            if (!newStudents[key]) newStudents[key] = [];

            const exists = newStudents[key].find(s => (s.name || s) === name);
            if (!exists) {
                newStudents[key].push(rfid ? { name, rfid } : name);
            }
        }

        this.students = newStudents;
        this.availableClasses = [...new Set(Object.keys(newStudents).map(k => k.split('-')[0]))].sort();
        return this.saveStudentList();
    }
}

window.StudentRFIDManager = StudentRFIDManager;
window.RFIDScanner = RFIDScanner;
window.parseStudentEntry = parseStudentEntry;