Merge pull request #17706 from demeritcowboy/mysql-ssl-alt
[civicrm-core.git] / tests / phpunit / CRM / Contribute / BAO / ContributionRecurTest.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 * Class CRM_Contribute_BAO_ContributionRecurTest
14 * @group headless
15 */
16 class CRM_Contribute_BAO_ContributionRecurTest extends CiviUnitTestCase {
17
18 use CRMTraits_Financial_OrderTrait;
19
20 /**
21 * Set up for test.
22 *
23 * @throws \CRM_Core_Exception
24 */
25 public function setUp() {
26 parent::setUp();
27 $this->_ids['payment_processor'] = $this->paymentProcessorCreate();
28 $this->_params = [
29 'contact_id' => $this->individualCreate(),
30 'amount' => 3.00,
31 'frequency_unit' => 'week',
32 'frequency_interval' => 1,
33 'installments' => 2,
34 'start_date' => 'yesterday',
35 'create_date' => 'yesterday',
36 'modified_date' => 'yesterday',
37 'cancel_date' => NULL,
38 'end_date' => '+ 2 weeks',
39 'processor_id' => '643411460836',
40 'trxn_id' => 'e0d0808e26f3e661c6c18eb7c039d363',
41 'invoice_id' => 'e0d0808e26f3e661c6c18eb7c039d363',
42 'contribution_status_id' => 1,
43 'is_test' => 0,
44 'cycle_day' => 1,
45 'next_sched_contribution_date' => '+ 1 week',
46 'failure_count' => 0,
47 'failure_retry_date' => NULL,
48 'auto_renew' => 0,
49 'currency' => 'USD',
50 'payment_processor_id' => $this->_ids['payment_processor'],
51 'is_email_receipt' => 1,
52 'financial_type_id' => 1,
53 'payment_instrument_id' => 1,
54 'campaign_id' => NULL,
55 ];
56 }
57
58 /**
59 * Cleanup after test.
60 *
61 * @throws \CRM_Core_Exception
62 */
63 public function teardown() {
64 $this->quickCleanUpFinancialEntities();
65 }
66
67 /**
68 * Test that an object can be retrieved & saved (per CRM-14986).
69 *
70 * This has been causing a DB error so we are checking for absence of error
71 *
72 * @throws \CRM_Core_Exception
73 */
74 public function testFindSave() {
75 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', $this->_params);
76 $dao = new CRM_Contribute_BAO_ContributionRecur();
77 $dao->id = $contributionRecur['id'];
78 $dao->find(TRUE);
79 $dao->is_email_receipt = 0;
80 $dao->save();
81 }
82
83 /**
84 * Test cancellation works per CRM-14986.
85 *
86 * We are checking for absence of error.
87 *
88 * @throws \CRM_Core_Exception
89 */
90 public function testCancelRecur() {
91 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', $this->_params);
92 CRM_Contribute_BAO_ContributionRecur::cancelRecurContribution(['id' => $contributionRecur['id']]);
93 }
94
95 /**
96 * Test checking if contribution recur object can allow for changes to financial types.
97 *
98 * @throws \CRM_Core_Exception
99 */
100 public function testSupportFinancialTypeChange() {
101 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', $this->_params);
102 $this->callAPISuccess('Contribution', 'create', [
103 'contribution_recur_id' => $contributionRecur['id'],
104 'total_amount' => '3.00',
105 'financial_type_id' => 1,
106 'payment_instrument_id' => 1,
107 'currency' => 'USD',
108 'contact_id' => $this->individualCreate(),
109 'contribution_status_id' => 1,
110 'receive_date' => 'yesterday',
111 ]);
112 $this->assertTrue(CRM_Contribute_BAO_ContributionRecur::supportsFinancialTypeChange($contributionRecur['id']));
113 }
114
115 /**
116 * Test we don't change unintended fields on API edit
117 *
118 * @throws \CRM_Core_Exception
119 */
120 public function testUpdateRecur() {
121 $createParams = $this->_params;
122 $createParams['currency'] = 'XAU';
123 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', $createParams);
124 $editParams = [
125 'id' => $contributionRecur['id'],
126 'end_date' => '+ 4 weeks',
127 ];
128 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', $editParams);
129 $dao = new CRM_Contribute_BAO_ContributionRecur();
130 $dao->id = $contributionRecur['id'];
131 $dao->find(TRUE);
132 $this->assertEquals('XAU', $dao->currency, 'Edit clobbered recur currency');
133 }
134
135 /**
136 * Check test contributions aren't picked up as template for non-test recurs
137 *
138 * @throws \API_Exception
139 * @throws \CRM_Core_Exception
140 * @throws \CiviCRM_API3_Exception
141 * @throws \Civi\API\Exception\UnauthorizedException
142 */
143 public function testGetTemplateContributionMatchTest1() {
144 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', $this->_params);
145 // Create a first contrib
146 $firstContrib = $this->callAPISuccess('Contribution', 'create', [
147 'contribution_recur_id' => $contributionRecur['id'],
148 'total_amount' => '3.00',
149 'financial_type_id' => 1,
150 'payment_instrument_id' => 1,
151 'currency' => 'USD',
152 'contact_id' => $this->individualCreate(),
153 'contribution_status_id' => 1,
154 'receive_date' => 'yesterday',
155 ]);
156 // Create a test contrib - should not be picked up as template for non-test recur
157 $this->callAPISuccess('Contribution', 'create', [
158 'contribution_recur_id' => $contributionRecur['id'],
159 'total_amount' => '3.00',
160 'financial_type_id' => 1,
161 'payment_instrument_id' => 1,
162 'currency' => 'USD',
163 'contact_id' => $this->individualCreate(),
164 'contribution_status_id' => 1,
165 'receive_date' => 'yesterday',
166 'is_test' => 1,
167 ]);
168 $fetchedTemplate = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution($contributionRecur['id']);
169 $this->assertEquals($firstContrib['id'], $fetchedTemplate['id']);
170 }
171
172 /**
173 * Check non-test contributions aren't picked up as template for test recurs
174 *
175 * @throws \API_Exception
176 * @throws \CRM_Core_Exception
177 * @throws \CiviCRM_API3_Exception
178 * @throws \Civi\API\Exception\UnauthorizedException
179 */
180 public function testGetTemplateContributionMatchTest() {
181 $params = $this->_params;
182 $params['is_test'] = 1;
183 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', $params);
184 // Create a first test contrib
185 $firstContrib = $this->callAPISuccess('Contribution', 'create', [
186 'contribution_recur_id' => $contributionRecur['id'],
187 'total_amount' => '3.00',
188 'financial_type_id' => 1,
189 'payment_instrument_id' => 1,
190 'currency' => 'USD',
191 'contact_id' => $this->individualCreate(),
192 'contribution_status_id' => 1,
193 'receive_date' => 'yesterday',
194 'is_test' => 1,
195 ]);
196 // Create a non-test contrib - should not be picked up as template for non-test recur
197 // This shouldn't occur - a live contrib against a test recur, but that's not the point...
198 $this->callAPISuccess('Contribution', 'create', [
199 'contribution_recur_id' => $contributionRecur['id'],
200 'total_amount' => '3.00',
201 'financial_type_id' => 1,
202 'payment_instrument_id' => 1,
203 'currency' => 'USD',
204 'contact_id' => $this->individualCreate(),
205 'contribution_status_id' => 1,
206 'receive_date' => 'yesterday',
207 'is_test' => 0,
208 ]);
209 $fetchedTemplate = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution($contributionRecur['id']);
210 $this->assertEquals($firstContrib['id'], $fetchedTemplate['id']);
211 }
212
213 /**
214 * Test that is_template contribution is used where available
215 *
216 * @throws \API_Exception
217 * @throws \CRM_Core_Exception
218 * @throws \CiviCRM_API3_Exception
219 * @throws \Civi\API\Exception\UnauthorizedException
220 */
221 public function testGetTemplateContributionNewTemplate() {
222 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', $this->_params);
223 // Create the template
224 $templateContrib = $this->callAPISuccess('Contribution', 'create', [
225 'contribution_recur_id' => $contributionRecur['id'],
226 'total_amount' => '3.00',
227 'financial_type_id' => 1,
228 'source' => 'Template Contribution',
229 'payment_instrument_id' => 1,
230 'currency' => 'USD',
231 'contact_id' => $this->individualCreate(),
232 'contribution_status_id' => 1,
233 'receive_date' => 'yesterday',
234 'is_template' => 1,
235 ]);
236 // Create another normal contrib
237 $this->callAPISuccess('Contribution', 'create', [
238 'contribution_recur_id' => $contributionRecur['id'],
239 'total_amount' => '3.00',
240 'financial_type_id' => 1,
241 'source' => 'Non-template Contribution',
242 'payment_instrument_id' => 1,
243 'currency' => 'USD',
244 'contact_id' => $this->individualCreate(),
245 'contribution_status_id' => 1,
246 'receive_date' => 'yesterday',
247 ]);
248 $fetchedTemplate = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution($contributionRecur['id']);
249 // Fetched template should be the is_template, not the latest contrib
250 $this->assertEquals($fetchedTemplate['id'], $templateContrib['id']);
251
252 $repeatContribution = $this->callAPISuccess('Contribution', 'repeattransaction', [
253 'contribution_status_id' => 'Completed',
254 'contribution_recur_id' => $contributionRecur['id'],
255 ]);
256 $this->assertEquals('Template Contribution', $repeatContribution['values'][$repeatContribution['id']]['source']);
257 }
258
259 /**
260 * Test to check if correct membership is auto renewed.
261 *
262 * @throws \CRM_Core_Exception
263 */
264 public function testAutoRenewalWhenOneMemberIsDeceased() {
265 $contactId1 = $this->individualCreate();
266 $contactId2 = $this->individualCreate();
267 $membershipOrganizationId = $this->organizationCreate();
268
269 $this->createExtraneousContribution();
270 $this->callAPISuccess('Contribution', 'create', [
271 'contact_id' => $contactId1,
272 'receive_date' => '2010-01-20',
273 'financial_type_id' => 'Member Dues',
274 'contribution_status_id' => 'Completed',
275 'total_amount' => 150,
276 ]);
277
278 // create membership type
279 $membershipTypeId1 = $this->callAPISuccess('MembershipType', 'create', [
280 'domain_id' => 1,
281 'member_of_contact_id' => $membershipOrganizationId,
282 'financial_type_id' => 'Member Dues',
283 'duration_unit' => 'month',
284 'duration_interval' => 1,
285 'period_type' => 'rolling',
286 'minimum_fee' => 100,
287 'name' => 'Parent',
288 ])['id'];
289
290 $membershipTypeID = $this->callAPISuccess('MembershipType', 'create', [
291 'domain_id' => 1,
292 'member_of_contact_id' => $membershipOrganizationId,
293 'financial_type_id' => 'Member Dues',
294 'duration_unit' => 'month',
295 'duration_interval' => 1,
296 'period_type' => 'rolling',
297 'minimum_fee' => 50,
298 'name' => 'Child',
299 ])['id'];
300
301 $contactIDs = [
302 $contactId1 => $membershipTypeId1,
303 $contactId2 => $membershipTypeID,
304 ];
305
306 $contributionRecurId = $this->callAPISuccess('contribution_recur', 'create', $this->_params)['id'];
307
308 $priceFields = CRM_Price_BAO_PriceSet::getDefaultPriceSet('membership');
309
310 // prepare order api params.
311 $params = [
312 'contact_id' => $contactId1,
313 'receive_date' => '2010-01-20',
314 'financial_type_id' => 'Member Dues',
315 'contribution_status_id' => 'Pending',
316 'contribution_recur_id' => $contributionRecurId,
317 'total_amount' => 150,
318 'api.Payment.create' => ['total_amount' => 150],
319 ];
320
321 foreach ($priceFields as $priceField) {
322 $lineItems = [];
323 $contactId = array_search($priceField['membership_type_id'], $contactIDs);
324 $lineItems[1] = [
325 'price_field_id' => $priceField['priceFieldID'],
326 'price_field_value_id' => $priceField['priceFieldValueID'],
327 'label' => $priceField['label'],
328 'field_title' => $priceField['label'],
329 'qty' => 1,
330 'unit_price' => $priceField['amount'],
331 'line_total' => $priceField['amount'],
332 'financial_type_id' => $priceField['financial_type_id'],
333 'entity_table' => 'civicrm_membership',
334 'membership_type_id' => $priceField['membership_type_id'],
335 ];
336 $params['line_items'][] = [
337 'line_item' => $lineItems,
338 'params' => [
339 'contact_id' => $contactId,
340 'membership_type_id' => $priceField['membership_type_id'],
341 'source' => 'Payment',
342 'join_date' => date('Y-m', strtotime('1 month ago')) . '-28',
343 'start_date' => date('Y-m') . '-28',
344 'contribution_recur_id' => $contributionRecurId,
345 'status_id' => 'Pending',
346 'is_override' => 1,
347 ],
348 ];
349 }
350 $order = $this->callAPISuccess('Order', 'create', $params);
351 $contributionId = $order['id'];
352 $membershipId1 = $this->callAPISuccessGetValue('Membership', [
353 'contact_id' => $contactId1,
354 'membership_type_id' => $membershipTypeId1,
355 'return' => 'id',
356 ]);
357
358 $membershipId2 = $this->callAPISuccessGetValue('Membership', [
359 'contact_id' => $contactId2,
360 'membership_type_id' => $membershipTypeID,
361 'return' => 'id',
362 ]);
363
364 // First renewal (2nd payment).
365 $this->callAPISuccess('Contribution', 'repeattransaction', [
366 'original_contribution_id' => $contributionId,
367 'contribution_status_id' => 'Completed',
368 ]);
369
370 // Second Renewal (3rd payment).
371 $this->callAPISuccess('Contribution', 'repeattransaction', [
372 'original_contribution_id' => $contributionId,
373 'contribution_status_id' => 'Completed',
374 ]);
375
376 // Third renewal (4th payment).
377 $this->callAPISuccess('Contribution', 'repeattransaction', ['original_contribution_id' => $contributionId, 'contribution_status_id' => 'Completed']);
378
379 // check line item and membership payment count.
380 $this->validateAllCounts($membershipId1, 4);
381 $this->validateAllCounts($membershipId2, 4);
382
383 $expectedDate = $this->getYearAndMonthFromOffset(4);
384 // check membership end date.
385 foreach ([$membershipId1, $membershipId2] as $mId) {
386 $endDate = $this->callAPISuccessGetValue('Membership', [
387 'id' => $mId,
388 'return' => 'end_date',
389 ]);
390 $this->assertEquals("{$expectedDate['year']}-{$expectedDate['month']}-27", $endDate, ts('End date incorrect.'));
391 }
392
393 // At this moment Contact 2 is deceased, but we wait until payment is recorded in civi before marking the contact deceased.
394 // At payment Gateway we update the amount from 150 to 100
395 // IPN is recorded for subsequent payment (5th payment).
396 $contribution = $this->callAPISuccess('Contribution', 'repeattransaction', [
397 'original_contribution_id' => $contributionId,
398 'contribution_status_id' => 'Completed',
399 'total_amount' => '100',
400 ]);
401
402 // now we mark the contact2 as deceased.
403 $this->callAPISuccess('Contact', 'create', [
404 'id' => $contactId2,
405 'is_deceased' => 1,
406 ]);
407
408 // We delete latest membership payment and line item.
409 $lineItemId = $this->callAPISuccessGetValue('LineItem', [
410 'contribution_id' => $contribution['id'],
411 'entity_id' => $membershipId2,
412 'entity_table' => 'civicrm_membership',
413 'return' => 'id',
414 ]);
415
416 // No api to delete membership payment.
417 CRM_Core_DAO::executeQuery('
418 DELETE FROM civicrm_membership_payment
419 WHERE contribution_id = %1
420 AND membership_id = %2
421 ', [
422 1 => [$contribution['id'], 'Integer'],
423 2 => [$membershipId2, 'Integer'],
424 ]);
425
426 $this->callAPISuccess('LineItem', 'delete', [
427 'id' => $lineItemId,
428 ]);
429
430 // set membership recurring to null.
431 $this->callAPISuccess('Membership', 'create', [
432 'id' => $membershipId2,
433 'contribution_recur_id' => NULL,
434 ]);
435
436 // check line item and membership payment count.
437 $this->validateAllCounts($membershipId1, 5);
438 $this->validateAllCounts($membershipId2, 4);
439
440 $checkAgainst = $this->callAPISuccessGetSingle('Membership', [
441 'id' => $membershipId2,
442 'return' => ['end_date', 'status_id'],
443 ]);
444
445 // record next subsequent payment (6th payment).
446 $this->callAPISuccess('Contribution', 'repeattransaction', [
447 'original_contribution_id' => $contributionId,
448 'contribution_status_id' => 'Completed',
449 'total_amount' => '100',
450 ]);
451
452 // check membership id 1 is renewed
453 $endDate = $this->callAPISuccessGetValue('Membership', [
454 'id' => $membershipId1,
455 'return' => 'end_date',
456 ]);
457 $expectedDate = $this->getYearAndMonthFromOffset(6);
458 $this->assertEquals("{$expectedDate['year']}-{$expectedDate['month']}-27", $endDate, ts('End date incorrect.'));
459 // check line item and membership payment count.
460 $this->validateAllCounts($membershipId1, 6);
461 $this->validateAllCounts($membershipId2, 4);
462
463 // check if membership status and end date is not changed.
464 $membership2 = $this->callAPISuccessGetSingle('Membership', [
465 'id' => $membershipId2,
466 'return' => ['end_date', 'status_id'],
467 ]);
468 $this->assertSame($membership2, $checkAgainst);
469 }
470
471 /**
472 * Check line item and membership payment count.
473 *
474 * @param int $membershipId
475 * @param int $count
476 *
477 * @throws \CRM_Core_Exception
478 */
479 public function validateAllCounts($membershipId, $count) {
480 $memPayParams = [
481 'membership_id' => $membershipId,
482 ];
483 $lineItemParams = [
484 'entity_id' => $membershipId,
485 'entity_table' => 'civicrm_membership',
486 ];
487 $this->callAPISuccessGetCount('LineItem', $lineItemParams, $count);
488 $this->callAPISuccessGetCount('MembershipPayment', $memPayParams, $count);
489 }
490
491 /**
492 * Given a number of months offset, get the year and month.
493 * Note the way php arithmetic works, using strtotime('+x months') doesn't
494 * work because it will roll over the day accounting for different number
495 * of days in the month, but we want the same day of the month, x months
496 * from now.
497 * e.g. July 31 + 4 months will return Dec 1 if using php functions, but
498 * we want Nov 31.
499 *
500 * @param int $offset
501 * @param int $year Optional input year to start
502 * @param int $month Optional input month to start
503 *
504 * @return array
505 * ['year' => int, 'month' => int]
506 */
507 private function getYearAndMonthFromOffset(int $offset, int $year = NULL, int $month = NULL) {
508 $dateInfo = [
509 'year' => $year ?? date('Y'),
510 'month' => ($month ?? date('m')) + $offset,
511 ];
512 if ($dateInfo['month'] > 12) {
513 $dateInfo['year']++;
514 $dateInfo['month'] -= 12;
515 }
516 if ($dateInfo['month'] < 10) {
517 $dateInfo['month'] = "0{$dateInfo['month']}";
518 }
519
520 return $dateInfo;
521 }
522
523 /**
524 * Test getYearAndMonthFromOffset
525 * @dataProvider yearMonthProvider
526 *
527 * @param array $input
528 * @param array $expected
529 */
530 public function testGetYearAndMonthFromOffset($input, $expected) {
531 $this->assertEquals($expected, $this->getYearAndMonthFromOffset($input[0], $input[1], $input[2]));
532 }
533
534 /**
535 * data provider for testGetYearAndMonthFromOffset
536 */
537 public function yearMonthProvider() {
538 return [
539 // input = offset, year, current month
540 ['input' => [4, 2020, 1], 'output' => ['year' => '2020', 'month' => '05']],
541 ['input' => [6, 2020, 1], 'output' => ['year' => '2020', 'month' => '07']],
542 ['input' => [4, 2020, 2], 'output' => ['year' => '2020', 'month' => '06']],
543 ['input' => [6, 2020, 2], 'output' => ['year' => '2020', 'month' => '08']],
544 ['input' => [4, 2020, 3], 'output' => ['year' => '2020', 'month' => '07']],
545 ['input' => [6, 2020, 3], 'output' => ['year' => '2020', 'month' => '09']],
546 ['input' => [4, 2020, 4], 'output' => ['year' => '2020', 'month' => '08']],
547 ['input' => [6, 2020, 4], 'output' => ['year' => '2020', 'month' => '10']],
548 ['input' => [4, 2020, 5], 'output' => ['year' => '2020', 'month' => '09']],
549 ['input' => [6, 2020, 5], 'output' => ['year' => '2020', 'month' => '11']],
550 ['input' => [4, 2020, 6], 'output' => ['year' => '2020', 'month' => '10']],
551 ['input' => [6, 2020, 6], 'output' => ['year' => '2020', 'month' => '12']],
552 ['input' => [4, 2020, 7], 'output' => ['year' => '2020', 'month' => '11']],
553 ['input' => [6, 2020, 7], 'output' => ['year' => '2021', 'month' => '01']],
554 ['input' => [4, 2020, 8], 'output' => ['year' => '2020', 'month' => '12']],
555 ['input' => [6, 2020, 8], 'output' => ['year' => '2021', 'month' => '02']],
556 ['input' => [4, 2020, 9], 'output' => ['year' => '2021', 'month' => '01']],
557 ['input' => [6, 2020, 9], 'output' => ['year' => '2021', 'month' => '03']],
558 ['input' => [4, 2020, 10], 'output' => ['year' => '2021', 'month' => '02']],
559 ['input' => [6, 2020, 10], 'output' => ['year' => '2021', 'month' => '04']],
560 ['input' => [4, 2020, 11], 'output' => ['year' => '2021', 'month' => '03']],
561 ['input' => [6, 2020, 11], 'output' => ['year' => '2021', 'month' => '05']],
562 ['input' => [4, 2020, 12], 'output' => ['year' => '2021', 'month' => '04']],
563 ['input' => [6, 2020, 12], 'output' => ['year' => '2021', 'month' => '06']],
564 ];
565 }
566
567 }