2026-05-27 08:47:08 +00:00

637 lines
15 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 LeadsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const leads = await db.leads.create(
{
id: data.id || undefined,
lead_name: data.lead_name
||
null
,
status: data.status
||
null
,
estimated_value: data.estimated_value
||
null
,
description: data.description
||
null
,
next_follow_up_at: data.next_follow_up_at
||
null
,
last_contacted_at: data.last_contacted_at
||
null
,
is_converted: data.is_converted
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await leads.setOwner( data.owner || null, {
transaction,
});
await leads.setContact( data.contact || null, {
transaction,
});
await leads.setSource( data.source || null, {
transaction,
});
return leads;
}
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 leadsData = data.map((item, index) => ({
id: item.id || undefined,
lead_name: item.lead_name
||
null
,
status: item.status
||
null
,
estimated_value: item.estimated_value
||
null
,
description: item.description
||
null
,
next_follow_up_at: item.next_follow_up_at
||
null
,
last_contacted_at: item.last_contacted_at
||
null
,
is_converted: item.is_converted
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const leads = await db.leads.bulkCreate(leadsData, { transaction });
// For each item created, replace relation files
return leads;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const leads = await db.leads.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.lead_name !== undefined) updatePayload.lead_name = data.lead_name;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.estimated_value !== undefined) updatePayload.estimated_value = data.estimated_value;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.next_follow_up_at !== undefined) updatePayload.next_follow_up_at = data.next_follow_up_at;
if (data.last_contacted_at !== undefined) updatePayload.last_contacted_at = data.last_contacted_at;
if (data.is_converted !== undefined) updatePayload.is_converted = data.is_converted;
updatePayload.updatedById = currentUser.id;
await leads.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await leads.setOwner(
data.owner,
{ transaction }
);
}
if (data.contact !== undefined) {
await leads.setContact(
data.contact,
{ transaction }
);
}
if (data.source !== undefined) {
await leads.setSource(
data.source,
{ transaction }
);
}
return leads;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const leads = await db.leads.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of leads) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of leads) {
await record.destroy({transaction});
}
});
return leads;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const leads = await db.leads.findByPk(id, options);
await leads.update({
deletedBy: currentUser.id
}, {
transaction,
});
await leads.destroy({
transaction
});
return leads;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const leads = await db.leads.findOne(
{ where },
{ transaction },
);
if (!leads) {
return leads;
}
const output = leads.get({plain: true});
output.deals_lead = await leads.getDeals_lead({
transaction
});
output.activities_lead = await leads.getActivities_lead({
transaction
});
output.notes_lead = await leads.getNotes_lead({
transaction
});
output.owner = await leads.getOwner({
transaction
});
output.contact = await leads.getContact({
transaction
});
output.source = await leads.getSource({
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: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.contacts,
as: 'contact',
where: filter.contact ? {
[Op.or]: [
{ id: { [Op.in]: filter.contact.split('|').map(term => Utils.uuid(term)) } },
{
full_name: {
[Op.or]: filter.contact.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.lead_sources,
as: 'source',
where: filter.source ? {
[Op.or]: [
{ id: { [Op.in]: filter.source.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.source.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.lead_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'leads',
'lead_name',
filter.lead_name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'leads',
'description',
filter.description,
),
};
}
if (filter.estimated_valueRange) {
const [start, end] = filter.estimated_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
estimated_value: {
...where.estimated_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
estimated_value: {
...where.estimated_value,
[Op.lte]: end,
},
};
}
}
if (filter.next_follow_up_atRange) {
const [start, end] = filter.next_follow_up_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
next_follow_up_at: {
...where.next_follow_up_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
next_follow_up_at: {
...where.next_follow_up_at,
[Op.lte]: end,
},
};
}
}
if (filter.last_contacted_atRange) {
const [start, end] = filter.last_contacted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_contacted_at: {
...where.last_contacted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_contacted_at: {
...where.last_contacted_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.is_converted) {
where = {
...where,
is_converted: filter.is_converted,
};
}
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.leads.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(
'leads',
'lead_name',
query,
),
],
};
}
const records = await db.leads.findAll({
attributes: [ 'id', 'lead_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['lead_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.lead_name,
}));
}
};