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 TodosDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const todos = await db.todos.create( { id: data.id || undefined, title: data.title || null , description: data.description || null , status: data.status || null , priority: data.priority || null , start_date: data.start_date || null , due_date: data.due_date || null , estimated_hours: data.estimated_hours || null , time_tracked: data.time_tracked || null , completed: data.completed || false , importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await todos.setAssignee( data.assignee || null, { transaction, }); await todos.setProject( data.project || null, { transaction, }); await todos.setTags(data.tags || [], { transaction, }); await FileDBApi.replaceRelationFiles( { belongsTo: db.todos.getTableName(), belongsToColumn: 'attachments', belongsToId: todos.id, }, data.attachments, options, ); return todos; } 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 todosData = data.map((item, index) => ({ id: item.id || undefined, title: item.title || null , description: item.description || null , status: item.status || null , priority: item.priority || null , start_date: item.start_date || null , due_date: item.due_date || null , estimated_hours: item.estimated_hours || null , time_tracked: item.time_tracked || null , completed: item.completed || false , importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const todos = await db.todos.bulkCreate(todosData, { transaction }); // For each item created, replace relation files for (let i = 0; i < todos.length; i++) { await FileDBApi.replaceRelationFiles( { belongsTo: db.todos.getTableName(), belongsToColumn: 'attachments', belongsToId: todos[i].id, }, data[i].attachments, options, ); } return todos; } static async update(id, data, options) { const currentUser = (options && options.currentUser) || {id: null}; const transaction = (options && options.transaction) || undefined; const todos = await db.todos.findByPk(id, {}, {transaction}); const updatePayload = {}; if (data.title !== undefined) updatePayload.title = data.title; if (data.description !== undefined) updatePayload.description = data.description; if (data.status !== undefined) updatePayload.status = data.status; if (data.priority !== undefined) updatePayload.priority = data.priority; if (data.start_date !== undefined) updatePayload.start_date = data.start_date; if (data.due_date !== undefined) updatePayload.due_date = data.due_date; if (data.estimated_hours !== undefined) updatePayload.estimated_hours = data.estimated_hours; if (data.time_tracked !== undefined) updatePayload.time_tracked = data.time_tracked; if (data.completed !== undefined) updatePayload.completed = data.completed; updatePayload.updatedById = currentUser.id; await todos.update(updatePayload, {transaction}); if (data.assignee !== undefined) { await todos.setAssignee( data.assignee, { transaction } ); } if (data.project !== undefined) { await todos.setProject( data.project, { transaction } ); } if (data.tags !== undefined) { await todos.setTags(data.tags, { transaction }); } await FileDBApi.replaceRelationFiles( { belongsTo: db.todos.getTableName(), belongsToColumn: 'attachments', belongsToId: todos.id, }, data.attachments, options, ); return todos; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const todos = await db.todos.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of todos) { await record.update( {deletedBy: currentUser.id}, {transaction} ); } for (const record of todos) { await record.destroy({transaction}); } }); return todos; } static async remove(id, options) { const currentUser = (options && options.currentUser) || {id: null}; const transaction = (options && options.transaction) || undefined; const todos = await db.todos.findByPk(id, options); await todos.update({ deletedBy: currentUser.id }, { transaction, }); await todos.destroy({ transaction }); return todos; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const todos = await db.todos.findOne( { where }, { transaction }, ); if (!todos) { return todos; } const output = todos.get({plain: true}); output.time_entries_todo = await todos.getTime_entries_todo({ transaction }); output.assignee = await todos.getAssignee({ transaction }); output.project = await todos.getProject({ transaction }); output.tags = await todos.getTags({ transaction }); output.attachments = await todos.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.users, as: 'assignee', where: filter.assignee ? { [Op.or]: [ { id: { [Op.in]: filter.assignee.split('|').map(term => Utils.uuid(term)) } }, { firstName: { [Op.or]: filter.assignee.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } }, ] } : {}, }, { model: db.projects, as: 'project', where: filter.project ? { [Op.or]: [ { id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } }, { name: { [Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } }, ] } : {}, }, { model: db.tags, as: 'tags', required: false, }, { model: db.file, as: 'attachments', }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.title) { where = { ...where, [Op.and]: Utils.ilike( 'todos', 'title', filter.title, ), }; } if (filter.description) { where = { ...where, [Op.and]: Utils.ilike( 'todos', 'description', filter.description, ), }; } if (filter.start_dateRange) { const [start, end] = filter.start_dateRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, start_date: { ...where.start_date, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, start_date: { ...where.start_date, [Op.lte]: end, }, }; } } if (filter.due_dateRange) { const [start, end] = filter.due_dateRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, due_date: { ...where.due_date, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, due_date: { ...where.due_date, [Op.lte]: end, }, }; } } if (filter.estimated_hoursRange) { const [start, end] = filter.estimated_hoursRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, estimated_hours: { ...where.estimated_hours, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, estimated_hours: { ...where.estimated_hours, [Op.lte]: end, }, }; } } if (filter.time_trackedRange) { const [start, end] = filter.time_trackedRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, time_tracked: { ...where.time_tracked, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, time_tracked: { ...where.time_tracked, [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.priority) { where = { ...where, priority: filter.priority, }; } if (filter.completed) { where = { ...where, completed: filter.completed, }; } if (filter.tags) { const searchTerms = filter.tags.split('|'); include = [ { model: db.tags, as: 'tags_filter', required: searchTerms.length > 0, where: searchTerms.length > 0 ? { [Op.or]: [ { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } }, { 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, }, }; } } } 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.todos.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( 'todos', 'title', query, ), ], }; } const records = await db.todos.findAll({ attributes: [ 'id', 'title' ], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['title', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.title, })); } };