-
-
Notifications
You must be signed in to change notification settings - Fork 260
/
createOrder.test.js
926 lines (825 loc) · 34.3 KB
/
createOrder.test.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
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
import { expect } from 'chai';
import config from 'config';
import gql from 'fake-tag';
import { cloneDeep } from 'lodash';
import nock from 'nock';
import sinon from 'sinon';
import { v4 as uuid } from 'uuid';
import { maxInteger } from '../../../../server/constants/math';
import emailLib from '../../../../server/lib/email';
import twitter from '../../../../server/lib/twitter';
import models from '../../../../server/models';
import * as store from '../../../stores';
import { fakeTier } from '../../../test-helpers/fake-data';
import * as utils from '../../../utils';
const baseOrder = Object.freeze({
quantity: 1,
interval: null,
totalAmount: 154300,
paymentMethod: {
name: '4242',
token: 'tok_1B5j8xDjPFcHOcTm3ogdnq0K',
data: {
expMonth: 10,
expYear: 2023,
brand: 'Visa',
country: 'US',
funding: 'credit',
},
},
collective: {
id: null,
},
});
const createOrderMutation = gql`
mutation CreateOrder($order: OrderInputType!) {
createOrder(order: $order) {
id
status
description
createdByUser {
id
}
paymentMethod {
id
}
totalAmount
fromCollective {
id
slug
name
website
}
collective {
id
slug
currency
}
subscription {
id
amount
interval
isActive
stripeSubscriptionId
}
}
}
`;
const constants = Object.freeze({
paymentMethod: {
name: 'payment method',
service: 'stripe',
type: 'creditcard',
data: {
expMonth: 11,
expYear: 2025,
},
},
});
describe('server/graphql/v1/createOrder', () => {
let sandbox, tweetStatusSpy, fearlesscitiesbrussels, emailSendMessageSpy;
before(() => {
nock('https://data.fixer.io')
.get(/20[0-9]{2}\-[0-9]{2}\-[0-9]{2}/)
.times(5)
.query({
access_key: config.fixer.accessKey, // eslint-disable-line camelcase
base: 'EUR',
symbols: 'USD',
})
.reply(200, { base: 'EUR', date: '2017-09-01', rates: { USD: 1.192 } });
nock('https://data.fixer.io')
.get('/latest')
.times(5)
.query({
access_key: config.fixer.accessKey, // eslint-disable-line camelcase
base: 'EUR',
symbols: 'USD',
})
.reply(200, { base: 'EUR', date: '2017-09-22', rates: { USD: 1.1961 } }, ['Server', 'nosniff']);
});
after(() => nock.cleanAll());
beforeEach(async () => {
await utils.resetTestDB();
sandbox = sinon.createSandbox();
tweetStatusSpy = sandbox.spy(twitter, 'tweetStatus');
emailSendMessageSpy = sandbox.spy(emailLib, 'sendMessage');
// Given a collective (with a host)
({ fearlesscitiesbrussels } = await store.newCollectiveWithHost('fearlesscitiesbrussels', 'EUR', 'EUR', 5));
// And the above collective's host has a stripe account
await store.stripeConnectedAccount(fearlesscitiesbrussels.HostCollectiveId);
// And given that the above collective is active
await fearlesscitiesbrussels.update({ isActive: true });
// And given that the endpoint for creating customers on Stripe
// is patched
utils.stubStripeCreate(sandbox, {
charge: {
currency: 'eur',
status: 'succeeded',
},
paymentIntentConfirmed: {
charges: { data: [{ id: 'ch_1AzPXHD8MNtzsDcgXpUhv4pm', currency: 'eur', status: 'succeeded' }] },
status: 'succeeded',
},
});
// And given the stripe stuff that depends on values in the
// order struct is patch. It's here and not on each test because
// the `totalAmount' field doesn't change throught the tests.
utils.stubStripeBalance(sandbox, baseOrder.totalAmount, 'eur', Math.round(baseOrder.totalAmount * 0.05), 4500); // This is the payment processor fee.
});
afterEach(() => sandbox.restore());
it('creates a pending order (pledge) if the collective is not active', async () => {
const collective = await models.Collective.create({
slug: 'test',
name: 'test',
isActive: false,
isPledged: true,
website: 'https://github.com/opencollective/frontend',
});
const thisOrder = cloneDeep(baseOrder);
thisOrder.collective.id = collective.id;
const remoteUser = await models.User.createUserWithCollective({
firstName: 'John',
lastName: 'Smith',
email: 'jsmith@email.com',
twitterHandle: 'johnsmith',
newsletterOptIn: true,
});
const res = await utils.graphqlQuery(
createOrderMutation,
{
order: thisOrder,
},
remoteUser,
);
// There should be no errors
res.errors && console.error(res.errors);
expect(res.errors).to.not.exist;
expect(res.data.createOrder.status).to.equal('PLEDGED');
});
it('creates a pending order (pledge) with inactive subscription if interval is included and collective is not active', async () => {
const collective = await models.Collective.create({
slug: 'test',
name: 'test',
isActive: false,
isPledged: true,
website: 'https://github.com/opencollective/frontend',
});
const thisOrder = cloneDeep(baseOrder);
thisOrder.collective.id = collective.id;
thisOrder.interval = 'month';
const remoteUser = await models.User.createUserWithCollective({
firstName: 'John',
lastName: 'Smith',
email: 'jsmith@email.com',
twitterHandle: 'johnsmith',
newsletterOptIn: true,
});
const res = await utils.graphqlQuery(
createOrderMutation,
{
order: thisOrder,
},
remoteUser,
);
// There should be no errors
res.errors && console.error(res.errors);
expect(res.errors).to.not.exist;
expect(res.data.createOrder.status).to.equal('PLEDGED');
expect(res.data.createOrder.subscription.interval).to.equal('month');
});
it('creates a pending order if the collective is active and the payment method type is manual', async () => {
const hostAdmin = await models.User.createUserWithCollective({
firstName: 'Mike',
lastName: 'Doe',
email: store.randEmail(),
});
const host = await models.Collective.create({
slug: 'host-collective',
name: 'Open Collective 501c3',
type: 'ORGANIZATION',
currency: 'USD',
CreatedByUserId: hostAdmin.id,
settings: {
paymentMethods: {
manual: {
instructions:
'Your order is pending. Please send a wire to <code>IBAN 1234567890987654321</code> for the amount of {amount} with the mention: {collective} {tier} order: {OrderId} {unknownVariable}',
},
},
},
});
await host.addUserWithRole(hostAdmin, 'ADMIN', { CreatedByUserId: hostAdmin.id });
const collective = await models.Collective.create({
slug: 'webpack',
name: 'test',
currency: 'USD',
isActive: true,
});
const event = await models.Collective.create({
slug: 'meetup-ev1',
name: 'meetup',
type: 'EVENT',
ParentCollectiveId: collective.id,
isActive: true,
});
const tier = await models.Tier.create({
slug: 'backer',
name: 'best backer',
amount: 1000,
currency: collective.currency,
CollectiveId: event.id,
});
await collective.addHost(host, hostAdmin, { shouldAutomaticallyApprove: true });
await collective.update({ isActive: true });
await utils.waitForCondition(() => emailSendMessageSpy.callCount === 1, {
tag: 'fearlesscitiesbrussels would love to be hosted ',
});
emailSendMessageSpy.resetHistory();
const thisOrder = cloneDeep(baseOrder);
delete thisOrder.paymentMethod;
thisOrder.paymentMethod = { type: 'manual' };
thisOrder.collective.id = event.id;
thisOrder.tier = { id: tier.id };
thisOrder.quantity = 2;
thisOrder.totalAmount = 2000;
const remoteUser = await models.User.createUserWithCollective({
firstName: 'John',
lastName: 'Smith',
email: 'jsmith@email.com',
twitterHandle: 'johnsmith',
});
const res = await utils.graphqlQuery(
createOrderMutation,
{
order: thisOrder,
},
remoteUser,
);
// There should be no errors
res.errors && console.error(res.errors);
expect(res.errors).to.not.exist;
expect(res.data.createOrder.status).to.equal('PENDING');
const transactionsCount = await models.Transaction.count({
where: { OrderId: res.data.createOrder.id },
});
expect(transactionsCount).to.equal(0);
await utils.waitForCondition(() => emailSendMessageSpy.callCount === 2);
expect(emailSendMessageSpy.callCount).to.equal(2);
const pendingEmailArgs = emailSendMessageSpy.args.find(callArgs =>
callArgs[1].includes('New pending financial contribution'),
);
expect(pendingEmailArgs).to.exist;
const actionRequiredEmailArgs = emailSendMessageSpy.args.find(callArgs => callArgs[1].includes('ACTION REQUIRED'));
expect(actionRequiredEmailArgs).to.exist;
expect(actionRequiredEmailArgs).to.exist;
expect(actionRequiredEmailArgs[0]).to.equal(remoteUser.email);
expect(actionRequiredEmailArgs[2]).to.match(/IBAN 1234567890987654321/);
expect(actionRequiredEmailArgs[2]).to.match(
/for the amount of <strong>\$20\.00<\/strong> with the mention: <strong>webpack event<\/strong> <strong>backer<\/strong> order: <strong>[0-9]+<\/strong>/,
);
expect(actionRequiredEmailArgs[1]).to.equal('ACTION REQUIRED: your $20 registration to meetup is pending');
});
it('creates an order as new user and sends a tweet', async () => {
const order = cloneDeep(baseOrder);
// And given a twitter connected account for the above
// collective
await models.ConnectedAccount.create({
CollectiveId: fearlesscitiesbrussels.id,
service: 'twitter',
clientId: 'clientid',
token: 'xxxx',
settings: {
newBacker: {
active: true,
tweet: '{backerTwitterHandle} thank you for your {amount} donation!',
},
},
});
// And given an order
order.collective = { id: fearlesscitiesbrussels.id };
const remoteUser = await models.User.createUserWithCollective({
firstName: 'John',
lastName: 'Smith',
email: 'jsmith@email.com',
twitterHandle: 'johnsmith',
newsletterOptIn: true,
});
// When the query is executed
const res = await utils.graphqlQuery(createOrderMutation, { order }, remoteUser);
// Then there should be no errors
res.errors && console.error(res.errors);
expect(res.errors).to.not.exist;
const fromCollective = res.data.createOrder.fromCollective;
const collective = res.data.createOrder.collective;
const transaction = await models.Transaction.findOne({
where: { CollectiveId: collective.id, amount: order.totalAmount },
});
expect(transaction.FromCollectiveId).to.equal(fromCollective.id);
expect(transaction.CollectiveId).to.equal(collective.id);
expect(transaction.currency).to.equal(collective.currency);
expect(transaction.hostFeeInHostCurrency).to.equal(0);
expect(transaction.platformFeeInHostCurrency).to.equal(-(0.05 * order.totalAmount));
expect(transaction.data.charge.currency).to.equal(collective.currency.toLowerCase());
expect(transaction.data.charge.status).to.equal('succeeded');
expect(transaction.data.balanceTransaction.net + transaction.hostFeeInHostCurrency).to.equal(
transaction.netAmountInCollectiveCurrency,
);
// we create a customer on the host stripe account even for one time charges
expect(transaction.data.charge.customer).to.not.be.null;
const {
createdByUser: { id },
} = res.data.createOrder;
const user = await models.User.findByPk(id);
expect(user.newsletterOptIn).to.be.true;
// make sure the payment has been recorded in the connected Stripe Account of the host
expect(transaction.data.charge.currency).to.equal('eur');
await utils.waitForCondition(() => tweetStatusSpy.callCount > 0);
expect(tweetStatusSpy.firstCall.args[1]).to.contain('@johnsmith thank you for your €1,543 donation!');
});
it('creates an order for an event ticket and receives the ticket confirmation by email with iCal.ics attached', async () => {
const d = new Date();
const startsAt = d.setMonth(d.getMonth() + 1);
const endsAt = new Date(startsAt);
endsAt.setHours(endsAt.getHours() + 2);
const event = await models.Collective.create({
type: 'EVENT',
isActive: true,
ParentCollectiveId: fearlesscitiesbrussels.id,
name: 'Sustain OSS London 2019',
description: 'Short description',
longDescription: 'Longer description',
locationName: 'Github',
address: 'San Francisco',
slug: 'sustainoss-london',
startsAt,
endsAt,
});
// Given an order request
const user = (await store.newUser('John Appleseed')).user;
const newOrder = cloneDeep(baseOrder);
const tier = await fakeTier({
CollectiveId: event.id,
name: 'tier-name',
type: 'TICKET',
amount: 0,
amountType: 'FLEXIBLE',
presets: [0, 500, 1000],
});
newOrder.collective = { id: event.id };
newOrder.tier = { id: tier.id };
newOrder.totalAmount = 1000;
// When the GraphQL query is executed
let res;
emailSendMessageSpy.resetHistory();
res = await utils.graphqlQuery(createOrderMutation, { order: newOrder }, user);
// There should be no errors
res.errors && console.error(res.errors);
expect(res.errors).to.not.exist;
await utils.waitForCondition(() => emailSendMessageSpy.callCount > 0);
expect(emailSendMessageSpy.callCount).to.equal(1);
expect(emailSendMessageSpy.firstCall.args[0]).to.equal(user.email);
expect(emailSendMessageSpy.firstCall.args[1]).to.equal(`1 ticket confirmed for ${event.name}`);
expect(emailSendMessageSpy.firstCall.args[2]).to.contain('kaaitheater'); // double check that we use the custom email for fearlesscitiesbrussels
expect(emailSendMessageSpy.firstCall.args[3].attachments[0].filename).to.equal(`${event.slug}.ics`);
expect(emailSendMessageSpy.firstCall.args[3].attachments[0].content).to.contain(
'/fearlesscitiesbrussels/events/sustainoss-london',
);
// also test the different path for free tickets
newOrder.totalAmount = 0;
delete newOrder.paymentMethod;
res = await utils.graphqlQuery(createOrderMutation, { order: newOrder }, user);
// Make sure the order's status is PAID
expect(res.data.createOrder.status).to.equal('PAID');
expect(res.data.createOrder.description).to.equal('Registration to Sustain OSS London 2019 (tier-name)');
// Then there should be no errors
res.errors && console.error(res.errors);
expect(res.errors).to.not.exist;
await utils.waitForCondition(() => emailSendMessageSpy.callCount > 0);
// expect(emailSendMessageSpy.callCount).to.equal(1); // this often fails (expect 2 to equal 1) :-/
expect(emailSendMessageSpy.firstCall.args[0]).to.equal(user.email);
expect(emailSendMessageSpy.firstCall.args[1]).to.equal(`1 ticket confirmed for ${event.name}`);
});
it('shoud not create an order as new incognito user', async () => {
// Given an order request
const newOrder = cloneDeep(baseOrder);
newOrder.collective = { id: fearlesscitiesbrussels.id };
newOrder.totalAmount = 0;
delete newOrder.paymentMethod;
// When the GraphQL query is executed
const res = await utils.graphqlQuery(createOrderMutation, { order: newOrder });
// Then there should be errors
expect(res.errors).to.exist;
expect(res.errors[0].message).to.equal(
'You need to provide a guest profile with an email for logged out contributions',
);
});
it("doesn't store the payment method for user if order fail", async () => {
const uniqueName = uuid();
// Given an order request
const newOrder = {
...cloneDeep(baseOrder),
collective: { id: fearlesscitiesbrussels.id },
paymentMethod: {
name: uniqueName,
token: 'tok_chargeDeclinedProcessingError', // See https://stripe.com/docs/testing#cards
service: 'stripe',
type: 'creditcard',
data: {
expMonth: 10,
expYear: 1999,
brand: 'Visa',
country: 'US',
funding: 'credit',
},
save: true,
},
};
const remoteUser = await models.User.createUserWithCollective({
firstName: '',
lastName: '',
email: store.randEmail('rejectedcard@protonmail.ch'),
});
const res = await utils.graphqlQuery(createOrderMutation, { order: newOrder }, remoteUser);
expect(res.errors[0].message).to.equal('Your card was declined.');
const pm = await models.PaymentMethod.findOne({ where: { name: uniqueName } });
// If payment fails, we keep `saved` to null
expect(pm.saved).to.be.null;
});
it('creates an order as logged in user', async () => {
// Given a user
const xdamman = (await store.newUser('xdamman')).user;
const order = cloneDeep(baseOrder);
// And given that the order is from the above user with the
// above payment method
order.fromCollective = { id: xdamman.CollectiveId };
order.collective = { id: fearlesscitiesbrussels.id };
// When the query is executed
const res = await utils.graphqlQuery(createOrderMutation, { order }, xdamman);
// Then there should be no errors
res.errors && console.error(res.errors);
expect(res.errors).to.not.exist;
// And then the creator of the order should be xdamman
const collective = res.data.createOrder.collective;
const transaction = await models.Transaction.findOne({
where: { CollectiveId: collective.id, amount: order.totalAmount },
});
expect(transaction.FromCollectiveId).to.equal(xdamman.CollectiveId);
expect(transaction.CollectiveId).to.equal(collective.id);
expect(transaction.currency).to.equal(collective.currency);
expect(transaction.hostFeeInHostCurrency).to.equal(0);
expect(transaction.platformFeeInHostCurrency).to.equal(-(0.05 * order.totalAmount));
expect(transaction.data.charge.currency).to.equal(collective.currency.toLowerCase());
expect(transaction.data.charge.status).to.equal('succeeded');
expect(transaction.data.balanceTransaction.net + transaction.hostFeeInHostCurrency).to.equal(
transaction.netAmountInCollectiveCurrency,
);
// make sure the payment has been recorded in the connected
// Stripe Account of the host
expect(transaction.data.charge.currency).to.equal('eur');
const createdOrder = await models.Order.findByPk(res.data.createOrder.id);
expect(createdOrder.status).to.equal('PAID');
});
it('creates an order as logged in user using saved credit card', async () => {
// Given a user
const xdamman = (await store.newUser('xdamman')).user;
// And that this user has a payment method saved
const pm = await models.PaymentMethod.create({
CollectiveId: xdamman.CollectiveId,
name: '4242',
service: 'stripe',
type: 'creditcard',
token: 'tok_2B5j8xDjPFcHOcTm3ogdnq0K',
});
// And the order is setup with the above data
const order = cloneDeep(baseOrder);
order.collective = { id: fearlesscitiesbrussels.id };
order.fromCollective = { id: xdamman.CollectiveId };
order.paymentMethod = { uuid: pm.uuid };
// When the order is created
const res = await utils.graphqlQuery(createOrderMutation, { order }, xdamman);
// There should be no errors
res.errors && console.error(res.errors);
expect(res.errors).to.not.exist;
// And the transaction has to have the data from the right user,
// right collective, and right amounts
const collective = res.data.createOrder.collective;
const transaction = await models.Transaction.findOne({
where: { CollectiveId: collective.id, amount: order.totalAmount },
});
expect(transaction.FromCollectiveId).to.equal(xdamman.CollectiveId);
expect(transaction.CollectiveId).to.equal(collective.id);
expect(transaction.currency).to.equal(collective.currency);
expect(transaction.hostFeeInHostCurrency).to.equal(0);
expect(transaction.platformFeeInHostCurrency).to.equal(-(0.05 * order.totalAmount));
expect(transaction.data.charge.currency).to.equal(collective.currency.toLowerCase());
expect(transaction.data.charge.status).to.equal('succeeded');
expect(transaction.data.balanceTransaction.net + transaction.hostFeeInHostCurrency).to.equal(
transaction.netAmountInCollectiveCurrency,
);
// make sure the payment has been recorded in the connected
// Stripe Account of the host
expect(transaction.data.charge.currency).to.equal('eur');
});
it('creates a recurring donation as logged in user', async () => {
// Given a user
const xdamman = (await store.newUser('xdamman')).user;
const order = cloneDeep(baseOrder);
// And the parameters for the query
order.fromCollective = { id: xdamman.CollectiveId };
order.paymentMethod = {
...constants.paymentMethod,
token: 'tok_1B5j8xDjPFcHOcTm3ogdnq0K',
};
order.interval = 'month';
order.totalAmount = 1000;
order.collective = { id: fearlesscitiesbrussels.id };
// When the order is created
const res = await utils.graphqlQuery(createOrderMutation, { order }, xdamman);
// There should be no errors
res.errors && console.error(res.errors);
expect(res.errors).to.not.exist;
// Then the created transaction should match the requested data
const orderCreated = res.data.createOrder;
const { collective, subscription } = orderCreated;
expect(subscription.interval).to.equal('month');
expect(subscription.isActive).to.be.true;
expect(subscription.amount).to.equal(order.totalAmount);
const transaction = await models.Transaction.findOne({
where: {
CollectiveId: collective.id,
FromCollectiveId: xdamman.CollectiveId,
amount: order.totalAmount,
},
});
// make sure the transaction has been recorded
expect(transaction.FromCollectiveId).to.equal(xdamman.CollectiveId);
expect(transaction.CollectiveId).to.equal(collective.id);
expect(transaction.currency).to.equal(collective.currency);
const createdOrder = await models.Order.findByPk(res.data.createOrder.id);
expect(createdOrder.status).to.equal('ACTIVE');
});
it('creates an order as a new user for a new organization', async () => {
const order = cloneDeep(baseOrder);
// Given the following data for the order
order.collective = { id: fearlesscitiesbrussels.id };
order.fromCollective = { name: 'NewCo', website: 'newco.com' };
order.paymentMethod = {
...constants.paymentMethod,
token: 'tok_3B5j8xDjPFcHOcTm3ogdnq0K',
};
const remoteUser = await models.User.createUserWithCollective({ email: store.randEmail() });
// When the order is created
const res = await utils.graphqlQuery(createOrderMutation, { order }, remoteUser);
// There should be no errors
res.errors && console.error(res.errors);
expect(res.errors).to.not.exist;
const orderCreated = res.data.createOrder;
const fromCollective = orderCreated.fromCollective;
const collective = orderCreated.collective;
const transactions = await models.Transaction.findAll({
where: { OrderId: orderCreated.id },
});
expect(fromCollective.website).to.equal('https://newco.com'); // api should prepend https://
expect(transactions.length).to.equal(4);
const contributions = transactions.filter(t => t.kind === 'CONTRIBUTION');
expect(contributions.length).to.equal(2);
expect(contributions[0].type).to.equal('DEBIT');
expect(contributions[0].FromCollectiveId).to.equal(collective.id);
expect(contributions[0].CollectiveId).to.equal(fromCollective.id);
expect(contributions[1].type).to.equal('CREDIT');
expect(contributions[1].FromCollectiveId).to.equal(fromCollective.id);
expect(contributions[1].CollectiveId).to.equal(collective.id);
});
it('creates an order as a logged in user for an existing organization', async () => {
const order = cloneDeep(baseOrder);
// Given some users
const xdamman = (await store.newUser('xdamman')).user;
const duc = (await store.newUser('another user')).user;
// And given an organization
const newco = await models.Collective.create({
type: 'ORGANIZATION',
name: 'newco',
CreatedByUserId: xdamman.id,
});
// And the order parameters
order.fromCollective = { id: newco.id };
order.collective = { id: fearlesscitiesbrussels.id };
order.paymentMethod = {
...constants.paymentMethod,
token: 'tok_4B5j8xDjPFcHOcTm3ogdnq0K',
service: 'stripe',
type: 'creditcard',
};
// Should fail if not an admin of the organization
let res = await utils.graphqlQuery(createOrderMutation, { order }, duc);
expect(res.errors).to.exist;
expect(res.errors[0].message).to.equal(
"You don't have sufficient permissions to create an order on behalf of the newco organization",
);
await models.Member.create({
CollectiveId: newco.id,
MemberCollectiveId: duc.CollectiveId,
role: 'ADMIN',
CreatedByUserId: duc.id,
});
res = await utils.graphqlQuery(createOrderMutation, { order }, duc);
// There should be no errors
res.errors && console.error(res.errors);
expect(res.errors).to.not.exist;
const orderCreated = res.data.createOrder;
const fromCollective = orderCreated.fromCollective;
const collective = orderCreated.collective;
const transactions = await models.Transaction.findAll({
where: { OrderId: orderCreated.id },
});
expect(orderCreated.createdByUser.id).to.equal(duc.id);
expect(transactions.length).to.equal(4);
const contributions = transactions.filter(t => t.kind === 'CONTRIBUTION');
expect(contributions.length).to.equal(2);
expect(contributions[0].type).to.equal('DEBIT');
expect(contributions[0].FromCollectiveId).to.equal(collective.id);
expect(contributions[0].CollectiveId).to.equal(fromCollective.id);
expect(contributions[1].type).to.equal('CREDIT');
expect(contributions[1].FromCollectiveId).to.equal(fromCollective.id);
expect(contributions[1].CollectiveId).to.equal(collective.id);
});
it("creates an order as a logged in user for an existing collective using the collective's payment method", async () => {
const duc = (await store.newUser('another user')).user;
const order = cloneDeep(baseOrder);
const newco = await models.Collective.create({
type: 'ORGANIZATION',
name: 'newco',
CreatedByUserId: duc.id,
});
order.collective = { id: fearlesscitiesbrussels.id };
order.fromCollective = { id: newco.id };
order.totalAmount = 20000;
const paymentMethod = await models.PaymentMethod.create({
...constants.paymentMethod,
token: 'tok_5B5j8xDjPFcHOcTm3ogdnq0K',
monthlyLimitPerMember: 10000,
CollectiveId: newco.id,
});
order.paymentMethod = { uuid: paymentMethod.uuid };
// Should fail if not an admin or member of the organization
let res = await utils.graphqlQuery(createOrderMutation, { order }, duc);
expect(res.errors).to.exist;
expect(res.errors[0].message).to.equal(
"You don't have sufficient permissions to create an order on behalf of the newco organization",
);
await models.Member.create({
CollectiveId: newco.id,
MemberCollectiveId: duc.CollectiveId,
role: 'MEMBER',
CreatedByUserId: duc.id,
});
// Should fail if order.totalAmount > PaymentMethod.monthlyLimitPerMember
res = await utils.graphqlQuery(createOrderMutation, { order }, duc);
expect(res.errors).to.exist;
expect(res.errors[0].message).to.equal(
'The total amount of this order (€200 ~= $239) is higher than your monthly spending limit on this payment method (stripe:creditcard) ($100)',
);
sandbox.useFakeTimers(new Date('2017-09-22').getTime());
await paymentMethod.update({ monthlyLimitPerMember: 25000 }); // $250 limit
res = await utils.graphqlQuery(createOrderMutation, { order }, duc);
// There should be no errors
res.errors && console.error(res.errors);
expect(res.errors).to.not.exist;
const availableBalance = await paymentMethod.getBalanceForUser(duc);
expect(availableBalance.amount).to.equal(1160);
const orderCreated = res.data.createOrder;
const fromCollective = orderCreated.fromCollective;
const collective = orderCreated.collective;
const transactions = await models.Transaction.findAll({
where: { OrderId: orderCreated.id },
order: [['id', 'ASC']],
});
expect(orderCreated.createdByUser.id).to.equal(duc.id);
expect(transactions.length).to.equal(4);
const contributions = transactions.filter(t => t.kind === 'CONTRIBUTION');
expect(contributions.length).to.equal(2);
expect(contributions[0].type).to.equal('DEBIT');
expect(contributions[0].FromCollectiveId).to.equal(collective.id);
expect(contributions[0].CollectiveId).to.equal(fromCollective.id);
expect(contributions[1].type).to.equal('CREDIT');
expect(contributions[1].FromCollectiveId).to.equal(fromCollective.id);
expect(contributions[1].CollectiveId).to.equal(collective.id);
// Should fail if order.totalAmount > PaymentMethod.getBalanceForUser
res = await utils.graphqlQuery(createOrderMutation, { order }, duc);
expect(res.errors).to.exist;
expect(res.errors[0].message).to.equal(
"You don't have enough funds available ($12 left) to execute this order (€200 ~= $239)",
);
});
describe('host moves funds between collectives', async () => {
const order = cloneDeep(baseOrder);
let hostAdmin, hostCollective;
beforeEach(async () => {
// First clean the database
await utils.resetTestDB();
// Given a host collective and its admin
({ hostAdmin, hostCollective } = await store.newHost('host-collective', 'USD', 10));
// And the above collective's host has a stripe account
await store.stripeConnectedAccount(hostCollective.id);
// And given two collectives in that host
const fromCollective = (await store.newCollectiveInHost('opensource', 'USD', hostCollective)).collective;
await fromCollective.update({ isActive: true });
const { collective } = await store.newCollectiveInHost('apex', 'USD', hostCollective);
await collective.update({ isActive: true });
// And given a payment method for the host
const paymentMethod = await models.PaymentMethod.create({
service: 'opencollective',
CollectiveId: fromCollective.id,
});
// And given the following changes for the order
order.fromCollective = { id: fromCollective.id };
order.collective = { id: collective.id };
order.paymentMethod = { uuid: paymentMethod.uuid };
order.interval = null;
order.totalAmount = maxInteger;
delete order.tier;
// And add some funds to the fromCollective
await models.Transaction.create({
CreatedByUserId: hostAdmin.id,
HostCollectiveId: fromCollective.HostCollectiveId,
CollectiveId: fromCollective.id,
netAmountInCollectiveCurrency: 746149,
type: 'CREDIT',
currency: 'USD',
});
});
it('Should fail if not enough funds in the fromCollective', async () => {
const res = await utils.graphqlQuery(createOrderMutation, { order }, hostAdmin);
expect(res.errors).to.exist;
expect(res.errors[0].message).to.equal(
"You don't have enough funds available ($7,461 left) to execute this order ($21,474,836)",
);
});
it('succeeds', async () => {
order.totalAmount = 20000;
const res = await utils.graphqlQuery(createOrderMutation, { order }, hostAdmin);
expect(res.errors).to.not.exist;
});
});
it("creates an order as a logged in user for an existing collective using the collective's balance", async () => {
const xdamman = (await store.newUser('xdamman')).user;
const order = cloneDeep(baseOrder);
const { hostCollective } = await store.newHost('Host Collective', 'USD', 10);
const fromCollective = (await store.newCollectiveInHost('opensource', 'USD', hostCollective)).collective;
await fromCollective.update({ isActive: true });
const collective = (await store.newCollectiveInHost('apex', 'USD', hostCollective)).collective;
await collective.update({ isActive: true });
await models.Member.create({
CreatedByUserId: xdamman.id,
CollectiveId: fromCollective.id,
MemberCollectiveId: xdamman.CollectiveId,
role: 'ADMIN',
});
const paymentMethod = await models.PaymentMethod.create({
CreatedByUserId: xdamman.id,
service: 'opencollective',
type: 'collective',
CollectiveId: fromCollective.id,
});
await models.Transaction.create({
CreatedByUserId: xdamman.id,
HostCollectiveId: fromCollective.HostCollectiveId,
CollectiveId: fromCollective.id,
netAmountInCollectiveCurrency: 746149,
type: 'CREDIT',
currency: 'USD',
});
order.fromCollective = { id: fromCollective.id };
order.collective = { id: collective.id };
order.paymentMethod = { uuid: paymentMethod.uuid };
order.interval = null;
order.totalAmount = maxInteger;
delete order.tier;
// Should fail if not enough funds in the fromCollective
let res = await utils.graphqlQuery(createOrderMutation, { order }, xdamman);
expect(res.errors).to.exist;
expect(res.errors[0].message).to.equal(
"You don't have enough funds available ($7,461 left) to execute this order ($21,474,836)",
);
order.totalAmount = 20000;
res = await utils.graphqlQuery(createOrderMutation, { order }, xdamman);
// There should be no errors
res.errors && console.error(res.errors);
expect(res.errors).to.not.exist;
const availableBalance = await paymentMethod.getBalanceForUser(xdamman);
expect(availableBalance.amount).to.equal(726149);
const orderCreated = res.data.createOrder;
const transactions = await models.Transaction.findAll({
where: { OrderId: orderCreated.id },
});
expect(orderCreated.createdByUser.id).to.equal(xdamman.id);
expect(transactions.length).to.equal(2);
expect(transactions[0].type).to.equal('DEBIT');
expect(transactions[0].FromCollectiveId).to.equal(collective.id);
expect(transactions[0].CollectiveId).to.equal(fromCollective.id);
expect(transactions[1].type).to.equal('CREDIT');
expect(transactions[1].FromCollectiveId).to.equal(fromCollective.id);
expect(transactions[1].CollectiveId).to.equal(collective.id);
});
});