29708/backend/src/db/api/food_distributions.js
2025-03-08 00:53:58 +00:00

443 lines
11 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 Food_distributionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const food_distributions = await db.food_distributions.create(
{
id: data.id || undefined,
distribution_date: data.distribution_date || null,
details: data.details || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await food_distributions.setHealth_official(data.health_official || null, {
transaction,
});
await food_distributions.setCommunity(data.community || null, {
transaction,
});
await food_distributions.setCommunities(data.communities || null, {
transaction,
});
return food_distributions;
}
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 food_distributionsData = data.map((item, index) => ({
id: item.id || undefined,
distribution_date: item.distribution_date || null,
details: item.details || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const food_distributions = await db.food_distributions.bulkCreate(
food_distributionsData,
{ transaction },
);
// For each item created, replace relation files
return food_distributions;
}
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 food_distributions = await db.food_distributions.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
if (data.distribution_date !== undefined)
updatePayload.distribution_date = data.distribution_date;
if (data.details !== undefined) updatePayload.details = data.details;
updatePayload.updatedById = currentUser.id;
await food_distributions.update(updatePayload, { transaction });
if (data.health_official !== undefined) {
await food_distributions.setHealth_official(
data.health_official,
{ transaction },
);
}
if (data.community !== undefined) {
await food_distributions.setCommunity(
data.community,
{ transaction },
);
}
if (data.communities !== undefined) {
await food_distributions.setCommunities(
data.communities,
{ transaction },
);
}
return food_distributions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const food_distributions = await db.food_distributions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of food_distributions) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of food_distributions) {
await record.destroy({ transaction });
}
});
return food_distributions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const food_distributions = await db.food_distributions.findByPk(
id,
options,
);
await food_distributions.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await food_distributions.destroy({
transaction,
});
return food_distributions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const food_distributions = await db.food_distributions.findOne(
{ where },
{ transaction },
);
if (!food_distributions) {
return food_distributions;
}
const output = food_distributions.get({ plain: true });
output.health_official = await food_distributions.getHealth_official({
transaction,
});
output.community = await food_distributions.getCommunity({
transaction,
});
output.communities = await food_distributions.getCommunities({
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 userCommunities = (user && user.communities?.id) || null;
if (userCommunities) {
if (options?.currentUser?.communitiesId) {
where.communitiesId = options.currentUser.communitiesId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'health_official',
where: filter.health_official
? {
[Op.or]: [
{
id: {
[Op.in]: filter.health_official
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
firstName: {
[Op.or]: filter.health_official
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.communities,
as: 'community',
},
{
model: db.communities,
as: 'communities',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.details) {
where = {
...where,
[Op.and]: Utils.ilike(
'food_distributions',
'details',
filter.details,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
distribution_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
distribution_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.distribution_dateRange) {
const [start, end] = filter.distribution_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
distribution_date: {
...where.distribution_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
distribution_date: {
...where.distribution_date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.community) {
const listItems = filter.community.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
communityId: { [Op.or]: listItems },
};
}
if (filter.communities) {
const listItems = filter.communities.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
communitiesId: { [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.communitiesId;
}
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.food_distributions.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('food_distributions', 'details', query),
],
};
}
const records = await db.food_distributions.findAll({
attributes: ['id', 'details'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['details', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.details,
}));
}
};