aboutsummaryrefslogtreecommitdiffstats
path: root/src/views/History/ChoreHistory.jsx
blob: 22ea6a9b842f7d44ab0ee5ff409f6ffa186daa69 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import { Checklist, EventBusy, Timelapse } from '@mui/icons-material'
import {
  Avatar,
  Box,
  Button,
  Chip,
  CircularProgress,
  Container,
  Grid,
  List,
  ListDivider,
  ListItem,
  ListItemContent,
  ListItemDecorator,
  Sheet,
  Typography,
} from '@mui/joy'
import moment from 'moment'
import React, { useEffect, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { API_URL } from '../../Config'
import { GetAllCircleMembers } from '../../utils/Fetcher'
import { Fetch } from '../../utils/TokenManager'

const ChoreHistory = () => {
  const [choreHistory, setChoresHistory] = useState([])
  const [userHistory, setUserHistory] = useState([])
  const [performers, setPerformers] = useState([])
  const [historyInfo, setHistoryInfo] = useState([])

  const [isLoading, setIsLoading] = useState(true) // Add loading state
  const { choreId } = useParams()

  useEffect(() => {
    setIsLoading(true) // Start loading

    Promise.all([
      Fetch(`${API_URL}/chores/${choreId}/history`).then(res => res.json()),
      GetAllCircleMembers().then(res => res.json()),
    ])
      .then(([historyData, usersData]) => {
        setChoresHistory(historyData.res)

        const newUserChoreHistory = {}
        historyData.res.forEach(choreHistory => {
          const userId = choreHistory.completedBy
          newUserChoreHistory[userId] = (newUserChoreHistory[userId] || 0) + 1
        })
        setUserHistory(newUserChoreHistory)

        setPerformers(usersData.res)
        updateHistoryInfo(historyData.res, newUserChoreHistory, usersData.res)
      })
      .catch(error => {
        console.error('Error fetching data:', error)
        // Handle errors, e.g., show an error message to the user
      })
      .finally(() => {
        setIsLoading(false) // Finish loading
      })
  }, [choreId])

  const updateHistoryInfo = (histories, userHistories, performers) => {
    // average delay for task completaion from due date:

    const averageDelay =
      histories.reduce((acc, chore) => {
        if (chore.dueDate) {
          // Only consider chores with a due date
          return acc + moment(chore.completedAt).diff(chore.dueDate, 'hours')
        }
        return acc
      }, 0) / histories.length
    const averageDelayMoment = moment.duration(averageDelay, 'hours')
    const maximumDelay = histories.reduce((acc, chore) => {
      if (chore.dueDate) {
        // Only consider chores with a due date
        const delay = moment(chore.completedAt).diff(chore.dueDate, 'hours')
        return delay > acc ? delay : acc
      }
      return acc
    }, 0)

    const maxDelayMoment = moment.duration(maximumDelay, 'hours')

    // find max value in userHistories:
    const userCompletedByMost = Object.keys(userHistories).reduce((a, b) =>
      userHistories[a] > userHistories[b] ? a : b,
    )
    const userCompletedByLeast = Object.keys(userHistories).reduce((a, b) =>
      userHistories[a] < userHistories[b] ? a : b,
    )

    const historyInfo = [
      {
        icon: (
          <Avatar>
            <Checklist />
          </Avatar>
        ),
        text: `${histories.length} completed`,
        subtext: `${Object.keys(userHistories).length} users contributed`,
      },
      {
        icon: (
          <Avatar>
            <Timelapse />
          </Avatar>
        ),
        text: `Completed within ${moment
          .duration(averageDelayMoment)
          .humanize()}`,
        subtext: `Maximum delay was ${moment
          .duration(maxDelayMoment)
          .humanize()}`,
      },
      {
        icon: <Avatar></Avatar>,
        text: `${
          performers.find(p => p.userId === Number(userCompletedByMost))
            ?.displayName
        } completed most`,
        subtext: `${userHistories[userCompletedByMost]} time/s`,
      },
    ]
    if (userCompletedByLeast !== userCompletedByMost) {
      historyInfo.push({
        icon: (
          <Avatar>
            {
              performers.find(p => p.userId === userCompletedByLeast)
                ?.displayName
            }
          </Avatar>
        ),
        text: `${
          performers.find(p => p.userId === Number(userCompletedByLeast))
            .displayName
        } completed least`,
        subtext: `${userHistories[userCompletedByLeast]} time/s`,
      })
    }

    setHistoryInfo(historyInfo)
  }

  function formatTimeDifference(startDate, endDate) {
    const diffInMinutes = moment(startDate).diff(endDate, 'minutes')
    let timeValue = diffInMinutes
    let unit = 'minute'

    if (diffInMinutes >= 60) {
      const diffInHours = moment(startDate).diff(endDate, 'hours')
      timeValue = diffInHours
      unit = 'hour'

      if (diffInHours >= 24) {
        const diffInDays = moment(startDate).diff(endDate, 'days')
        timeValue = diffInDays
        unit = 'day'
      }
    }

    return `${timeValue} ${unit}${timeValue !== 1 ? 's' : ''}`
  }
  if (isLoading) {
    return <CircularProgress /> // Show loading indicator
  }
  if (!choreHistory.length) {
    return (
      <Container
        maxWidth='md'
        sx={{
          textAlign: 'center',
          display: 'flex',
          // make sure the content is centered vertically:
          alignItems: 'center',
          justifyContent: 'center',
          flexDirection: 'column',
          height: '50vh',
        }}
      >
        <EventBusy
          sx={{
            fontSize: '6rem',
            // color: 'text.disabled',
            mb: 1,
          }}
        />

        <Typography level='h3' gutterBottom>
          No History Yet
        </Typography>
        <Typography level='body1'>
          You haven't completed any tasks. Once you start finishing tasks,
          they'll show up here.
        </Typography>
        <Button variant='soft' sx={{ mt: 2 }}>
          <Link to='/my/chores'>Go back to chores</Link>
        </Button>
      </Container>
    )
  }

  return (
    <Container maxWidth='md'>
      <Typography level='h3' mb={1.5}>
        Summary:
      </Typography>
      {/* <Sheet sx={{ mb: 1, borderRadius: 'sm', p: 2, boxShadow: 'md' }}>
        <ListItem sx={{ gap: 1.5 }}>
          <ListItemDecorator>
            <Avatar>
              <AccountCircle />
            </Avatar>
          </ListItemDecorator>
          <ListItemContent>
            <Typography level='body1' sx={{ fontWeight: 'md' }}>
              {choreHistory.length} completed
            </Typography>
            <Typography level='body2' color='text.tertiary'>
              {Object.keys(userHistory).length} users contributed
            </Typography>
          </ListItemContent>
        </ListItem>
      </Sheet> */}
      <Grid container>
        {historyInfo.map((info, index) => (
          <Grid key={index} item xs={12} sm={6}>
            <Sheet sx={{ mb: 1, borderRadius: 'sm', p: 2, boxShadow: 'md' }}>
              <ListItem sx={{ gap: 1.5 }}>
                <ListItemDecorator>{info.icon}</ListItemDecorator>
                <ListItemContent>
                  <Typography level='body1' sx={{ fontWeight: 'md' }}>
                    {info.text}
                  </Typography>
                  <Typography level='body1' color='text.tertiary'>
                    {info.subtext}
                  </Typography>
                </ListItemContent>
              </ListItem>
            </Sheet>
          </Grid>
        ))}
      </Grid>
      {/* User History Cards */}
      <Typography level='h3' my={1.5}>
        History:
      </Typography>
      <Box sx={{ borderRadius: 'sm', p: 2, boxShadow: 'md' }}>
        {/* Chore History List (Updated Style) */}

        <List sx={{ p: 0 }}>
          {choreHistory.map((chore, index) => (
            <>
              <ListItem sx={{ gap: 1.5, alignItems: 'flex-start' }}>
                {' '}
                {/* Adjusted spacing and alignment */}
                <ListItemDecorator>
                  <Avatar sx={{ mr: 1 }}>
                    {performers
                      .find(p => p.userId === chore.completedBy)
                      ?.displayName?.charAt(0) || '?'}
                  </Avatar>
                </ListItemDecorator>
                <ListItemContent sx={{ my: 0 }}>
                  {' '}
                  {/* Removed vertical margin */}
                  <Box
                    sx={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                    }}
                  >
                    <Typography level='body1' sx={{ fontWeight: 'md' }}>
                      {moment(chore.completedAt).format('ddd MM/DD/yyyy HH:mm')}
                    </Typography>

                    <Chip>
                      {chore.dueDate && chore.completedAt > chore.dueDate
                        ? 'Late'
                        : 'On Time'}
                    </Chip>
                  </Box>
                  <Typography level='body2' color='text.tertiary'>
                    <Chip>
                      {
                        performers.find(p => p.userId === chore.completedBy)
                          ?.displayName
                      }
                    </Chip>{' '}
                    completed
                    {chore.completedBy !== chore.assignedTo && (
                      <>
                        {', '}
                        assigned to{' '}
                        <Chip>
                          {
                            performers.find(p => p.userId === chore.assignedTo)
                              ?.displayName
                          }
                        </Chip>
                      </>
                    )}
                  </Typography>
                  {chore.dueDate && (
                    <Typography level='body2' color='text.tertiary'>
                      Due: {moment(chore.dueDate).format('ddd MM/DD/yyyy')}
                    </Typography>
                  )}
                  {chore.notes && (
                    <Typography level='body2' color='text.tertiary'>
                      Note: {chore.notes}
                    </Typography>
                  )}
                </ListItemContent>
              </ListItem>
              {index < choreHistory.length - 1 && (
                <>
                  <ListDivider component='li'>
                    {/* time between two completion: */}
                    {index < choreHistory.length - 1 &&
                      choreHistory[index + 1].completedAt && (
                        <Typography level='body3' color='text.tertiary'>
                          {formatTimeDifference(
                            chore.completedAt,
                            choreHistory[index + 1].completedAt,
                          )}{' '}
                          before
                        </Typography>
                      )}
                  </ListDivider>
                </>
              )}
            </>
          ))}
        </List>
      </Box>
    </Container>
  )
}

export default ChoreHistory