Use metadata for getOptions abbreviation & include currency symbol
[civicrm-core.git] / tests / phpunit / api / v3 / ContributionTest.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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_* functions
30 *
31 * @package CiviCRM_APIv3
32 * @subpackage API_Contribution
33 * @group headless
34 */
35 class api_v3_ContributionTest extends CiviUnitTestCase {
36
37 protected $_individualId;
38 protected $_contribution;
39 protected $_financialTypeId = 1;
40 protected $_apiversion;
41 protected $_entity = 'Contribution';
42 public $debug = 0;
43 protected $_params;
44 protected $_ids = [];
45 protected $_pageParams = [];
46 /**
47 * Payment processor ID (dummy processor).
48 *
49 * @var int
50 */
51 protected $paymentProcessorID;
52
53 /**
54 * Parameters to create payment processor.
55 *
56 * @var array
57 */
58 protected $_processorParams = [];
59
60 /**
61 * ID of created event.
62 *
63 * @var int
64 */
65 protected $_eventID;
66
67 /**
68 * @var CiviMailUtils
69 */
70 protected $mut;
71
72 /**
73 * Setup function.
74 */
75 public function setUp() {
76 parent::setUp();
77
78 $this->_apiversion = 3;
79 $this->_individualId = $this->individualCreate();
80 $this->_params = [
81 'contact_id' => $this->_individualId,
82 'receive_date' => '20120511',
83 'total_amount' => 100.00,
84 'financial_type_id' => $this->_financialTypeId,
85 'non_deductible_amount' => 10.00,
86 'fee_amount' => 5.00,
87 'net_amount' => 95.00,
88 'source' => 'SSF',
89 'contribution_status_id' => 1,
90 ];
91 $this->_processorParams = [
92 'domain_id' => 1,
93 'name' => 'Dummy',
94 'payment_processor_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', 'Dummy'),
95 'financial_account_id' => 12,
96 'is_active' => 1,
97 'user_name' => '',
98 'url_site' => 'http://dummy.com',
99 'url_recur' => 'http://dummy.com',
100 'billing_mode' => 1,
101 ];
102 $this->paymentProcessorID = $this->processorCreate();
103 $this->_pageParams = [
104 'title' => 'Test Contribution Page',
105 'financial_type_id' => 1,
106 'currency' => 'USD',
107 'financial_account_id' => 1,
108 'payment_processor' => $this->paymentProcessorID,
109 'is_active' => 1,
110 'is_allow_other_amount' => 1,
111 'min_amount' => 10,
112 'max_amount' => 1000,
113 ];
114 }
115
116 /**
117 * Clean up after each test.
118 */
119 public function tearDown() {
120 $this->quickCleanUpFinancialEntities();
121 $this->quickCleanup(['civicrm_uf_match']);
122 $financialAccounts = $this->callAPISuccess('FinancialAccount', 'get', []);
123 foreach ($financialAccounts['values'] as $financialAccount) {
124 if ($financialAccount['name'] == 'Test Tax financial account ' || $financialAccount['name'] == 'Test taxable financial Type') {
125 $entityFinancialTypes = $this->callAPISuccess('EntityFinancialAccount', 'get', [
126 'financial_account_id' => $financialAccount['id'],
127 ]);
128 foreach ($entityFinancialTypes['values'] as $entityFinancialType) {
129 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialType['id']]);
130 }
131 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
132 }
133 }
134 }
135
136 /**
137 * Test Get.
138 */
139 public function testGetContribution() {
140 $contributionSettings = $this->enableTaxAndInvoicing();
141 $invoice_prefix = CRM_Contribute_BAO_Contribution::checkContributeSettings('invoice_prefix', TRUE);
142 $p = [
143 'contact_id' => $this->_individualId,
144 'receive_date' => '2010-01-20',
145 'total_amount' => 100.00,
146 'financial_type_id' => $this->_financialTypeId,
147 'non_deductible_amount' => 10.00,
148 'fee_amount' => 5.00,
149 'net_amount' => 95.00,
150 'trxn_id' => 23456,
151 'invoice_id' => 78910,
152 'source' => 'SSF',
153 'contribution_status_id' => 1,
154 ];
155 $this->_contribution = $this->callAPISuccess('contribution', 'create', $p);
156
157 $params = [
158 'contribution_id' => $this->_contribution['id'],
159 ];
160
161 $contributions = $this->callAPIAndDocument('contribution', 'get', $params, __FUNCTION__, __FILE__);
162 $financialParams['id'] = $this->_financialTypeId;
163 $default = NULL;
164 CRM_Financial_BAO_FinancialType::retrieve($financialParams, $default);
165
166 $this->assertEquals(1, $contributions['count']);
167 $contribution = $contributions['values'][$contributions['id']];
168 $this->assertEquals($contribution['contact_id'], $this->_individualId);
169 // Note there was an assertion converting financial_type_id to 'Donation' which wasn't working.
170 // Passing back a string rather than an id seems like an error/cruft.
171 // If it is to be introduced we should discuss.
172 $this->assertEquals($contribution['financial_type_id'], 1);
173 $this->assertEquals($contribution['total_amount'], 100.00);
174 $this->assertEquals($contribution['non_deductible_amount'], 10.00);
175 $this->assertEquals($contribution['fee_amount'], 5.00);
176 $this->assertEquals($contribution['net_amount'], 95.00);
177 $this->assertEquals($contribution['trxn_id'], 23456);
178 $this->assertEquals($contribution['invoice_id'], 78910);
179 $this->assertEquals($contribution['invoice_number'], $invoice_prefix . $contributions['id']);
180 $this->assertEquals($contribution['contribution_source'], 'SSF');
181 $this->assertEquals($contribution['contribution_status'], 'Completed');
182 // Create a second contribution - we are testing that 'id' gets the right contribution id (not the contact id).
183 $p['trxn_id'] = '3847';
184 $p['invoice_id'] = '3847';
185
186 $contribution2 = $this->callAPISuccess('contribution', 'create', $p);
187
188 // Now we have 2 - test getcount.
189 $contribution = $this->callAPISuccess('contribution', 'getcount', []);
190 $this->assertEquals(2, $contribution);
191 // Test id only format.
192 $contribution = $this->callAPISuccess('contribution', 'get', [
193 'id' => $this->_contribution['id'],
194 'format.only_id' => 1,
195 ]);
196 $this->assertEquals($this->_contribution['id'], $contribution, print_r($contribution, TRUE));
197 // Test id only format.
198 $contribution = $this->callAPISuccess('contribution', 'get', [
199 'id' => $contribution2['id'],
200 'format.only_id' => 1,
201 ]);
202 $this->assertEquals($contribution2['id'], $contribution);
203 // Test id as field.
204 $contribution = $this->callAPISuccess('contribution', 'get', [
205 'id' => $this->_contribution['id'],
206 ]);
207 $this->assertEquals(1, $contribution['count']);
208
209 // Test get by contact id works.
210 $contribution = $this->callAPISuccess('contribution', 'get', ['contact_id' => $this->_individualId]);
211
212 $this->assertEquals(2, $contribution['count']);
213 $this->callAPISuccess('Contribution', 'Delete', [
214 'id' => $this->_contribution['id'],
215 ]);
216 $this->callAPISuccess('Contribution', 'Delete', [
217 'id' => $contribution2['id'],
218 ]);
219 }
220
221 /**
222 * Test that test contributions can be retrieved.
223 */
224 public function testGetTestContribution() {
225 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params, ['is_test' => 1]));
226 $this->callAPISuccessGetSingle('Contribution', ['is_test' => 1]);
227 }
228
229 /**
230 * Test the 'return' param works for all fields.
231 */
232 public function testGetContributionReturnFunctionality() {
233 $params = $this->_params;
234 $params['check_number'] = 'bouncer';
235 $params['payment_instrument_id'] = 'Check';
236 $params['cancel_date'] = 'yesterday';
237 $params['receipt_date'] = 'yesterday';
238 $params['thankyou_date'] = 'yesterday';
239 $params['revenue_recognition_date'] = 'yesterday';
240 $params['amount_level'] = 'Unreasonable';
241 $params['cancel_reason'] = 'You lose sucker';
242 $params['creditnote_id'] = 'sudo rm -rf';
243 $params['tax_amount'] = '1';
244 $address = $this->callAPISuccess('Address', 'create', [
245 'street_address' => 'Knockturn Alley',
246 'contact_id' => $this->_individualId,
247 'location_type_id' => 'Home',
248 ]);
249 $params['address_id'] = $address['id'];
250 $contributionPage = $this->contributionPageCreate();
251 $params['contribution_page_id'] = $contributionPage['id'];
252 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
253 'contact_id' => $this->_individualId,
254 'frequency_interval' => 1,
255 'amount' => 5,
256 ]);
257 $params['contribution_recur_id'] = $contributionRecur['id'];
258
259 $params['campaign_id'] = $this->campaignCreate();
260
261 $contributionID = $this->contributionCreate($params);
262
263 // update contribution with invoice number
264 $params = array_merge($params, [
265 'id' => $contributionID,
266 'invoice_number' => CRM_Utils_Array::value('invoice_prefix', Civi::settings()->get('contribution_invoice_settings')) . "" . $contributionID,
267 'trxn_id' => 12345,
268 'invoice_id' => 6789,
269 ]);
270 $contributionID = $this->contributionCreate($params);
271
272 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID]);
273 $this->assertEquals('bouncer', $contribution['check_number']);
274 $this->assertEquals('bouncer', $contribution['contribution_check_number']);
275
276 $fields = CRM_Contribute_BAO_Contribution::fields();
277 // Re-add these 2 to the fields to check. They were locked in but the metadata changed so we
278 // need to specify them.
279 $fields['address_id'] = $fields['contribution_address_id'];
280 $fields['check_number'] = $fields['contribution_check_number'];
281
282 $fieldsLockedIn = [
283 'contribution_id', 'contribution_contact_id', 'financial_type_id', 'contribution_page_id',
284 'payment_instrument_id', 'receive_date', 'non_deductible_amount', 'total_amount',
285 'fee_amount', 'net_amount', 'trxn_id', 'invoice_id', 'currency', 'contribution_cancel_date', 'cancel_reason',
286 'receipt_date', 'thankyou_date', 'contribution_source', 'amount_level', 'contribution_recur_id',
287 'is_test', 'is_pay_later', 'contribution_status_id', 'address_id', 'check_number', 'contribution_campaign_id',
288 'creditnote_id', 'tax_amount', 'revenue_recognition_date', 'decoy',
289 ];
290 $missingFields = array_diff($fieldsLockedIn, array_keys($fields));
291 // If any of the locked in fields disappear from the $fields array we need to make sure it is still
292 // covered as the test contract now guarantees them in the return array.
293 $this->assertEquals($missingFields, [29 => 'decoy'], 'A field which was covered by the test contract has changed.');
294 foreach ($fields as $fieldName => $fieldSpec) {
295 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID, 'return' => $fieldName]);
296 $returnField = $fieldName;
297 if ($returnField == 'contribution_contact_id') {
298 $returnField = 'contact_id';
299 }
300 $this->assertTrue((!empty($contribution[$returnField]) || $contribution[$returnField] === "0"), $returnField);
301 }
302 }
303
304 /**
305 * Test cancel reason works as a filter.
306 */
307 public function testFilterCancelReason() {
308 $params = $this->_params;
309 $params['cancel_date'] = 'yesterday';
310 $params['cancel_reason'] = 'You lose sucker';
311 $this->callAPISuccess('Contribution', 'create', $params);
312 $params = $this->_params;
313 $params['cancel_date'] = 'yesterday';
314 $params['cancel_reason'] = 'You are a winner';
315 $this->callAPISuccess('Contribution', 'create', $params);
316 $this->callAPISuccessGetCount('Contribution', ['cancel_reason' => 'You are a winner'], 1);
317 }
318
319 /**
320 * We need to ensure previous tested behaviour still works as part of the api contract.
321 */
322 public function testGetContributionLegacyBehaviour() {
323 $p = [
324 'contact_id' => $this->_individualId,
325 'receive_date' => '2010-01-20',
326 'total_amount' => 100.00,
327 'contribution_type_id' => $this->_financialTypeId,
328 'non_deductible_amount' => 10.00,
329 'fee_amount' => 5.00,
330 'net_amount' => 95.00,
331 'trxn_id' => 23456,
332 'invoice_id' => 78910,
333 'source' => 'SSF',
334 'contribution_status_id' => 1,
335 ];
336 $this->_contribution = $this->callAPISuccess('Contribution', 'create', $p);
337
338 $params = [
339 'contribution_id' => $this->_contribution['id'],
340 ];
341 $contribution = $this->callAPISuccess('contribution', 'get', $params);
342 $financialParams['id'] = $this->_financialTypeId;
343 $default = NULL;
344 CRM_Financial_BAO_FinancialType::retrieve($financialParams, $default);
345
346 $this->assertEquals(1, $contribution['count']);
347 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId);
348 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], $this->_financialTypeId);
349 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_type_id'], $this->_financialTypeId);
350 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
351 $this->assertEquals($contribution['values'][$contribution['id']]['non_deductible_amount'], 10.00);
352 $this->assertEquals($contribution['values'][$contribution['id']]['fee_amount'], 5.00);
353 $this->assertEquals($contribution['values'][$contribution['id']]['net_amount'], 95.00);
354 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 23456);
355 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 78910);
356 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_source'], 'SSF');
357 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status'], 'Completed');
358
359 // Create a second contribution - we are testing that 'id' gets the right contribution id (not the contact id).
360 $p['trxn_id'] = '3847';
361 $p['invoice_id'] = '3847';
362
363 $contribution2 = $this->callAPISuccess('contribution', 'create', $p);
364
365 // now we have 2 - test getcount
366 $contribution = $this->callAPISuccess('contribution', 'getcount', []);
367 $this->assertEquals(2, $contribution);
368 //test id only format
369 $contribution = $this->callAPISuccess('contribution', 'get', [
370 'id' => $this->_contribution['id'],
371 'format.only_id' => 1,
372 ]);
373 $this->assertEquals($this->_contribution['id'], $contribution, print_r($contribution, TRUE));
374 //test id only format
375 $contribution = $this->callAPISuccess('contribution', 'get', [
376 'id' => $contribution2['id'],
377 'format.only_id' => 1,
378 ]);
379 $this->assertEquals($contribution2['id'], $contribution);
380 $contribution = $this->callAPISuccess('contribution', 'get', [
381 'id' => $this->_contribution['id'],
382 ]);
383 //test id as field
384 $this->assertEquals(1, $contribution['count']);
385 // $this->assertEquals($this->_contribution['id'], $contribution['id'] ) ;
386 //test get by contact id works
387 $contribution = $this->callAPISuccess('contribution', 'get', ['contact_id' => $this->_individualId]);
388
389 $this->assertEquals(2, $contribution['count']);
390 $this->callAPISuccess('Contribution', 'Delete', [
391 'id' => $this->_contribution['id'],
392 ]);
393 $this->callAPISuccess('Contribution', 'Delete', [
394 'id' => $contribution2['id'],
395 ]);
396 }
397
398 /**
399 * Create an contribution_id=FALSE and financial_type_id=Donation.
400 */
401 public function testCreateEmptyContributionIDUseDonation() {
402 $params = [
403 'contribution_id' => FALSE,
404 'contact_id' => 1,
405 'total_amount' => 1,
406 'check_permissions' => FALSE,
407 'financial_type_id' => 'Donation',
408 ];
409 $this->callAPISuccess('contribution', 'create', $params);
410 }
411
412 /**
413 * Check with complete array + custom field.
414 *
415 * Note that the test is written on purpose without any
416 * variables specific to participant so it can be replicated into other entities
417 * and / or moved to the automated test suite
418 */
419 public function testCreateWithCustom() {
420 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__, __FILE__);
421
422 $params = $this->_params;
423 $params['custom_' . $ids['custom_field_id']] = "custom string";
424
425 $result = $this->callAPIAndDocument($this->_entity, 'create', $params, __FUNCTION__, __FILE__);
426 $this->assertEquals($result['id'], $result['values'][$result['id']]['id']);
427 $check = $this->callAPISuccess($this->_entity, 'get', [
428 'return.custom_' . $ids['custom_field_id'] => 1,
429 'id' => $result['id'],
430 ]);
431 $this->customFieldDelete($ids['custom_field_id']);
432 $this->customGroupDelete($ids['custom_group_id']);
433 $this->assertEquals("custom string", $check['values'][$check['id']]['custom_' . $ids['custom_field_id']]);
434 }
435
436 /**
437 * Check with complete array + custom field.
438 *
439 * Note that the test is written on purpose without any
440 * variables specific to participant so it can be replicated into other entities
441 * and / or moved to the automated test suite
442 */
443 public function testCreateGetFieldsWithCustom() {
444 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__, __FILE__);
445 $idsContact = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__, 'ContactTest.php');
446 $result = $this->callAPISuccess('Contribution', 'getfields', []);
447 $this->assertArrayHasKey('custom_' . $ids['custom_field_id'], $result['values']);
448 $this->assertArrayNotHasKey('custom_' . $idsContact['custom_field_id'], $result['values']);
449 $this->customFieldDelete($ids['custom_field_id']);
450 $this->customGroupDelete($ids['custom_group_id']);
451 $this->customFieldDelete($idsContact['custom_field_id']);
452 $this->customGroupDelete($idsContact['custom_group_id']);
453 }
454
455 public function testCreateContributionNoLineItems() {
456
457 $params = [
458 'contact_id' => $this->_individualId,
459 'receive_date' => '20120511',
460 'total_amount' => 100.00,
461 'financial_type_id' => $this->_financialTypeId,
462 'payment_instrument_id' => 1,
463 'non_deductible_amount' => 10.00,
464 'fee_amount' => 50.00,
465 'net_amount' => 90.00,
466 'trxn_id' => 12345,
467 'invoice_id' => 67890,
468 'source' => 'SSF',
469 'contribution_status_id' => 1,
470 'skipLineItem' => 1,
471 ];
472
473 $contribution = $this->callAPISuccess('contribution', 'create', $params);
474 $lineItems = $this->callAPISuccess('line_item', 'get', [
475 'entity_id' => $contribution['id'],
476 'entity_table' => 'civicrm_contribution',
477 'sequential' => 1,
478 ]);
479 $this->assertEquals(0, $lineItems['count']);
480 }
481
482 /**
483 * Test checks that passing in line items suppresses the create mechanism.
484 */
485 public function testCreateContributionChainedLineItems() {
486 $params = [
487 'contact_id' => $this->_individualId,
488 'receive_date' => '20120511',
489 'total_amount' => 100.00,
490 'financial_type_id' => $this->_financialTypeId,
491 'payment_instrument_id' => 1,
492 'non_deductible_amount' => 10.00,
493 'fee_amount' => 50.00,
494 'net_amount' => 90.00,
495 'trxn_id' => 12345,
496 'invoice_id' => 67890,
497 'source' => 'SSF',
498 'contribution_status_id' => 1,
499 'skipLineItem' => 1,
500 'api.line_item.create' => [
501 [
502 'price_field_id' => 1,
503 'qty' => 2,
504 'line_total' => '20',
505 'unit_price' => '10',
506 ],
507 [
508 'price_field_id' => 1,
509 'qty' => 1,
510 'line_total' => '80',
511 'unit_price' => '80',
512 ],
513 ],
514 ];
515
516 $description = "Create Contribution with Nested Line Items.";
517 $subfile = "CreateWithNestedLineItems";
518 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__, __FILE__, $description, $subfile);
519
520 $lineItems = $this->callAPISuccess('line_item', 'get', [
521 'entity_id' => $contribution['id'],
522 'contribution_id' => $contribution['id'],
523 'entity_table' => 'civicrm_contribution',
524 'sequential' => 1,
525 ]);
526 $this->assertEquals(2, $lineItems['count']);
527 }
528
529 public function testCreateContributionOffline() {
530 $params = [
531 'contact_id' => $this->_individualId,
532 'receive_date' => '20120511',
533 'total_amount' => 100.00,
534 'financial_type_id' => 1,
535 'trxn_id' => 12345,
536 'invoice_id' => 67890,
537 'source' => 'SSF',
538 'contribution_status_id' => 1,
539 ];
540
541 $contribution = $this->callAPISuccess('contribution', 'create', $params);
542 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId);
543 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
544 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
545 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
546 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
547 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
548 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 1);
549 $lineItems = $this->callAPISuccess('line_item', 'get', [
550 'entity_id' => $contribution['id'],
551 'contribution_id' => $contribution['id'],
552 'entity_table' => 'civicrm_contribution',
553 'sequential' => 1,
554 ]);
555 $this->assertEquals(1, $lineItems['count']);
556 $this->assertEquals($contribution['id'], $lineItems['values'][0]['entity_id']);
557 $this->assertEquals($contribution['id'], $lineItems['values'][0]['contribution_id']);
558 $this->_checkFinancialRecords($contribution, 'offline');
559 $this->contributionGetnCheck($params, $contribution['id']);
560 }
561
562 /**
563 * Test create with valid payment instrument.
564 */
565 public function testCreateContributionWithPaymentInstrument() {
566 $params = $this->_params + ['payment_instrument' => 'EFT'];
567 $contribution = $this->callAPISuccess('contribution', 'create', $params);
568 $contribution = $this->callAPISuccess('contribution', 'get', [
569 'sequential' => 1,
570 'id' => $contribution['id'],
571 ]);
572 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
573 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
574
575 $this->callAPISuccess('contribution', 'create', [
576 'id' => $contribution['id'],
577 'payment_instrument' => 'Credit Card',
578 ]);
579 $contribution = $this->callAPISuccess('contribution', 'get', [
580 'sequential' => 1,
581 'id' => $contribution['id'],
582 ]);
583 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
584 $this->assertEquals('Credit Card', $contribution['values'][0]['payment_instrument']);
585 }
586
587 public function testGetContributionByPaymentInstrument() {
588 $params = $this->_params + ['payment_instrument' => 'EFT'];
589 $params2 = $this->_params + ['payment_instrument' => 'Cash'];
590 $this->callAPISuccess('contribution', 'create', $params);
591 $this->callAPISuccess('contribution', 'create', $params2);
592 $contribution = $this->callAPISuccess('contribution', 'get', [
593 'sequential' => 1,
594 'contribution_payment_instrument' => 'Cash',
595 ]);
596 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
597 $this->assertEquals('Cash', $contribution['values'][0]['payment_instrument']);
598 $this->assertEquals(1, $contribution['count']);
599 $contribution = $this->callAPISuccess('contribution', 'get', ['sequential' => 1, 'payment_instrument' => 'Cash']);
600 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
601 $this->assertEquals('Cash', $contribution['values'][0]['payment_instrument']);
602 $this->assertEquals(1, $contribution['count']);
603 $contribution = $this->callAPISuccess('contribution', 'get', [
604 'sequential' => 1,
605 'payment_instrument_id' => 5,
606 ]);
607 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
608 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
609 $this->assertEquals(1, $contribution['count']);
610 $contribution = $this->callAPISuccess('contribution', 'get', [
611 'sequential' => 1,
612 'payment_instrument' => 'EFT',
613 ]);
614 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
615 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
616 $this->assertEquals(1, $contribution['count']);
617 $contribution = $this->callAPISuccess('contribution', 'create', [
618 'id' => $contribution['id'],
619 'payment_instrument' => 'Credit Card',
620 ]);
621 $contribution = $this->callAPISuccess('contribution', 'get', ['sequential' => 1, 'id' => $contribution['id']]);
622 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
623 $this->assertEquals('Credit Card', $contribution['values'][0]['payment_instrument']);
624 $this->assertEquals(1, $contribution['count']);
625 }
626
627 /**
628 * CRM-16227 introduces invoice_id as a parameter.
629 */
630 public function testGetContributionByInvoice() {
631 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params, ['invoice_id' => 'curly']));
632 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params), ['invoice_id' => 'churlish']);
633 $this->callAPISuccessGetCount('Contribution', [], 2);
634 $this->callAPISuccessGetSingle('Contribution', ['invoice_id' => 'curly']);
635 // The following don't work. They are the format we are trying to introduce but although the form uses this format
636 // CRM_Contact_BAO_Query::convertFormValues puts them into the other format & the where only supports that.
637 // ideally the where clause would support this format (as it does on contact_BAO_Query) and those lines would
638 // come out of convertFormValues
639 // $this->callAPISuccessGetSingle('Contribution', array('invoice_id' => array('LIKE' => '%ish%')));
640 // $this->callAPISuccessGetSingle('Contribution', array('invoice_id' => array('NOT IN' => array('curly'))));
641 // $this->callAPISuccessGetCount('Contribution', array('invoice_id' => array('LIKE' => '%ly%')), 2);
642 // $this->callAPISuccessGetCount('Contribution', array('invoice_id' => array('IN' => array('curly', 'churlish'))),
643 // 2);
644 }
645
646 /**
647 * Check the credit note retrieval is case insensitive.
648 */
649 public function testGetCreditNoteCaseInsensitive() {
650 $this->contributionCreate(['contact_id' => $this->_individualId]);
651 $this->contributionCreate(['creditnote_id' => 'cN1234', 'contact_id' => $this->_individualId, 'invoice_id' => rand(), 'trxn_id' => rand()]);
652 $contribution = $this->callAPISuccess('Contribution', 'getsingle', ['creditnote_id' => 'CN1234']);
653 $this->assertEquals($contribution['creditnote_id'], 'cN1234');
654 }
655
656 /**
657 * Test retrieval by total_amount works.
658 *
659 * @throws Exception
660 */
661 public function testGetContributionByTotalAmount() {
662 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params, ['total_amount' => '5']));
663 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params, ['total_amount' => '10']));
664 $this->callAPISuccessGetCount('Contribution', ['total_amount' => 10], 1);
665 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => 6]], 1);
666 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => 0]], 2);
667 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => -5]], 2);
668 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['<' => 0]], 0);
669 $this->callAPISuccessGetCount('Contribution', [], 2);
670 }
671
672 /**
673 * Create test with unique field name on source.
674 */
675 public function testCreateContributionSource() {
676
677 $params = [
678 'contact_id' => $this->_individualId,
679 'receive_date' => date('Ymd'),
680 'total_amount' => 100.00,
681 'financial_type_id' => $this->_financialTypeId,
682 'payment_instrument_id' => 1,
683 'non_deductible_amount' => 10.00,
684 'fee_amount' => 50.00,
685 'net_amount' => 90.00,
686 'trxn_id' => 12345,
687 'invoice_id' => 67890,
688 'contribution_source' => 'SSF',
689 'contribution_status_id' => 1,
690 ];
691
692 $contribution = $this->callAPISuccess('contribution', 'create', $params);
693 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
694 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
695 }
696
697 /**
698 * Create test with unique field name on source.
699 *
700 * @param string $thousandSeparator
701 * punctuation used to refer to thousands.
702 *
703 * @dataProvider getThousandSeparators
704 */
705 public function testCreateDefaultNow($thousandSeparator) {
706 $this->setCurrencySeparators($thousandSeparator);
707 $params = $this->_params;
708 unset($params['receive_date'], $params['net_amount']);
709
710 $params['total_amount'] = $this->formatMoneyInput(5000.77);
711 $params['fee_amount'] = $this->formatMoneyInput(.77);
712 $params['skipCleanMoney'] = FALSE;
713
714 $contribution = $this->callAPISuccess('contribution', 'create', $params);
715 $contribution = $this->callAPISuccessGetSingle('contribution', ['id' => $contribution['id']]);
716 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receive_date'])));
717 $this->assertEquals(5000.77, $contribution['total_amount'], 'failed to handle ' . $this->formatMoneyInput(5000.77));
718 $this->assertEquals(.77, $contribution['fee_amount']);
719 $this->assertEquals(5000, $contribution['net_amount']);
720 }
721
722 /**
723 * Create test with unique field name on source.
724 */
725 public function testCreateContributionNullOutThankyouDate() {
726
727 $params = $this->_params;
728 $params['thankyou_date'] = 'yesterday';
729
730 $contribution = $this->callAPISuccess('contribution', 'create', $params);
731 $contribution = $this->callAPISuccessGetSingle('contribution', ['id' => $contribution['id']]);
732 $this->assertEquals(date('Y-m-d', strtotime('yesterday')), date('Y-m-d', strtotime($contribution['thankyou_date'])));
733
734 $params['thankyou_date'] = 'null';
735 $contribution = $this->callAPISuccess('contribution', 'create', $params);
736 $contribution = $this->assertTrue(empty($contribution['thankyou_date']));
737 }
738
739 /**
740 * Create test with unique field name on source.
741 */
742 public function testCreateContributionSourceInvalidContact() {
743
744 $params = [
745 'contact_id' => 999,
746 'receive_date' => date('Ymd'),
747 'total_amount' => 100.00,
748 'financial_type_id' => $this->_financialTypeId,
749 'payment_instrument_id' => 1,
750 'non_deductible_amount' => 10.00,
751 'fee_amount' => 50.00,
752 'net_amount' => 90.00,
753 'trxn_id' => 12345,
754 'invoice_id' => 67890,
755 'contribution_source' => 'SSF',
756 'contribution_status_id' => 1,
757 ];
758
759 $this->callAPIFailure('contribution', 'create', $params, 'contact_id is not valid : 999');
760 }
761
762 public function testCreateContributionSourceInvalidContContact() {
763
764 $params = [
765 'contribution_contact_id' => 999,
766 'receive_date' => date('Ymd'),
767 'total_amount' => 100.00,
768 'financial_type_id' => $this->_financialTypeId,
769 'payment_instrument_id' => 1,
770 'non_deductible_amount' => 10.00,
771 'fee_amount' => 50.00,
772 'net_amount' => 90.00,
773 'trxn_id' => 12345,
774 'invoice_id' => 67890,
775 'contribution_source' => 'SSF',
776 'contribution_status_id' => 1,
777 ];
778
779 $this->callAPIFailure('contribution', 'create', $params);
780 }
781
782 /**
783 * Test note created correctly.
784 */
785 public function testCreateContributionWithNote() {
786 $description = "Demonstrates creating contribution with Note Entity.";
787 $subfile = "ContributionCreateWithNote";
788 $params = [
789 'contact_id' => $this->_individualId,
790 'receive_date' => '2012-01-01',
791 'total_amount' => 100.00,
792 'financial_type_id' => $this->_financialTypeId,
793 'payment_instrument_id' => 1,
794 'non_deductible_amount' => 10.00,
795 'fee_amount' => 50.00,
796 'net_amount' => 90.00,
797 'trxn_id' => 12345,
798 'invoice_id' => 67890,
799 'source' => 'SSF',
800 'contribution_status_id' => 1,
801 'note' => 'my contribution note',
802 ];
803
804 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__, __FILE__, $description, $subfile);
805 $result = $this->callAPISuccess('note', 'get', [
806 'entity_table' => 'civicrm_contribution',
807 'entity_id' => $contribution['id'],
808 'sequential' => 1,
809 ]);
810 $this->assertEquals('my contribution note', $result['values'][0]['note']);
811 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
812 }
813
814 public function testCreateContributionWithNoteUniqueNameAliases() {
815 $params = [
816 'contact_id' => $this->_individualId,
817 'receive_date' => '2012-01-01',
818 'total_amount' => 100.00,
819 'financial_type_id' => $this->_financialTypeId,
820 'payment_instrument_id' => 1,
821 'non_deductible_amount' => 10.00,
822 'fee_amount' => 50.00,
823 'net_amount' => 90.00,
824 'trxn_id' => 12345,
825 'invoice_id' => 67890,
826 'source' => 'SSF',
827 'contribution_status_id' => 1,
828 'contribution_note' => 'my contribution note',
829 ];
830
831 $contribution = $this->callAPISuccess('contribution', 'create', $params);
832 $result = $this->callAPISuccess('note', 'get', [
833 'entity_table' => 'civicrm_contribution',
834 'entity_id' => $contribution['id'],
835 'sequential' => 1,
836 ]);
837 $this->assertEquals('my contribution note', $result['values'][0]['note']);
838 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
839 }
840
841 /**
842 * This is the test for creating soft credits.
843 */
844 public function testCreateContributionWithSoftCredit() {
845 $description = "Demonstrates creating contribution with SoftCredit.";
846 $subfile = "ContributionCreateWithSoftCredit";
847 $contact2 = $this->callAPISuccess('Contact', 'create', [
848 'display_name' => 'superman',
849 'contact_type' => 'Individual',
850 ]);
851 $softParams = [
852 'contact_id' => $contact2['id'],
853 'amount' => 50,
854 'soft_credit_type_id' => 3,
855 ];
856
857 $params = $this->_params + ['soft_credit' => [1 => $softParams]];
858 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__, __FILE__, $description, $subfile);
859 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
860
861 $this->assertEquals($softParams['contact_id'], $result['values'][0]['soft_credit'][1]['contact_id']);
862 $this->assertEquals($softParams['amount'], $result['values'][0]['soft_credit'][1]['amount']);
863 $this->assertEquals($softParams['soft_credit_type_id'], $result['values'][0]['soft_credit'][1]['soft_credit_type']);
864
865 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
866 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
867 }
868
869 public function testCreateContributionWithSoftCreditDefaults() {
870 $description = "Demonstrates creating contribution with Soft Credit defaults for amount and type.";
871 $subfile = "ContributionCreateWithSoftCreditDefaults";
872 $contact2 = $this->callAPISuccess('Contact', 'create', [
873 'display_name' => 'superman',
874 'contact_type' => 'Individual',
875 ]);
876 $params = $this->_params + [
877 'soft_credit_to' => $contact2['id'],
878 ];
879 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__, __FILE__, $description, $subfile);
880 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
881
882 $this->assertEquals($contact2['id'], $result['values'][0]['soft_credit'][1]['contact_id']);
883 // Default soft credit amount = contribution.total_amount
884 $this->assertEquals($this->_params['total_amount'], $result['values'][0]['soft_credit'][1]['amount']);
885 $this->assertEquals(CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"), $result['values'][0]['soft_credit'][1]['soft_credit_type']);
886
887 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
888 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
889 }
890
891 /**
892 * Test creating contribution with Soft Credit by passing in honor_contact_id.
893 */
894 public function testCreateContributionWithHonoreeContact() {
895 $description = "Demonstrates creating contribution with Soft Credit by passing in honor_contact_id.";
896 $subfile = "ContributionCreateWithHonoreeContact";
897 $contact2 = $this->callAPISuccess('Contact', 'create', [
898 'display_name' => 'superman',
899 'contact_type' => 'Individual',
900 ]);
901 $params = $this->_params + [
902 'honor_contact_id' => $contact2['id'],
903 ];
904 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__, __FILE__, $description, $subfile);
905 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
906
907 $this->assertEquals($contact2['id'], $result['values'][0]['soft_credit'][1]['contact_id']);
908 // Default soft credit amount = contribution.total_amount
909 // Legacy mode in create api (honor_contact_id param) uses the standard "In Honor of" soft credit type
910 $this->assertEquals($this->_params['total_amount'], $result['values'][0]['soft_credit'][1]['amount']);
911 $softCreditValueTypeID = $result['values'][0]['soft_credit'][1]['soft_credit_type'];
912 $this->assertEquals('in_honor_of', CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $softCreditValueTypeID));
913
914 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
915 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
916 }
917
918 /**
919 * Test using example code.
920 */
921 public function testContributionCreateExample() {
922 //make sure at least on page exists since there is a truncate in tear down
923 $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
924 require_once 'api/v3/examples/Contribution/Create.php';
925 $result = contribution_create_example();
926 $id = $result['id'];
927 $expectedResult = contribution_create_expectedresult();
928 $this->checkArrayEquals($expectedResult, $result);
929 $this->contributionDelete($id);
930 }
931
932 /**
933 * Function tests that additional financial records are created when fee amount is recorded.
934 */
935 public function testCreateContributionWithFee() {
936 $params = [
937 'contact_id' => $this->_individualId,
938 'receive_date' => '20120511',
939 'total_amount' => 100.00,
940 'fee_amount' => 50,
941 'financial_type_id' => 1,
942 'trxn_id' => 12345,
943 'invoice_id' => 67890,
944 'source' => 'SSF',
945 'contribution_status_id' => 1,
946 ];
947
948 $contribution = $this->callAPISuccess('contribution', 'create', $params);
949 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId);
950 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
951 $this->assertEquals($contribution['values'][$contribution['id']]['fee_amount'], 50.00);
952 $this->assertEquals($contribution['values'][$contribution['id']]['net_amount'], 50.00);
953 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
954 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
955 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
956 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
957 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 1);
958
959 $lineItems = $this->callAPISuccess('line_item', 'get', [
960
961 'entity_id' => $contribution['id'],
962 'entity_table' => 'civicrm_contribution',
963 'sequential' => 1,
964 ]);
965 $this->assertEquals(1, $lineItems['count']);
966 $this->assertEquals($contribution['id'], $lineItems['values'][0]['entity_id']);
967 $this->assertEquals($contribution['id'], $lineItems['values'][0]['contribution_id']);
968 $lineItems = $this->callAPISuccess('line_item', 'get', [
969
970 'entity_id' => $contribution['id'],
971 'contribution_id' => $contribution['id'],
972 'entity_table' => 'civicrm_contribution',
973 'sequential' => 1,
974 ]);
975 $this->assertEquals(1, $lineItems['count']);
976 $this->_checkFinancialRecords($contribution, 'feeAmount');
977 }
978
979 /**
980 * Function tests that additional financial records are created when online contribution is created.
981 */
982 public function testCreateContributionOnline() {
983 CRM_Financial_BAO_PaymentProcessor::create($this->_processorParams);
984 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
985 $this->assertAPISuccess($contributionPage);
986 $params = [
987 'contact_id' => $this->_individualId,
988 'receive_date' => '20120511',
989 'total_amount' => 100.00,
990 'financial_type_id' => 1,
991 'contribution_page_id' => $contributionPage['id'],
992 'payment_processor' => $this->paymentProcessorID,
993 'trxn_id' => 12345,
994 'invoice_id' => 67890,
995 'source' => 'SSF',
996 'contribution_status_id' => 1,
997
998 ];
999
1000 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1001 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId);
1002 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1003 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1004 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1005 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1006 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1007 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 1);
1008 $contribution['payment_instrument_id'] = $this->callAPISuccessGetValue('PaymentProcessor', [
1009 'id' => $this->paymentProcessorID,
1010 'return' => 'payment_instrument_id',
1011 ]);
1012 $this->_checkFinancialRecords($contribution, 'online');
1013 }
1014
1015 /**
1016 * Check handling of financial type.
1017 *
1018 * In the interests of removing financial type / contribution type checks from
1019 * legacy format function lets test that the api is doing this for us
1020 */
1021 public function testCreateInvalidFinancialType() {
1022 $params = $this->_params;
1023 $params['financial_type_id'] = 99999;
1024 $this->callAPIFailure($this->_entity, 'create', $params, "'99999' is not a valid option for field financial_type_id");
1025 }
1026
1027 /**
1028 * Check handling of financial type.
1029 *
1030 * In the interests of removing financial type / contribution type checks from
1031 * legacy format function lets test that the api is doing this for us
1032 */
1033 public function testValidNamedFinancialType() {
1034 $params = $this->_params;
1035 $params['financial_type_id'] = 'Donation';
1036 $this->callAPISuccess($this->_entity, 'create', $params);
1037 }
1038
1039 /**
1040 * Tests that additional financial records are created.
1041 *
1042 * Checks when online contribution with pay later option is created
1043 */
1044 public function testCreateContributionPayLaterOnline() {
1045 CRM_Financial_BAO_PaymentProcessor::create($this->_processorParams);
1046 $this->_pageParams['is_pay_later'] = 1;
1047 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
1048 $this->assertAPISuccess($contributionPage);
1049 $params = [
1050 'contact_id' => $this->_individualId,
1051 'receive_date' => '20120511',
1052 'total_amount' => 100.00,
1053 'financial_type_id' => 1,
1054 'contribution_page_id' => $contributionPage['id'],
1055 'trxn_id' => 12345,
1056 'is_pay_later' => 1,
1057 'invoice_id' => 67890,
1058 'source' => 'SSF',
1059 'contribution_status_id' => 2,
1060
1061 ];
1062
1063 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__, __FILE__);
1064 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId);
1065 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1066 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1067 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1068 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1069 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1070 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 2);
1071 $this->_checkFinancialRecords($contribution, 'payLater');
1072 }
1073
1074 /**
1075 * Function tests that additional financial records are created for online contribution with pending option.
1076 */
1077 public function testCreateContributionPendingOnline() {
1078 CRM_Financial_BAO_PaymentProcessor::create($this->_processorParams);
1079 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
1080 $this->assertAPISuccess($contributionPage);
1081 $params = [
1082 'contact_id' => $this->_individualId,
1083 'receive_date' => '20120511',
1084 'total_amount' => 100.00,
1085 'financial_type_id' => 1,
1086 'contribution_page_id' => $contributionPage['id'],
1087 'trxn_id' => 12345,
1088 'invoice_id' => 67890,
1089 'source' => 'SSF',
1090 'contribution_status_id' => 2,
1091 ];
1092
1093 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1094 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId);
1095 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1096 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1097 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1098 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1099 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1100 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 2);
1101 $this->_checkFinancialRecords($contribution, 'pending');
1102 }
1103
1104 /**
1105 * Test that BAO defaults work.
1106 */
1107 public function testCreateBAODefaults() {
1108 unset($this->_params['contribution_source_id'], $this->_params['payment_instrument_id']);
1109 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
1110 $contribution = $this->callAPISuccess('contribution', 'getsingle', [
1111 'id' => $contribution['id'],
1112 'api.contribution.delete' => 1,
1113 ]);
1114 $this->assertEquals(1, $contribution['contribution_status_id']);
1115 $this->assertEquals('Check', $contribution['payment_instrument']);
1116 $this->callAPISuccessGetCount('Contribution', ['id' => $contribution['id']], 0);
1117 }
1118
1119 /**
1120 * Test that getsingle can be chained with delete.
1121 */
1122 public function testDeleteChainedGetSingle() {
1123 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
1124 $contribution = $this->callAPISuccess('contribution', 'getsingle', [
1125 'id' => $contribution['id'],
1126 'api.contribution.delete' => 1,
1127 ]);
1128 $this->callAPISuccessGetCount('Contribution', ['id' => $contribution['id']], 0);
1129 }
1130
1131 /**
1132 * Function tests that line items, financial records are updated when contribution amount is changed.
1133 */
1134 public function testCreateUpdateContributionChangeTotal() {
1135 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
1136 $lineItems = $this->callAPISuccess('line_item', 'getvalue', [
1137
1138 'entity_id' => $contribution['id'],
1139 'entity_table' => 'civicrm_contribution',
1140 'sequential' => 1,
1141 'return' => 'line_total',
1142 ]);
1143 $this->assertEquals('100.00', $lineItems);
1144 $trxnAmount = $this->_getFinancialTrxnAmount($contribution['id']);
1145 // Financial trxn SUM = 100 + 5 (fee)
1146 $this->assertEquals('105.00', $trxnAmount);
1147 $newParams = [
1148
1149 'id' => $contribution['id'],
1150 'total_amount' => '125',
1151 ];
1152 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1153
1154 $lineItems = $this->callAPISuccess('line_item', 'getvalue', [
1155
1156 'entity_id' => $contribution['id'],
1157 'entity_table' => 'civicrm_contribution',
1158 'sequential' => 1,
1159 'return' => 'line_total',
1160 ]);
1161
1162 $this->assertEquals('125.00', $lineItems);
1163 $trxnAmount = $this->_getFinancialTrxnAmount($contribution['id']);
1164
1165 // Financial trxn SUM = 125 + 5 (fee).
1166 $this->assertEquals('130.00', $trxnAmount);
1167 $this->assertEquals('125.00', $this->_getFinancialItemAmount($contribution['id']));
1168 }
1169
1170 /**
1171 * Function tests that line items, financial records are updated when pay later contribution is received.
1172 */
1173 public function testCreateUpdateContributionPayLater() {
1174 $contribParams = [
1175 'contact_id' => $this->_individualId,
1176 'receive_date' => '2012-01-01',
1177 'total_amount' => 100.00,
1178 'financial_type_id' => $this->_financialTypeId,
1179 'payment_instrument_id' => 1,
1180 'contribution_status_id' => 2,
1181 'is_pay_later' => 1,
1182
1183 ];
1184 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1185
1186 $newParams = array_merge($contribParams, [
1187 'id' => $contribution['id'],
1188 'contribution_status_id' => 1,
1189 ]);
1190 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1191 $contribution = $contribution['values'][$contribution['id']];
1192 $this->assertEquals($contribution['contribution_status_id'], '1');
1193 $this->_checkFinancialItem($contribution['id'], 'paylater');
1194 $this->_checkFinancialTrxn($contribution, 'payLater');
1195 }
1196
1197 /**
1198 * Function tests that financial records are updated when Payment Instrument is changed.
1199 */
1200 public function testCreateUpdateContributionPaymentInstrument() {
1201 $instrumentId = $this->_addPaymentInstrument();
1202 $contribParams = [
1203 'contact_id' => $this->_individualId,
1204 'total_amount' => 100.00,
1205 'financial_type_id' => $this->_financialTypeId,
1206 'payment_instrument_id' => 4,
1207 'contribution_status_id' => 1,
1208
1209 ];
1210 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1211
1212 $newParams = array_merge($contribParams, [
1213 'id' => $contribution['id'],
1214 'payment_instrument_id' => $instrumentId,
1215 ]);
1216 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1217 $this->assertAPISuccess($contribution);
1218 $this->checkFinancialTrxnPaymentInstrumentChange($contribution['id'], 4, $instrumentId);
1219
1220 // cleanup - delete created payment instrument
1221 $this->_deletedAddedPaymentInstrument();
1222 }
1223
1224 /**
1225 * Function tests that financial records are updated when Payment Instrument is changed when amount is negative.
1226 */
1227 public function testCreateUpdateNegativeContributionPaymentInstrument() {
1228 $instrumentId = $this->_addPaymentInstrument();
1229 $contribParams = [
1230 'contact_id' => $this->_individualId,
1231 'total_amount' => -100.00,
1232 'financial_type_id' => $this->_financialTypeId,
1233 'payment_instrument_id' => 4,
1234 'contribution_status_id' => 1,
1235
1236 ];
1237 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1238
1239 $newParams = array_merge($contribParams, [
1240 'id' => $contribution['id'],
1241 'payment_instrument_id' => $instrumentId,
1242 ]);
1243 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1244 $this->assertAPISuccess($contribution);
1245 $this->checkFinancialTrxnPaymentInstrumentChange($contribution['id'], 4, $instrumentId, -100);
1246
1247 // cleanup - delete created payment instrument
1248 $this->_deletedAddedPaymentInstrument();
1249 }
1250
1251 /**
1252 * Function tests that financial records are added when Contribution is Refunded.
1253 */
1254 public function testCreateUpdateContributionRefund() {
1255 $contributionParams = [
1256 'contact_id' => $this->_individualId,
1257 'receive_date' => '2012-01-01',
1258 'total_amount' => 100.00,
1259 'financial_type_id' => $this->_financialTypeId,
1260 'payment_instrument_id' => 4,
1261 'contribution_status_id' => 1,
1262 'trxn_id' => 'original_payment',
1263 ];
1264 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1265 $newParams = array_merge($contributionParams, [
1266 'id' => $contribution['id'],
1267 'contribution_status_id' => 'Refunded',
1268 'cancel_date' => '2015-01-01 09:00',
1269 'refund_trxn_id' => 'the refund',
1270 ]);
1271
1272 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1273 $this->_checkFinancialTrxn($contribution, 'refund');
1274 $this->_checkFinancialItem($contribution['id'], 'refund');
1275 $this->assertEquals('original_payment', $this->callAPISuccessGetValue('Contribution', [
1276 'id' => $contribution['id'],
1277 'return' => 'trxn_id',
1278 ]));
1279 }
1280
1281 /**
1282 * Refund a contribution for a financial type with a contra account.
1283 *
1284 * CRM-17951 the contra account is a financial account with a relationship to a
1285 * financial type. It is not always configured but should be reflected
1286 * in the financial_trxn & financial_item table if it is.
1287 */
1288 public function testCreateUpdateChargebackContributionDefaultAccount() {
1289 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params);
1290 $this->callAPISuccess('Contribution', 'create', [
1291 'id' => $contribution['id'],
1292 'contribution_status_id' => 'Chargeback',
1293 ]);
1294 $this->callAPISuccessGetSingle('Contribution', ['contribution_status_id' => 'Chargeback']);
1295
1296 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1297 'contribution_id' => $contribution['id'],
1298 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1299 ]);
1300 $this->assertEquals(1, $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1301 $this->callAPISuccessGetSingle('FinancialTrxn', [
1302 'total_amount' => -100,
1303 'status_id' => 'Chargeback',
1304 'to_financial_account_id' => 6,
1305 ]);
1306 }
1307
1308 /**
1309 * Refund a contribution for a financial type with a contra account.
1310 *
1311 * CRM-17951 the contra account is a financial account with a relationship to a
1312 * financial type. It is not always configured but should be reflected
1313 * in the financial_trxn & financial_item table if it is.
1314 */
1315 public function testCreateUpdateChargebackContributionCustomAccount() {
1316 $financialAccount = $this->callAPISuccess('FinancialAccount', 'create', [
1317 'name' => 'Chargeback Account',
1318 'is_active' => TRUE,
1319 ]);
1320
1321 $entityFinancialAccount = $this->callAPISuccess('EntityFinancialAccount', 'create', [
1322 'entity_id' => $this->_financialTypeId,
1323 'entity_table' => 'civicrm_financial_type',
1324 'account_relationship' => 'Chargeback Account is',
1325 'financial_account_id' => 'Chargeback Account',
1326 ]);
1327
1328 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params);
1329 $this->callAPISuccess('Contribution', 'create', [
1330 'id' => $contribution['id'],
1331 'contribution_status_id' => 'Chargeback',
1332 ]);
1333 $this->callAPISuccessGetSingle('Contribution', ['contribution_status_id' => 'Chargeback']);
1334
1335 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1336 'contribution_id' => $contribution['id'],
1337 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1338 ]);
1339 $this->assertEquals($financialAccount['id'], $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1340
1341 $this->callAPISuccess('Contribution', 'delete', ['id' => $contribution['id']]);
1342 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialAccount['id']]);
1343 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
1344 }
1345
1346 /**
1347 * Refund a contribution for a financial type with a contra account.
1348 *
1349 * CRM-17951 the contra account is a financial account with a relationship to a
1350 * financial type. It is not always configured but should be reflected
1351 * in the financial_trxn & financial_item table if it is.
1352 */
1353 public function testCreateUpdateRefundContributionConfiguredContraAccount() {
1354 $financialAccount = $this->callAPISuccess('FinancialAccount', 'create', [
1355 'name' => 'Refund Account',
1356 'is_active' => TRUE,
1357 ]);
1358
1359 $entityFinancialAccount = $this->callAPISuccess('EntityFinancialAccount', 'create', [
1360 'entity_id' => $this->_financialTypeId,
1361 'entity_table' => 'civicrm_financial_type',
1362 'account_relationship' => 'Credit/Contra Revenue Account is',
1363 'financial_account_id' => 'Refund Account',
1364 ]);
1365
1366 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params);
1367 $this->callAPISuccess('Contribution', 'create', [
1368 'id' => $contribution['id'],
1369 'contribution_status_id' => 'Refunded',
1370 ]);
1371
1372 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1373 'contribution_id' => $contribution['id'],
1374 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1375 ]);
1376 $this->assertEquals($financialAccount['id'], $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1377
1378 $this->callAPISuccess('Contribution', 'delete', ['id' => $contribution['id']]);
1379 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialAccount['id']]);
1380 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
1381 }
1382
1383 /**
1384 * Function tests that trxn_id is set when passed in.
1385 *
1386 * Here we ensure that the civicrm_financial_trxn.trxn_id & the civicrm_contribution.trxn_id are set
1387 * when trxn_id is passed in.
1388 */
1389 public function testCreateUpdateContributionRefundTrxnIDPassedIn() {
1390 $contributionParams = [
1391 'contact_id' => $this->_individualId,
1392 'receive_date' => '2012-01-01',
1393 'total_amount' => 100.00,
1394 'financial_type_id' => $this->_financialTypeId,
1395 'payment_instrument_id' => 4,
1396 'contribution_status_id' => 1,
1397 'trxn_id' => 'original_payment',
1398 ];
1399 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1400 $newParams = array_merge($contributionParams, [
1401 'id' => $contribution['id'],
1402 'contribution_status_id' => 'Refunded',
1403 'cancel_date' => '2015-01-01 09:00',
1404 'trxn_id' => 'the refund',
1405 ]);
1406
1407 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1408 $this->_checkFinancialTrxn($contribution, 'refund');
1409 $this->_checkFinancialItem($contribution['id'], 'refund');
1410 $this->assertEquals('the refund', $this->callAPISuccessGetValue('Contribution', [
1411 'id' => $contribution['id'],
1412 'return' => 'trxn_id',
1413 ]));
1414 }
1415
1416 /**
1417 * Function tests that trxn_id is set when passed in.
1418 *
1419 * Here we ensure that the civicrm_contribution.trxn_id is set
1420 * when trxn_id is passed in but if refund_trxn_id is different then that
1421 * is kept for the refund transaction.
1422 */
1423 public function testCreateUpdateContributionRefundRefundAndTrxnIDPassedIn() {
1424 $contributionParams = [
1425 'contact_id' => $this->_individualId,
1426 'receive_date' => '2012-01-01',
1427 'total_amount' => 100.00,
1428 'financial_type_id' => $this->_financialTypeId,
1429 'payment_instrument_id' => 4,
1430 'contribution_status_id' => 1,
1431 'trxn_id' => 'original_payment',
1432 ];
1433 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1434 $newParams = array_merge($contributionParams, [
1435 'id' => $contribution['id'],
1436 'contribution_status_id' => 'Refunded',
1437 'cancel_date' => '2015-01-01 09:00',
1438 'trxn_id' => 'cont id',
1439 'refund_trxn_id' => 'the refund',
1440 ]);
1441
1442 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1443 $this->_checkFinancialTrxn($contribution, 'refund');
1444 $this->_checkFinancialItem($contribution['id'], 'refund');
1445 $this->assertEquals('cont id', $this->callAPISuccessGetValue('Contribution', [
1446 'id' => $contribution['id'],
1447 'return' => 'trxn_id',
1448 ]));
1449 }
1450
1451 /**
1452 * Function tests that refund_trxn_id is set when passed in empty.
1453 *
1454 * Here we ensure that the civicrm_contribution.trxn_id is set
1455 * when trxn_id is passed in but if refund_trxn_id isset but empty then that
1456 * is kept for the refund transaction.
1457 */
1458 public function testCreateUpdateContributionRefundRefundNullTrxnIDPassedIn() {
1459 $contributionParams = [
1460 'contact_id' => $this->_individualId,
1461 'receive_date' => '2012-01-01',
1462 'total_amount' => 100.00,
1463 'financial_type_id' => $this->_financialTypeId,
1464 'payment_instrument_id' => 4,
1465 'contribution_status_id' => 1,
1466 'trxn_id' => 'original_payment',
1467 ];
1468 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1469 $newParams = array_merge($contributionParams, [
1470 'id' => $contribution['id'],
1471 'contribution_status_id' => 'Refunded',
1472 'cancel_date' => '2015-01-01 09:00',
1473 'trxn_id' => 'cont id',
1474 'refund_trxn_id' => '',
1475 ]);
1476
1477 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1478 $this->_checkFinancialTrxn($contribution, 'refund', NULL, ['trxn_id' => NULL]);
1479 $this->_checkFinancialItem($contribution['id'], 'refund');
1480 $this->assertEquals('cont id', $this->callAPISuccessGetValue('Contribution', [
1481 'id' => $contribution['id'],
1482 'return' => 'trxn_id',
1483 ]));
1484 }
1485
1486 /**
1487 * Function tests invalid contribution status change.
1488 */
1489 public function testCreateUpdateContributionInValidStatusChange() {
1490 $contribParams = [
1491 'contact_id' => 1,
1492 'receive_date' => '2012-01-01',
1493 'total_amount' => 100.00,
1494 'financial_type_id' => 1,
1495 'payment_instrument_id' => 1,
1496 'contribution_status_id' => 1,
1497 ];
1498 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1499 $newParams = array_merge($contribParams, [
1500 'id' => $contribution['id'],
1501 'contribution_status_id' => 2,
1502 ]);
1503 $this->callAPIFailure('contribution', 'create', $newParams, ts('Cannot change contribution status from Completed to Pending.'));
1504
1505 }
1506
1507 /**
1508 * Function tests that financial records are added when Pending Contribution is Canceled.
1509 */
1510 public function testCreateUpdateContributionCancelPending() {
1511 $contribParams = [
1512 'contact_id' => $this->_individualId,
1513 'receive_date' => '2012-01-01',
1514 'total_amount' => 100.00,
1515 'financial_type_id' => $this->_financialTypeId,
1516 'payment_instrument_id' => 1,
1517 'contribution_status_id' => 2,
1518 'is_pay_later' => 1,
1519
1520 ];
1521 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1522 $newParams = array_merge($contribParams, [
1523 'id' => $contribution['id'],
1524 'contribution_status_id' => 3,
1525 'cancel_date' => '2012-02-02 09:00',
1526 ]);
1527 //Check if trxn_date is same as cancel_date.
1528 $checkTrxnDate = [
1529 'trxn_date' => '2012-02-02 09:00:00',
1530 ];
1531 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1532 $this->_checkFinancialTrxn($contribution, 'cancelPending', NULL, $checkTrxnDate);
1533 $this->_checkFinancialItem($contribution['id'], 'cancelPending');
1534 }
1535
1536 /**
1537 * Function tests that financial records are added when Financial Type is Changed.
1538 */
1539 public function testCreateUpdateContributionChangeFinancialType() {
1540 $contribParams = [
1541 'contact_id' => $this->_individualId,
1542 'receive_date' => '2012-01-01',
1543 'total_amount' => 100.00,
1544 'financial_type_id' => 1,
1545 'payment_instrument_id' => 1,
1546 'contribution_status_id' => 1,
1547
1548 ];
1549 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1550 $newParams = array_merge($contribParams, [
1551 'id' => $contribution['id'],
1552 'financial_type_id' => 3,
1553 ]);
1554 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1555 $this->_checkFinancialTrxn($contribution, 'changeFinancial');
1556 $this->_checkFinancialItem($contribution['id'], 'changeFinancial');
1557 }
1558
1559 /**
1560 * Test that update does not change status id CRM-15105.
1561 */
1562 public function testCreateUpdateWithoutChangingPendingStatus() {
1563 $contribution = $this->callAPISuccess('contribution', 'create', array_merge($this->_params, ['contribution_status_id' => 2]));
1564 $this->callAPISuccess('contribution', 'create', ['id' => $contribution['id'], 'source' => 'new source']);
1565 $contribution = $this->callAPISuccess('contribution', 'getsingle', [
1566 'id' => $contribution['id'],
1567 'api.contribution.delete' => 1,
1568 ]);
1569 $this->assertEquals(2, $contribution['contribution_status_id']);
1570 }
1571
1572 /**
1573 * Test Updating a Contribution.
1574 *
1575 * CHANGE: we require the API to do an incremental update
1576 */
1577 public function testCreateUpdateContribution() {
1578 $contributionID = $this->contributionCreate([
1579 'contact_id' => $this->_individualId,
1580 'trxn_id' => 212355,
1581 'financial_type_id' => $this->_financialTypeId,
1582 'invoice_id' => 'old_invoice',
1583 ]);
1584 $old_params = [
1585 'contribution_id' => $contributionID,
1586 ];
1587 $original = $this->callAPISuccess('contribution', 'get', $old_params);
1588 $this->assertEquals($original['id'], $contributionID);
1589 //set up list of old params, verify
1590
1591 //This should not be required on update:
1592 $old_contact_id = $original['values'][$contributionID]['contact_id'];
1593 $old_payment_instrument = $original['values'][$contributionID]['instrument_id'];
1594 $old_fee_amount = $original['values'][$contributionID]['fee_amount'];
1595 $old_source = $original['values'][$contributionID]['contribution_source'];
1596
1597 $old_trxn_id = $original['values'][$contributionID]['trxn_id'];
1598 $old_invoice_id = $original['values'][$contributionID]['invoice_id'];
1599
1600 //check against values in CiviUnitTestCase::createContribution()
1601 $this->assertEquals($old_contact_id, $this->_individualId);
1602 $this->assertEquals($old_fee_amount, 5.00);
1603 $this->assertEquals($old_source, 'SSF');
1604 $this->assertEquals($old_trxn_id, 212355);
1605 $this->assertEquals($old_invoice_id, 'old_invoice');
1606 $params = [
1607 'id' => $contributionID,
1608 'contact_id' => $this->_individualId,
1609 'total_amount' => 105.00,
1610 'fee_amount' => 7.00,
1611 'financial_type_id' => $this->_financialTypeId,
1612 'non_deductible_amount' => 22.00,
1613 'contribution_status_id' => 1,
1614 'note' => 'Donating for Noble Cause',
1615 ];
1616
1617 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1618
1619 $new_params = [
1620 'contribution_id' => $contribution['id'],
1621 ];
1622 $contribution = $this->callAPISuccessGetSingle('contribution', $new_params);
1623
1624 $this->assertEquals($contribution['contact_id'], $this->_individualId);
1625 $this->assertEquals($contribution['total_amount'], 105.00);
1626 $this->assertEquals($contribution['financial_type_id'], $this->_financialTypeId);
1627 $this->assertEquals($contribution['financial_type'], 'Donation');
1628 $this->assertEquals($contribution['instrument_id'], $old_payment_instrument);
1629 $this->assertEquals($contribution['non_deductible_amount'], 22.00);
1630 $this->assertEquals($contribution['fee_amount'], 7.00);
1631 $this->assertEquals($contribution['trxn_id'], $old_trxn_id);
1632 $this->assertEquals($contribution['invoice_id'], $old_invoice_id);
1633 $this->assertEquals($contribution['contribution_source'], $old_source);
1634 $this->assertEquals($contribution['contribution_status'], 'Completed');
1635
1636 $this->assertEquals($contribution['net_amount'], $contribution['total_amount'] - $contribution['fee_amount']);
1637
1638 $params = [
1639 'contribution_id' => $contributionID,
1640 ];
1641 $result = $this->callAPISuccess('contribution', 'delete', $params);
1642 $this->assertAPISuccess($result);
1643 }
1644
1645 /**
1646 * Check that net_amount is updated when a contribution is updated.
1647 *
1648 * Update fee amount AND total amount, just fee amount, just total amount
1649 * and neither to check that net_amount is keep updated.
1650 */
1651 public function testUpdateContributionNetAmountVariants() {
1652 $contributionID = $this->contributionCreate(['contact_id' => $this->individualCreate()]);
1653
1654 $this->callAPISuccess('Contribution', 'create', [
1655 'id' => $contributionID,
1656 'total_amount' => 90,
1657 'fee_amount' => 6,
1658 ]);
1659 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1660 'id' => $contributionID,
1661 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1662 ]);
1663 $this->assertEquals(6, $contribution['fee_amount']);
1664 $this->assertEquals(90, $contribution['total_amount']);
1665 $this->assertEquals(84, $contribution['net_amount']);
1666
1667 $this->callAPISuccess('Contribution', 'create', [
1668 'id' => $contributionID,
1669 'fee_amount' => 3,
1670 ]);
1671 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1672 'id' => $contributionID,
1673 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1674 ]);
1675 $this->assertEquals(3, $contribution['fee_amount']);
1676 $this->assertEquals(90, $contribution['total_amount']);
1677 $this->assertEquals(87, $contribution['net_amount']);
1678
1679 $this->callAPISuccess('Contribution', 'create', [
1680 'id' => $contributionID,
1681 'total_amount' => 200,
1682 ]);
1683 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1684 'id' => $contributionID,
1685 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1686 ]);
1687 $this->assertEquals(3, $contribution['fee_amount']);
1688 $this->assertEquals(200, $contribution['total_amount']);
1689 $this->assertEquals(197, $contribution['net_amount']);
1690
1691 $this->callAPISuccess('Contribution', 'create', [
1692 'id' => $contributionID,
1693 'payment_instrument' => 'Cash',
1694 ]);
1695 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1696 'id' => $contributionID,
1697 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1698 ]);
1699 $this->assertEquals(3, $contribution['fee_amount']);
1700 $this->assertEquals(200, $contribution['total_amount']);
1701 $this->assertEquals(197, $contribution['net_amount']);
1702 }
1703
1704 /**
1705 * Attempt (but fail) to delete a contribution without parameters.
1706 */
1707 public function testDeleteEmptyParamsContribution() {
1708 $params = [];
1709 $this->callAPIFailure('contribution', 'delete', $params);
1710 }
1711
1712 public function testDeleteParamsNotArrayContribution() {
1713 $params = 'contribution_id= 1';
1714 $contribution = $this->callAPIFailure('contribution', 'delete', $params);
1715 $this->assertEquals($contribution['error_message'], 'Input variable `params` is not an array');
1716 }
1717
1718 public function testDeleteWrongParamContribution() {
1719 $params = [
1720 'contribution_source' => 'SSF',
1721 ];
1722 $this->callAPIFailure('contribution', 'delete', $params);
1723 }
1724
1725 public function testDeleteContribution() {
1726 $contributionID = $this->contributionCreate([
1727 'contact_id' => $this->_individualId,
1728 'financial_type_id' => $this->_financialTypeId,
1729 ]);
1730 $params = [
1731 'id' => $contributionID,
1732 ];
1733 $this->callAPIAndDocument('contribution', 'delete', $params, __FUNCTION__, __FILE__);
1734 }
1735
1736 /**
1737 * Test civicrm_contribution_search with empty params.
1738 *
1739 * All available contributions expected.
1740 */
1741 public function testSearchEmptyParams() {
1742 $params = [];
1743
1744 $p = [
1745 'contact_id' => $this->_individualId,
1746 'receive_date' => date('Ymd'),
1747 'total_amount' => 100.00,
1748 'financial_type_id' => $this->_financialTypeId,
1749 'non_deductible_amount' => 10.00,
1750 'fee_amount' => 5.00,
1751 'net_amount' => 95.00,
1752 'trxn_id' => 23456,
1753 'invoice_id' => 78910,
1754 'source' => 'SSF',
1755 'contribution_status_id' => 1,
1756 ];
1757 $contribution = $this->callAPISuccess('contribution', 'create', $p);
1758
1759 $result = $this->callAPISuccess('contribution', 'get', $params);
1760 // We're taking the first element.
1761 $res = $result['values'][$contribution['id']];
1762
1763 $this->assertEquals($p['contact_id'], $res['contact_id']);
1764 $this->assertEquals($p['total_amount'], $res['total_amount']);
1765 $this->assertEquals($p['financial_type_id'], $res['financial_type_id']);
1766 $this->assertEquals($p['net_amount'], $res['net_amount']);
1767 $this->assertEquals($p['non_deductible_amount'], $res['non_deductible_amount']);
1768 $this->assertEquals($p['fee_amount'], $res['fee_amount']);
1769 $this->assertEquals($p['trxn_id'], $res['trxn_id']);
1770 $this->assertEquals($p['invoice_id'], $res['invoice_id']);
1771 $this->assertEquals($p['source'], $res['contribution_source']);
1772 // contribution_status_id = 1 => Completed
1773 $this->assertEquals('Completed', $res['contribution_status']);
1774
1775 $this->contributionDelete($contribution['id']);
1776 }
1777
1778 /**
1779 * Test civicrm_contribution_search. Success expected.
1780 */
1781 public function testSearch() {
1782 $p1 = [
1783 'contact_id' => $this->_individualId,
1784 'receive_date' => date('Ymd'),
1785 'total_amount' => 100.00,
1786 'financial_type_id' => $this->_financialTypeId,
1787 'non_deductible_amount' => 10.00,
1788 'contribution_status_id' => 1,
1789 ];
1790 $contribution1 = $this->callAPISuccess('contribution', 'create', $p1);
1791
1792 $p2 = [
1793 'contact_id' => $this->_individualId,
1794 'receive_date' => date('Ymd'),
1795 'total_amount' => 200.00,
1796 'financial_type_id' => $this->_financialTypeId,
1797 'non_deductible_amount' => 20.00,
1798 'trxn_id' => 5454565,
1799 'invoice_id' => 1212124,
1800 'fee_amount' => 50.00,
1801 'net_amount' => 60.00,
1802 'contribution_status_id' => 2,
1803 ];
1804 $contribution2 = $this->callAPISuccess('contribution', 'create', $p2);
1805
1806 $params = [
1807 'contribution_id' => $contribution2['id'],
1808 ];
1809 $result = $this->callAPISuccess('contribution', 'get', $params);
1810 $res = $result['values'][$contribution2['id']];
1811
1812 $this->assertEquals($p2['contact_id'], $res['contact_id']);
1813 $this->assertEquals($p2['total_amount'], $res['total_amount']);
1814 $this->assertEquals($p2['financial_type_id'], $res['financial_type_id']);
1815 $this->assertEquals($p2['net_amount'], $res['net_amount']);
1816 $this->assertEquals($p2['non_deductible_amount'], $res['non_deductible_amount']);
1817 $this->assertEquals($p2['fee_amount'], $res['fee_amount']);
1818 $this->assertEquals($p2['trxn_id'], $res['trxn_id']);
1819 $this->assertEquals($p2['invoice_id'], $res['invoice_id']);
1820 // contribution_status_id = 2 => Pending
1821 $this->assertEquals('Pending', $res['contribution_status']);
1822
1823 $this->contributionDelete($contribution1['id']);
1824 $this->contributionDelete($contribution2['id']);
1825 }
1826
1827 /**
1828 * Test completing a transaction via the API.
1829 *
1830 * Note that we are creating a logged in user because email goes out from
1831 * that person
1832 */
1833 public function testCompleteTransaction() {
1834 $mut = new CiviMailUtils($this, TRUE);
1835 $this->swapMessageTemplateForTestTemplate();
1836 $this->createLoggedInUser();
1837 $params = array_merge($this->_params, ['contribution_status_id' => 2]);
1838 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1839 $this->callAPISuccess('contribution', 'completetransaction', [
1840 'id' => $contribution['id'],
1841 ]);
1842 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
1843 $this->assertEquals('SSF', $contribution['contribution_source']);
1844 $this->assertEquals('Completed', $contribution['contribution_status']);
1845 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receipt_date'])));
1846 $mut->checkMailLog([
1847 'email:::anthony_anderson@civicrm.org',
1848 'is_monetary:::1',
1849 'amount:::100.00',
1850 'currency:::USD',
1851 'receive_date:::' . date('Ymd', strtotime($contribution['receive_date'])),
1852 "receipt_date:::\n",
1853 'contributeMode:::notify',
1854 'title:::Contribution',
1855 'displayName:::Mr. Anthony Anderson II',
1856 'contributionStatus:::Completed',
1857 ]);
1858 $mut->stop();
1859 $this->revertTemplateToReservedTemplate();
1860 }
1861
1862 /**
1863 * Test completing a transaction via the API with a non-USD transaction.
1864 */
1865 public function testCompleteTransactionEuro() {
1866 $mut = new CiviMailUtils($this, TRUE);
1867 $this->swapMessageTemplateForTestTemplate();
1868 $this->createLoggedInUser();
1869 $params = array_merge($this->_params, ['contribution_status_id' => 2, 'currency' => 'EUR']);
1870 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1871
1872 $this->callAPISuccess('contribution', 'completetransaction', [
1873 'id' => $contribution['id'],
1874 ]);
1875
1876 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
1877 $this->assertEquals('SSF', $contribution['contribution_source']);
1878 $this->assertEquals('Completed', $contribution['contribution_status']);
1879 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receipt_date'])));
1880
1881 $entityFinancialTransactions = $this->getFinancialTransactionsForContribution($contribution['id']);
1882 $entityFinancialTransaction = reset($entityFinancialTransactions);
1883 $financialTrxn = $this->callAPISuccessGetSingle('FinancialTrxn', ['id' => $entityFinancialTransaction['financial_trxn_id']]);
1884 $this->assertEquals('EUR', $financialTrxn['currency']);
1885
1886 $mut->checkMailLog([
1887 'email:::anthony_anderson@civicrm.org',
1888 'is_monetary:::1',
1889 'amount:::100.00',
1890 'currency:::EUR',
1891 'receive_date:::' . date('Ymd', strtotime($contribution['receive_date'])),
1892 "receipt_date:::\n",
1893 'contributeMode:::notify',
1894 'title:::Contribution',
1895 'displayName:::Mr. Anthony Anderson II',
1896 'contributionStatus:::Completed',
1897 ]);
1898 $mut->stop();
1899 $this->revertTemplateToReservedTemplate();
1900 }
1901
1902 /**
1903 * Test to ensure mail is sent on chosing pay later
1904 */
1905 public function testpayLater() {
1906 $mut = new CiviMailUtils($this, TRUE);
1907 $this->swapMessageTemplateForTestTemplate();
1908 $this->createLoggedInUser();
1909
1910 // create contribution page first
1911 $contributionPageParams = [
1912 'title' => 'Help Support CiviCRM!',
1913 'financial_type_id' => 1,
1914 'is_monetary' => TRUE,
1915 'is_pay_later' => 1,
1916 'is_quick_config' => TRUE,
1917 'pay_later_text' => 'I will send payment by check',
1918 'pay_later_receipt' => 'This is a pay later reciept',
1919 'is_allow_other_amount' => 1,
1920 'min_amount' => 10.00,
1921 'max_amount' => 10000.00,
1922 'goal_amount' => 100000.00,
1923 'is_email_receipt' => 1,
1924 'is_active' => 1,
1925 'amount_block_is_active' => 1,
1926 'currency' => 'USD',
1927 'is_billing_required' => 0,
1928 ];
1929 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', $contributionPageParams);
1930
1931 // submit form values
1932 $priceSet = $this->callAPISuccess('price_set', 'getsingle', ['name' => 'default_contribution_amount']);
1933 $params = [
1934 'id' => $contributionPageResult['id'],
1935 'contact_id' => $this->_individualId,
1936 'email-5' => 'anthony_anderson@civicrm.org',
1937 'payment_processor_id' => 0,
1938 'amount' => 100.00,
1939 'tax_amount' => '',
1940 'currencyID' => 'USD',
1941 'is_pay_later' => 1,
1942 'invoiceID' => 'f28e1ddc86f8c4a0ff5bcf46393e4bc8',
1943 'is_quick_config' => 1,
1944 'description' => 'Online Contribution: Help Support CiviCRM!',
1945 'price_set_id' => $priceSet['id'],
1946 ];
1947 $this->callAPISuccess('contribution_page', 'submit', $params);
1948
1949 $mut->checkMailLog([
1950 'is_pay_later:::1',
1951 'email:::anthony_anderson@civicrm.org',
1952 'pay_later_receipt:::' . $contributionPageParams['pay_later_receipt'],
1953 'displayName:::Mr. Anthony Anderson II',
1954 'contributionPageId:::' . $contributionPageResult['id'],
1955 'title:::' . $contributionPageParams['title'],
1956 'amount:::' . $params['amount'],
1957 ]);
1958 $mut->stop();
1959 $this->revertTemplateToReservedTemplate();
1960 }
1961
1962 /**
1963 * Test to check whether contact billing address is used when no contribution address
1964 */
1965 public function testBillingAddress() {
1966 $mut = new CiviMailUtils($this, TRUE);
1967 $this->swapMessageTemplateForTestTemplate();
1968 $this->createLoggedInUser();
1969
1970 //Scenario 1: When Contact don't have any address
1971 $params = array_merge($this->_params, ['contribution_status_id' => 2]);
1972 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1973 $this->callAPISuccess('contribution', 'completetransaction', [
1974 'id' => $contribution['id'],
1975 ]);
1976 $mut->checkMailLog([
1977 'address:::',
1978 ]);
1979
1980 // Scenario 2: Contribution using address
1981 $address = $this->callAPISuccess('address', 'create', [
1982 'street_address' => 'contribution billing st',
1983 'location_type_id' => 2,
1984 'contact_id' => $this->_params['contact_id'],
1985 ]);
1986 $params = array_merge($this->_params, [
1987 'contribution_status_id' => 2,
1988 'address_id' => $address['id'],
1989 ]
1990 );
1991 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1992 $this->callAPISuccess('contribution', 'completetransaction', [
1993 'id' => $contribution['id'],
1994 ]);
1995 $mut->checkMailLog([
1996 'address:::contribution billing st',
1997 ]);
1998
1999 // Scenario 3: Contribution wtth no address but contact has a billing address
2000 $this->callAPISuccess('address', 'create', [
2001 'id' => $address['id'],
2002 'street_address' => 'is billing st',
2003 'contact_id' => $this->_params['contact_id'],
2004 ]);
2005 $params = array_merge($this->_params, ['contribution_status_id' => 2]);
2006 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2007 $this->callAPISuccess('contribution', 'completetransaction', [
2008 'id' => $contribution['id'],
2009 ]);
2010 $mut->checkMailLog([
2011 'address:::is billing st',
2012 ]);
2013
2014 $mut->stop();
2015 $this->revertTemplateToReservedTemplate();
2016 }
2017
2018 /**
2019 * Test completing a transaction via the API.
2020 *
2021 * Note that we are creating a logged in user because email goes out from
2022 * that person
2023 */
2024 public function testCompleteTransactionFeeAmount() {
2025 $this->createLoggedInUser();
2026 $params = array_merge($this->_params, ['contribution_status_id' => 2]);
2027 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2028 $this->callAPISuccess('contribution', 'completetransaction', [
2029 'id' => $contribution['id'],
2030 'fee_amount' => '.56',
2031 'trxn_id' => '7778888',
2032 ]);
2033 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id'], 'sequential' => 1]);
2034 $this->assertEquals('Completed', $contribution['contribution_status']);
2035 $this->assertEquals('7778888', $contribution['trxn_id']);
2036 $this->assertEquals('.56', $contribution['fee_amount']);
2037 $this->assertEquals('99.44', $contribution['net_amount']);
2038 }
2039
2040 /**
2041 * CRM-19126 Add test to verify when complete transaction is called tax amount is not changed.
2042 *
2043 * @param string $thousandSeparator
2044 * punctuation used to refer to thousands.
2045 *
2046 * @dataProvider getThousandSeparators
2047 */
2048 public function testCheckTaxAmount($thousandSeparator) {
2049 $this->setCurrencySeparators($thousandSeparator);
2050 $contact = $this->createLoggedInUser();
2051 $financialType = $this->callAPISuccess('financial_type', 'create', [
2052 'name' => 'Test taxable financial Type',
2053 'is_reserved' => 0,
2054 'is_active' => 1,
2055 ]);
2056 $financialAccount = $this->callAPISuccess('financial_account', 'create', [
2057 'name' => 'Test Tax financial account ',
2058 'contact_id' => $contact,
2059 'financial_account_type_id' => 2,
2060 'is_tax' => 1,
2061 'tax_rate' => 5.00,
2062 'is_reserved' => 0,
2063 'is_active' => 1,
2064 'is_default' => 0,
2065 ]);
2066 $financialTypeId = $financialType['id'];
2067 $financialAccountId = $financialAccount['id'];
2068 $financialAccountParams = [
2069 'entity_table' => 'civicrm_financial_type',
2070 'entity_id' => $financialTypeId,
2071 'account_relationship' => 10,
2072 'financial_account_id' => $financialAccountId,
2073 ];
2074 CRM_Financial_BAO_FinancialTypeAccount::add($financialAccountParams);
2075
2076 $params = array_merge($this->_params, ['contribution_status_id' => 2, 'financial_type_id' => $financialTypeId]);
2077 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2078 $contribution1 = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id'], 'return' => 'tax_amount', 'sequential' => 1]);
2079 $this->callAPISuccess('contribution', 'completetransaction', [
2080 'id' => $contribution['id'],
2081 'trxn_id' => '777788888',
2082 'fee_amount' => '6.00',
2083 ]);
2084 $contribution2 = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id'], 'return' => ['tax_amount', 'fee_amount', 'net_amount'], 'sequential' => 1]);
2085 $this->assertEquals($contribution1['values'][0]['tax_amount'], $contribution2['values'][0]['tax_amount']);
2086 $this->assertEquals('6.00', $contribution2['values'][0]['fee_amount']);
2087 $this->assertEquals('99.00', $contribution2['values'][0]['net_amount']);
2088 }
2089
2090 /**
2091 * Test repeat contribution successfully creates line item.
2092 */
2093 public function testRepeatTransaction() {
2094 $originalContribution = $this->setUpRepeatTransaction($recurParams = [], 'single');
2095 $this->callAPISuccess('contribution', 'repeattransaction', [
2096 'original_contribution_id' => $originalContribution['id'],
2097 'contribution_status_id' => 'Completed',
2098 'trxn_id' => uniqid(),
2099 ]);
2100 $lineItemParams = [
2101 'entity_id' => $originalContribution['id'],
2102 'sequential' => 1,
2103 'return' => [
2104 'entity_table',
2105 'qty',
2106 'unit_price',
2107 'line_total',
2108 'label',
2109 'financial_type_id',
2110 'deductible_amount',
2111 'price_field_value_id',
2112 'price_field_id',
2113 ],
2114 ];
2115 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2116 'entity_id' => $originalContribution['id'],
2117 ]));
2118 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2119 'entity_id' => $originalContribution['id'] + 1,
2120 ]));
2121 unset($lineItem1['values'][0]['id'], $lineItem1['values'][0]['entity_id']);
2122 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2123 $this->assertEquals($lineItem1['values'][0], $lineItem2['values'][0]);
2124 $this->_checkFinancialRecords([
2125 'id' => $originalContribution['id'] + 1,
2126 'payment_instrument_id' => $this->callAPISuccessGetValue('PaymentProcessor', [
2127 'id' => $originalContribution['payment_processor_id'],
2128 'return' => 'payment_instrument_id',
2129 ]),
2130 ], 'online');
2131 $this->quickCleanUpFinancialEntities();
2132 }
2133
2134 /**
2135 * Test repeat contribution successfully creates line items (plural).
2136 */
2137 public function testRepeatTransactionLineItems() {
2138 // CRM-19309
2139 $originalContribution = $this->setUpRepeatTransaction($recurParams = [], 'multiple');
2140 $this->callAPISuccess('contribution', 'repeattransaction', [
2141 'original_contribution_id' => $originalContribution['id'],
2142 'contribution_status_id' => 'Completed',
2143 'trxn_id' => uniqid(),
2144 ]);
2145
2146 $lineItemParams = [
2147 'entity_id' => $originalContribution['id'],
2148 'sequential' => 1,
2149 'return' => [
2150 'entity_table',
2151 'qty',
2152 'unit_price',
2153 'line_total',
2154 'label',
2155 'financial_type_id',
2156 'deductible_amount',
2157 'price_field_value_id',
2158 'price_field_id',
2159 ],
2160 ];
2161 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2162 'entity_id' => $originalContribution['id'],
2163 ]));
2164 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2165 'entity_id' => $originalContribution['id'] + 1,
2166 ]));
2167
2168 // unset id and entity_id for all of them to be able to compare the lineItems:
2169 unset($lineItem1['values'][0]['id'], $lineItem1['values'][0]['entity_id']);
2170 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2171 $this->assertEquals($lineItem1['values'][0], $lineItem2['values'][0]);
2172
2173 unset($lineItem1['values'][1]['id'], $lineItem1['values'][1]['entity_id']);
2174 unset($lineItem2['values'][1]['id'], $lineItem2['values'][1]['entity_id']);
2175 $this->assertEquals($lineItem1['values'][1], $lineItem2['values'][1]);
2176
2177 // CRM-19309 so in future we also want to:
2178 // check that financial_line_items have been created for entity_id 3 and 4;
2179
2180 $this->callAPISuccessGetCount('FinancialItem', ['description' => 'Sales Tax', 'amount' => 0], 0);
2181 $this->quickCleanUpFinancialEntities();
2182 }
2183
2184 /**
2185 * Test repeat contribution successfully creates is_test transaction.
2186 */
2187 public function testRepeatTransactionIsTest() {
2188 $this->_params['is_test'] = 1;
2189 $originalContribution = $this->setUpRepeatTransaction(['is_test' => 1], 'single');
2190
2191 $this->callAPISuccess('contribution', 'repeattransaction', [
2192 'original_contribution_id' => $originalContribution['id'],
2193 'contribution_status_id' => 'Completed',
2194 'trxn_id' => uniqid(),
2195 ]);
2196 $this->callAPISuccessGetCount('Contribution', ['contribution_test' => 1], 2);
2197 }
2198
2199 /**
2200 * Test repeat contribution passed in status.
2201 */
2202 public function testRepeatTransactionPassedInStatus() {
2203 $originalContribution = $this->setUpRepeatTransaction($recurParams = [], 'single');
2204
2205 $this->callAPISuccess('contribution', 'repeattransaction', [
2206 'original_contribution_id' => $originalContribution['id'],
2207 'contribution_status_id' => 'Pending',
2208 'trxn_id' => uniqid(),
2209 ]);
2210 $this->callAPISuccessGetCount('Contribution', ['contribution_status_id' => 2], 1);
2211 }
2212
2213 /**
2214 * Test repeat contribution accepts recur_id instead of original_contribution_id.
2215 */
2216 public function testRepeatTransactionAcceptRecurID() {
2217 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2218 'contact_id' => $this->_individualId,
2219 'installments' => '12',
2220 'frequency_interval' => '1',
2221 'amount' => '100',
2222 'contribution_status_id' => 1,
2223 'start_date' => '2012-01-01 00:00:00',
2224 'currency' => 'USD',
2225 'frequency_unit' => 'month',
2226 'payment_processor_id' => $this->paymentProcessorID,
2227 ]);
2228 $this->callAPISuccess('contribution', 'create', array_merge(
2229 $this->_params,
2230 ['contribution_recur_id' => $contributionRecur['id']])
2231 );
2232
2233 $this->callAPISuccess('contribution', 'repeattransaction', [
2234 'contribution_recur_id' => $contributionRecur['id'],
2235 'contribution_status_id' => 'Completed',
2236 'trxn_id' => uniqid(),
2237 ]);
2238
2239 $this->quickCleanUpFinancialEntities();
2240 }
2241
2242 /**
2243 * CRM-19873 Test repattransaction if contribution_recur_id is a test.
2244 */
2245 public function testRepeatTransactionTestRecurId() {
2246 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2247 'contact_id' => $this->_individualId,
2248 'frequency_interval' => '1',
2249 'amount' => '1.00',
2250 'contribution_status_id' => 1,
2251 'start_date' => '2017-01-01 00:00:00',
2252 'currency' => 'USD',
2253 'frequency_unit' => 'month',
2254 'payment_processor_id' => $this->paymentProcessorID,
2255 'is_test' => 1,
2256 ]);
2257 $this->callAPISuccess('contribution', 'create', array_merge(
2258 $this->_params,
2259 [
2260 'contribution_recur_id' => $contributionRecur['id'],
2261 'is_test' => 1,
2262 ])
2263 );
2264
2265 $repeatedContribution = $this->callAPISuccess('contribution', 'repeattransaction', [
2266 'contribution_recur_id' => $contributionRecur['id'],
2267 'contribution_status_id' => 'Completed',
2268 'trxn_id' => uniqid(),
2269 ]);
2270
2271 $this->assertEquals($contributionRecur['values'][1]['is_test'], $repeatedContribution['values'][2]['is_test']);
2272 $this->quickCleanUpFinancialEntities();
2273 }
2274
2275 /**
2276 * CRM-19945 Tests that Contribute.repeattransaction renews a membership when contribution status=Completed
2277 *
2278 */
2279 public function testRepeatTransactionMembershipRenewCompletedContribution() {
2280 list($originalContribution, $membership) = $this->setUpAutoRenewMembership();
2281
2282 $this->callAPISuccess('contribution', 'create', [
2283 'contact_id' => $originalContribution['values'][1]['contact_id'],
2284 'financial_type_id' => $originalContribution['values'][1]['financial_type_id'],
2285 'total_amount' => $originalContribution['values'][1]['total_amount'],
2286 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2287 'contribution_status_id' => "Failed",
2288 ]);
2289
2290 $this->callAPISuccess('membership', 'create', [
2291 'id' => $membership['id'],
2292 'end_date' => 'yesterday',
2293 'status_id' => 'Expired',
2294 ]);
2295
2296 $contribution = $this->callAPISuccess('contribution', 'repeattransaction', [
2297 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2298 'contribution_status_id' => 'Completed',
2299 'trxn_id' => 'bobsled',
2300 ]);
2301
2302 $membershipStatusId = $this->callAPISuccess('membership', 'getvalue', [
2303 'id' => $membership['id'],
2304 'return' => 'status_id',
2305 ]);
2306
2307 $membership = $this->callAPISuccess('membership', 'get', [
2308 'id' => $membership['id'],
2309 ]);
2310
2311 $this->assertEquals('New', CRM_Core_PseudoConstant::getName('CRM_Member_BAO_Membership', 'status_id', $membershipStatusId));
2312
2313 $lineItem = $this->callAPISuccessGetSingle('LineItem', ['contribution_id' => $contribution['id']]);
2314 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
2315 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']]);
2316 $this->quickCleanUpFinancialEntities();
2317 $this->contactDelete($originalContribution['values'][1]['contact_id']);
2318 }
2319
2320 /**
2321 * CRM-19945 Tests that Contribute.repeattransaction DOES NOT renew a membership when contribution status=Failed
2322 *
2323 * @dataProvider contributionStatusProvider
2324 */
2325 public function testRepeatTransactionMembershipRenewContributionNotCompleted($contributionStatus) {
2326 // Completed status should renew so we don't test that here
2327 // In Progress status is only for recurring contributions so we don't test that here
2328 if (in_array($contributionStatus['name'], ['Completed', 'In Progress'])) {
2329 return;
2330 }
2331 list($originalContribution, $membership) = $this->setUpAutoRenewMembership();
2332
2333 $this->callAPISuccess('contribution', 'create', [
2334 'contact_id' => $originalContribution['values'][1]['contact_id'],
2335 'financial_type_id' => $originalContribution['values'][1]['financial_type_id'],
2336 'total_amount' => $originalContribution['values'][1]['total_amount'],
2337 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2338 'contribution_status_id' => "Completed",
2339 ]);
2340
2341 $this->callAPISuccess('membership', 'create', [
2342 'id' => $membership['id'],
2343 'end_date' => 'yesterday',
2344 'status_id' => 'Expired',
2345 ]);
2346
2347 $contribution = $this->callAPISuccess('contribution', 'repeattransaction', [
2348 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2349 'contribution_status_id' => $contributionStatus['name'],
2350 'trxn_id' => 'bobsled',
2351 ]);
2352
2353 $updatedMembership = $this->callAPISuccess('membership', 'getsingle', [
2354 'id' => $membership['id'],
2355 ]);
2356
2357 $dateTime = new DateTime('yesterday');
2358 $this->assertEquals($dateTime->format('Y-m-d'), $updatedMembership['end_date']);
2359 $this->assertEquals(CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Expired'), $updatedMembership['status_id']);
2360
2361 $lineItem = $this->callAPISuccessGetSingle('LineItem', ['contribution_id' => $contribution['id']]);
2362 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
2363 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']]);
2364 $this->quickCleanUpFinancialEntities();
2365 $this->contactDelete($originalContribution['values'][1]['contact_id']);
2366 }
2367
2368 /**
2369 * Dataprovider provides contribution status as [optionvalue=>contribution_status_name]
2370 * FIXME: buildOptions seems to die in CRM_Core_Config::_construct when in test mode.
2371 *
2372 * @return array
2373 * @throws \CiviCRM_API3_Exception
2374 */
2375 public function contributionStatusProvider() {
2376 $contributionStatuses = civicrm_api3('OptionValue', 'get', [
2377 'return' => ["id", "name"],
2378 'option_group_id' => "contribution_status",
2379 ]);
2380 foreach ($contributionStatuses['values'] as $statusName) {
2381 $statuses[] = [$statusName];
2382 }
2383 return $statuses;
2384 }
2385
2386 /**
2387 * CRM-16397 test appropriate action if total amount has changed for single line items.
2388 */
2389 public function testRepeatTransactionAlteredAmount() {
2390 $paymentProcessorID = $this->paymentProcessorCreate();
2391 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2392 'contact_id' => $this->_individualId,
2393 'installments' => '12',
2394 'frequency_interval' => '1',
2395 'amount' => '500',
2396 'contribution_status_id' => 1,
2397 'start_date' => '2012-01-01 00:00:00',
2398 'currency' => 'USD',
2399 'frequency_unit' => 'month',
2400 'payment_processor_id' => $paymentProcessorID,
2401 ]);
2402 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2403 $this->_params,
2404 [
2405 'contribution_recur_id' => $contributionRecur['id'],
2406 ])
2407 );
2408
2409 $this->callAPISuccess('contribution', 'repeattransaction', [
2410 'original_contribution_id' => $originalContribution['id'],
2411 'contribution_status_id' => 'Completed',
2412 'trxn_id' => uniqid(),
2413 'total_amount' => '400',
2414 'fee_amount' => 50,
2415 ]);
2416
2417 $lineItemParams = [
2418 'entity_id' => $originalContribution['id'],
2419 'sequential' => 1,
2420 'return' => [
2421 'entity_table',
2422 'qty',
2423 'unit_price',
2424 'line_total',
2425 'label',
2426 'financial_type_id',
2427 'deductible_amount',
2428 'price_field_value_id',
2429 'price_field_id',
2430 ],
2431 ];
2432 $this->callAPISuccessGetSingle('contribution', [
2433 'total_amount' => 400,
2434 'fee_amount' => 50,
2435 'net_amount' => 350,
2436 ]);
2437 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2438 'entity_id' => $originalContribution['id'],
2439 ]));
2440 $expectedLineItem = array_merge(
2441 $lineItem1['values'][0], [
2442 'line_total' => '400.00',
2443 'unit_price' => '400.00',
2444 ]
2445 );
2446
2447 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2448 'entity_id' => $originalContribution['id'] + 1,
2449 ]));
2450
2451 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2452 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2453 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2454 }
2455
2456 /**
2457 * CRM-17718 test appropriate action if financial type has changed for single line items.
2458 */
2459 public function testRepeatTransactionPassedInFinancialType() {
2460 $originalContribution = $this->setUpRecurringContribution();
2461
2462 $this->callAPISuccess('contribution', 'repeattransaction', [
2463 'original_contribution_id' => $originalContribution['id'],
2464 'contribution_status_id' => 'Completed',
2465 'trxn_id' => uniqid(),
2466 'financial_type_id' => 2,
2467 ]);
2468 $lineItemParams = [
2469 'entity_id' => $originalContribution['id'],
2470 'sequential' => 1,
2471 'return' => [
2472 'entity_table',
2473 'qty',
2474 'unit_price',
2475 'line_total',
2476 'label',
2477 'financial_type_id',
2478 'deductible_amount',
2479 'price_field_value_id',
2480 'price_field_id',
2481 ],
2482 ];
2483
2484 $this->callAPISuccessGetSingle('contribution', [
2485 'total_amount' => 100,
2486 'financial_type_id' => 2,
2487 ]);
2488 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2489 'entity_id' => $originalContribution['id'],
2490 ]));
2491 $expectedLineItem = array_merge(
2492 $lineItem1['values'][0], [
2493 'line_total' => '100.00',
2494 'unit_price' => '100.00',
2495 'financial_type_id' => 2,
2496 'contribution_type_id' => 2,
2497 ]
2498 );
2499 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2500 'entity_id' => $originalContribution['id'] + 1,
2501 ]));
2502 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2503 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2504 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2505 }
2506
2507 /**
2508 * CRM-17718 test appropriate action if financial type has changed for single line items.
2509 */
2510 public function testRepeatTransactionUpdatedFinancialType() {
2511 $originalContribution = $this->setUpRecurringContribution([], ['financial_type_id' => 2]);
2512
2513 $this->callAPISuccess('contribution', 'repeattransaction', [
2514 'contribution_recur_id' => $originalContribution['id'],
2515 'contribution_status_id' => 'Completed',
2516 'trxn_id' => uniqid(),
2517 ]);
2518 $lineItemParams = [
2519 'entity_id' => $originalContribution['id'],
2520 'sequential' => 1,
2521 'return' => [
2522 'entity_table',
2523 'qty',
2524 'unit_price',
2525 'line_total',
2526 'label',
2527 'financial_type_id',
2528 'deductible_amount',
2529 'price_field_value_id',
2530 'price_field_id',
2531 ],
2532 ];
2533
2534 $this->callAPISuccessGetSingle('contribution', [
2535 'total_amount' => 100,
2536 'financial_type_id' => 2,
2537 ]);
2538 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2539 'entity_id' => $originalContribution['id'],
2540 ]));
2541 $expectedLineItem = array_merge(
2542 $lineItem1['values'][0], [
2543 'line_total' => '100.00',
2544 'unit_price' => '100.00',
2545 'financial_type_id' => 2,
2546 'contribution_type_id' => 2,
2547 ]
2548 );
2549
2550 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2551 'entity_id' => $originalContribution['id'] + 1,
2552 ]));
2553 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2554 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2555 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2556 }
2557
2558 /**
2559 * CRM-16397 test appropriate action if campaign has been passed in.
2560 */
2561 public function testRepeatTransactionPassedInCampaign() {
2562 $paymentProcessorID = $this->paymentProcessorCreate();
2563 $campaignID = $this->campaignCreate();
2564 $campaignID2 = $this->campaignCreate();
2565 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2566 'contact_id' => $this->_individualId,
2567 'installments' => '12',
2568 'frequency_interval' => '1',
2569 'amount' => '100',
2570 'contribution_status_id' => 1,
2571 'start_date' => '2012-01-01 00:00:00',
2572 'currency' => 'USD',
2573 'frequency_unit' => 'month',
2574 'payment_processor_id' => $paymentProcessorID,
2575 ]);
2576 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2577 $this->_params,
2578 [
2579 'contribution_recur_id' => $contributionRecur['id'],
2580 'campaign_id' => $campaignID,
2581 ])
2582 );
2583
2584 $this->callAPISuccess('contribution', 'repeattransaction', [
2585 'original_contribution_id' => $originalContribution['id'],
2586 'contribution_status_id' => 'Completed',
2587 'trxn_id' => uniqid(),
2588 'campaign_id' => $campaignID2,
2589 ]);
2590
2591 $this->callAPISuccessGetSingle('contribution', [
2592 'total_amount' => 100,
2593 'campaign_id' => $campaignID2,
2594 ]);
2595 }
2596
2597 /**
2598 * CRM-17718 campaign stored on contribution recur gets priority.
2599 *
2600 * This reflects the fact we permit people to update them.
2601 */
2602 public function testRepeatTransactionUpdatedCampaign() {
2603 $paymentProcessorID = $this->paymentProcessorCreate();
2604 $campaignID = $this->campaignCreate();
2605 $campaignID2 = $this->campaignCreate();
2606 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2607 'contact_id' => $this->_individualId,
2608 'installments' => '12',
2609 'frequency_interval' => '1',
2610 'amount' => '100',
2611 'contribution_status_id' => 1,
2612 'start_date' => '2012-01-01 00:00:00',
2613 'currency' => 'USD',
2614 'frequency_unit' => 'month',
2615 'payment_processor_id' => $paymentProcessorID,
2616 'campaign_id' => $campaignID,
2617 ]);
2618 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2619 $this->_params,
2620 [
2621 'contribution_recur_id' => $contributionRecur['id'],
2622 'campaign_id' => $campaignID2,
2623 ])
2624 );
2625
2626 $this->callAPISuccess('contribution', 'repeattransaction', [
2627 'original_contribution_id' => $originalContribution['id'],
2628 'contribution_status_id' => 'Completed',
2629 'trxn_id' => uniqid(),
2630 ]);
2631
2632 $this->callAPISuccessGetSingle('contribution', [
2633 'total_amount' => 100,
2634 'campaign_id' => $campaignID,
2635 ]);
2636 }
2637
2638 /**
2639 * CRM-20685 Repeattransaction produces incorrect Financial Type ID (in specific circumstance) - if number of lineItems = 1.
2640 *
2641 * This case happens when the line item & contribution do not have the same type in his initiating transaction.
2642 */
2643 public function testRepeatTransactionUpdatedFinancialTypeAndNotEquals() {
2644 $originalContribution = $this->setUpRecurringContribution([], ['financial_type_id' => 2]);
2645 // This will made the trick to get the not equals behaviour.
2646 $this->callAPISuccess('line_item', 'create', ['id' => 1, 'financial_type_id' => 4]);
2647 $this->callAPISuccess('contribution', 'repeattransaction', [
2648 'contribution_recur_id' => $originalContribution['id'],
2649 'contribution_status_id' => 'Completed',
2650 'trxn_id' => uniqid(),
2651 ]);
2652 $lineItemParams = [
2653 'entity_id' => $originalContribution['id'],
2654 'sequential' => 1,
2655 'return' => [
2656 'entity_table',
2657 'qty',
2658 'unit_price',
2659 'line_total',
2660 'label',
2661 'financial_type_id',
2662 'deductible_amount',
2663 'price_field_value_id',
2664 'price_field_id',
2665 ],
2666 ];
2667 $this->callAPISuccessGetSingle('contribution', [
2668 'total_amount' => 100,
2669 'financial_type_id' => 2,
2670 ]);
2671 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2672 'entity_id' => $originalContribution['id'],
2673 ]));
2674 $expectedLineItem = array_merge(
2675 $lineItem1['values'][0], [
2676 'line_total' => '100.00',
2677 'unit_price' => '100.00',
2678 'financial_type_id' => 4,
2679 'contribution_type_id' => 4,
2680 ]
2681 );
2682
2683 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2684 'entity_id' => $originalContribution['id'] + 1,
2685 ]));
2686 $this->callAPISuccess('line_item', 'create', ['id' => 1, 'financial_type_id' => 1]);
2687 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2688 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2689 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2690 }
2691
2692 /**
2693 * Test completing a transaction does not 'mess' with net amount (CRM-15960).
2694 */
2695 public function testCompleteTransactionNetAmountOK() {
2696 $this->createLoggedInUser();
2697 $params = array_merge($this->_params, ['contribution_status_id' => 2]);
2698 unset($params['net_amount']);
2699 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2700 $this->callAPISuccess('contribution', 'completetransaction', [
2701 'id' => $contribution['id'],
2702 ]);
2703 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
2704 $this->assertEquals('Completed', $contribution['contribution_status']);
2705 $this->assertTrue(($contribution['total_amount'] - $contribution['net_amount']) == $contribution['fee_amount']);
2706 }
2707
2708 /**
2709 * CRM-14151 - Test completing a transaction via the API.
2710 */
2711 public function testCompleteTransactionWithReceiptDateSet() {
2712 $this->swapMessageTemplateForTestTemplate();
2713 $mut = new CiviMailUtils($this, TRUE);
2714 $this->createLoggedInUser();
2715 $params = array_merge($this->_params, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
2716 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2717 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contribution['id'], 'trxn_date' => date('Y-m-d')]);
2718 $contribution = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id'], 'sequential' => 1]);
2719 $this->assertEquals('Completed', $contribution['values'][0]['contribution_status']);
2720 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['values'][0]['receive_date'])));
2721 $mut->checkMailLog([
2722 'Receipt - Contribution',
2723 'receipt_date:::' . date('Ymd'),
2724 ]);
2725 $mut->stop();
2726 $this->revertTemplateToReservedTemplate();
2727 }
2728
2729 /**
2730 * CRM-1960 - Test to ensure that completetransaction respects the is_email_receipt setting
2731 */
2732 public function testCompleteTransactionWithEmailReceiptInput() {
2733 $contributionPage = $this->createReceiptableContributionPage();
2734
2735 $this->_params['contribution_page_id'] = $contributionPage['id'];
2736 $params = array_merge($this->_params, ['contribution_status_id' => 2]);
2737 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2738 // Complete the transaction overriding is_email_receipt to = FALSE
2739 $this->callAPISuccess('contribution', 'completetransaction', [
2740 'id' => $contribution['id'],
2741 'trxn_date' => date('2011-04-09'),
2742 'trxn_id' => 'kazam',
2743 'is_email_receipt' => 0,
2744 ]);
2745 // Check if a receipt was issued
2746 $receipt_date = $this->callAPISuccess('Contribution', 'getvalue', ['id' => $contribution['id'], 'return' => 'receipt_date']);
2747 $this->assertEquals('', $receipt_date);
2748 }
2749
2750 /**
2751 * Test that $is_recur is assigned to the receipt.
2752 */
2753 public function testCompleteTransactionForRecurring() {
2754
2755 $this->swapMessageTemplateForTestTemplate();
2756 $recurring = $this->setUpRecurringContribution();
2757 $contributionPage = $this->createReceiptableContributionPage(['is_recur' => TRUE, 'recur_frequency_unit' => 'month', 'recur_interval' => 1]);
2758
2759 $this->_params['contribution_page_id'] = $contributionPage['id'];
2760 $this->_params['contribution_recur_id'] = $recurring['id'];
2761
2762 $contribution = $this->setUpForCompleteTransaction();
2763
2764 $this->callAPISuccess('contribution', 'completetransaction', [
2765 'id' => $contribution['id'],
2766 'trxn_date' => date('2011-04-09'),
2767 'trxn_id' => 'kazam',
2768 'is_email_receipt' => 1,
2769 ]);
2770
2771 $this->mut->checkMailLog([
2772 'is_recur:::1',
2773 'cancelSubscriptionUrl:::' . CIVICRM_UF_BASEURL,
2774 ]);
2775 $this->mut->stop();
2776 $this->revertTemplateToReservedTemplate();
2777 }
2778
2779 /**
2780 * CRM-19710 - Test to ensure that completetransaction respects the input for is_email_receipt setting.
2781 *
2782 * If passed in it will override the default from contribution page.
2783 */
2784 public function testCompleteTransactionWithEmailReceiptInputTrue() {
2785 $mut = new CiviMailUtils($this, TRUE);
2786 $this->createLoggedInUser();
2787 // Create a Contribution Page with is_email_receipt = FALSE
2788 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', [
2789 'receipt_from_name' => 'Mickey Mouse',
2790 'receipt_from_email' => 'mickey@mouse.com',
2791 'title' => "Test Contribution Page",
2792 'financial_type_id' => 1,
2793 'currency' => 'CAD',
2794 'is_monetary' => TRUE,
2795 'is_email_receipt' => 0,
2796 ]);
2797 $this->_params['contribution_page_id'] = $contributionPage['id'];
2798 $params = array_merge($this->_params, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
2799 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2800 // Complete the transaction overriding is_email_receipt to = TRUE
2801 $this->callAPISuccess('contribution', 'completetransaction', [
2802 'id' => $contribution['id'],
2803 'is_email_receipt' => 1,
2804 ]);
2805 $mut->checkMailLog([
2806 'Please print this receipt for your records.',
2807 ]);
2808 $mut->stop();
2809 }
2810
2811 /**
2812 * Complete the transaction using the template with all the possible.
2813 */
2814 public function testCompleteTransactionWithTestTemplate() {
2815 $this->swapMessageTemplateForTestTemplate();
2816 $contribution = $this->setUpForCompleteTransaction();
2817 $this->callAPISuccess('contribution', 'completetransaction', [
2818 'id' => $contribution['id'],
2819 'trxn_date' => date('2011-04-09'),
2820 'trxn_id' => 'kazam',
2821 ]);
2822 $receive_date = $this->callAPISuccess('Contribution', 'getvalue', ['id' => $contribution['id'], 'return' => 'receive_date']);
2823 $this->mut->checkMailLog([
2824 'email:::anthony_anderson@civicrm.org',
2825 'is_monetary:::1',
2826 'amount:::100.00',
2827 'currency:::USD',
2828 'receive_date:::' . date('Ymd', strtotime($receive_date)),
2829 'receipt_date:::' . date('Ymd'),
2830 'contributeMode:::notify',
2831 'title:::Contribution',
2832 'displayName:::Mr. Anthony Anderson II',
2833 'trxn_id:::kazam',
2834 'contactID:::' . $this->_params['contact_id'],
2835 'contributionID:::' . $contribution['id'],
2836 'financialTypeId:::1',
2837 'financialTypeName:::Donation',
2838 ]);
2839 $this->mut->stop();
2840 $this->revertTemplateToReservedTemplate();
2841 }
2842
2843 /**
2844 * Complete the transaction using the template with all the possible.
2845 */
2846 public function testCompleteTransactionContributionPageFromAddress() {
2847 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', [
2848 'receipt_from_name' => 'Mickey Mouse',
2849 'receipt_from_email' => 'mickey@mouse.com',
2850 'title' => "Test Contribution Page",
2851 'financial_type_id' => 1,
2852 'currency' => 'NZD',
2853 'goal_amount' => 50,
2854 'is_pay_later' => 1,
2855 'is_monetary' => TRUE,
2856 'is_email_receipt' => TRUE,
2857 ]);
2858 $this->_params['contribution_page_id'] = $contributionPage['id'];
2859 $contribution = $this->setUpForCompleteTransaction();
2860 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contribution['id']]);
2861 $this->mut->checkMailLog([
2862 'mickey@mouse.com',
2863 'Mickey Mouse <',
2864 ]);
2865 $this->mut->stop();
2866 }
2867
2868 /**
2869 * Test completing first transaction in a recurring series.
2870 *
2871 * The status should be set to 'in progress' and the next scheduled payment date calculated.
2872 *
2873 * @dataProvider getScheduledDateData
2874 *
2875 * @param array $dataSet
2876 *
2877 * @throws \Exception
2878 */
2879 public function testCompleteTransactionSetStatusToInProgress($dataSet) {
2880 $paymentProcessorID = $this->paymentProcessorCreate();
2881 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
2882 'contact_id' => $this->_individualId,
2883 'installments' => '2',
2884 'frequency_interval' => '1',
2885 'amount' => '500',
2886 'contribution_status_id' => 'Pending',
2887 'start_date' => '2012-01-01 00:00:00',
2888 'currency' => 'USD',
2889 'frequency_unit' => 'month',
2890 'payment_processor_id' => $paymentProcessorID,
2891 ], $dataSet['data']));
2892 $contribution = $this->callAPISuccess('contribution', 'create', array_merge(
2893 $this->_params,
2894 [
2895 'contribution_recur_id' => $contributionRecur['id'],
2896 'contribution_status_id' => 'Pending',
2897 'receive_date' => $dataSet['receive_date'],
2898 ])
2899 );
2900 $this->callAPISuccess('Contribution', 'completetransaction', [
2901 'id' => $contribution,
2902 'receive_date' => $dataSet['receive_date'],
2903 ]);
2904 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
2905 'id' => $contributionRecur['id'],
2906 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
2907 ]);
2908 $this->assertEquals(5, $contributionRecur['contribution_status_id']);
2909 $this->assertEquals($dataSet['expected'], $contributionRecur['next_sched_contribution_date']);
2910 $this->callAPISuccess('Contribution', 'create', array_merge(
2911 $this->_params,
2912 [
2913 'contribution_recur_id' => $contributionRecur['id'],
2914 'contribution_status_id' => 'Completed',
2915 ]
2916 ));
2917 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
2918 'id' => $contributionRecur['id'],
2919 'return' => ['contribution_status_id'],
2920 ]);
2921 $this->assertEquals(1, $contributionRecur['contribution_status_id']);
2922 }
2923
2924 /**
2925 * Get dates for testing.
2926 *
2927 * @return array
2928 */
2929 public function getScheduledDateData() {
2930 $result = [];
2931 $result[]['2016-08-31-1-month'] = [
2932 'data' => [
2933 'start_date' => '2016-08-31',
2934 'frequency_interval' => 1,
2935 'frequency_unit' => 'month',
2936 ],
2937 'receive_date' => '2016-08-31',
2938 'expected' => '2016-10-01 00:00:00',
2939 ];
2940 $result[]['2012-01-01-1-month'] = [
2941 'data' => [
2942 'start_date' => '2012-01-01',
2943 'frequency_interval' => 1,
2944 'frequency_unit' => 'month',
2945 ],
2946 'receive_date' => '2012-01-01',
2947 'expected' => '2012-02-01 00:00:00',
2948 ];
2949 $result[]['2012-01-01-1-month'] = [
2950 'data' => [
2951 'start_date' => '2012-01-01',
2952 'frequency_interval' => 1,
2953 'frequency_unit' => 'month',
2954 ],
2955 'receive_date' => '2012-02-29',
2956 'expected' => '2012-03-29 00:00:00',
2957 ];
2958 $result['receive_date_includes_time']['2012-01-01-1-month'] = [
2959 'data' => [
2960 'start_date' => '2012-01-01',
2961 'frequency_interval' => 1,
2962 'frequency_unit' => 'month',
2963 'next_sched_contribution_date' => '2012-02-29',
2964 ],
2965 'receive_date' => '2012-02-29 16:00:00',
2966 'expected' => '2012-03-29 00:00:00',
2967 ];
2968 return $result;
2969 }
2970
2971 /**
2972 * Test completing a pledge with the completeTransaction api..
2973 *
2974 * Note that we are creating a logged in user because email goes out from
2975 * that person.
2976 */
2977 public function testCompleteTransactionUpdatePledgePayment() {
2978 $this->swapMessageTemplateForTestTemplate();
2979 $mut = new CiviMailUtils($this, TRUE);
2980 $mut->clearMessages();
2981 $this->createLoggedInUser();
2982 $contributionID = $this->createPendingPledgeContribution();
2983 $this->callAPISuccess('contribution', 'completetransaction', [
2984 'id' => $contributionID,
2985 'trxn_date' => '1 Feb 2013',
2986 ]);
2987 $pledge = $this->callAPISuccessGetSingle('Pledge', [
2988 'id' => $this->_ids['pledge'],
2989 ]);
2990 $this->assertEquals('Completed', $pledge['pledge_status']);
2991
2992 $status = $this->callAPISuccessGetValue('PledgePayment', [
2993 'pledge_id' => $this->_ids['pledge'],
2994 'return' => 'status_id',
2995 ]);
2996 $this->assertEquals(1, $status);
2997 $mut->checkMailLog([
2998 'amount:::500.00',
2999 'receive_date:::20130201000000',
3000 "receipt_date:::\n",
3001 ]);
3002 $mut->stop();
3003 $this->revertTemplateToReservedTemplate();
3004 }
3005
3006 /**
3007 * Test completing a transaction with an event via the API.
3008 *
3009 * Note that we are creating a logged in user because email goes out from
3010 * that person
3011 */
3012 public function testCompleteTransactionWithParticipantRecord() {
3013 $mut = new CiviMailUtils($this, TRUE);
3014 $mut->clearMessages();
3015 $this->_individualId = $this->createLoggedInUser();
3016 $contributionID = $this->createPendingParticipantContribution();
3017 $this->callAPISuccess('contribution', 'completetransaction', [
3018 'id' => $contributionID,
3019 ]
3020 );
3021 $participantStatus = $this->callAPISuccessGetValue('participant', [
3022 'id' => $this->_ids['participant'],
3023 'return' => 'participant_status_id',
3024 ]);
3025 $this->assertEquals(1, $participantStatus);
3026
3027 //Assert only three activities are created.
3028 $activities = CRM_Activity_BAO_Activity::getContactActivity($this->_individualId);
3029 $this->assertEquals(3, count($activities));
3030 $activityNames = array_count_values(CRM_Utils_Array::collect('activity_name', $activities));
3031 // record two activities before and after completing payment for Event registration
3032 $this->assertEquals(2, $activityNames['Event Registration']);
3033 // update the original 'Contribution' activity created after completing payment
3034 $this->assertEquals(1, $activityNames['Contribution']);
3035
3036 $mut->checkMailLog([
3037 'Annual CiviCRM meet',
3038 'Event',
3039 'This letter is a confirmation that your registration has been received and your status has been updated to Registered.',
3040 ]);
3041 $mut->stop();
3042 }
3043
3044 /**
3045 * Test membership is renewed when transaction completed.
3046 */
3047 public function testCompleteTransactionMembershipPriceSet() {
3048 $this->createPriceSetWithPage('membership');
3049 $stateOfGrace = $this->callAPISuccess('MembershipStatus', 'getvalue', [
3050 'name' => 'Grace',
3051 'return' => 'id',
3052 ]);
3053 $this->setUpPendingContribution($this->_ids['price_field_value'][0]);
3054 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids['membership']]);
3055 $logs = $this->callAPISuccess('MembershipLog', 'get', [
3056 'membership_id' => $this->_ids['membership'],
3057 ]);
3058 $this->assertEquals(1, $logs['count']);
3059 $this->assertEquals($stateOfGrace, $membership['status_id']);
3060 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $this->_ids['contribution']]);
3061 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids['membership']]);
3062 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 1 year')), $membership['end_date']);
3063 $this->callAPISuccessGetSingle('LineItem', [
3064 'entity_id' => $this->_ids['membership'],
3065 'entity_table' => 'civicrm_membership',
3066 ]);
3067 $logs = $this->callAPISuccess('MembershipLog', 'get', [
3068 'membership_id' => $this->_ids['membership'],
3069 ]);
3070 $this->assertEquals(2, $logs['count']);
3071 $this->assertNotEquals($stateOfGrace, $logs['values'][2]['status_id']);
3072 //Assert only three activities are created.
3073 $activities = CRM_Activity_BAO_Activity::getContactActivity($this->_ids['contact']);
3074 $this->assertEquals(3, count($activities));
3075 $activityNames = array_flip(CRM_Utils_Array::collect('activity_name', $activities));
3076 $this->assertArrayHasKey('Contribution', $activityNames);
3077 $this->assertArrayHasKey('Membership Signup', $activityNames);
3078 $this->assertArrayHasKey('Change Membership Status', $activityNames);
3079 $this->cleanUpAfterPriceSets();
3080 }
3081
3082 /**
3083 * Test if renewal activity is create after changing Pending contribution to Completed via offline
3084 */
3085 public function testPendingToCompleteContribution() {
3086 $this->createPriceSetWithPage('membership');
3087 $this->setUpPendingContribution($this->_ids['price_field_value'][0]);
3088 $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids['membership']]);
3089 // Case 1: Assert that Membership Signup Activity is created on Pending to Completed Contribution via backoffice
3090 $activity = $this->callAPISuccess('Activity', 'get', [
3091 'activity_type_id' => 'Membership Signup',
3092 'source_record_id' => $this->_ids['membership'],
3093 'status_id' => 'Scheduled',
3094 ]);
3095 $this->assertEquals(1, $activity['count']);
3096
3097 // change pending contribution to completed
3098 $form = new CRM_Contribute_Form_Contribution();
3099
3100 $form->_params = [
3101 'id' => $this->_ids['contribution'],
3102 'total_amount' => 20,
3103 'net_amount' => 20,
3104 'fee_amount' => 0,
3105 'financial_type_id' => 1,
3106 'contact_id' => $this->_individualId,
3107 'contribution_status_id' => 1,
3108 'billing_middle_name' => '',
3109 'billing_last_name' => 'Adams',
3110 'billing_street_address-5' => '790L Lincoln St S',
3111 'billing_city-5' => 'Maryknoll',
3112 'billing_state_province_id-5' => 1031,
3113 'billing_postal_code-5' => 10545,
3114 'billing_country_id-5' => 1228,
3115 'frequency_interval' => 1,
3116 'frequency_unit' => 'month',
3117 'installments' => '',
3118 'hidden_AdditionalDetail' => 1,
3119 'hidden_Premium' => 1,
3120 'from_email_address' => '"civi45" <civi45@civicrm.com>',
3121 'receipt_date' => '',
3122 'receipt_date_time' => '',
3123 'payment_processor_id' => $this->paymentProcessorID,
3124 'currency' => 'USD',
3125 'contribution_page_id' => $this->_ids['contribution_page'],
3126 'contribution_mode' => 'membership',
3127 'source' => 'Membership Signup and Renewal',
3128 ];
3129
3130 $form->testSubmit($form->_params, CRM_Core_Action::UPDATE);
3131
3132 // Case 2: After successful payment for Pending backoffice there are three activities created
3133 // 2.a Update status of existing Scheduled Membership Signup (created in step 1) to Completed
3134 $activity = $this->callAPISuccess('Activity', 'get', [
3135 'activity_type_id' => 'Membership Signup',
3136 'source_record_id' => $this->_ids['membership'],
3137 'status_id' => 'Completed',
3138 ]);
3139 $this->assertEquals(1, $activity['count']);
3140 // 2.b Contribution activity created to record successful payment
3141 $activity = $this->callAPISuccess('Activity', 'get', [
3142 'activity_type_id' => 'Contribution',
3143 'source_record_id' => $this->_ids['contribution'],
3144 'status_id' => 'Completed',
3145 ]);
3146 $this->assertEquals(1, $activity['count']);
3147
3148 // 2.c 'Change membership type' activity created to record Membership status change from Grace to Current
3149 $activity = $this->callAPISuccess('Activity', 'get', [
3150 'activity_type_id' => 'Change Membership Status',
3151 'source_record_id' => $this->_ids['membership'],
3152 'status_id' => 'Completed',
3153 ]);
3154 $this->assertEquals(1, $activity['count']);
3155 $this->assertEquals('Status changed from Grace to Current', $activity['values'][$activity['id']]['subject']);
3156
3157 //Create another pending contribution for renewal
3158 $contribution = $this->callAPISuccess('contribution', 'create', [
3159 'domain_id' => 1,
3160 'contact_id' => $this->_ids['contact'],
3161 'receive_date' => date('Ymd'),
3162 'total_amount' => 20.00,
3163 'financial_type_id' => 1,
3164 'payment_instrument_id' => 'Credit Card',
3165 'non_deductible_amount' => 10.00,
3166 'trxn_id' => 'rdhfi88',
3167 'invoice_id' => 'dofhiewuyr',
3168 'source' => 'SSF',
3169 'contribution_status_id' => 2,
3170 'contribution_page_id' => $this->_ids['contribution_page'],
3171 // We can't rely on contribution api to link line items correctly to membership
3172 'skipLineItem' => TRUE,
3173 'api.membership_payment.create' => ['membership_id' => $this->_ids['membership']],
3174 ]);
3175
3176 $this->callAPISuccess('line_item', 'create', [
3177 'entity_id' => $contribution['id'],
3178 'entity_table' => 'civicrm_contribution',
3179 'contribution_id' => $contribution['id'],
3180 'price_field_id' => $this->_ids['price_field'][0],
3181 'qty' => 1,
3182 'unit_price' => 20,
3183 'line_total' => 20,
3184 'financial_type_id' => 1,
3185 'price_field_value_id' => $this->_ids['price_field_value']['cont'],
3186 ]);
3187 $this->callAPISuccess('line_item', 'create', [
3188 'entity_id' => $this->_ids['membership'],
3189 'entity_table' => 'civicrm_membership',
3190 'contribution_id' => $contribution['id'],
3191 'price_field_id' => $this->_ids['price_field'][0],
3192 'qty' => 1,
3193 'unit_price' => 20,
3194 'line_total' => 20,
3195 'financial_type_id' => 1,
3196 'price_field_value_id' => $this->_ids['price_field_value'][0],
3197 'membership_type_id' => $this->_ids['membership_type'],
3198 ]);
3199
3200 //Update it to Failed.
3201 $form->_params['id'] = $contribution['id'];
3202 $form->_params['contribution_status_id'] = 4;
3203
3204 $form->testSubmit($form->_params, CRM_Core_Action::UPDATE);
3205 //Existing membership should not get updated to expired.
3206 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids['membership']]);
3207 $this->assertNotEquals($membership['status_id'], 4);
3208 }
3209
3210 /**
3211 * Test membership is renewed when transaction completed.
3212 */
3213 public function testCompleteTransactionMembershipPriceSetTwoTerms() {
3214 $this->createPriceSetWithPage('membership');
3215 $this->setUpPendingContribution($this->_ids['price_field_value'][1]);
3216 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $this->_ids['contribution']]);
3217 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids['membership']]);
3218 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 2 years')), $membership['end_date']);
3219 $this->cleanUpAfterPriceSets();
3220 }
3221
3222 public function cleanUpAfterPriceSets() {
3223 $this->quickCleanUpFinancialEntities();
3224 $this->contactDelete($this->_ids['contact']);
3225 }
3226
3227 /**
3228 * Set up a pending transaction with a specific price field id.
3229 *
3230 * @param int $priceFieldValueID
3231 * @param array $contriParams
3232 */
3233 public function setUpPendingContribution($priceFieldValueID, $contriParams = []) {
3234 $contactID = $this->individualCreate();
3235 $membership = $this->callAPISuccess('membership', 'create', [
3236 'contact_id' => $contactID,
3237 'membership_type_id' => $this->_ids['membership_type'],
3238 'start_date' => 'yesterday - 1 year',
3239 'end_date' => 'yesterday',
3240 'join_date' => 'yesterday - 1 year',
3241 ]);
3242 $contribution = $this->callAPISuccess('contribution', 'create', array_merge([
3243 'domain_id' => 1,
3244 'contact_id' => $contactID,
3245 'receive_date' => date('Ymd'),
3246 'total_amount' => 20.00,
3247 'financial_type_id' => 1,
3248 'payment_instrument_id' => 'Credit Card',
3249 'non_deductible_amount' => 10.00,
3250 'trxn_id' => 'jdhfi' . rand(1, 100),
3251 'invoice_id' => 'djfhiew' . rand(5, 100),
3252 'source' => 'SSF',
3253 'contribution_status_id' => 2,
3254 'contribution_page_id' => $this->_ids['contribution_page'],
3255 'api.membership_payment.create' => ['membership_id' => $membership['id']],
3256 ], $contriParams));
3257
3258 $this->callAPISuccess('line_item', 'create', [
3259 'entity_id' => $contribution['id'],
3260 'entity_table' => 'civicrm_contribution',
3261 'contribution_id' => $contribution['id'],
3262 'price_field_id' => $this->_ids['price_field'][0],
3263 'qty' => 1,
3264 'unit_price' => 20,
3265 'line_total' => 20,
3266 'financial_type_id' => 1,
3267 'price_field_value_id' => $priceFieldValueID,
3268 ]);
3269 $this->_ids['contact'] = $contactID;
3270 $this->_ids['contribution'] = $contribution['id'];
3271 $this->_ids['membership'] = $membership['id'];
3272 }
3273
3274 /**
3275 * Test sending a mail via the API.
3276 */
3277 public function testSendMail() {
3278 $mut = new CiviMailUtils($this, TRUE);
3279 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
3280 $this->callAPISuccess('contribution', 'sendconfirmation', [
3281 'id' => $contribution['id'],
3282 'receipt_from_email' => 'api@civicrm.org',
3283 ]);
3284 $mut->checkMailLog([
3285 '$ 100.00',
3286 'Contribution Information',
3287 'Please print this confirmation for your records',
3288 ], [
3289 'Event',
3290 ]);
3291
3292 $this->checkCreditCardDetails($mut, $contribution['id']);
3293 $mut->stop();
3294 }
3295
3296 /**
3297 * Test sending a mail via the API.
3298 * This simulates webform_civicrm using pay later contribution page
3299 */
3300 public function testSendconfirmationPayLater() {
3301 $mut = new CiviMailUtils($this, TRUE);
3302
3303 // Create contribution page
3304 $pageParams = [
3305 'title' => 'Webform Contributions',
3306 'financial_type_id' => 1,
3307 'contribution_type_id' => 1,
3308 'is_confirm_enabled' => 1,
3309 'is_pay_later' => 1,
3310 'pay_later_text' => 'I will send payment by cheque',
3311 'pay_later_receipt' => 'Send your cheque payable to "CiviCRM LLC" to the office',
3312 ];
3313 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $pageParams);
3314
3315 // Create pay later contribution
3316 $contribParams = [
3317 'contact_id' => $this->_individualId,
3318 'financial_type_id' => 1,
3319 'is_pay_later' => 1,
3320 'contribution_status_id' => 2,
3321 'contribution_page_id' => $contributionPage['id'],
3322 'total_amount' => '10.00',
3323 ];
3324 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
3325
3326 // Create line item
3327 $lineItemParams = [
3328 'contribution_id' => $contribution['id'],
3329 'entity_id' => $contribution['id'],
3330 'entity_table' => 'civicrm_contribution',
3331 'label' => 'My lineitem label',
3332 'qty' => 1,
3333 'unit_price' => "10.00",
3334 'line_total' => "10.00",
3335 ];
3336 $lineItem = $this->callAPISuccess('lineItem', 'create', $lineItemParams);
3337
3338 // Create email
3339 try {
3340 civicrm_api3('contribution', 'sendconfirmation', [
3341 'id' => $contribution['id'],
3342 'receipt_from_email' => 'api@civicrm.org',
3343 ]);
3344 }
3345 catch (Exception $e) {
3346 // Need to figure out how to stop this some other day
3347 // We don't care about the Payment Processor because this is Pay Later
3348 // The point of this test is to check we get the pay_later version of the mail
3349 if ($e->getMessage() != "Undefined variable: CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage") {
3350 throw $e;
3351 }
3352 }
3353
3354 // Retrieve mail & check it has the pay_later_receipt info
3355 $mut->getMostRecentEmail('raw');
3356 $mut->checkMailLog([
3357 (string) $contribParams['total_amount'],
3358 $pageParams['pay_later_receipt'],
3359 ], [
3360 'Event',
3361 ]);
3362 $mut->stop();
3363 }
3364
3365 /**
3366 * Check credit card details in sent mail via API
3367 *
3368 * @param $mut obj CiviMailUtils instance
3369 * @param int $contributionID Contribution ID
3370 *
3371 */
3372 public function checkCreditCardDetails($mut, $contributionID) {
3373 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
3374 $this->callAPISuccess('contribution', 'sendconfirmation', [
3375 'id' => $contributionID,
3376 'receipt_from_email' => 'api@civicrm.org',
3377 'payment_processor_id' => $this->paymentProcessorID,
3378 ]);
3379 $mut->checkMailLog([
3380 // credit card header
3381 'Credit Card Information',
3382 // billing header
3383 'Billing Name and Address',
3384 // billing name
3385 'anthony_anderson@civicrm.org',
3386 ], [
3387 'Event',
3388 ]);
3389 }
3390
3391 /**
3392 * Test sending a mail via the API.
3393 */
3394 public function testSendMailEvent() {
3395 $mut = new CiviMailUtils($this, TRUE);
3396 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
3397 $event = $this->eventCreate([
3398 'is_email_confirm' => 1,
3399 'confirm_from_email' => 'test@civicrm.org',
3400 ]);
3401 $this->_eventID = $event['id'];
3402 $participantParams = [
3403 'contact_id' => $this->_individualId,
3404 'event_id' => $this->_eventID,
3405 'status_id' => 1,
3406 'role_id' => 1,
3407 // to ensure it matches later on
3408 'register_date' => '2007-07-21 00:00:00',
3409 'source' => 'Online Event Registration: API Testing',
3410
3411 ];
3412 $participant = $this->callAPISuccess('participant', 'create', $participantParams);
3413 $this->callAPISuccess('participant_payment', 'create', [
3414 'participant_id' => $participant['id'],
3415 'contribution_id' => $contribution['id'],
3416 ]);
3417 $this->callAPISuccess('contribution', 'sendconfirmation', [
3418 'id' => $contribution['id'],
3419 'receipt_from_email' => 'api@civicrm.org',
3420 ]);
3421
3422 $mut->checkMailLog([
3423 'Annual CiviCRM meet',
3424 'Event',
3425 'To: "Mr. Anthony Anderson II" <anthony_anderson@civicrm.org>',
3426 ], []);
3427 $mut->stop();
3428 }
3429
3430 /**
3431 * This function does a GET & compares the result against the $params.
3432 *
3433 * Use as a double check on Creates.
3434 *
3435 * @param array $params
3436 * @param int $id
3437 * @param bool $delete
3438 */
3439 public function contributionGetnCheck($params, $id, $delete = TRUE) {
3440
3441 $contribution = $this->callAPISuccess('Contribution', 'Get', [
3442 'id' => $id,
3443 ]);
3444
3445 if ($delete) {
3446 $this->callAPISuccess('contribution', 'delete', ['id' => $id]);
3447 }
3448 $this->assertAPISuccess($contribution, 0);
3449 $values = $contribution['values'][$contribution['id']];
3450 $params['receive_date'] = date('Y-m-d H:i:s', strtotime($params['receive_date']));
3451 // this is not returned in id format
3452 unset($params['payment_instrument_id']);
3453 $params['contribution_source'] = $params['source'];
3454 unset($params['source']);
3455 foreach ($params as $key => $value) {
3456 $this->assertEquals($value, $values[$key], $key . " value: $value doesn't match " . print_r($values, TRUE));
3457 }
3458 }
3459
3460 /**
3461 * Create a pending contribution & linked pending pledge record.
3462 */
3463 public function createPendingPledgeContribution() {
3464
3465 $pledgeID = $this->pledgeCreate(['contact_id' => $this->_individualId, 'installments' => 1, 'amount' => 500]);
3466 $this->_ids['pledge'] = $pledgeID;
3467 $contribution = $this->callAPISuccess('contribution', 'create', array_merge($this->_params, [
3468 'contribution_status_id' => 'Pending',
3469 'total_amount' => 500,
3470 ]));
3471 $paymentID = $this->callAPISuccessGetValue('PledgePayment', [
3472 'options' => ['limit' => 1],
3473 'return' => 'id',
3474 ]);
3475 $this->callAPISuccess('PledgePayment', 'create', [
3476 'id' => $paymentID,
3477 'contribution_id' =>
3478 $contribution['id'],
3479 'status_id' => 'Pending',
3480 'scheduled_amount' => 500,
3481 ]);
3482
3483 return $contribution['id'];
3484 }
3485
3486 /**
3487 * Create a pending contribution & linked pending participant record (along with an event).
3488 */
3489 public function createPendingParticipantContribution() {
3490 $event = $this->eventCreate(['is_email_confirm' => 1, 'confirm_from_email' => 'test@civicrm.org']);
3491 $participantID = $this->participantCreate(['event_id' => $event['id'], 'status_id' => 6, 'contact_id' => $this->_individualId]);
3492 $this->_ids['participant'] = $participantID;
3493 $params = array_merge($this->_params, ['contact_id' => $this->_individualId, 'contribution_status_id' => 2, 'financial_type_id' => 'Event Fee']);
3494 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3495 $this->callAPISuccess('participant_payment', 'create', [
3496 'contribution_id' => $contribution['id'],
3497 'participant_id' => $participantID,
3498 ]);
3499 $this->callAPISuccess('line_item', 'get', [
3500 'entity_id' => $contribution['id'],
3501 'entity_table' => 'civicrm_contribution',
3502 'api.line_item.create' => [
3503 'entity_id' => $participantID,
3504 'entity_table' => 'civicrm_participant',
3505 ],
3506 ]);
3507 return $contribution['id'];
3508 }
3509
3510 /**
3511 * Get financial transaction amount.
3512 *
3513 * @param int $contId
3514 *
3515 * @return null|string
3516 */
3517 public function _getFinancialTrxnAmount($contId) {
3518 $query = "SELECT
3519 SUM( ft.total_amount ) AS total
3520 FROM civicrm_financial_trxn AS ft
3521 LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.id = ceft.financial_trxn_id
3522 WHERE ceft.entity_table = 'civicrm_contribution'
3523 AND ceft.entity_id = {$contId}";
3524
3525 $result = CRM_Core_DAO::singleValueQuery($query);
3526 return $result;
3527 }
3528
3529 /**
3530 * @param int $contId
3531 *
3532 * @return null|string
3533 */
3534 public function _getFinancialItemAmount($contId) {
3535 $lineItem = key(CRM_Price_BAO_LineItem::getLineItems($contId, 'contribution'));
3536 $query = "SELECT
3537 SUM(amount)
3538 FROM civicrm_financial_item
3539 WHERE entity_table = 'civicrm_line_item'
3540 AND entity_id = {$lineItem}";
3541 $result = CRM_Core_DAO::singleValueQuery($query);
3542 return $result;
3543 }
3544
3545 /**
3546 * @param int $contId
3547 * @param $context
3548 */
3549 public function _checkFinancialItem($contId, $context) {
3550 if ($context != 'paylater') {
3551 $params = [
3552 'entity_id' => $contId,
3553 'entity_table' => 'civicrm_contribution',
3554 ];
3555 $trxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($params, TRUE));
3556 $entityParams = [
3557 'financial_trxn_id' => $trxn['financial_trxn_id'],
3558 'entity_table' => 'civicrm_financial_item',
3559 ];
3560 $entityTrxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
3561 $params = [
3562 'id' => $entityTrxn['entity_id'],
3563 ];
3564 }
3565 if ($context == 'paylater') {
3566 $lineItems = CRM_Price_BAO_LineItem::getLineItems($contId, 'contribution');
3567 foreach ($lineItems as $key => $item) {
3568 $params = [
3569 'entity_id' => $key,
3570 'entity_table' => 'civicrm_line_item',
3571 ];
3572 $compareParams = ['status_id' => 1];
3573 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
3574 }
3575 }
3576 elseif ($context == 'refund') {
3577 $compareParams = [
3578 'status_id' => 1,
3579 'financial_account_id' => 1,
3580 'amount' => -100,
3581 ];
3582 }
3583 elseif ($context == 'cancelPending') {
3584 $compareParams = [
3585 'status_id' => 3,
3586 'financial_account_id' => 1,
3587 'amount' => -100,
3588 ];
3589 }
3590 elseif ($context == 'changeFinancial') {
3591 $lineKey = key(CRM_Price_BAO_LineItem::getLineItems($contId, 'contribution'));
3592 $params = [
3593 'entity_id' => $lineKey,
3594 'amount' => -100,
3595 ];
3596 $compareParams = [
3597 'financial_account_id' => 1,
3598 ];
3599 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
3600 $params = [
3601 'financial_account_id' => 3,
3602 'entity_id' => $lineKey,
3603 ];
3604 $compareParams = [
3605 'amount' => 100,
3606 ];
3607 }
3608 if ($context != 'paylater') {
3609 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
3610 }
3611 }
3612
3613 /**
3614 * Check correct financial transaction entries were created for the change in payment instrument.
3615 *
3616 * @param int $contributionID
3617 * @param int $originalInstrumentID
3618 * @param int $newInstrumentID
3619 * @param int $amount
3620 */
3621 public function checkFinancialTrxnPaymentInstrumentChange($contributionID, $originalInstrumentID, $newInstrumentID, $amount = 100) {
3622
3623 $entityFinancialTrxns = $this->getFinancialTransactionsForContribution($contributionID);
3624
3625 $originalTrxnParams = [
3626 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($originalInstrumentID),
3627 'payment_instrument_id' => $originalInstrumentID,
3628 'amount' => $amount,
3629 'status_id' => 1,
3630 ];
3631
3632 $reversalTrxnParams = [
3633 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($originalInstrumentID),
3634 'payment_instrument_id' => $originalInstrumentID,
3635 'amount' => -$amount,
3636 'status_id' => 1,
3637 ];
3638
3639 $newTrxnParams = [
3640 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($newInstrumentID),
3641 'payment_instrument_id' => $newInstrumentID,
3642 'amount' => $amount,
3643 'status_id' => 1,
3644 ];
3645
3646 foreach ([$originalTrxnParams, $reversalTrxnParams, $newTrxnParams] as $index => $transaction) {
3647 $entityFinancialTrxn = $entityFinancialTrxns[$index];
3648 $this->assertEquals($entityFinancialTrxn['amount'], $transaction['amount']);
3649
3650 $financialTrxn = $this->callAPISuccessGetSingle('FinancialTrxn', [
3651 'id' => $entityFinancialTrxn['financial_trxn_id'],
3652 ]);
3653 $this->assertEquals($transaction['status_id'], $financialTrxn['status_id']);
3654 $this->assertEquals($transaction['amount'], $financialTrxn['total_amount']);
3655 $this->assertEquals($transaction['amount'], $financialTrxn['net_amount']);
3656 $this->assertEquals(0, $financialTrxn['fee_amount']);
3657 $this->assertEquals($transaction['payment_instrument_id'], $financialTrxn['payment_instrument_id']);
3658 $this->assertEquals($transaction['to_financial_account_id'], $financialTrxn['to_financial_account_id']);
3659
3660 // Generic checks.
3661 $this->assertEquals(1, $financialTrxn['is_payment']);
3662 $this->assertEquals('USD', $financialTrxn['currency']);
3663 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($financialTrxn['trxn_date'])));
3664 }
3665 }
3666
3667 /**
3668 * Check financial transaction.
3669 *
3670 * @todo break this down into sensible functions - most calls to it only use a few lines out of the big if.
3671 *
3672 * @param array $contribution
3673 * @param string $context
3674 * @param int $instrumentId
3675 * @param array $extraParams
3676 */
3677 public function _checkFinancialTrxn($contribution, $context, $instrumentId = NULL, $extraParams = []) {
3678 $financialTrxns = $this->getFinancialTransactionsForContribution($contribution['id']);
3679 $trxn = array_pop($financialTrxns);
3680
3681 $params = [
3682 'id' => $trxn['financial_trxn_id'],
3683 ];
3684 if ($context == 'payLater') {
3685 $compareParams = [
3686 'status_id' => 1,
3687 'from_financial_account_id' => CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is'),
3688 ];
3689 }
3690 elseif ($context == 'refund') {
3691 $compareParams = [
3692 'to_financial_account_id' => 6,
3693 'total_amount' => -100,
3694 'status_id' => 7,
3695 'trxn_date' => '2015-01-01 09:00:00',
3696 'trxn_id' => 'the refund',
3697 ];
3698 }
3699 elseif ($context == 'cancelPending') {
3700 $compareParams = [
3701 'to_financial_account_id' => 7,
3702 'total_amount' => -100,
3703 'status_id' => 3,
3704 ];
3705 }
3706 elseif ($context == 'changeFinancial' || $context == 'paymentInstrument') {
3707 // @todo checkFinancialTrxnPaymentInstrumentChange instead for paymentInstrument.
3708 // It does the same thing with greater readability.
3709 // @todo remove handling for
3710
3711 $entityParams = [
3712 'entity_id' => $contribution['id'],
3713 'entity_table' => 'civicrm_contribution',
3714 'amount' => -100,
3715 ];
3716 $trxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
3717 $trxnParams1 = [
3718 'id' => $trxn['financial_trxn_id'],
3719 ];
3720 if (empty($extraParams)) {
3721 $compareParams = [
3722 'total_amount' => -100,
3723 'status_id' => 1,
3724 ];
3725 }
3726 else {
3727 $compareParams = [
3728 'total_amount' => 100,
3729 'status_id' => 1,
3730 ];
3731 }
3732 if ($context == 'paymentInstrument') {
3733 $compareParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($instrumentId);
3734 $compareParams['payment_instrument_id'] = $instrumentId;
3735 }
3736 else {
3737 $compareParams['to_financial_account_id'] = 12;
3738 }
3739 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams1, array_merge($compareParams, $extraParams));
3740 $compareParams['total_amount'] = 100;
3741 }
3742
3743 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $params, array_merge($compareParams, $extraParams));
3744 }
3745
3746 /**
3747 * @return mixed
3748 */
3749 public function _addPaymentInstrument() {
3750 $gId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'payment_instrument', 'id', 'name');
3751 $optionParams = [
3752 'option_group_id' => $gId,
3753 'label' => 'Test Card',
3754 'name' => 'Test Card',
3755 'value' => '6',
3756 'weight' => '6',
3757 'is_active' => 1,
3758 ];
3759 $optionValue = $this->callAPISuccess('option_value', 'create', $optionParams);
3760 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
3761 $financialParams = [
3762 'entity_table' => 'civicrm_option_value',
3763 'entity_id' => $optionValue['id'],
3764 'account_relationship' => $relationTypeId,
3765 'financial_account_id' => 7,
3766 ];
3767 CRM_Financial_BAO_FinancialTypeAccount::add($financialParams);
3768 $this->assertNotEmpty($optionValue['values'][$optionValue['id']]['value']);
3769 return $optionValue['values'][$optionValue['id']]['value'];
3770 }
3771
3772 public function _deletedAddedPaymentInstrument() {
3773 $result = $this->callAPISuccess('OptionValue', 'get', [
3774 'option_group_id' => 'payment_instrument',
3775 'name' => 'Test Card',
3776 'value' => '6',
3777 'is_active' => 1,
3778 ]);
3779 if ($id = CRM_Utils_Array::value('id', $result)) {
3780 $this->callAPISuccess('OptionValue', 'delete', ['id' => $id]);
3781 }
3782 }
3783
3784 /**
3785 * Set up the basic recurring contribution for tests.
3786 *
3787 * @param array $generalParams
3788 * Parameters that can be merged into the recurring AND the contribution.
3789 *
3790 * @param array $recurParams
3791 * Parameters to merge into the recur only.
3792 *
3793 * @return array|int
3794 */
3795 protected function setUpRecurringContribution($generalParams = [], $recurParams = []) {
3796 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
3797 'contact_id' => $this->_individualId,
3798 'installments' => '12',
3799 'frequency_interval' => '1',
3800 'amount' => '100',
3801 'contribution_status_id' => 1,
3802 'start_date' => '2012-01-01 00:00:00',
3803 'currency' => 'USD',
3804 'frequency_unit' => 'month',
3805 'payment_processor_id' => $this->paymentProcessorID,
3806 ], $generalParams, $recurParams));
3807 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
3808 $this->_params,
3809 [
3810 'contribution_recur_id' => $contributionRecur['id'],
3811 ], $generalParams)
3812 );
3813 return $originalContribution;
3814 }
3815
3816 /**
3817 * Set up a basic auto-renew membership for tests.
3818 *
3819 * @param array $generalParams
3820 * Parameters that can be merged into the recurring AND the contribution.
3821 *
3822 * @param array $recurParams
3823 * Parameters to merge into the recur only.
3824 *
3825 * @return array|int
3826 */
3827 protected function setUpAutoRenewMembership($generalParams = [], $recurParams = []) {
3828 $newContact = $this->callAPISuccess('Contact', 'create', [
3829 'contact_type' => 'Individual',
3830 'sort_name' => 'McTesterson, Testy',
3831 'display_name' => 'Testy McTesterson',
3832 'preferred_language' => 'en_US',
3833 'preferred_mail_format' => 'Both',
3834 'first_name' => 'Testy',
3835 'last_name' => 'McTesterson',
3836 'contact_is_deleted' => '0',
3837 'email_id' => '4',
3838 'email' => 'tmctesterson@example.com',
3839 'on_hold' => '0',
3840 ]);
3841 $membershipType = $this->callAPISuccess('MembershipType', 'create', [
3842 'domain_id' => "Default Domain Name",
3843 'member_of_contact_id' => 1,
3844 'financial_type_id' => "Member Dues",
3845 'duration_unit' => "month",
3846 'duration_interval' => 1,
3847 'period_type' => 'rolling',
3848 'name' => "Standard Member",
3849 'minimum_fee' => 100,
3850 ]);
3851 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
3852 'contact_id' => $newContact['id'],
3853 'installments' => '12',
3854 'frequency_interval' => '1',
3855 'amount' => '100',
3856 'contribution_status_id' => 1,
3857 'start_date' => '2012-01-01 00:00:00',
3858 'currency' => 'USD',
3859 'frequency_unit' => 'month',
3860 'payment_processor_id' => $this->paymentProcessorID,
3861 ], $generalParams, $recurParams));
3862
3863 $membership = $this->callAPISuccess('membership', 'create', [
3864 'contact_id' => $newContact['id'],
3865 'contribution_recur_id' => $contributionRecur['id'],
3866 'financial_type_id' => "Member Dues",
3867 'membership_type_id' => $membershipType['id'],
3868 'num_terms' => 1,
3869 'skipLineItem' => TRUE,
3870 ]);
3871
3872 CRM_Price_BAO_LineItem::getLineItemArray($this->_params, NULL, 'membership', $membershipType['id']);
3873 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
3874 $this->_params,
3875 [
3876 'contact_id' => $newContact['id'],
3877 'contribution_recur_id' => $contributionRecur['id'],
3878 'financial_type_id' => "Member Dues",
3879 'contribution_status_id' => 1,
3880 'invoice_id' => uniqid(),
3881 ], $generalParams)
3882 );
3883 $lineItem = $this->callAPISuccess('LineItem', 'getsingle', []);
3884 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
3885 $membership = $this->callAPISuccess('Membership', 'getsingle', ['id' => $lineItem['entity_id']]);
3886 $this->callAPISuccess('LineItem', 'getsingle', []);
3887 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']], 1);
3888
3889 return [$originalContribution, $membership];
3890 }
3891
3892 /**
3893 * Set up a repeat transaction.
3894 *
3895 * @param array $recurParams
3896 * @param mixed $flag
3897 * @param array $contributionParams
3898 * @return array
3899 */
3900 protected function setUpRepeatTransaction($recurParams = [], $flag, $contributionParams = []) {
3901 $paymentProcessorID = $this->paymentProcessorCreate();
3902 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
3903 'contact_id' => $this->_individualId,
3904 'installments' => '12',
3905 'frequency_interval' => '1',
3906 'amount' => '500',
3907 'contribution_status_id' => 1,
3908 'start_date' => '2012-01-01 00:00:00',
3909 'currency' => 'USD',
3910 'frequency_unit' => 'month',
3911 'payment_processor_id' => $paymentProcessorID,
3912 ], $recurParams));
3913
3914 $originalContribution = '';
3915 if ($flag == 'multiple') {
3916 // CRM-19309 create a contribution + also add in line_items (plural):
3917 $params = array_merge($this->_params, $contributionParams);
3918 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
3919 $params,
3920 [
3921 'contribution_recur_id' => $contributionRecur['id'],
3922 'skipLineItem' => 1,
3923 'api.line_item.create' => [
3924 [
3925 'price_field_id' => 1,
3926 'qty' => 2,
3927 'line_total' => '20',
3928 'unit_price' => '10',
3929 'financial_type_id' => 1,
3930 ],
3931 [
3932 'price_field_id' => 1,
3933 'qty' => 1,
3934 'line_total' => '80',
3935 'unit_price' => '80',
3936 'financial_type_id' => 2,
3937 ],
3938 ],
3939 ]
3940 )
3941 );
3942 }
3943 elseif ($flag == 'single') {
3944 $params = array_merge($this->_params, ['contribution_recur_id' => $contributionRecur['id']]);
3945 $params = array_merge($params, $contributionParams);
3946 $originalContribution = $this->callAPISuccess('contribution', 'create', $params);
3947 }
3948 $originalContribution['payment_processor_id'] = $paymentProcessorID;
3949 return $originalContribution;
3950 }
3951
3952 /**
3953 * Common set up routine.
3954 *
3955 * @return array
3956 */
3957 protected function setUpForCompleteTransaction() {
3958 $this->mut = new CiviMailUtils($this, TRUE);
3959 $this->createLoggedInUser();
3960 $params = array_merge($this->_params, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
3961 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3962 return $contribution;
3963 }
3964
3965 /**
3966 * Test repeat contribution uses the Payment Processor' payment_instrument setting.
3967 */
3968 public function testRepeatTransactionWithNonCreditCardDefault() {
3969 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
3970 'contact_id' => $this->_individualId,
3971 'installments' => '12',
3972 'frequency_interval' => '1',
3973 'amount' => '100',
3974 'contribution_status_id' => 1,
3975 'start_date' => '2012-01-01 00:00:00',
3976 'currency' => 'USD',
3977 'frequency_unit' => 'month',
3978 'payment_processor_id' => $this->paymentProcessorID,
3979 ]);
3980 $contribution1 = $this->callAPISuccess('contribution', 'create', array_merge(
3981 $this->_params,
3982 ['contribution_recur_id' => $contributionRecur['id'], 'payment_instrument_id' => 2])
3983 );
3984 $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name');
3985 $contribution2 = $this->callAPISuccess('contribution', 'repeattransaction', [
3986 'contribution_status_id' => 'Completed',
3987 'trxn_id' => uniqid(),
3988 'original_contribution_id' => $contribution1,
3989 ]);
3990 $this->assertEquals(array_search('Debit Card', $paymentInstruments), $contribution2['values'][$contribution2['id']]['payment_instrument_id']);
3991 $this->quickCleanUpFinancialEntities();
3992 }
3993
3994 /**
3995 * CRM-20008 Tests repeattransaction creates pending membership.
3996 */
3997 public function testRepeatTransactionMembershipCreatePendingContribution() {
3998 list($originalContribution, $membership) = $this->setUpAutoRenewMembership();
3999 $this->callAPISuccess('membership', 'create', [
4000 'id' => $membership['id'],
4001 'end_date' => 'yesterday',
4002 'status_id' => 'Expired',
4003 ]);
4004 $repeatedContribution = $this->callAPISuccess('contribution', 'repeattransaction', [
4005 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
4006 'contribution_status_id' => 'Pending',
4007 'trxn_id' => uniqid(),
4008 ]);
4009 $membershipStatusId = $this->callAPISuccess('membership', 'getvalue', [
4010 'id' => $membership['id'],
4011 'return' => 'status_id',
4012 ]);
4013
4014 // Let's see if the membership payments got created while we're at it.
4015 $membershipPayments = $this->callAPISuccess('MembershipPayment', 'get', [
4016 'membership_id' => $membership['id'],
4017 ]);
4018 $this->assertEquals(2, $membershipPayments['count']);
4019
4020 $this->assertEquals('Expired', CRM_Core_PseudoConstant::getLabel('CRM_Member_BAO_Membership', 'status_id', $membershipStatusId));
4021 $this->callAPISuccess('Contribution', 'completetransaction', ['id' => $repeatedContribution['id']]);
4022 $membership = $this->callAPISuccessGetSingle('membership', [
4023 'id' => $membership['id'],
4024 'return' => 'status_id, end_date',
4025 ]);
4026 $this->assertEquals('New', CRM_Core_PseudoConstant::getName('CRM_Member_BAO_Membership', 'status_id', $membership['status_id']));
4027 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 1 month')), $membership['end_date']);
4028
4029 $this->quickCleanUpFinancialEntities();
4030 $this->contactDelete($originalContribution['values'][1]['contact_id']);
4031 }
4032
4033 /**
4034 * Test sending a mail via the API.
4035 */
4036 public function testSendMailWithAPISetFromDetails() {
4037 $mut = new CiviMailUtils($this, TRUE);
4038 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
4039 $this->callAPISuccess('contribution', 'sendconfirmation', [
4040 'id' => $contribution['id'],
4041 'receipt_from_email' => 'api@civicrm.org',
4042 'receipt_from_name' => 'CiviCRM LLC',
4043 ]);
4044 $mut->checkMailLog([
4045 'From: CiviCRM LLC <api@civicrm.org>',
4046 'Contribution Information',
4047 'Please print this confirmation for your records',
4048 ], [
4049 'Event',
4050 ]);
4051 $mut->stop();
4052 }
4053
4054 /**
4055 * Test sending a mail via the API.
4056 */
4057 public function testSendMailWithNoFromSetFallToDomain() {
4058 $this->createLoggedInUser();
4059 $mut = new CiviMailUtils($this, TRUE);
4060 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
4061 $this->callAPISuccess('contribution', 'sendconfirmation', [
4062 'id' => $contribution['id'],
4063 ]);
4064 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => 1]);
4065 $mut->checkMailLog([
4066 'From: ' . $domain['from_name'] . ' <' . $domain['from_email'] . '>',
4067 'Contribution Information',
4068 'Please print this confirmation for your records',
4069 ], [
4070 'Event',
4071 ]);
4072 $mut->stop();
4073 }
4074
4075 /**
4076 * Test sending a mail via the API.
4077 */
4078 public function testSendMailWithRepeatTransactionAPIFalltoDomain() {
4079 $this->createLoggedInUser();
4080 $mut = new CiviMailUtils($this, TRUE);
4081 $contribution = $this->setUpRepeatTransaction([], 'single');
4082 $this->callAPISuccess('contribution', 'repeattransaction', [
4083 'contribution_status_id' => 'Completed',
4084 'trxn_id' => uniqid(),
4085 'original_contribution_id' => $contribution,
4086 ]);
4087 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => 1]);
4088 $mut->checkMailLog([
4089 'From: ' . $domain['from_name'] . ' <' . $domain['from_email'] . '>',
4090 'Contribution Information',
4091 'Please print this confirmation for your records',
4092 ], [
4093 'Event',
4094 ]
4095 );
4096 $mut->stop();
4097 }
4098
4099 /**
4100 * Test sending a mail via the API.
4101 */
4102 public function testSendMailWithRepeatTransactionAPIFalltoContributionPage() {
4103 $mut = new CiviMailUtils($this, TRUE);
4104 $contributionPage = $this->contributionPageCreate(['receipt_from_name' => 'CiviCRM LLC', 'receipt_from_email' => 'contributionpage@civicrm.org', 'is_email_receipt' => 1]);
4105 $paymentProcessorID = $this->paymentProcessorCreate();
4106 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
4107 'contact_id' => $this->_individualId,
4108 'installments' => '12',
4109 'frequency_interval' => '1',
4110 'amount' => '500',
4111 'contribution_status_id' => 1,
4112 'start_date' => '2012-01-01 00:00:00',
4113 'currency' => 'USD',
4114 'frequency_unit' => 'month',
4115 'payment_processor_id' => $paymentProcessorID,
4116 ]);
4117 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
4118 $this->_params,
4119 [
4120 'contribution_recur_id' => $contributionRecur['id'],
4121 'contribution_page_id' => $contributionPage['id'],
4122 ])
4123 );
4124 $this->callAPISuccess('contribution', 'repeattransaction', [
4125 'contribution_status_id' => 'Completed',
4126 'trxn_id' => uniqid(),
4127 'original_contribution_id' => $originalContribution,
4128 ]
4129 );
4130 $mut->checkMailLog([
4131 'From: CiviCRM LLC <contributionpage@civicrm.org>',
4132 'Contribution Information',
4133 'Please print this confirmation for your records',
4134 ], [
4135 'Event',
4136 ]);
4137 $mut->stop();
4138 }
4139
4140 /**
4141 * Test sending a mail via the API.
4142 */
4143 public function testSendMailWithRepeatTransactionAPIFalltoSystemFromNoDefaultFrom() {
4144 $mut = new CiviMailUtils($this, TRUE);
4145 $originalContribution = $contribution = $this->setUpRepeatTransaction([], 'single');
4146 $fromEmail = $this->CallAPISuccess('optionValue', 'get', ['is_default' => 1, 'option_group_id' => 'from_email_address', 'sequential' => 1]);
4147 foreach ($fromEmail['values'] as $from) {
4148 $this->callAPISuccess('optionValue', 'create', ['is_default' => 0, 'id' => $from['id']]);
4149 }
4150 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => CRM_Core_Config::domainID()]);
4151 $this->callAPISuccess('contribution', 'repeattransaction', [
4152 'contribution_status_id' => 'Completed',
4153 'trxn_id' => uniqid(),
4154 'original_contribution_id' => $originalContribution,
4155 ]);
4156 $mut->checkMailLog([
4157 'From: ' . $domain['name'] . ' <' . $domain['domain_email'] . '>',
4158 'Contribution Information',
4159 'Please print this confirmation for your records',
4160 ], [
4161 'Event',
4162 ]);
4163 $mut->stop();
4164 }
4165
4166 /**
4167 * Create a Contribution Page with is_email_receipt = TRUE.
4168 *
4169 * @param array $params
4170 * Params to overwrite with.
4171 *
4172 * @return array|int
4173 */
4174 protected function createReceiptableContributionPage($params = []) {
4175 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', array_merge([
4176 'receipt_from_name' => 'Mickey Mouse',
4177 'receipt_from_email' => 'mickey@mouse.com',
4178 'title' => "Test Contribution Page",
4179 'financial_type_id' => 1,
4180 'currency' => 'CAD',
4181 'is_monetary' => TRUE,
4182 'is_email_receipt' => TRUE,
4183 ], $params));
4184 return $contributionPage;
4185 }
4186
4187 /**
4188 * function to test card_type and pan truncation.
4189 */
4190 public function testCardTypeAndPanTruncation() {
4191 $creditCardTypeIDs = array_flip(CRM_Financial_DAO_FinancialTrxn::buildOptions('card_type_id'));
4192 $contactId = $this->individualCreate();
4193 $params = [
4194 'contact_id' => $contactId,
4195 'receive_date' => '2016-01-20',
4196 'total_amount' => 100,
4197 'financial_type_id' => 1,
4198 'payment_instrument' => 'Credit Card',
4199 'card_type_id' => $creditCardTypeIDs['Visa'],
4200 'pan_truncation' => 4567,
4201 ];
4202 $contribution = $this->callAPISuccess('contribution', 'create', $params);
4203 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
4204 $financialTrxn = $this->callAPISuccessGetSingle(
4205 'FinancialTrxn',
4206 [
4207 'id' => $lastFinancialTrxnId['financialTrxnId'],
4208 'return' => ['card_type_id', 'pan_truncation'],
4209 ]
4210 );
4211 $this->assertEquals(CRM_Utils_Array::value('card_type_id', $financialTrxn), $creditCardTypeIDs['Visa']);
4212 $this->assertEquals(CRM_Utils_Array::value('pan_truncation', $financialTrxn), 4567);
4213 $params = [
4214 'id' => $contribution['id'],
4215 'pan_truncation' => 2345,
4216 'card_type_id' => $creditCardTypeIDs['Amex'],
4217 ];
4218 $contribution = $this->callAPISuccess('contribution', 'create', $params);
4219 $financialTrxn = $this->callAPISuccessGetSingle(
4220 'FinancialTrxn',
4221 [
4222 'id' => $lastFinancialTrxnId['financialTrxnId'],
4223 'return' => ['card_type_id', 'pan_truncation'],
4224 ]
4225 );
4226 $this->assertEquals(CRM_Utils_Array::value('card_type_id', $financialTrxn), $creditCardTypeIDs['Amex']);
4227 $this->assertEquals(CRM_Utils_Array::value('pan_truncation', $financialTrxn), 2345);
4228 }
4229
4230 /**
4231 * Test repeat contribution uses non default currency
4232 * @see https://issues.civicrm.org/jira/projects/CRM/issues/CRM-20678
4233 */
4234 public function testRepeatTransactionWithDifferenceCurrency() {
4235 $originalContribution = $this->setUpRepeatTransaction(['currency' => 'AUD'], 'single', ['currency' => 'AUD']);
4236 $contribution = $this->callAPISuccess('contribution', 'repeattransaction', [
4237 'original_contribution_id' => $originalContribution['id'],
4238 'contribution_status_id' => 'Completed',
4239 'trxn_id' => uniqid(),
4240 ]);
4241 $this->assertEquals('AUD', $contribution['values'][$contribution['id']]['currency']);
4242 }
4243
4244 /**
4245 * Get the financial items for the contribution.
4246 *
4247 * @param int $contributionID
4248 *
4249 * @return array
4250 * Array of associated financial items.
4251 */
4252 protected function getFinancialTransactionsForContribution($contributionID) {
4253 $trxnParams = [
4254 'entity_id' => $contributionID,
4255 'entity_table' => 'civicrm_contribution',
4256 ];
4257 // @todo the following function has naming errors & has a weird signature & appears to
4258 // only be called from test classes. Move into test suite & maybe just use api
4259 // from this function.
4260 return array_merge(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($trxnParams, FALSE, []));
4261 }
4262
4263 /**
4264 * Test getunique api call for Contribution entity
4265 */
4266 public function testContributionGetUnique() {
4267 $result = $this->callAPIAndDocument($this->_entity, 'getunique', [], __FUNCTION__, __FILE__);
4268 $this->assertEquals(2, $result['count']);
4269 $this->assertEquals(['trxn_id'], $result['values']['UI_contrib_trxn_id']);
4270 $this->assertEquals(['invoice_id'], $result['values']['UI_contrib_invoice_id']);
4271 }
4272
4273 /**
4274 * Test Repeat Transaction Contribution with Tax amount.
4275 * https://lab.civicrm.org/dev/core/issues/806
4276 */
4277 public function testRepeatContributionWithTaxAmount() {
4278 $this->enableTaxAndInvoicing();
4279 $financialType = $this->callAPISuccess('financial_type', 'create', [
4280 'name' => 'Test taxable financial Type',
4281 'is_reserved' => 0,
4282 'is_active' => 1,
4283 ]);
4284 $this->relationForFinancialTypeWithFinancialAccount($financialType['id']);
4285 $contribution = $this->setUpRepeatTransaction(
4286 [],
4287 'single',
4288 [
4289 'financial_type_id' => $financialType['id'],
4290 ]
4291 );
4292 $this->callAPISuccess('contribution', 'repeattransaction', [
4293 'original_contribution_id' => $contribution['id'],
4294 'contribution_status_id' => 'Completed',
4295 'trxn_id' => uniqid(),
4296 ]);
4297 $this->callAPISuccessGetCount('Contribution', [], 2);
4298 }
4299
4300 public function testGetCurrencyOptions() {
4301 $result = $this->callAPISuccess('Contribution', 'getoptions', [
4302 'field' => 'currency',
4303 ]);
4304 $this->assertEquals('US Dollar', $result['values']['USD']);
4305 $this->assertNotContains('$', $result['values']);
4306 $result = $this->callAPISuccess('Contribution', 'getoptions', [
4307 'field' => 'currency',
4308 'context' => "abbreviate",
4309 ]);
4310 $this->assertEquals('$', $result['values']['USD']);
4311 $this->assertNotContains('US Dollar', $result['values']);
4312 }
4313
4314 }