forked from rafaeljesus/newww
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustomer.js
469 lines (402 loc) · 13.9 KB
/
customer.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
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
var customer = module.exports = {};
var Joi = require('joi');
var Org = require('../agents/org');
var User = require('../agents/user');
var Customer = require('../agents/customer');
var P = require('bluebird');
var utils = require('../lib/utils');
var validate = require('validate-npm-package-name');
var invalidUserName = require('npm-user-validate').username;
var _ = require('lodash');
customer.getBillingInfo = function(request, reply) {
var opts = {
title: 'Billing',
updated: ('updated' in request.query),
canceled: ('canceled' in request.query),
stripePublicKey: process.env.STRIPE_PUBLIC_KEY
};
// Display a message to unpaid collaborators about the
// package they could be accessing if they paid for it
if (request.query.package) {
opts.package = request.query.package;
}
var stripeDataErrorHandler = function(err) {
if (err.statusCode === 404) {
return null;
} else {
throw err;
}
};
var stripeDataPromise = request.customer.getStripeData()
.catch(stripeDataErrorHandler);
var getByIdPromise = request.customer.getById(request.loggedInUser.email)
.catch(stripeDataErrorHandler);
var customerStripeData = P.join(stripeDataPromise, getByIdPromise, function(stripeCustomer, licenseApiCustomer) {
if (stripeCustomer && licenseApiCustomer) {
stripeCustomer.customer_id = licenseApiCustomer.stripe_customer_id;
}
return {
customer: stripeCustomer
};
});
var customerSubscriptions = request.customer.getSubscriptions()
.catch(function(err) {
request.logger.error('unable to get subscriptions for ' + request.loggedInUser.name);
request.logger.error(err);
return [];
}).then(function(subs) {
var privateModules = [],
orgs = [];
subs.forEach(function(sub) {
sub.cost = (sub.amount / 100) * sub.quantity;
if (sub.privateModules) {
privateModules.push(sub);
} else {
orgs.push(sub);
}
});
opts.totalCost = subs.map(function(sub) {
return sub.cost;
}).reduce(function(prev, curr) {
return prev + curr;
}, 0);
return {
privateModules: privateModules,
orgs: orgs
};
});
var onSuccess = function(opts) {
return reply.view('user/billing', opts);
};
var onError = function(err) {
request.logger.error(err);
return reply.view('errors/internal', err).code(500);
};
P.join(customerStripeData, customerSubscriptions, function(customer, subscriptions) {
var addopts = [customer, subscriptions];
addopts.forEach(function(e) {
_.extend(opts, e);
});
return opts;
})
.then(onSuccess, onError);
};
customer.updateBillingInfo = function(request, reply, callback) {
var sendToHubspot = request.server.methods.npme.sendData;
var coupon = request.payload.coupon;
var billingInfo = {
name: request.loggedInUser.name,
email: request.loggedInUser.email,
card: request.payload.stripeToken,
};
if (coupon) {
billingInfo.coupon = coupon.toLowerCase();
}
request.customer.updateBilling(billingInfo, function(err) {
var opts = {};
if (err) {
opts.errors = [];
opts.errors.push(new Error(err));
return reply.view('user/billing', opts);
}
var data = {
hs_context: {
pageName: "customer-billing-update",
ipAddress: utils.getUserIP(request)
},
email: billingInfo.email
};
sendToHubspot(process.env.HUBSPOT_FORM_PRIVATE_NPM_SIGNUP, data, function(er) {
if (er) {
request.logger.error('unable to send billing email to HubSpot');
request.logger.error(er);
}
if (callback) {
return callback(er);
}
return reply.redirect('/settings/billing?updated=1');
});
});
};
customer.deleteBillingInfo = function(request, reply) {
request.customer.del(function(err, customer) {
if (err) {
request.logger.error("unable to delete billing info for " + customer);
request.logger.error(err);
return reply.view('errors/internal').code(500);
}
return reply.redirect('/settings/billing?canceled=1');
});
};
var plans = {
private_modules: 'npm-paid-individual-user-7',
orgs: 'npm-paid-org-7'
};
var subscriptionSchema = {
planType: Joi.string().valid(Object.keys(plans)).required(),
stripeToken: Joi.string(),
coupon: Joi.string().optional().allow(''),
"human-name": Joi.string().optional().allow(''),
orgScope: Joi.string().when('planType', {
is: 'orgs',
then: Joi.required()
}),
"new-user": Joi.string().optional(),
"paid-org-type": Joi.string().optional(),
"card-number": Joi.string().optional(),
"card-cvc": Joi.string().optional(),
"card-exp-month": Joi.string().optional(),
"card-exp-year": Joi.string().optional()
};
customer.subscribe = function(request, reply) {
var loggedInUser = request.loggedInUser.name;
Joi.validate(request.payload, subscriptionSchema, function(err, planData) {
if (err) {
var notices;
if (planData.planType === 'orgs') {
notices = err.details.map(function(e) {
return e.message;
});
return reply.view('org/create', {
stripePublicKey: process.env.STRIPE_PUBLIC_KEY,
errorNotices: notices
});
} else {
notices = err.details.map(function(e) {
return P.reject(e.message);
});
return request.saveNotifications(notices).then(function(token) {
return reply.redirect('/settings/billing' + (token ? '?notice=' + token : ''));
}).catch(function(err) {
request.logger.error(err);
});
}
}
var planType = planData.planType;
var planInfo = {
plan: plans[planType]
};
if (request.loggedInUser.customer) {
return subscribe();
} else {
return customer.updateBillingInfo(request, reply, subscribe);
}
function subscribe() {
if (planType === 'orgs') {
return subscribeToOrg();
} else {
return request.customer.createSubscription(planInfo, function(err, subscriptions) {
if (err) {
request.logger.error("unable to update subscription to " + planInfo.plan);
request.logger.error(err);
}
if (typeof subscriptions === 'string') {
request.logger.info("created subscription: ", planInfo);
}
User(request.loggedInUser).dropCache(request.loggedInUser.name, function(err) {
if (err) {
request.logger.error(err);
return reply.view('errors/internal', err);
}
return reply.redirect('/settings/billing?updated=1');
});
});
}
}
function subscribeToOrg() {
var newUser = planData['new-user'];
if (newUser && invalidUserName(newUser)) {
var err = new Error("User name must be valid");
request.logger.error(err);
return request.saveNotifications([
P.reject(err.message)
]).then(function(token) {
var url = '/org/transfer-user-name';
var param = token ? "?notice=" + token : "";
param = param + "&orgScope=" + request.query.orgScope;
url = url + param;
return reply.redirect(url);
}).catch(function(err) {
request.logger.error(err);
});
}
// check if the org name works as a package name
var valid = validate('@' + planData.orgScope + '/foo');
if (!valid.errors) {
// now check if the org name works on its own
valid = validate(planData.orgScope);
}
if (valid.errors) {
return reply.view('org/create', {
stripePublicKey: process.env.STRIPE_PUBLIC_KEY,
errorNotices: valid.errors
});
}
var opts = {};
Org(loggedInUser)
.getInfo(planData.orgScope)
.then(function() {
throw Object.assign(new Error("Org already exists"), {
code: 'EEXIST',
statusCode: 409,
what: 'org'
});
})
.catch(function(err) {
if (err.statusCode !== 404) {
throw err;
}
// org doesn't yet exist, transfer user then create org
var start = newUser ? User(request.loggedInUser).toOrg(loggedInUser, newUser) : P.resolve(null);
return start;
})
.then(function(newUserData) {
var setSession = P.promisify(request.server.methods.user.setSession(request));
var delSession = P.promisify(request.server.methods.user.delSession(request));
loggedInUser = newUserData ? newUser : loggedInUser;
if (newUserData) {
return delSession(request.loggedInUser)
.then(function() {
request.logger.info("setting session to: " + loggedInUser);
return setSession({
name: loggedInUser
});
});
} else {
return Org(loggedInUser)
.create({
scope: planData.orgScope,
humanName: planData["human-name"]
});
}
})
.then(function() {
planInfo.npm_org = planData.orgScope;
return Customer(loggedInUser).createSubscription(planInfo);
})
.tap(function(subscription) {
if (typeof subscription === 'string') {
request.logger.info("created subscription: ", planInfo);
}
var dropCache = P.promisify(User(request.loggedInUser).dropCache);
return dropCache(loggedInUser);
})
.then(function(subscription) {
return Customer(loggedInUser).extendSponsorship(subscription.license_id, loggedInUser);
})
.then(function(extendedSponsorship) {
return Customer(loggedInUser).acceptSponsorship(extendedSponsorship.verification_key);
})
.then(function() {
return reply.redirect('/org/' + planData.orgScope);
})
.catch(function(err) {
if (!(err.code === 'EEXIST' && err.what === 'org')) {
throw err;
}
return Org(loggedInUser).getUsers(planData.orgScope)
.then(function(users) {
users = users || {};
users.items = users.items || [];
var isSuperAdmin = users.items.filter(function(user) {
return user.role && user.role.match(/super-admin/);
}).some(function(admin) {
return admin.name === loggedInUser;
});
if (isSuperAdmin) {
opts.users = users;
return request.customer.getLicenseForOrg(planData.orgScope);
} else {
throw Object.assign(new Error("Org already exists"), {
statusCode: 409,
code: 'EEXIST',
what: 'org'
});
}
})
.then(function(license) {
if (license && license.length) {
throw Object.assign(new Error("You already own this Organization"), {
code: 'EEXIST',
statusCode: 409,
what: 'license'
});
} else {
throw Object.assign(new Error("No license for this org"), {
code: 'ENOLICENSE',
statusCode: 404
});
}
})
.catch(function(err) {
if (err.code !== 'ENOLICENSE' && err.code !== 'ENOCUSTOMER') {
throw err;
}
planInfo.npm_org = planData.orgScope;
return request.customer.createSubscription(planInfo);
})
.then(function(license) {
license = license || {};
var extensions = opts.users.items.map(function(user) {
return request.customer.extendSponsorship(license.license_id, user.name);
});
return P.all(extensions);
})
.then(function(sponsorships) {
var acceptances = sponsorships.map(function(sponsorship) {
return request.customer.acceptSponsorship(sponsorship.verification_key);
});
return P.all(acceptances)
.catch(function(err) {
if (err.statusCode !== 409) {
throw err;
}
});
})
.then(function() {
var redirectUrl = "/org/" + planData.orgScope;
var message = "You have successfully restarted " + planData.orgScope;
return request.saveNotifications([
P.resolve(message)
]).then(function(token) {
var param = token ? "?notice=" + token : "";
redirectUrl = redirectUrl + param;
return reply.redirect(redirectUrl);
}).catch(function(err) {
request.logger.error(err);
return reply.redirect(redirectUrl);
});
});
})
.catch(function(err) {
if (!(err.statusCode === 409 && err.message)) {
throw err;
}
return reply.view('org/create', {
stripePublicKey: process.env.STRIPE_PUBLIC_KEY,
inUseError: true,
orgScope: planData.orgScope,
humanName: planData["human-name"],
errorNotices: [err]
});
})
.catch(function(err) {
if (err.statusCode < 500) {
request.logger.error(err);
return request.saveNotifications([
P.reject(err.message)
]).then(function(token) {
var url = '/org/create';
var param = token ? "?notice=" + token : "";
url = url + param;
return reply.redirect(url);
}).catch(function(err) {
request.logger.error(err);
});
} else {
return reply(err);
}
});
}
});
};