39541-vm/backend/src/db/api/trip_events.js
2026-04-10 08:24:28 +00:00

585 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 Trip_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const trip_events = await db.trip_events.create(
{
id: data.id || undefined,
event_type: data.event_type
||
null
,
event_at: data.event_at
||
null
,
description: data.description
||
null
,
latitude: data.latitude
||
null
,
longitude: data.longitude
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await trip_events.setTrip( data.trip || null, {
transaction,
});
await trip_events.setReported_by( data.reported_by || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.trip_events.getTableName(),
belongsToColumn: 'attachments',
belongsToId: trip_events.id,
},
data.attachments,
options,
);
return trip_events;
}
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 trip_eventsData = data.map((item, index) => ({
id: item.id || undefined,
event_type: item.event_type
||
null
,
event_at: item.event_at
||
null
,
description: item.description
||
null
,
latitude: item.latitude
||
null
,
longitude: item.longitude
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const trip_events = await db.trip_events.bulkCreate(trip_eventsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < trip_events.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.trip_events.getTableName(),
belongsToColumn: 'attachments',
belongsToId: trip_events[i].id,
},
data[i].attachments,
options,
);
}
return trip_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const trip_events = await db.trip_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.event_type !== undefined) updatePayload.event_type = data.event_type;
if (data.event_at !== undefined) updatePayload.event_at = data.event_at;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.latitude !== undefined) updatePayload.latitude = data.latitude;
if (data.longitude !== undefined) updatePayload.longitude = data.longitude;
updatePayload.updatedById = currentUser.id;
await trip_events.update(updatePayload, {transaction});
if (data.trip !== undefined) {
await trip_events.setTrip(
data.trip,
{ transaction }
);
}
if (data.reported_by !== undefined) {
await trip_events.setReported_by(
data.reported_by,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.trip_events.getTableName(),
belongsToColumn: 'attachments',
belongsToId: trip_events.id,
},
data.attachments,
options,
);
return trip_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const trip_events = await db.trip_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of trip_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of trip_events) {
await record.destroy({transaction});
}
});
return trip_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const trip_events = await db.trip_events.findByPk(id, options);
await trip_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await trip_events.destroy({
transaction
});
return trip_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const trip_events = await db.trip_events.findOne(
{ where },
{ transaction },
);
if (!trip_events) {
return trip_events;
}
const output = trip_events.get({plain: true});
output.trip = await trip_events.getTrip({
transaction
});
output.reported_by = await trip_events.getReported_by({
transaction
});
output.attachments = await trip_events.getAttachments({
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 = [
{
model: db.trips,
as: 'trip',
where: filter.trip ? {
[Op.or]: [
{ id: { [Op.in]: filter.trip.split('|').map(term => Utils.uuid(term)) } },
{
trip_code: {
[Op.or]: filter.trip.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'reported_by',
where: filter.reported_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.reported_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.reported_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'trip_events',
'description',
filter.description,
),
};
}
if (filter.event_atRange) {
const [start, end] = filter.event_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
event_at: {
...where.event_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
event_at: {
...where.event_at,
[Op.lte]: end,
},
};
}
}
if (filter.latitudeRange) {
const [start, end] = filter.latitudeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
latitude: {
...where.latitude,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
latitude: {
...where.latitude,
[Op.lte]: end,
},
};
}
}
if (filter.longitudeRange) {
const [start, end] = filter.longitudeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
longitude: {
...where.longitude,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
longitude: {
...where.longitude,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.event_type) {
where = {
...where,
event_type: filter.event_type,
};
}
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.trip_events.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(
'trip_events',
'event_type',
query,
),
],
};
}
const records = await db.trip_events.findAll({
attributes: [ 'id', 'event_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['event_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.event_type,
}));
}
};