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