Ensure contribution_id is always set and clarify what functions do
authorMatthew Wire (MJW Consulting) <mjw@mjwconsult.co.uk>
Sun, 6 Oct 2019 17:23:14 +0000 (19:23 +0200)
committerMatthew Wire (MJW Consulting) <mjw@mjwconsult.co.uk>
Sun, 6 Oct 2019 20:26:40 +0000 (22:26 +0200)
CRM/Member/BAO/Membership.php

index 54ea9d029781cf01ec629f2806aba31aee423c2f..db9c7f3995c0421b563e1fc4732dd98997fe4907 100644 (file)
@@ -360,12 +360,22 @@ class CRM_Member_BAO_Membership extends CRM_Member_DAO_Membership {
     }
     $params['skipLineItem'] = TRUE;
 
-    //record contribution for this membership
+    // Record contribution for this membership and create a MembershipPayment
     if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
       $memInfo = array_merge($params, ['membership_id' => $membership->id]);
       $params['contribution'] = self::recordMembershipContribution($memInfo);
     }
 
+    // Add/update MembershipPayment record for this membership if it is a related contribution
+    if (!empty($params['relate_contribution_id'])) {
+      $membershipPaymentParams = [
+        'membership_id' => $membership->id,
+        'membership_type_id' => $membership->membership_type_id,
+        'contribution_id' => $params['relate_contribution_id'],
+      ];
+      civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
+    }
+
     if (!empty($params['lineItems'])) {
       $params['line_item'] = $params['lineItems'];
     }
@@ -402,16 +412,6 @@ class CRM_Member_BAO_Membership extends CRM_Member_DAO_Membership {
       );
     }
 
-    //insert payment record for this membership
-    if (!empty($params['relate_contribution_id'])) {
-      $membershipPaymentParams = [
-        'membership_id' => $membership->id,
-        'membership_type_id' => $membership->membership_type_id,
-        'contribution_id' => $params['relate_contribution_id'],
-      ];
-      civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
-    }
-
     $transaction->commit();
 
     self::createRelatedMemberships($params, $membership);
@@ -2438,14 +2438,17 @@ WHERE      civicrm_membership.is_test = 0
 
   /**
    * Record contribution record associated with membership.
+   * This will update an existing contribution if $params['contribution_id'] is passed in.
+   * This will create a MembershipPayment to link the contribution and membership
    *
    * @param array $params
    *   Array of submitted params.
    * @param array $ids
    *   (@return CRM_Contribute_BAO_Contribution
    *
-   * @throws \CiviCRM_API3_Exception
+   * @return CRM_Contribute_BAO_Contribution
    * @throws \CRM_Core_Exception
+   * @throws \CiviCRM_API3_Exception
    */
   public static function recordMembershipContribution(&$params, $ids = []) {
     if (!empty($ids)) {