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