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