summaryrefslogtreecommitdiff
path: root/client/components/MealList.jsx
blob: 8f5e5df1c313d339f93ab1e904f6e4124c8f689e (plain)
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
import React from 'react'
import MealFilter from './MealFilter.jsx'
import client from '../client'

export default class MealList extends React.Component {
  constructor(props) {
    super()

    this.state = {
      total: 0,
      limit: 0,
      skip: 0,
      data: []
    }

    this.handleCreate = this.handleCreate.bind(this)
    this.handleUpdate = this.handleUpdate.bind(this)
    this.handleDelete = this.handleDelete.bind(this)
    this.pickMeal = this.pickMeal.bind(this)
    this.loadMeals = this.loadMeals.bind(this)
  }
  handleCreate(meal) {
    const meals = this.state.data.slice()
    meals.unshift( meal )
    this.setState({
      data: meals.sort(sortByDate)
    })
  }
  handleUpdate(meal) {
    const meals = this.state.data.map((data) => {
      return (data.id === meal.id) ? meal : data
    }).sort(sortByDate)
    this.setState({
      data: meals
    })
  }
  handleDelete(mealid) {
    const meals = this.state.data.filter((data) => {
      return data.id !== mealid
    }).sort(sortByDate)
    this.setState({
      data: meals
    })
  }
  pickMeal(meal) {
    this.mealForm.pick(meal)
  }
  loadMeals(meals) {
    this.setState({ data: meals })
  }
  render() {
    const canEdit = canEditUserMeals(this.props.currentUser, this.props.user)
    var groups = groupByDate(this.state.data)
    const items = Object.keys(groups).sort().reverse().map((date) => {
      const group = groups[date]
      const mealitems = group.meals.map((meal) => {
        return (
          <MealItem
            key={meal.id}
            meal={meal}
            canEdit={canEdit}
            onClick={this.pickMeal}
            onDelete={this.handleDelete} />
        )
      })
      const isOverLimit = group.calories > this.props.user.goal ? 'isOverLimit' : 'isUnderLimit'
      return (
        <div key={group.date} className='group'>
          <span className='groupDate'>{group.date}</span>
          <span className={'calories ' + isOverLimit}>{group.calories} cal</span>
          <br />
          {mealitems}
        </div>
      )
    })
    if (! items.length) {
      items.push(
        <div className='quiet' key='nomeals'>No meals found</div>
      )
    }
    return (
      <div>
        <MealForm user={this.props.user}
          currentUser={this.props.currentUser}
          ref={(mealForm) => { this.mealForm = mealForm }}
          onCreate={(meal) => { this.handleCreate(meal) }}
          onUpdate={(meal) => { this.handleUpdate(meal) }}
        />
        <MealFilter user={this.props.user}
          ref={(mealFilter) => { this.mealFilter = mealFilter }}
          onChange={ this.loadMeals }
        />
        <div>
          {items}
        </div>
      </div>
    )
  }
}

class MealItem extends React.Component {
  constructor() {
    super()
    this.handleClick = this.handleClick.bind(this)
    this.remove = this.remove.bind(this)
  }
  handleClick() {
    if (this.props.canEdit) {
      this.props.onClick(this.props.meal)
    }
  }
  remove(e) {
    e.stopPropagation()
    const mealid = this.props.meal.id
    const mealsService = client.service('meals')
    const params = { query: { token: client.get('token') } }
    mealsService.remove(mealid, params).then(result => {
      this.props.onDelete(mealid)
    }).catch(error => {
      console.error(error)
    })
  }
  render() {
    const meal = this.props.meal
    // const canEdit = this.props.meal.userid === this.props.currentUser.id ? 'canEdit' : ''
    const canEdit = this.props.canEdit ? 'canEdit' : ''
    const date = parseDate(meal.date)
    const time = parseTime(meal.date)
    return (
      <div className={'meal row ' + canEdit} onClick={this.handleClick}>
        <div className='name'>{meal.name}</div>
        <div className='calories'>{meal.calories} cal</div>
        <div className='date'>{date}</div>
        <div className='time'>{time}</div>
        <div className='remove' onClick={this.remove}>x</div>
      </div>
    )
  }
}

class MealForm extends React.Component {
  constructor(props) {
    super()
    this.state = {
      id: '',
      userid: props.user.id,
      name: '',
      calories: '',
      date: new Date ().toISOString(),
    }
    this.updateState = this.updateState.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }
  reset() {
    this.setState({
      id: '',
      name: '',
      calories: '',
      date: new Date ().toISOString(),
    })
  }
  pick(meal){
    this.setState(meal)
  }
  updateState(event){
    const name = event.target.name
    let value = event.target.value
    console.log(name, value)
    if (name === 'date') {
      value = new Date(value + 'T' + this.state.date.split("T")[1] ).toISOString()
    } else if (name === 'time') {
      value = new Date(this.state.date.split("T")[0] + value).toISOString()
    } else if (name === 'calories') {
      value = parseInt(value)
    }
    this.setState({
      [name]: value,
      error: null,
    })
  }
  handleSubmit(event) {
    event.preventDefault()

    const id = this.state.id

    if (! id) {
      this.create()
    }
    else {
      this.update()
    }
  }
  create() {
    const mealsService = client.service('meals')
    const params = { query: { token: client.get('token') } }

    mealsService.create(this.state, params).then(result => {
      this.props.onCreate(result)
      this.reset()
    }).catch(error => {
      console.error(error)
      this.setState({
        error: error.toString()
      })
    })
  }
  update() {
    const mealsService = client.service('meals')
    const params = { query: { token: client.get('token') } }

    mealsService.update(this.state.id, this.state, params).then(result => {
      this.props.onUpdate(result)
      this.reset()
    }).catch(error => {
      console.error(error)
      this.setState({
        error: error.toString()
      })
    })
  }
  render() {
    const id = this.state.id
    const action = id ? 'update' : 'create'
    const canEdit = canEditUserMeals(this.props.currentUser, this.props.user)
    if (! canEdit) {
      return (<div></div>)
    }
    console.log(this.state.date)

    const date = parseDate(this.state.date)
    const time = parseTime(this.state.date)

    return (
      <form onSubmit={this.handleSubmit} className={action}>
        <input type='hidden' name='id' value={this.state.id} readOnly />
        <input type='hidden' name='userid' value={this.state.userid} readOnly />
        <input type='text' name='name' placeholder='Name' value={this.state.name} required onChange={this.updateState} />
        <input type='number' name='calories' placeholder='Calories' value={this.state.calories} required onChange={this.updateState} min='0' max='10000' />
        <input type='date' name='date' placeholder='Date' value={date} required onChange={this.updateState} />
        <input type='time' name='time' placeholder='Time' value={time} required onChange={this.updateState} step='60' />
        <input type='submit' value={capitalize(action)} />
        <span className='clear' onClick={() => this.reset()}>cancel</span>
        <div className='error'>{this.state.error}</div>
      </form>
    )
  }
}

function canEditUserMeals (currentUser, user) {
  const isValidRole = (currentUser.role === 'admin')
  return (user.id == currentUser.id) || isValidRole
}

function groupByDate(a) {
  return a.reduce(function(rv, x) {
    var date = parseDate(x.date)
    var ab = rv[date] = rv[date] || { date: date, calories: 0, meals: [] }
    ab.meals.push(x)
    ab.calories += x.calories
    return rv
  }, {})
}

function sortByDate(a,b){
  return new Date(b.date) - new Date(a.date)
}

function parseDate(d){
  return new Date(d).toISOString().substr(0, 10)
}

function parseTime(d){
  return new Date(d).toISOString().substr(11, 5)
}

function capitalize(s){
  s = s || '';
  return (s[0] || '').toUpperCase() + s.substr(1)
}