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