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