Skip to content

Commit

Permalink
fix materializeTask logic to work better and improve retrieveTasks an…
Browse files Browse the repository at this point in the history
…d delayTasks logic b00tc4mp#426
  • Loading branch information
pankelix committed Mar 18, 2024
1 parent 46e564a commit c95ae83
Show file tree
Hide file tree
Showing 16 changed files with 719 additions and 79 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ export default async (req, res) => {
const payload = jwt.verify(token, process.env.JWT_SECRET)
const homeId = payload.sub

const { task, date } = req.body
const { task } = req.body
try {
const materializedTaskId = await logic.materializeTask(homeId, task, date)
const materializedTaskId = await logic.materializeTask(homeId, task)

res.json(materializedTaskId)
} catch (error) {
Expand Down
12 changes: 10 additions & 2 deletions staff/miguel-arias/project/api/logic/completeTask.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,23 +51,31 @@ function completeTask(profileId, taskId, pincode, date) {
throw new ContentError('this task is already done')

let completionDate = new Date(date)
completionDate.setHours(0, 0, 0, 0)

const today = new Date()
today.setHours(0, 0, 0, 0)

if (completionDate < today)
throw new ContentError('date must be after today')

/* if (completionDate < task.completionDate)
throw new ContentError("tasks can't be completed before their due completionDate") */

let completedTask
try {
completedTask = await Task.create({ home: task.home._id.toString(), template: task.template._id.toString(), assignee: task.assignee ? task.assignee._id.toString() : null, done: true, date: completionDate, delay: task.delay })
completedTask = await Task.create({ home: task.home._id.toString(), template: task.template._id.toString(), assignee: task.assignee ? task.assignee._id.toString() : undefined, done: true, date: completionDate, delay: task.delay })
} catch (error) {
throw new SystemError(error.message)
}

const newCompletionDate = new Date(completionDate);
newCompletionDate.setDate(newCompletionDate.getDate() + task.template.periodicity)
newCompletionDate.setHours(0, 0, 0, 0)

let nextTask
try {
nextTask = await Task.create({ home: task.home._id.toString(), template: task.template._id.toString(), assignee: task.assignee ? task.assignee._id.toString() : null, done: false, date: newCompletionDate })
nextTask = await Task.create({ home: task.home._id.toString(), template: task.template._id.toString(), assignee: task.assignee ? task.assignee._id.toString() : undefined, done: false, date: newCompletionDate })
} catch (error) {
throw new SystemError(error.message)
}
Expand Down
13 changes: 7 additions & 6 deletions staff/miguel-arias/project/api/logic/createTask.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { validate, errors } from 'com'
const { SystemError, NotFoundError } = errors

import { dayStart } from '@formkit/tempo'

import { Home, Template, Task } from '../data/models.js'
import { ContentError } from 'com/errors.js'

Expand Down Expand Up @@ -33,14 +31,17 @@ function createTask(homeId, templateId, date) {
if (!template)
throw new NotFoundError('template not found')

date = new Date(date)
const today = dayStart(new Date())
let creationDate = new Date(date)
creationDate.setHours(0, 0, 0, 0)

const today = new Date()
today.setHours(0, 0, 0, 0)

if (date < today)
if (creationDate < today)
throw new ContentError('date must be after today')

try {
const task = await Task.create({ home: homeId, template: templateId, date: date })
const task = await Task.create({ home: homeId, template: templateId, date: creationDate })

return task
} catch (error) {
Expand Down
1 change: 0 additions & 1 deletion staff/miguel-arias/project/api/logic/createTask.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,6 @@ describe('createTask', async () => {
expect(error).to.be.instanceOf(ContentError)
expect(error.message).to.equal('date must be after today')
}

})

after(async () => await mongoose.disconnect())
Expand Down
11 changes: 9 additions & 2 deletions staff/miguel-arias/project/api/logic/delayTask.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Task, Profile } from '../data/models.js'
function delayTask(profileId, taskId, date) {
validate.id(profileId, 'profile id')
validate.id(taskId, 'task id')
validate.date(date)

return (async () => {
let profile
Expand All @@ -28,9 +29,15 @@ function delayTask(profileId, taskId, date) {
if (!task)
throw new NotFoundError('task not found')

date = new Date(date)
let delayDate = new Date(date)

task.date = date
const today = new Date()
today.setHours(0, 0, 0, 0)

if (delayDate < today)
throw new ContentError('date must be after today')

task.date = delayDate
task.delay = task.delay + 1

try {
Expand Down
23 changes: 22 additions & 1 deletion staff/miguel-arias/project/api/logic/delayTask.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ dotenv.config()
import mongoose from 'mongoose'
import { expect } from 'chai'

import { addDay } from '@formkit/tempo'
import { addDay, format } from '@formkit/tempo'

import random from './helpers/random.js'
import delayTask from './delayTask.js'
Expand Down Expand Up @@ -66,7 +66,28 @@ describe('delayTask', () => {
expect(error).to.be.instanceOf(NotFoundError)
expect(error.message).to.equal('task not found')
}
})

it('fails on date later than today', async () => {
const profile = await Profile.create({ home: random.id(), name: random.name(), pincode: random.pincode() })

const profileId = profile._id.toString()

const task = await Task.create({ home: random.id(), template: random.id(), assignee: random.id() })

const taskId = task._id.toString()

let wrongDate = new Date()
wrongDate.setDate(wrongDate.getDate() - 1) //tomorrow
const finalWrongDate = format(wrongDate, 'YYYY-MM-DD')

try {
await delayTask(profileId, taskId, finalWrongDate)
throw new Error('should not reach this point')
} catch (error) {
expect(error).to.be.instanceOf(ContentError)
expect(error.message).to.equal('date must be after today')
}
})

after(async () => await mongoose.disconnect())
Expand Down
9 changes: 8 additions & 1 deletion staff/miguel-arias/project/api/logic/deleteTask.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,17 @@ function deleteTask(profileId, taskId) {
throw new NotFoundError('task not found')

try {
task = await Task.findByIdAndDelete(taskId)
await Task.findByIdAndDelete(taskId)
} catch (error) {
throw new SystemError(error.message)
}

if (task.oldId)
try {
await Task.findByIdAndDelete(task.oldId.split('_')[0])
} catch (error) {
throw new SystemError(error.message)
}
})()
}

Expand Down
14 changes: 7 additions & 7 deletions staff/miguel-arias/project/api/logic/materializeTask.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
import { validate, errors } from 'com'
const { SystemError, NotFoundError } = errors

import { dayStart } from '@formkit/tempo'

import { Home, Task } from '../data/models.js'
import { ContentError } from 'com/errors.js'


function materializeTask(homeId, task, date) {
function materializeTask(homeId, task) {
validate.id(homeId, 'home id')
validate.object(task)
validate.date(date)

return (async () => {
let home
Expand All @@ -23,10 +20,13 @@ function materializeTask(homeId, task, date) {
if (!home)
throw new NotFoundError('home not found')

let materializationDate = new Date(date)
const today = dayStart(new Date())
let materializationDate = new Date(task.date)
materializationDate.setHours(0, 0, 0, 0)

const today = new Date()
today.setHours(0, 0, 0, 0)

if (today > materializationDate)
if (materializationDate < today)
throw new ContentError('date must be after today')

try {
Expand Down
111 changes: 111 additions & 0 deletions staff/miguel-arias/project/api/logic/retrieveTasks.2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { validate, errors } from 'com'
const { SystemError, NotFoundError } = errors

import { addDay, weekStart, weekEnd, dayEnd } from '@formkit/tempo'

import { Home, Task } from '../data/models.js'

function retrieveTasks(homeId, week) {
validate.id(homeId, 'home id')

return (async () => {

let home
try {
home = await Home.findById(homeId).lean()
} catch (error) {
throw new SystemError(error.message)
}

if (!home)
throw new NotFoundError('home not found')

const referenceDate = addDay(new Date(), week * 7)

const startOfCurrentWeek = weekStart(referenceDate, 1)

const endOfCurrentWeek = weekEnd(referenceDate, 1)

// traer todas las tareas
let tasks
try {
tasks = await Task.find({ home: homeId }).populate('template', '-__v').select('-__v').sort({ date: 1 }).lean()
} catch (error) {
throw new SystemError(error.message)
}

let tasksAndEchoes = []

tasks.forEach(task => {
if (task.done === true) {
if (task.date >= startOfCurrentWeek && task.date <= endOfCurrentWeek) {
tasksAndEchoes.push({ ...task })
}
}

if (task.done === false) {
const existingEcho = tasksAndEchoes.find(echo => echo._id ? echo._id === task.oldId : null)

if (existingEcho) {
const index = tasksAndEchoes.indexOf(existingEcho)
tasksAndEchoes.splice(index, 1)
}

if (task.date >= startOfCurrentWeek && task.date <= endOfCurrentWeek)
tasksAndEchoes.push({ ...task })

let currentDate = new Date(task.date)
let idCounter = 0

while (currentDate <= endOfCurrentWeek) {
currentDate = addDay(currentDate, task.template.periodicity)
if (currentDate >= startOfCurrentWeek && currentDate <= endOfCurrentWeek) {
const newTask = { ...task, date: new Date(currentDate), assignee: '', _id: task._id + '_' + idCounter, done: false }

if (newTask.date >= task.date) {
tasksAndEchoes.push(newTask)
idCounter++
}
}
}
}
})

// de cada tarea quiero que se haga un date = date x periodicity mientras date <= endOfCurrentWeek
// si task.date >= startOfCurrentWeek && task.date <= endOfCurrentWeek, la pusheo en un nuevo array
// devuelvo este nuevo array

/* let tasks
try {
tasks = await Task.find({ home: homeId, date: { $gte: startOfCurrentWeek, $lte: endOfCurrentWeek } }).populate('template', '-__v').select('-__v').sort({ date: 1 }).lean()
} catch (error) {
throw new SystemError(error.message)
} */

tasksAndEchoes.forEach(task => {
task.id = task._id.toString()
delete task._id

task.date = dayEnd(task.date)
})

tasksAndEchoes.sort((a, b) => a.date - b.date)

/* let duplicatedTasks = tasks.map(task => ({ ...task, date: new Date(task.date) }))
let newTasks = []
duplicatedTasks.forEach(task => {
task.date = addDay(new Date(task.date), task.template.periodicity)
task.assignee = ''
//if (task.date >= startOfCurrentWeek && task.date <= endOfCurrentWeek)
newTasks.push(task)
})
const allTasks = [...tasks, ...newTasks].sort((a, b) => a.date - b.date);
return allTasks */

return tasksAndEchoes
})()
}

export default retrieveTasks
12 changes: 6 additions & 6 deletions staff/miguel-arias/project/api/logic/retrieveTasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,13 @@ function retrieveTasks(homeId, week) {
let tasksAndEchoes = []

tasks.forEach(task => {
if (task.done === true) {
if (task.date >= startOfCurrentWeek && task.date <= endOfCurrentWeek) {
tasksAndEchoes.push({ ...task })
}
}
if (task.done === true && task.date >= startOfCurrentWeek && task.date <= endOfCurrentWeek)
tasksAndEchoes.push({ ...task })

if (task.oldId && task.date >= startOfCurrentWeek && task.date <= endOfCurrentWeek)
tasksAndEchoes.push({ ...task })

if (task.done === false) {
if (task.done === false && !task.oldId) {
const existingEcho = tasksAndEchoes.find(echo => echo._id ? echo._id === task.oldId : null)

if (existingEcho) {
Expand Down
Loading

0 comments on commit c95ae83

Please sign in to comment.