Merge pull request #21940 from eileenmcnaughton/debug
[civicrm-core.git] / CRM / Batch / Form / Entry.php
index 39b4586ad4858a81254246c1b8a92bdb580da7f5..0a395b52afad3a2dd833dc7c4bc63bf1e619773b 100644 (file)
@@ -136,6 +136,13 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
     return $this->currentRowMembershipID;
   }
 
+  /**
+   * Get the order (contribution) status for the current row.
+   */
+  protected function getCurrentRowPaymentStatus() {
+    return CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $this->currentRow['contribution_status_id']);
+  }
+
   /**
    * Get the contact ID for the current row.
    *
@@ -312,7 +319,7 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
         $this->add('select', "member_option[$rowNumber]", '', $options);
       }
       if ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
-        $options = ['' => '-select-'];
+        $options = ['' => ts('-select-')];
         $optionTypes = [
           '1' => ts('Adjust Pledge Payment Schedule?'),
           '2' => ts('Adjust Total Pledge Amount?'),
@@ -781,7 +788,7 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
         $this->updateContactInfo($value);
 
         //check for custom data
-        $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key],
+        $value['custom'] = CRM_Core_BAO_CustomField::postProcess($this->currentRow,
           $key,
           'Membership',
           $value['membership_type_id']
@@ -813,20 +820,13 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
           'membership_type_id' => $value['membership_type_id'],
           'financial_type_id' => $value['financial_type_id'],
         ], $key);
+        $order->setEntityParameters($this->getCurrentRowMembershipParams(), $key);
 
         if (!empty($order->getLineItems())) {
           $value['lineItems'] = [$order->getPriceSetID() => $order->getPriceFieldIndexedLineItems()];
           $value['processPriceSet'] = TRUE;
         }
         // end of contribution related section
-
-        $membershipParams = [
-          'start_date' => $value['membership_start_date'] ?? NULL,
-          'end_date' => $value['membership_end_date'] ?? NULL,
-          'join_date' => $value['membership_join_date'] ?? NULL,
-          'campaign_id' => $value['member_campaign_id'] ?? NULL,
-        ];
-
         if ($this->currentRowIsRenew()) {
           // The following parameter setting may be obsolete.
           $this->_params = $params;
@@ -835,10 +835,9 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
             'end_date' => $value['membership_end_date'] ?? NULL,
             'start_date' => $value['membership_start_date'] ?? NULL,
           ];
-          $membershipSource = $value['source'] ?? NULL;
+
           $membership = $this->legacyProcessMembership(
-            $value['contact_id'], $value['membership_type_id'],
-            $value['custom'], $membershipSource, ['campaign_id' => $value['member_campaign_id'] ?? NULL], $formDates
+            $value['custom'], $formDates
           );
 
           // make contribution entry
@@ -850,11 +849,37 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
           $this->setCurrentRowMembershipID($membership->id);
         }
         else {
-          // @todo - specify the relevant fields - don't copy all over
-          $membershipParams = array_merge($value, $membershipParams);
-          $membership = CRM_Member_BAO_Membership::create($membershipParams);
-        }
+          $createdOrder = civicrm_api3('Order', 'create', [
+            'line_items' => $order->getLineItemForV3OrderApi(),
+            'receive_date' => $this->currentRow['receive_date'],
+            'check_number' => $this->currentRow['check_number'] ?? '',
+            'contact_id' => $this->getCurrentRowContactID(),
+            'batch_id' => $this->_batchId,
+            'financial_type_id' => $this->currentRow['financial_type_id'],
+            'payment_instrument_id' => $this->currentRow['payment_instrument_id'],
+          ]);
+          $this->currentRowContributionID = $createdOrder['id'];
+
+          $this->setCurrentRowMembershipID($createdOrder['values'][$this->getCurrentRowContributionID()]['line_item'][0]['entity_id']);
+          if ($this->getCurrentRowPaymentStatus() === 'Completed') {
+            civicrm_api3('Payment', 'create', [
+              'total_amount' => $order->getTotalAmount() + $order->getTotalTaxAmount(),
+              'check_number' => $this->currentRow['check_number'] ?? '',
+              'trxn_date' => $this->currentRow['receive_date'],
+              'trxn_id' => $this->currentRow['trxn_id'],
+              'payment_instrument_id' => $this->currentRow['payment_instrument_id'],
+              'contribution_id' => $this->getCurrentRowContributionID(),
+              'is_send_contribution_notification' => FALSE,
+            ]);
+          }
 
+          if (in_array($this->getCurrentRowPaymentStatus(), ['Failed', 'Cancelled'])) {
+            Contribution::update()
+              ->addValue('contribution_status_id', $this->currentRow['contribution_status_id'])
+              ->addWhere('id', '=', $this->getCurrentRowContributionID())
+              ->execute();
+          }
+        }
         //process premiums
         if (!empty($value['product_name'])) {
           if ($value['product_name'][0] > 0) {
@@ -878,9 +903,9 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
         // end of premium
 
         //send receipt mail.
-        if ($membership->id && !empty($value['send_receipt'])) {
-          $value['membership_id'] = $membership->id;
-          $this->emailReceipt($this, $value, $membership);
+        if ($this->getCurrentRowMembershipID() && !empty($value['send_receipt'])) {
+          $value['membership_id'] = $this->getCurrentRowMembershipID();
+          $this->emailReceipt($this, $value);
         }
       }
     }
@@ -893,15 +918,16 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
    * @param CRM_Core_Form $form
    *   Form object.
    * @param array $formValues
-   * @param object $membership
-   *   Object.
    *
    * @return bool
    *   true if mail was sent successfully
    * @throws \CRM_Core_Exception|\API_Exception
    *
    */
-  protected function emailReceipt($form, &$formValues, $membership): bool {
+  protected function emailReceipt($form, &$formValues): bool {
+    $membership = new CRM_Member_BAO_Membership();
+    $membership->id = $this->getCurrentRowMembershipID();
+    $membership->fetch();
     // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
     if (!empty($formValues['payment_instrument_id'])) {
       $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
@@ -1005,12 +1031,7 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
   }
 
   /**
-   * @param int $contactID
-   * @param int $membershipTypeID
    * @param $customFieldsFormatted
-   * @param $membershipSource
-   * @param $isPayLater
-   * @param array $memParams
    * @param array $formDates
    *
    * @return CRM_Member_BAO_Membership
@@ -1018,155 +1039,64 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
    * @throws \CRM_Core_Exception
    * @throws \CiviCRM_API3_Exception
    */
-  protected function legacyProcessMembership($contactID, $membershipTypeID, $customFieldsFormatted, $membershipSource, $memParams = [], $formDates = []): CRM_Member_DAO_Membership {
+  protected function legacyProcessMembership($customFieldsFormatted, $formDates = []): CRM_Member_DAO_Membership {
     $updateStatusId = FALSE;
     $changeToday = NULL;
-    $is_test = FALSE;
     $numRenewTerms = 1;
-    $allStatus = CRM_Member_PseudoConstant::membershipStatus();
     $format = '%Y%m%d';
-    $statusFormat = '%Y-%m-%d';
-    $membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipType($membershipTypeID);
     $ids = [];
     $isPayLater = NULL;
+    $memParams = $this->getCurrentRowMembershipParams();
     $currentMembership = $this->getCurrentMembership();
 
-    if ($currentMembership) {
-
-      // Do NOT do anything.
-      //1. membership with status : PENDING/CANCELLED (CRM-2395)
-      //2. Paylater/IPN renew. CRM-4556.
-      if (in_array($currentMembership['status_id'], [
-        array_search('Pending', $allStatus),
-        // CRM-15475
-        array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
-      ])) {
-
-        $memParams = array_merge([
-          'id' => $currentMembership['id'],
-          'status_id' => $currentMembership['status_id'],
-          'start_date' => $currentMembership['start_date'],
-          'end_date' => $currentMembership['end_date'],
-          'join_date' => $currentMembership['join_date'],
-          'membership_type_id' => $membershipTypeID,
-          'max_related' => !empty($membershipTypeDetails['max_related']) ? $membershipTypeDetails['max_related'] : NULL,
-          'membership_activity_status' => $isPayLater ? 'Scheduled' : 'Completed',
-        ], $memParams);
-
-        return CRM_Member_BAO_Membership::create($memParams);
-      }
-
-      // Now Renew the membership
-      if (!$currentMembership['is_current_member']) {
-        // membership is not CURRENT
+    // Now Renew the membership
+    if (!$currentMembership['is_current_member']) {
+      // membership is not CURRENT
 
-        // CRM-7297 Membership Upsell - calculate dates based on new membership type
-        $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'],
-          $changeToday,
-          $membershipTypeID,
-          $numRenewTerms
-        );
-
-        $currentMembership['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
-        foreach (['start_date', 'end_date'] as $dateType) {
-          $currentMembership[$dateType] = $formDates[$dateType] ?? NULL;
-          if (empty($currentMembership[$dateType])) {
-            $currentMembership[$dateType] = $dates[$dateType] ?? NULL;
-          }
-        }
-        $currentMembership['is_test'] = $is_test;
-
-        if (!empty($membershipSource)) {
-          $currentMembership['source'] = $membershipSource;
-        }
-
-        if (!empty($currentMembership['id'])) {
-          $ids['membership'] = $currentMembership['id'];
-        }
-        $memParams = array_merge($currentMembership, $memParams);
-        $memParams['membership_type_id'] = $membershipTypeID;
+      // CRM-7297 Membership Upsell - calculate dates based on new membership type
+      $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'],
+        $changeToday,
+        $this->getCurrentRowMembershipTypeID(),
+        $numRenewTerms
+      );
 
-        //set the log start date.
-        $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
+      foreach (['start_date', 'end_date'] as $dateType) {
+        $memParams[$dateType] = $memParams[$dateType] ?: ($dates[$dateType] ?? NULL);
       }
-      else {
-
-        // CURRENT Membership
-        $membership = new CRM_Member_DAO_Membership();
-        $membership->id = $currentMembership['id'];
-        $membership->find(TRUE);
-        // CRM-7297 Membership Upsell - calculate dates based on new membership type
-        $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id,
-          $changeToday,
-          $membershipTypeID,
-          $numRenewTerms
-        );
 
-        // Insert renewed dates for CURRENT membership
-        $memParams['join_date'] = CRM_Utils_Date::isoToMysql($membership->join_date);
-        $memParams['start_date'] = $formDates['start_date'] ?? CRM_Utils_Date::isoToMysql($membership->start_date);
-        $memParams['end_date'] = $formDates['end_date'] ?? NULL;
-        if (empty($memParams['end_date'])) {
-          $memParams['end_date'] = $dates['end_date'] ?? NULL;
-        }
-        $memParams['membership_type_id'] = $membershipTypeID;
+      $ids['membership'] = $currentMembership['id'];
 
-        //set the log start date.
-        $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
-
-        //CRM-18067
-        if (!empty($membershipSource)) {
-          $memParams['source'] = $membershipSource;
-        }
-        elseif (empty($membership->source)) {
-          $memParams['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
-            $currentMembership['id'],
-            'source'
-          );
-        }
-
-        if (!empty($currentMembership['id'])) {
-          $ids['membership'] = $currentMembership['id'];
-        }
-        $memParams['membership_activity_status'] = $isPayLater ? 'Scheduled' : 'Completed';
-      }
+      //set the log start date.
+      $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
     }
     else {
-      // NEW Membership
-      $memParams = array_merge([
-        'contact_id' => $contactID,
-        'membership_type_id' => $membershipTypeID,
-      ], $memParams);
-
-      $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
-
-      foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
-        $memParams[$dateType] = $formDates[$dateType] ?? NULL;
-        if (empty($memParams[$dateType])) {
-          $memParams[$dateType] = $dates[$dateType] ?? NULL;
-        }
-      }
 
-      $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(CRM_Utils_Date::customFormat($dates['start_date'],
-        $statusFormat),
-        CRM_Utils_Date::customFormat($dates['end_date'],
-          $statusFormat
-        ),
-        CRM_Utils_Date::customFormat($dates['join_date'],
-          $statusFormat
-        ),
-        'now',
-        TRUE,
-        $membershipTypeID,
-        $memParams
+      // CURRENT Membership
+      $membership = new CRM_Member_DAO_Membership();
+      $membership->id = $currentMembership['id'];
+      $membership->find(TRUE);
+      // CRM-7297 Membership Upsell - calculate dates based on new membership type
+      $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id,
+        $changeToday,
+        $this->getCurrentRowMembershipTypeID(),
+        $numRenewTerms
       );
-      $updateStatusId = $status['id'] ?? NULL;
 
-      if (!empty($membershipSource)) {
-        $memParams['source'] = $membershipSource;
+      // Insert renewed dates for CURRENT membership
+      $memParams['join_date'] = CRM_Utils_Date::isoToMysql($membership->join_date);
+      $memParams['start_date'] = $formDates['start_date'] ?? CRM_Utils_Date::isoToMysql($membership->start_date);
+      $memParams['end_date'] = $formDates['end_date'] ?? NULL;
+      if (empty($memParams['end_date'])) {
+        $memParams['end_date'] = $dates['end_date'] ?? NULL;
+      }
+
+      //set the log start date.
+      $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
+
+      if (!empty($currentMembership['id'])) {
+        $ids['membership'] = $currentMembership['id'];
       }
-      $memParams['is_test'] = $is_test;
-      $memParams['is_pay_later'] = $isPayLater;
+      $memParams['membership_activity_status'] = $isPayLater ? 'Scheduled' : 'Completed';
     }
 
     //CRM-4555
@@ -1244,9 +1174,12 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
    * Is the current row a renewal.
    *
    * @return bool
+   *
+   * @throws \CRM_Core_Exception
+   * @throws \CiviCRM_API3_Exception
    */
   private function currentRowIsRenew(): bool {
-    return $this->currentRowIsRenewOption === 2;
+    return $this->currentRowIsRenewOption === 2 && $this->getCurrentMembership();
   }
 
   /**
@@ -1264,10 +1197,44 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
       $this->currentRowExistingMembership = CRM_Member_BAO_Membership::getContactMembership($this->getCurrentRowContactID(), $this->getCurrentRowMembershipTypeID(),
         FALSE, NULL, TRUE
       );
-      // Check and fix the membership if it is STALE
-      CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($this->currentRowExistingMembership);
+      if ($this->currentRowExistingMembership) {
+        // Check and fix the membership if it is STALE
+        CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($this->currentRowExistingMembership);
+      }
     }
     return $this->currentRowExistingMembership;
   }
 
+  /**
+   * Get the params as related to the membership entity.
+   *
+   * @return array
+   */
+  private function getCurrentRowMembershipParams(): array {
+    return array_merge($this->getCurrentRowCustomParams(), [
+      'start_date' => $this->currentRow['membership_start_date'] ?? NULL,
+      'end_date' => $this->currentRow['membership_end_date'] ?? NULL,
+      'join_date' => $this->currentRow['membership_join_date'] ?? NULL,
+      'campaign_id' => $this->currentRow['member_campaign_id'] ?? NULL,
+      'source' => $this->currentRow['source'] ?? (!$this->currentRowIsRenew() ? ts('Batch entry') : ''),
+      'membership_type_id' => $this->currentRow['membership_type_id'],
+      'contact_id' => $this->getCurrentRowContactID(),
+    ]);
+  }
+
+  /**
+   * Get the custom value parameters from the current row.
+   *
+   * @return array
+   */
+  private function getCurrentRowCustomParams(): array {
+    $return = [];
+    foreach ($this->currentRow as $field => $value) {
+      if (strpos($field, 'custom_') === 0) {
+        $return[$field] = $value;
+      }
+    }
+    return $return;
+  }
+
 }