30243/backend/src/db/api/applications.js
2025-03-27 16:27:47 +00:00

457 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 ApplicationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const applications = await db.applications.create(
{
id: data.id || undefined,
application_letter: data.application_letter || null,
cbt_score: data.cbt_score || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await applications.setUser(data.user || null, {
transaction,
});
await applications.setJob_opportunity(data.job_opportunity || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.applications.getTableName(),
belongsToColumn: 'resume',
belongsToId: applications.id,
},
data.resume,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.applications.getTableName(),
belongsToColumn: 'cover_letter',
belongsToId: applications.id,
},
data.cover_letter,
options,
);
return applications;
}
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 applicationsData = data.map((item, index) => ({
id: item.id || undefined,
application_letter: item.application_letter || null,
cbt_score: item.cbt_score || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const applications = await db.applications.bulkCreate(applicationsData, {
transaction,
});
// For each item created, replace relation files
for (let i = 0; i < applications.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.applications.getTableName(),
belongsToColumn: 'resume',
belongsToId: applications[i].id,
},
data[i].resume,
options,
);
}
for (let i = 0; i < applications.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.applications.getTableName(),
belongsToColumn: 'cover_letter',
belongsToId: applications[i].id,
},
data[i].cover_letter,
options,
);
}
return applications;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const applications = await db.applications.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
if (data.application_letter !== undefined)
updatePayload.application_letter = data.application_letter;
if (data.cbt_score !== undefined) updatePayload.cbt_score = data.cbt_score;
updatePayload.updatedById = currentUser.id;
await applications.update(updatePayload, { transaction });
if (data.user !== undefined) {
await applications.setUser(
data.user,
{ transaction },
);
}
if (data.job_opportunity !== undefined) {
await applications.setJob_opportunity(
data.job_opportunity,
{ transaction },
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.applications.getTableName(),
belongsToColumn: 'resume',
belongsToId: applications.id,
},
data.resume,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.applications.getTableName(),
belongsToColumn: 'cover_letter',
belongsToId: applications.id,
},
data.cover_letter,
options,
);
return applications;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const applications = await db.applications.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of applications) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of applications) {
await record.destroy({ transaction });
}
});
return applications;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const applications = await db.applications.findByPk(id, options);
await applications.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await applications.destroy({
transaction,
});
return applications;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const applications = await db.applications.findOne(
{ where },
{ transaction },
);
if (!applications) {
return applications;
}
const output = applications.get({ plain: true });
output.user = await applications.getUser({
transaction,
});
output.job_opportunity = await applications.getJob_opportunity({
transaction,
});
output.resume = await applications.getResume({
transaction,
});
output.cover_letter = await applications.getCover_letter({
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.users,
as: 'user',
where: filter.user
? {
[Op.or]: [
{
id: {
[Op.in]: filter.user
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
firstName: {
[Op.or]: filter.user
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.job_opportunities,
as: 'job_opportunity',
where: filter.job_opportunity
? {
[Op.or]: [
{
id: {
[Op.in]: filter.job_opportunity
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
title: {
[Op.or]: filter.job_opportunity
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.file,
as: 'resume',
},
{
model: db.file,
as: 'cover_letter',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.application_letter) {
where = {
...where,
[Op.and]: Utils.ilike(
'applications',
'application_letter',
filter.application_letter,
),
};
}
if (filter.cbt_scoreRange) {
const [start, end] = filter.cbt_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cbt_score: {
...where.cbt_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cbt_score: {
...where.cbt_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
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.applications.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('applications', 'application_letter', query),
],
};
}
const records = await db.applications.findAll({
attributes: ['id', 'application_letter'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['application_letter', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.application_letter,
}));
}
};