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 ClientsDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const clients = await db.clients.create( { id: data.id || undefined, first_name: data.first_name || null, last_name: data.last_name || null, email: data.email || null, phone_number: data.phone_number || null, date_of_birth: data.date_of_birth || null, gender: data.gender || null, address: data.address || null, medical_history: data.medical_history || null, fitness_goals: data.fitness_goals || null, importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await clients.setOrganizations(data.organizations || null, { transaction, }); await clients.setSegments(data.segments || [], { transaction, }); return clients; } 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 clientsData = data.map((item, index) => ({ id: item.id || undefined, first_name: item.first_name || null, last_name: item.last_name || null, email: item.email || null, phone_number: item.phone_number || null, date_of_birth: item.date_of_birth || null, gender: item.gender || null, address: item.address || null, medical_history: item.medical_history || null, fitness_goals: item.fitness_goals || null, importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const clients = await db.clients.bulkCreate(clientsData, { transaction }); // For each item created, replace relation files return clients; } 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 clients = await db.clients.findByPk(id, {}, { transaction }); const updatePayload = {}; if (data.first_name !== undefined) updatePayload.first_name = data.first_name; if (data.last_name !== undefined) updatePayload.last_name = data.last_name; if (data.email !== undefined) updatePayload.email = data.email; if (data.phone_number !== undefined) updatePayload.phone_number = data.phone_number; if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth; if (data.gender !== undefined) updatePayload.gender = data.gender; if (data.address !== undefined) updatePayload.address = data.address; if (data.medical_history !== undefined) updatePayload.medical_history = data.medical_history; if (data.fitness_goals !== undefined) updatePayload.fitness_goals = data.fitness_goals; updatePayload.updatedById = currentUser.id; await clients.update(updatePayload, { transaction }); if (data.organizations !== undefined) { await clients.setOrganizations( data.organizations, { transaction }, ); } if (data.segments !== undefined) { await clients.setSegments(data.segments, { transaction }); } return clients; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const clients = await db.clients.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of clients) { await record.update({ deletedBy: currentUser.id }, { transaction }); } for (const record of clients) { await record.destroy({ transaction }); } }); return clients; } static async remove(id, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const clients = await db.clients.findByPk(id, options); await clients.update( { deletedBy: currentUser.id, }, { transaction, }, ); await clients.destroy({ transaction, }); return clients; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const clients = await db.clients.findOne({ where }, { transaction }); if (!clients) { return clients; } const output = clients.get({ plain: true }); output.appointments_client = await clients.getAppointments_client({ transaction, }); output.food_logs_client = await clients.getFood_logs_client({ transaction, }); output.invoices_client = await clients.getInvoices_client({ transaction, }); output.nutrition_plans_client = await clients.getNutrition_plans_client({ transaction, }); output.payments_client = await clients.getPayments_client({ transaction, }); output.subscriptions_client = await clients.getSubscriptions_client({ transaction, }); output.workout_plans_client = await clients.getWorkout_plans_client({ transaction, }); output.segments = await clients.getSegments({ transaction, }); output.organizations = await clients.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.organizations, as: 'organizations', }, { model: db.segments, as: 'segments', }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.first_name) { where = { ...where, [Op.and]: Utils.ilike('clients', 'first_name', filter.first_name), }; } if (filter.last_name) { where = { ...where, [Op.and]: Utils.ilike('clients', 'last_name', filter.last_name), }; } if (filter.email) { where = { ...where, [Op.and]: Utils.ilike('clients', 'email', filter.email), }; } if (filter.phone_number) { where = { ...where, [Op.and]: Utils.ilike('clients', 'phone_number', filter.phone_number), }; } if (filter.address) { where = { ...where, [Op.and]: Utils.ilike('clients', 'address', filter.address), }; } if (filter.medical_history) { where = { ...where, [Op.and]: Utils.ilike( 'clients', 'medical_history', filter.medical_history, ), }; } if (filter.fitness_goals) { where = { ...where, [Op.and]: Utils.ilike( 'clients', 'fitness_goals', filter.fitness_goals, ), }; } if (filter.date_of_birthRange) { const [start, end] = filter.date_of_birthRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, date_of_birth: { ...where.date_of_birth, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, date_of_birth: { ...where.date_of_birth, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true', }; } if (filter.gender) { where = { ...where, gender: filter.gender, }; } if (filter.organizations) { const listItems = filter.organizations.split('|').map((item) => { return Utils.uuid(item); }); where = { ...where, organizationsId: { [Op.or]: listItems }, }; } if (filter.segments) { const searchTerms = filter.segments.split('|'); include = [ { model: db.segments, as: 'segments_filter', required: searchTerms.length > 0, where: searchTerms.length > 0 ? { [Op.or]: [ { id: { [Op.in]: searchTerms.map((term) => Utils.uuid(term)), }, }, { segment_name: { [Op.or]: searchTerms.map((term) => ({ [Op.iLike]: `%${term}%`, })), }, }, ], } : undefined, }, ...include, ]; } 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.clients.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('clients', 'first_name', query), ], }; } const records = await db.clients.findAll({ attributes: ['id', 'first_name'], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['first_name', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.first_name, })); } };