FitTrackee/fittrackee_client/src/utils/stats.js

109 lines
2.9 KiB
JavaScript
Raw Normal View History

2019-01-04 10:07:24 +01:00
import {
addDays,
addMonths,
addYears, format, startOfMonth,
startOfWeek,
startOfYear
} from 'date-fns'
const xAxisFormats = [
{ duration: 'week', dateFormat: 'YYYY-MM-DD', xAxis: 'DD/MM' },
{ duration: 'month', dateFormat: 'YYYY-MM', xAxis: 'MM/YYYY' },
{ duration: 'year', dateFormat: 'YYYY', xAxis: 'YYYY' },
]
export const formatDuration = (totalSeconds, formatWithDay = false) => {
let days = '0'
if (formatWithDay) {
days = String(Math.floor(totalSeconds / 86400))
totalSeconds %= 86400
}
const hours = String(Math.floor(totalSeconds / 3600)).padStart(2, '0')
totalSeconds %= 3600
const minutes = String(Math.floor(totalSeconds / 60)).padStart(2, '0')
const seconds = String(totalSeconds % 60).padStart(2, '0')
if (formatWithDay) {
return `${
days === '0' ? '' : `${days}d:`
}${
hours === '00' ? '' : `${hours}h:`
}${minutes}m:${seconds}s`
}
return `${hours === '00' ? '' : `${hours}:`}${minutes}:${seconds}`
}
export const formatChartData = chartData => {
for (let i = 0; i < chartData.length; i++) {
chartData[i].time = new Date(chartData[i].time).getTime()
chartData[i].duration = formatDuration(chartData[i].duration)
}
return chartData
}
const dateIncrement = (duration, day) => {
switch (duration) {
case 'week':
return addDays(day, 7)
case 'year':
return addYears(day, 1)
case 'month':
default:
return addMonths(day, 1)
}
}
const startDate = (duration, day) => {
switch (duration) {
case 'week':
return startOfWeek(day)
case 'year':
return startOfYear(day)
case 'month':
default:
return startOfMonth(day)
}
}
export const formatStats = (
stats, sports, params
) => {
const nbActivitiesStats = []
const distanceStats = []
const durationStats = []
for (let day = startDate(params.duration, params.start);
day <= params.end;
day = dateIncrement(params.duration, day)
) {
const [xAxisFormat] = xAxisFormats.filter(
x => x.duration === params.duration
)
const date = format(day, xAxisFormat.dateFormat)
const xAxis = format(day, xAxisFormat.xAxis)
const dataNbActivities = { date: xAxis }
const dataDistance = { date: xAxis }
const dataDuration = { date: xAxis }
if (stats[date]) {
Object.keys(stats[date]).map(sportId => {
const sportLabel = sports.filter(s => s.id === +sportId)[0].label
dataNbActivities[sportLabel] = stats[date][sportId].nb_activities
dataDistance[sportLabel] = stats[date][sportId].total_distance
dataDuration[sportLabel] = stats[date][sportId].total_duration
return null
})
}
nbActivitiesStats.push(dataNbActivities)
distanceStats.push(dataDistance)
durationStats.push(dataDuration)
}
return {
activities: nbActivitiesStats,
distance: distanceStats,
duration: durationStats
}
}