Skip to content

Commit

Permalink
add create template and complete task logics b00tc4mp#426
Browse files Browse the repository at this point in the history
  • Loading branch information
pankelix committed Feb 29, 2024
1 parent 6f6fb5b commit 1853a6f
Show file tree
Hide file tree
Showing 27 changed files with 430 additions and 60 deletions.
38 changes: 38 additions & 0 deletions staff/miguel-arias/project/api/handlers/createTemplateHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import jwt from 'jsonwebtoken'
const { JsonWebTokenError } = jwt

import { errors } from 'com'
const { NotFoundError, ContentError, TokenError } = errors

import logic from '../logic/index.js'

export default async (req, res) => {
const token = req.headers.authorization.substring(7)
const payload = jwt.verify(token, process.env.JWT_SECRET)
const homeId = payload.sub

const { name, periodicityNumber, periodicityRange, rooms, points } = req.body
try {
await logic.createTemplate(homeId, name, periodicityNumber, periodicityRange, rooms, points)
} catch (error) {
let status = 500

if (error instanceof NotFoundError)
status = 404

if (error instanceof DuplicityError)
status = 409

if (error instanceof ContentError || error instanceof TypeError)
status = 406

if (error instanceof JsonWebTokenError) {
status = 401
error = new TokenError(error.message)
}

res.status(status).json({ error: error.constructor.name, message: error.message })
}

res.status(201).send()
}
4 changes: 4 additions & 0 deletions staff/miguel-arias/project/api/handlers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import assignTaskHandler from './assignTaskHandler.js'
import delayTaskHandler from './delayTaskHandler.js'
import deleteTaskHandler from './deleteTaskHandler.js'
import completeTaskHandler from './completeTaskHandler.js'
import retrieveRoomsHandler from './retrieveRoomsHandler.js'
import createTemplateHandler from './createTemplateHandler.js'

export {
registerHomeHandler,
Expand All @@ -26,4 +28,6 @@ export {
delayTaskHandler,
deleteTaskHandler,
completeTaskHandler,
retrieveRoomsHandler,
createTemplateHandler,
}
35 changes: 35 additions & 0 deletions staff/miguel-arias/project/api/handlers/retrieveRoomsHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import jwt from 'jsonwebtoken'
const { JsonWebTokenError } = jwt

import { errors } from 'com'
const { NotFoundError, ContentError, TokenError } = errors

import logic from "../logic/index.js"

export default async (req, res) => {
try {
const token = req.headers.authorization.substring(7)
const payload = jwt.verify(token, process.env.JWT_SECRET)
const homeId = payload.sub

const tasks = await logic.retrieveRooms(homeId)

res.json(tasks)

} catch (error) {
let status = 500

if (error instanceof ContentError || error instanceof TypeError)
status = 406

if (error instanceof NotFoundError)
status = 404

if (error instanceof JsonWebTokenError) {
status = 401
error = new TokenError(error.message)
}

res.status(status).json({ error: error.constructor.name, message: error.message })
}
}
31 changes: 20 additions & 11 deletions staff/miguel-arias/project/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,20 @@ import cors from 'cors'

import {
registerHomeHandler,
authenticateHomeHandler,
retrieveHomeHandler,
retrieveTasksHandler,
authenticateHomeHandler,
retrieveProfilesHandler,
retrieveTemplatesHandler,
authenticateProfileHandler,
retrieveRoleHandler,
authenticateProfileHandler,
createTaskHandler,
retrieveTasksHandler,
deleteTaskHandler,
assignTaskHandler,
delayTaskHandler,
deleteTaskHandler
completeTaskHandler,
retrieveTemplatesHandler,
retrieveRoomsHandler,
createTemplateHandler,
} from './handlers/index.js'

mongoose.connect(process.env.MONGODB_URL)
Expand All @@ -33,23 +36,29 @@ mongoose.connect(process.env.MONGODB_URL)

server.post('/homes/auth', jsonBodyParser, authenticateHomeHandler)

server.get('/profiles', retrieveProfilesHandler)

server.get('/profiles/:profileId/role', retrieveRoleHandler)

server.post('/profiles/auth', jsonBodyParser, authenticateProfileHandler)

server.get('/tasks', retrieveTasksHandler)

server.post('/tasks', jsonBodyParser, createTaskHandler)

server.post('/tasks/:taskId/delete', deleteTaskHandler)

server.patch('/tasks/:taskId/assign/:profileId', assignTaskHandler)

server.patch('/tasks/:taskId/delay', jsonBodyParser, delayTaskHandler)

server.post('/tasks/:taskId/delete', deleteTaskHandler)
server.patch('/tasks/:taskId/complete', jsonBodyParser, completeTaskHandler)

server.get('/tasks', retrieveTasksHandler)
server.get('/templates', retrieveTemplatesHandler)

server.get('/profiles', retrieveProfilesHandler)
server.post('/templates', jsonBodyParser, createTemplateHandler)

server.get('/profiles/:profileId/role', retrieveRoleHandler)

server.get('/templates', retrieveTemplatesHandler)
server.get('/rooms', retrieveRoomsHandler)

const date = new Date()
server.listen(process.env.PORT, () => console.log(`Server is online at ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()} in port ${process.env.PORT}`))
Expand Down
1 change: 1 addition & 0 deletions staff/miguel-arias/project/api/logic/completeTask.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ function completeTask(profileId, taskId, pincode, date) {
validate.pincode(pincode)

return (async () => {
debugger
let profile
try {
profile = await Profile.findById(profileId)
Expand Down
5 changes: 3 additions & 2 deletions staff/miguel-arias/project/api/logic/completeTask.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import mongoose from 'mongoose'
import completeTask from './completeTask.js'

(async () => {
const date = '2024-03-01'
try {
await mongoose.connect('mongodb://127.0.0.1:27017/test')
await mongoose.connect('mongodb://127.0.0.1:27017/project')

await completeTask('65d79ed33377222a97582a18', '65d79ed43377222a97582a2e', '1234', new Date)
await completeTask('65da45873f666061bc54cf3c', '65da45873f666061bc54cf5c', '1234', new Date(date))
//sessionProfileId, taskId, pincode, date

console.log('task completed')
Expand Down
6 changes: 0 additions & 6 deletions staff/miguel-arias/project/api/logic/createTask.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,6 @@ import createTask from './createTask.js'
await mongoose.connect('mongodb://127.0.0.1:27017/test')

await createTask('65d5081ea39e64389e9fd25a')
await createTask('65d5081ea39e64389e9fd25e')
await createTask('65d5081ea39e64389e9fd260')
await createTask('65d5081ea39e64389e9fd263')
await createTask('65d5081ea39e64389e9fd266')
await createTask('65d5081ea39e64389e9fd268')
await createTask('65d5081ea39e64389e9fd26a')

console.log('task registered')

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

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

function createTemplate(homeId, name, rooms, periodicity, points) {
function createTemplate(homeId, name, periodicityNumber, periodicityRange, rooms, points) {
validate.id(homeId, 'home id')
validate.text(name, 'name')
validate.array(rooms, 'rooms')
validate.number(periodicity, 'periodicity')
validate.number(periodicityNumber, 'periodicity number')
validate.text(periodicityRange, 'periodicity range')
validate.number(points, 'points')

return (async () => {

if(periodicityNumber === 0)
throw new ContentError("periodicity can't be 0")

let home
try {
home = await Home.findById(homeId).lean()
Expand All @@ -21,6 +26,12 @@ function createTemplate(homeId, name, rooms, periodicity, points) {
if (!home)
throw new NotFoundError('home not found')

let periodicity
if (periodicityRange === 'day')
periodicity = periodicityNumber
else if (periodicityRange === 'week')
periodicity = periodicityNumber * 7

try {
const template = await Template.create({ home: homeId, name, rooms, periodicity, points })

Expand Down
10 changes: 3 additions & 7 deletions staff/miguel-arias/project/api/logic/createTemplate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,9 @@ import createTemplate from './createTemplate.js'
try {
await mongoose.connect('mongodb://127.0.0.1:27017/test')

await createTemplate('Limpiar ducha', ['65d4f9f6f620be020216951e', '65d4f9f6f620be0202169521'], 14, 15)
await createTemplate('Quitar polvo', ['65d4f9f6f620be0202169524', '65d4f9f6f620be020216952e', '65d4f9f6f620be0202169536'], 4, 5)
await createTemplate('Fregar platos', ['65d4f9f6f620be020216952c'], 1, 2)
await createTemplate('Recoger hojas', ['65d4f9f6f620be020216952a', '65d4f9f6f620be0202169527'], 28, 15)
await createTemplate('Cambiar sábanas', ['65d4f9f6f620be0202169532'], 7, 2)
await createTemplate('Cambiar sábanas', ['65d4f9f6f620be0202169534'], 7, 2)
await createTemplate('Limpiar horno', ['65d4f9f6f620be020216952c'], 21, 10)
await createTemplate('65d79ed33377222a975829fa', 'Limpiar ducha', 3, 'week', ['65d79ed33377222a97582a02', '65d79ed33377222a97582a04'], 15)

//homeId, name, rooms, periodicityNumber, periodicityRange, points

console.log('template registered')

Expand Down
8 changes: 7 additions & 1 deletion staff/miguel-arias/project/api/logic/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import createTask from './createTask.js'
import assignTask from './assignTask.js'
import delayTask from './delayTask.js'
import deleteTask from './deleteTask.js'
import retrieveRooms from './retrieveRooms.js'
import createTemplate from './createTemplate.js'
import completeTask from './completeTask.js'

const logic = {
registerHome,
Expand All @@ -23,7 +26,10 @@ const logic = {
createTask,
assignTask,
delayTask,
deleteTask
deleteTask,
retrieveRooms,
createTemplate,
completeTask,
}

export default logic
40 changes: 40 additions & 0 deletions staff/miguel-arias/project/api/logic/retrieveRooms.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { validate, errors } from 'com'
const { SystemError, NotFoundError } = errors

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

function retrieveRooms(homeId) {
validate.id(homeId)

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

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

let rooms
try {
rooms = await Room.find({ home: homeId }).select('-__v').lean()
} catch (error) {
throw new SystemError(error.message)
}

if (!rooms)
throw new NotFoundError('room not found')

rooms.forEach(room => {
room.id = room._id.toString()
delete room._id
})

return rooms
})()
}

export default retrieveRooms
16 changes: 16 additions & 0 deletions staff/miguel-arias/project/api/logic/retrieveRooms.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import mongoose from 'mongoose'

import retrieveRooms from './retrieveRooms.js'

(async () => {
try {
await mongoose.connect('mongodb://127.0.0.1:27017/test')

const rooms = await retrieveRooms('65d79ed33377222a975829fa')
console.log('rooms retrieved', rooms)

await mongoose.disconnect()
} catch (error) {
console.log(error)
}
})()
10 changes: 10 additions & 0 deletions staff/miguel-arias/project/api/test/retrieve-profiles.test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
source colors.sh

echo -e "${blue}TEST retrieve-profiles${reset}"

echo
echo -e "${tomato}CASE failure on incorrect token${reset}"

curl 'http://localhost:8000/profiles' \
-H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2NWRhNDU4NzNmNjY2MDYxYmM1NGNmMWIiLCJpYXQiOjE3MDkxNjM0MDQsImV4cCI6MTcwOTE2NzAwNH0.CB6vPB5pFCKhViEsEkba9larS6_QpsQaxVXrFZ3-XfY' \
-v
2 changes: 1 addition & 1 deletion staff/miguel-arias/project/app/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ function App() {
else if (error instanceof DuplicityError || error instanceof NotFoundError)
level = 'error'
else if (error instanceof TokenError) {
logic.logoutUser(() => navigate('/login'))
logic.logoutHome(() => navigate('/login'))

message = 'Session expired'
}
Expand Down
14 changes: 8 additions & 6 deletions staff/miguel-arias/project/app/src/components/Calendar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ function Calendar(props) {

const refreshTemplates = async () => {
try {
const templates = await props.loadTemplates()
const templates = await logic.retrieveTemplates()

setTemplates(templates)
} catch (error) {
Expand All @@ -46,7 +46,7 @@ function Calendar(props) {

const refreshTasks = async () => {
try {
const tasks = await props.loadTasks()
const tasks = await logic.retrieveTasks()
// tasks = await logic.orderTasks(tasks)
setTasks(tasks)
} catch (error) {
Expand Down Expand Up @@ -159,7 +159,9 @@ function Calendar(props) {
let pincode = digit1 + digit2 + digit3 + digit4

try {
await completeTask(task.id, pincode, dateObject)
await logic.completeTask(task.id, pincode, dateObject)
refreshTasks()
setView(null)
} catch (error) {
context.handleError(error)
}
Expand All @@ -173,9 +175,9 @@ function Calendar(props) {
{tasks.map(task => <Task key={task.id} task={task} profileName={profiles.map(profile => task.assignee === profile.id ? profile.name : '')} onTaskClick={handleOnTaskClick} />)} {/* TODO move map to find */}

{view === 'react-to-task-view' && <Container>
{<h3>{helper.arrangeText(task.template.name)}</h3>}
{<h3>{helper.arrangeDate(task.date)}</h3>}
<h3>{profiles.map(profile => profile.id === task.assignee ? profile.name : '')}</h3>
{role === 'admin' && <h3>{helper.arrangeText(task.template.name)}</h3>}
{role === 'admin' && <h3>{helper.arrangeDate(task.date)}</h3>}
{role === 'admin' && <h3>{profiles.map(profile => profile.id === task.assignee ? profile.name : '')}</h3>}
{role !== null && <Button onClick={() => handleAssignThisTask(null)}>Take this task</Button>}
{role === 'admin' && <Button onClick={handleAssignThisTaskTo}>Assign this task to...</Button>}
{role !== null && <Button onClick={handleCompleteTaskClick}>Complete this task</Button>}
Expand Down
1 change: 1 addition & 0 deletions staff/miguel-arias/project/app/src/components/Profiles.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ function Profiles(props) {

{pinCode === 'pinCode' && <Container>
<Form onSubmit={handleSubmit}>
<h3>{name}</h3>
<p>Pin code</p>
<Input id='digit1' placeholder='-'></Input>
<Input id='digit2' placeholder='-'></Input>
Expand Down
Loading

0 comments on commit 1853a6f

Please sign in to comment.