2026-01-26 21:17:39 +00:00

580 lines
14 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 SalesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const sales = await db.sales.create(
{
id: data.id || undefined,
document_number: data.document_number
||
null
,
sale_date: data.sale_date
||
null
,
delivery_date: data.delivery_date
||
null
,
customer_name: data.customer_name
||
null
,
total: data.total
||
null
,
profit: data.profit
||
null
,
status: data.status
||
null
,
creado_por: data.creado_por
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
if (data.sale_items && data.sale_items.length > 0) {
for (const item of data.sale_items) {
await db.sale_items.create({
...item,
saleId: sales.id,
createdById: currentUser.id,
updatedById: currentUser.id,
}, { transaction });
}
}
return sales;
}
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 salesData = data.map((item, index) => ({
id: item.id || undefined,
document_number: item.document_number
||
null
,
sale_date: item.sale_date
||
null
,
delivery_date: item.delivery_date
||
null
,
customer_name: item.customer_name
||
null
,
total: item.total
||
null
,
profit: item.profit
||
null
,
status: item.status
||
null
,
creado_por: item.creado_por
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const sales = await db.sales.bulkCreate(salesData, { transaction });
// For each item created, replace relation files
return sales;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const sales = await db.sales.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.document_number !== undefined) updatePayload.document_number = data.document_number;
if (data.sale_date !== undefined) updatePayload.sale_date = data.sale_date;
if (data.delivery_date !== undefined) updatePayload.delivery_date = data.delivery_date;
if (data.customer_name !== undefined) updatePayload.customer_name = data.customer_name;
if (data.total !== undefined) updatePayload.total = data.total;
if (data.profit !== undefined) updatePayload.profit = data.profit;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.creado_por !== undefined) updatePayload.creado_por = data.creado_por;
updatePayload.updatedById = currentUser.id;
await sales.update(updatePayload, {transaction});
return sales;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const sales = await db.sales.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of sales) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of sales) {
await record.destroy({transaction});
}
});
return sales;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const sales = await db.sales.findByPk(id, options);
await sales.update({
deletedBy: currentUser.id
}, {
transaction,
});
await sales.destroy({
transaction
});
return sales;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const sales = await db.sales.findOne(
{ where },
{ transaction },
);
if (!sales) {
return sales;
}
const output = sales.get({plain: true});
output.sale_items_sale = await sales.getSale_items_sale({
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 = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.document_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'sales',
'document_number',
filter.document_number,
),
};
}
if (filter.customer_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'sales',
'customer_name',
filter.customer_name,
),
};
}
if (filter.creado_por) {
where = {
...where,
[Op.and]: Utils.ilike(
'sales',
'creado_por',
filter.creado_por,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
sale_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
delivery_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.sale_dateRange) {
const [start, end] = filter.sale_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sale_date: {
...where.sale_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sale_date: {
...where.sale_date,
[Op.lte]: end,
},
};
}
}
if (filter.delivery_dateRange) {
const [start, end] = filter.delivery_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
delivery_date: {
...where.delivery_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
delivery_date: {
...where.delivery_date,
[Op.lte]: end,
},
};
}
}
if (filter.totalRange) {
const [start, end] = filter.totalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total: {
...where.total,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total: {
...where.total,
[Op.lte]: end,
},
};
}
}
if (filter.profitRange) {
const [start, end] = filter.profitRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
profit: {
...where.profit,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
profit: {
...where.profit,
[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.sales.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(
'sales',
'document_number',
query,
),
],
};
}
const records = await db.sales.findAll({
attributes: [ 'id', 'document_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['document_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.document_number,
}));
}
};