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