39271-vm/backend/src/db/api/students.js
2026-03-23 04:48:34 +00:00

755 lines
18 KiB
JavaScript

const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class StudentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const students = await db.students.create(
{
id: data.id || undefined,
student_full_name: data.student_full_name
||
null
,
roll_no: data.roll_no
||
null
,
registration_no: data.registration_no
||
null
,
date_of_birth: data.date_of_birth
||
null
,
gender: data.gender
||
null
,
address: data.address
||
null
,
contact_phone: data.contact_phone
||
null
,
guardian_name: data.guardian_name
||
null
,
guardian_phone: data.guardian_phone
||
null
,
is_active: data.is_active
||
false
,
admission_date: data.admission_date
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await students.setSchool( data.school || null, {
transaction,
});
await students.setClassroom( data.classroom || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.students.getTableName(),
belongsToColumn: 'photo',
belongsToId: students.id,
},
data.photo,
options,
);
return students;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const studentsData = data.map((item, index) => ({
id: item.id || undefined,
student_full_name: item.student_full_name
||
null
,
roll_no: item.roll_no
||
null
,
registration_no: item.registration_no
||
null
,
date_of_birth: item.date_of_birth
||
null
,
gender: item.gender
||
null
,
address: item.address
||
null
,
contact_phone: item.contact_phone
||
null
,
guardian_name: item.guardian_name
||
null
,
guardian_phone: item.guardian_phone
||
null
,
is_active: item.is_active
||
false
,
admission_date: item.admission_date
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const students = await db.students.bulkCreate(studentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < students.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.students.getTableName(),
belongsToColumn: 'photo',
belongsToId: students[i].id,
},
data[i].photo,
options,
);
}
return students;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const students = await db.students.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.student_full_name !== undefined) updatePayload.student_full_name = data.student_full_name;
if (data.roll_no !== undefined) updatePayload.roll_no = data.roll_no;
if (data.registration_no !== undefined) updatePayload.registration_no = data.registration_no;
if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
if (data.gender !== undefined) updatePayload.gender = data.gender;
if (data.address !== undefined) updatePayload.address = data.address;
if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
if (data.guardian_name !== undefined) updatePayload.guardian_name = data.guardian_name;
if (data.guardian_phone !== undefined) updatePayload.guardian_phone = data.guardian_phone;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.admission_date !== undefined) updatePayload.admission_date = data.admission_date;
updatePayload.updatedById = currentUser.id;
await students.update(updatePayload, {transaction});
if (data.school !== undefined) {
await students.setSchool(
data.school,
{ transaction }
);
}
if (data.classroom !== undefined) {
await students.setClassroom(
data.classroom,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.students.getTableName(),
belongsToColumn: 'photo',
belongsToId: students.id,
},
data.photo,
options,
);
return students;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const students = await db.students.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of students) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of students) {
await record.destroy({transaction});
}
});
return students;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const students = await db.students.findByPk(id, options);
await students.update({
deletedBy: currentUser.id
}, {
transaction,
});
await students.destroy({
transaction
});
return students;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const students = await db.students.findOne(
{ where },
{ transaction },
);
if (!students) {
return students;
}
const output = students.get({plain: true});
output.marks_entries_student = await students.getMarks_entries_student({
transaction
});
output.student_results_student = await students.getStudent_results_student({
transaction
});
output.attendance_records_student = await students.getAttendance_records_student({
transaction
});
output.certificates_student = await students.getCertificates_student({
transaction
});
output.school = await students.getSchool({
transaction
});
output.classroom = await students.getClassroom({
transaction
});
output.photo = await students.getPhoto({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.schools,
as: 'school',
},
{
model: db.classrooms,
as: 'classroom',
where: filter.classroom ? {
[Op.or]: [
{ id: { [Op.in]: filter.classroom.split('|').map(term => Utils.uuid(term)) } },
{
class_label: {
[Op.or]: filter.classroom.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'photo',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.student_full_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'students',
'student_full_name',
filter.student_full_name,
),
};
}
if (filter.roll_no) {
where = {
...where,
[Op.and]: Utils.ilike(
'students',
'roll_no',
filter.roll_no,
),
};
}
if (filter.registration_no) {
where = {
...where,
[Op.and]: Utils.ilike(
'students',
'registration_no',
filter.registration_no,
),
};
}
if (filter.address) {
where = {
...where,
[Op.and]: Utils.ilike(
'students',
'address',
filter.address,
),
};
}
if (filter.contact_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'students',
'contact_phone',
filter.contact_phone,
),
};
}
if (filter.guardian_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'students',
'guardian_name',
filter.guardian_name,
),
};
}
if (filter.guardian_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'students',
'guardian_phone',
filter.guardian_phone,
),
};
}
if (filter.date_of_birthRange) {
const [start, end] = filter.date_of_birthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.lte]: end,
},
};
}
}
if (filter.admission_dateRange) {
const [start, end] = filter.admission_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
admission_date: {
...where.admission_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
admission_date: {
...where.admission_date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.gender) {
where = {
...where,
gender: filter.gender,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.school) {
const listItems = filter.school.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.students.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'students',
'student_full_name',
query,
),
],
};
}
const records = await db.students.findAll({
attributes: [ 'id', 'student_full_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['student_full_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.student_full_name,
}));
}
};