Skip to content

Commit

Permalink
fix some visualization bugs in Calendar b00tc4mp#426
Browse files Browse the repository at this point in the history
  • Loading branch information
pankelix committed Mar 21, 2024
1 parent 4cb4fe6 commit e5fe157
Show file tree
Hide file tree
Showing 23 changed files with 420 additions and 195 deletions.
2 changes: 1 addition & 1 deletion staff/miguel-arias/project/api/logic/completeTask.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ describe('completeTask', () => {

const taskId = task._id.toString()

debugger

await completeTask(profileId, taskId, pincode, format(addDay(new Date(), -1), 'YYYY-MM-DD'))

const taskdeleted = await Task.findById(taskId)
Expand Down
1 change: 1 addition & 0 deletions staff/miguel-arias/project/api/logic/delayTask.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ function delayTask(profileId, taskId, date) {
throw new NotFoundError('task not found')

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

const today = new Date()
today.setHours(0, 0, 0, 0)
Expand Down
10 changes: 10 additions & 0 deletions staff/miguel-arias/project/api/logic/deleteOwnProfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ function deleteOwnProfile(profileId) {
if (!profile)
throw new NotFoundError('profile not found')

let adminProfile
try {
adminProfile = await Profile.findOne({ _id: { $ne: profile._id }, role: 'admin' }).lean()
} catch (error) {
throw new SystemError(error.message)
}

if (!adminProfile)
throw new PermissionError("this profile is the only admin and can't be deleted")

try {
await Task.updateMany({ assignee: profileId }, { $unset: { assignee: 1 } })
} catch (error) {
Expand Down
19 changes: 19 additions & 0 deletions staff/miguel-arias/project/api/logic/deleteOwnProfile.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ describe('deleteOwnProfile', () => {

const profileId = profile._id.toString()

await Profile.create({ home: random.id(), name: random.name(), pincode: hash, role: 'admin', color: { name: random.name(), code: random.name() } })

const homeId = random.id()
const templateId = random.id()

Expand Down Expand Up @@ -61,5 +63,22 @@ describe('deleteOwnProfile', () => {
}
})

it('fails on being the only admin', async () => {
const adminProfile = await Profile.create({ home: random.id(), name: random.name(), pincode: random.pincode(), role: 'admin', color: { name: random.name(), code: random.name() } })

const adminProfileId = adminProfile._id.toString()

await Profile.create({ home: random.id(), name: random.name(), pincode: random.pincode(), color: { name: random.name(), code: random.name() } })

try {
await deleteOwnProfile(adminProfileId)
throw new Error('should not reach this point')
} catch (error) {
expect(error).to.be.instanceOf(PermissionError)
expect(error.message).to.equal("this profile is the only admin and can't be deleted")
}
})


after(async () => await mongoose.disconnect())
})
19 changes: 17 additions & 2 deletions staff/miguel-arias/project/api/logic/deleteRoom.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Profile, Room, Template } from '../data/models.js'
import { Profile, Room, Template, Task } from '../data/models.js'
import { validate, errors } from 'com'
const { SystemError, NotFoundError, PermissionError } = errors

Expand Down Expand Up @@ -30,8 +30,23 @@ function deleteRoom(profileId, roomId) {
if (!room)
throw new NotFoundError('room not found')

let templates
try {
await Template.updateMany({ rooms: roomId }, { $pull: { rooms: roomId } })
templates = await Template.find({ rooms: roomId })
} catch (error) {
throw new SystemError(error.message)
}

const templateIds = templates.map(template => template._id)

try {
await Task.deleteMany({ template: { $in: templateIds } })
} catch (error) {
throw new SystemError(error.message)
}

try {
await Template.deleteMany({ rooms: roomId })
} catch (error) {
throw new SystemError(error.message)
}
Expand Down
115 changes: 115 additions & 0 deletions staff/miguel-arias/project/api/logic/populate2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import mongoose from 'mongoose'
import registerHome from './registerHome.js'
import registerProfile from './registerProfile.js'
import createRoom from './createRoom.js'
import createTemplate from './createTemplate.js'
import createTask from './createTask.js'
import { format, addDay } from '@formkit/tempo'

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

(async () => {
try {
await mongoose.connect('mongodb://127.0.0.1:27017/project2')
await Home.deleteMany()
await Room.deleteMany()
await Profile.deleteMany()
await Template.deleteMany()
await Task.deleteMany()

//Home
let mansion
let casoplon
let casita
let pisito
try {
mansion = await registerHome('Man Sion', '[email protected]', '123123123')
casoplon = await registerHome('Ca Soplon', '[email protected]', '123123123')
casita = await registerHome('Ca Sita', '[email protected]', '123123123')
pisito = await registerHome('Pi sito', '[email protected]', '123123123')
} catch (error) {
console.log(error)
}

//Room
let kidsBathroom
let adultsBathroom
let livingRoom
let terrace
let yard
let kitchen
let diningRoom
let hall
let kidsBedroom
let adultsBedroom
let office
try {
kidsBathroom = await createRoom(mansion.id, 'kids-bathroom')
adultsBathroom = await createRoom(mansion.id, 'adults-bathroom')
livingRoom = await createRoom(mansion.id, 'living-room')
terrace = await createRoom(mansion.id, 'terrace')
yard = await createRoom(mansion.id, 'yard')
kitchen = await createRoom(mansion.id, 'kitchen')
diningRoom = await createRoom(mansion.id, 'dining-room')
hall = await createRoom(mansion.id, 'hall')
kidsBedroom = await createRoom(mansion.id, 'kids-bedroom')
adultsBedroom = await createRoom(mansion.id, 'adults-bedroom')
office = await createRoom(mansion.id, 'office')
} catch (error) {
console.log(error)
}

//Profile
let peter
let wendy
let michael
let john
let james
try {
peter = await registerProfile(mansion.id, 'Peter Pan', '1234', { name: 'Emerald green', code: '#2ECC71' })
wendy = await registerProfile(mansion.id, 'Wendy Darling', '1234', { name: 'Blue', code: '#3498DB' })
james = await registerProfile(mansion.id, 'James Hook', '1234', { name: 'Red', code: '#E74C3C' })
michael = await registerProfile(mansion.id, 'Michael Darling', '1234', { name: 'Dark purple', code: '#8E44AD' })
john = await registerProfile(mansion.id, 'John Darling', '1234', { name: 'Soft yellow', code: '#F1C40F' })
} catch (error) {
console.log(error)
}

//Template
let cleanShower
let dust
let doDishes
let lawnRaking
let changeSheets
let cleanWindow
let cleanOven
try {
//homeId, name, periodicityNumber, periodicityRange, rooms, points
cleanShower = await createTemplate(mansion.id, 'clean-shower', 1, 'week', [kidsBathroom.id, adultsBathroom.id], 15)
dust = await createTemplate(mansion.id, 'dust', 2, 'week', [livingRoom.id, hall.id, office.id], 5)
doDishes = await createTemplate(mansion.id, 'do-dishes', 6, 'day', [kitchen.id], 2)
lawnRaking = await createTemplate(mansion.id, 'lawn-raking', 4, 'week', [terrace.id, yard.id], 15)
changeSheets = await createTemplate(mansion.id, 'change-sheets', 3, 'day', [kidsBedroom.id], 2)
cleanWindow = await createTemplate(mansion.id, 'clean window', 2, 'week', [adultsBedroom.id], 7)
cleanOven = await createTemplate(mansion.id, 'clean-oven', 3, 'week', [kitchen.id], 10)
} catch (error) {
console.log(error)
}

//Task
//homeId, templateId, date
await createTask(mansion.id, cleanShower.id, format(addDay(new Date(), 0), 'YYYY-MM-DD'))
/* await createTask(mansion.id, dust.id, format(addDay(new Date(), 1), 'YYYY-MM-DD'))
await createTask(mansion.id, doDishes.id, format(addDay(new Date(), 2), 'YYYY-MM-DD')) */
await createTask(mansion.id, lawnRaking.id, format(addDay(new Date(), 3), 'YYYY-MM-DD'))
await createTask(mansion.id, changeSheets.id, format(addDay(new Date(), 4), 'YYYY-MM-DD'))
/* await createTask(mansion.id, cleanWindow.id, format(addDay(new Date(), 5), 'YYYY-MM-DD')) */
await createTask(mansion.id, cleanOven.id, format(addDay(new Date(), 6), 'YYYY-MM-DD'))

console.log('database populated')

await mongoose.disconnect()
} catch (error) {
console.log(error)
}
})()
6 changes: 3 additions & 3 deletions staff/miguel-arias/project/api/logic/retrieveProfileTasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ function retrieveProfileTasks(homeId, profileId, week) {
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 }
const taskEcho = { ...task, date: new Date(currentDate), assignee: '', _id: task._id + '_' + idCounter, done: false, delay: 0 }

if (newTask.date >= task.date) {
tasksAndEchoes.push(newTask)
if (taskEcho.date >= task.date) {
tasksAndEchoes.push(taskEcho)
idCounter++
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ describe('retrieveProfileTasks', () => {
const task2 = await Task.create({ home: homeId, template: template2Id, assignee: profileId, date: weekStart(new Date(), 1) })

const retrievedTasks = await retrieveProfileTasks(homeId, profileId, 0)
debugger

expect(retrievedTasks.length).to.equal(4)
expect(retrievedTasks[0].home.toString()).to.equal(homeId)
expect(retrievedTasks[0].template._id.toString()).to.equal(template2Id)
Expand Down
49 changes: 20 additions & 29 deletions staff/miguel-arias/project/api/logic/retrieveTasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ function retrieveTasks(homeId, week) {
validate.id(homeId, 'home id')

return (async () => {

// Comprobaciones de seguridad
let home
try {
home = await Home.findById(homeId).lean()
Expand All @@ -20,90 +20,81 @@ function retrieveTasks(homeId, week) {
if (!home)
throw new NotFoundError('home not found')

// Calcular la semana que queremos traer
const referenceDate = addDay(new Date(), week * 7)

const startOfCurrentWeek = weekStart(referenceDate, 1)

const endOfCurrentWeek = weekEnd(referenceDate, 1)

// traer todas las tareas
// Traer todas las tareas en esa semana
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)
}

// Tasks y echoes
let tasksAndEchoes = []

tasks.forEach(task => {
// Tareas completadas y que entran en la semana de referencia
if (task.done === true && task.date >= startOfCurrentWeek && task.date <= endOfCurrentWeek)
tasksAndEchoes.push({ ...task })

// Tareas materializadas que entran en la semana de referencia
if (task.oldId && task.date >= startOfCurrentWeek && task.date <= endOfCurrentWeek)
tasksAndEchoes.push({ ...task })

// Para el resto de tareas
if (task.done === false && !task.oldId) {
// Encuentro las tareas cuyo id coincida con el oldId de una tarea materializada
const existingEcho = tasksAndEchoes.find(echo => echo._id ? echo._id === task.oldId : null)

// Si lo encuentra, sustituyo esa tarea para evitar duplicados
if (existingEcho) {
const index = tasksAndEchoes.indexOf(existingEcho)
tasksAndEchoes.splice(index, 1)
}

// Si una tarea de la base de datos está dentro de la semana de referencia
if (task.date >= startOfCurrentWeek && task.date <= endOfCurrentWeek)
tasksAndEchoes.push({ ...task })

// Aqui creo los echoes
let currentDate = new Date(task.date)
let idCounter = 0

// Mientras la fecha de la tarea no supere el final del week (por ponerle un final al while)
while (currentDate <= endOfCurrentWeek) {
// Sumo la periodicidad a la fecha, para tener la fecha del primer echo
currentDate = addDay(currentDate, task.template.periodicity)
// Si este echo entra dentro de la semana de referencia
if (currentDate >= startOfCurrentWeek && currentDate <= endOfCurrentWeek) {
const newTask = { ...task, date: new Date(currentDate), assignee: '', _id: task._id + '_' + idCounter, done: false }
const taskEcho = { ...task, date: new Date(currentDate), assignee: '', _id: task._id + '_' + idCounter, done: false, delay: 0 }

if (newTask.date >= task.date) {
tasksAndEchoes.push(newTask)
// Para asegurar que solo entren echoes que son iguales o posteriores a la fecha de la tarea original
if (taskEcho.date >= task.date) {
tasksAndEchoes.push(taskEcho)
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)
} */

// Limpiar las tareas y los echoes
tasksAndEchoes.forEach(task => {
task.id = task._id.toString()
delete task._id

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

// Ordenar las tareas y los echoes por fecha
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
})()
}
Expand Down
4 changes: 2 additions & 2 deletions staff/miguel-arias/project/app/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import session from './logic/session'
import logic from './logic'

function App() {
console.log('App')
/* console.log('App') */

const [level, setLevel] = useState(null)
const [message, setMessage] = useState(null)
Expand Down Expand Up @@ -94,7 +94,7 @@ function App() {
<Routes>
<Route path='/register' element={logic.isUserLoggedIn() ? <Navigate to='/' /> : <Register onLoginClick={handleLoginShow} onSuccess={handleLoginShow} />} />
<Route path='/login' element={logic.isUserLoggedIn() ? <Navigate to='/' /> : <Login onRegisterClick={handleRegisterShow} onSuccess={handleHomeShow} />} />
<Route path='/*' element={logic.isUserLoggedIn() ? <Home onLogoutClick={handleLoginShow} role={role} confirm={confirm} confirmAction={confirmAction} onDeletionSuccess={handleConfirmToFalse} /> : <Navigate to='/login' />} />
<Route path='/*' element={logic.isUserLoggedIn() ? <Home onLogoutClick={handleLoginShow} role={role} confirm={confirm} confirmAction={confirmAction} onDeletion={handleConfirmToFalse} /> : <Navigate to='/login' />} />
</Routes>
</Context.Provider>
</>
Expand Down
4 changes: 2 additions & 2 deletions staff/miguel-arias/project/app/src/components/Calendar.1.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { Container, Button, Form, Input, Label } from '../library'
import { Task, EmptyDate } from '.'

function Calendar(props) {
console.log('Calendar')
/* console.log('Calendar') */

const context = useContext()
const navigate = useNavigate()
Expand Down Expand Up @@ -116,7 +116,7 @@ function Calendar(props) {
}

useEffect(() => {
console.log('Tasks/Profiles effect')
/* console.log('Tasks/Profiles effect') */

refreshToday()
retrieveAssignee()
Expand Down
Loading

0 comments on commit e5fe157

Please sign in to comment.