aboutsummaryrefslogtreecommitdiffstats
path: root/src/views/Chores/MyChores.jsx
blob: d4eed5a3300908e10af52d7d8d2211d05fabc555 (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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
import { Add, CancelRounded, EditCalendar } from '@mui/icons-material'
import {
  Badge,
  Box,
  Checkbox,
  Container,
  IconButton,
  Input,
  List,
  ListItem,
  Menu,
  MenuItem,
  Snackbar,
  Typography,
} from '@mui/joy'
import Fuse from 'fuse.js'
import { useContext, useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { UserContext } from '../../contexts/UserContext'
import { GetAllUsers, GetChores, GetUserProfile } from '../../utils/Fetcher'
import LoadingComponent from '../components/Loading'
import ChoreCard from './ChoreCard'

const MyChores = () => {
  const { userProfile, setUserProfile } = useContext(UserContext)
  const [isSnackbarOpen, setIsSnackbarOpen] = useState(false)
  const [snackBarMessage, setSnackBarMessage] = useState(null)
  const [chores, setChores] = useState([])
  const [filteredChores, setFilteredChores] = useState([])
  const [selectedFilter, setSelectedFilter] = useState('All')
  const [searchTerm, setSearchTerm] = useState('')
  const [activeUserId, setActiveUserId] = useState(0)
  const [performers, setPerformers] = useState([])
  const [anchorEl, setAnchorEl] = useState(null)
  const menuRef = useRef(null)
  const Navigate = useNavigate()
  const choreSorter = (a, b) => {
    // 1. Handle null due dates (always last):
    if (!a.nextDueDate && !b.nextDueDate) return 0 // Both null, no order
    if (!a.nextDueDate) return 1 // a is null, comes later
    if (!b.nextDueDate) return -1 // b is null, comes earlier

    const aDueDate = new Date(a.nextDueDate)
    const bDueDate = new Date(b.nextDueDate)
    const now = new Date()

    const oneDayInMs = 24 * 60 * 60 * 1000

    // 2. Prioritize tasks due today +- 1 day:
    const aTodayOrNear = Math.abs(aDueDate - now) <= oneDayInMs
    const bTodayOrNear = Math.abs(bDueDate - now) <= oneDayInMs
    if (aTodayOrNear && !bTodayOrNear) return -1 // a is closer
    if (!aTodayOrNear && bTodayOrNear) return 1 // b is closer

    // 3. Handle overdue tasks (excluding today +- 1):
    const aOverdue = aDueDate < now && !aTodayOrNear
    const bOverdue = bDueDate < now && !bTodayOrNear
    if (aOverdue && !bOverdue) return -1 // a is overdue, comes earlier
    if (!aOverdue && bOverdue) return 1 // b is overdue, comes earlier

    // 4. Sort future tasks by due date:
    return aDueDate - bDueDate // Sort ascending by due date
  }

  const handleSelectedFilter = selected => {
    setFilteredChores(FILTERS[selected](chores))

    setSelectedFilter(selected)
  }

  useEffect(() => {
    if (userProfile === null) {
      GetUserProfile()
        .then(response => response.json())
        .then(data => {
          setUserProfile(data.res)
        })
    }
    GetChores()
      .then(response => response.json())
      .then(data => {
        data.res.sort(choreSorter)
        setChores(data.res)

        setFilteredChores(data.res)
      })

    GetAllUsers()
      .then(response => response.json())
      .then(data => {
        setPerformers(data.res)
      })

    const currentUser = JSON.parse(localStorage.getItem('user'))
    if (currentUser !== null) {
      setActiveUserId(currentUser.id)
    }
  }, [])
  useEffect(() => {
    document.addEventListener('mousedown', handleMenuOutsideClick)
    return () => {
      document.removeEventListener('mousedown', handleMenuOutsideClick)
    }
  }, [anchorEl])
  const handleMenuOutsideClick = event => {
    if (
      anchorEl &&
      !anchorEl.contains(event.target) &&
      !menuRef.current.contains(event.target)
    ) {
      handleFilterMenuClose()
    }
  }
  const handleFilterMenuOpen = event => {
    event.preventDefault()
    setAnchorEl(event.currentTarget)
  }

  const handleFilterMenuClose = () => {
    setAnchorEl(null)
  }
  const handleChoreUpdated = (updatedChore, event) => {
    const newChores = chores.map(chore => {
      if (chore.id === updatedChore.id) {
        return updatedChore
      }
      return chore
    })

    const newFilteredChores = filteredChores.map(chore => {
      if (chore.id === updatedChore.id) {
        return updatedChore
      }
      return chore
    })
    setChores(newChores)
    setFilteredChores(newFilteredChores)
    switch (event) {
      case 'completed':
        setSnackBarMessage('Completed')
        break
      case 'skipped':
        setSnackBarMessage('Skipped')
        break
      case 'rescheduled':
        setSnackBarMessage('Rescheduled')
        break
      default:
        setSnackBarMessage('Updated')
    }
    setIsSnackbarOpen(true)
  }

  const handleChoreDeleted = deletedChore => {
    const newChores = chores.filter(chore => chore.id !== deletedChore.id)
    const newFilteredChores = filteredChores.filter(
      chore => chore.id !== deletedChore.id,
    )
    setChores(newChores)
    setFilteredChores(newFilteredChores)
  }

  const searchOptions = {
    // keys to search in
    keys: ['name', 'labels'],
    includeScore: true, // Optional: if you want to see how well each result matched the search term
    isCaseSensitive: false,
    findAllMatches: true,
  }
  const fuse = new Fuse(chores, searchOptions)

  const handleSearchChange = e => {
    const search = e.target.value
    if (search === '') {
      setFilteredChores(chores)
      setSearchTerm('')
      return
    }

    const term = search.toLowerCase()
    setSearchTerm(term)
    setFilteredChores(fuse.search(term).map(result => result.item))
  }

  if (userProfile === null) {
    return <LoadingComponent />
  }

  return (
    <Container maxWidth='md'>
      {/* <Typography level='h3' mb={1.5}>
        My Chores
      </Typography> */}
      {/* <Sheet> */}
      <List
        orientation='horizontal'
        wrap
        sx={{
          '--List-gap': '8px',
          '--ListItem-radius': '20px',
          '--ListItem-minHeight': '32px',
          '--ListItem-gap': '4px',
          mt: 0.2,
        }}
      >
        {['All', 'Overdue', 'Due today', 'Due in week'].map(filter => (
          <Badge
            key={filter}
            anchorOrigin={{
              vertical: 'top',
              horizontal: 'right',
            }}
            variant='outlined'
            color={selectedFilter === filter ? 'primary' : 'neutral'}
            badgeContent={FILTERS[filter](chores).length}
            badgeInset={'5px'}
          >
            <ListItem key={filter}>
              <Checkbox
                key={'checkbox' + filter}
                label={filter}
                onClick={() => handleSelectedFilter(filter)}
                checked={filter === selectedFilter}
                disableIcon
                overlay
                size='sm'
              />
            </ListItem>
          </Badge>
        ))}

        <ListItem onClick={handleFilterMenuOpen}>
          <Checkbox key='checkboxAll' label='⋮' disableIcon overlay size='lg' />
        </ListItem>
        <Menu
          ref={menuRef}
          anchorEl={anchorEl}
          open={Boolean(anchorEl)}
          onClose={handleFilterMenuClose}
        >
          <MenuItem
            onClick={() => {
              setFilteredChores(
                FILTERS['Assigned To Me'](chores, userProfile.id),
              )
              setSelectedFilter('Assigned To Me')
              handleFilterMenuClose()
            }}
          >
            Assigned to me
          </MenuItem>
          <MenuItem
            onClick={() => {
              setFilteredChores(
                FILTERS['Created By Me'](chores, userProfile.id),
              )
              setSelectedFilter('Created By Me')
              handleFilterMenuClose()
            }}
          >
            Created by me
          </MenuItem>
          <MenuItem
            onClick={() => {
              setFilteredChores(FILTERS['No Due Date'](chores, userProfile.id))
              setSelectedFilter('No Due Date')
              handleFilterMenuClose()
            }}
          >
            No Due Date
          </MenuItem>
        </Menu>
      </List>
      {/* Search box to filter  */}
      <Box>
        <Input
          placeholder='Search'
          value={searchTerm}
          sx={{
            mt: 1,
            mb: 1,
            borderRadius: 20,
            // border: '1px solid',
            borderColor: 'text.disabled',
            padding: 1,
          }}
          onChange={handleSearchChange}
          endDecorator={
            searchTerm && (
              <CancelRounded
                onClick={() => {
                  setSearchTerm('')
                  setFilteredChores(chores)
                }}
              />
            )
          }
        />
      </Box>

      {/* </Sheet> */}
      {filteredChores.length === 0 && (
        <Box
          sx={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            flexDirection: 'column',
            height: '50vh',
          }}
        >
          <EditCalendar
            sx={{
              fontSize: '4rem',
              // color: 'text.disabled',
              mb: 1,
            }}
          />
          <Typography level='title-md' gutterBottom>
            Nothing scheduled
          </Typography>
        </Box>
      )}

      {filteredChores.map(chore => (
        <ChoreCard
          key={chore.id}
          chore={chore}
          onChoreUpdate={handleChoreUpdated}
          onChoreRemove={handleChoreDeleted}
          performers={performers}
        />
      ))}

      <Box
        // variant='outlined'
        sx={{
          position: 'fixed',
          bottom: 0,
          left: 10,
          p: 2, // padding
          display: 'flex',
          justifyContent: 'flex-end',
          gap: 2,
          'z-index': 1000,
        }}
      >
        <IconButton
          color='primary'
          variant='solid'
          sx={{
            borderRadius: '50%',
            width: 50,
            height: 50,
          }}
          //   startDecorator={<Add />}
          onClick={() => {
            Navigate(`/chores/create`)
          }}
        >
          <Add />
        </IconButton>
      </Box>
      <Snackbar
        open={isSnackbarOpen}
        onClose={() => {
          setIsSnackbarOpen(false)
        }}
        autoHideDuration={3000}
        variant='soft'
        color='success'
        size='lg'
        invertedColors
      >
        <Typography level='title-md'>{snackBarMessage}</Typography>
      </Snackbar>
    </Container>
  )
}

const FILTERS = {
  All: function (chores) {
    return chores
  },
  Overdue: function (chores) {
    return chores.filter(chore => {
      if (chore.nextDueDate === null) return false
      return new Date(chore.nextDueDate) < new Date()
    })
  },
  'Due today': function (chores) {
    return chores.filter(chore => {
      return (
        new Date(chore.nextDueDate).toDateString() === new Date().toDateString()
      )
    })
  },
  'Due in week': function (chores) {
    return chores.filter(chore => {
      return (
        new Date(chore.nextDueDate) <
          new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) &&
        new Date(chore.nextDueDate) > new Date()
      )
    })
  },
  'Created By Me': function (chores, userID) {
    return chores.filter(chore => {
      return chore.createdBy === userID
    })
  },
  'Assigned To Me': function (chores, userID) {
    return chores.filter(chore => {
      return chore.assignedTo === userID
    })
  },
  'No Due Date': function (chores, userID) {
    return chores.filter(chore => {
      return chore.nextDueDate === null
    })
  },
}

export default MyChores