31706/backend/src/db/api/disposals.js
2025-05-22 11:21:28 +00:00

331 lines
8.0 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 DisposalsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const disposals = await db.disposals.create(
{
id: data.id || undefined,
disposal_date: data.disposal_date || null,
method: data.method || null,
condition: data.condition || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await disposals.setAsset(data.asset || null, {
transaction,
});
return disposals;
}
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 disposalsData = data.map((item, index) => ({
id: item.id || undefined,
disposal_date: item.disposal_date || null,
method: item.method || null,
condition: item.condition || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const disposals = await db.disposals.bulkCreate(disposalsData, {
transaction,
});
// For each item created, replace relation files
return disposals;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const disposals = await db.disposals.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.disposal_date !== undefined)
updatePayload.disposal_date = data.disposal_date;
if (data.method !== undefined) updatePayload.method = data.method;
if (data.condition !== undefined) updatePayload.condition = data.condition;
updatePayload.updatedById = currentUser.id;
await disposals.update(updatePayload, { transaction });
if (data.asset !== undefined) {
await disposals.setAsset(
data.asset,
{ transaction },
);
}
return disposals;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const disposals = await db.disposals.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of disposals) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of disposals) {
await record.destroy({ transaction });
}
});
return disposals;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const disposals = await db.disposals.findByPk(id, options);
await disposals.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await disposals.destroy({
transaction,
});
return disposals;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const disposals = await db.disposals.findOne({ where }, { transaction });
if (!disposals) {
return disposals;
}
const output = disposals.get({ plain: true });
output.asset = await disposals.getAsset({
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.assets,
as: 'asset',
where: filter.asset
? {
[Op.or]: [
{
id: {
[Op.in]: filter.asset
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
name: {
[Op.or]: filter.asset
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.method) {
where = {
...where,
[Op.and]: Utils.ilike('disposals', 'method', filter.method),
};
}
if (filter.condition) {
where = {
...where,
[Op.and]: Utils.ilike('disposals', 'condition', filter.condition),
};
}
if (filter.disposal_dateRange) {
const [start, end] = filter.disposal_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
disposal_date: {
...where.disposal_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
disposal_date: {
...where.disposal_date,
[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.disposals.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('disposals', 'method', query),
],
};
}
const records = await db.disposals.findAll({
attributes: ['id', 'method'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['method', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.method,
}));
}
};