summaryrefslogtreecommitdiffstats
path: root/models/checklists.js
blob: b90656e45e465577baf7c11c7bd4c046306e9d03 (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
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
Checklists = new Mongo.Collection('checklists');

Checklists.attachSchema(new SimpleSchema({
  cardId: {
    type: String,
  },
  title: {
    type: String,
  },
  items: {
    type: [Object],
    defaultValue: [],
  },
  'items.$._id': {
    type: String,
  },
  'items.$.title': {
    type: String,
  },
  'items.$.sort': {
    type: Number,
    decimal: true,
  },
  'items.$.isFinished': {
    type: Boolean,
    defaultValue: false,
  },
  finishedAt: {
    type: Date,
    optional: true,
  },
  createdAt: {
    type: Date,
    denyUpdate: false,
    autoValue() { // eslint-disable-line consistent-return
      if (this.isInsert) {
        return new Date();
      } else {
        this.unset();
      }
    },
  },
  sort: {
    type: Number,
    decimal: true,
  },
}));

const self = Checklists;

Checklists.helpers({
  itemCount() {
    return this.items.length;
  },
  getItemsSorted() {
    return _.sortBy(this.items, 'sort');
  },
  finishedCount() {
    return this.items.filter((item) => {
      return item.isFinished;
    }).length;
  },
  isFinished() {
    return 0 !== this.itemCount() && this.itemCount() === this.finishedCount();
  },
  getItem(_id) {
    return _.findWhere(this.items, { _id });
  },
  itemIndex(itemId) {
    const items = self.findOne({_id : this._id}).items;
    return _.pluck(items, '_id').indexOf(itemId);
  },
  getNewItemId() {
    const itemCount = this.itemCount();
    let idx = 0;
    if (itemCount > 0) {
      const lastId = this.items[itemCount - 1]._id;
      const lastIdSuffix = lastId.substr(this._id.length);
      idx = parseInt(lastIdSuffix, 10) + 1;
    }
    return `${this._id}${idx}`;
  },
});

Checklists.allow({
  insert(userId, doc) {
    return allowIsBoardMemberByCard(userId, Cards.findOne(doc.cardId));
  },
  update(userId, doc) {
    return allowIsBoardMemberByCard(userId, Cards.findOne(doc.cardId));
  },
  remove(userId, doc) {
    return allowIsBoardMemberByCard(userId, Cards.findOne(doc.cardId));
  },
  fetch: ['userId', 'cardId'],
});

Checklists.before.insert((userId, doc) => {
  doc.createdAt = new Date();
  if (!doc.userId) {
    doc.userId = userId;
  }
});

Checklists.mutations({
  //for checklist itself
  setTitle(title) {
    return { $set: { title } };
  },
  //for items in checklist
  addItem(title) {
    const _id = this.getNewItemId();
    return {
      $addToSet: {
        items: {
          _id, title,
          isFinished: false,
          sort: this.itemCount(),
        },
      },
    };
  },
  addFullItem(item) {
    const itemsUpdate = {};
    this.items.forEach(function(iterItem, index) {
      if (iterItem.sort >= item.sort) {
        itemsUpdate[`items.${index}.sort`] = iterItem.sort + 1;
      }
    });
    if (!_.isEmpty(itemsUpdate)) {
      self.direct.update({ _id: this._id }, { $set: itemsUpdate });
    }
    return { $addToSet: { items: item } };
  },
  removeItem(itemId) {
    const item = this.getItem(itemId);
    const itemsUpdate = {};
    this.items.forEach(function(iterItem, index) {
      if (iterItem.sort > item.sort) {
        itemsUpdate[`items.${index}.sort`] = iterItem.sort - 1;
      }
    });
    if (!_.isEmpty(itemsUpdate)) {
      self.direct.update({ _id: this._id }, { $set: itemsUpdate });
    }
    return { $pull: { items: { _id: itemId } } };
  },
  editItem(itemId, title) {
    if (this.getItem(itemId)) {
      const itemIndex = this.itemIndex(itemId);
      return {
        $set: {
          [`items.${itemIndex}.title`]: title,
        },
      };
    }
    return {};
  },
  finishItem(itemId) {
    if (this.getItem(itemId)) {
      const itemIndex = this.itemIndex(itemId);
      return {
        $set: {
          [`items.${itemIndex}.isFinished`]: true,
        },
      };
    }
    return {};
  },
  resumeItem(itemId) {
    if (this.getItem(itemId)) {
      const itemIndex = this.itemIndex(itemId);
      return {
        $set: {
          [`items.${itemIndex}.isFinished`]: false,
        },
      };
    }
    return {};
  },
  toggleItem(itemId) {
    const item = this.getItem(itemId);
    if (item) {
      const itemIndex = this.itemIndex(itemId);
      return {
        $set: {
          [`items.${itemIndex}.isFinished`]: !item.isFinished,
        },
      };
    }
    return {};
  },
  sortItems(itemIDs) {
    const validItems = [];
    itemIDs.forEach((itemID) => {
      if (this.getItem(itemID)) {
        validItems.push(this.itemIndex(itemID));
      }
    });
    const modifiedValues = {};
    for (let i = 0; i < validItems.length; i++) {
      modifiedValues[`items.${validItems[i]}.sort`] = i;
    }
    return {
      $set: modifiedValues,
    };
  },
});

if (Meteor.isServer) {
  Meteor.startup(() => {
    Checklists._collection._ensureIndex({ cardId: 1, createdAt: 1 });
  });

  Checklists.after.insert((userId, doc) => {
    Activities.insert({
      userId,
      activityType: 'addChecklist',
      cardId: doc.cardId,
      boardId: Cards.findOne(doc.cardId).boardId,
      checklistId: doc._id,
    });
  });

  //TODO: so there will be no activity for adding item into checklist, maybe will be implemented in the future.
  // The future is now
  Checklists.after.update((userId, doc, fieldNames, modifier) => {
    if (fieldNames.includes('items')) {
      if (modifier.$addToSet) {
        Activities.insert({
          userId,
          activityType: 'addChecklistItem',
          cardId: doc.cardId,
          boardId: Cards.findOne(doc.cardId).boardId,
          checklistId: doc._id,
          checklistItemId: modifier.$addToSet.items._id,
        });
      } else if (modifier.$pull) {
        const activity = Activities.findOne({
          checklistItemId: modifier.$pull.items._id,
        });
        if (activity) {
          Activities.remove(activity._id);
        }
      }
    }
  });

  Checklists.before.remove((userId, doc) => {
    const activities = Activities.find({ checklistId: doc._id });
    if (activities) {
      activities.forEach((activity) => {
        Activities.remove(activity._id);
      });
    }
  });
}

//CARD COMMENT REST API
if (Meteor.isServer) {
  JsonRoutes.add('GET', '/api/boards/:boardId/cards/:cardId/checklists', function (req, res, next) {
    Authentication.checkUserId( req.userId);
    const paramCardId = req.params.cardId;
    JsonRoutes.sendResult(res, {
      code: 200,
      data: Checklists.find({ cardId: paramCardId }).map(function (doc) {
        return {
          _id: doc._id,
          title: doc.title,
        };
      }),
    });
  });

  JsonRoutes.add('GET', '/api/boards/:boardId/cards/:cardId/checklists/:checklistId', function (req, res, next) {
    Authentication.checkUserId( req.userId);
    const paramChecklistId = req.params.checklistId;
    const paramCardId = req.params.cardId;
    JsonRoutes.sendResult(res, {
      code: 200,
      data: Checklists.findOne({ _id: paramChecklistId, cardId: paramCardId }),
    });
  });

  JsonRoutes.add('POST', '/api/boards/:boardId/cards/:cardId/checklists', function (req, res, next) {
    Authentication.checkUserId( req.userId);
    const paramCardId = req.params.cardId;

    const checklistToSend = {};
    checklistToSend.cardId = paramCardId;
    checklistToSend.title = req.body.title;
    checklistToSend.items = [];
    const id = Checklists.insert(checklistToSend);
    const checklist = Checklists.findOne({_id: id});
    req.body.items.forEach(function (item) {
      checklist.addItem(item);
    }, this);


    JsonRoutes.sendResult(res, {
      code: 200,
      data: {
        _id: id,
      },
    });
  });

  JsonRoutes.add('DELETE', '/api/boards/:boardId/cards/:cardId/checklists/:checklistId', function (req, res, next) {
    Authentication.checkUserId( req.userId);
    const paramCommentId = req.params.commentId;
    const paramCardId = req.params.cardId;
    Checklists.remove({ _id: paramCommentId, cardId: paramCardId });
    JsonRoutes.sendResult(res, {
      code: 200,
      data: {
        _id: paramCardId,
      },
    });
  });
}