aboutsummaryrefslogtreecommitdiffstats
path: root/src/views/ChoresOverview.jsx
blob: 396ab0d17faef1c2456d4a32a595c3684cd4103a (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
import {
  Adjust,
  CancelRounded,
  CheckBox,
  Edit,
  HelpOutline,
  History,
  QueryBuilder,
  SearchRounded,
  Warning,
} from '@mui/icons-material'
import {
  Avatar,
  Button,
  ButtonGroup,
  Chip,
  Container,
  Grid,
  IconButton,
  Input,
  Table,
  Tooltip,
  Typography,
} from '@mui/joy'

import moment from 'moment'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { API_URL } from '../Config'
import { GetAllUsers } from '../utils/Fetcher'
import { Fetch } from '../utils/TokenManager'
import DateModal from './Modals/Inputs/DateModal'
// import moment from 'moment'

// enum for chore status:
const CHORE_STATUS = {
  NO_DUE_DATE: 'No due date',
  DUE_SOON: 'Soon',
  DUE_NOW: 'Due',
  OVER_DUE: 'Overdue',
}

const ChoresOverview = () => {
  const [chores, setChores] = useState([])
  const [filteredChores, setFilteredChores] = useState([])
  const [performers, setPerformers] = useState([])
  const [activeUserId, setActiveUserId] = useState(null)
  const [isDateModalOpen, setIsDateModalOpen] = useState(false)
  const [choreId, setChoreId] = useState(null)
  const [search, setSearch] = useState('')
  const Navigate = useNavigate()

  const getChoreStatus = chore => {
    if (chore.nextDueDate === null) {
      return CHORE_STATUS.NO_DUE_DATE
    }
    const dueDate = new Date(chore.nextDueDate)
    const now = new Date()
    const diff = dueDate - now
    if (diff < 0) {
      return CHORE_STATUS.OVER_DUE
    }
    if (diff > 1000 * 60 * 60 * 24) {
      return CHORE_STATUS.DUE_NOW
    }
    if (diff > 0) {
      return CHORE_STATUS.DUE_SOON
    }
    return CHORE_STATUS.NO_DUE_DATE
  }
  const getChoreStatusColor = chore => {
    switch (getChoreStatus(chore)) {
      case CHORE_STATUS.NO_DUE_DATE:
        return 'neutral'
      case CHORE_STATUS.DUE_SOON:
        return 'success'
      case CHORE_STATUS.DUE_NOW:
        return 'primary'
      case CHORE_STATUS.OVER_DUE:
        return 'warning'
      default:
        return 'neutral'
    }
  }
  const getChoreStatusIcon = chore => {
    switch (getChoreStatus(chore)) {
      case CHORE_STATUS.NO_DUE_DATE:
        return <HelpOutline />
      case CHORE_STATUS.DUE_SOON:
        return <QueryBuilder />
      case CHORE_STATUS.DUE_NOW:
        return <Adjust />
      case CHORE_STATUS.OVER_DUE:
        return <Warning />
      default:
        return <HelpOutline />
    }
  }
  useEffect(() => {
    // fetch chores:
    Fetch(`${API_URL}/chores/`)
      .then(response => response.json())
      .then(data => {
        const filteredData = data.res.filter(
          chore => chore.assignedTo === activeUserId || chore.assignedTo === 0,
        )
        setChores(data.res)
        setFilteredChores(data.res)
      })
    GetAllUsers()
      .then(response => response.json())
      .then(data => {
        setPerformers(data.res)
      })
    const user = JSON.parse(localStorage.getItem('user'))
    if (user != null && user.id > 0) {
      setActiveUserId(user.id)
    }
  }, [])

  return (
    <Container>
      <Typography level='h4' mb={1.5}>
        Chores Overviews
      </Typography>
      {/* <SummaryCard /> */}
      <Grid container>
        <Grid
          item
          sm={6}
          alignSelf={'flex-start'}
          minWidth={100}
          display='flex'
          gap={2}
        >
          <Input
            placeholder='Search'
            value={search}
            onChange={e => {
              if (e.target.value === '') {
                setFilteredChores(chores)
              }
              setSearch(e.target.value)
              const newChores = chores.filter(chore => {
                return chore.name.includes(e.target.value)
              })
              setFilteredChores(newChores)
            }}
            endDecorator={
              search !== '' ? (
                <Button
                  variant='text'
                  onClick={() => {
                    setSearch('')
                    setFilteredChores(chores)
                  }}
                >
                  <CancelRounded />
                </Button>
              ) : (
                <Button variant='text'>
                  <SearchRounded />
                </Button>
              )
            }
          ></Input>
        </Grid>
        <Grid item sm={6} justifyContent={'flex-end'} display={'flex'} gap={2}>
          <Button
            onClick={() => {
              Navigate(`/chores/create`)
            }}
          >
            New Chore
          </Button>
        </Grid>
      </Grid>

      <Table>
        <thead>
          <tr>
            {/* first column has minium size because its icon */}
            <th style={{ width: 100 }}>Due</th>
            <th>Chore</th>
            <th>Assignee</th>
            <th>Due</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          {filteredChores.map(chore => (
            <tr key={chore.id}>
              {/* cirular icon if the chore is due will be red else yellow: */}
              <td>
                <Chip color={getChoreStatusColor(chore)}>
                  {getChoreStatus(chore)}
                </Chip>
              </td>
              <td
                onClick={() => {
                  Navigate(`/chores/${chore.id}/edit`)
                }}
              >
                {chore.name || '--'}
              </td>
              <td>
                {chore.assignedTo > 0 ? (
                  <Tooltip
                    title={
                      performers.find(p => p.id === chore.assignedTo)
                        ?.displayName
                    }
                    size='sm'
                  >
                    <Chip
                      startDecorator={
                        <Avatar color='primary'>
                          {
                            performers.find(p => p.id === chore.assignedTo)
                              ?.displayName[0]
                          }
                        </Avatar>
                      }
                    >
                      {performers.find(p => p.id === chore.assignedTo)?.name}
                    </Chip>
                  </Tooltip>
                ) : (
                  <Chip
                    color='warning'
                    startDecorator={<Avatar color='primary'>?</Avatar>}
                  >
                    Unassigned
                  </Chip>
                )}
              </td>
              <td>
                <Tooltip
                  title={
                    chore.nextDueDate === null
                      ? 'no due date'
                      : moment(chore.nextDueDate).format('YYYY-MM-DD')
                  }
                  size='sm'
                >
                  <Typography>
                    {chore.nextDueDate === null
                      ? '--'
                      : moment(chore.nextDueDate).fromNow()}
                  </Typography>
                </Tooltip>
              </td>

              <td>
                <ButtonGroup
                // display='flex'
                // // justifyContent='space-around'
                // alignItems={'center'}
                // gap={0.5}
                >
                  <IconButton
                    variant='outlined'
                    size='sm'
                    // sx={{ borderRadius: '50%' }}
                    onClick={() => {
                      Fetch(`${API_URL}/chores/${chore.id}/do`, {
                        method: 'POST',
                      }).then(response => {
                        if (response.ok) {
                          response.json().then(data => {
                            const newChore = data.res
                            const newChores = [...chores]
                            const index = newChores.findIndex(
                              c => c.id === chore.id,
                            )
                            newChores[index] = newChore
                            setChores(newChores)
                            setFilteredChores(newChores)
                          })
                        }
                      })
                    }}
                    aria-setsize={2}
                  >
                    <CheckBox />
                  </IconButton>
                  <IconButton
                    variant='outlined'
                    size='sm'
                    // sx={{ borderRadius: '50%' }}
                    onClick={() => {
                      setChoreId(chore.id)
                      setIsDateModalOpen(true)
                    }}
                    aria-setsize={2}
                  >
                    <History />
                  </IconButton>
                  <IconButton
                    variant='outlined'
                    size='sm'
                    // sx={{
                    //   borderRadius: '50%',
                    // }}
                    onClick={() => {
                      Navigate(`/chores/${chore.id}/edit`)
                    }}
                  >
                    <Edit />
                  </IconButton>
                </ButtonGroup>
              </td>
            </tr>
          ))}
        </tbody>
      </Table>
      <DateModal
        isOpen={isDateModalOpen}
        key={choreId}
        title={`Change due date`}
        onClose={() => {
          setIsDateModalOpen(false)
        }}
        onSave={date => {
          if (activeUserId === null) {
            alert('Please select a performer')
            return
          }
          fetch(
            `${API_URL}/chores/${choreId}/do?performer=${activeUserId}&completedDate=${new Date(
              date,
            ).toISOString()}`,
            {
              method: 'POST',
            },
          ).then(response => {
            if (response.ok) {
              response.json().then(data => {
                const newChore = data.res
                const newChores = [...chores]
                const index = newChores.findIndex(c => c.id === chore.id)
                newChores[index] = newChore
                setChores(newChores)
                setFilteredChores(newChores)
              })
            }
          })
        }}
      />
    </Container>
  )
}

export default ChoresOverview