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