Skip to content

Commit

Permalink
Create a new dateBase fix errors correct time errors add a timezone i…
Browse files Browse the repository at this point in the history
…n the backend to indicate that the time is UTC. Fix errors in trackList endpoints and add times and counters.
  • Loading branch information
Lourdesjupo committed Mar 1, 2024
1 parent 954d58a commit f3745fe
Show file tree
Hide file tree
Showing 10 changed files with 56 additions and 86 deletions.
17 changes: 9 additions & 8 deletions server/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ async function connectDb() {
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_DATABASE_NAME,
port:process.env.DB_PORT
port:process.env.DB_PORT,
timezone: 'Z'
});

await connection.connect();
Expand Down Expand Up @@ -67,7 +68,7 @@ server.post('/api/addonetaskchecked', async (req, res) => {
console.log('llamo');
const body = req.body;
let insert =
'INSERT INTO oneTaskCompleted (fkOneTask) VALUE (?)';
'INSERT INTO oneTaskCompleted (fkoneTask) VALUE (?)';
const connect = await connectDb();
const [resultInsert] = await connect.query(insert, [
body.id
Expand All @@ -82,7 +83,7 @@ server.post('/api/addonetaskchecked', async (req, res) => {
server.get('/api/getonetimetasks', async (req,res)=>{
const connect = await connectDb();
//const selectAll = "SELECT * from oneTask "
const selectAll = "SELECT oneTask.id,oneTask.name,oneTask.iconName,oneTask.createdAt,oneTask.alertQty,oneTask.alertUnits,completedDate FROM oneTask LEFT JOIN( SELECT fkOneTask, MAX(completedDate) as completedDate FROM oneTaskCompleted GROUP BY fkOneTask) lastComplete ON oneTask.id = lastComplete.fkOneTask"
const selectAll = "SELECT oneTask.idoneTask,oneTask.name,oneTask.iconName,oneTask.createdAt,oneTask.alertQty,oneTask.alertUnits,completedDate FROM oneTask LEFT JOIN( SELECT fkoneTask, MAX(completedDate) as completedDate FROM oneTaskCompleted GROUP BY fkoneTask) lastComplete ON oneTask.idoneTask = lastComplete.fkoneTask"
const[tasks] = await connect.query(selectAll)


Expand All @@ -95,7 +96,7 @@ server.post('/api/addonetaskchecked', async (req, res) => {
server.get('/api/getonetimecompletedata/:id', async (req, res) => {
const id = req.params.id;
const connect = await connectDb();
const selectAll = `select * FROM oneTask, oneTaskCompleted WHERE oneTask.id = oneTaskCompleted.fkOneTask AND id = ${id} order by completedDate DESC LIMIT 1`;
const selectAll = `select * FROM oneTask, oneTaskCompleted WHERE oneTask.idoneTask = oneTaskCompleted.fkoneTask AND id = ${id} order by completedDate DESC LIMIT 1`;
const [tasks] = await connect.query(selectAll);

console.log(tasks);
Expand Down Expand Up @@ -127,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 * from trackList ';
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 connect = await connectDb();
const [result] = await connect.query(selectAll);
console.log(result);
Expand All @@ -143,8 +144,8 @@ server.post('/api/addtracktask', async (req, res) => {
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.idTimeTrack, hoy])
insert = 'INSERT INTO trackTime (fktrackList,startTime) VALUES (?, ?)';
const [resultInsert] = await connect.query(insert, [req.body.idtrackTime, hoy])
res.json(
resultInsert
);
Expand All @@ -168,7 +169,7 @@ server.post('/api/addtracktask', async (req, res) => {

server.get('/api/allTracks/:id', async (req, res) => {
const id = req.params.id;
const allTaskTimes = `select * FROM trackTime, trackList WHERE trackList.id = trackTime.fkTrackList AND id= ? order by stopTime desc LIMIT 1;`;
const allTaskTimes = `select * FROM trackTime, trackList WHERE trackList.idtrackList = trackTime.fktrackList AND id= ? order by stopTime desc LIMIT 1;`;
const connect = await connectDb();
const [result] = await connect.query(allTaskTimes, [id]);
connect.end();
Expand Down
7 changes: 2 additions & 5 deletions src/components/AddTask_TrackTime.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { useState } from 'react';
import addTrackTask from '../services/ApiTrackTimeAdd';
import { Link } from 'react-router-dom';

// ESTIMATED TIME = ESTIMATED TIME MINS (El tiempo está calculado en minutos.)

function AddTask_TrackTime() {
const [color, setColor] = useState('#ffffff');
const [mins, setMins] = useState(0);
Expand All @@ -14,11 +16,6 @@ function AddTask_TrackTime() {
const mins2 =parseInt(mins)
const total = hoursInMinutes + mins2

console.log('total', total)




const handleName = (ev) => {
setName(ev.target.value);
};
Expand Down
84 changes: 27 additions & 57 deletions src/components/TrackedTimeItem.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,57 +14,25 @@ import addTimeTrack from '../services/ApiTrackTimeRecord';
import allTracks from '../services/ApiAllTracksAndTime';
import { useEffect } from 'react';

function TrackedTimeItem({ id, nameTask, color, estimatedTime, totalTime }) {
const [record, setRecord] = useState('play');
const [recordText, setRecordText] = useState('▶ Iniciar trabajo');
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}`

//{id: start: , stop: }
const [timer, setTimer] = useState({
useEffect(()=>{
setInterval(()=>{
setNow(new Date())
},60000)
},[])

});
const [currentTask, setCurrentTask] = useState({});
const [startTime, setStartTime] = useState('');
const [diff, setDiff] = useState('')
//const now = ;
console.log('DIFFF', diff )
const handleClick = (id) => {

// useEffect(()=>{
// if(diff)
// },[])



const handleRecord = (id) => {
if (record === 'play') {
setRecord('stop');
//Envío el id y que se ha clickado start
addTimeTrack({ clicked: 'start', idTimeTrack: id });
//const now = new Date().getTime()
// setInitialTime({id, startTime:now})
//Me traigo todas las tareas y las seteo en allTasks
allTracks(id).then((data) => {
setCurrentTask(data);
const date = new Date(data.startTime);
const miliseconds = date.getTime();
setStartTime(miliseconds);
setDiff(new Date(+new Date() - startTime))
//const mili = miliseconds.getTime()
// console.log('datitos', miliseconds);

setTimer({hours:'00',minutes:'00',seconds:'00'})
});

return setRecordText('▢ Detener trabajo');
} else {
setRecord('play');
addTimeTrack({ clicked: 'stop', idTimeTrack: id });
allTracks().then((data) => {
//setAllTasks(data);
});
// const now = new Date().getTime()
//setInitialTime({id, startTime:now})
return setRecordText('▶ Iniciar trabajo');
}
};

return (
Expand All @@ -89,25 +57,27 @@ function TrackedTimeItem({ id, nameTask, color, estimatedTime, totalTime }) {

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

<Typography>Tiempo de trabajo: {totalTime}</Typography>
<Stack alignItems='flex-end' justifyContent='center' spacing={5}>
</>)
}
{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>
</Stack> */}
</AccordionDetails>
</Accordion>
</>
Expand Down
4 changes: 3 additions & 1 deletion src/components/TrackedTimeList.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ function TrackedTimeList(){
console.log('listas de tareasm', listTasks)
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)
})

Expand All @@ -27,7 +28,8 @@ console.log('listas de tareasm', listTasks)
nameTask={task.name}
color={task.color}
estimatedTime={task.estimatedTime}
totalTime={task.totalTime}
elapsedTime={task.elapsedTime}
startTime={task.startTime}
/>
)
})}
Expand Down
7 changes: 0 additions & 7 deletions src/services/ApiAllTracksAndTime.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,6 @@ const allTracks = async (id)=>{
`${import.meta.env.VITE_CHRONOLOGICA_API}/api/allTracks/${id}`
);
const dataJson = await response.json();

// const start = dataJson[0].startTime

// const time = start.split('T')
// const hours = time[1].split('.')
// const[horas, minutos, segundos] = hours[0].split(':')

const time = dataJson[0].startTime;

console.log('tiempo', time);
Expand Down
2 changes: 1 addition & 1 deletion src/services/ApiOneTime.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export const getOneTimeListTasks = async () => {
const dataJson = await response.json();
const result = dataJson.map((task) => {
return {
id: task.id,
id: task.idoneTask,
name: task.name,
icon: task.iconName,
create: task.createdAt,
Expand Down
2 changes: 1 addition & 1 deletion src/services/ApiOneTimeAdd.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

function AddOneTask(data) {
return fetch(`${import.meta.env.CHRONOLOGICA_API}/api/addonetask`, {
return fetch(`${import.meta.env.VITE_CHRONOLOGICA_API}/api/addonetask`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(data),
Expand Down
10 changes: 7 additions & 3 deletions src/services/ApiTrackTimeRecord.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
function addTimeTrack (param) {
fetch(`${import.meta.env.CHRONOLOGICA_API}/api/addTimeTrack`, {



function addTimeTrack (command, id) {
console.log( command, id );
fetch(`${import.meta.env.VITE_CHRONOLOGICA_API}/api/addTimeTrack`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(param),
body: JSON.stringify(command, id ),
})
.then((response) => response.json())
.then((result) => {
Expand Down
8 changes: 5 additions & 3 deletions src/services/ApiTrackedTime.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ export const getTrackedListTasks = async ()=> {
const dataJson= await response.json()
const result = dataJson.map((task) => {
return {
id: task.id,
id: task.idtrackList,
name: task.nameTask,
color:task.color,
estimatedTime: task.estimatedTime
color: task.color,
estimatedTime: task.estimatedTime,
elapsedTime: task.elapsedTime,
startTime: task.startTime ? new Date(task.startTime) : undefined
};
});

Expand Down
1 change: 1 addition & 0 deletions src/services/CalculateTime.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ function CalculateTime(response) {
}

lastClick = new Date(response.lastComplete);
//console.log('lastClick:', lastClick, 'and last complete: ', response.lastComplete)

const result = sumarDias(lastClick, daysForReminder);

Expand Down

0 comments on commit f3745fe

Please sign in to comment.