31176/backend/src/db/api/visitors.js
2025-05-02 12:36:11 +00:00

450 lines
11 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 VisitorsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const visitors = await db.visitors.create(
{
id: data.id || undefined,
full_name: data.full_name || null,
email: data.email || null,
phone: data.phone || null,
purpose: data.purpose || null,
check_in_time: data.check_in_time || null,
check_out_time: data.check_out_time || null,
status: data.status || null,
badge_id: data.badge_id || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await visitors.setHost(data.host || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.visitors.getTableName(),
belongsToColumn: 'photo',
belongsToId: visitors.id,
},
data.photo,
options,
);
return visitors;
}
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 visitorsData = data.map((item, index) => ({
id: item.id || undefined,
full_name: item.full_name || null,
email: item.email || null,
phone: item.phone || null,
purpose: item.purpose || null,
check_in_time: item.check_in_time || null,
check_out_time: item.check_out_time || null,
status: item.status || null,
badge_id: item.badge_id || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const visitors = await db.visitors.bulkCreate(visitorsData, {
transaction,
});
// For each item created, replace relation files
for (let i = 0; i < visitors.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.visitors.getTableName(),
belongsToColumn: 'photo',
belongsToId: visitors[i].id,
},
data[i].photo,
options,
);
}
return visitors;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const visitors = await db.visitors.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.purpose !== undefined) updatePayload.purpose = data.purpose;
if (data.check_in_time !== undefined)
updatePayload.check_in_time = data.check_in_time;
if (data.check_out_time !== undefined)
updatePayload.check_out_time = data.check_out_time;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.badge_id !== undefined) updatePayload.badge_id = data.badge_id;
updatePayload.updatedById = currentUser.id;
await visitors.update(updatePayload, { transaction });
if (data.host !== undefined) {
await visitors.setHost(
data.host,
{ transaction },
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.visitors.getTableName(),
belongsToColumn: 'photo',
belongsToId: visitors.id,
},
data.photo,
options,
);
return visitors;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const visitors = await db.visitors.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of visitors) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of visitors) {
await record.destroy({ transaction });
}
});
return visitors;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const visitors = await db.visitors.findByPk(id, options);
await visitors.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await visitors.destroy({
transaction,
});
return visitors;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const visitors = await db.visitors.findOne({ where }, { transaction });
if (!visitors) {
return visitors;
}
const output = visitors.get({ plain: true });
output.pre_registrations_visitor =
await visitors.getPre_registrations_visitor({
transaction,
});
output.host = await visitors.getHost({
transaction,
});
output.photo = await visitors.getPhoto({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.employees,
as: 'host',
where: filter.host
? {
[Op.or]: [
{
id: {
[Op.in]: filter.host
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
name: {
[Op.or]: filter.host
.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.full_name) {
where = {
...where,
[Op.and]: Utils.ilike('visitors', 'full_name', filter.full_name),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike('visitors', 'email', filter.email),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike('visitors', 'phone', filter.phone),
};
}
if (filter.purpose) {
where = {
...where,
[Op.and]: Utils.ilike('visitors', 'purpose', filter.purpose),
};
}
if (filter.badge_id) {
where = {
...where,
[Op.and]: Utils.ilike('visitors', 'badge_id', filter.badge_id),
};
}
if (filter.check_in_timeRange) {
const [start, end] = filter.check_in_timeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
check_in_time: {
...where.check_in_time,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
check_in_time: {
...where.check_in_time,
[Op.lte]: end,
},
};
}
}
if (filter.check_out_timeRange) {
const [start, end] = filter.check_out_timeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
check_out_time: {
...where.check_out_time,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
check_out_time: {
...where.check_out_time,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
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,
},
};
}
}
}
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.visitors.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) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('visitors', 'full_name', query),
],
};
}
const records = await db.visitors.findAll({
attributes: ['id', 'full_name'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['full_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.full_name,
}));
}
};