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