31442/backend/src/db/api/annonces.js
2025-05-12 09:39:45 +00:00

393 lines
9.5 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 AnnoncesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const annonces = await db.annonces.create(
{
id: data.id || undefined,
adresse: data.adresse || null,
loyer: data.loyer || null,
description: data.description || null,
conditions: data.conditions || null,
date_creation: data.date_creation || null,
active: data.active || false,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await annonces.setUtilisateur(data.utilisateur || null, {
transaction,
});
return annonces;
}
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 annoncesData = data.map((item, index) => ({
id: item.id || undefined,
adresse: item.adresse || null,
loyer: item.loyer || null,
description: item.description || null,
conditions: item.conditions || null,
date_creation: item.date_creation || null,
active: item.active || false,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const annonces = await db.annonces.bulkCreate(annoncesData, {
transaction,
});
// For each item created, replace relation files
return annonces;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const annonces = await db.annonces.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.adresse !== undefined) updatePayload.adresse = data.adresse;
if (data.loyer !== undefined) updatePayload.loyer = data.loyer;
if (data.description !== undefined)
updatePayload.description = data.description;
if (data.conditions !== undefined)
updatePayload.conditions = data.conditions;
if (data.date_creation !== undefined)
updatePayload.date_creation = data.date_creation;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await annonces.update(updatePayload, { transaction });
if (data.utilisateur !== undefined) {
await annonces.setUtilisateur(
data.utilisateur,
{ transaction },
);
}
return annonces;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const annonces = await db.annonces.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of annonces) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of annonces) {
await record.destroy({ transaction });
}
});
return annonces;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const annonces = await db.annonces.findByPk(id, options);
await annonces.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await annonces.destroy({
transaction,
});
return annonces;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const annonces = await db.annonces.findOne({ where }, { transaction });
if (!annonces) {
return annonces;
}
const output = annonces.get({ plain: true });
output.candidatures_annonce = await annonces.getCandidatures_annonce({
transaction,
});
output.photos_annonce_annonce = await annonces.getPhotos_annonce_annonce({
transaction,
});
output.utilisateur = await annonces.getUtilisateur({
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.utilisateurs,
as: 'utilisateur',
where: filter.utilisateur
? {
[Op.or]: [
{
id: {
[Op.in]: filter.utilisateur
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
nom: {
[Op.or]: filter.utilisateur
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.adresse) {
where = {
...where,
[Op.and]: Utils.ilike('annonces', 'adresse', filter.adresse),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike('annonces', 'description', filter.description),
};
}
if (filter.conditions) {
where = {
...where,
[Op.and]: Utils.ilike('annonces', 'conditions', filter.conditions),
};
}
if (filter.loyerRange) {
const [start, end] = filter.loyerRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
loyer: {
...where.loyer,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
loyer: {
...where.loyer,
[Op.lte]: end,
},
};
}
}
if (filter.date_creationRange) {
const [start, end] = filter.date_creationRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
date_creation: {
...where.date_creation,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
date_creation: {
...where.date_creation,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
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.annonces.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('annonces', 'adresse', query),
],
};
}
const records = await db.annonces.findAll({
attributes: ['id', 'adresse'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['adresse', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.adresse,
}));
}
};