40205-vm/backend/src/db/api/drivers.js
2026-06-04 18:06:41 +00:00

693 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 DriversDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const drivers = await db.drivers.create(
{
id: data.id || undefined,
name: data.name
||
null
,
phone: data.phone
||
null
,
national_id: data.national_id
||
null
,
vehicle_type: data.vehicle_type
||
null
,
online_status: data.online_status
||
null
,
current_lat: data.current_lat
||
null
,
current_lng: data.current_lng
||
null
,
balance_owed: data.balance_owed
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await drivers.setUser( data.user || null, {
transaction,
});
await drivers.setAssigned_city( data.assigned_city || null, {
transaction,
});
await drivers.setAssigned_region( data.assigned_region || null, {
transaction,
});
return drivers;
}
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 driversData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
phone: item.phone
||
null
,
national_id: item.national_id
||
null
,
vehicle_type: item.vehicle_type
||
null
,
online_status: item.online_status
||
null
,
current_lat: item.current_lat
||
null
,
current_lng: item.current_lng
||
null
,
balance_owed: item.balance_owed
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const drivers = await db.drivers.bulkCreate(driversData, { transaction });
// For each item created, replace relation files
return drivers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const drivers = await db.drivers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.national_id !== undefined) updatePayload.national_id = data.national_id;
if (data.vehicle_type !== undefined) updatePayload.vehicle_type = data.vehicle_type;
if (data.online_status !== undefined) updatePayload.online_status = data.online_status;
if (data.current_lat !== undefined) updatePayload.current_lat = data.current_lat;
if (data.current_lng !== undefined) updatePayload.current_lng = data.current_lng;
if (data.balance_owed !== undefined) updatePayload.balance_owed = data.balance_owed;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await drivers.update(updatePayload, {transaction});
if (data.user !== undefined) {
await drivers.setUser(
data.user,
{ transaction }
);
}
if (data.assigned_city !== undefined) {
await drivers.setAssigned_city(
data.assigned_city,
{ transaction }
);
}
if (data.assigned_region !== undefined) {
await drivers.setAssigned_region(
data.assigned_region,
{ transaction }
);
}
return drivers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const drivers = await db.drivers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of drivers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of drivers) {
await record.destroy({transaction});
}
});
return drivers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const drivers = await db.drivers.findByPk(id, options);
await drivers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await drivers.destroy({
transaction
});
return drivers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const drivers = await db.drivers.findOne(
{ where },
{ transaction },
);
if (!drivers) {
return drivers;
}
const output = drivers.get({plain: true});
output.orders_assigned_driver = await drivers.getOrders_assigned_driver({
transaction
});
output.driver_locations_driver = await drivers.getDriver_locations_driver({
transaction
});
output.driver_payment_slips_driver = await drivers.getDriver_payment_slips_driver({
transaction
});
output.driver_return_slips_driver = await drivers.getDriver_return_slips_driver({
transaction
});
output.user = await drivers.getUser({
transaction
});
output.assigned_city = await drivers.getAssigned_city({
transaction
});
output.assigned_region = await drivers.getAssigned_region({
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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.cities,
as: 'assigned_city',
where: filter.assigned_city ? {
[Op.or]: [
{ id: { [Op.in]: filter.assigned_city.split('|').map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: filter.assigned_city.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.regions,
as: 'assigned_region',
where: filter.assigned_region ? {
[Op.or]: [
{ id: { [Op.in]: filter.assigned_region.split('|').map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: filter.assigned_region.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'drivers',
'name',
filter.name,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'drivers',
'phone',
filter.phone,
),
};
}
if (filter.national_id) {
where = {
...where,
[Op.and]: Utils.ilike(
'drivers',
'national_id',
filter.national_id,
),
};
}
if (filter.current_latRange) {
const [start, end] = filter.current_latRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
current_lat: {
...where.current_lat,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
current_lat: {
...where.current_lat,
[Op.lte]: end,
},
};
}
}
if (filter.current_lngRange) {
const [start, end] = filter.current_lngRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
current_lng: {
...where.current_lng,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
current_lng: {
...where.current_lng,
[Op.lte]: end,
},
};
}
}
if (filter.balance_owedRange) {
const [start, end] = filter.balance_owedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
balance_owed: {
...where.balance_owed,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
balance_owed: {
...where.balance_owed,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.vehicle_type) {
where = {
...where,
vehicle_type: filter.vehicle_type,
};
}
if (filter.online_status) {
where = {
...where,
online_status: filter.online_status,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.drivers.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(
'drivers',
'name',
query,
),
],
};
}
const records = await db.drivers.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};