30262/backend/src/db/api/movimentacoes.js
2025-03-28 15:12:17 +00:00

500 lines
12 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 MovimentacoesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const movimentacoes = await db.movimentacoes.create(
{
id: data.id || undefined,
quantidade: data.quantidade || null,
tipo: data.tipo || null,
data: data.data || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await movimentacoes.setItem(data.item || null, {
transaction,
});
await movimentacoes.setSub_estoque_origem(data.sub_estoque_origem || null, {
transaction,
});
await movimentacoes.setSub_estoque_destino(
data.sub_estoque_destino || null,
{
transaction,
},
);
await movimentacoes.setLocalidade(data.localidade || null, {
transaction,
});
return movimentacoes;
}
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 movimentacoesData = data.map((item, index) => ({
id: item.id || undefined,
quantidade: item.quantidade || null,
tipo: item.tipo || null,
data: item.data || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const movimentacoes = await db.movimentacoes.bulkCreate(movimentacoesData, {
transaction,
});
// For each item created, replace relation files
return movimentacoes;
}
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 movimentacoes = await db.movimentacoes.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
if (data.quantidade !== undefined)
updatePayload.quantidade = data.quantidade;
if (data.tipo !== undefined) updatePayload.tipo = data.tipo;
if (data.data !== undefined) updatePayload.data = data.data;
updatePayload.updatedById = currentUser.id;
await movimentacoes.update(updatePayload, { transaction });
if (data.item !== undefined) {
await movimentacoes.setItem(
data.item,
{ transaction },
);
}
if (data.sub_estoque_origem !== undefined) {
await movimentacoes.setSub_estoque_origem(
data.sub_estoque_origem,
{ transaction },
);
}
if (data.sub_estoque_destino !== undefined) {
await movimentacoes.setSub_estoque_destino(
data.sub_estoque_destino,
{ transaction },
);
}
if (data.localidade !== undefined) {
await movimentacoes.setLocalidade(
data.localidade,
{ transaction },
);
}
return movimentacoes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const movimentacoes = await db.movimentacoes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of movimentacoes) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of movimentacoes) {
await record.destroy({ transaction });
}
});
return movimentacoes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const movimentacoes = await db.movimentacoes.findByPk(id, options);
await movimentacoes.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await movimentacoes.destroy({
transaction,
});
return movimentacoes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const movimentacoes = await db.movimentacoes.findOne(
{ where },
{ transaction },
);
if (!movimentacoes) {
return movimentacoes;
}
const output = movimentacoes.get({ plain: true });
output.item = await movimentacoes.getItem({
transaction,
});
output.sub_estoque_origem = await movimentacoes.getSub_estoque_origem({
transaction,
});
output.sub_estoque_destino = await movimentacoes.getSub_estoque_destino({
transaction,
});
output.localidade = await movimentacoes.getLocalidade({
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 userLocalidade = (user && user.localidade?.id) || null;
if (userLocalidade) {
if (options?.currentUser?.localidadeId) {
where.localidadeId = options.currentUser.localidadeId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.itens,
as: 'item',
where: filter.item
? {
[Op.or]: [
{
id: {
[Op.in]: filter.item
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
nome: {
[Op.or]: filter.item
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.sub_estoques,
as: 'sub_estoque_origem',
where: filter.sub_estoque_origem
? {
[Op.or]: [
{
id: {
[Op.in]: filter.sub_estoque_origem
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
name: {
[Op.or]: filter.sub_estoque_origem
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.sub_estoques,
as: 'sub_estoque_destino',
where: filter.sub_estoque_destino
? {
[Op.or]: [
{
id: {
[Op.in]: filter.sub_estoque_destino
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
name: {
[Op.or]: filter.sub_estoque_destino
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.localidade,
as: 'localidade',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.quantidadeRange) {
const [start, end] = filter.quantidadeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantidade: {
...where.quantidade,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantidade: {
...where.quantidade,
[Op.lte]: end,
},
};
}
}
if (filter.dataRange) {
const [start, end] = filter.dataRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
data: {
...where.data,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
data: {
...where.data,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.tipo) {
where = {
...where,
tipo: filter.tipo,
};
}
if (filter.localidade) {
const listItems = filter.localidade.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
localidadeId: { [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.localidadeId;
}
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.movimentacoes.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('movimentacoes', 'tipo', query),
],
};
}
const records = await db.movimentacoes.findAll({
attributes: ['id', 'tipo'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['tipo', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.tipo,
}));
}
};