Skip to content

Commit

Permalink
Add trackTime start and Stop and calculate de elapsed time. Modify m…
Browse files Browse the repository at this point in the history
…essages in tracktime about times
  • Loading branch information
Lourdesjupo committed Mar 4, 2024
1 parent f3745fe commit 9f99965
Show file tree
Hide file tree
Showing 5 changed files with 119 additions and 76 deletions.
57 changes: 33 additions & 24 deletions server/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ server.post('/api/addtracktask', async (req, res) => {

//Get lista de tareas TrackList
server.get('/api/tracktasklist', async (req, res) => {
const selectAll = 'SELECT tl.idtrackList, tl.nameTask, tl.color, tl.estimatedTime, tl.elapsedTime, tt.startTime FROM trackList as tl LEFT JOIN trackTime as tt ON tl.idtrackList = tt.fktrackList WHERE tt.stopTime is NULL';
const selectAll = `SELECT tl.idtrackList, tl.nameTask, tl.color, tl.estimatedTime, tl.elapsedTime, MAX(tt.startTime) AS startTime, (SELECT stopTime FROM trackTime WHERE fktrackList = tl.idtrackList AND startTime = MAX(tt.startTime)) AS stopTime FROM trackList AS tl LEFT JOIN trackTime AS tt ON tl.idtrackList = tt.fktrackList GROUP BY tl.idtrackList, tl.nameTask, tl.color, tl.estimatedTime, tl.elapsedTime;`
const connect = await connectDb();
const [result] = await connect.query(selectAll);
console.log(result);
Expand All @@ -139,30 +139,39 @@ server.post('/api/addtracktask', async (req, res) => {
//guardar el dato de stop/start de tracktime

server.post('/api/addTimeTrack', async(req,res)=>{
console.log(req.body)
const hoy = new Date();
const connect = await connectDb();
let insert
if(req.body.clicked === 'start'){
insert = 'INSERT INTO trackTime (fktrackList,startTime) VALUES (?, ?)';
const [resultInsert] = await connect.query(insert, [req.body.idtrackTime, hoy])
res.json(
resultInsert
);
} else{
const lastStartTimeForfkTrackList =
'UPDATE freedb_chronoLogica.trackTime SET stopTime = ? where fkTrackList = ? and stopTime IS NULL';
// insert = 'INSERT INTO trackTime (fkTrackList,stopTime) VALUES (?, ?)';
const [resultInsert] = await connect.query(lastStartTimeForfkTrackList, [
hoy,
req.body.idTimeTrack,
]);

connect.end();
res.json(resultInsert);
}


if (
!req.body.id ||
!req.body.action ||
(req.body.action !== 'stop' && req.body.action !== 'start')
) {
return res.status(400).send('Invalid request')
}

const now = new Date();
const connect = await connectDb();
let insert
if(req.body.action === 'start'){
insert = 'INSERT INTO trackTime (fktrackList,startTime) VALUES (?, ?)';
await connect.query(insert, [req.body.id, now])
} else {
const lastStartTimeForfkTrackList = 'UPDATE trackTime SET stopTime = ? where fkTrackList = ? and stopTime IS NULL';
await connect.query(lastStartTimeForfkTrackList, [
now,
req.body.id,
]);
const startTime ='select MAX(startTime) as startTime from trackTime where fkTrackList = ?';
const [[{startTime: st}]] = await connect.query(startTime, [
req.body.id,
]);

const elTimeMins = (now - st) / 1000 / 60;
console.log('elTimeMins', elTimeMins);
const elapsedTime = 'UPDATE trackList SET elapsedTime = elapsedTime + ? WHERE idtrackList = ?'
await connect.query(elapsedTime, [elTimeMins, req.body.id]);
connect.end();
}
res.status(200).end();
});

//Get all tasks and times
Expand Down
91 changes: 56 additions & 35 deletions src/components/TrackedTimeItem.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,45 @@ import addTimeTrack from '../services/ApiTrackTimeRecord';
import allTracks from '../services/ApiAllTracksAndTime';
import { useEffect } from 'react';

function TrackedTimeItem({ id, nameTask, color, estimatedTime, elapsedTime, startTime }) {
const [taskStatus, setTaskStatus] = useState(startTime ? 'running':'stopped');
// console.log('tipo de startTime',typeof startTime, 'startTime:', startTime)
const [now, setNow] = useState (new Date())
const sessionTimeSecs = Math.round((now - startTime)/1000)
const totalMinutes = Math.floor(sessionTimeSecs / 60)
const hours = Math.floor(totalMinutes / 60)
const minutes = totalMinutes % 60
const secs = sessionTimeSecs % 60
const timer = `${hours < 10 ? '0' : ''}${hours} : ${minutes < 10 ? '0' : ''}${minutes} : ${secs < 10 ? '0' : ''}${secs}`
function TrackedTimeItem({
id,
nameTask,
color,
estimatedTime,
elapsedTime,
startTime,
stopTime,
onTaskStatusAction,
}) {
const taskStatus = startTime && !stopTime ? 'running' : 'stopped';
const [loading, setLoading] = useState(false);
const [now, setNow] = useState(new Date());
const sessionTimeSecs = Math.round((now - startTime) / 1000);
const totalMinutes = Math.floor(sessionTimeSecs / 60);
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
const secs = sessionTimeSecs % 60;
const timer = `${hours < 10 ? '0' : ''}${hours} : ${
minutes < 10 ? '0' : ''
}${minutes} : ${secs < 10 ? '0' : ''}${secs}`;

useEffect(()=>{
setInterval(()=>{
setNow(new Date())
},60000)
},[])

const handleClick = (id) => {
useEffect(() => {
setInterval(() => {
setNow(new Date());
}, 1000);
}, []);

const handleClick = async (ev) => {
ev.preventDefault()
setLoading(true);
await onTaskStatusAction(id, taskStatus === 'running' ? 'stop' : 'start');
setLoading(false);
};

return (
<>
<Accordion>
<AccordionSummary expandIcon={<ExpandMoreIcon />} id={id}>
<AccordionSummary expandIcon={<ExpandMoreIcon />} id={id}>
<Paper
variant='outlined'
sx={{ width: 10, backgroundColor: color }}
Expand All @@ -55,29 +69,36 @@ function TrackedTimeItem({ id, nameTask, color, estimatedTime, elapsedTime, star
{nameTask}
</Typography>

<Button
onClick={() => {
handleClick();
<Button
onClick={(ev) => {
ev.preventDefault()
handleClick(ev);
}}
>
{' '}
{taskStatus === 'running' ? '▢ Detener trabajo': '▶ Iniciar trabajo'}
{taskStatus === 'running'
? '▢ Detener trabajo'
: '▶ Iniciar trabajo'}
</Button>
{/* <Button onClick={handleRecord} > ▶ Iniciar trabajo</Button>
<Button sx={{}} > ▢ Detener trabajo</Button> */}
</AccordionSummary>
<AccordionDetails sx={{ backgroundColor: '#F6F4F8' }}>
{estimatedTime !== 0 &&
(<>
<Typography>Tiempo estimado finalización tarea: {estimatedTime}</Typography>
<Typography>Tiempo restante: {estimatedTime - elapsedTime}</Typography>

</>)
}
{taskStatus === 'running' && (<Typography>Tiempo de trabajo: {timer}</Typography>) }
{/* <Stack alignItems='flex-end' justifyContent='center' spacing={5}>
<Typography>{timer.hours}: {timer.minutes}:{timer.seconds}</Typography>
</Stack> */}
{estimatedTime !== 0 ? (
<>
<Typography>
Tiempo estimado finalización tarea: {estimatedTime}
</Typography>
<Typography>
Tiempo restante: {Math.round(estimatedTime - elapsedTime)}
</Typography>
</>
) : (
<>
<Typography>Tiempo invertido: {Math.round(elapsedTime)}</Typography>
</>
)}
{taskStatus === 'running' && (
<Typography>Tiempo de trabajo: {timer}</Typography>
)}
</AccordionDetails>
</Accordion>
</>
Expand Down
30 changes: 24 additions & 6 deletions src/components/TrackedTimeList.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,32 @@ import { getTrackedListTasks } from "../services/ApiTrackedTime";
import TrackedTimeItem from "./TrackedTimeItem";
import { Button, Stack, Typography } from "@mui/material";
import { Link } from "react-router-dom";
import addTimeTrack from "../services/ApiTrackTimeRecord";


function TrackedTimeList(){
//listTask = {color: rgb..., estimatedTime: int, id, name: string}

const [listTasks,setListTasks] = useState([])
console.log('listas de tareasm', listTasks)

async function handleTaskStatusAction (id, action) {
console.log(1)
await addTimeTrack(id, action)
console.log(2)
console.log('addTimeTrack:', id,action)
await loadTasks ()
}

async function loadTasks() {
const trackedListTask = await getTrackedListTasks()
// @TODO: PONER VALIDACIONES DEL TRACKED LIST EJ;
//que los tipos sean correctos y que existan los datos (campos no vacios)
setListTasks(trackedListTask)
}


useEffect (()=>{
getTrackedListTasks().then((trackedListTask)=>{
// @TODO: PONER VALIDACIONES DEL TRACKED LIST EJ;que los tipos sean correctos y que existan los datos (campos no vacios)
setListTasks(trackedListTask)
})

loadTasks ()
},[])

return (
Expand All @@ -30,6 +46,8 @@ console.log('listas de tareasm', listTasks)
estimatedTime={task.estimatedTime}
elapsedTime={task.elapsedTime}
startTime={task.startTime}
stopTime={task.stopTime}
onTaskStatusAction={handleTaskStatusAction}
/>
)
})}
Expand Down
14 changes: 4 additions & 10 deletions src/services/ApiTrackTimeRecord.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@

//Añadir Stop / Start a una tarea


function addTimeTrack (command, id) {
console.log( command, id );
fetch(`${import.meta.env.VITE_CHRONOLOGICA_API}/api/addTimeTrack`, {
async function addTimeTrack(id, action) {
await fetch(`${import.meta.env.VITE_CHRONOLOGICA_API}/api/addTimeTrack`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(command, id ),
body: JSON.stringify({ id, action}),
})
.then((response) => response.json())
.then((result) => {
console.log('API', result);
return result;
});
}


Expand Down
3 changes: 2 additions & 1 deletion src/services/ApiTrackedTime.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ export const getTrackedListTasks = async ()=> {
color: task.color,
estimatedTime: task.estimatedTime,
elapsedTime: task.elapsedTime,
startTime: task.startTime ? new Date(task.startTime) : undefined
startTime: task.startTime ? new Date(task.startTime) : undefined,
stopTime: task.stopTime ? new Date(task.stopTime) : undefined
};
});

Expand Down

0 comments on commit 9f99965

Please sign in to comment.