-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathmarket.js
267 lines (251 loc) · 8.9 KB
/
market.js
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
// Licensed under the Apache License. See footer for details.
const express = require('express');
const path = require('path');
const async = require('async');
const router = express.Router();
const marketDbName = 'market';
const challengesDbName = 'challenges';
const workoutsDbName = 'workouts';
let Market;
let UserChallenges;
let UserWorkouts;
function checkAuthenticated(req, res, next) {
if (req.isAuthenticated() && req.user.organization) {
next();
} else {
res.status(401).send({ message: 'You need to be authenticated and part of an organization' });
}
}
// | GET | /api/market/challenges | view available challenges
router.get('/market/challenges', (req, res) => {
console.log('Retrieving market challenges');
Market.list({ include_docs: true }, (err, result) => {
if (err) {
res.status(500).send({ ok: false });
} else {
res.send(result.rows.map(row => row.doc));
}
});
});
// | GET | /api/organization/challenges | view challenges owned by the current organization
router.get('/organization/challenges', checkAuthenticated, (req, res) => {
console.log(`Retrieving organization challenges for ${req.user._id} / ${req.user.organization}`);
Market.find({
selector: {
organization: req.user.organization
}
}, (err, result) => {
if (err) {
res.status(500).send({ ok: false });
} else {
res.send(result.docs);
}
});
});
// | GET | /api/organization/challenges/:id | view challenge owned by the current organization
router.get('/organization/challenges/:id', checkAuthenticated, (req, res) => {
console.log(`Retrieving organization challenge ${req.params.id} for ${req.user._id} / ${req.user.organization}`);
if (!req.params.id) {
res.status(500).send({ message: 'Missing _id' });
} else {
Market.get(req.params.id, (err, challenge) => {
if (err) {
console.log(err);
res.status(500).send({ ok: false });
} else if (challenge.organization !== req.user.organization) {
res.status(401).send({ ok: false, message: 'Not owner' });
} else {
res.status(200).send(challenge);
}
});
}
});
// | POST | /api/organization/challenges | allows to submit a new challenge to the market
// requires authentication
// user must be an organization
router.post('/organization/challenges', checkAuthenticated, (req, res) => {
console.log(`Storing new challenge for ${req.user._id} / ${req.user.organization}:`, req.body);
const challenge = req.body;
// sanity check
delete challenge._id;
delete challenge._rev;
// assign this workout to the current user
challenge.organization = req.user.organization;
Market.insert(challenge, (err, result) => {
if (err) {
res.status(500).send({ ok: false });
} else {
challenge._id = result.id;
challenge._rev = result.rev;
res.status(201).send(challenge);
}
});
});
// | PUT | /api/organization/challenges | allows an organization to update its challenge
// requires authentication
// user must be an organization
// challenge must be owned by user
router.put('/organization/challenges/:id', checkAuthenticated, (req, res) => {
console.log(`Updating challenge for ${req.user._id} / ${req.user.organization}:`, req.body);
const challenge = req.body;
if (!challenge._id || !challenge._rev) {
res.status(500).send({ message: 'Missing _id or _rev' });
} else {
Market.get(challenge._id, (err, existing) => {
if (err) {
console.log(err);
res.status(500).send({ ok: false });
} else if (existing.organization !== req.user.organization) {
res.status(401).send({ ok: false, message: 'Not owner' });
} else {
challenge.updated_at = new Date();
Market.insert(challenge, (insertErr, updated) => {
if (insertErr) {
console.log(err);
res.status(500).send({ ok: false });
} else {
challenge._rev = updated.rev;
res.status(200).send(challenge);
}
});
}
});
}
});
// | GET | /api/organization/challenges/summary/:id | view a challenge summary
router.get('/organization/challenges/:id/summary', checkAuthenticated, (req, res) => {
console.log(`Retrieving challenge summary for ${req.user._id} / ${req.user.organization} / ${req.params.id}:`);
async.waterfall([
// get the challenge from the database
// and ensure the challenge belong to the organization
(callback) => {
Market.get(req.params.id, (err, challenge) => {
if (err) {
callback(err);
} else if (challenge && challenge.organization === req.user.organization) {
callback(null, challenge);
} else {
callback(new Error('not found'));
}
});
},
// find all users who have signed up for this challenge
(challenge, callback) => {
console.log('Retrieving users subscribed to challenge', challenge._id);
UserChallenges.find({
selector: {
challengeId: challenge._id
}
}, (err, result) => {
if (err) {
callback(err);
} else {
callback(null, challenge, result.docs);
}
});
},
// find all workouts linked to these challenges
(challenge, userChallenges, callback) => {
console.log('Retrieving workouts for challenge', challenge._id);
UserWorkouts.find({
selector: {
challengeId: challenge._id
}
}, (err, result) => {
if (err) {
callback(err);
} else {
callback(null, challenge, userChallenges, result.docs);
}
});
},
// from the workout, count how many users are actively participating
// from the workout, count how many users have completed the challenge
(challenge, userChallenges, workouts, callback) => {
let reserved = 0;
let granted = 0;
userChallenges.forEach((userChallenge) => {
// for each user, count the workouts
const count = workouts.filter(workout =>
workout.accountId === userChallenge.accountId &&
workout.activity === challenge.activity).length;
if (count >= challenge.goal) {
// goal reached, the user deserves the reward!
granted += 1;
} else {
// goal not reached yet but we need to save a reward in case the user reaches the goal
reserved += 1;
}
});
const summary = {
participants: userChallenges.length,
workouts: workouts.length,
rewards: {
total: challenge.rewards,
reserved,
granted,
remaining: challenge.rewards - reserved - granted
}
};
callback(null, summary);
},
], (err, result) => {
if (err) {
res.status(500).send(err);
} else {
res.send(result);
}
});
});
// | DELETE | /api/organization/challenges | allows to delete its challenge from the market
// requires authentication
// user must be an organization
// challenge must be owned by user
router.delete('/organization/challenges/:id', checkAuthenticated, (req, res) => {
console.log(`Removing challenge for ${req.user._id} / ${req.user.organization}:`, req.body);
const challenge = req.body;
if (!challenge._id || !challenge._rev) {
res.status(500).send({ message: 'Missing _id or _rev' });
} else {
Market.get(challenge._id, (err, existing) => {
if (err) {
console.log(err);
res.status(500).send({ ok: false });
} else if (existing.organization !== req.user.organization) {
res.status(401).send({ ok: false, message: 'Not owner' });
} else {
Market.destroy(challenge._id, challenge._rev, (deleteErr, result) => {
if (deleteErr) {
res.status(500).send({ ok: false });
} else {
res.status(200).send(result);
}
});
}
});
}
});
module.exports = (appEnv, readyCallback) => {
const Database = require('../config/database');
UserChallenges = Database(appEnv, challengesDbName, null, () => {
UserWorkouts = Database(appEnv, workoutsDbName, null, () => {
Market = Database(appEnv, marketDbName,
path.resolve(`${__dirname}/../seed/market.json`), () => {
readyCallback(null, router);
});
});
});
};
//------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//------------------------------------------------------------------------------