Merge branch '4.5' into 4.6
[civicrm-core.git] / CRM / Batch / Form / Entry.php
old mode 100644 (file)
new mode 100755 (executable)
index 185c542..ec48e66
@@ -1,7 +1,7 @@
 <?php
 /*
  +--------------------------------------------------------------------+
- | CiviCRM version 4.5                                                |
+ | CiviCRM version 4.6                                                |
  +--------------------------------------------------------------------+
  | Copyright CiviCRM LLC (c) 2004-2014                                |
  +--------------------------------------------------------------------+
 class CRM_Batch_Form_Entry extends CRM_Core_Form {
 
   /**
-   * maximum profile fields that will be displayed
-   *
+   * Maximum profile fields that will be displayed.
    */
   protected $_rowCount = 1;
 
   /**
-   * Batch id
+   * Batch id.
    */
   protected $_batchId;
 
   /**
-   * Batch information
+   * Batch information.
    */
   protected $_batchInfo = array();
 
   /**
-   * store the profile id associated with the batch type
+   * Store the profile id associated with the batch type.
    */
   protected $_profileId;
 
@@ -65,19 +64,19 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
 
   public $_params;
 
-  public $_membershipId = null;
+  public $_membershipId = NULL;
   /**
-   * when not to reset sort_name
+   * When not to reset sort_name.
    */
   protected $_preserveDefault = TRUE;
 
   /**
-   * Contact fields
+   * Contact fields.
    */
   protected $_contactFields = array();
 
   /**
-   * Fields array of fields in the batch profile
+   * Fields array of fields in the batch profile.
    * (based on the uf_field table data)
    * (this can't be protected as it is passed into the CRM_Contact_Form_Task_Batch::parseStreetAddress function
    * (although a future refactoring might hopefully change that so it uses the api & the function is not
@@ -85,13 +84,13 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
    * @var array
    */
   public $_fields = array();
+
   /**
-   * build all the data structures needed to build the form
+   * Build all the data structures needed to build the form.
    *
    * @return void
-   * @access public
    */
-  function preProcess() {
+  public function preProcess() {
     $this->_batchId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
 
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
@@ -107,37 +106,40 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
       $this->_profileId = CRM_Batch_BAO_Batch::getProfileId($this->_batchInfo['type_id']);
     }
     CRM_Core_Resources::singleton()
-    ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
-    ->addSetting(array('batch' => array('type_id' => $this->_batchInfo['type_id'])))
-    ->addSetting(array('setting' => array('monetaryThousandSeparator' => CRM_Core_Config::singleton()->monetaryThousandSeparator)))
-    ->addSetting(array('setting' => array('monetaryDecimalPoint' => CRM_Core_Config::singleton()->monetaryDecimalPoint)));
+      ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
+      ->addSetting(array('batch' => array('type_id' => $this->_batchInfo['type_id'])))
+      ->addSetting(array('setting' => array('monetaryThousandSeparator' => CRM_Core_Config::singleton()->monetaryThousandSeparator)))
+      ->addSetting(array('setting' => array('monetaryDecimalPoint' => CRM_Core_Config::singleton()->monetaryDecimalPoint)));
 
   }
 
   /**
-   * Build the form
+   * Build the form object.
    *
-   * @access public
    *
    * @return void
    */
-  function buildQuickForm() {
+  public function buildQuickForm() {
     if (!$this->_profileId) {
       CRM_Core_Error::fatal(ts('Profile for bulk data entry is missing.'));
     }
 
     $this->addElement('hidden', 'batch_id', $this->_batchId);
 
+    $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
     // get the profile information
-    if ($this->_batchInfo['type_id'] == 1) {
+    if ($this->_batchInfo['type_id'] == $batchTypes['Contribution']) {
       CRM_Utils_System::setTitle(ts('Batch Data Entry for Contributions'));
       $customFields = CRM_Core_BAO_CustomField::getFields('Contribution');
     }
-    else {
+    elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
       CRM_Utils_System::setTitle(ts('Batch Data Entry for Memberships'));
       $customFields = CRM_Core_BAO_CustomField::getFields('Membership');
     }
-
+    elseif ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
+      CRM_Utils_System::setTitle(ts('Batch Data Entry for Pledge Payments'));
+      $customFields = CRM_Core_BAO_CustomField::getFields('Contribution');
+    }
     $this->_fields = array();
     $this->_fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, CRM_Core_Action::VIEW);
 
@@ -173,12 +175,12 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
         array(
           'type' => 'upload',
           'name' => ts('Validate & Process the Batch'),
-          'isDefault' => TRUE
+          'isDefault' => TRUE,
         ),
         array(
           'type' => 'cancel',
           'name' => ts('Save & Continue Later'),
-        )
+        ),
       )
     );
 
@@ -186,15 +188,22 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
 
     $fileFieldExists = FALSE;
     $preserveDefaultsArray = array(
-      'first_name', 'last_name', 'middle_name',
+      'first_name',
+      'last_name',
+      'middle_name',
       'organization_name',
       'household_name',
     );
 
     $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
     $contactReturnProperties = array();
+    $config = CRM_Core_Config::singleton();
+
     for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
-      $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', array('create' => TRUE, 'placeholder' => ts('- select -')));
+      $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', array(
+          'create' => TRUE,
+          'placeholder' => ts('- select -'),
+        ));
 
       // special field specific to membership batch udpate
       if ($this->_batchInfo['type_id'] == 2) {
@@ -204,6 +213,26 @@ 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 = array('' => '-select-');
+        $optionTypes = array(
+          '1' => ts('Adjust Pledge Payment Schedule?'),
+          '2' => ts('Adjust Total Pledge Amount?'),
+        );
+        $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes);
+        if (!empty($this->_batchId) && !empty($this->_batchInfo['data']) && !empty($rowNumber)) {
+          $dataValues = json_decode($this->_batchInfo['data'], TRUE);
+          if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) {
+            $pledgeIDs = CRM_Pledge_BAO_Pledge::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]);
+            foreach ($pledgeIDs as $pledgeID) {
+              $pledgePayment = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeID);
+              $options += array($pledgeID => CRM_Utils_Date::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']);
+            }
+          }
+        }
+
+        $this->add('select', "open_pledges[$rowNumber]", '', $options);
+      }
 
       foreach ($this->_fields as $name => $field) {
         if (in_array($field['field_type'], $contactTypes)) {
@@ -220,32 +249,37 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
 
     $this->assign('fields', $this->_fields);
     CRM_Core_Resources::singleton()
-    ->addSetting(array('contact' => array(
-      'return' => implode(',', $contactReturnProperties),
-      'fieldmap' => array_flip($contactReturnProperties),
-    )));
+      ->addSetting(array(
+        'contact' => array(
+          'return' => implode(',', $contactReturnProperties),
+          'fieldmap' => array_flip($contactReturnProperties),
+        ),
+      ));
 
     // don't set the status message when form is submitted.
     $buttonName = $this->controller->getButtonName('submit');
 
     if ($suppressFields && $buttonName != '_qf_Entry_next') {
-      CRM_Core_Session::setStatus(ts("FILE or Autocomplete Select type field(s) in the selected profile are not supported for Batch Update."), ts("Some fields have been excluded."), "info");
+      CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Batch Update."), ts('Some Fields Excluded'), 'info');
     }
   }
 
   /**
-   * form validations
+   * Form validations.
    *
-   * @param array $params   posted values of the form
-   * @param array $files    list of errors to be posted back to the form
-   * @param array $self     form object
+   * @param array $params
+   *   Posted values of the form.
+   * @param array $files
+   *   List of errors to be posted back to the form.
+   * @param array $self
+   *   Form object.
    *
-   * @return array list of errors to be posted back to the form
-   * @static
-   * @access public
+   * @return array
+   *   list of errors to be posted back to the form
    */
-  static function formRule($params, $files, $self) {
+  public static function formRule($params, $files, $self) {
     $errors = array();
+    $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
 
     if (!empty($params['_qf_Entry_upload_force'])) {
       return TRUE;
@@ -264,13 +298,22 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
       }
 
       //membership type is required for membership batch entry
-      if ( $self->_batchInfo['type_id'] == 2 ) {
+      if ($self->_batchInfo['type_id'] == $batchTypes['Membership']) {
         if (empty($value['membership_type'][1])) {
           $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
         }
       }
     }
-
+    if ($self->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
+      foreach (array_unique($params["open_pledges"]) as $value) {
+        $duplicateRows = array_keys($params["open_pledges"], $value);
+        if (count($duplicateRows) > 1) {
+          foreach ($duplicateRows as $key) {
+            $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
+          }
+        }
+      }
+    }
     if ($batchTotal != $self->_batchInfo['total']) {
       $self->assign('batchAmountMismatch', TRUE);
       $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
@@ -285,42 +328,41 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
   }
 
   /**
-   * Override default cancel action
+   * Override default cancel action.
    */
-  function cancelAction() {
+  public function cancelAction() {
     // redirect to batch listing
     CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
     CRM_Utils_System::civiExit();
   }
 
   /**
-   * This function sets the default values for the form.
+   * Set default values for the form.
    *
-   * @access public
    *
    * @return void
    */
-  function setDefaultValues() {
+  public function setDefaultValues() {
     if (empty($this->_fields)) {
       return;
     }
 
     // for add mode set smart defaults
-    if ( $this->_action & CRM_Core_Action::ADD ) {
-      list( $currentDate, $currentTime ) = CRM_Utils_Date::setDateDefaults( NULL, 'activityDateTime' );
+    if ($this->_action & CRM_Core_Action::ADD) {
+      list($currentDate, $currentTime) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
 
       //get all status
       $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
-      $completeStatus = array_search( 'Completed', $allStatus );
+      $completeStatus = array_search('Completed', $allStatus);
       $specialFields = array(
         'join_date' => $currentDate,
         'receive_date' => $currentDate,
         'receive_date_time' => $currentTime,
-        'contribution_status_id' => $completeStatus
+        'contribution_status_id' => $completeStatus,
       );
 
       for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
-        foreach ($specialFields as $key => $value ) {
+        foreach ($specialFields as $key => $value) {
           $defaults['field'][$rowNumber][$key] = $value;
         }
       }
@@ -336,22 +378,21 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
   }
 
   /**
-   * process the form after the input has been submitted and validated
+   * Process the form after the input has been submitted and validated.
    *
-   * @access public
    *
    * @return void
    */
   public function postProcess() {
     $params = $this->controller->exportValues($this->_name);
-
     $params['actualBatchTotal'] = 0;
 
     // get the profile information
-    if ($this->_batchInfo['type_id'] == 1) {
+    $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
+    if (in_array($this->_batchInfo['type_id'], array($batchTypes['Pledge Payment'], $batchTypes['Contribution']))) {
       $this->processContribution($params);
     }
-    else {
+    elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
       $this->processMembership($params);
     }
 
@@ -372,11 +413,11 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
   }
 
   /**
-   * process contribution records
+   * Process contribution records.
    *
-   * @param array $params associated array of submitted values
+   * @param array $params
+   *   Associated array of submitted values.
    *
-   * @access public
    *
    * @return void
    */
@@ -429,7 +470,7 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
 
         foreach ($dates as $val) {
           if (!empty($value[$val])) {
-            $value[$val] = CRM_Utils_Date::processDate( $value[$val], $value[$val . '_time'], TRUE );
+            $value[$val] = CRM_Utils_Date::processDate($value[$val], $value[$val . '_time'], TRUE);
           }
         }
 
@@ -445,7 +486,7 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
 
         );
         foreach ($fieldTranslations as $formField => $baoField) {
-          if(isset($value[$formField])) {
+          if (isset($value[$formField])) {
             $value[$baoField] = $value[$formField];
           }
           unset($value[$formField]);
@@ -456,8 +497,8 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
         $value['skipRecentView'] = TRUE;
 
         // build line item params
-        $this->_priceSet['fields'][$priceFieldID]['options'][$priceFieldValueID ]['amount'] =  $value['total_amount'];
-        $value['price_'. $priceFieldID] = 1;
+        $this->_priceSet['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
+        $value['price_' . $priceFieldID] = 1;
 
         $lineItem = array();
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
@@ -474,9 +515,36 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
           }
         }
         $value['line_item'] = $lineItem;
-
         //finally call contribution create for all the magic
         $contribution = CRM_Contribute_BAO_Contribution::create($value, CRM_Core_DAO::$_nullArray);
+        $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
+        if (!empty($this->_batchInfo['type_id']) && ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment'])) {
+          $adjustTotalAmount = FALSE;
+          if (isset($params['option_type'][$key])) {
+            if ($params['option_type'][$key] == 2) {
+              $adjustTotalAmount = TRUE;
+            }
+          }
+          $pledgeId = $params['open_pledges'][$key];
+          if (is_numeric($pledgeId)) {
+            $result = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId);
+            $pledgePaymentId = 0;
+            foreach ($result as $key => $values) {
+              if ($values['status'] != 'Completed') {
+                $pledgePaymentId = $values['id'];
+                break;
+              }
+            }
+            CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id);
+            CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId,
+              array($pledgePaymentId),
+              $contribution->contribution_status_id,
+              NULL,
+              $contribution->total_amount,
+              $adjustTotalAmount
+            );
+          }
+        }
 
         //process premiums
         if (!empty($value['product_name'])) {
@@ -501,27 +569,25 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
         // end of premium
 
         //send receipt mail.
-        if ( $contribution->id && !empty($value['send_receipt'])) {
-            // add the domain email id
-            $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
-            $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
-
-            $value['from_email_address'] = $domainEmail;
-            $value['contribution_id'] = $contribution->id;
-            CRM_Contribute_Form_AdditionalInfo::emailReceipt( $this, $value );
+        if ($contribution->id && !empty($value['send_receipt'])) {
+          // add the domain email id
+          $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
+          $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
+          $value['from_email_address'] = $domainEmail;
+          $value['contribution_id'] = $contribution->id;
+          CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $value);
         }
       }
     }
     return TRUE;
   }
-  //end of function
 
   /**
-   * process membership records
+   * Process membership records.
    *
-   * @param array $params associated array of submitted values
+   * @param array $params
+   *   Associated array of submitted values.
    *
-   * @access public
    *
    * @return bool
    */
@@ -529,14 +595,14 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
     $dateTypes = array(
       'join_date' => 'joinDate',
       'membership_start_date' => 'startDate',
-      'membership_end_date' => 'endDate'
+      'membership_end_date' => 'endDate',
     );
 
     $dates = array(
       'join_date',
       'start_date',
       'end_date',
-      'reminder_date'
+      'reminder_date',
     );
 
     // get the price set associated with offline memebership
@@ -638,7 +704,7 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
         }
 
         if (!empty($value['receive_date'])) {
-          $value['receive_date'] = CRM_Utils_Date::processDate( $value['receive_date'], $value['receive_date_time'] , TRUE );
+          $value['receive_date'] = CRM_Utils_Date::processDate($value['receive_date'], $value['receive_date_time'], TRUE);
         }
 
         $params['actualBatchTotal'] += $value['total_amount'];
@@ -653,7 +719,7 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
 
         $editedFieldParams = array(
           'price_set_id' => $priceSetId,
-          'name' => $value['membership_type'][0]
+          'name' => $value['membership_type'][0],
         );
 
         $editedResults = array();
@@ -666,7 +732,7 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
           $fid = $editedResults['id'];
           $editedFieldParams = array(
             'price_field_id' => $editedResults['id'],
-            'membership_type_id' => $value['membership_type_id']
+            'membership_type_id' => $value['membership_type_id'],
           );
 
           $editedResults = array();
@@ -702,10 +768,10 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
         unset($value['membership_start_date']);
         unset($value['membership_end_date']);
 
-        $value['is_renew'] = false;
-        if (!empty($params['member_option']) && CRM_Utils_Array::value( $key, $params['member_option'] ) == 2 ) {
+        $value['is_renew'] = FALSE;
+        if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
           $this->_params = $params;
-          $value['is_renew'] = true;
+          $value['is_renew'] = TRUE;
           $membership = CRM_Member_BAO_Membership::renewMembershipFormWrapper(
             $value['contact_id'],
             $value['membership_type_id'],
@@ -734,7 +800,7 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
 
             $premiumParams = array(
               'product_id' => $value['product_name'][0],
-              'contribution_id' => $value['contribution_id'],
+              'contribution_id' => CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id'),
               'product_option' => $value['product_option'],
               'quantity' => 1,
             );
@@ -744,15 +810,16 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
         // end of premium
 
         //send receipt mail.
-        if ( $membership->id && !empty($value['send_receipt'])) {
+        if ($membership->id && !empty($value['send_receipt'])) {
 
-            // add the domain email id
-            $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
-            $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
+          // add the domain email id
+          $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
+          $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
 
-            $value['from_email_address'] = $domainEmail;
-            $value['membership_id']      = $membership->id;
-            CRM_Member_Form_Membership::emailReceipt( $this, $value, $membership );
+          $value['from_email_address'] = $domainEmail;
+          $value['membership_id'] = $membership->id;
+          $value['contribution_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id');
+          CRM_Member_Form_Membership::emailReceipt($this, $value, $membership);
         }
       }
     }
@@ -760,11 +827,11 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
   }
 
   /**
-   * update contact information
+   * Update contact information.
    *
-   * @param array $value associated array of submitted values
+   * @param array $value
+   *   Associated array of submitted values.
    *
-   * @access public
    *
    * @return void
    */
@@ -784,11 +851,11 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
    * then it probably means there is some functionality that needs to be moved
    * out of the form layer
    *
-   * @param unknown_type $params
+   * @param array $params
    *
    * @return bool
    */
-  function testProcessMembership($params) {
+  public function testProcessMembership($params) {
     return $this->processMembership($params);
   }
 
@@ -801,8 +868,8 @@ class CRM_Batch_Form_Entry extends CRM_Core_Form {
    *
    * @return bool
    */
-  function testProcessContribution($params) {
+  public function testProcessContribution($params) {
     return $this->processContribution($params);
   }
-}
 
+}