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