Spaces:
Sleeping
Sleeping
| const db = require('../db'); | |
| /** | |
| * Generate the next sequential Student ID (e.g., SKUEDU0701) | |
| */ | |
| async function generateNextStudentId() { | |
| try { | |
| const now = new Date(); | |
| const currentMonth = String(now.getMonth() + 1).padStart(2, '0'); | |
| const prefix = `SKUEDU${currentMonth}`; | |
| let maxNum = 0; | |
| // Fetch all leads that have an ID starting with the current prefix | |
| const { data: allLeads, error: maxIdError } = await db | |
| .from('leads') | |
| .select('student_id') | |
| .not('student_id', 'is', null) | |
| .like('student_id', `${prefix}%`); | |
| if (!maxIdError && allLeads && allLeads.length > 0) { | |
| allLeads.forEach(lead => { | |
| const id = lead.student_id.toUpperCase(); | |
| if (id.startsWith(prefix)) { | |
| const numPart = parseInt(id.replace(prefix, ''), 10); | |
| if (!isNaN(numPart) && numPart > maxNum) { | |
| maxNum = numPart; | |
| } | |
| } | |
| }); | |
| } | |
| const nextNum = String(maxNum + 1).padStart(2, '0'); // at least 2 digits e.g. 01, 02 | |
| return `${prefix}${nextNum}`; | |
| } catch (err) { | |
| console.error('Error generating student ID:', err); | |
| // Fallback if DB fails | |
| const currentMonth = String(new Date().getMonth() + 1).padStart(2, '0'); | |
| return `SKUEDU${currentMonth}${String(Math.floor(Math.random() * 90) + 10)}`; | |
| } | |
| } | |
| module.exports = { | |
| generateNextStudentId | |
| }; | |