Merge pull request #15755 from seamuslee001/copywrite_date_update
[civicrm-core.git] / tests / phpunit / api / v3 / ContributionPageTest.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * Test APIv3 civicrm_contribute_recur* functions
30 *
31 * @package CiviCRM_APIv3
32 * @subpackage API_Contribution
33 * @group headless
34 */
35 class api_v3_ContributionPageTest extends CiviUnitTestCase {
36 protected $testAmount = 34567;
37 protected $params;
38 protected $id = 0;
39 protected $contactIds = [];
40 protected $_entity = 'contribution_page';
41 protected $contribution_result = NULL;
42 protected $_priceSetParams = [];
43 protected $_membershipBlockAmount = 2;
44 /**
45 * Payment processor details.
46 * @var array
47 */
48 protected $_paymentProcessor = [];
49
50 /**
51 * @var array
52 * - contribution_page
53 * - price_set
54 * - price_field
55 * - price_field_value
56 */
57 protected $_ids = [];
58
59
60 public $DBResetRequired = TRUE;
61
62 public function setUp() {
63 parent::setUp();
64 $this->contactIds[] = $this->individualCreate();
65 $this->params = [
66 'title' => "Test Contribution Page",
67 'financial_type_id' => 1,
68 'currency' => 'NZD',
69 'goal_amount' => $this->testAmount,
70 'is_pay_later' => 1,
71 'pay_later_text' => 'Send check',
72 'is_monetary' => TRUE,
73 'is_email_receipt' => TRUE,
74 'receipt_from_email' => 'yourconscience@donate.com',
75 'receipt_from_name' => 'Ego Freud',
76 ];
77
78 $this->_priceSetParams = [
79 'is_quick_config' => 1,
80 'extends' => 'CiviContribute',
81 'financial_type_id' => 'Donation',
82 'title' => 'my Page',
83 ];
84 }
85
86 public function tearDown() {
87 foreach ($this->contactIds as $id) {
88 $this->callAPISuccess('contact', 'delete', ['id' => $id]);
89 }
90 $this->quickCleanUpFinancialEntities();
91 parent::tearDown();
92 }
93
94 /**
95 * @param int $version
96 * @dataProvider versionThreeAndFour
97 */
98 public function testCreateContributionPage($version) {
99 $this->_apiversion = $version;
100 $result = $this->callAPIAndDocument($this->_entity, 'create', $this->params, __FUNCTION__, __FILE__);
101 $this->assertEquals(1, $result['count']);
102 $this->assertNotNull($result['values'][$result['id']]['id']);
103 $this->getAndCheck($this->params, $result['id'], $this->_entity);
104 }
105
106 /**
107 * @param int $version
108 * @dataProvider versionThreeAndFour
109 */
110 public function testGetBasicContributionPage($version) {
111 $this->_apiversion = $version;
112 $createResult = $this->callAPISuccess($this->_entity, 'create', $this->params);
113 $this->id = $createResult['id'];
114 $getParams = [
115 'currency' => 'NZD',
116 'financial_type_id' => 1,
117 ];
118 $getResult = $this->callAPIAndDocument($this->_entity, 'get', $getParams, __FUNCTION__, __FILE__);
119 $this->assertEquals(1, $getResult['count']);
120 }
121
122 public function testGetContributionPageByAmount() {
123 $createResult = $this->callAPISuccess($this->_entity, 'create', $this->params);
124 $this->id = $createResult['id'];
125 $getParams = [
126 // 3456
127 'amount' => '' . $this->testAmount,
128 'currency' => 'NZD',
129 'financial_type_id' => 1,
130 ];
131 $getResult = $this->callAPISuccess($this->_entity, 'get', $getParams);
132 $this->assertEquals(1, $getResult['count']);
133 }
134
135 /**
136 * @param int $version
137 * @dataProvider versionThreeAndFour
138 */
139 public function testDeleteContributionPage($version) {
140 $this->_apiversion = $version;
141 $createResult = $this->callAPISuccess($this->_entity, 'create', $this->params);
142 $deleteParams = ['id' => $createResult['id']];
143 $this->callAPIAndDocument($this->_entity, 'delete', $deleteParams, __FUNCTION__, __FILE__);
144 $checkDeleted = $this->callAPISuccess($this->_entity, 'get', []);
145 $this->assertEquals(0, $checkDeleted['count']);
146 }
147
148 public function testGetFieldsContributionPage() {
149 $result = $this->callAPISuccess($this->_entity, 'getfields', ['action' => 'create']);
150 $this->assertEquals(12, $result['values']['start_date']['type']);
151 }
152
153 /**
154 * Test form submission with basic price set.
155 */
156 public function testSubmit() {
157 $this->setUpContributionPage();
158 $submitParams = $this->getBasicSubmitParams();
159
160 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
161 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['contribution_page_id' => $this->_ids['contribution_page']]);
162 //assert non-deductible amount
163 $this->assertEquals(5.00, $contribution['non_deductible_amount']);
164 }
165
166 /**
167 * Test form submission with basic price set.
168 */
169 public function testSubmitZeroDollar() {
170 $this->setUpContributionPage();
171 $priceFieldID = reset($this->_ids['price_field']);
172 $submitParams = [
173 'price_' . $priceFieldID => $this->_ids['price_field_value']['cheapskate'],
174 'id' => (int) $this->_ids['contribution_page'],
175 'amount' => 0,
176 'priceSetId' => $this->_ids['price_set'][0],
177 'payment_processor_id' => '',
178 ];
179
180 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
181 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['contribution_page_id' => $this->_ids['contribution_page']]);
182
183 $this->assertEquals($this->formatMoneyInput(0), $contribution['non_deductible_amount']);
184 $this->assertEquals($this->formatMoneyInput(0), $contribution['total_amount']);
185 }
186
187 /**
188 * Test form submission with billing first & last name where the contact does NOT
189 * otherwise have one.
190 */
191 public function testSubmitNewBillingNameData() {
192 $this->setUpContributionPage();
193 $contact = $this->callAPISuccess('Contact', 'create', ['contact_type' => 'Individual', 'email' => 'wonderwoman@amazon.com']);
194 $priceFieldID = reset($this->_ids['price_field']);
195 $priceFieldValueID = reset($this->_ids['price_field_value']);
196 $submitParams = [
197 'price_' . $priceFieldID => $priceFieldValueID,
198 'id' => (int) $this->_ids['contribution_page'],
199 'amount' => 10,
200 'billing_first_name' => 'Wonder',
201 'billing_last_name' => 'Woman',
202 'contactID' => $contact['id'],
203 'email' => 'wonderwoman@amazon.com',
204 ];
205
206 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
207 $contact = $this->callAPISuccess('Contact', 'get', [
208 'id' => $contact['id'],
209 'return' => [
210 'first_name',
211 'last_name',
212 'sort_name',
213 'display_name',
214 ],
215 ]);
216 $this->assertEquals([
217 'first_name' => 'Wonder',
218 'last_name' => 'Woman',
219 'display_name' => 'Wonder Woman',
220 'sort_name' => 'Woman, Wonder',
221 'id' => $contact['id'],
222 'contact_id' => $contact['id'],
223 ], $contact['values'][$contact['id']]);
224
225 }
226
227 /**
228 * Test form submission with billing first & last name where the contact does
229 * otherwise have one and should not be overwritten.
230 */
231 public function testSubmitNewBillingNameDoNotOverwrite() {
232 $this->setUpContributionPage();
233 $contact = $this->callAPISuccess('Contact', 'create', [
234 'contact_type' => 'Individual',
235 'email' => 'wonderwoman@amazon.com',
236 'first_name' => 'Super',
237 'last_name' => 'Boy',
238 ]);
239 $priceFieldID = reset($this->_ids['price_field']);
240 $priceFieldValueID = reset($this->_ids['price_field_value']);
241 $submitParams = [
242 'price_' . $priceFieldID => $priceFieldValueID,
243 'id' => (int) $this->_ids['contribution_page'],
244 'amount' => 10,
245 'billing_first_name' => 'Wonder',
246 'billing_last_name' => 'Woman',
247 'contactID' => $contact['id'],
248 'email' => 'wonderwoman@amazon.com',
249 ];
250
251 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
252 $contact = $this->callAPISuccess('Contact', 'get', [
253 'id' => $contact['id'],
254 'return' => [
255 'first_name',
256 'last_name',
257 'sort_name',
258 'display_name',
259 ],
260 ]);
261 $this->assertEquals([
262 'first_name' => 'Super',
263 'last_name' => 'Boy',
264 'display_name' => 'Super Boy',
265 'sort_name' => 'Boy, Super',
266 'id' => $contact['id'],
267 'contact_id' => $contact['id'],
268 ], $contact['values'][$contact['id']]);
269
270 }
271
272 /**
273 * Test process with instant payment when more than one configured for the page.
274 *
275 * CRM-16923
276 */
277 public function testSubmitRecurMultiProcessorInstantPayment() {
278 $this->setUpContributionPage();
279 $this->setupPaymentProcessor();
280 $paymentProcessor2ID = $this->paymentProcessorCreate([
281 'payment_processor_type_id' => 'Dummy',
282 'name' => 'processor 2',
283 'class_name' => 'Payment_Dummy',
284 'billing_mode' => 1,
285 ]);
286 $dummyPP = Civi\Payment\System::singleton()->getById($paymentProcessor2ID);
287 $dummyPP->setDoDirectPaymentResult([
288 'payment_status_id' => 1,
289 'trxn_id' => 'create_first_success',
290 'fee_amount' => .85,
291 ]);
292 $processor = $dummyPP->getPaymentProcessor();
293 $this->callAPISuccess('ContributionPage', 'create', [
294 'id' => $this->_ids['contribution_page'],
295 'payment_processor' => [$paymentProcessor2ID, $this->_ids['payment_processor']],
296 ]);
297
298 $priceFieldID = reset($this->_ids['price_field']);
299 $priceFieldValueID = reset($this->_ids['price_field_value']);
300 $submitParams = [
301 'price_' . $priceFieldID => $priceFieldValueID,
302 'id' => (int) $this->_ids['contribution_page'],
303 'amount' => 10,
304 'is_recur' => 1,
305 'frequency_interval' => 1,
306 'frequency_unit' => 'month',
307 'payment_processor_id' => $paymentProcessor2ID,
308 ];
309
310 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
311 $contribution = $this->callAPISuccess('contribution', 'getsingle', [
312 'contribution_page_id' => $this->_ids['contribution_page'],
313 'contribution_status_id' => 1,
314 ]);
315 $this->assertEquals('create_first_success', $contribution['trxn_id']);
316 $this->assertEquals(10, $contribution['total_amount']);
317 $this->assertEquals(.85, $contribution['fee_amount']);
318 $this->assertEquals(9.15, $contribution['net_amount']);
319 $this->_checkFinancialRecords([
320 'id' => $contribution['id'],
321 'total_amount' => $contribution['total_amount'],
322 'payment_instrument_id' => $processor['payment_instrument_id'],
323 ], 'online');
324 }
325
326 /**
327 * Test submit with a membership block in place.
328 */
329 public function testSubmitMembershipBlockNotSeparatePayment() {
330 $this->setUpMembershipContributionPage();
331 $submitParams = [
332 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
333 'id' => (int) $this->_ids['contribution_page'],
334 'amount' => 10,
335 'billing_first_name' => 'Billy',
336 'billing_middle_name' => 'Goat',
337 'billing_last_name' => 'Gruff',
338 'selectMembership' => $this->_ids['membership_type'],
339
340 ];
341
342 $this->callAPIAndDocument('contribution_page', 'submit', $submitParams, __FUNCTION__, __FILE__, 'submit contribution page', NULL);
343 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['contribution_page_id' => $this->_ids['contribution_page']]);
344 $membershipPayment = $this->callAPISuccess('membership_payment', 'getsingle', ['contribution_id' => $contribution['id']]);
345 $this->callAPISuccessGetSingle('LineItem', ['contribution_id' => $contribution['id'], 'entity_id' => $membershipPayment['id']]);
346 }
347
348 /**
349 * Test submit with a membership block in place works with renewal.
350 *
351 * @throws \CRM_Core_Exception
352 */
353 public function testSubmitMembershipBlockNotSeparatePaymentProcessorInstantRenew() {
354 $this->setUpMembershipContributionPage();
355 $dummyPP = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
356 $dummyPP->setDoDirectPaymentResult(['payment_status_id' => 1]);
357 $submitParams = [
358 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
359 'id' => (int) $this->_ids['contribution_page'],
360 'amount' => 10,
361 'billing_first_name' => 'Billy',
362 'billing_middle_name' => 'Goat',
363 'billing_last_name' => 'Gruff',
364 'selectMembership' => $this->_ids['membership_type'],
365 'payment_processor_id' => 1,
366 'credit_card_number' => '4111111111111111',
367 'credit_card_type' => 'Visa',
368 'credit_card_exp_date' => ['M' => 9, 'Y' => 2040],
369 'cvv2' => 123,
370 ];
371
372 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
373 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['contribution_page_id' => $this->_ids['contribution_page']]);
374 $membershipPayment = $this->callAPISuccess('membership_payment', 'getsingle', ['contribution_id' => $contribution['id']]);
375 $this->callAPISuccessGetCount('LineItem', [
376 'entity_table' => 'civicrm_membership',
377 'entity_id' => $membershipPayment['id'],
378 ], 1);
379
380 $submitParams['contact_id'] = $contribution['contact_id'];
381
382 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
383 $this->callAPISuccessGetCount('LineItem', [
384 'entity_table' => 'civicrm_membership',
385 'entity_id' => $membershipPayment['id'],
386 ], 2);
387 $membership = $this->callAPISuccessGetSingle('Membership', [
388 'id' => $membershipPayment['membership_id'],
389 'return' => ['end_date', 'join_date', 'start_date'],
390 ]);
391 $this->assertEquals(date('Y-m-d'), $membership['start_date']);
392 $this->assertEquals(date('Y-m-d'), $membership['join_date']);
393 $this->assertEquals(date('Y-m-d', strtotime('+ 2 year - 1 day')), $membership['end_date']);
394 }
395
396 /**
397 * Test submit with a membership block in place.
398 */
399 public function testSubmitMembershipBlockNotSeparatePaymentWithEmail() {
400 $mut = new CiviMailUtils($this, TRUE);
401 $this->setUpMembershipContributionPage();
402 $this->addProfile('supporter_profile', $this->_ids['contribution_page']);
403
404 $submitParams = [
405 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
406 'id' => (int) $this->_ids['contribution_page'],
407 'amount' => 10,
408 'billing_first_name' => 'Billy',
409 'billing_middle_name' => 'Goat',
410 'billing_last_name' => 'Gruff',
411 'selectMembership' => $this->_ids['membership_type'],
412 'email-Primary' => 'billy-goat@the-bridge.net',
413 'payment_processor_id' => $this->_paymentProcessor['id'],
414 'credit_card_number' => '4111111111111111',
415 'credit_card_type' => 'Visa',
416 'credit_card_exp_date' => ['M' => 9, 'Y' => 2040],
417 'cvv2' => 123,
418 ];
419
420 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
421 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['contribution_page_id' => $this->_ids['contribution_page']]);
422 $this->callAPISuccess('membership_payment', 'getsingle', ['contribution_id' => $contribution['id']]);
423 $mut->checkMailLog([
424 'Membership Type: General',
425 'Test Frontend title',
426 ]);
427 $mut->stop();
428 $mut->clearMessages();
429 }
430
431 /**
432 * Test submit with a membership block in place.
433 */
434 public function testSubmitMembershipBlockNotSeparatePaymentZeroDollarsWithEmail() {
435 $mut = new CiviMailUtils($this, TRUE);
436 $this->_ids['membership_type'] = [$this->membershipTypeCreate(['minimum_fee' => 0])];
437 $this->setUpMembershipContributionPage();
438 $this->addProfile('supporter_profile', $this->_ids['contribution_page']);
439
440 $submitParams = [
441 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
442 'id' => (int) $this->_ids['contribution_page'],
443 'amount' => 0,
444 'billing_first_name' => 'Billy',
445 'billing_middle_name' => 'Goat',
446 'billing_last_name' => 'Gruffier',
447 'selectMembership' => $this->_ids['membership_type'],
448 'email-Primary' => 'billy-goat@the-new-bridge.net',
449 'payment_processor_id' => $this->params['payment_processor_id'],
450 ];
451
452 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
453 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['contribution_page_id' => $this->_ids['contribution_page']]);
454 $this->callAPISuccess('membership_payment', 'getsingle', ['contribution_id' => $contribution['id']]);
455 //Assert only one mail is being sent.
456 $msgs = $mut->getAllMessages();
457 $this->assertCount(1, $msgs);
458
459 $mut->checkMailLog([
460 'Membership Type: General',
461 'Gruffier',
462 ], [
463 'Amount',
464 ]);
465 $mut->stop();
466 $mut->clearMessages();
467 }
468
469 /**
470 * Test submit with a pay later abnd check line item in mails.
471 */
472 public function testSubmitMembershipBlockIsSeparatePaymentPayLaterWithEmail() {
473 $mut = new CiviMailUtils($this, TRUE);
474 $this->setUpMembershipContributionPage();
475 $submitParams = [
476 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
477 'id' => (int) $this->_ids['contribution_page'],
478 'amount' => 10,
479 'billing_first_name' => 'Billy',
480 'billing_middle_name' => 'Goat',
481 'billing_last_name' => 'Gruff',
482 'is_pay_later' => 1,
483 'selectMembership' => $this->_ids['membership_type'],
484 'email-Primary' => 'billy-goat@the-bridge.net',
485 ];
486
487 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
488 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['contribution_page_id' => $this->_ids['contribution_page']]);
489 $this->callAPISuccess('membership_payment', 'getsingle', ['contribution_id' => $contribution['id']]);
490 $mut->checkMailLog([
491 'Membership Amount -... $ 2.00',
492 ]);
493 $mut->stop();
494 $mut->clearMessages();
495 }
496
497 /**
498 * Test submit with a membership block in place.
499 */
500 public function testSubmitMembershipBlockIsSeparatePayment() {
501 $this->setUpMembershipContributionPage(TRUE);
502 $this->_ids['membership_type'] = [$this->membershipTypeCreate(['minimum_fee' => 2])];
503 $submitParams = [
504 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
505 'id' => (int) $this->_ids['contribution_page'],
506 'amount' => 10,
507 'billing_first_name' => 'Billy',
508 'billing_middle_name' => 'Goat',
509 'billing_last_name' => 'Gruff',
510 'selectMembership' => $this->_ids['membership_type'],
511 ];
512
513 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
514 $contributions = $this->callAPISuccess('contribution', 'get', ['contribution_page_id' => $this->_ids['contribution_page']]);
515 $this->assertCount(2, $contributions['values']);
516 $lines = $this->callAPISuccess('LineItem', 'get', ['sequential' => 1]);
517 $this->assertEquals(10, $lines['values'][0]['line_total']);
518 $membershipPayment = $this->callAPISuccess('membership_payment', 'getsingle', []);
519 $this->assertTrue(in_array($membershipPayment['contribution_id'], array_keys($contributions['values'])));
520 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $membershipPayment['membership_id']]);
521 $this->assertEquals($membership['contact_id'], $contributions['values'][$membershipPayment['contribution_id']]['contact_id']);
522 }
523
524 /**
525 * Test submit with a membership block in place.
526 */
527 public function testSubmitMembershipBlockIsSeparatePaymentWithPayLater() {
528 $this->setUpMembershipContributionPage(TRUE);
529 $this->_ids['membership_type'] = [$this->membershipTypeCreate(['minimum_fee' => 2])];
530 //Pay later
531 $submitParams = [
532 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
533 'id' => (int) $this->_ids['contribution_page'],
534 'amount' => 0,
535 'billing_first_name' => 'Billy',
536 'billing_middle_name' => 'Goat',
537 'billing_last_name' => 'Gruff',
538 'is_pay_later' => 1,
539 'selectMembership' => $this->_ids['membership_type'],
540 ];
541
542 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
543 $contributions = $this->callAPISuccess('contribution', 'get', ['contribution_page_id' => $this->_ids['contribution_page']]);
544 $this->assertCount(2, $contributions['values']);
545 foreach ($contributions['values'] as $val) {
546 $this->assertEquals(CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'), $val['contribution_status_id']);
547 }
548
549 //Membership should be in Pending state.
550 $membershipPayment = $this->callAPISuccess('membership_payment', 'getsingle', []);
551 $this->assertTrue(in_array($membershipPayment['contribution_id'], array_keys($contributions['values'])));
552 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $membershipPayment['membership_id']]);
553 $pendingStatus = $this->callAPISuccessGetSingle('MembershipStatus', [
554 'return' => ["id"],
555 'name' => "Pending",
556 ]);
557 $this->assertEquals($membership['status_id'], $pendingStatus['id']);
558 $this->assertEquals($membership['contact_id'], $contributions['values'][$membershipPayment['contribution_id']]['contact_id']);
559 }
560
561 /**
562 * Test submit with a membership block in place.
563 */
564 public function testSubmitMembershipBlockIsSeparatePaymentWithEmail() {
565 $mut = new CiviMailUtils($this, TRUE);
566 $this->setUpMembershipContributionPage(TRUE);
567 $this->addProfile('supporter_profile', $this->_ids['contribution_page']);
568
569 $submitParams = [
570 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
571 'id' => (int) $this->_ids['contribution_page'],
572 'amount' => 10,
573 'billing_first_name' => 'Billy',
574 'billing_middle_name' => 'Goat',
575 'billing_last_name' => 'Gruff',
576 'selectMembership' => $this->_ids['membership_type'],
577 'email-Primary' => 'billy-goat@the-bridge.net',
578 'payment_processor_id' => $this->_paymentProcessor['id'],
579 'credit_card_number' => '4111111111111111',
580 'credit_card_type' => 'Visa',
581 'credit_card_exp_date' => ['M' => 9, 'Y' => 2040],
582 'cvv2' => 123,
583 ];
584
585 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
586 $contributions = $this->callAPISuccess('contribution', 'get', ['contribution_page_id' => $this->_ids['contribution_page']]);
587 $this->assertCount(2, $contributions['values']);
588 $membershipPayment = $this->callAPISuccess('membership_payment', 'getsingle', []);
589 $this->assertTrue(in_array($membershipPayment['contribution_id'], array_keys($contributions['values'])));
590 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $membershipPayment['membership_id']]);
591 $this->assertEquals($membership['contact_id'], $contributions['values'][$membershipPayment['contribution_id']]['contact_id']);
592 // We should have two separate email messages, each with their own amount
593 // line and no total line.
594 $mut->checkAllMailLog(
595 [
596 'Amount: $ 2.00',
597 'Amount: $ 10.00',
598 'Membership Fee',
599 ],
600 [
601 'Total: $',
602 ]
603 );
604 $mut->stop();
605 $mut->clearMessages();
606 }
607
608 /**
609 * Test submit with a membership block in place.
610 */
611 public function testSubmitMembershipBlockIsSeparatePaymentZeroDollarsPayLaterWithEmail() {
612 $mut = new CiviMailUtils($this, TRUE);
613 $this->_ids['membership_type'] = [$this->membershipTypeCreate(['minimum_fee' => 0])];
614 $this->setUpMembershipContributionPage(TRUE);
615 $this->addProfile('supporter_profile', $this->_ids['contribution_page']);
616
617 $submitParams = [
618 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
619 'id' => (int) $this->_ids['contribution_page'],
620 'amount' => 0,
621 'billing_first_name' => 'Billy',
622 'billing_middle_name' => 'Goat',
623 'billing_last_name' => 'Gruffalo',
624 'selectMembership' => $this->_ids['membership_type'],
625 'payment_processor_id' => 0,
626 'email-Primary' => 'gruffalo@the-bridge.net',
627 ];
628
629 $this->callAPIAndDocument('contribution_page', 'submit', $submitParams, __FUNCTION__, __FILE__, 'submit contribution page', NULL);
630 $contributions = $this->callAPISuccess('contribution', 'get', ['contribution_page_id' => $this->_ids['contribution_page']]);
631 $this->assertCount(2, $contributions['values']);
632 $membershipPayment = $this->callAPISuccess('membership_payment', 'getsingle', []);
633 $this->assertTrue(in_array($membershipPayment['contribution_id'], array_keys($contributions['values'])));
634 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $membershipPayment['membership_id']]);
635 $this->assertEquals($membership['contact_id'], $contributions['values'][$membershipPayment['contribution_id']]['contact_id']);
636 $mut->checkMailLog([
637 'Gruffalo',
638 'General Membership: $ 0.00',
639 'Membership Fee',
640 ]);
641 $mut->stop();
642 $mut->clearMessages();
643 }
644
645 /**
646 * Test submit with a membership block in place.
647 */
648 public function testSubmitMembershipBlockTwoTypesIsSeparatePayment() {
649 $this->_ids['membership_type'] = [$this->membershipTypeCreate(['minimum_fee' => 6])];
650 $this->_ids['membership_type'][] = $this->membershipTypeCreate(['name' => 'Student', 'minimum_fee' => 50]);
651 $this->setUpMembershipContributionPage(TRUE);
652 $submitParams = [
653 'price_' . $this->_ids['price_field'][0] => $this->_ids['price_field_value'][1],
654 'id' => (int) $this->_ids['contribution_page'],
655 'amount' => 10,
656 'billing_first_name' => 'Billy',
657 'billing_middle_name' => 'Goat',
658 'billing_last_name' => 'Gruff',
659 'selectMembership' => $this->_ids['membership_type'][1],
660 ];
661
662 $this->callAPIAndDocument('contribution_page', 'submit', $submitParams, __FUNCTION__, __FILE__, 'submit contribution page', NULL);
663 $contributions = $this->callAPISuccess('contribution', 'get', ['contribution_page_id' => $this->_ids['contribution_page']]);
664 $this->assertCount(2, $contributions['values']);
665 $ids = array_keys($contributions['values']);
666 $this->assertEquals('10.00', $contributions['values'][$ids[0]]['total_amount']);
667 $this->assertEquals('50.00', $contributions['values'][$ids[1]]['total_amount']);
668 $membershipPayment = $this->callAPISuccess('membership_payment', 'getsingle', []);
669 $this->assertArrayHasKey($membershipPayment['contribution_id'], $contributions['values']);
670 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $membershipPayment['membership_id']]);
671 $this->assertEquals($membership['contact_id'], $contributions['values'][$membershipPayment['contribution_id']]['contact_id']);
672 }
673
674 /**
675 * Test submit with a membership block in place.
676 *
677 * We are expecting a separate payment for the membership vs the contribution.
678 *
679 * @throws \CRM_Core_Exception
680 * @throws \CiviCRM_API3_Exception
681 */
682 public function testSubmitMembershipBlockIsSeparatePaymentPaymentProcessorNow() {
683 $mut = new CiviMailUtils($this, TRUE);
684 $this->setUpMembershipContributionPage(TRUE);
685 $processor = Civi\Payment\System::singleton()->getById($this->_paymentProcessor['id']);
686 $processor->setDoDirectPaymentResult(['fee_amount' => .72]);
687 $submitParams = [
688 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
689 'id' => (int) $this->_ids['contribution_page'],
690 'amount' => 10,
691 'billing_first_name' => 'Billy',
692 'billing_middle_name' => 'Goat',
693 'billing_last_name' => 'Gruff',
694 'email-Primary' => 'henry@8th.king',
695 'selectMembership' => $this->_ids['membership_type'],
696 'payment_processor_id' => $this->_paymentProcessor['id'],
697 'credit_card_number' => '4111111111111111',
698 'credit_card_type' => 'Visa',
699 'credit_card_exp_date' => ['M' => 9, 'Y' => 2040],
700 'cvv2' => 123,
701 ];
702
703 $this->callAPIAndDocument('contribution_page', 'submit', $submitParams, __FUNCTION__, __FILE__, 'submit contribution page', NULL);
704 $contributions = $this->callAPISuccess('contribution', 'get', [
705 'contribution_page_id' => $this->_ids['contribution_page'],
706 'contribution_status_id' => 1,
707 ]);
708 $this->assertCount(2, $contributions['values']);
709 $membershipPayment = $this->callAPISuccess('membership_payment', 'getsingle', []);
710 $this->assertTrue(in_array($membershipPayment['contribution_id'], array_keys($contributions['values'])));
711 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $membershipPayment['membership_id']]);
712 $this->assertEquals($membership['contact_id'], $contributions['values'][$membershipPayment['contribution_id']]['contact_id']);
713 $lineItem = $this->callAPISuccessGetSingle('LineItem', ['entity_table' => 'civicrm_membership']);
714 $this->assertEquals($lineItem['entity_id'], $membership['id']);
715 $this->assertEquals($lineItem['contribution_id'], $membershipPayment['contribution_id']);
716 $this->assertEquals($lineItem['qty'], 1);
717 $this->assertEquals($lineItem['unit_price'], 2);
718 $this->assertEquals($lineItem['line_total'], 2);
719 foreach ($contributions['values'] as $contribution) {
720 $this->assertEquals(.72, $contribution['fee_amount']);
721 $this->assertEquals($contribution['total_amount'] - .72, $contribution['net_amount']);
722 }
723 // The total string is currently absent & it seems worse with - although at some point
724 // it may have been intended
725 $mut->checkAllMailLog(['$ 2.00', 'Contribution Amount', '$ 10.00'], ['Total:']);
726 $mut->stop();
727 $mut->clearMessages();
728 }
729
730 /**
731 * Test submit with a membership block in place.
732 *
733 * Ensure a separate payment for the membership vs the contribution, with
734 * correct amounts.
735 *
736 * @param string $thousandSeparator
737 * punctuation used to refer to thousands.
738 *
739 * @dataProvider getThousandSeparators
740 */
741 public function testSubmitMembershipBlockIsSeparatePaymentPaymentProcessorNowChargesCorrectAmounts($thousandSeparator) {
742 $this->setCurrencySeparators($thousandSeparator);
743 $this->setUpMembershipContributionPage(TRUE);
744 $processor = Civi\Payment\System::singleton()->getById($this->_paymentProcessor['id']);
745 $processor->setDoDirectPaymentResult(['fee_amount' => .72]);
746 $test_uniq = uniqid();
747 $contributionPageAmount = 10;
748 $submitParams = [
749 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
750 'id' => (int) $this->_ids['contribution_page'],
751 'amount' => $contributionPageAmount,
752 'billing_first_name' => 'Billy',
753 'billing_middle_name' => 'Goat',
754 'billing_last_name' => 'Gruff',
755 'email-Primary' => 'henry@8th.king',
756 'selectMembership' => $this->_ids['membership_type'],
757 'payment_processor_id' => $this->_paymentProcessor['id'],
758 'credit_card_number' => '4111111111111111',
759 'credit_card_type' => 'Visa',
760 'credit_card_exp_date' => ['M' => 9, 'Y' => 2040],
761 'cvv2' => 123,
762 'TEST_UNIQ' => $test_uniq,
763 ];
764
765 // set custom hook
766 $this->hookClass->setHook('civicrm_alterPaymentProcessorParams', [$this, 'hook_civicrm_alterPaymentProcessorParams']);
767
768 $this->callAPISuccess('contribution_page', 'submit', $submitParams, __FUNCTION__, __FILE__, 'submit contribution page', NULL);
769 $contributions = $this->callAPISuccess('contribution', 'get', [
770 'contribution_page_id' => $this->_ids['contribution_page'],
771 'contribution_status_id' => 1,
772 ]);
773
774 $result = civicrm_api3('SystemLog', 'get', [
775 'sequential' => 1,
776 'message' => ['LIKE' => "%{$test_uniq}%"],
777 ]);
778 $this->assertCount(2, $result['values'], "Expected exactly 2 log entries matching {$test_uniq}.");
779
780 // Examine logged entries to ensure correct values.
781 $contribution_ids = [];
782 $found_membership_amount = $found_contribution_amount = FALSE;
783 foreach ($result['values'] as $value) {
784 list($junk, $json) = explode("$test_uniq:", $value['message']);
785 $logged_contribution = json_decode($json, TRUE);
786 $contribution_ids[] = $logged_contribution['contributionID'];
787 if (!empty($logged_contribution['total_amount'])) {
788 $amount = $logged_contribution['total_amount'];
789 }
790 else {
791 $amount = $logged_contribution['amount'];
792 }
793
794 if ($amount == $this->_membershipBlockAmount) {
795 $found_membership_amount = TRUE;
796 }
797 if ($amount == $contributionPageAmount) {
798 $found_contribution_amount = TRUE;
799 }
800 }
801
802 $distinct_contribution_ids = array_unique($contribution_ids);
803 $this->assertCount(2, $distinct_contribution_ids, "Expected exactly 2 log contributions with distinct contributionIDs.");
804 $this->assertTrue($found_contribution_amount, "Expected one log contribution with amount '$contributionPageAmount' (the contribution page amount)");
805 $this->assertTrue($found_membership_amount, "Expected one log contribution with amount '$this->_membershipBlockAmount' (the membership amount)");
806 }
807
808 /**
809 * Test that when a transaction fails the pending contribution remains.
810 *
811 * An activity should also be created. CRM-16417.
812 */
813 public function testSubmitPaymentProcessorFailure() {
814 $this->setUpContributionPage();
815 $this->setupPaymentProcessor();
816 $this->createLoggedInUser();
817 $priceFieldID = reset($this->_ids['price_field']);
818 $priceFieldValueID = reset($this->_ids['price_field_value']);
819 $submitParams = [
820 'price_' . $priceFieldID => $priceFieldValueID,
821 'id' => (int) $this->_ids['contribution_page'],
822 'amount' => 10,
823 'payment_processor_id' => 1,
824 'credit_card_number' => '4111111111111111',
825 'credit_card_type' => 'Visa',
826 'credit_card_exp_date' => ['M' => 9, 'Y' => 2008],
827 'cvv2' => 123,
828 ];
829
830 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
831 $contribution = $this->callAPISuccessGetSingle('contribution', [
832 'contribution_page_id' => $this->_ids['contribution_page'],
833 'contribution_status_id' => 'Failed',
834 ]);
835
836 $this->callAPISuccessGetSingle('activity', [
837 'source_record_id' => $contribution['id'],
838 'activity_type_id' => 'Failed Payment',
839 ]);
840
841 }
842
843 /**
844 * Test submit recurring (yearly) membership with immediate confirmation (IATS style).
845 *
846 * - we process 2 membership transactions against with a recurring contribution against a contribution page with an immediate
847 * processor (IATS style - denoted by returning trxn_id)
848 * - the first creates a new membership, completed contribution, in progress recurring. Check these
849 * - create another - end date should be extended
850 */
851 public function testSubmitMembershipPriceSetPaymentPaymentProcessorRecurInstantPaymentYear() {
852 $this->doSubmitMembershipPriceSetPaymentPaymentProcessorRecurInstantPayment(['duration_unit' => 'year', 'recur_frequency_unit' => 'year']);
853 }
854
855 /**
856 * Test submit recurring (monthly) membership with immediate confirmation (IATS style).
857 *
858 * - we process 2 membership transactions against with a recurring contribution against a contribution page with an immediate
859 * processor (IATS style - denoted by returning trxn_id)
860 * - the first creates a new membership, completed contribution, in progress recurring. Check these
861 * - create another - end date should be extended
862 */
863 public function testSubmitMembershipPriceSetPaymentPaymentProcessorRecurInstantPaymentMonth() {
864 $this->doSubmitMembershipPriceSetPaymentPaymentProcessorRecurInstantPayment(['duration_unit' => 'month', 'recur_frequency_unit' => 'month']);
865 }
866
867 /**
868 * Test submit recurring (mismatched frequency unit) membership with immediate confirmation (IATS style).
869 *
870 * - we process 2 membership transactions against with a recurring contribution against a contribution page with an immediate
871 * processor (IATS style - denoted by returning trxn_id)
872 * - the first creates a new membership, completed contribution, in progress recurring. Check these
873 * - create another - end date should be extended
874 */
875 //public function testSubmitMembershipPriceSetPaymentPaymentProcessorRecurInstantPaymentDifferentFrequency() {
876 // $this->doSubmitMembershipPriceSetPaymentPaymentProcessorRecurInstantPayment(array('duration_unit' => 'year', 'recur_frequency_unit' => 'month'));
877 //}
878
879 /**
880 * Helper function for testSubmitMembershipPriceSetPaymentProcessorRecurInstantPayment*
881 * @param array $params
882 *
883 * @throws \CRM_Core_Exception
884 * @throws \Exception
885 */
886 public function doSubmitMembershipPriceSetPaymentPaymentProcessorRecurInstantPayment($params = []) {
887 $this->params['is_recur'] = 1;
888 $this->params['recur_frequency_unit'] = $params['recur_frequency_unit'];
889 $membershipTypeParams['duration_unit'] = $params['duration_unit'];
890 if ($params['recur_frequency_unit'] === $params['duration_unit']) {
891 $durationUnit = $params['duration_unit'];
892 }
893 else {
894 $durationUnit = NULL;
895 }
896 $this->setUpMembershipContributionPage(FALSE, FALSE, $membershipTypeParams);
897 $dummyPP = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
898 $dummyPP->setDoDirectPaymentResult(['payment_status_id' => 1, 'trxn_id' => 'create_first_success']);
899 $processor = $dummyPP->getPaymentProcessor();
900
901 if ($params['recur_frequency_unit'] === $params['duration_unit']) {
902 // Membership will be in "New" state because it will get confirmed as payment matches
903 $expectedMembershipStatus = 1;
904 }
905 else {
906 // Membership will still be in "Pending" state as it won't get confirmed as payment doesn't match
907 $expectedMembershipStatus = 5;
908 }
909
910 $submitParams = [
911 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
912 'id' => (int) $this->_ids['contribution_page'],
913 'amount' => 10,
914 'billing_first_name' => 'Billy',
915 'billing_middle_name' => 'Goat',
916 'billing_last_name' => 'Gruff',
917 'email' => 'billy@goat.gruff',
918 'selectMembership' => $this->_ids['membership_type'],
919 'payment_processor_id' => 1,
920 'credit_card_number' => '4111111111111111',
921 'credit_card_type' => 'Visa',
922 'credit_card_exp_date' => ['M' => 9, 'Y' => 2040],
923 'cvv2' => 123,
924 'is_recur' => 1,
925 'frequency_interval' => 1,
926 'frequency_unit' => $this->params['recur_frequency_unit'],
927 ];
928
929 $this->callAPIAndDocument('contribution_page', 'submit', $submitParams, __FUNCTION__, __FILE__, 'submit contribution page', NULL);
930 $contribution = $this->callAPISuccess('contribution', 'getsingle', [
931 'contribution_page_id' => $this->_ids['contribution_page'],
932 'contribution_status_id' => 1,
933 ]);
934 $this->assertEquals($processor['payment_instrument_id'], $contribution['payment_instrument_id']);
935
936 $this->assertEquals('create_first_success', $contribution['trxn_id']);
937 $membershipPayment = $this->callAPISuccess('membership_payment', 'getsingle', []);
938 $this->assertEquals($membershipPayment['contribution_id'], $contribution['id']);
939 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $membershipPayment['membership_id']]);
940 $this->assertEquals($membership['contact_id'], $contribution['contact_id']);
941 $this->assertEquals($expectedMembershipStatus, $membership['status_id']);
942 $this->callAPISuccess('contribution_recur', 'getsingle', ['id' => $contribution['contribution_recur_id']]);
943 $this->assertEquals($contribution['contribution_recur_id'], $membership['contribution_recur_id']);
944
945 $this->callAPISuccess('line_item', 'getsingle', ['contribution_id' => $contribution['id'], 'entity_id' => $membership['id']]);
946 //renew it with processor setting completed - should extend membership
947 $submitParams['contact_id'] = $contribution['contact_id'];
948 $dummyPP->setDoDirectPaymentResult(['payment_status_id' => 1, 'trxn_id' => 'create_second_success']);
949 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
950 $this->callAPISuccess('contribution', 'getsingle', [
951 'id' => ['NOT IN' => [$contribution['id']]],
952 'contribution_page_id' => $this->_ids['contribution_page'],
953 'contribution_status_id' => 1,
954 ]);
955 $renewedMembership = $this->callAPISuccessGetSingle('membership', ['id' => $membershipPayment['membership_id']]);
956 if ($durationUnit) {
957 // We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
958 $renewedMembershipEndDate = $this->membershipRenewalDate($durationUnit, $membership['end_date']);
959 $this->assertEquals($renewedMembershipEndDate, $renewedMembership['end_date']);
960 }
961 $recurringContribution = $this->callAPISuccess('contribution_recur', 'getsingle', ['id' => $contribution['contribution_recur_id']]);
962 $this->assertEquals($processor['payment_instrument_id'], $recurringContribution['payment_instrument_id']);
963 $this->assertEquals(5, $recurringContribution['contribution_status_id']);
964 }
965
966 /**
967 * Test submit recurring membership with immediate confirmation (IATS style).
968 *
969 * - we process 2 membership transactions against with a recurring contribution against a contribution page with an immediate
970 * processor (IATS style - denoted by returning trxn_id)
971 * - the first creates a new membership, completed contribution, in progress recurring. Check these
972 * - create another - end date should be extended
973 */
974 public function testSubmitMembershipComplexNonPriceSetPaymentPaymentProcessorRecurInstantPayment() {
975 $this->params['is_recur'] = 1;
976 $this->params['recur_frequency_unit'] = $membershipTypeParams['duration_unit'] = 'year';
977 // Add a membership so membership & contribution are not both 1.
978 $preExistingMembershipID = $this->contactMembershipCreate(['contact_id' => $this->contactIds[0]]);
979 $this->setUpMembershipContributionPage(FALSE, FALSE, $membershipTypeParams);
980 $dummyPP = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
981 $dummyPP->setDoDirectPaymentResult(['payment_status_id' => 1, 'trxn_id' => 'create_first_success']);
982 $processor = $dummyPP->getPaymentProcessor();
983
984 $submitParams = [
985 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
986 'price_' . $this->_ids['price_field']['cont'] => 88,
987 'id' => (int) $this->_ids['contribution_page'],
988 'amount' => 10,
989 'billing_first_name' => 'Billy',
990 'billing_middle_name' => 'Goat',
991 'billing_last_name' => 'Gruff',
992 'email' => 'billy@goat.gruff',
993 'selectMembership' => $this->_ids['membership_type'],
994 'payment_processor_id' => 1,
995 'credit_card_number' => '4111111111111111',
996 'credit_card_type' => 'Visa',
997 'credit_card_exp_date' => ['M' => 9, 'Y' => 2040],
998 'cvv2' => 123,
999 'is_recur' => 1,
1000 'frequency_interval' => 1,
1001 'frequency_unit' => $this->params['recur_frequency_unit'],
1002 ];
1003
1004 $this->callAPIAndDocument('contribution_page', 'submit', $submitParams, __FUNCTION__, __FILE__, 'submit contribution page', NULL);
1005 $contribution = $this->callAPISuccess('contribution', 'getsingle', [
1006 'contribution_page_id' => $this->_ids['contribution_page'],
1007 'contribution_status_id' => 1,
1008 ]);
1009 $this->assertEquals($processor['payment_instrument_id'], $contribution['payment_instrument_id']);
1010
1011 $this->assertEquals('create_first_success', $contribution['trxn_id']);
1012 $membershipPayment = $this->callAPISuccess('membership_payment', 'getsingle', []);
1013 $this->assertEquals($membershipPayment['contribution_id'], $contribution['id']);
1014 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $membershipPayment['membership_id']]);
1015 $this->assertEquals($membership['contact_id'], $contribution['contact_id']);
1016 $this->assertEquals(1, $membership['status_id']);
1017 $this->callAPISuccess('contribution_recur', 'getsingle', ['id' => $contribution['contribution_recur_id']]);
1018
1019 $lines = $this->callAPISuccess('line_item', 'get', ['sequential' => 1, 'contribution_id' => $contribution['id']]);
1020 $this->assertEquals(2, $lines['count']);
1021 $this->assertEquals('civicrm_membership', $lines['values'][0]['entity_table']);
1022 $this->assertEquals($preExistingMembershipID + 1, $lines['values'][0]['entity_id']);
1023 $this->assertEquals('civicrm_contribution', $lines['values'][1]['entity_table']);
1024 $this->assertEquals($contribution['id'], $lines['values'][1]['entity_id']);
1025 $this->callAPISuccessGetSingle('MembershipPayment', ['contribution_id' => $contribution['id'], 'membership_id' => $preExistingMembershipID + 1]);
1026
1027 //renew it with processor setting completed - should extend membership
1028 $submitParams['contact_id'] = $contribution['contact_id'];
1029 $dummyPP->setDoDirectPaymentResult(['payment_status_id' => 1, 'trxn_id' => 'create_second_success']);
1030 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
1031 $renewContribution = $this->callAPISuccess('contribution', 'getsingle', [
1032 'id' => ['NOT IN' => [$contribution['id']]],
1033 'contribution_page_id' => $this->_ids['contribution_page'],
1034 'contribution_status_id' => 1,
1035 ]);
1036 $lines = $this->callAPISuccess('line_item', 'get', ['sequential' => 1, 'contribution_id' => $renewContribution['id']]);
1037 $this->assertEquals(2, $lines['count']);
1038 $this->assertEquals('civicrm_membership', $lines['values'][0]['entity_table']);
1039 $this->assertEquals($preExistingMembershipID + 1, $lines['values'][0]['entity_id']);
1040 $this->assertEquals('civicrm_contribution', $lines['values'][1]['entity_table']);
1041 $this->assertEquals($renewContribution['id'], $lines['values'][1]['entity_id']);
1042
1043 $renewedMembership = $this->callAPISuccessGetSingle('membership', ['id' => $membershipPayment['membership_id']]);
1044 $this->assertEquals(date('Y-m-d', strtotime('+ 1 ' . $this->params['recur_frequency_unit'], strtotime($membership['end_date']))), $renewedMembership['end_date']);
1045 $recurringContribution = $this->callAPISuccess('contribution_recur', 'getsingle', ['id' => $contribution['contribution_recur_id']]);
1046 $this->assertEquals($processor['payment_instrument_id'], $recurringContribution['payment_instrument_id']);
1047 $this->assertEquals(5, $recurringContribution['contribution_status_id']);
1048 }
1049
1050 /**
1051 * Test submit recurring membership with immediate confirmation (IATS style).
1052 *
1053 * - we process 2 membership transactions against with a recurring contribution against a contribution page with an immediate
1054 * processor (IATS style - denoted by returning trxn_id)
1055 * - the first creates a new membership, completed contribution, in progress recurring. Check these
1056 * - create another - end date should be extended
1057 */
1058 public function testSubmitMembershipComplexPriceSetPaymentPaymentProcessorRecurInstantPayment() {
1059 $this->params['is_recur'] = 1;
1060 $this->params['recur_frequency_unit'] = $membershipTypeParams['duration_unit'] = 'year';
1061 // Add a membership so membership & contribution are not both 1.
1062 $preExistingMembershipID = $this->contactMembershipCreate(['contact_id' => $this->contactIds[0]]);
1063 $this->createPriceSetWithPage();
1064 $this->addSecondOrganizationMembershipToPriceSet();
1065 $this->setupPaymentProcessor();
1066
1067 $dummyPP = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
1068 $dummyPP->setDoDirectPaymentResult(['payment_status_id' => 1, 'trxn_id' => 'create_first_success']);
1069 $processor = $dummyPP->getPaymentProcessor();
1070
1071 $submitParams = [
1072 'price_' . $this->_ids['price_field'][0] => $this->_ids['price_field_value']['cont'],
1073 'price_' . $this->_ids['price_field']['org1'] => $this->_ids['price_field_value']['org1'],
1074 'price_' . $this->_ids['price_field']['org2'] => $this->_ids['price_field_value']['org2'],
1075 'id' => (int) $this->_ids['contribution_page'],
1076 'amount' => 10,
1077 'billing_first_name' => 'Billy',
1078 'billing_middle_name' => 'Goat',
1079 'billing_last_name' => 'Gruff',
1080 'email' => 'billy@goat.gruff',
1081 'selectMembership' => NULL,
1082 'payment_processor_id' => 1,
1083 'credit_card_number' => '4111111111111111',
1084 'credit_card_type' => 'Visa',
1085 'credit_card_exp_date' => ['M' => 9, 'Y' => 2040],
1086 'cvv2' => 123,
1087 'frequency_interval' => 1,
1088 'frequency_unit' => $this->params['recur_frequency_unit'],
1089 ];
1090
1091 $this->callAPIAndDocument('contribution_page', 'submit', $submitParams, __FUNCTION__, __FILE__, 'submit contribution page', NULL);
1092 $contribution = $this->callAPISuccess('contribution', 'getsingle', [
1093 'contribution_page_id' => $this->_ids['contribution_page'],
1094 'contribution_status_id' => 1,
1095 ]);
1096 $this->assertEquals($processor['payment_instrument_id'], $contribution['payment_instrument_id']);
1097
1098 $this->assertEquals('create_first_success', $contribution['trxn_id']);
1099 $membershipPayments = $this->callAPISuccess('membership_payment', 'get', [
1100 'sequential' => 1,
1101 'contribution_id' => $contribution['id'],
1102 ]);
1103 $this->assertEquals(2, $membershipPayments['count']);
1104 $lines = $this->callAPISuccess('line_item', 'get', ['sequential' => 1, 'contribution_id' => $contribution['id']]);
1105 $this->assertEquals(3, $lines['count']);
1106 $this->assertEquals('civicrm_membership', $lines['values'][0]['entity_table']);
1107 $this->assertEquals($preExistingMembershipID + 1, $lines['values'][0]['entity_id']);
1108 $this->assertEquals('civicrm_contribution', $lines['values'][1]['entity_table']);
1109 $this->assertEquals($contribution['id'], $lines['values'][1]['entity_id']);
1110 $this->assertEquals('civicrm_membership', $lines['values'][2]['entity_table']);
1111 $this->assertEquals($preExistingMembershipID + 2, $lines['values'][2]['entity_id']);
1112
1113 $this->callAPISuccessGetSingle('MembershipPayment', ['contribution_id' => $contribution['id'], 'membership_id' => $preExistingMembershipID + 1]);
1114 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $preExistingMembershipID + 1]);
1115
1116 //renew it with processor setting completed - should extend membership
1117 $submitParams['contact_id'] = $contribution['contact_id'];
1118 $dummyPP->setDoDirectPaymentResult(['payment_status_id' => 1, 'trxn_id' => 'create_second_success']);
1119 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
1120 $renewContribution = $this->callAPISuccess('contribution', 'getsingle', [
1121 'id' => ['NOT IN' => [$contribution['id']]],
1122 'contribution_page_id' => $this->_ids['contribution_page'],
1123 'contribution_status_id' => 1,
1124 ]);
1125 $lines = $this->callAPISuccess('line_item', 'get', ['sequential' => 1, 'contribution_id' => $renewContribution['id']]);
1126 $this->assertEquals(3, $lines['count']);
1127 $this->assertEquals('civicrm_membership', $lines['values'][0]['entity_table']);
1128 $this->assertEquals($preExistingMembershipID + 1, $lines['values'][0]['entity_id']);
1129 $this->assertEquals('civicrm_contribution', $lines['values'][1]['entity_table']);
1130 $this->assertEquals($renewContribution['id'], $lines['values'][1]['entity_id']);
1131
1132 $renewedMembership = $this->callAPISuccessGetSingle('membership', ['id' => $preExistingMembershipID + 1]);
1133 $this->assertEquals(date('Y-m-d', strtotime('+ 1 ' . $this->params['recur_frequency_unit'], strtotime($membership['end_date']))), $renewedMembership['end_date']);
1134 }
1135
1136 /**
1137 * Extend the price set with a second organisation's membership.
1138 */
1139 public function addSecondOrganizationMembershipToPriceSet() {
1140 $organization2ID = $this->organizationCreate();
1141 $membershipTypes = $this->callAPISuccess('MembershipType', 'get', []);
1142 $this->_ids['membership_type'] = array_keys($membershipTypes['values']);
1143 $this->_ids['membership_type']['org2'] = $this->membershipTypeCreate(['contact_id' => $organization2ID, 'name' => 'Org 2']);
1144 $priceField = $this->callAPISuccess('PriceField', 'create', [
1145 'price_set_id' => $this->_ids['price_set'],
1146 'html_type' => 'Radio',
1147 'name' => 'Org1 Price',
1148 'label' => 'Org1Price',
1149 ]);
1150 $this->_ids['price_field']['org1'] = $priceField['id'];
1151
1152 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', [
1153 'name' => 'org1 amount',
1154 'label' => 'org 1 Amount',
1155 'amount' => 2,
1156 'financial_type_id' => 'Member Dues',
1157 'format.only_id' => TRUE,
1158 'membership_type_id' => reset($this->_ids['membership_type']),
1159 'price_field_id' => $priceField['id'],
1160 ]);
1161 $this->_ids['price_field_value']['org1'] = $priceFieldValue;
1162
1163 $priceField = $this->callAPISuccess('PriceField', 'create', [
1164 'price_set_id' => $this->_ids['price_set'],
1165 'html_type' => 'Radio',
1166 'name' => 'Org2 Price',
1167 'label' => 'Org2Price',
1168 ]);
1169 $this->_ids['price_field']['org2'] = $priceField['id'];
1170
1171 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', [
1172 'name' => 'org2 amount',
1173 'label' => 'org 2 Amount',
1174 'amount' => 200,
1175 'financial_type_id' => 'Member Dues',
1176 'format.only_id' => TRUE,
1177 'membership_type_id' => $this->_ids['membership_type']['org2'],
1178 'price_field_id' => $priceField['id'],
1179 ]);
1180 $this->_ids['price_field_value']['org2'] = $priceFieldValue;
1181
1182 }
1183
1184 /**
1185 * Test submit recurring membership with immediate confirmation (IATS style).
1186 *
1187 * - we process 2 membership transactions against with a recurring contribution against a contribution page with an immediate
1188 * processor (IATS style - denoted by returning trxn_id)
1189 * - the first creates a new membership, completed contribution, in progress recurring. Check these
1190 * - create another - end date should be extended
1191 */
1192 public function testSubmitMembershipPriceSetPaymentPaymentProcessorSeparatePaymentRecurInstantPayment() {
1193
1194 $this->setUpMembershipContributionPage(TRUE);
1195 $dummyPP = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
1196 $dummyPP->setDoDirectPaymentResult(['payment_status_id' => 1, 'trxn_id' => 'create_first_success']);
1197
1198 $submitParams = [
1199 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
1200 'id' => (int) $this->_ids['contribution_page'],
1201 'amount' => 10,
1202 'billing_first_name' => 'Billy',
1203 'billing_middle_name' => 'Goat',
1204 'billing_last_name' => 'Gruff',
1205 'email' => 'billy@goat.gruff',
1206 'selectMembership' => $this->_ids['membership_type'],
1207 'payment_processor_id' => 1,
1208 'credit_card_number' => '4111111111111111',
1209 'credit_card_type' => 'Visa',
1210 'credit_card_exp_date' => ['M' => 9, 'Y' => 2040],
1211 'cvv2' => 123,
1212 'is_recur' => 1,
1213 'auto_renew' => TRUE,
1214 'frequency_interval' => 1,
1215 'frequency_unit' => 'month',
1216 ];
1217
1218 $this->callAPIAndDocument('contribution_page', 'submit', $submitParams, __FUNCTION__, __FILE__, 'submit contribution page', NULL);
1219 $contribution = $this->callAPISuccess('contribution', 'get', [
1220 'contribution_page_id' => $this->_ids['contribution_page'],
1221 'contribution_status_id' => 1,
1222 ]);
1223
1224 $this->assertEquals(2, $contribution['count']);
1225 $membershipPayment = $this->callAPISuccess('membership_payment', 'getsingle', []);
1226 $this->callAPISuccessGetSingle('membership', ['id' => $membershipPayment['membership_id']]);
1227 $this->assertNotEmpty($contribution['values'][$membershipPayment['contribution_id']]['contribution_recur_id']);
1228 $this->callAPISuccess('contribution_recur', 'getsingle', []);
1229 }
1230
1231 /**
1232 * Test submit recurring membership with delayed confirmation (Authorize.net style)
1233 * - we process 2 membership transactions against with a recurring contribution against a contribution page with a delayed
1234 * processor (Authorize.net style - denoted by NOT returning trxn_id)
1235 * - the first creates a pending membership, pending contribution, penging recurring. Check these
1236 * - complete the transaction
1237 * - create another - end date should NOT be extended
1238 */
1239 public function testSubmitMembershipPriceSetPaymentPaymentProcessorRecurDelayed() {
1240 $this->params['is_recur'] = 1;
1241 $this->params['recur_frequency_unit'] = $membershipTypeParams['duration_unit'] = 'year';
1242 $this->setUpMembershipContributionPage();
1243 $dummyPP = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
1244 $dummyPP->setDoDirectPaymentResult(['payment_status_id' => 2]);
1245 $this->membershipTypeCreate(['name' => 'Student']);
1246
1247 // Add a contribution & a couple of memberships so the id will not be 1 & will differ from membership id.
1248 // This saves us from 'accidental success'.
1249 $this->contributionCreate(['contact_id' => $this->contactIds[0]]);
1250 $this->contactMembershipCreate(['contact_id' => $this->contactIds[0]]);
1251 $this->contactMembershipCreate(['contact_id' => $this->contactIds[0], 'membership_type_id' => 'Student']);
1252
1253 $submitParams = [
1254 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
1255 'id' => (int) $this->_ids['contribution_page'],
1256 'amount' => 10,
1257 'billing_first_name' => 'Billy',
1258 'billing_middle_name' => 'Goat',
1259 'billing_last_name' => 'Gruff',
1260 'email' => 'billy@goat.gruff',
1261 'selectMembership' => $this->_ids['membership_type'],
1262 'payment_processor_id' => 1,
1263 'credit_card_number' => '4111111111111111',
1264 'credit_card_type' => 'Visa',
1265 'credit_card_exp_date' => ['M' => 9, 'Y' => 2040],
1266 'cvv2' => 123,
1267 'is_recur' => 1,
1268 'frequency_interval' => 1,
1269 'frequency_unit' => $this->params['recur_frequency_unit'],
1270 ];
1271
1272 $this->callAPIAndDocument('contribution_page', 'submit', $submitParams, __FUNCTION__, __FILE__, 'submit contribution page', NULL);
1273 $contribution = $this->callAPISuccess('contribution', 'getsingle', [
1274 'contribution_page_id' => $this->_ids['contribution_page'],
1275 'contribution_status_id' => 2,
1276 ]);
1277
1278 $membershipPayment = $this->callAPISuccess('membership_payment', 'getsingle', []);
1279 $this->assertEquals($membershipPayment['contribution_id'], $contribution['id']);
1280 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $membershipPayment['membership_id']]);
1281 $this->assertEquals($membership['contact_id'], $contribution['contact_id']);
1282 $this->assertEquals(5, $membership['status_id']);
1283
1284 $line = $this->callAPISuccess('line_item', 'getsingle', ['contribution_id' => $contribution['id']]);
1285 $this->assertEquals('civicrm_membership', $line['entity_table']);
1286 $this->assertEquals($membership['id'], $line['entity_id']);
1287
1288 $this->callAPISuccess('contribution', 'completetransaction', [
1289 'id' => $contribution['id'],
1290 'trxn_id' => 'ipn_called',
1291 'payment_processor_id' => $this->_paymentProcessor['id'],
1292 ]);
1293 $line = $this->callAPISuccess('line_item', 'getsingle', ['contribution_id' => $contribution['id']]);
1294 $this->assertEquals('civicrm_membership', $line['entity_table']);
1295 $this->assertEquals($membership['id'], $line['entity_id']);
1296
1297 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $membershipPayment['membership_id']]);
1298 //renew it with processor setting completed - should extend membership
1299 $submitParams = array_merge($submitParams, [
1300 'contact_id' => $contribution['contact_id'],
1301 'is_recur' => 1,
1302 'frequency_interval' => 1,
1303 'frequency_unit' => $this->params['recur_frequency_unit'],
1304 ]);
1305
1306 $dummyPP->setDoDirectPaymentResult(['payment_status_id' => 2]);
1307 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
1308 $newContribution = $this->callAPISuccess('contribution', 'getsingle', [
1309 'id' => [
1310 'NOT IN' => [$contribution['id']],
1311 ],
1312 'contribution_page_id' => $this->_ids['contribution_page'],
1313 'contribution_status_id' => 2,
1314 ]);
1315 $line = $this->callAPISuccess('line_item', 'getsingle', ['contribution_id' => $newContribution['id']]);
1316 $this->assertEquals('civicrm_membership', $line['entity_table']);
1317 $this->assertEquals($membership['id'], $line['entity_id']);
1318
1319 $renewedMembership = $this->callAPISuccessGetSingle('membership', ['id' => $membershipPayment['membership_id']]);
1320 //no renewal as the date hasn't changed
1321 $this->assertEquals($membership['end_date'], $renewedMembership['end_date']);
1322 $recurringContribution = $this->callAPISuccess('contribution_recur', 'getsingle', ['id' => $newContribution['contribution_recur_id']]);
1323 $this->assertEquals(2, $recurringContribution['contribution_status_id']);
1324 }
1325
1326 /**
1327 * Test non-recur contribution with membership payment
1328 */
1329 public function testSubmitMembershipIsSeparatePaymentNotRecur() {
1330 //Create recur contribution page.
1331 $this->setUpMembershipContributionPage(TRUE, TRUE);
1332 $dummyPP = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
1333 $dummyPP->setDoDirectPaymentResult(['payment_status_id' => 1, 'trxn_id' => 'create_first_success']);
1334
1335 //Sumbit payment with recur disabled.
1336 $submitParams = [
1337 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
1338 'id' => (int) $this->_ids['contribution_page'],
1339 'amount' => 10,
1340 'frequency_interval' => 1,
1341 'frequency_unit' => 'month',
1342 'billing_first_name' => 'Billy',
1343 'billing_middle_name' => 'Goat',
1344 'billing_last_name' => 'Gruff',
1345 'email' => 'billy@goat.gruff',
1346 'selectMembership' => $this->_ids['membership_type'],
1347 'payment_processor_id' => 1,
1348 'credit_card_number' => '4111111111111111',
1349 'credit_card_type' => 'Visa',
1350 'credit_card_exp_date' => ['M' => 9, 'Y' => 2040],
1351 'cvv2' => 123,
1352 ];
1353
1354 //Assert if recur contribution is created.
1355 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
1356 $recur = $this->callAPISuccess('contribution_recur', 'get', []);
1357 $this->assertEmpty($recur['count']);
1358 }
1359
1360 /**
1361 * Set up membership contribution page.
1362 * @param bool $isSeparatePayment
1363 * @param bool $isRecur
1364 * @param array $membershipTypeParams Parameters to pass to membershiptype.create API
1365 */
1366 public function setUpMembershipContributionPage($isSeparatePayment = FALSE, $isRecur = FALSE, $membershipTypeParams = []) {
1367 $this->setUpMembershipBlockPriceSet($membershipTypeParams);
1368 $this->setupPaymentProcessor();
1369 $this->setUpContributionPage($isRecur);
1370
1371 $this->callAPISuccess('membership_block', 'create', [
1372 'entity_id' => $this->_ids['contribution_page'],
1373 'entity_table' => 'civicrm_contribution_page',
1374 'is_required' => TRUE,
1375 'is_active' => TRUE,
1376 'is_separate_payment' => $isSeparatePayment,
1377 'membership_type_default' => $this->_ids['membership_type'],
1378 ]);
1379 }
1380
1381 /**
1382 * Set up pledge block.
1383 */
1384 public function setUpPledgeBlock() {
1385 $params = [
1386 'entity_table' => 'civicrm_contribution_page',
1387 'entity_id' => $this->_ids['contribution_page'],
1388 'pledge_frequency_unit' => 'week',
1389 'is_pledge_interval' => 0,
1390 'pledge_start_date' => json_encode(['calendar_date' => date('Ymd', strtotime("+1 month"))]),
1391 ];
1392 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::create($params);
1393 $this->_ids['pledge_block_id'] = $pledgeBlock->id;
1394 }
1395
1396 /**
1397 * The default data set does not include a complete default membership price set - not quite sure why.
1398 *
1399 * This function ensures it exists & populates $this->_ids with it's data
1400 */
1401 public function setUpMembershipBlockPriceSet($membershipTypeParams = []) {
1402 $this->_ids['price_set'][] = $this->callAPISuccess('price_set', 'getvalue', [
1403 'name' => 'default_membership_type_amount',
1404 'return' => 'id',
1405 ]);
1406 if (empty($this->_ids['membership_type'])) {
1407 $membershipTypeParams = array_merge([
1408 'minimum_fee' => 2,
1409 ], $membershipTypeParams);
1410 $this->_ids['membership_type'] = [$this->membershipTypeCreate($membershipTypeParams)];
1411 }
1412 $priceField = $this->callAPISuccess('price_field', 'create', [
1413 'price_set_id' => reset($this->_ids['price_set']),
1414 'name' => 'membership_amount',
1415 'label' => 'Membership Amount',
1416 'html_type' => 'Radio',
1417 'sequential' => 1,
1418 ]);
1419 $this->_ids['price_field'][] = $priceField['id'];
1420
1421 foreach ($this->_ids['membership_type'] as $membershipTypeID) {
1422 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', [
1423 'name' => 'membership_amount',
1424 'label' => 'Membership Amount',
1425 'amount' => $this->_membershipBlockAmount,
1426 'financial_type_id' => 'Donation',
1427 'format.only_id' => TRUE,
1428 'membership_type_id' => $membershipTypeID,
1429 'price_field_id' => $priceField['id'],
1430 ]);
1431 $this->_ids['price_field_value'][] = $priceFieldValue;
1432 }
1433 if (!empty($this->_ids['membership_type']['org2'])) {
1434 $priceField = $this->callAPISuccess('price_field', 'create', [
1435 'price_set_id' => reset($this->_ids['price_set']),
1436 'name' => 'membership_org2',
1437 'label' => 'Membership Org2',
1438 'html_type' => 'Checkbox',
1439 'sequential' => 1,
1440 ]);
1441 $this->_ids['price_field']['org2'] = $priceField['id'];
1442
1443 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', [
1444 'name' => 'membership_org2',
1445 'label' => 'Membership org 2',
1446 'amount' => 55,
1447 'financial_type_id' => 'Member Dues',
1448 'format.only_id' => TRUE,
1449 'membership_type_id' => $this->_ids['membership_type']['org2'],
1450 'price_field_id' => $priceField['id'],
1451 ]);
1452 $this->_ids['price_field_value']['org2'] = $priceFieldValue;
1453 }
1454 $priceField = $this->callAPISuccess('price_field', 'create', [
1455 'price_set_id' => reset($this->_ids['price_set']),
1456 'name' => 'Contribution',
1457 'label' => 'Contribution',
1458 'html_type' => 'Text',
1459 'sequential' => 1,
1460 'is_enter_qty' => 1,
1461 ]);
1462 $this->_ids['price_field']['cont'] = $priceField['id'];
1463 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', [
1464 'name' => 'contribution',
1465 'label' => 'Give me money',
1466 'amount' => 88,
1467 'financial_type_id' => 'Donation',
1468 'format.only_id' => TRUE,
1469 'price_field_id' => $priceField['id'],
1470 ]);
1471 $this->_ids['price_field_value'][] = $priceFieldValue;
1472 }
1473
1474 /**
1475 * Add text field other amount to the price set.
1476 */
1477 public function addOtherAmountFieldToMembershipPriceSet() {
1478 $this->_ids['price_field']['other_amount'] = $this->callAPISuccess('price_field', 'create', [
1479 'price_set_id' => reset($this->_ids['price_set']),
1480 'name' => 'other_amount',
1481 'label' => 'Other Amount',
1482 'html_type' => 'Text',
1483 'format.only_id' => TRUE,
1484 'sequential' => 1,
1485 ]);
1486 $this->_ids['price_field_value']['other_amount'] = $this->callAPISuccess('price_field_value', 'create', [
1487 'financial_type_id' => 'Donation',
1488 'format.only_id' => TRUE,
1489 'label' => 'Other Amount',
1490 'amount' => 1,
1491 'price_field_id' => $this->_ids['price_field']['other_amount'],
1492 ]);
1493 }
1494
1495 /**
1496 * Help function to set up contribution page with some defaults.
1497 * @param bool $isRecur
1498 */
1499 public function setUpContributionPage($isRecur = FALSE) {
1500 if ($isRecur) {
1501 $this->params['is_recur'] = 1;
1502 $this->params['recur_frequency_unit'] = 'month';
1503 }
1504 $this->params['frontend_title'] = 'Test Frontend title';
1505 $contributionPageResult = $this->callAPISuccess($this->_entity, 'create', $this->params);
1506 if (empty($this->_ids['price_set'])) {
1507 $priceSet = $this->callAPISuccess('price_set', 'create', $this->_priceSetParams);
1508 $this->_ids['price_set'][] = $priceSet['id'];
1509 }
1510 $priceSetID = reset($this->_ids['price_set']);
1511 CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $contributionPageResult['id'], $priceSetID);
1512
1513 if (empty($this->_ids['price_field'])) {
1514 $priceField = $this->callAPISuccess('price_field', 'create', [
1515 'price_set_id' => $priceSetID,
1516 'label' => 'Goat Breed',
1517 'html_type' => 'Radio',
1518 ]);
1519 $this->_ids['price_field'] = [$priceField['id']];
1520 }
1521 if (empty($this->_ids['price_field_value'])) {
1522 $this->callAPISuccess('price_field_value', 'create', [
1523 'price_set_id' => $priceSetID,
1524 'price_field_id' => $priceField['id'],
1525 'label' => 'Long Haired Goat',
1526 'financial_type_id' => 'Donation',
1527 'amount' => 20,
1528 'non_deductible_amount' => 15,
1529 ]);
1530 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', [
1531 'price_set_id' => $priceSetID,
1532 'price_field_id' => $priceField['id'],
1533 'label' => 'Shoe-eating Goat',
1534 'financial_type_id' => 'Donation',
1535 'amount' => 10,
1536 'non_deductible_amount' => 5,
1537 ]);
1538 $this->_ids['price_field_value'] = [$priceFieldValue['id']];
1539
1540 $this->_ids['price_field_value']['cheapskate'] = $this->callAPISuccess('price_field_value', 'create', [
1541 'price_set_id' => $priceSetID,
1542 'price_field_id' => $priceField['id'],
1543 'label' => 'Stingy Goat',
1544 'financial_type_id' => 'Donation',
1545 'amount' => 0,
1546 'non_deductible_amount' => 0,
1547 ])['id'];
1548 }
1549 $this->_ids['contribution_page'] = $contributionPageResult['id'];
1550 }
1551
1552 /**
1553 * Helper function to set up contribution page which can be used to purchase a
1554 * membership type for different intervals.
1555 */
1556 public function setUpMultiIntervalMembershipContributionPage() {
1557 $this->setupPaymentProcessor();
1558 $contributionPage = $this->callAPISuccess($this->_entity, 'create', $this->params);
1559 $this->_ids['contribution_page'] = $contributionPage['id'];
1560
1561 $this->_ids['membership_type'] = $this->membershipTypeCreate([
1562 // force auto-renew
1563 'auto_renew' => 2,
1564 'duration_unit' => 'month',
1565 ]);
1566
1567 $priceSet = civicrm_api3('PriceSet', 'create', [
1568 'is_quick_config' => 0,
1569 'extends' => 'CiviMember',
1570 'financial_type_id' => 'Member Dues',
1571 'title' => 'CRM-21177',
1572 ]);
1573 $this->_ids['price_set'] = $priceSet['id'];
1574
1575 $priceField = $this->callAPISuccess('price_field', 'create', [
1576 'price_set_id' => $this->_ids['price_set'],
1577 'name' => 'membership_type',
1578 'label' => 'Membership Type',
1579 'html_type' => 'Radio',
1580 ]);
1581 $this->_ids['price_field'] = $priceField['id'];
1582
1583 $priceFieldValueMonthly = $this->callAPISuccess('price_field_value', 'create', [
1584 'name' => 'CRM-21177_Monthly',
1585 'label' => 'CRM-21177 - Monthly',
1586 'amount' => 20,
1587 'membership_num_terms' => 1,
1588 'membership_type_id' => $this->_ids['membership_type'],
1589 'price_field_id' => $this->_ids['price_field'],
1590 'financial_type_id' => 'Member Dues',
1591 ]);
1592 $this->_ids['price_field_value_monthly'] = $priceFieldValueMonthly['id'];
1593
1594 $priceFieldValueYearly = $this->callAPISuccess('price_field_value', 'create', [
1595 'name' => 'CRM-21177_Yearly',
1596 'label' => 'CRM-21177 - Yearly',
1597 'amount' => 200,
1598 'membership_num_terms' => 12,
1599 'membership_type_id' => $this->_ids['membership_type'],
1600 'price_field_id' => $this->_ids['price_field'],
1601 'financial_type_id' => 'Member Dues',
1602 ]);
1603 $this->_ids['price_field_value_yearly'] = $priceFieldValueYearly['id'];
1604
1605 CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $this->_ids['contribution_page'], $this->_ids['price_set']);
1606
1607 $this->callAPISuccess('membership_block', 'create', [
1608 'entity_id' => $this->_ids['contribution_page'],
1609 'entity_table' => 'civicrm_contribution_page',
1610 'is_required' => TRUE,
1611 'is_separate_payment' => FALSE,
1612 'is_active' => TRUE,
1613 'membership_type_default' => $this->_ids['membership_type'],
1614 ]);
1615 }
1616
1617 /**
1618 * Test submit with a membership block in place.
1619 */
1620 public function testSubmitMultiIntervalMembershipContributionPage() {
1621 $this->setUpMultiIntervalMembershipContributionPage();
1622 $submitParams = [
1623 'price_' . $this->_ids['price_field'] => $this->_ids['price_field_value_monthly'],
1624 'id' => (int) $this->_ids['contribution_page'],
1625 'amount' => 20,
1626 'first_name' => 'Billy',
1627 'last_name' => 'Gruff',
1628 'email' => 'billy@goat.gruff',
1629 'payment_processor_id' => $this->_ids['payment_processor'],
1630 'credit_card_number' => '4111111111111111',
1631 'credit_card_type' => 'Visa',
1632 'credit_card_exp_date' => ['M' => 9, 'Y' => 2040],
1633 'cvv2' => 123,
1634 'auto_renew' => 1,
1635 ];
1636 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
1637
1638 $submitParams['price_' . $this->_ids['price_field']] = $this->_ids['price_field_value_yearly'];
1639 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
1640
1641 $contribution = $this->callAPISuccess('Contribution', 'get', [
1642 'contribution_page_id' => $this->_ids['contribution_page'],
1643 'sequential' => 1,
1644 'api.ContributionRecur.getsingle' => [],
1645 ]);
1646 $this->assertEquals(1, $contribution['values'][0]['api.ContributionRecur.getsingle']['frequency_interval']);
1647 //$this->assertEquals(12, $contribution['values'][1]['api.ContributionRecur.getsingle']['frequency_interval']);
1648 }
1649
1650 public static function setUpBeforeClass() {
1651 // put stuff here that should happen before all tests in this unit
1652 }
1653
1654 /**
1655 * @throws \Exception
1656 */
1657 public static function tearDownAfterClass() {
1658 $tablesToTruncate = [
1659 'civicrm_contact',
1660 'civicrm_financial_type',
1661 'civicrm_contribution',
1662 'civicrm_contribution_page',
1663 ];
1664 $unitTest = new CiviUnitTestCase();
1665 $unitTest->quickCleanup($tablesToTruncate);
1666 }
1667
1668 /**
1669 * Create a payment processor instance.
1670 */
1671 protected function setupPaymentProcessor() {
1672 $this->params['payment_processor_id'] = $this->_ids['payment_processor'] = $this->paymentProcessorCreate([
1673 'payment_processor_type_id' => 'Dummy',
1674 'class_name' => 'Payment_Dummy',
1675 'billing_mode' => 1,
1676 ]);
1677 $this->_paymentProcessor = $this->callAPISuccess('payment_processor', 'getsingle', ['id' => $this->params['payment_processor_id']]);
1678 }
1679
1680 /**
1681 * Test submit recurring pledge.
1682 *
1683 * - we process 1 pledge with a future start date. A recur contribution and the pledge should be created with first payment date in the future.
1684 */
1685 public function testSubmitPledgePaymentPaymentProcessorRecurFuturePayment() {
1686 $this->params['adjust_recur_start_date'] = TRUE;
1687 $this->params['is_pay_later'] = FALSE;
1688 $this->setUpContributionPage();
1689 $this->setUpPledgeBlock();
1690 $this->setupPaymentProcessor();
1691 $dummyPP = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
1692 $dummyPP->setDoDirectPaymentResult(['payment_status_id' => 1, 'trxn_id' => 'create_first_success']);
1693
1694 $submitParams = [
1695 'id' => (int) $this->_ids['contribution_page'],
1696 'amount' => 100,
1697 'billing_first_name' => 'Billy',
1698 'billing_middle_name' => 'Goat',
1699 'billing_last_name' => 'Gruff',
1700 'email' => 'billy@goat.gruff',
1701 'payment_processor_id' => 1,
1702 'credit_card_number' => '4111111111111111',
1703 'credit_card_type' => 'Visa',
1704 'credit_card_exp_date' => ['M' => 9, 'Y' => 2040],
1705 'cvv2' => 123,
1706 'pledge_frequency_interval' => 1,
1707 'pledge_frequency_unit' => 'week',
1708 'pledge_installments' => 3,
1709 'is_pledge' => TRUE,
1710 'pledge_block_id' => (int) $this->_ids['pledge_block_id'],
1711 ];
1712
1713 $this->callAPIAndDocument('contribution_page', 'submit', $submitParams, __FUNCTION__, __FILE__, 'submit contribution page', NULL);
1714
1715 // Check if contribution created.
1716 $contribution = $this->callAPISuccess('contribution', 'getsingle', [
1717 'contribution_page_id' => $this->_ids['contribution_page'],
1718 // Will be pending when actual payment processor is used (dummy processor does not support future payments).
1719 'contribution_status_id' => 'Completed',
1720 ]);
1721
1722 $this->assertEquals('create_first_success', $contribution['trxn_id']);
1723
1724 // Check if pledge created.
1725 $pledge = $this->callAPISuccess('pledge', 'getsingle', []);
1726 $this->assertEquals(date('Ymd', strtotime($pledge['pledge_start_date'])), date('Ymd', strtotime("+1 month")));
1727 $this->assertEquals($pledge['pledge_amount'], 300.00);
1728
1729 // Check if pledge payments created.
1730 $params = [
1731 'pledge_id' => $pledge['id'],
1732 ];
1733 $pledgePayment = $this->callAPISuccess('pledge_payment', 'get', $params);
1734 $this->assertEquals($pledgePayment['count'], 3);
1735 $this->assertEquals(date('Ymd', strtotime($pledgePayment['values'][1]['scheduled_date'])), date('Ymd', strtotime("+1 month")));
1736 $this->assertEquals($pledgePayment['values'][1]['scheduled_amount'], 100.00);
1737 // Will be pending when actual payment processor is used (dummy processor does not support future payments).
1738 $this->assertEquals($pledgePayment['values'][1]['status_id'], 1);
1739
1740 // Check contribution recur record.
1741 $recur = $this->callAPISuccess('contribution_recur', 'getsingle', ['id' => $contribution['contribution_recur_id']]);
1742 $this->assertEquals(date('Ymd', strtotime($recur['start_date'])), date('Ymd', strtotime("+1 month")));
1743 $this->assertEquals($recur['amount'], 100.00);
1744 // In progress status.
1745 $this->assertEquals($recur['contribution_status_id'], 5);
1746 }
1747
1748 /**
1749 * Test submit pledge payment.
1750 *
1751 * - test submitting a pledge payment using contribution form.
1752 */
1753 public function testSubmitPledgePayment() {
1754 $this->testSubmitPledgePaymentPaymentProcessorRecurFuturePayment();
1755 $pledge = $this->callAPISuccess('pledge', 'getsingle', []);
1756 $params = [
1757 'pledge_id' => $pledge['id'],
1758 ];
1759 $submitParams = [
1760 'id' => (int) $pledge['pledge_contribution_page_id'],
1761 'pledge_amount' => [2 => 1],
1762 'billing_first_name' => 'Billy',
1763 'billing_middle_name' => 'Goat',
1764 'billing_last_name' => 'Gruff',
1765 'email' => 'billy@goat.gruff',
1766 'payment_processor_id' => 1,
1767 'credit_card_number' => '4111111111111111',
1768 'credit_card_type' => 'Visa',
1769 'credit_card_exp_date' => ['M' => 9, 'Y' => 2040],
1770 'cvv2' => 123,
1771 'pledge_id' => $pledge['id'],
1772 'cid' => $pledge['contact_id'],
1773 'contact_id' => $pledge['contact_id'],
1774 'amount' => 100.00,
1775 'is_pledge' => TRUE,
1776 'pledge_block_id' => $this->_ids['pledge_block_id'],
1777 ];
1778 $pledgePayment = $this->callAPISuccess('pledge_payment', 'get', $params);
1779 $this->assertEquals($pledgePayment['values'][2]['status_id'], 2);
1780
1781 $this->callAPIAndDocument('contribution_page', 'submit', $submitParams, __FUNCTION__, __FILE__, 'submit contribution page', NULL);
1782
1783 // Check if contribution created.
1784 $contribution = $this->callAPISuccess('contribution', 'getsingle', [
1785 'contribution_page_id' => $pledge['pledge_contribution_page_id'],
1786 'contribution_status_id' => 'Completed',
1787 'contact_id' => $pledge['contact_id'],
1788 'contribution_recur_id' => ['IS NULL' => 1],
1789 ]);
1790
1791 $this->assertEquals(100.00, $contribution['total_amount']);
1792 $pledgePayment = $this->callAPISuccess('pledge_payment', 'get', $params);
1793 $this->assertEquals($pledgePayment['values'][2]['status_id'], 1, "This pledge payment should have been completed");
1794 $this->assertEquals($pledgePayment['values'][2]['contribution_id'], $contribution['id']);
1795 }
1796
1797 /**
1798 * Test form submission with multiple option price set.
1799 *
1800 * @param string $thousandSeparator
1801 * punctuation used to refer to thousands.
1802 *
1803 * @dataProvider getThousandSeparators
1804 */
1805 public function testSubmitContributionPageWithPriceSet($thousandSeparator) {
1806 $this->setCurrencySeparators($thousandSeparator);
1807 $this->_priceSetParams['is_quick_config'] = 0;
1808 $this->setUpContributionPage();
1809 $submitParams = [
1810 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
1811 'id' => (int) $this->_ids['contribution_page'],
1812 'amount' => 80,
1813 'first_name' => 'Billy',
1814 'last_name' => 'Gruff',
1815 'email' => 'billy@goat.gruff',
1816 'is_pay_later' => TRUE,
1817 ];
1818 $this->addPriceFields($submitParams);
1819
1820 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
1821 $contribution = $this->callAPISuccessGetSingle('contribution', [
1822 'contribution_page_id' => $this->_ids['contribution_page'],
1823 'contribution_status_id' => 'Pending',
1824 ]);
1825 $this->assertEquals(80, $contribution['total_amount']);
1826 $lineItems = $this->callAPISuccess('LineItem', 'get', [
1827 'contribution_id' => $contribution['id'],
1828 ]);
1829 $this->assertEquals(3, $lineItems['count']);
1830 $totalLineAmount = 0;
1831 foreach ($lineItems['values'] as $lineItem) {
1832 $totalLineAmount = $totalLineAmount + $lineItem['line_total'];
1833 }
1834 $this->assertEquals(80, $totalLineAmount);
1835 }
1836
1837 /**
1838 * Function to add additional price fields to priceset.
1839 * @param array $params
1840 */
1841 public function addPriceFields(&$params) {
1842 $priceSetID = reset($this->_ids['price_set']);
1843 $priceField = $this->callAPISuccess('price_field', 'create', [
1844 'price_set_id' => $priceSetID,
1845 'label' => 'Chicken Breed',
1846 'html_type' => 'CheckBox',
1847 ]);
1848 $priceFieldValue1 = $this->callAPISuccess('price_field_value', 'create', [
1849 'price_set_id' => $priceSetID,
1850 'price_field_id' => $priceField['id'],
1851 'label' => 'Shoe-eating chicken -1',
1852 'financial_type_id' => 'Donation',
1853 'amount' => 30,
1854 ]);
1855 $priceFieldValue2 = $this->callAPISuccess('price_field_value', 'create', [
1856 'price_set_id' => $priceSetID,
1857 'price_field_id' => $priceField['id'],
1858 'label' => 'Shoe-eating chicken -2',
1859 'financial_type_id' => 'Donation',
1860 'amount' => 40,
1861 ]);
1862 $params['price_' . $priceField['id']] = [
1863 $priceFieldValue1['id'] => 1,
1864 $priceFieldValue2['id'] => 1,
1865 ];
1866 }
1867
1868 /**
1869 * Test Tax Amount is calculated properly when using PriceSet with Field Type = Text/Numeric Quantity
1870 *
1871 * @param string $thousandSeparator
1872 * punctuation used to refer to thousands.
1873 *
1874 * @dataProvider getThousandSeparators
1875 */
1876 public function testSubmitContributionPageWithPriceSetQuantity($thousandSeparator) {
1877 $this->setCurrencySeparators($thousandSeparator);
1878 $this->_priceSetParams['is_quick_config'] = 0;
1879 $this->enableTaxAndInvoicing();
1880 $financialType = $this->createFinancialType();
1881 $financialTypeId = $financialType['id'];
1882 // This function sets the Tax Rate at 10% - it currently has no way to pass Tax Rate into it - so let's work with 10%
1883 $this->relationForFinancialTypeWithFinancialAccount($financialType['id'], 5);
1884
1885 $this->setUpContributionPage();
1886 $submitParams = [
1887 'price_' . $this->_ids['price_field'][0] => reset($this->_ids['price_field_value']),
1888 'id' => (int) $this->_ids['contribution_page'],
1889 'first_name' => 'J',
1890 'last_name' => 'T',
1891 'email' => 'JT@ohcanada.ca',
1892 'is_pay_later' => TRUE,
1893 'receive_date' => date('Y-m-d H:i:s'),
1894 ];
1895
1896 // Create PriceSet/PriceField
1897 $priceSetID = reset($this->_ids['price_set']);
1898 $priceField = $this->callAPISuccess('price_field', 'create', [
1899 'price_set_id' => $priceSetID,
1900 'label' => 'Printing Rights',
1901 'html_type' => 'Text',
1902 ]);
1903 $priceFieldValue = $this->callAPISuccess('price_field_value', 'create', [
1904 'price_set_id' => $priceSetID,
1905 'price_field_id' => $priceField['id'],
1906 'label' => 'Printing Rights',
1907 'financial_type_id' => $financialTypeId,
1908 'amount' => '16.95',
1909 ]);
1910 $priceFieldId = $priceField['id'];
1911
1912 // Set quantity for our test
1913 $submitParams['price_' . $priceFieldId] = 180;
1914
1915 // contribution_page submit requires amount and tax_amount - and that's ok we're not testing that - we're testing at the LineItem level
1916 $submitParams['amount'] = $this->formatMoneyInput(180 * 16.95);
1917 // This is the correct Tax Amount - use it later to compare to what the CiviCRM Core came up with at the LineItem level
1918 $submitParams['tax_amount'] = $this->formatMoneyInput(180 * 16.95 * 0.10);
1919
1920 $this->callAPISuccess('contribution_page', 'submit', $submitParams);
1921 $contribution = $this->callAPISuccessGetSingle('contribution', [
1922 'contribution_page_id' => $this->_ids['contribution_page'],
1923 ]);
1924
1925 // Retrieve the lineItem that belongs to the Printing Rights and check the tax_amount CiviCRM Core calculated for it
1926 $lineItem = $this->callAPISuccessGetSingle('LineItem', [
1927 'contribution_id' => $contribution['id'],
1928 'label' => 'Printing Rights',
1929 ]);
1930
1931 $lineItem_TaxAmount = round($lineItem['tax_amount'], 2);
1932
1933 $this->assertEquals($lineItem['line_total'], $contribution['total_amount'], 'Contribution total should match line total');
1934 $this->assertEquals($lineItem_TaxAmount, round(180 * 16.95 * 0.10, 2), 'Wrong Sales Tax Amount is calculated and stored.');
1935 }
1936
1937 /**
1938 * Test validating a contribution page submit.
1939 *
1940 * @throws \CRM_Core_Exception
1941 */
1942 public function testValidate() {
1943 $this->setUpContributionPage();
1944 $errors = $this->callAPISuccess('ContributionPage', 'validate', array_merge($this->getBasicSubmitParams(), ['action' => 'submit']))['values'];
1945 $this->assertEmpty($errors);
1946 }
1947
1948 /**
1949 * Test validating a contribution page submit in POST context.
1950 *
1951 * A likely use case for the validation is when the is being submitted and some handling is
1952 * to be done before processing but the validity of input needs to be checked first.
1953 *
1954 * For example Paypal Checkout will replace the confirm button with it's own but we are able to validate
1955 * before paypal launches it's modal. In this case the $_REQUEST is post but we need validation to succeed.
1956 */
1957 public function testValidatePost() {
1958 $_SERVER['REQUEST_METHOD'] = 'POST';
1959 $this->setUpContributionPage();
1960 $errors = $this->callAPISuccess('ContributionPage', 'validate', array_merge($this->getBasicSubmitParams(), ['action' => 'submit']))['values'];
1961 $this->assertEmpty($errors);
1962 unset($_SERVER['REQUEST_METHOD']);
1963 }
1964
1965 /**
1966 * Test that an error is generated if required fields are not submitted.
1967 */
1968 public function testValidateOutputOnMissingRecurFields() {
1969 $this->params['is_recur_interval'] = 1;
1970 $this->setUpContributionPage(TRUE);
1971 $submitParams = array_merge($this->getBasicSubmitParams(), ['action' => 'submit']);
1972 $submitParams['is_recur'] = 1;
1973 $submitParams['frequency_interval'] = '';
1974 $submitParams['frequency_unit'] = '';
1975 $errors = $this->callAPISuccess('ContributionPage', 'validate', $submitParams)['values'];
1976 $this->assertEquals('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).', $errors['frequency_interval']);
1977 }
1978
1979 /**
1980 * Implements hook_civicrm_alterPaymentProcessorParams().
1981 *
1982 * @throws \Exception
1983 */
1984 public function hook_civicrm_alterPaymentProcessorParams($paymentObj, &$rawParams, &$cookedParams) {
1985 // Ensure total_amount are the same if they're both given.
1986 $total_amount = CRM_Utils_Array::value('total_amount', $rawParams);
1987 $amount = CRM_Utils_Array::value('amount', $rawParams);
1988 if (!empty($total_amount) && !empty($amount) && $total_amount != $amount) {
1989 throw new Exception("total_amount '$total_amount' and amount '$amount' differ.");
1990 }
1991
1992 // Log parameters for later debugging and testing.
1993 $message = __FUNCTION__ . ": {$rawParams['TEST_UNIQ']}:";
1994 $log_params = array_intersect_key($rawParams, [
1995 'amount' => 1,
1996 'total_amount' => 1,
1997 'contributionID' => 1,
1998 ]);
1999 $message .= json_encode($log_params);
2000 $log = new CRM_Utils_SystemLogger();
2001 $log->debug($message, $_REQUEST);
2002 }
2003
2004 /**
2005 * Get the params for a basic simple submit.
2006 *
2007 * @return array
2008 */
2009 protected function getBasicSubmitParams() {
2010 $priceFieldID = reset($this->_ids['price_field']);
2011 $priceFieldValueID = reset($this->_ids['price_field_value']);
2012 $submitParams = [
2013 'price_' . $priceFieldID => $priceFieldValueID,
2014 'id' => (int) $this->_ids['contribution_page'],
2015 'amount' => 10,
2016 'priceSetId' => $this->_ids['price_set'][0],
2017 'payment_processor_id' => 0,
2018 ];
2019 return $submitParams;
2020 }
2021
2022 }