30632/backend/src/db/api/vehicles.js
2025-04-11 03:50:00 +00:00

414 lines
9.7 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 VehiclesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vehicles = await db.vehicles.create(
{
id: data.id || undefined,
make: data.make || null,
model: data.model || null,
year: data.year || null,
registration: data.registration || null,
vin: data.vin || null,
notes: data.notes || null,
is_primary: data.is_primary || false,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await vehicles.setClient(data.client || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.vehicles.getTableName(),
belongsToColumn: 'vehicle_image',
belongsToId: vehicles.id,
},
data.vehicle_image,
options,
);
return vehicles;
}
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 vehiclesData = data.map((item, index) => ({
id: item.id || undefined,
make: item.make || null,
model: item.model || null,
year: item.year || null,
registration: item.registration || null,
vin: item.vin || null,
notes: item.notes || null,
is_primary: item.is_primary || false,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const vehicles = await db.vehicles.bulkCreate(vehiclesData, {
transaction,
});
// For each item created, replace relation files
for (let i = 0; i < vehicles.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.vehicles.getTableName(),
belongsToColumn: 'vehicle_image',
belongsToId: vehicles[i].id,
},
data[i].vehicle_image,
options,
);
}
return vehicles;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vehicles = await db.vehicles.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.make !== undefined) updatePayload.make = data.make;
if (data.model !== undefined) updatePayload.model = data.model;
if (data.year !== undefined) updatePayload.year = data.year;
if (data.registration !== undefined)
updatePayload.registration = data.registration;
if (data.vin !== undefined) updatePayload.vin = data.vin;
if (data.notes !== undefined) updatePayload.notes = data.notes;
if (data.is_primary !== undefined)
updatePayload.is_primary = data.is_primary;
updatePayload.updatedById = currentUser.id;
await vehicles.update(updatePayload, { transaction });
if (data.client !== undefined) {
await vehicles.setClient(
data.client,
{ transaction },
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.vehicles.getTableName(),
belongsToColumn: 'vehicle_image',
belongsToId: vehicles.id,
},
data.vehicle_image,
options,
);
return vehicles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vehicles = await db.vehicles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of vehicles) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of vehicles) {
await record.destroy({ transaction });
}
});
return vehicles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vehicles = await db.vehicles.findByPk(id, options);
await vehicles.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await vehicles.destroy({
transaction,
});
return vehicles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const vehicles = await db.vehicles.findOne({ where }, { transaction });
if (!vehicles) {
return vehicles;
}
const output = vehicles.get({ plain: true });
output.jobs_vehicle = await vehicles.getJobs_vehicle({
transaction,
});
output.requests_vehicle = await vehicles.getRequests_vehicle({
transaction,
});
output.client = await vehicles.getClient({
transaction,
});
output.vehicle_image = await vehicles.getVehicle_image({
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.clients,
as: 'client',
where: filter.client
? {
[Op.or]: [
{
id: {
[Op.in]: filter.client
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
name: {
[Op.or]: filter.client
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.file,
as: 'vehicle_image',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.make) {
where = {
...where,
[Op.and]: Utils.ilike('vehicles', 'make', filter.make),
};
}
if (filter.model) {
where = {
...where,
[Op.and]: Utils.ilike('vehicles', 'model', filter.model),
};
}
if (filter.year) {
where = {
...where,
[Op.and]: Utils.ilike('vehicles', 'year', filter.year),
};
}
if (filter.registration) {
where = {
...where,
[Op.and]: Utils.ilike(
'vehicles',
'registration',
filter.registration,
),
};
}
if (filter.vin) {
where = {
...where,
[Op.and]: Utils.ilike('vehicles', 'vin', filter.vin),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike('vehicles', 'notes', filter.notes),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.is_primary) {
where = {
...where,
is_primary: filter.is_primary,
};
}
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.vehicles.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('vehicles', 'make', query),
],
};
}
const records = await db.vehicles.findAll({
attributes: ['id', 'make'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['make', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.make,
}));
}
};