31342/backend/src/db/api/milk_collections.js
2025-05-08 11:07:55 +00:00

492 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 Milk_collectionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const milk_collections = await db.milk_collections.create(
{
id: data.id || undefined,
collection_date: data.collection_date || null,
quantity: data.quantity || null,
price_per_liter: data.price_per_liter || null,
total_value: data.total_value || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await milk_collections.setMember(data.member || null, {
transaction,
});
await milk_collections.setSavingcooperative(
data.savingcooperative || null,
{
transaction,
},
);
return milk_collections;
}
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 milk_collectionsData = data.map((item, index) => ({
id: item.id || undefined,
collection_date: item.collection_date || null,
quantity: item.quantity || null,
price_per_liter: item.price_per_liter || null,
total_value: item.total_value || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const milk_collections = await db.milk_collections.bulkCreate(
milk_collectionsData,
{ transaction },
);
// For each item created, replace relation files
return milk_collections;
}
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 milk_collections = await db.milk_collections.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
if (data.collection_date !== undefined)
updatePayload.collection_date = data.collection_date;
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.price_per_liter !== undefined)
updatePayload.price_per_liter = data.price_per_liter;
if (data.total_value !== undefined)
updatePayload.total_value = data.total_value;
updatePayload.updatedById = currentUser.id;
await milk_collections.update(updatePayload, { transaction });
if (data.member !== undefined) {
await milk_collections.setMember(
data.member,
{ transaction },
);
}
if (data.savingcooperative !== undefined) {
await milk_collections.setSavingcooperative(
data.savingcooperative,
{ transaction },
);
}
return milk_collections;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const milk_collections = await db.milk_collections.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of milk_collections) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of milk_collections) {
await record.destroy({ transaction });
}
});
return milk_collections;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const milk_collections = await db.milk_collections.findByPk(id, options);
await milk_collections.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await milk_collections.destroy({
transaction,
});
return milk_collections;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const milk_collections = await db.milk_collections.findOne(
{ where },
{ transaction },
);
if (!milk_collections) {
return milk_collections;
}
const output = milk_collections.get({ plain: true });
output.member = await milk_collections.getMember({
transaction,
});
output.savingcooperative = await milk_collections.getSavingcooperative({
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 userSavingcooperative = (user && user.SavingCooperative?.id) || null;
if (userSavingcooperative) {
if (options?.currentUser?.SavingCooperativeId) {
where.SavingCooperativeId = options.currentUser.SavingCooperativeId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.members,
as: 'member',
where: filter.member
? {
[Op.or]: [
{
id: {
[Op.in]: filter.member
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
first_name: {
[Op.or]: filter.member
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.savingcooperative,
as: 'savingcooperative',
where: filter.savingcooperative
? {
[Op.or]: [
{
id: {
[Op.in]: filter.savingcooperative
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
name: {
[Op.or]: filter.savingcooperative
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
collection_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
collection_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.collection_dateRange) {
const [start, end] = filter.collection_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
collection_date: {
...where.collection_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
collection_date: {
...where.collection_date,
[Op.lte]: end,
},
};
}
}
if (filter.quantityRange) {
const [start, end] = filter.quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.lte]: end,
},
};
}
}
if (filter.price_per_literRange) {
const [start, end] = filter.price_per_literRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price_per_liter: {
...where.price_per_liter,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price_per_liter: {
...where.price_per_liter,
[Op.lte]: end,
},
};
}
}
if (filter.total_valueRange) {
const [start, end] = filter.total_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_value: {
...where.total_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_value: {
...where.total_value,
[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,
},
};
}
}
}
if (globalAccess) {
delete where.SavingCooperativeId;
}
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.milk_collections.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('milk_collections', 'collection_date', query),
],
};
}
const records = await db.milk_collections.findAll({
attributes: ['id', 'collection_date'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['collection_date', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.collection_date,
}));
}
};