Cleanup AdditionalPaymentTest to use event trait
authorEileen McNaughton <emcnaughton@wikimedia.org>
Mon, 19 Jun 2023 01:44:17 +0000 (13:44 +1200)
committerEileen McNaughton <emcnaughton@wikimedia.org>
Tue, 20 Jun 2023 23:15:15 +0000 (16:15 -0700)
Fix additional payment test to use Event test trait

Civi/Test/EventTestTrait.php
tests/phpunit/CRM/Event/BAO/AdditionalPaymentTest.php

index 33b8d5e76e3506f1c81d03bd7f45209254862cbf..c3ed13598376b7aadfb1c6c0547280907a26018a 100644 (file)
@@ -383,6 +383,7 @@ trait EventTestTrait {
     }
     return [
       'free' => ['name' => 'free', 'label' => 'Complementary', 'amount' => 0],
+      'student_early' => ['name' => 'student_early', 'label' => 'Student early bird', 'amount' => 50],
       'student' => ['name' => 'student', 'label' => 'Student Rate', 'amount' => 100],
       'student_plus' => ['name' => 'student_plus', 'label' => 'Student Deluxe', 'amount' => 200],
       'standard' => ['name' => 'standard', 'label' => 'Standard Rate', 'amount' => 300],
index d38990b3b7398d400bfd204db3f8424667d632bc..dc1dec76962beb54ea17bec451a01473da89fd41 100644 (file)
@@ -9,6 +9,7 @@
  +--------------------------------------------------------------------+
  */
 
+use Civi\Api4\Contribution;
 use Civi\Api4\EntityFinancialAccount;
 
 /**
@@ -34,68 +35,34 @@ class CRM_Event_BAO_AdditionalPaymentTest extends CiviUnitTestCase {
 
   /**
    * Set up.
-   *
-   * @throws \CRM_Core_Exception
    */
   public function setUp(): void {
     parent::setUp();
     $this->contactID = $this->individualCreate();
-    $event = $this->eventCreate();
+    $event = $this->eventCreatePaid();
     $this->eventID = $event['id'];
   }
 
   /**
    * Cleanup after test.
-   *
-   * @throws \CRM_Core_Exception
    */
   public function tearDown(): void {
-    $this->eventDelete($this->eventID);
     $this->quickCleanUpFinancialEntities();
     parent::tearDown();
   }
 
-  /**
-   * Check that all tests that have created payments have created them with the right financial entities.
-   *
-   * Ideally this would be on CiviUnitTestCase but many classes would still fail. Also, it might
-   * be good if it only ran on tests that created at least one contribution.
-   *
-   * @throws \CRM_Core_Exception
-   */
-  protected function assertPostConditions(): void {
-    $this->validateAllPayments();
-    $this->validateAllContributions();
-  }
-
   /**
    * Helper function to record participant with paid contribution.
    *
-   * @param int $feeTotal
-   * @param int $actualPaidAmt
+   * @param float $actualPaidAmt
    * @param array $participantParams
    * @param array $contributionParams
    *
    * @return array
-   * @throws \CRM_Core_Exception
    */
-  protected function addParticipantWithPayment($feeTotal, $actualPaidAmt, $participantParams = [], $contributionParams = []) {
-    $priceSetId = $this->eventPriceSetCreate($feeTotal);
-    CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->eventID, $priceSetId);
+  protected function addParticipantWithPayment(float $actualPaidAmt, array $participantParams = [], array $contributionParams = []): array {
     // -- processing priceSet using the BAO
     $lineItems = [];
-    $priceSet = CRM_Price_BAO_PriceSet::getSetDetail($priceSetId, TRUE, FALSE);
-    $priceSet = $priceSet[$priceSetId] ?? NULL;
-    $feeBlock = $priceSet['fields'] ?? NULL;
-    $params['price_2'] = $feeTotal;
-    $tempParams = $params;
-
-    CRM_Price_BAO_PriceSet::processAmount($feeBlock,
-      $params, $lineItems
-    );
-    foreach ($lineItems as $lineItemID => $lineItem) {
-      $lineItems[$lineItemID]['entity_table'] = 'civicrm_participant';
-    }
 
     $participantParams = array_merge(
       [
@@ -103,7 +70,7 @@ class CRM_Event_BAO_AdditionalPaymentTest extends CiviUnitTestCase {
         'is_test' => 0,
         'is_pay_later' => 0,
         'event_id' => $this->eventID,
-        'register_date' => date('Y-m-d') . " 00:00:00",
+        'register_date' => date('Y-m-d') . ' 00:00:00',
         'role_id' => 1,
         'status_id' => 14,
         'source' => 'Event_' . $this->eventID,
@@ -117,7 +84,6 @@ class CRM_Event_BAO_AdditionalPaymentTest extends CiviUnitTestCase {
     // create participant contribution with partial payment
     $contributionParams = array_merge(
       [
-        'total_amount' => $feeTotal,
         'source' => 'Fall Fundraiser Dinner: Offline registration',
         'currency' => 'USD',
         'receipt_date' => 'today',
@@ -127,22 +93,50 @@ class CRM_Event_BAO_AdditionalPaymentTest extends CiviUnitTestCase {
         'contribution_status_id' => 'Pending',
         'receive_date' => 'today',
         'api.Payment.create' => ['total_amount' => $actualPaidAmt],
-        'line_items' => [['line_item' => $lineItems, 'params' => $participantParams]],
+        'line_items' => [
+          [
+            'line_item' => [
+              [
+                'entity_table' => 'civicrm_participant',
+                'price_field_value_id' => $this->ids['PriceFieldValue']['PaidEvent_student'],
+              ],
+            ],
+            'params' => $participantParams,
+          ],
+        ],
       ],
       $contributionParams
     );
 
     $contribution = $this->callAPISuccess('Order', 'create', $contributionParams);
-    $participant = $this->callAPISuccessGetSingle('participant', []);
+    $this->ids['Contribution']['PaidEvent'] = $contribution['id'];
+    $participant = $this->callAPISuccessGetSingle('Participant', []);
     $this->callAPISuccessGetSingle('ParticipantPayment', ['contribution_id' => $contribution['id'], 'participant_id' => $participant['id']]);
 
+    // Check it is correct.
+    try {
+      $contribution = Contribution::get(FALSE)
+        ->addWhere('id', '=', $contribution['id'])
+        ->addSelect('paid_amount', 'total_amount', 'balance_amount', 'contribution_status_id:label')
+        ->execute()
+        ->first();
+
+      $this->assertEquals(100, $contribution['total_amount']);
+      $this->assertEquals($actualPaidAmt, $contribution['paid_amount'], 'Amount paid is not correct');
+      $this->assertEquals(100 - $actualPaidAmt, $contribution['balance_amount'], 'Balance is not correct');
+      if ($actualPaidAmt > 0) {
+        $this->assertEquals('Partially paid', $contribution['contribution_status_id:label'], 'Contribution status is not correct');
+      }
+      else {
+        $this->assertEquals('Pending Label**', $contribution['contribution_status_id:label'], 'Contribution status is not correct');
+      }
+    }
+    catch (CRM_Core_Exception $e) {
+      $this->fail('Failed to retrieve contribution ' . $e->getMessage());
+    }
     return [
       'participant' => $participant,
       'contribution' => $this->callAPISuccessGetSingle('Contribution', ['id' => $contribution['id']]),
-      'lineItem' => $lineItems,
-      'params' => $tempParams,
-      'feeBlock' => $feeBlock,
-      'priceSetId' => $priceSetId,
     ];
   }
 
@@ -151,16 +145,13 @@ class CRM_Event_BAO_AdditionalPaymentTest extends CiviUnitTestCase {
    *
    * @throws \CRM_Core_Exception
    */
-  public function testPaymentWithCustomPaymentInstrument() {
-    $feeAmt = 100;
-    $amtPaid = 0;
-
+  public function testPaymentWithCustomPaymentInstrument(): void {
     // Create undetermined Payment Instrument
     $paymentInstrumentID = $this->createPaymentInstrument(['label' => 'Undetermined'], 'Accounts Receivable');
 
     // record pending payment for an event
     $result = $this->addParticipantWithPayment(
-      $feeAmt, $amtPaid,
+      0,
       ['is_pay_later' => 1],
       [
         'total_amount' => 100,
@@ -168,18 +159,11 @@ class CRM_Event_BAO_AdditionalPaymentTest extends CiviUnitTestCase {
         'contribution_status_id' => CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'),
       ]
     );
-    $contributionID = $result['contribution']['id'];
-
-    // check payment info
-    $paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($result['participant']['id'], 'event');
-    $this->assertEquals($feeAmt, $this->callAPISuccessGetValue('Contribution', ['return' => 'total_amount', 'id' => $contributionID]), 'Total amount recorded is not correct');
-    $this->assertEquals($amtPaid, round($paymentInfo['paid']), 'Amount paid is not correct');
-    $this->assertEquals($feeAmt, CRM_Contribute_BAO_Contribution::getContributionBalance($contributionID), 'Balance is not correct');
-    $this->assertEquals('Pending Label**', $paymentInfo['contribution_status'], 'Contribution status is not correct');
+    $contributionID = $this->ids['Contribution']['PaidEvent'];
 
+    $_REQUEST['id'] = $contributionID;
     // make additional payment via 'Record Payment' form
-    $form = new CRM_Contribute_Form_AdditionalPayment();
-    $submitParams = [
+    $form = $this->getFormObject('CRM_Contribute_Form_AdditionalPayment', [
       'contact_id' => $result['contribution']['contact_id'],
       'contribution_id' => $contributionID,
       'total_amount' => 100,
@@ -188,16 +172,21 @@ class CRM_Event_BAO_AdditionalPaymentTest extends CiviUnitTestCase {
       'payment_processor_id' => 0,
       'payment_instrument_id' => CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', 'Check'),
       'check_number' => '#123',
-    ];
-    $form->cid = $result['contribution']['contact_id'];
-    $form->testSubmit($submitParams);
+    ]);
+    $form->preProcess();
+    $form->buildForm();
+    $form->postProcess();
 
-    // check payment info again and see if the payment is completed
-    $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID]);
-    $this->assertEquals($feeAmt, $contribution['total_amount'], 'Total amount recorded is not proper');
-    $this->assertEquals($feeAmt, CRM_Core_BAO_FinancialTrxn::getTotalPayments($contributionID), 'Amount paid is not correct');
-    $this->assertEquals(CRM_Contribute_BAO_Contribution::getContributionBalance($contributionID), 0, 'Balance amount is not proper');
-    $this->assertEquals('Completed', $contribution['contribution_status'], 'Contribution status is not correct');
+    $contribution = Contribution::get(FALSE)
+      ->addWhere('id', '=', $contributionID)
+      ->addSelect('paid_amount', 'total_amount', 'balance_amount', 'contribution_status_id:label')
+      ->execute()
+      ->first();
+
+    $this->assertEquals(100, $contribution['total_amount']);
+    $this->assertEquals(100, $contribution['paid_amount'], 'Amount paid is not correct');
+    $this->assertEquals(0, $contribution['balance_amount'], 'Balance is not correct');
+    $this->assertEquals('Completed', $contribution['contribution_status_id:label'], 'Contribution status is not correct');
 
     $this->callAPISuccess('OptionValue', 'delete', ['id' => $paymentInstrumentID]);
   }
@@ -209,7 +198,9 @@ class CRM_Event_BAO_AdditionalPaymentTest extends CiviUnitTestCase {
    * @param string $financialAccountName
    *
    * @return int
+   *
    * @noinspection PhpDocMissingThrowsInspection
+   * @noinspection PhpUnhandledExceptionInspection
    */
   protected function createPaymentInstrument(array $params = [], string $financialAccountName = 'Donation'): int {
     $params = array_merge([
@@ -242,26 +233,16 @@ class CRM_Event_BAO_AdditionalPaymentTest extends CiviUnitTestCase {
     // participant ids are all 1 so they might match by accident.
     $this->contributionCreate(['contact_id' => $this->individualCreate([], 0, TRUE)]);
 
-    $feeAmt = 100;
     $amtPaid = (float) 60;
-    $balance = (float) 40;
-    $result = $this->addParticipantWithPayment($feeAmt, $amtPaid);
-    $amountPaid = CRM_Core_BAO_FinancialTrxn::getTotalPayments($result['contribution']['id']);
-    $contributionBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($result['contribution']['id']);
-
-    $this->assertEquals($feeAmt, $this->callAPISuccess('Contribution', 'getvalue', ['return' => 'total_amount', 'id' => $result['contribution']['id']]), 'Total amount recorded is not correct');
-    $this->assertEquals($amtPaid, $amountPaid, 'Amount paid is not correct');
-    $this->assertEquals($balance, $contributionBalance, 'Balance is not correct');
-
-    $this->assertEquals('Partially paid', $result['contribution']['contribution_status']);
+    $result = $this->addParticipantWithPayment($amtPaid);
     $this->assertEquals('Partially paid', $result['participant']['participant_status']);
 
     // Check the record payment link has the right id and that it doesn't
     // match by accident.
-    $this->assertNotEquals($result['contribution']['id'], $result['participant']['id']);
-    $paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($result['participant']['id'], 'event');
+    $this->assertNotEquals($this->ids['Contribution']['PaidEvent'], $result['participant']['id']);
+    $paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->ids['Contribution']['PaidEvent']);
     $this->assertEquals('Record Payment', $paymentInfo['payment_links'][0]['title']);
-    $this->assertEquals($result['contribution']['id'], $paymentInfo['payment_links'][0]['qs']['id']);
+    $this->assertEquals($this->ids['Contribution']['PaidEvent'], $paymentInfo['payment_links'][0]['qs']['id']);
   }
 
   /**
@@ -269,10 +250,9 @@ class CRM_Event_BAO_AdditionalPaymentTest extends CiviUnitTestCase {
    *
    * @throws \CRM_Core_Exception
    */
-  public function testTransactionInfo() {
-    $feeAmt = 100;
+  public function testTransactionInfo(): void {
     $amtPaid = 80;
-    $result = $this->addParticipantWithPayment($feeAmt, $amtPaid);
+    $result = $this->addParticipantWithPayment($amtPaid);
     $contributionID = $result['contribution']['id'];
 
     $this->callAPISuccess('Payment', 'create', [
@@ -283,8 +263,11 @@ class CRM_Event_BAO_AdditionalPaymentTest extends CiviUnitTestCase {
     ]);
 
     //Change selection to a lower amount.
-    $params['price_2'] = 50;
-    CRM_Price_BAO_LineItem::changeFeeSelections($params, $result['participant']['id'], 'participant', $contributionID, $result['feeBlock'], $result['lineItem']);
+    $params['price_2'] = $this->ids['PriceFieldValue']['PaidEvent_student_early'];
+    $priceSet = CRM_Price_BAO_PriceSet::getSetDetail($this->ids['PriceSet']['PaidEvent']);
+    $priceSet = $priceSet[$this->ids['PriceSet']['PaidEvent']] ?? NULL;
+    $feeBlock = $priceSet['fields'] ?? NULL;
+    CRM_Price_BAO_LineItem::changeFeeSelections($params, $result['participant']['id'], 'participant', $contributionID, $feeBlock, NULL);
 
     $this->callAPISuccess('Payment', 'create', [
       'total_amount' => -50,
@@ -295,16 +278,16 @@ class CRM_Event_BAO_AdditionalPaymentTest extends CiviUnitTestCase {
     $paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($result['participant']['id'], 'event', TRUE);
     $transaction = $paymentInfo['transaction'];
 
-    //Assert all transaction(owed and refund) are listed on view payments.
-    $this->assertEquals(count($transaction), 3, 'Transaction Details is not proper');
-    $this->assertEquals($transaction[0]['total_amount'], 80.00);
-    $this->assertEquals($transaction[0]['status'], 'Completed');
+    // Assert all transaction(owed and refund) are listed on view payments.
+    $this->assertCount(3, $transaction, 'Transaction Details is not proper');
+    $this->assertEquals(80.00, $transaction[0]['total_amount']);
+    $this->assertEquals('Completed', $transaction[0]['status']);
 
-    $this->assertEquals($transaction[1]['total_amount'], 20.00);
-    $this->assertEquals($transaction[1]['status'], 'Completed');
+    $this->assertEquals(20.00, $transaction[1]['total_amount']);
+    $this->assertEquals('Completed', $transaction[1]['status']);
 
-    $this->assertEquals($transaction[2]['total_amount'], -50.00);
-    $this->assertEquals($transaction[2]['status'], 'Refunded Label**');
+    $this->assertEquals(-50.00, $transaction[2]['total_amount']);
+    $this->assertEquals('Refunded Label**', $transaction[2]['status']);
   }
 
 }