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