Merge pull request #18838 from eileenmcnaughton/vrenew
[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 original contribution where there
2810 * is more than one line item.
2811 */
2812 public function testRepeatTransactionPassedInFinancialTypeTwoLineItems() {
2813 $this->_params = $this->getParticipantOrderParams();
2814 $originalContribution = $this->setUpRecurringContribution();
2815
2816 $this->callAPISuccess('Contribution', 'repeattransaction', [
2817 'original_contribution_id' => $originalContribution['id'],
2818 'contribution_status_id' => 'Completed',
2819 'trxn_id' => 'repeat',
2820 'financial_type_id' => 2,
2821 ]);
2822
2823 // Retrieve the new contribution and note the financial type passed in has been ignored.
2824 $contribution = $this->callAPISuccessGetSingle('Contribution', [
2825 'trxn_id' => 'repeat',
2826 ]);
2827 $this->assertEquals(4, $contribution['financial_type_id']);
2828
2829 $lineItems = $this->callAPISuccess('line_item', 'get', [
2830 'entity_id' => $contribution['id'],
2831 ])['values'];
2832 foreach ($lineItems as $lineItem) {
2833 $this->assertNotEquals(2, $lineItem['financial_type_id']);
2834 }
2835 }
2836
2837 /**
2838 * CRM-17718 test appropriate action if financial type has changed for single line items.
2839 */
2840 public function testRepeatTransactionUpdatedFinancialType() {
2841 $originalContribution = $this->setUpRecurringContribution([], ['financial_type_id' => 2]);
2842
2843 $this->callAPISuccess('contribution', 'repeattransaction', [
2844 'contribution_recur_id' => $originalContribution['id'],
2845 'contribution_status_id' => 'Completed',
2846 'trxn_id' => uniqid(),
2847 ]);
2848 $lineItemParams = [
2849 'entity_id' => $originalContribution['id'],
2850 'sequential' => 1,
2851 'return' => [
2852 'entity_table',
2853 'qty',
2854 'unit_price',
2855 'line_total',
2856 'label',
2857 'financial_type_id',
2858 'deductible_amount',
2859 'price_field_value_id',
2860 'price_field_id',
2861 ],
2862 ];
2863
2864 $this->callAPISuccessGetSingle('contribution', [
2865 'total_amount' => 100,
2866 'financial_type_id' => 2,
2867 ]);
2868 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2869 'entity_id' => $originalContribution['id'],
2870 ]));
2871 $expectedLineItem = array_merge(
2872 $lineItem1['values'][0], [
2873 'line_total' => '100.00',
2874 'unit_price' => '100.00',
2875 'financial_type_id' => 2,
2876 'contribution_type_id' => 2,
2877 ]
2878 );
2879
2880 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2881 'entity_id' => $originalContribution['id'] + 1,
2882 ]));
2883 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2884 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2885 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2886 }
2887
2888 /**
2889 * CRM-16397 test appropriate action if campaign has been passed in.
2890 */
2891 public function testRepeatTransactionPassedInCampaign() {
2892 $paymentProcessorID = $this->paymentProcessorCreate();
2893 $campaignID = $this->campaignCreate();
2894 $campaignID2 = $this->campaignCreate();
2895 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2896 'contact_id' => $this->_individualId,
2897 'installments' => '12',
2898 'frequency_interval' => '1',
2899 'amount' => '100',
2900 'contribution_status_id' => 1,
2901 'start_date' => '2012-01-01 00:00:00',
2902 'currency' => 'USD',
2903 'frequency_unit' => 'month',
2904 'payment_processor_id' => $paymentProcessorID,
2905 ]);
2906 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2907 $this->_params,
2908 [
2909 'contribution_recur_id' => $contributionRecur['id'],
2910 'campaign_id' => $campaignID,
2911 ])
2912 );
2913
2914 $this->callAPISuccess('contribution', 'repeattransaction', [
2915 'original_contribution_id' => $originalContribution['id'],
2916 'contribution_status_id' => 'Completed',
2917 'trxn_id' => uniqid(),
2918 'campaign_id' => $campaignID2,
2919 ]);
2920
2921 $this->callAPISuccessGetSingle('contribution', [
2922 'total_amount' => 100,
2923 'campaign_id' => $campaignID2,
2924 ]);
2925 }
2926
2927 /**
2928 * CRM-17718 campaign stored on contribution recur gets priority.
2929 *
2930 * This reflects the fact we permit people to update them.
2931 */
2932 public function testRepeatTransactionUpdatedCampaign() {
2933 $paymentProcessorID = $this->paymentProcessorCreate();
2934 $campaignID = $this->campaignCreate();
2935 $campaignID2 = $this->campaignCreate();
2936 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2937 'contact_id' => $this->_individualId,
2938 'installments' => '12',
2939 'frequency_interval' => '1',
2940 'amount' => '100',
2941 'contribution_status_id' => 1,
2942 'start_date' => '2012-01-01 00:00:00',
2943 'currency' => 'USD',
2944 'frequency_unit' => 'month',
2945 'payment_processor_id' => $paymentProcessorID,
2946 'campaign_id' => $campaignID,
2947 ]);
2948 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2949 $this->_params,
2950 [
2951 'contribution_recur_id' => $contributionRecur['id'],
2952 'campaign_id' => $campaignID2,
2953 ])
2954 );
2955
2956 $this->callAPISuccess('contribution', 'repeattransaction', [
2957 'original_contribution_id' => $originalContribution['id'],
2958 'contribution_status_id' => 'Completed',
2959 'trxn_id' => uniqid(),
2960 ]);
2961
2962 $this->callAPISuccessGetSingle('contribution', [
2963 'total_amount' => 100,
2964 'campaign_id' => $campaignID,
2965 ]);
2966 }
2967
2968 /**
2969 * CRM-20685 Repeattransaction produces incorrect Financial Type ID (in specific circumstance) - if number of lineItems = 1.
2970 *
2971 * This case happens when the line item & contribution do not have the same type in his initiating transaction.
2972 */
2973 public function testRepeatTransactionUpdatedFinancialTypeAndNotEquals() {
2974 $originalContribution = $this->setUpRecurringContribution([], ['financial_type_id' => 2]);
2975 // This will made the trick to get the not equals behaviour.
2976 $this->callAPISuccess('line_item', 'create', ['id' => 1, 'financial_type_id' => 4]);
2977 $this->callAPISuccess('contribution', 'repeattransaction', [
2978 'contribution_recur_id' => $originalContribution['id'],
2979 'contribution_status_id' => 'Completed',
2980 'trxn_id' => uniqid(),
2981 ]);
2982 $lineItemParams = [
2983 'entity_id' => $originalContribution['id'],
2984 'sequential' => 1,
2985 'return' => [
2986 'entity_table',
2987 'qty',
2988 'unit_price',
2989 'line_total',
2990 'label',
2991 'financial_type_id',
2992 'deductible_amount',
2993 'price_field_value_id',
2994 'price_field_id',
2995 ],
2996 ];
2997 $this->callAPISuccessGetSingle('contribution', [
2998 'total_amount' => 100,
2999 'financial_type_id' => 2,
3000 ]);
3001 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
3002 'entity_id' => $originalContribution['id'],
3003 ]));
3004 $expectedLineItem = array_merge(
3005 $lineItem1['values'][0], [
3006 'line_total' => '100.00',
3007 'unit_price' => '100.00',
3008 'financial_type_id' => 4,
3009 'contribution_type_id' => 4,
3010 ]
3011 );
3012
3013 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
3014 'entity_id' => $originalContribution['id'] + 1,
3015 ]));
3016 $this->callAPISuccess('line_item', 'create', ['id' => 1, 'financial_type_id' => 1]);
3017 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
3018 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
3019 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
3020 }
3021
3022 /**
3023 * Test completing a transaction does not 'mess' with net amount (CRM-15960).
3024 */
3025 public function testCompleteTransactionNetAmountOK() {
3026 $this->createLoggedInUser();
3027 $params = array_merge($this->_params, ['contribution_status_id' => 2]);
3028 unset($params['net_amount']);
3029 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3030 $this->callAPISuccess('contribution', 'completetransaction', [
3031 'id' => $contribution['id'],
3032 ]);
3033 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
3034 $this->assertEquals('Completed', $contribution['contribution_status']);
3035 $this->assertTrue(($contribution['total_amount'] - $contribution['net_amount']) == $contribution['fee_amount']);
3036 }
3037
3038 /**
3039 * CRM-14151 - Test completing a transaction via the API.
3040 */
3041 public function testCompleteTransactionWithReceiptDateSet() {
3042 $this->swapMessageTemplateForTestTemplate();
3043 $mut = new CiviMailUtils($this, TRUE);
3044 $this->createLoggedInUser();
3045 $params = array_merge($this->_params, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
3046 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3047 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contribution['id'], 'trxn_date' => date('Y-m-d')]);
3048 $contribution = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id'], 'sequential' => 1]);
3049 $this->assertEquals('Completed', $contribution['values'][0]['contribution_status']);
3050 // Make sure receive_date is original date and make sure payment date is today
3051 $this->assertEquals('2012-05-11', date('Y-m-d', strtotime($contribution['values'][0]['receive_date'])));
3052 $payment = $this->callAPISuccess('payment', 'get', ['contribution_id' => $contribution['id'], 'sequential' => 1]);
3053 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($payment['values'][0]['trxn_date'])));
3054 $mut->checkMailLog([
3055 'Receipt - Contribution',
3056 'receipt_date:::' . date('Ymd'),
3057 ]);
3058 $mut->stop();
3059 $this->revertTemplateToReservedTemplate();
3060 }
3061
3062 /**
3063 * CRM-1960 - Test to ensure that completetransaction respects the is_email_receipt setting
3064 */
3065 public function testCompleteTransactionWithEmailReceiptInput() {
3066 $contributionPage = $this->createReceiptableContributionPage();
3067
3068 $this->_params['contribution_page_id'] = $contributionPage['id'];
3069 $params = array_merge($this->_params, ['contribution_status_id' => 2]);
3070 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3071 // Complete the transaction overriding is_email_receipt to = FALSE
3072 $this->callAPISuccess('contribution', 'completetransaction', [
3073 'id' => $contribution['id'],
3074 'trxn_date' => date('2011-04-09'),
3075 'trxn_id' => 'kazam',
3076 'is_email_receipt' => 0,
3077 ]);
3078 // Check if a receipt was issued
3079 $receipt_date = $this->callAPISuccess('Contribution', 'getvalue', ['id' => $contribution['id'], 'return' => 'receipt_date']);
3080 $this->assertEquals('', $receipt_date);
3081 }
3082
3083 /**
3084 * Test that $is_recur is assigned to the receipt.
3085 */
3086 public function testCompleteTransactionForRecurring() {
3087 $this->mut = new CiviMailUtils($this, TRUE);
3088 $this->swapMessageTemplateForTestTemplate();
3089 $recurring = $this->setUpRecurringContribution();
3090 $contributionPage = $this->createReceiptableContributionPage(['is_recur' => TRUE, 'recur_frequency_unit' => 'month', 'recur_interval' => 1]);
3091
3092 $this->_params['contribution_page_id'] = $contributionPage['id'];
3093 $this->_params['contribution_recur_id'] = $recurring['id'];
3094
3095 $contribution = $this->setUpForCompleteTransaction();
3096
3097 $this->callAPISuccess('contribution', 'completetransaction', [
3098 'id' => $contribution['id'],
3099 'trxn_date' => date('2011-04-09'),
3100 'trxn_id' => 'kazam',
3101 'is_email_receipt' => 1,
3102 ]);
3103
3104 $this->mut->checkMailLog([
3105 'is_recur:::1',
3106 'cancelSubscriptionUrl:::' . CIVICRM_UF_BASEURL,
3107 ]);
3108 $this->mut->stop();
3109 $this->revertTemplateToReservedTemplate();
3110 }
3111
3112 /**
3113 * CRM-19710 - Test to ensure that completetransaction respects the input for is_email_receipt setting.
3114 *
3115 * If passed in it will override the default from contribution page.
3116 */
3117 public function testCompleteTransactionWithEmailReceiptInputTrue() {
3118 $mut = new CiviMailUtils($this, TRUE);
3119 $this->createLoggedInUser();
3120 // Create a Contribution Page with is_email_receipt = FALSE
3121 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', [
3122 'receipt_from_name' => 'Mickey Mouse',
3123 'receipt_from_email' => 'mickey@mouse.com',
3124 'title' => "Test Contribution Page",
3125 'financial_type_id' => 1,
3126 'currency' => 'CAD',
3127 'is_monetary' => TRUE,
3128 'is_email_receipt' => 0,
3129 ]);
3130 $this->_params['contribution_page_id'] = $contributionPage['id'];
3131 $params = array_merge($this->_params, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
3132 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3133 // Complete the transaction overriding is_email_receipt to = TRUE
3134 $this->callAPISuccess('contribution', 'completetransaction', [
3135 'id' => $contribution['id'],
3136 'is_email_receipt' => 1,
3137 ]);
3138 $mut->checkMailLog([
3139 'Contribution Information',
3140 ]);
3141 $mut->stop();
3142 }
3143
3144 /**
3145 * Complete the transaction using the template with all the possible.
3146 */
3147 public function testCompleteTransactionWithTestTemplate() {
3148 $this->swapMessageTemplateForTestTemplate();
3149 $contribution = $this->setUpForCompleteTransaction();
3150 $this->callAPISuccess('contribution', 'completetransaction', [
3151 'id' => $contribution['id'],
3152 'trxn_date' => date('2011-04-09'),
3153 'trxn_id' => 'kazam',
3154 ]);
3155 $receive_date = $this->callAPISuccess('Contribution', 'getvalue', ['id' => $contribution['id'], 'return' => 'receive_date']);
3156 $this->mut->checkMailLog([
3157 'email:::anthony_anderson@civicrm.org',
3158 'is_monetary:::1',
3159 'amount:::100.00',
3160 'currency:::USD',
3161 'receive_date:::' . date('Ymd', strtotime($receive_date)),
3162 'receipt_date:::' . date('Ymd'),
3163 'contributeMode:::notify',
3164 'title:::Contribution',
3165 'displayName:::Mr. Anthony Anderson II',
3166 'trxn_id:::kazam',
3167 'contactID:::' . $this->_params['contact_id'],
3168 'contributionID:::' . $contribution['id'],
3169 'financialTypeId:::1',
3170 'financialTypeName:::Donation',
3171 ]);
3172 $this->mut->stop();
3173 $this->revertTemplateToReservedTemplate();
3174 }
3175
3176 /**
3177 * Complete the transaction using the template with all the possible.
3178 */
3179 public function testCompleteTransactionContributionPageFromAddress() {
3180 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', [
3181 'receipt_from_name' => 'Mickey Mouse',
3182 'receipt_from_email' => 'mickey@mouse.com',
3183 'title' => "Test Contribution Page",
3184 'financial_type_id' => 1,
3185 'currency' => 'NZD',
3186 'goal_amount' => 50,
3187 'is_pay_later' => 1,
3188 'is_monetary' => TRUE,
3189 'is_email_receipt' => TRUE,
3190 ]);
3191 $this->_params['contribution_page_id'] = $contributionPage['id'];
3192 $contribution = $this->setUpForCompleteTransaction();
3193 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contribution['id']]);
3194 $this->mut->checkMailLog([
3195 'mickey@mouse.com',
3196 'Mickey Mouse <',
3197 ]);
3198 $this->mut->stop();
3199 }
3200
3201 /**
3202 * Test completing first transaction in a recurring series.
3203 *
3204 * The status should be set to 'in progress' and the next scheduled payment date calculated.
3205 *
3206 * @dataProvider getScheduledDateData
3207 *
3208 * @param array $dataSet
3209 *
3210 * @throws \Exception
3211 */
3212 public function testCompleteTransactionSetStatusToInProgress($dataSet) {
3213 $paymentProcessorID = $this->paymentProcessorCreate();
3214 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
3215 'contact_id' => $this->_individualId,
3216 'installments' => '2',
3217 'frequency_interval' => '1',
3218 'amount' => '500',
3219 'contribution_status_id' => 'Pending',
3220 'start_date' => '2012-01-01 00:00:00',
3221 'currency' => 'USD',
3222 'frequency_unit' => 'month',
3223 'payment_processor_id' => $paymentProcessorID,
3224 ], $dataSet['data']));
3225 $contribution = $this->callAPISuccess('contribution', 'create', array_merge(
3226 $this->_params,
3227 [
3228 'contribution_recur_id' => $contributionRecur['id'],
3229 'contribution_status_id' => 'Pending',
3230 'receive_date' => $dataSet['receive_date'],
3231 ])
3232 );
3233 $this->callAPISuccess('Contribution', 'completetransaction', [
3234 'id' => $contribution,
3235 'receive_date' => $dataSet['receive_date'],
3236 ]);
3237 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
3238 'id' => $contributionRecur['id'],
3239 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
3240 ]);
3241 $this->assertEquals(5, $contributionRecur['contribution_status_id']);
3242 $this->assertEquals($dataSet['expected'], $contributionRecur['next_sched_contribution_date']);
3243 $this->callAPISuccess('Contribution', 'create', array_merge(
3244 $this->_params,
3245 [
3246 'contribution_recur_id' => $contributionRecur['id'],
3247 'contribution_status_id' => 'Completed',
3248 ]
3249 ));
3250 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
3251 'id' => $contributionRecur['id'],
3252 'return' => ['contribution_status_id'],
3253 ]);
3254 $this->assertEquals(1, $contributionRecur['contribution_status_id']);
3255 }
3256
3257 /**
3258 * Get dates for testing.
3259 *
3260 * @return array
3261 */
3262 public function getScheduledDateData() {
3263 $result = [];
3264 $result[]['2016-08-31-1-month'] = [
3265 'data' => [
3266 'start_date' => '2016-08-31',
3267 'frequency_interval' => 1,
3268 'frequency_unit' => 'month',
3269 ],
3270 'receive_date' => '2016-08-31',
3271 'expected' => '2016-10-01 00:00:00',
3272 ];
3273 $result[]['2012-01-01-1-month'] = [
3274 'data' => [
3275 'start_date' => '2012-01-01',
3276 'frequency_interval' => 1,
3277 'frequency_unit' => 'month',
3278 ],
3279 'receive_date' => '2012-01-01',
3280 'expected' => '2012-02-01 00:00:00',
3281 ];
3282 $result[]['2012-01-01-1-month'] = [
3283 'data' => [
3284 'start_date' => '2012-01-01',
3285 'frequency_interval' => 1,
3286 'frequency_unit' => 'month',
3287 ],
3288 'receive_date' => '2012-02-29',
3289 'expected' => '2012-03-29 00:00:00',
3290 ];
3291 $result['receive_date_includes_time']['2012-01-01-1-month'] = [
3292 'data' => [
3293 'start_date' => '2012-01-01',
3294 'frequency_interval' => 1,
3295 'frequency_unit' => 'month',
3296 'next_sched_contribution_date' => '2012-02-29',
3297 ],
3298 'receive_date' => '2012-02-29 16:00:00',
3299 'expected' => '2012-03-29 00:00:00',
3300 ];
3301 return $result;
3302 }
3303
3304 /**
3305 * Test completing a pledge with the completeTransaction api..
3306 *
3307 * Note that we are creating a logged in user because email goes out from
3308 * that person.
3309 */
3310 public function testCompleteTransactionUpdatePledgePayment() {
3311 $this->swapMessageTemplateForTestTemplate();
3312 $mut = new CiviMailUtils($this, TRUE);
3313 $mut->clearMessages();
3314 $this->createLoggedInUser();
3315 $contributionID = $this->createPendingPledgeContribution();
3316 $this->callAPISuccess('contribution', 'completetransaction', [
3317 'id' => $contributionID,
3318 'trxn_date' => '1 Feb 2013',
3319 ]);
3320 $pledge = $this->callAPISuccessGetSingle('Pledge', [
3321 'id' => $this->_ids['pledge'],
3322 ]);
3323 $this->assertEquals('Completed', $pledge['pledge_status']);
3324
3325 $status = $this->callAPISuccessGetValue('PledgePayment', [
3326 'pledge_id' => $this->_ids['pledge'],
3327 'return' => 'status_id',
3328 ]);
3329 $this->assertEquals(1, $status);
3330 $mut->checkMailLog([
3331 'amount:::500.00',
3332 // The `receive_date` should remain as it was created.
3333 // TODO: the latest payment transaction date (and maybe other details,
3334 // such as amount and payment instrument) would be a useful token to make
3335 // available.
3336 'receive_date:::20120511000000',
3337 "receipt_date:::\n",
3338 ]);
3339 $mut->stop();
3340 $this->revertTemplateToReservedTemplate();
3341 }
3342
3343 /**
3344 * Test completing a transaction with an event via the API.
3345 *
3346 * Note that we are creating a logged in user because email goes out from
3347 * that person
3348 *
3349 * @throws \CRM_Core_Exception
3350 */
3351 public function testCompleteTransactionWithParticipantRecord() {
3352 $mut = new CiviMailUtils($this, TRUE);
3353 $mut->clearMessages();
3354 $this->_individualId = $this->createLoggedInUser();
3355 // Unset source to test whether one is generated if not set already on the contribution.
3356 unset($this->_params['source']);
3357 $contributionID = $this->createPendingParticipantContribution();
3358 $this->createJoinedProfile(['entity_id' => $this->_ids['event']['test'], 'entity_table' => 'civicrm_event']);
3359 $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']);
3360 $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']);
3361 $this->eliminateUFGroupOne();
3362
3363 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contributionID]);
3364 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID, 'return' => ['contribution_source']]);
3365 $this->assertEquals('Online Event Registration: Annual CiviCRM meet', $contribution['contribution_source']);
3366 $participantStatus = $this->callAPISuccessGetValue('participant', [
3367 'id' => $this->_ids['participant'],
3368 'return' => 'participant_status_id',
3369 ]);
3370 $this->assertEquals(1, $participantStatus);
3371
3372 //Assert only three activities are created.
3373 $activities = $this->callAPISuccess('Activity', 'get', [
3374 'contact_id' => $this->_individualId,
3375 ])['values'];
3376
3377 $this->assertCount(3, $activities);
3378 $activityNames = array_count_values(CRM_Utils_Array::collect('activity_name', $activities));
3379 // record two activities before and after completing payment for Event registration
3380 $this->assertEquals(2, $activityNames['Event Registration']);
3381 // update the original 'Contribution' activity created after completing payment
3382 $this->assertEquals(1, $activityNames['Contribution']);
3383
3384 $mut->checkMailLog([
3385 'Annual CiviCRM meet',
3386 'Event',
3387 'This is a confirmation that your registration has been received and your status has been updated to Registered.',
3388 'First Name: Logged In',
3389 'Public title',
3390 'public 2',
3391 'public 3',
3392 ], ['Back end title', 'title_post_2', 'title_post_3']);
3393 $mut->stop();
3394 }
3395
3396 /**
3397 * Test membership is renewed when transaction completed.
3398 */
3399 public function testCompleteTransactionMembershipPriceSet() {
3400 $this->createPriceSetWithPage('membership');
3401 $stateOfGrace = $this->callAPISuccess('MembershipStatus', 'getvalue', [
3402 'name' => 'Grace',
3403 'return' => 'id',
3404 ]);
3405 $this->setUpPendingContribution($this->_ids['price_field_value'][0]);
3406 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids['membership']]);
3407 $logs = $this->callAPISuccess('MembershipLog', 'get', [
3408 'membership_id' => $this->_ids['membership'],
3409 ]);
3410 $this->assertEquals(1, $logs['count']);
3411 $this->assertEquals($stateOfGrace, $membership['status_id']);
3412 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $this->_ids['contribution']]);
3413 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids['membership']]);
3414 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 1 year')), $membership['end_date']);
3415 $this->callAPISuccessGetSingle('LineItem', [
3416 'entity_id' => $this->_ids['membership'],
3417 'entity_table' => 'civicrm_membership',
3418 ]);
3419 $logs = $this->callAPISuccess('MembershipLog', 'get', [
3420 'membership_id' => $this->_ids['membership'],
3421 ]);
3422 $this->assertEquals(2, $logs['count']);
3423 $this->assertNotEquals($stateOfGrace, $logs['values'][2]['status_id']);
3424 //Assert only three activities are created.
3425 $activities = CRM_Activity_BAO_Activity::getContactActivity($this->_ids['contact']);
3426 $this->assertEquals(3, count($activities));
3427 $activityNames = array_flip(CRM_Utils_Array::collect('activity_name', $activities));
3428 $this->assertArrayHasKey('Contribution', $activityNames);
3429 $this->assertArrayHasKey('Membership Signup', $activityNames);
3430 $this->assertArrayHasKey('Change Membership Status', $activityNames);
3431 $this->cleanUpAfterPriceSets();
3432 }
3433
3434 /**
3435 * Test if renewal activity is create after changing Pending contribution to
3436 * Completed via offline
3437 *
3438 * @throws \CRM_Core_Exception
3439 * @throws \CRM_Core_Exception
3440 * @throws \CiviCRM_API3_Exception
3441 */
3442 public function testPendingToCompleteContribution(): void {
3443 $this->createPriceSetWithPage('membership');
3444 $this->setUpPendingContribution($this->_ids['price_field_value'][0]);
3445 $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids['membership']]);
3446 // Case 1: Assert that Membership Signup Activity is created on Pending to Completed Contribution via backoffice
3447 $activity = $this->callAPISuccess('Activity', 'get', [
3448 'activity_type_id' => 'Membership Signup',
3449 'source_record_id' => $this->_ids['membership'],
3450 'status_id' => 'Scheduled',
3451 ]);
3452 $this->assertEquals(1, $activity['count']);
3453
3454 // change pending contribution to completed
3455 $form = new CRM_Contribute_Form_Contribution();
3456
3457 $form->_params = [
3458 'id' => $this->_ids['contribution'],
3459 'total_amount' => 20,
3460 'net_amount' => 20,
3461 'fee_amount' => 0,
3462 'financial_type_id' => 1,
3463 'contact_id' => $this->_individualId,
3464 'contribution_status_id' => 1,
3465 'billing_middle_name' => '',
3466 'billing_last_name' => 'Adams',
3467 'billing_street_address-5' => '790L Lincoln St S',
3468 'billing_city-5' => 'Maryknoll',
3469 'billing_state_province_id-5' => 1031,
3470 'billing_postal_code-5' => 10545,
3471 'billing_country_id-5' => 1228,
3472 'frequency_interval' => 1,
3473 'frequency_unit' => 'month',
3474 'installments' => '',
3475 'hidden_AdditionalDetail' => 1,
3476 'hidden_Premium' => 1,
3477 'from_email_address' => '"civi45" <civi45@civicrm.com>',
3478 'receipt_date' => '',
3479 'receipt_date_time' => '',
3480 'payment_processor_id' => $this->paymentProcessorID,
3481 'currency' => 'USD',
3482 'contribution_page_id' => $this->_ids['contribution_page'],
3483 'contribution_mode' => 'membership',
3484 'source' => 'Membership Signup and Renewal',
3485 ];
3486
3487 $form->testSubmit($form->_params, CRM_Core_Action::UPDATE);
3488
3489 // Case 2: After successful payment for Pending backoffice there are three activities created
3490 // 2.a Update status of existing Scheduled Membership Signup (created in step 1) to Completed
3491 $activity = $this->callAPISuccess('Activity', 'get', [
3492 'activity_type_id' => 'Membership Signup',
3493 'source_record_id' => $this->_ids['membership'],
3494 'status_id' => 'Completed',
3495 ]);
3496 $this->assertEquals(1, $activity['count']);
3497 // 2.b Contribution activity created to record successful payment
3498 $activity = $this->callAPISuccess('Activity', 'get', [
3499 'activity_type_id' => 'Contribution',
3500 'source_record_id' => $this->_ids['contribution'],
3501 'status_id' => 'Completed',
3502 ]);
3503 $this->assertEquals(1, $activity['count']);
3504
3505 // 2.c 'Change membership type' activity created to record Membership status change from Grace to Current
3506 $activity = $this->callAPISuccess('Activity', 'get', [
3507 'activity_type_id' => 'Change Membership Status',
3508 'source_record_id' => $this->_ids['membership'],
3509 'status_id' => 'Completed',
3510 ]);
3511 $this->assertEquals(1, $activity['count']);
3512 $this->assertEquals('Status changed from Grace to Current', $activity['values'][$activity['id']]['subject']);
3513 $membershipLogs = $this->callAPISuccess('MembershipLog', 'get', ['sequential' => 1])['values'];
3514 $this->assertEquals('Grace', CRM_Core_PseudoConstant::getName('CRM_Member_BAO_Membership', 'status_id', $membershipLogs[0]['status_id']));
3515 $this->assertEquals('Current', CRM_Core_PseudoConstant::getName('CRM_Member_BAO_Membership', 'status_id', $membershipLogs[1]['status_id']));
3516 //Create another pending contribution for renewal
3517 $contribution = $this->callAPISuccess('contribution', 'create', [
3518 'domain_id' => 1,
3519 'contact_id' => $this->_ids['contact'],
3520 'receive_date' => date('Ymd'),
3521 'total_amount' => 20.00,
3522 'financial_type_id' => 1,
3523 'payment_instrument_id' => 'Credit Card',
3524 'non_deductible_amount' => 10.00,
3525 'trxn_id' => 'rdhfi88',
3526 'invoice_id' => 'dofhiewuyr',
3527 'source' => 'SSF',
3528 'contribution_status_id' => 2,
3529 'contribution_page_id' => $this->_ids['contribution_page'],
3530 // We can't rely on contribution api to link line items correctly to membership
3531 'skipLineItem' => TRUE,
3532 'api.membership_payment.create' => ['membership_id' => $this->_ids['membership']],
3533 ]);
3534
3535 $this->callAPISuccess('line_item', 'create', [
3536 'entity_id' => $contribution['id'],
3537 'entity_table' => 'civicrm_contribution',
3538 'contribution_id' => $contribution['id'],
3539 'price_field_id' => $this->_ids['price_field'][0],
3540 'qty' => 1,
3541 'unit_price' => 20,
3542 'line_total' => 20,
3543 'financial_type_id' => 1,
3544 'price_field_value_id' => $this->_ids['price_field_value']['cont'],
3545 ]);
3546 $this->callAPISuccess('line_item', 'create', [
3547 'entity_id' => $this->_ids['membership'],
3548 'entity_table' => 'civicrm_membership',
3549 'contribution_id' => $contribution['id'],
3550 'price_field_id' => $this->_ids['price_field'][0],
3551 'qty' => 1,
3552 'unit_price' => 20,
3553 'line_total' => 20,
3554 'financial_type_id' => 1,
3555 'price_field_value_id' => $this->_ids['price_field_value'][0],
3556 'membership_type_id' => $this->_ids['membership_type'],
3557 ]);
3558
3559 //Update it to Failed.
3560 $form->_params['id'] = $contribution['id'];
3561 $form->_params['contribution_status_id'] = 4;
3562
3563 $form->testSubmit($form->_params, CRM_Core_Action::UPDATE);
3564 //Existing membership should not get updated to expired.
3565 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids['membership']]);
3566 $this->assertNotEquals(4, $membership['status_id']);
3567 }
3568
3569 /**
3570 * Test membership is renewed for 2 terms when transaction completed based on the line item having 2 terms as qty.
3571 *
3572 * Also check that altering the qty for the most recent contribution results in repeattransaction picking it up.
3573 */
3574 public function testCompleteTransactionMembershipPriceSetTwoTerms() {
3575 $this->createPriceSetWithPage('membership');
3576 $this->setUpPendingContribution($this->_ids['price_field_value'][1]);
3577 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $this->_ids['contribution']]);
3578 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $this->_ids['membership']]);
3579 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 2 years')), $membership['end_date']);
3580
3581 $paymentProcessorID = $this->paymentProcessorAuthorizeNetCreate();
3582
3583 $contributionRecurID = $this->callAPISuccess('ContributionRecur', 'create', ['contact_id' => $membership['contact_id'], 'payment_processor_id' => $paymentProcessorID, 'amount' => 20, 'frequency_interval' => 1])['id'];
3584 $this->callAPISuccess('Contribution', 'create', ['id' => $this->_ids['contribution'], 'contribution_recur_id' => $contributionRecurID]);
3585 $this->callAPISuccess('contribution', 'repeattransaction', ['contribution_recur_id' => $contributionRecurID, 'contribution_status_id' => 'Completed']);
3586 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $this->_ids['membership']]);
3587 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 4 years')), $membership['end_date']);
3588
3589 // 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.
3590 $contribution = Contribution::get()->setOrderBy(['id' => 'DESC'])->setSelect(['id'])->execute()->first();
3591 CRM_Core_DAO::executeQuery('UPDATE civicrm_line_item SET price_field_value_id = ' . $this->_ids['price_field_value'][0] . ' WHERE contribution_id = ' . $contribution['id']);
3592 $this->callAPISuccess('contribution', 'repeattransaction', ['contribution_recur_id' => $contributionRecurID, 'contribution_status_id' => 'Completed']);
3593 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $this->_ids['membership']]);
3594 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 5 years')), $membership['end_date']);
3595
3596 $this->cleanUpAfterPriceSets();
3597 }
3598
3599 public function cleanUpAfterPriceSets() {
3600 $this->quickCleanUpFinancialEntities();
3601 $this->contactDelete($this->_ids['contact']);
3602 }
3603
3604 /**
3605 * Set up a pending transaction with a specific price field id.
3606 *
3607 * @param int $priceFieldValueID
3608 * @param array $contriParams
3609 *
3610 * @throws \CRM_Core_Exception
3611 */
3612 public function setUpPendingContribution($priceFieldValueID, $contriParams = []) {
3613 $contactID = $this->individualCreate();
3614 $contribution = $this->callAPISuccess('Order', 'create', array_merge([
3615 'domain_id' => 1,
3616 'contact_id' => $contactID,
3617 'receive_date' => date('Ymd'),
3618 'total_amount' => 20.00,
3619 'financial_type_id' => 1,
3620 'payment_instrument_id' => 'Credit Card',
3621 'non_deductible_amount' => 10.00,
3622 'trxn_id' => 'jdhfi' . rand(1, 100),
3623 'invoice_id' => 'djfhiew' . rand(5, 100),
3624 'source' => 'SSF',
3625 'contribution_status_id' => 2,
3626 'contribution_page_id' => $this->_ids['contribution_page'],
3627 'line_items' => [
3628 [
3629 'line_item' => [
3630 [
3631 'price_field_id' => $this->_ids['price_field'][0],
3632 'qty' => 1,
3633 'entity_table' => 'civicrm_membership',
3634 'unit_price' => 20,
3635 'line_total' => 20,
3636 'financial_type_id' => 1,
3637 'price_field_value_id' => $priceFieldValueID,
3638 ],
3639 ],
3640 'params' => [
3641 'contact_id' => $contactID,
3642 'membership_type_id' => $this->_ids['membership_type'],
3643 'start_date' => 'yesterday - 1 year',
3644 'end_date' => 'yesterday',
3645 'join_date' => 'yesterday - 1 year',
3646 ],
3647 ],
3648 ],
3649 ], $contriParams));
3650
3651 $this->_ids['contact'] = $contactID;
3652 $this->_ids['contribution'] = $contribution['id'];
3653 $this->_ids['membership'] = $this->callAPISuccessGetValue('MembershipPayment', ['return' => 'membership_id', 'contribution_id' => $contribution['id']]);
3654 }
3655
3656 /**
3657 * Test sending a mail via the API.
3658 *
3659 * @throws \CRM_Core_Exception
3660 * @throws \CiviCRM_API3_Exception
3661 */
3662 public function testSendMail() {
3663 $mut = new CiviMailUtils($this, TRUE);
3664 $orderParams = $this->_params;
3665 $orderParams['contribution_status_id'] = 'Pending';
3666 $orderParams['api.PaymentProcessor.pay'] = [
3667 'payment_processor_id' => $this->paymentProcessorID,
3668 'credit_card_type' => 'Visa',
3669 'credit_card_number' => 41111111111111,
3670 'amount' => 5,
3671 ];
3672
3673 $order = $this->callAPISuccess('Order', 'create', $orderParams);
3674 $this->callAPISuccess('Payment', 'create', ['total_amount' => 5, 'is_send_notification' => 0, 'order_id' => $order['id']]);
3675 $address = $this->callAPISuccess('Address', 'create', ['contribution_id' => $order['id'], 'name' => 'bob', 'contact_id' => 1, 'street_address' => 'blah']);
3676 $this->callAPISuccess('Contribution', 'create', ['id' => $order['id'], 'address_id' => $address['id']]);
3677 $this->callAPISuccess('contribution', 'sendconfirmation', [
3678 'id' => $order['id'],
3679 'receipt_from_email' => 'api@civicrm.org',
3680 ]);
3681 $mut->checkMailLog([
3682 '$ 100.00',
3683 'Contribution Information',
3684 ], [
3685 'Event',
3686 ]);
3687
3688 $this->checkCreditCardDetails($mut, $order['id']);
3689 $mut->stop();
3690 $tplVars = CRM_Core_Smarty::singleton()->get_template_vars();
3691 $this->assertEquals('bob', $tplVars['billingName']);
3692 $this->assertEquals("bob\nblah\n", $tplVars['address']);
3693 }
3694
3695 /**
3696 * Test sending a mail via the API.
3697 * This simulates webform_civicrm using pay later contribution page
3698 */
3699 public function testSendconfirmationPayLater() {
3700 $mut = new CiviMailUtils($this, TRUE);
3701
3702 // Create contribution page
3703 $pageParams = [
3704 'title' => 'Webform Contributions',
3705 'financial_type_id' => 1,
3706 'contribution_type_id' => 1,
3707 'is_confirm_enabled' => 1,
3708 'is_pay_later' => 1,
3709 'pay_later_text' => 'I will send payment by cheque',
3710 'pay_later_receipt' => 'Send your cheque payable to "CiviCRM LLC" to the office',
3711 ];
3712 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $pageParams);
3713
3714 // Create pay later contribution
3715 $contribParams = [
3716 'contact_id' => $this->_individualId,
3717 'financial_type_id' => 1,
3718 'is_pay_later' => 1,
3719 'contribution_status_id' => 2,
3720 'contribution_page_id' => $contributionPage['id'],
3721 'total_amount' => '10.00',
3722 ];
3723 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
3724
3725 // Create line item
3726 $lineItemParams = [
3727 'contribution_id' => $contribution['id'],
3728 'entity_id' => $contribution['id'],
3729 'entity_table' => 'civicrm_contribution',
3730 'label' => 'My lineitem label',
3731 'qty' => 1,
3732 'unit_price' => "10.00",
3733 'line_total' => "10.00",
3734 ];
3735 $lineItem = $this->callAPISuccess('lineItem', 'create', $lineItemParams);
3736
3737 // Create email
3738 try {
3739 civicrm_api3('contribution', 'sendconfirmation', [
3740 'id' => $contribution['id'],
3741 'receipt_from_email' => 'api@civicrm.org',
3742 ]);
3743 }
3744 catch (Exception $e) {
3745 // Need to figure out how to stop this some other day
3746 // We don't care about the Payment Processor because this is Pay Later
3747 // The point of this test is to check we get the pay_later version of the mail
3748 if ($e->getMessage() != "Undefined variable: CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage") {
3749 throw $e;
3750 }
3751 }
3752
3753 // Retrieve mail & check it has the pay_later_receipt info
3754 $mut->getMostRecentEmail('raw');
3755 $mut->checkMailLog([
3756 (string) $contribParams['total_amount'],
3757 $pageParams['pay_later_receipt'],
3758 ], [
3759 'Event',
3760 ]);
3761 $this->checkReceiptDetails($mut, $contributionPage['id'], $contribution['id'], $pageParams);
3762 $mut->stop();
3763 }
3764
3765 /**
3766 * Check credit card details in sent mail via API
3767 *
3768 * @param CiviMailUtils $mut
3769 * @param int $contributionID Contribution ID
3770 *
3771 * @throws \CRM_Core_Exception
3772 */
3773 public function checkCreditCardDetails($mut, $contributionID) {
3774 $this->callAPISuccess('contribution', 'create', $this->_params);
3775 $this->callAPISuccess('contribution', 'sendconfirmation', [
3776 'id' => $contributionID,
3777 'receipt_from_email' => 'api@civicrm.org',
3778 'payment_processor_id' => $this->paymentProcessorID,
3779 ]);
3780 $mut->checkMailLog([
3781 // billing header
3782 'Billing Name and Address',
3783 // billing name
3784 'anthony_anderson@civicrm.org',
3785 ], [
3786 'Event',
3787 ]);
3788 }
3789
3790 /**
3791 * Check receipt details in sent mail via API
3792 *
3793 * @param CiviMailUtils $mut
3794 * @param int $pageID Page ID
3795 * @param int $contributionID Contribution ID
3796 * @param array $pageParams
3797 *
3798 * @throws \CRM_Core_Exception
3799 */
3800 public function checkReceiptDetails($mut, $pageID, $contributionID, $pageParams) {
3801 $pageReceipt = [
3802 'receipt_from_name' => "Page FromName",
3803 'receipt_from_email' => "page_from@email.com",
3804 'cc_receipt' => "page_cc@email.com",
3805 'receipt_text' => "Page Receipt Text",
3806 'pay_later_receipt' => $pageParams['pay_later_receipt'],
3807 ];
3808 $customReceipt = [
3809 'receipt_from_name' => "Custom FromName",
3810 'receipt_from_email' => "custom_from@email.com",
3811 'cc_receipt' => "custom_cc@email.com",
3812 'receipt_text' => "Test Custom Receipt Text",
3813 'pay_later_receipt' => 'Mail your check to test@example.com within 3 business days.',
3814 ];
3815 $this->callAPISuccess('ContributionPage', 'create', array_merge([
3816 'id' => $pageID,
3817 'is_email_receipt' => 1,
3818 ], $pageReceipt));
3819
3820 $this->callAPISuccess('contribution', 'sendconfirmation', array_merge([
3821 'id' => $contributionID,
3822 'payment_processor_id' => $this->paymentProcessorID,
3823 ], $customReceipt));
3824
3825 //Verify if custom receipt details are present in email.
3826 //Page receipt details shouldn't be included.
3827 $mut->checkMailLog(array_values($customReceipt), array_values($pageReceipt));
3828 }
3829
3830 /**
3831 * Test sending a mail via the API.
3832 */
3833 public function testSendMailEvent() {
3834 $mut = new CiviMailUtils($this, TRUE);
3835 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
3836 $event = $this->eventCreate([
3837 'is_email_confirm' => 1,
3838 'confirm_from_email' => 'test@civicrm.org',
3839 ]);
3840 $this->_eventID = $event['id'];
3841 $participantParams = [
3842 'contact_id' => $this->_individualId,
3843 'event_id' => $this->_eventID,
3844 'status_id' => 1,
3845 'role_id' => 1,
3846 // to ensure it matches later on
3847 'register_date' => '2007-07-21 00:00:00',
3848 'source' => 'Online Event Registration: API Testing',
3849
3850 ];
3851 $participant = $this->callAPISuccess('participant', 'create', $participantParams);
3852 $this->callAPISuccess('participant_payment', 'create', [
3853 'participant_id' => $participant['id'],
3854 'contribution_id' => $contribution['id'],
3855 ]);
3856 $this->callAPISuccess('contribution', 'sendconfirmation', [
3857 'id' => $contribution['id'],
3858 'receipt_from_email' => 'api@civicrm.org',
3859 ]);
3860
3861 $mut->checkMailLog([
3862 'Annual CiviCRM meet',
3863 'Event',
3864 'To: "Mr. Anthony Anderson II" <anthony_anderson@civicrm.org>',
3865 ], []);
3866 $mut->stop();
3867 }
3868
3869 /**
3870 * This function does a GET & compares the result against the $params.
3871 *
3872 * Use as a double check on Creates.
3873 *
3874 * @param array $params
3875 * @param int $id
3876 * @param bool $delete
3877 */
3878 public function contributionGetnCheck($params, $id, $delete = TRUE) {
3879
3880 $contribution = $this->callAPISuccess('Contribution', 'Get', [
3881 'id' => $id,
3882 ]);
3883
3884 if ($delete) {
3885 $this->callAPISuccess('contribution', 'delete', ['id' => $id]);
3886 }
3887 $this->assertAPISuccess($contribution, 0);
3888 $values = $contribution['values'][$contribution['id']];
3889 $params['receive_date'] = date('Y-m-d H:i:s', strtotime($params['receive_date']));
3890 // this is not returned in id format
3891 unset($params['payment_instrument_id']);
3892 $params['contribution_source'] = $params['source'];
3893 unset($params['source']);
3894 foreach ($params as $key => $value) {
3895 $this->assertEquals($value, $values[$key], $key . " value: $value doesn't match " . print_r($values, TRUE));
3896 }
3897 }
3898
3899 /**
3900 * Create a pending contribution & linked pending pledge record.
3901 */
3902 public function createPendingPledgeContribution() {
3903
3904 $pledgeID = $this->pledgeCreate(['contact_id' => $this->_individualId, 'installments' => 1, 'amount' => 500]);
3905 $this->_ids['pledge'] = $pledgeID;
3906 $contribution = $this->callAPISuccess('contribution', 'create', array_merge($this->_params, [
3907 'contribution_status_id' => 'Pending',
3908 'total_amount' => 500,
3909 ]));
3910 $paymentID = $this->callAPISuccessGetValue('PledgePayment', [
3911 'options' => ['limit' => 1],
3912 'return' => 'id',
3913 ]);
3914 $this->callAPISuccess('PledgePayment', 'create', [
3915 'id' => $paymentID,
3916 'contribution_id' =>
3917 $contribution['id'],
3918 'status_id' => 'Pending',
3919 'scheduled_amount' => 500,
3920 ]);
3921
3922 return $contribution['id'];
3923 }
3924
3925 /**
3926 * Create a pending contribution & linked pending participant record (along with an event).
3927 */
3928 public function createPendingParticipantContribution() {
3929 $this->_ids['event']['test'] = $this->eventCreate(['is_email_confirm' => 1, 'confirm_from_email' => 'test@civicrm.org'])['id'];
3930 $participantID = $this->participantCreate(['event_id' => $this->_ids['event']['test'], 'status_id' => 6, 'contact_id' => $this->_individualId]);
3931 $this->_ids['participant'] = $participantID;
3932 $params = array_merge($this->_params, ['contact_id' => $this->_individualId, 'contribution_status_id' => 2, 'financial_type_id' => 'Event Fee']);
3933 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3934 $this->callAPISuccess('participant_payment', 'create', [
3935 'contribution_id' => $contribution['id'],
3936 'participant_id' => $participantID,
3937 ]);
3938 $this->callAPISuccess('line_item', 'get', [
3939 'entity_id' => $contribution['id'],
3940 'entity_table' => 'civicrm_contribution',
3941 'api.line_item.create' => [
3942 'entity_id' => $participantID,
3943 'entity_table' => 'civicrm_participant',
3944 ],
3945 ]);
3946 return $contribution['id'];
3947 }
3948
3949 /**
3950 * Get financial transaction amount.
3951 *
3952 * @param int $contId
3953 *
3954 * @return null|string
3955 */
3956 public function _getFinancialTrxnAmount($contId) {
3957 $query = "SELECT
3958 SUM( ft.total_amount ) AS total
3959 FROM civicrm_financial_trxn AS ft
3960 LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.id = ceft.financial_trxn_id
3961 WHERE ceft.entity_table = 'civicrm_contribution'
3962 AND ceft.entity_id = {$contId}";
3963
3964 $result = CRM_Core_DAO::singleValueQuery($query);
3965 return $result;
3966 }
3967
3968 /**
3969 * @param int $contId
3970 *
3971 * @return null|string
3972 */
3973 public function _getFinancialItemAmount($contId) {
3974 $lineItem = key(CRM_Price_BAO_LineItem::getLineItems($contId, 'contribution'));
3975 $query = "SELECT
3976 SUM(amount)
3977 FROM civicrm_financial_item
3978 WHERE entity_table = 'civicrm_line_item'
3979 AND entity_id = {$lineItem}";
3980 $result = CRM_Core_DAO::singleValueQuery($query);
3981 return $result;
3982 }
3983
3984 /**
3985 * @param int $contId
3986 * @param $context
3987 */
3988 public function _checkFinancialItem($contId, $context) {
3989 if ($context != 'paylater') {
3990 $params = [
3991 'entity_id' => $contId,
3992 'entity_table' => 'civicrm_contribution',
3993 ];
3994 $trxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($params, TRUE));
3995 $entityParams = [
3996 'financial_trxn_id' => $trxn['financial_trxn_id'],
3997 'entity_table' => 'civicrm_financial_item',
3998 ];
3999 $entityTrxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
4000 $params = [
4001 'id' => $entityTrxn['entity_id'],
4002 ];
4003 }
4004 if ($context == 'paylater') {
4005 $lineItems = CRM_Price_BAO_LineItem::getLineItems($contId, 'contribution');
4006 foreach ($lineItems as $key => $item) {
4007 $params = [
4008 'entity_id' => $key,
4009 'entity_table' => 'civicrm_line_item',
4010 ];
4011 $compareParams = ['status_id' => 1];
4012 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
4013 }
4014 }
4015 elseif ($context == 'refund') {
4016 $compareParams = [
4017 'status_id' => 1,
4018 'financial_account_id' => 1,
4019 'amount' => -100,
4020 ];
4021 }
4022 elseif ($context == 'cancelPending') {
4023 $compareParams = [
4024 'status_id' => 3,
4025 'financial_account_id' => 1,
4026 'amount' => -100,
4027 ];
4028 }
4029 elseif ($context == 'changeFinancial') {
4030 $lineKey = key(CRM_Price_BAO_LineItem::getLineItems($contId, 'contribution'));
4031 $params = [
4032 'entity_id' => $lineKey,
4033 'amount' => -100,
4034 ];
4035 $compareParams = [
4036 'financial_account_id' => 1,
4037 ];
4038 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
4039 $params = [
4040 'financial_account_id' => 3,
4041 'entity_id' => $lineKey,
4042 ];
4043 $compareParams = [
4044 'amount' => 100,
4045 ];
4046 }
4047 if ($context != 'paylater') {
4048 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
4049 }
4050 }
4051
4052 /**
4053 * Check correct financial transaction entries were created for the change in payment instrument.
4054 *
4055 * @param int $contributionID
4056 * @param int $originalInstrumentID
4057 * @param int $newInstrumentID
4058 * @param int $amount
4059 */
4060 public function checkFinancialTrxnPaymentInstrumentChange($contributionID, $originalInstrumentID, $newInstrumentID, $amount = 100) {
4061
4062 $entityFinancialTrxns = $this->getFinancialTransactionsForContribution($contributionID);
4063
4064 $originalTrxnParams = [
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 $reversalTrxnParams = [
4072 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($originalInstrumentID),
4073 'payment_instrument_id' => $originalInstrumentID,
4074 'amount' => -$amount,
4075 'status_id' => 1,
4076 ];
4077
4078 $newTrxnParams = [
4079 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($newInstrumentID),
4080 'payment_instrument_id' => $newInstrumentID,
4081 'amount' => $amount,
4082 'status_id' => 1,
4083 ];
4084
4085 foreach ([$originalTrxnParams, $reversalTrxnParams, $newTrxnParams] as $index => $transaction) {
4086 $entityFinancialTrxn = $entityFinancialTrxns[$index];
4087 $this->assertEquals($entityFinancialTrxn['amount'], $transaction['amount']);
4088
4089 $financialTrxn = $this->callAPISuccessGetSingle('FinancialTrxn', [
4090 'id' => $entityFinancialTrxn['financial_trxn_id'],
4091 ]);
4092 $this->assertEquals($transaction['status_id'], $financialTrxn['status_id']);
4093 $this->assertEquals($transaction['amount'], $financialTrxn['total_amount']);
4094 $this->assertEquals($transaction['amount'], $financialTrxn['net_amount']);
4095 $this->assertEquals(0, $financialTrxn['fee_amount']);
4096 $this->assertEquals($transaction['payment_instrument_id'], $financialTrxn['payment_instrument_id']);
4097 $this->assertEquals($transaction['to_financial_account_id'], $financialTrxn['to_financial_account_id']);
4098
4099 // Generic checks.
4100 $this->assertEquals(1, $financialTrxn['is_payment']);
4101 $this->assertEquals('USD', $financialTrxn['currency']);
4102 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($financialTrxn['trxn_date'])));
4103 }
4104 }
4105
4106 /**
4107 * Check financial transaction.
4108 *
4109 * @todo break this down into sensible functions - most calls to it only use a few lines out of the big if.
4110 *
4111 * @param array $contribution
4112 * @param string $context
4113 * @param int $instrumentId
4114 * @param array $extraParams
4115 */
4116 public function _checkFinancialTrxn($contribution, $context, $instrumentId = NULL, $extraParams = []) {
4117 $financialTrxns = $this->getFinancialTransactionsForContribution($contribution['id']);
4118 $trxn = array_pop($financialTrxns);
4119
4120 $params = [
4121 'id' => $trxn['financial_trxn_id'],
4122 ];
4123 if ($context == 'payLater') {
4124 $compareParams = [
4125 'status_id' => 1,
4126 'from_financial_account_id' => CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is'),
4127 ];
4128 }
4129 elseif ($context == 'refund') {
4130 $compareParams = [
4131 'to_financial_account_id' => 6,
4132 'total_amount' => -100,
4133 'status_id' => 7,
4134 'trxn_date' => '2015-01-01 09:00:00',
4135 'trxn_id' => 'the refund',
4136 ];
4137 }
4138 elseif ($context == 'cancelPending') {
4139 $compareParams = [
4140 'to_financial_account_id' => 7,
4141 'total_amount' => -100,
4142 'status_id' => 3,
4143 ];
4144 }
4145 elseif ($context == 'changeFinancial' || $context == 'paymentInstrument') {
4146 // @todo checkFinancialTrxnPaymentInstrumentChange instead for paymentInstrument.
4147 // It does the same thing with greater readability.
4148 // @todo remove handling for
4149
4150 $entityParams = [
4151 'entity_id' => $contribution['id'],
4152 'entity_table' => 'civicrm_contribution',
4153 'amount' => -100,
4154 ];
4155 $trxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
4156 $trxnParams1 = [
4157 'id' => $trxn['financial_trxn_id'],
4158 ];
4159 if (empty($extraParams)) {
4160 $compareParams = [
4161 'total_amount' => -100,
4162 'status_id' => 1,
4163 ];
4164 }
4165 elseif ($context !== 'changeFinancial') {
4166 $compareParams = [
4167 'total_amount' => 100,
4168 'status_id' => 1,
4169 ];
4170 }
4171 if ($context == 'paymentInstrument') {
4172 $compareParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($instrumentId);
4173 $compareParams['payment_instrument_id'] = $instrumentId;
4174 }
4175 else {
4176 $compareParams['to_financial_account_id'] = 12;
4177 }
4178 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams1, array_merge($compareParams, $extraParams));
4179 $compareParams['total_amount'] = 100;
4180 // Reverse the extra params now that we will be checking the new positive transaction.
4181 if ($context === 'changeFinancial' && !empty($extraParams)) {
4182 foreach ($extraParams as $param => $value) {
4183 $extraParams[$param] = 0 - $value;
4184 }
4185 }
4186 }
4187
4188 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $params, array_merge($compareParams, $extraParams));
4189 }
4190
4191 /**
4192 * @return mixed
4193 */
4194 public function _addPaymentInstrument() {
4195 $gId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'payment_instrument', 'id', 'name');
4196 $optionParams = [
4197 'option_group_id' => $gId,
4198 'label' => 'Test Card',
4199 'name' => 'Test Card',
4200 'value' => '6',
4201 'weight' => '6',
4202 'is_active' => 1,
4203 ];
4204 $optionValue = $this->callAPISuccess('option_value', 'create', $optionParams);
4205 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
4206 $financialParams = [
4207 'entity_table' => 'civicrm_option_value',
4208 'entity_id' => $optionValue['id'],
4209 'account_relationship' => $relationTypeId,
4210 'financial_account_id' => 7,
4211 ];
4212 CRM_Financial_BAO_FinancialTypeAccount::add($financialParams);
4213 $this->assertNotEmpty($optionValue['values'][$optionValue['id']]['value']);
4214 return $optionValue['values'][$optionValue['id']]['value'];
4215 }
4216
4217 public function _deletedAddedPaymentInstrument() {
4218 $result = $this->callAPISuccess('OptionValue', 'get', [
4219 'option_group_id' => 'payment_instrument',
4220 'name' => 'Test Card',
4221 'value' => '6',
4222 'is_active' => 1,
4223 ]);
4224 if ($id = CRM_Utils_Array::value('id', $result)) {
4225 $this->callAPISuccess('OptionValue', 'delete', ['id' => $id]);
4226 }
4227 }
4228
4229 /**
4230 * Set up the basic recurring contribution for tests.
4231 *
4232 * @param array $generalParams
4233 * Parameters that can be merged into the recurring AND the contribution.
4234 *
4235 * @param array $recurParams
4236 * Parameters to merge into the recur only.
4237 *
4238 * @return array|int
4239 * @throws \CRM_Core_Exception
4240 */
4241 protected function setUpRecurringContribution($generalParams = [], $recurParams = []) {
4242 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4243 'contact_id' => $this->_individualId,
4244 'installments' => '12',
4245 'frequency_interval' => '1',
4246 'amount' => '100',
4247 'contribution_status_id' => 1,
4248 'start_date' => '2012-01-01 00:00:00',
4249 'currency' => 'USD',
4250 'frequency_unit' => 'month',
4251 'payment_processor_id' => $this->paymentProcessorID,
4252 ], $generalParams, $recurParams));
4253 $contributionParams = array_merge(
4254 $this->_params,
4255 [
4256 'contribution_recur_id' => $contributionRecur['id'],
4257 'contribution_status_id' => 'Pending',
4258 ], $generalParams);
4259 $contributionParams['api.Payment.create'] = ['total_amount' => $contributionParams['total_amount']];
4260 $originalContribution = $this->callAPISuccess('Order', 'create', $contributionParams);
4261 return $originalContribution;
4262 }
4263
4264 /**
4265 * Set up a basic auto-renew membership for tests.
4266 *
4267 * @param array $generalParams
4268 * Parameters that can be merged into the recurring AND the contribution.
4269 *
4270 * @param array $recurParams
4271 * Parameters to merge into the recur only.
4272 *
4273 * @return array|int
4274 * @throws \CRM_Core_Exception
4275 */
4276 protected function setUpAutoRenewMembership($generalParams = [], $recurParams = []) {
4277 $newContact = $this->callAPISuccess('Contact', 'create', [
4278 'contact_type' => 'Individual',
4279 'sort_name' => 'McTesterson, Testy',
4280 'display_name' => 'Testy McTesterson',
4281 'preferred_language' => 'en_US',
4282 'preferred_mail_format' => 'Both',
4283 'first_name' => 'Testy',
4284 'last_name' => 'McTesterson',
4285 'contact_is_deleted' => '0',
4286 'email_id' => '4',
4287 'email' => 'tmctesterson@example.com',
4288 'on_hold' => '0',
4289 ]);
4290 $membershipType = $this->callAPISuccess('MembershipType', 'create', [
4291 'domain_id' => 'Default Domain Name',
4292 'member_of_contact_id' => 1,
4293 'financial_type_id' => 'Member Dues',
4294 'duration_unit' => 'month',
4295 'duration_interval' => 1,
4296 'period_type' => 'rolling',
4297 'name' => 'Standard Member',
4298 'minimum_fee' => 100,
4299 ]);
4300 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4301 'contact_id' => $newContact['id'],
4302 'installments' => '12',
4303 'frequency_interval' => '1',
4304 'amount' => '100',
4305 'contribution_status_id' => 1,
4306 'start_date' => '2012-01-01 00:00:00',
4307 'currency' => 'USD',
4308 'frequency_unit' => 'month',
4309 'payment_processor_id' => $this->paymentProcessorID,
4310 ], $generalParams, $recurParams));
4311
4312 $membership = $this->callAPISuccess('membership', 'create', [
4313 'contact_id' => $newContact['id'],
4314 'contribution_recur_id' => $contributionRecur['id'],
4315 'financial_type_id' => "Member Dues",
4316 'membership_type_id' => $membershipType['id'],
4317 'num_terms' => 1,
4318 'skipLineItem' => TRUE,
4319 ]);
4320
4321 CRM_Price_BAO_LineItem::getLineItemArray($this->_params, NULL, 'membership', $membershipType['id']);
4322 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
4323 $this->_params,
4324 [
4325 'contact_id' => $newContact['id'],
4326 'contribution_recur_id' => $contributionRecur['id'],
4327 'financial_type_id' => "Member Dues",
4328 'contribution_status_id' => 1,
4329 'invoice_id' => uniqid(),
4330 ], $generalParams)
4331 );
4332 $lineItem = $this->callAPISuccess('LineItem', 'getsingle', []);
4333 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
4334 $membership = $this->callAPISuccess('Membership', 'getsingle', ['id' => $lineItem['entity_id']]);
4335 $this->callAPISuccess('LineItem', 'getsingle', []);
4336 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']], 1);
4337
4338 return [$originalContribution, $membership];
4339 }
4340
4341 /**
4342 * Set up a repeat transaction.
4343 *
4344 * @param array $recurParams
4345 * @param mixed $flag
4346 * @param array $contributionParams
4347 * @return array
4348 */
4349 protected function setUpRepeatTransaction($recurParams = [], $flag, $contributionParams = []) {
4350 $paymentProcessorID = $this->paymentProcessorCreate();
4351 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4352 'contact_id' => $this->_individualId,
4353 'installments' => '12',
4354 'frequency_interval' => '1',
4355 'amount' => '500',
4356 'contribution_status_id' => 1,
4357 'start_date' => '2012-01-01 00:00:00',
4358 'currency' => 'USD',
4359 'frequency_unit' => 'month',
4360 'payment_processor_id' => $paymentProcessorID,
4361 ], $recurParams));
4362
4363 $originalContribution = '';
4364 if ($flag == 'multiple') {
4365 // CRM-19309 create a contribution + also add in line_items (plural):
4366 $params = array_merge($this->_params, $contributionParams);
4367 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
4368 $params,
4369 [
4370 'contribution_recur_id' => $contributionRecur['id'],
4371 'skipLineItem' => 1,
4372 'api.line_item.create' => [
4373 [
4374 'price_field_id' => 1,
4375 'qty' => 2,
4376 'line_total' => '20',
4377 'unit_price' => '10',
4378 'financial_type_id' => 1,
4379 ],
4380 [
4381 'price_field_id' => 1,
4382 'qty' => 1,
4383 'line_total' => '80',
4384 'unit_price' => '80',
4385 'financial_type_id' => 2,
4386 ],
4387 ],
4388 ]
4389 )
4390 );
4391 }
4392 elseif ($flag == 'single') {
4393 $params = array_merge($this->_params, ['contribution_recur_id' => $contributionRecur['id']]);
4394 $params = array_merge($params, $contributionParams);
4395 $originalContribution = $this->callAPISuccess('contribution', 'create', $params);
4396 }
4397 $originalContribution['contribution_recur_id'] = $contributionRecur['id'];
4398 $originalContribution['payment_processor_id'] = $paymentProcessorID;
4399 return $originalContribution;
4400 }
4401
4402 /**
4403 * Common set up routine.
4404 *
4405 * @return array
4406 */
4407 protected function setUpForCompleteTransaction() {
4408 $this->mut = new CiviMailUtils($this, TRUE);
4409 $this->createLoggedInUser();
4410 $params = array_merge($this->_params, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
4411 $contribution = $this->callAPISuccess('contribution', 'create', $params);
4412 return $contribution;
4413 }
4414
4415 /**
4416 * Test repeat contribution uses the Payment Processor' payment_instrument setting.
4417 *
4418 * @throws \CRM_Core_Exception
4419 */
4420 public function testRepeatTransactionWithNonCreditCardDefault() {
4421 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
4422 'contact_id' => $this->_individualId,
4423 'installments' => '12',
4424 'frequency_interval' => '1',
4425 'amount' => '100',
4426 'contribution_status_id' => 1,
4427 'start_date' => '2012-01-01 00:00:00',
4428 'currency' => 'USD',
4429 'frequency_unit' => 'month',
4430 'payment_processor_id' => $this->paymentProcessorID,
4431 ]);
4432 $contribution1 = $this->callAPISuccess('contribution', 'create', array_merge(
4433 $this->_params,
4434 ['contribution_recur_id' => $contributionRecur['id'], 'payment_instrument_id' => 2])
4435 );
4436 $contribution2 = $this->callAPISuccess('contribution', 'repeattransaction', [
4437 'contribution_status_id' => 'Completed',
4438 'trxn_id' => 'blah',
4439 'original_contribution_id' => $contribution1,
4440 ]);
4441 $this->assertEquals('Debit Card', CRM_Contribute_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $contribution2['values'][$contribution2['id']]['payment_instrument_id']));
4442 }
4443
4444 /**
4445 * CRM-20008 Tests repeattransaction creates pending membership.
4446 */
4447 public function testRepeatTransactionMembershipCreatePendingContribution() {
4448 list($originalContribution, $membership) = $this->setUpAutoRenewMembership();
4449 $this->callAPISuccess('membership', 'create', [
4450 'id' => $membership['id'],
4451 'end_date' => 'yesterday',
4452 'status_id' => 'Expired',
4453 ]);
4454 $repeatedContribution = $this->callAPISuccess('contribution', 'repeattransaction', [
4455 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
4456 'contribution_status_id' => 'Pending',
4457 'trxn_id' => uniqid(),
4458 ]);
4459 $membershipStatusId = $this->callAPISuccess('membership', 'getvalue', [
4460 'id' => $membership['id'],
4461 'return' => 'status_id',
4462 ]);
4463
4464 // Let's see if the membership payments got created while we're at it.
4465 $membershipPayments = $this->callAPISuccess('MembershipPayment', 'get', [
4466 'membership_id' => $membership['id'],
4467 ]);
4468 $this->assertEquals(2, $membershipPayments['count']);
4469
4470 $this->assertEquals('Expired', CRM_Core_PseudoConstant::getLabel('CRM_Member_BAO_Membership', 'status_id', $membershipStatusId));
4471 $this->callAPISuccess('Contribution', 'completetransaction', ['id' => $repeatedContribution['id']]);
4472 $membership = $this->callAPISuccessGetSingle('membership', [
4473 'id' => $membership['id'],
4474 'return' => 'status_id, end_date',
4475 ]);
4476 $this->assertEquals('New', CRM_Core_PseudoConstant::getName('CRM_Member_BAO_Membership', 'status_id', $membership['status_id']));
4477 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 1 month')), $membership['end_date']);
4478 }
4479
4480 /**
4481 * Test sending a mail via the API.
4482 *
4483 * @throws \CRM_Core_Exception
4484 */
4485 public function testSendMailWithAPISetFromDetails() {
4486 $mut = new CiviMailUtils($this, TRUE);
4487 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
4488 $this->callAPISuccess('contribution', 'sendconfirmation', [
4489 'id' => $contribution['id'],
4490 'receipt_from_email' => 'api@civicrm.org',
4491 'receipt_from_name' => 'CiviCRM LLC',
4492 ]);
4493 $mut->checkMailLog([
4494 'From: CiviCRM LLC <api@civicrm.org>',
4495 'Contribution Information',
4496 ], [
4497 'Event',
4498 ]);
4499 $mut->stop();
4500 }
4501
4502 /**
4503 * Test sending a mail via the API.
4504 */
4505 public function testSendMailWithNoFromSetFallToDomain() {
4506 $this->createLoggedInUser();
4507 $mut = new CiviMailUtils($this, TRUE);
4508 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
4509 $this->callAPISuccess('contribution', 'sendconfirmation', [
4510 'id' => $contribution['id'],
4511 ]);
4512 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => 1]);
4513 $mut->checkMailLog([
4514 'From: ' . $domain['from_name'] . ' <' . $domain['from_email'] . '>',
4515 'Contribution Information',
4516 ], [
4517 'Event',
4518 ]);
4519 $mut->stop();
4520 }
4521
4522 /**
4523 * Test sending a mail via the API.
4524 */
4525 public function testSendMailWithRepeatTransactionAPIFalltoDomain() {
4526 $this->createLoggedInUser();
4527 $mut = new CiviMailUtils($this, TRUE);
4528 $contribution = $this->setUpRepeatTransaction([], 'single');
4529 $this->callAPISuccess('contribution', 'repeattransaction', [
4530 'contribution_status_id' => 'Completed',
4531 'trxn_id' => uniqid(),
4532 'original_contribution_id' => $contribution,
4533 ]);
4534 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => 1]);
4535 $mut->checkMailLog([
4536 'From: ' . $domain['from_name'] . ' <' . $domain['from_email'] . '>',
4537 'Contribution Information',
4538 ], [
4539 'Event',
4540 ]
4541 );
4542 $mut->stop();
4543 }
4544
4545 /**
4546 * Test sending a mail via the API.
4547 */
4548 public function testSendMailWithRepeatTransactionAPIFalltoContributionPage() {
4549 $mut = new CiviMailUtils($this, TRUE);
4550 $contributionPage = $this->contributionPageCreate(['receipt_from_name' => 'CiviCRM LLC', 'receipt_from_email' => 'contributionpage@civicrm.org', 'is_email_receipt' => 1]);
4551 $paymentProcessorID = $this->paymentProcessorCreate();
4552 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
4553 'contact_id' => $this->_individualId,
4554 'installments' => '12',
4555 'frequency_interval' => '1',
4556 'amount' => '500',
4557 'contribution_status_id' => 1,
4558 'start_date' => '2012-01-01 00:00:00',
4559 'currency' => 'USD',
4560 'frequency_unit' => 'month',
4561 'payment_processor_id' => $paymentProcessorID,
4562 ]);
4563 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
4564 $this->_params,
4565 [
4566 'contribution_recur_id' => $contributionRecur['id'],
4567 'contribution_page_id' => $contributionPage['id'],
4568 ])
4569 );
4570 $this->callAPISuccess('contribution', 'repeattransaction', [
4571 'contribution_status_id' => 'Completed',
4572 'trxn_id' => uniqid(),
4573 'original_contribution_id' => $originalContribution,
4574 ]
4575 );
4576 $mut->checkMailLog([
4577 'From: CiviCRM LLC <contributionpage@civicrm.org>',
4578 'Contribution Information',
4579 ], [
4580 'Event',
4581 ]);
4582 $mut->stop();
4583 }
4584
4585 /**
4586 * Test sending a mail via the API.
4587 */
4588 public function testSendMailWithRepeatTransactionAPIFalltoSystemFromNoDefaultFrom() {
4589 $mut = new CiviMailUtils($this, TRUE);
4590 $originalContribution = $contribution = $this->setUpRepeatTransaction([], 'single');
4591 $fromEmail = $this->CallAPISuccess('optionValue', 'get', ['is_default' => 1, 'option_group_id' => 'from_email_address', 'sequential' => 1]);
4592 foreach ($fromEmail['values'] as $from) {
4593 $this->callAPISuccess('optionValue', 'create', ['is_default' => 0, 'id' => $from['id']]);
4594 }
4595 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => CRM_Core_Config::domainID()]);
4596 $this->callAPISuccess('contribution', 'repeattransaction', [
4597 'contribution_status_id' => 'Completed',
4598 'trxn_id' => uniqid(),
4599 'original_contribution_id' => $originalContribution,
4600 ]);
4601 $mut->checkMailLog([
4602 'From: ' . $domain['name'] . ' <' . $domain['domain_email'] . '>',
4603 'Contribution Information',
4604 ], [
4605 'Event',
4606 ]);
4607 $mut->stop();
4608 }
4609
4610 /**
4611 * Create a Contribution Page with is_email_receipt = TRUE.
4612 *
4613 * @param array $params
4614 * Params to overwrite with.
4615 *
4616 * @return array|int
4617 */
4618 protected function createReceiptableContributionPage($params = []) {
4619 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', array_merge([
4620 'receipt_from_name' => 'Mickey Mouse',
4621 'receipt_from_email' => 'mickey@mouse.com',
4622 'title' => "Test Contribution Page",
4623 'financial_type_id' => 1,
4624 'currency' => 'CAD',
4625 'is_monetary' => TRUE,
4626 'is_email_receipt' => TRUE,
4627 ], $params));
4628 return $contributionPage;
4629 }
4630
4631 /**
4632 * function to test card_type and pan truncation.
4633 */
4634 public function testCardTypeAndPanTruncation() {
4635 $creditCardTypeIDs = array_flip(CRM_Financial_DAO_FinancialTrxn::buildOptions('card_type_id'));
4636 $contactId = $this->individualCreate();
4637 $params = [
4638 'contact_id' => $contactId,
4639 'receive_date' => '2016-01-20',
4640 'total_amount' => 100,
4641 'financial_type_id' => 1,
4642 'payment_instrument' => 'Credit Card',
4643 'card_type_id' => $creditCardTypeIDs['Visa'],
4644 'pan_truncation' => 4567,
4645 ];
4646 $contribution = $this->callAPISuccess('contribution', 'create', $params);
4647 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
4648 $financialTrxn = $this->callAPISuccessGetSingle(
4649 'FinancialTrxn',
4650 [
4651 'id' => $lastFinancialTrxnId['financialTrxnId'],
4652 'return' => ['card_type_id', 'pan_truncation'],
4653 ]
4654 );
4655 $this->assertEquals(CRM_Utils_Array::value('card_type_id', $financialTrxn), $creditCardTypeIDs['Visa']);
4656 $this->assertEquals(CRM_Utils_Array::value('pan_truncation', $financialTrxn), 4567);
4657 $params = [
4658 'id' => $contribution['id'],
4659 'pan_truncation' => 2345,
4660 'card_type_id' => $creditCardTypeIDs['Amex'],
4661 ];
4662 $contribution = $this->callAPISuccess('contribution', 'create', $params);
4663 $financialTrxn = $this->callAPISuccessGetSingle(
4664 'FinancialTrxn',
4665 [
4666 'id' => $lastFinancialTrxnId['financialTrxnId'],
4667 'return' => ['card_type_id', 'pan_truncation'],
4668 ]
4669 );
4670 $this->assertEquals(CRM_Utils_Array::value('card_type_id', $financialTrxn), $creditCardTypeIDs['Amex']);
4671 $this->assertEquals(CRM_Utils_Array::value('pan_truncation', $financialTrxn), 2345);
4672 }
4673
4674 /**
4675 * Test repeat contribution uses non default currency
4676 * @see https://issues.civicrm.org/jira/projects/CRM/issues/CRM-20678
4677 */
4678 public function testRepeatTransactionWithDifferenceCurrency() {
4679 $originalContribution = $this->setUpRepeatTransaction(['currency' => 'AUD'], 'single', ['currency' => 'AUD']);
4680 $contribution = $this->callAPISuccess('contribution', 'repeattransaction', [
4681 'original_contribution_id' => $originalContribution['id'],
4682 'contribution_status_id' => 'Completed',
4683 'trxn_id' => uniqid(),
4684 ]);
4685 $this->assertEquals('AUD', $contribution['values'][$contribution['id']]['currency']);
4686 }
4687
4688 /**
4689 * Get the financial items for the contribution.
4690 *
4691 * @param int $contributionID
4692 *
4693 * @return array
4694 * Array of associated financial items.
4695 */
4696 protected function getFinancialTransactionsForContribution($contributionID) {
4697 $trxnParams = [
4698 'entity_id' => $contributionID,
4699 'entity_table' => 'civicrm_contribution',
4700 ];
4701 // @todo the following function has naming errors & has a weird signature & appears to
4702 // only be called from test classes. Move into test suite & maybe just use api
4703 // from this function.
4704 return array_merge(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($trxnParams));
4705 }
4706
4707 /**
4708 * Test getunique api call for Contribution entity
4709 */
4710 public function testContributionGetUnique() {
4711 $result = $this->callAPIAndDocument($this->entity, 'getunique', [], __FUNCTION__, __FILE__);
4712 $this->assertEquals(2, $result['count']);
4713 $this->assertEquals(['trxn_id'], $result['values']['UI_contrib_trxn_id']);
4714 $this->assertEquals(['invoice_id'], $result['values']['UI_contrib_invoice_id']);
4715 }
4716
4717 /**
4718 * Test Repeat Transaction Contribution with Tax amount.
4719 * https://lab.civicrm.org/dev/core/issues/806
4720 */
4721 public function testRepeatContributionWithTaxAmount() {
4722 $this->enableTaxAndInvoicing();
4723 $financialType = $this->callAPISuccess('financial_type', 'create', [
4724 'name' => 'Test taxable financial Type',
4725 'is_reserved' => 0,
4726 'is_active' => 1,
4727 ]);
4728 $this->addTaxAccountToFinancialType($financialType['id']);
4729 $contribution = $this->setUpRepeatTransaction(
4730 [],
4731 'single',
4732 [
4733 'financial_type_id' => $financialType['id'],
4734 ]
4735 );
4736 $this->callAPISuccess('contribution', 'repeattransaction', [
4737 'original_contribution_id' => $contribution['id'],
4738 'contribution_status_id' => 'Completed',
4739 'trxn_id' => uniqid(),
4740 ]);
4741 $payments = $this->callAPISuccess('Contribution', 'get', ['sequential' => 1])['values'];
4742 //Assert if first payment and repeated payment has the same contribution amount.
4743 $this->assertEquals($payments[0]['total_amount'], $payments[1]['total_amount']);
4744 $this->callAPISuccessGetCount('Contribution', [], 2);
4745
4746 //Assert line item records.
4747 $lineItems = $this->callAPISuccess('LineItem', 'get', ['sequential' => 1])['values'];
4748 foreach ($lineItems as $lineItem) {
4749 $this->assertEquals($lineItem['unit_price'], $this->_params['total_amount']);
4750 $this->assertEquals($lineItem['line_total'], $this->_params['total_amount']);
4751 }
4752 $this->callAPISuccessGetCount('Contribution', [], 2);
4753 }
4754
4755 public function testGetCurrencyOptions() {
4756 $result = $this->callAPISuccess('Contribution', 'getoptions', [
4757 'field' => 'currency',
4758 ]);
4759 $this->assertEquals('US Dollar', $result['values']['USD']);
4760 $this->assertNotContains('$', $result['values']);
4761 $result = $this->callAPISuccess('Contribution', 'getoptions', [
4762 'field' => 'currency',
4763 'context' => "abbreviate",
4764 ]);
4765 $this->assertEquals('$', $result['values']['USD']);
4766 $this->assertNotContains('US Dollar', $result['values']);
4767 }
4768
4769 /**
4770 * @throws \API_Exception
4771 * @throws \CRM_Core_Exception
4772 * @throws \Civi\API\Exception\UnauthorizedException
4773 */
4774 public function testSetCustomDataInCreateAndHook() {
4775 $this->createCustomGroupWithFieldOfType([], 'int');
4776 $this->ids['CustomField']['text'] = (int) $this->createTextCustomField(['custom_group_id' => $this->ids['CustomGroup']['Custom Group']])['id'];
4777 $this->hookClass->setHook('civicrm_post', [
4778 $this,
4779 'civicrmPostContributionCustom',
4780 ]);
4781 $params = $this->_params;
4782 $params['custom_' . $this->ids['CustomField']['text']] = 'Some Text';
4783 $contribution = $this->callAPISuccess('Contribution', 'create', $params);
4784 $getContribution = $this->callAPISuccess('Contribution', 'get', [
4785 'id' => $contribution['id'],
4786 'return' => ['id', 'custom_' . $this->ids['CustomField']['text'], 'custom_' . $this->ids['CustomField']['int']],
4787 ]);
4788 $this->assertEquals(5, $getContribution['values'][$contribution['id']][$this->getCustomFieldName('int')]);
4789 $this->assertEquals('Some Text', $getContribution['values'][$contribution['id']]['custom_' . $this->ids['CustomField']['text']]);
4790 $this->callAPISuccess('CustomField', 'delete', ['id' => $this->ids['CustomField']['text']]);
4791 $this->callAPISuccess('CustomField', 'delete', ['id' => $this->ids['CustomField']['int']]);
4792 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $this->ids['CustomGroup']['Custom Group']]);
4793 }
4794
4795 /**
4796 * Implement post hook.
4797 *
4798 * @param string $op
4799 * @param string $objectName
4800 * @param int $objectId
4801 * @param \CRM_Core_DAO $objectRef
4802 *
4803 * @throws \CRM_Core_Exception
4804 */
4805 public function civicrmPostContributionCustom($op, $objectName, $objectId, &$objectRef) {
4806 if ($objectName === 'Contribution' && $op === 'create') {
4807 $this->callAPISuccess('Contribution', 'create', [
4808 'id' => $objectId,
4809 'custom_' . $this->ids['CustomField']['int'] => 5,
4810 ]);
4811 }
4812 }
4813
4814 /**
4815 * Test that passing in label for an option value linked to a custom field works
4816 * @see dev/core#1816
4817 */
4818 public function testCustomValueOptionLabelTest() {
4819 $this->createCustomGroupWithFieldOfType([], 'radio');
4820 $params = $this->_params;
4821 $params['custom_' . $this->ids['CustomField']['radio']] = 'Red Testing';
4822 $contribution = $this->callAPISuccess('Contribution', 'Create', $params);
4823 }
4824
4825 /**
4826 * Test repeatTransaction with installments and next_sched_contribution_date
4827 *
4828 * @dataProvider getRepeatTransactionNextSchedData
4829 *
4830 * @param array $dataSet
4831 *
4832 * @throws \Exception
4833 */
4834 public function testRepeatTransactionUpdateNextSchedContributionDate($dataSet) {
4835 $paymentProcessorID = $this->paymentProcessorCreate();
4836 // Create the contribution before the recur so it doesn't trigger the update of next_sched_contribution_date
4837 $contribution = $this->callAPISuccess('contribution', 'create', array_merge(
4838 $this->_params,
4839 [
4840 'contribution_status_id' => 'Completed',
4841 'receive_date' => $dataSet['repeat'][0]['receive_date'],
4842 ])
4843 );
4844 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4845 'contact_id' => $this->_individualId,
4846 'frequency_interval' => '1',
4847 'amount' => '500',
4848 'contribution_status_id' => 'Pending',
4849 'start_date' => '2012-01-01 00:00:00',
4850 'currency' => 'USD',
4851 'frequency_unit' => 'month',
4852 'payment_processor_id' => $paymentProcessorID,
4853 ], $dataSet['recur']));
4854 // Link the existing contribution to the recur *after* creating the recur.
4855 // If we just created the contribution now the next_sched_contribution_date would be automatically set
4856 // and we want to test the case when it is empty.
4857 $this->callAPISuccess('contribution', 'create', [
4858 'id' => $contribution['id'],
4859 'contribution_recur_id' => $contributionRecur['id'],
4860 ]);
4861
4862 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4863 'id' => $contributionRecur['id'],
4864 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4865 ]);
4866 // Check that next_sched_contribution_date is empty
4867 $this->assertEquals('', $contributionRecur['next_sched_contribution_date'] ?? '');
4868
4869 $this->callAPISuccess('Contribution', 'repeattransaction', [
4870 'contribution_status_id' => 'Completed',
4871 'contribution_recur_id' => $contributionRecur['id'],
4872 'receive_date' => $dataSet['repeat'][0]['receive_date'],
4873 ]);
4874 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4875 'id' => $contributionRecur['id'],
4876 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4877 ]);
4878 // Check that recur has status "In Progress"
4879 $this->assertEquals(
4880 (string) CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', $dataSet['repeat'][0]['expectedRecurStatus']),
4881 $contributionRecur['contribution_status_id']
4882 );
4883 // Check that next_sched_contribution_date has been set to 1 period after the contribution receive date (ie. 1 month)
4884 $this->assertEquals($dataSet['repeat'][0]['expectedNextSched'], $contributionRecur['next_sched_contribution_date']);
4885
4886 // Now call Contribution.repeattransaction again and check that the next_sched_contribution_date has moved forward by 1 period again
4887 $this->callAPISuccess('Contribution', 'repeattransaction', [
4888 'contribution_status_id' => 'Completed',
4889 'contribution_recur_id' => $contributionRecur['id'],
4890 'receive_date' => $dataSet['repeat'][1]['receive_date'],
4891 ]);
4892 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4893 'id' => $contributionRecur['id'],
4894 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4895 ]);
4896 // Check that recur has status "In Progress" or "Completed" depending on whether number of installments has been reached
4897 $this->assertEquals(
4898 (string) CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', $dataSet['repeat'][1]['expectedRecurStatus']),
4899 $contributionRecur['contribution_status_id']
4900 );
4901 // Check that next_sched_contribution_date has been set to 1 period after the contribution receive date (ie. 1 month)
4902 $this->assertEquals($dataSet['repeat'][1]['expectedNextSched'], $contributionRecur['next_sched_contribution_date'] ?? '');
4903 }
4904
4905 /**
4906 * Get dates for testing.
4907 *
4908 * @return array
4909 */
4910 public function getRepeatTransactionNextSchedData() {
4911 // Both these tests handle/test the case that next_sched_contribution_date is empty when Contribution.repeattransaction
4912 // is called for the first time. Historically setting it was inconsistent but on new updates it should always be set.
4913 /*
4914 * This tests that calling Contribution.repeattransaction with installments does the following:
4915 * - For the first call to repeattransaction the recur status is In Progress and next_sched_contribution_date is updated
4916 * to match next expected receive_date.
4917 * - Once the 3rd contribution is created contributionRecur status = completed and next_sched_contribution_date = ''.
4918 */
4919 $result['receive_date_includes_time_with_installments']['2012-01-01-1-month'] = [
4920 'recur' => [
4921 'start_date' => '2012-01-01',
4922 'frequency_interval' => 1,
4923 'installments' => '3',
4924 'frequency_unit' => 'month',
4925 ],
4926 'repeat' => [
4927 [
4928 'receive_date' => '2012-02-29 16:00:00',
4929 'expectedNextSched' => '2012-03-29 00:00:00',
4930 'expectedRecurStatus' => 'In Progress',
4931 ],
4932 [
4933 'receive_date' => '2012-03-29 16:00:00',
4934 'expectedNextSched' => '',
4935 'expectedRecurStatus' => 'Completed',
4936 ],
4937 ],
4938 ];
4939 /*
4940 * This tests that calling Contribution.repeattransaction with no installments does the following:
4941 * - For the each call to repeattransaction the recur status is In Progress and next_sched_contribution_date is updated
4942 * to match next expected receive_date.
4943 */
4944 $result['receive_date_includes_time_no_installments']['2012-01-01-1-month'] = [
4945 'recur' => [
4946 'start_date' => '2012-01-01',
4947 'frequency_interval' => 1,
4948 'frequency_unit' => 'month',
4949 ],
4950 'repeat' => [
4951 [
4952 'receive_date' => '2012-02-29 16:00:00',
4953 'expectedNextSched' => '2012-03-29 00:00:00',
4954 'expectedRecurStatus' => 'In Progress',
4955 ],
4956 [
4957 'receive_date' => '2012-03-29 16:00:00',
4958 'expectedNextSched' => '2012-04-29 00:00:00',
4959 'expectedRecurStatus' => 'In Progress',
4960 ],
4961 ],
4962 ];
4963 return $result;
4964 }
4965
4966 /**
4967 * Make sure that recording a payment doesn't alter the receive_date of a
4968 * pending contribution.
4969 */
4970 public function testPaymentDontChangeReceiveDate() {
4971 $params = [
4972 'contact_id' => $this->_individualId,
4973 'total_amount' => 100,
4974 'receive_date' => '2020-02-02',
4975 'contribution_status_id' => 'Pending',
4976 ];
4977 $contributionID = $this->contributionCreate($params);
4978 $paymentParams = [
4979 'contribution_id' => $contributionID,
4980 'total_amount' => 100,
4981 'trxn_date' => '2020-03-04',
4982 ];
4983 $this->callAPISuccess('payment', 'create', $paymentParams);
4984
4985 //check if contribution status is set to "Completed".
4986 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
4987 'id' => $contributionID,
4988 ]);
4989 $this->assertEquals('2020-02-02 00:00:00', $contribution['receive_date']);
4990 }
4991
4992 /**
4993 * Make sure that recording a payment with Different Payment Instrument update main contribution record payment
4994 * instrument too. If multiple Payment Recorded, last payment record payment (when No more due) instrument set to main
4995 * payment
4996 */
4997 public function testPaymentVerifyPaymentInstrumentChange() {
4998 // Create Pending contribution with pay later mode, with payment instrument Check
4999 $params = [
5000 'contact_id' => $this->_individualId,
5001 'total_amount' => 100,
5002 'receive_date' => '2020-02-02',
5003 'contribution_status_id' => 'Pending',
5004 'is_pay_later' => 1,
5005 'payment_instrument_id' => 'Check',
5006 ];
5007 $contributionID = $this->contributionCreate($params);
5008
5009 // Record the the Payment with instrument other than Check, e.g EFT
5010 $paymentParams = [
5011 'contribution_id' => $contributionID,
5012 'total_amount' => 50,
5013 'trxn_date' => '2020-03-04',
5014 'payment_instrument_id' => 'EFT',
5015 ];
5016 $this->callAPISuccess('payment', 'create', $paymentParams);
5017
5018 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
5019 'id' => $contributionID,
5020 ]);
5021 // payment status should be 'Partially paid'
5022 $this->assertEquals('Partially paid', $contribution['contribution_status']);
5023
5024 // Record the the Payment with instrument other than Check, e.g Cash (pay all remaining amount)
5025 $paymentParams = [
5026 'contribution_id' => $contributionID,
5027 'total_amount' => 50,
5028 'trxn_date' => '2020-03-04',
5029 'payment_instrument_id' => 'Cash',
5030 ];
5031 $this->callAPISuccess('payment', 'create', $paymentParams);
5032
5033 //check if contribution Payment Instrument (Payment Method) is is set to "Cash".
5034 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
5035 'id' => $contributionID,
5036 ]);
5037 $this->assertEquals('Cash', $contribution['payment_instrument']);
5038 $this->assertEquals('Completed', $contribution['contribution_status']);
5039 }
5040
5041 /**
5042 * Test the "clean money" functionality.
5043 */
5044 public function testCleanMoney() {
5045 $params = [
5046 'contact_id' => $this->_individualId,
5047 'financial_type_id' => 1,
5048 'total_amount' => '$100',
5049 'fee_amount' => '$20',
5050 'net_amount' => '$80',
5051 'non_deductible_amount' => '$80',
5052 'sequential' => 1,
5053 ];
5054 $id = $this->callAPISuccess('Contribution', 'create', $params)['id'];
5055 // Reading the return values of the API isn't reliable here; get the data from the db.
5056 $contribution = $this->callAPISuccess('Contribution', 'getsingle', ['id' => $id]);
5057 $this->assertEquals('100.00', $contribution['total_amount']);
5058 $this->assertEquals('20.00', $contribution['fee_amount']);
5059 $this->assertEquals('80.00', $contribution['net_amount']);
5060 $this->assertEquals('80.00', $contribution['non_deductible_amount']);
5061 }
5062
5063 }