-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathworkspace.js
More file actions
597 lines (504 loc) · 21.1 KB
/
workspace.js
File metadata and controls
597 lines (504 loc) · 21.1 KB
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
import WorkspaceModel from '../models/workspace';
import { AccountType, Currency } from 'codex-accounting-sdk/types';
import PlanModel from '../models/plan';
import * as telegram from '../utils/telegram';
import HawkCatcher from '@hawk.so/nodejs';
import escapeHTML from 'escape-html';
import cloudPaymentsApi from '../utils/cloudPaymentsApi';
import { emailNotification, TaskPriorities } from '../utils/emailNotifications';
import { SenderWorkerTaskType } from '../types/userNotifications';
import ProjectToWorkspace from '../models/projectToWorkspace';
import Validator from '../utils/validator';
import { dateFromObjectId } from '../utils/dates';
const { ApolloError, UserInputError, ForbiddenError } = require('apollo-server-express');
const crypto = require('crypto');
const EventsFactory = require('../models/eventsFactory');
/**
* See all types and fields here {@see ../typeDefs/workspace.graphql}
*/
module.exports = {
Query: {
/**
* Returns workspace(s) info by id(s)
* Returns all user's workspaces if ids = []
* @param {ResolverObj} _obj - object that contains the result returned from the resolver on the parent field
* @param {String[]} ids - workspace ids
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
* @return {Workspace[]}
*/
async workspaces(_obj, { ids }, { user, factories }) {
const authenticatedUser = await factories.usersFactory.findById(user.id);
return factories.workspacesFactory.findManyByIds(await authenticatedUser.getWorkspacesIds(ids));
},
},
Mutation: {
/**
* Create new workspace
* @param {ResolverObj} _obj - object that contains the result returned from the resolver on the parent field
* @param {String} name - workspace name
* @param {String} description - workspace description
* @param {string} image - workspace image
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
* @param {Accounting} accounting - SDK for creating account for new workspace
*
* @return {WorkspaceModel} created workspace
*/
async createWorkspace(_obj, { name, description, image }, { user, factories, accounting }) {
try {
// Create workspace account and set account id to workspace
const accountResponse = await accounting.createAccount({
name: 'WORKSPACE:' + name,
type: AccountType.LIABILITY,
currency: Currency.USD,
});
const accountId = accountResponse.recordId;
/**
* @type {WorkspaceDBScheme}
*/
const options = {
name,
description,
image,
accountId,
};
const ownerModel = await factories.usersFactory.findById(user.id);
return await factories.workspacesFactory.create(options, ownerModel);
} catch (err) {
console.log('\nლ(´ڡ`ლ) Error [resolvers:workspace:createWorkspace]: \n\n', err, '\n\n');
throw new ApolloError('Something went wrong');
}
},
/**
* Invite user to workspace
* @param {ResolverObj} _obj - object that contains the result returned from the resolver on the parent field
* @param {String} userEmail - email of the user to invite
* @param {string} workspaceId - id of the workspace to which the user is invited
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
* @return {Promise<boolean>} - true if operation is successful
*/
async inviteToWorkspace(_obj, { userEmail, workspaceId }, { user, factories }) {
const userModel = await factories.usersFactory.findById(user.id);
const [ isWorkspaceBelongsToUser ] = await userModel.getWorkspacesIds([ workspaceId ]);
if (!isWorkspaceBelongsToUser) {
throw new ApolloError('There is no workspace with that id');
}
const invitedUser = await factories.usersFactory.findByEmail(userEmail);
const workspace = await factories.workspacesFactory.findById(workspaceId);
if (!invitedUser) {
await workspace.addUnregisteredMember(userEmail);
} else {
const [ isUserInThatWorkspace ] = await invitedUser.getWorkspacesIds([ workspaceId ]);
if (isUserInThatWorkspace) {
throw new ApolloError('User already invited to this workspace');
}
await invitedUser.addWorkspace(workspaceId, true);
await workspace.addMember(invitedUser._id.toString(), true);
}
const linkHash = crypto
.createHash('sha256')
.update(`${workspaceId}:${userEmail}:${process.env.INVITE_LINK_HASH_SALT}`)
.digest('hex');
const inviteLink = `${process.env.GARAGE_URL}/join/${workspaceId}/${linkHash}`;
await emailNotification({
type: SenderWorkerTaskType.WorkspaceInvite,
payload: {
workspaceName: workspace.name,
inviteLink,
endpoint: userEmail,
},
}, {
priority: TaskPriorities.IMPORTANT,
});
return true;
},
/**
* Join to workspace by invite link with invite hash
*
* @param {ResolverObj} _obj - object that contains the result returned from the resolver on the parent field
* @param {String} inviteHash - hash passed to the invite link
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
*
* @return {Promise<object>} - true if operation is successful
*/
async joinByInviteLink(_obj, { inviteHash }, { user, factories }) {
const currentUser = await factories.usersFactory.findById(user.id);
const workspace = await factories.workspacesFactory.findByInviteHash(inviteHash);
if (await workspace.getMemberInfo(user.id)) {
throw new ApolloError('You are already member of this workspace');
}
await workspace.addMember(currentUser._id.toString());
await currentUser.addWorkspace(workspace._id.toString());
return {
recordId: workspace._id.toString(),
record: workspace,
};
},
/**
* Confirm user invitation by special link for user (for example, from email invitation)
*
* @param {ResolverObj} _obj - object that contains the result returned from the resolver on the parent field
* @param {String} inviteHash - hash passed to the invite link
* @param {String} workspaceId - id of the workspace to which the user is invited
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
*
* @return {Promise<object>} - true if operation is successful
*/
async confirmInvitation(_obj, { inviteHash, workspaceId }, { user, factories }) {
const currentUser = await factories.usersFactory.findById(user.id);
const workspace = await factories.workspacesFactory.findById(workspaceId);
const hash = crypto
.createHash('sha256')
.update(`${workspaceId}:${currentUser.email}:${process.env.INVITE_LINK_HASH_SALT}`)
.digest('hex');
if (hash !== inviteHash) {
throw new ApolloError('The link is broken');
}
const membershipExists = await workspace.confirmMembership(currentUser);
if (membershipExists) {
await currentUser.confirmMembership(workspaceId);
} else {
await currentUser.addWorkspace(workspaceId);
}
return {
recordId: workspace._id.toString(),
record: workspace,
};
},
/**
* Update workspace settings
*
* @param {ResolverObj} _obj - object that contains the result returned from the resolver on the parent field
* @param {string} workspaceId - id of the updated workspace
* @param {string} name - workspace name
* @param {string} description - workspace description
* @param {string} image - workspace logo
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
*
* @returns {Promise<Boolean>}
*/
async updateWorkspace(_obj, { workspaceId, name, description, image }, { user, factories }) {
// @makeAnIssue Create directives for arguments validation
if (!Validator.string(name)) {
throw new UserInputError('Invalid name length');
}
if (!Validator.string(description, 0)) {
throw new UserInputError('Invalid description length');
}
const workspaceToUpdate = await factories.workspacesFactory.findById(workspaceId);
try {
/**
* @type {WorkspaceDBScheme}
*/
const options = {
name,
description,
};
if (image) {
options.image = image;
}
await workspaceToUpdate.updateWorkspace(options);
} catch (err) {
throw new ApolloError('Something went wrong');
}
return true;
},
/**
* Grant admin permissions
*
* @param {ResolverObj} _obj - object that contains the result returned from the resolver on the parent field
* @param {string} workspaceId - id of the workspace
* @param {string} userId - id of user to grant permissions
* @param {boolean} state - state of permissions (true to grant, false to withdraw)
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
* @return {Promise<boolean>} - true if operation is successful
*/
async grantAdmin(_obj, { workspaceId, userId, state }, { user, factories }) {
const workspace = await factories.workspacesFactory.findById(workspaceId);
await workspace.grantAdmin(userId, state);
return true;
},
/**
* Remove user from workspace
*
* @param {ResolverObj} _obj - object that contains the result returned from the resolver on the parent field
* @param {string} workspaceId - id of the workspace where the user should be removed
* @param {string} userId - id of user to remove
* @param {string} userEmail - email of user to remove
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
* @return {Promise<boolean>} - true if operation is successful
* @returns {Promise<boolean>}
*/
async removeMemberFromWorkspace(_obj, { workspaceId, userId, userEmail }, { user, factories }) {
const workspace = await factories.workspacesFactory.findById(workspaceId);
if (userId) {
const userModel = await factories.usersFactory.findById(userId);
await workspace.removeMember(userModel);
} else {
await workspace.removeMemberByEmail(userEmail);
}
return true;
},
/**
* Mutation in order to leave workspace
* @param {ResolverObj} _obj - object that contains the result returned from the resolver on the parent field
* @param {string} workspaceId - id of the workspace where the user should be removed
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
* @return {Promise<boolean>} - true if operation is successful
*/
async leaveWorkspace(_obj, { workspaceId }, { user, factories }) {
const userModel = await factories.usersFactory.findById(user.id);
const workspaceModel = await factories.workspacesFactory.findById(workspaceId);
if (!workspaceModel) {
throw new UserInputError('There is no workspace with provided id');
}
const memberInfo = await workspaceModel.getMemberInfo(user.id);
if (memberInfo.isAdmin) {
const membersInfo = (await workspaceModel.getMembers());
const isThereOtherAdmins = !!membersInfo.find(
member => member.isAdmin && member.userId.toString() !== user.id
);
if (!isThereOtherAdmins) {
throw new ForbiddenError('You can\'t leave this workspace because you are the last admin');
}
}
await workspaceModel.removeMember(userModel);
return true;
},
/**
* Mutation in order to leave workspace
* @param {ResolverObj} _obj - object that contains the result returned from the resolver on the parent field
* @param {string} workspaceId - id of the workspace where the user should be removed
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
* @return {Promise<boolean>} - true if operation is successful
*/
async deleteWorkspace(_obj, { workspaceId }, { user, factories }) {
const workspaceModel = await factories.workspacesFactory.findById(workspaceId);
if (!workspaceModel) {
throw new UserInputError('There is no workspace with provided id');
}
const memberInfo = await workspaceModel.getMemberInfo(user.id);
/**
* Return if user is not Admin.
*/
if (!memberInfo.isAdmin) {
return false;
}
const membersInfo = (await workspaceModel.getMembers());
for (const member of membersInfo) {
const userModel = await factories.usersFactory.findById(member.userId.toString());
await userModel.markWorkspaceAsRemoved(workspaceId.toString());
}
const projectToWorkspace = new ProjectToWorkspace(workspaceId.toString());
const projectsInfo = await projectToWorkspace.getProjects();
if (projectsInfo.length) {
for (const project of projectsInfo) {
/**
* Remove project events
*/
await new EventsFactory(project._id).remove();
/**
* Remove project
*/
const projectModel = await factories.projectsFactory.findById(project.id.toString());
await projectModel.markProjectAsRemoved();
}
}
await workspaceModel.markWorkspaceAsRemoved();
return true;
},
/**
* Change workspace plan for default plan mutation implementation
*
* @param {ResolverObj} _obj - object that contains the result returned from the resolver on the parent field
* @param {string} workspaceId - id of workspace to change plan
* @param {ContextFactories} factories - factories to work with models
*/
async changeWorkspacePlanToDefault(
_obj,
{
input: { workspaceId },
},
{ factories, user }
) {
const workspaceModel = await factories.workspacesFactory.findById(workspaceId);
if (!workspaceModel) {
throw new UserInputError('There is no workspace with provided id');
}
const defaultPlan = await factories.plansFactory.getDefaultPlan();
if (workspaceModel.tariffPlanId === defaultPlan.id) {
throw new UserInputError('You already use default plan');
}
const oldPlanModel = await factories.plansFactory.findById(workspaceModel.tariffPlanId);
const userModel = await factories.usersFactory.findById(user.id);
try {
const date = new Date();
// Push old plan to plan history
await workspaceModel.updatePlanHistory(workspaceModel.tariffPlanId, date, userModel._id);
// Update workspace last charge date
await workspaceModel.updateLastChargeDate(date);
// Change workspace plan
await workspaceModel.changePlan(defaultPlan._id);
} catch (err) {
console.error('\nლ(´ڡ`ლ) Error [resolvers:workspace:changeWorkspacePlan]: \n\n', err, '\n\n');
HawkCatcher.send(err);
throw new ApolloError('An error occurred while changing the plan');
}
// Send a message of a succesfully plan changed to the telegram bot
const message = `🤑 <b>${escapeHTML(userModel.name || userModel.email)}</b> changed plan of «<b>${escapeHTML(workspaceModel.name)}</b>» workspace
⭕️ <i>${oldPlanModel.name} $${oldPlanModel.monthlyCharge}</i> → ✅ <b>${defaultPlan.name} $${defaultPlan.monthlyCharge}</b> `;
telegram.sendMessage(message);
const updatedWorkspaceModel = await factories.workspacesFactory.findById(workspaceId);
return {
recordId: workspaceId,
record: updatedWorkspaceModel,
};
},
/**
* Return empty object to call resolver for specific mutation
*/
workspace: () => ({}),
},
Workspace: {
/**
* Returns workspace creation date
*
* @param {WorkspaceDBScheme} workspace - result of parent resolver
*
* @returns {Date}
*/
creationDate(workspace) {
return dateFromObjectId(workspace._id);
},
/**
* Returns workspace invite hash
* If workspace has not hash this resolver generates it
*
* @param {WorkspaceDBScheme} workspaceData - result from resolver above
* @param _args - empty list of args
* @param {ContextFactories} factories - factories for working with models
*
* @returns {Promise<string>}
*/
async inviteHash(workspaceData, _args, { factories }) {
if (workspaceData.inviteHash && workspaceData.inviteHash !== '') {
return workspaceData.inviteHash;
}
const inviteHash = WorkspaceModel.generateInviteHash();
const workspace = await factories.workspacesFactory.findById(workspaceData._id);
if (!workspace) {
throw Error('Can\'t find workspace with this id: ' + workspaceData._id);
}
await workspace.updateInviteHash(inviteHash);
return workspace.inviteHash;
},
/**
* Fetch projects in workspace
* @param {ResolverObj} workspace - result from resolver above
* @param {String[]} ids - project ids
* @returns {Promise<Project[]>}
*/
async projects(workspace, { ids }) {
const projectToWorkspace = new ProjectToWorkspace(workspace._id);
return projectToWorkspace.getProjects(ids);
},
/**
* Returns workspace team
* @param {WorkspaceDBScheme} workspaceData - result from resolver above
* @param _args - empty list of args
* @param {ContextFactories} factories - factories for working with models
* @return {Promise<MemberDBScheme[]>}
*/
async team(workspaceData, _args, { factories }) {
const workspaceModel = await factories.workspacesFactory.findById(workspaceData._id.toString());
return workspaceModel.getMembers();
},
/**
* Returns workspace plan
*
* @param {WorkspaceDBScheme} workspace - result from resolver above
* @param _args - empty list of arguments
* @param {ContextFactories} factories - factories to work with models
* @returns {Promise<PlanModel>}
*/
async plan(workspace, _args, { factories }) {
const plan = await factories.plansFactory.findById(workspace.tariffPlanId);
return new PlanModel(plan);
},
},
/**
* Resolver for Union Member type.
* Represents two types of Members in workspace's team
*/
Member: {
/**
* Returns type of the team member
* @param {MemberDBScheme} memberData - result from resolver above
*/
__resolveType(memberData) {
return WorkspaceModel.isPendingMember(memberData) ? 'PendingMember' : 'ConfirmedMember';
},
},
/**
* Resolver for confirmed member data in workspace
*/
ConfirmedMember: {
/**
* Fetch user of the workspace
* @param {ConfirmedMemberDBScheme} memberData - result from resolver above
* @param _args - empty list of args
* @param {ContextFactories} factories - factories for working with models
*/
user(memberData, _args, { factories }) {
return factories.usersFactory.findById(memberData.userId.toString());
},
/**
* True if user has admin permissions
* @param {ConfirmedMemberDBScheme} memberData - result from resolver above
*/
isAdmin(memberData) {
return !WorkspaceModel.isPendingMember(memberData) && (memberData.isAdmin || false);
},
},
WorkspaceMutations: {
/**
* Cancels subscription for workspace
* @param _obj - result of the parent resolver
* @param {string} workspaceId - workspace id to cancel subscription for
* @param {ContextFactories} factories - factories to work with models
* @return {Promise<{recordId: *, record: {subscriptionId: null}}>}
*/
async cancelSubscription(
_obj,
{
input: { workspaceId },
},
{ factories }
) {
const workspaceModel = await factories.workspacesFactory.findById(workspaceId);
if (!workspaceModel) {
throw new UserInputError('There is no workspace with provided id');
}
if (!workspaceModel.subscriptionId) {
throw new UserInputError('There is no subscription for provided workspace');
}
await cloudPaymentsApi.cancelSubscription(workspaceModel.subscriptionId);
return {
recordId: workspaceModel._id,
record: {
...workspaceModel,
subscriptionId: null,
},
};
},
},
};