38035-vm/backend/src/db/api/plantings.js
2026-01-31 15:17:52 +00:00

695 lines
17 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 PlantingsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const plantings = await db.plantings.create(
{
id: data.id || undefined,
date_planted: data.date_planted
||
null
,
expected_harvest_date: data.expected_harvest_date
||
null
,
area_planted: data.area_planted
||
null
,
seed_variety: data.seed_variety
||
null
,
seed_rate: data.seed_rate
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await plantings.setField( data.field || null, {
transaction,
});
await plantings.setCrop( data.crop || null, {
transaction,
});
await plantings.setPlanted_by( data.planted_by || null, {
transaction,
});
await plantings.setOrganizations( data.organizations || null, {
transaction,
});
return plantings;
}
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 plantingsData = data.map((item, index) => ({
id: item.id || undefined,
date_planted: item.date_planted
||
null
,
expected_harvest_date: item.expected_harvest_date
||
null
,
area_planted: item.area_planted
||
null
,
seed_variety: item.seed_variety
||
null
,
seed_rate: item.seed_rate
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const plantings = await db.plantings.bulkCreate(plantingsData, { transaction });
// For each item created, replace relation files
return plantings;
}
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 plantings = await db.plantings.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.date_planted !== undefined) updatePayload.date_planted = data.date_planted;
if (data.expected_harvest_date !== undefined) updatePayload.expected_harvest_date = data.expected_harvest_date;
if (data.area_planted !== undefined) updatePayload.area_planted = data.area_planted;
if (data.seed_variety !== undefined) updatePayload.seed_variety = data.seed_variety;
if (data.seed_rate !== undefined) updatePayload.seed_rate = data.seed_rate;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await plantings.update(updatePayload, {transaction});
if (data.field !== undefined) {
await plantings.setField(
data.field,
{ transaction }
);
}
if (data.crop !== undefined) {
await plantings.setCrop(
data.crop,
{ transaction }
);
}
if (data.planted_by !== undefined) {
await plantings.setPlanted_by(
data.planted_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await plantings.setOrganizations(
data.organizations,
{ transaction }
);
}
return plantings;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const plantings = await db.plantings.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of plantings) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of plantings) {
await record.destroy({transaction});
}
});
return plantings;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const plantings = await db.plantings.findByPk(id, options);
await plantings.update({
deletedBy: currentUser.id
}, {
transaction,
});
await plantings.destroy({
transaction
});
return plantings;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const plantings = await db.plantings.findOne(
{ where },
{ transaction },
);
if (!plantings) {
return plantings;
}
const output = plantings.get({plain: true});
output.field = await plantings.getField({
transaction
});
output.crop = await plantings.getCrop({
transaction
});
output.planted_by = await plantings.getPlanted_by({
transaction
});
output.organizations = await plantings.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.fields,
as: 'field',
where: filter.field ? {
[Op.or]: [
{ id: { [Op.in]: filter.field.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.field.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.crops,
as: 'crop',
where: filter.crop ? {
[Op.or]: [
{ id: { [Op.in]: filter.crop.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.crop.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'planted_by',
where: filter.planted_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.planted_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.planted_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.seed_variety) {
where = {
...where,
[Op.and]: Utils.ilike(
'plantings',
'seed_variety',
filter.seed_variety,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'plantings',
'notes',
filter.notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
date_planted: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
expected_harvest_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.date_plantedRange) {
const [start, end] = filter.date_plantedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
date_planted: {
...where.date_planted,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
date_planted: {
...where.date_planted,
[Op.lte]: end,
},
};
}
}
if (filter.expected_harvest_dateRange) {
const [start, end] = filter.expected_harvest_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expected_harvest_date: {
...where.expected_harvest_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expected_harvest_date: {
...where.expected_harvest_date,
[Op.lte]: end,
},
};
}
}
if (filter.area_plantedRange) {
const [start, end] = filter.area_plantedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
area_planted: {
...where.area_planted,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
area_planted: {
...where.area_planted,
[Op.lte]: end,
},
};
}
}
if (filter.seed_rateRange) {
const [start, end] = filter.seed_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
seed_rate: {
...where.seed_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
seed_rate: {
...where.seed_rate,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.plantings.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(
'plantings',
'seed_variety',
query,
),
],
};
}
const records = await db.plantings.findAll({
attributes: [ 'id', 'seed_variety' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['seed_variety', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.seed_variety,
}));
}
};