Esempio n. 1
0
 /**
  * This function is the main function that is called when the page loads, it decides the which action has to be taken for the page.
  * 
  * return null
  * @access public
  */
 function run()
 {
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, false, 'browse');
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $this->assign('action', $this->_action);
     $this->assign('context', $this->_context);
     $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     require_once 'CRM/Pledge/Page/Tab.php';
     CRM_Pledge_Page_Tab::setContext();
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $this->edit();
     } else {
         $pledgeId = CRM_Utils_Request::retrieve('pledgeId', 'Positive', $this);
         require_once 'CRM/Pledge/BAO/Payment.php';
         $paymentDetails = CRM_Pledge_BAO_Payment::getPledgePayments($pledgeId);
         $this->assign('rows', $paymentDetails);
         $this->assign('pledgeId', $pledgeId);
         $this->assign('contactId', $this->_contactId);
         // check if we can process credit card contribs
         $processors = CRM_Core_PseudoConstant::paymentProcessor(false, false, "billing_mode IN ( 1, 3 )");
         if (count($processors) > 0) {
             $this->assign('newCredit', true);
         } else {
             $this->assign('newCredit', false);
         }
         // check is the user has view/edit signer permission
         $permission = 'view';
         if (CRM_Core_Permission::check('edit pledges')) {
             $permission = 'edit';
         }
         $this->assign('permission', $permission);
     }
     return parent::run();
 }
Esempio n. 2
0
 /**
  * This function update contribution as well as related objects.
  */
 function transitionComponents($params, $processContributionObject = false)
 {
     // get minimum required values.
     $contactId = CRM_Utils_Array::value('contact_id', $params);
     $componentId = CRM_Utils_Array::value('component_id', $params);
     $componentName = CRM_Utils_Array::value('componentName', $params);
     $contributionId = CRM_Utils_Array::value('contribution_id', $params);
     $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
     // if we already processed contribution object pass previous status id.
     $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
     $updateResult = array();
     require_once 'CRM/Contribute/PseudoConstant.php';
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(null, 'name');
     // we process only ( Completed, Cancelled, or Failed ) contributions.
     if (!$contributionId || !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses), array_search('Cancelled', $contributionStatuses), array_search('Failed', $contributionStatuses)))) {
         return $updateResult;
     }
     if (!$componentName || !$componentId) {
         // get the related component details.
         $componentDetails = self::getComponentDetails($contributionId);
     } else {
         $componentDetails['contact_id'] = $contactId;
         $componentDetails['component'] = $componentName;
         if ($componentName = 'event') {
             $componentDetails['participant'] = $componentId;
         } else {
             $componentDetails['membership'] = $componentId;
         }
     }
     if (CRM_Utils_Array::value('contact_id', $componentDetails)) {
         $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contact_id');
     }
     // do check for required ids.
     if (!CRM_Utils_Array::value('membership', $componentDetails) && !CRM_Utils_Array::value('participant', $componentDetails) && !CRM_Utils_Array::value('pledge_payment', $componentDetails) || !CRM_Utils_Array::value('contact_id', $componentDetails)) {
         return $updateResult;
     }
     //now we are ready w/ required ids, start processing.
     require_once 'CRM/Core/Payment/BaseIPN.php';
     $baseIPN = new CRM_Core_Payment_BaseIPN();
     $input = $ids = $objects = array();
     $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
     $ids['contribution'] = $contributionId;
     $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
     $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
     $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
     $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
     $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
     $ids['contributionRecur'] = null;
     $ids['contributionPage'] = null;
     if (!$baseIPN->validateData($input, $ids, $objects, false)) {
         CRM_Core_Error::fatal();
     }
     $membership =& $objects['membership'];
     $participant =& $objects['participant'];
     $pledgePayment =& $objects['pledge_payment'];
     $contribution =& $objects['contribution'];
     if ($pledgePayment) {
         require_once 'CRM/Pledge/BAO/Payment.php';
         $pledgePaymentIDs = array();
         foreach ($pledgePayment as $key => $object) {
             $pledgePaymentIDs[] = $object->id;
         }
         $pledgeID = $pledgePayment[0]->pledge_id;
     }
     require_once 'CRM/Event/PseudoConstant.php';
     require_once 'CRM/Event/BAO/Participant.php';
     require_once 'CRM/Pledge/BAO/Pledge.php';
     require_once 'CRM/Member/PseudoConstant.php';
     require_once 'CRM/Member/BAO/Membership.php';
     $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
     if ($participant) {
         $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
         $oldStatus = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participant->id, 'status_id');
     }
     // we might want to process contribution object.
     $processContribution = false;
     if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
         if ($membership) {
             $membership->status_id = array_search('Cancelled', $membershipStatuses);
             $membership->save();
             $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
             if ($processContributionObject) {
                 $processContribution = true;
             }
         }
         if ($participant) {
             $updatedStatusId = array_search('Cancelled', $participantStatuses);
             CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true);
             $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
             if ($processContributionObject) {
                 $processContribution = true;
             }
         }
         if ($pledgePayment) {
             CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
             $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
             if ($processContributionObject) {
                 $processContribution = true;
             }
         }
     } else {
         if ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
             if ($membership) {
                 $membership->status_id = array_search('Expired', $membershipStatuses);
                 $membership->save();
                 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
                 if ($processContributionObject) {
                     $processContribution = true;
                 }
             }
             if ($participant) {
                 $updatedStatusId = array_search('Cancelled', $participantStatuses);
                 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true);
                 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
                 if ($processContributionObject) {
                     $processContribution = true;
                 }
             }
             if ($pledgePayment) {
                 CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
                 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
                 if ($processContributionObject) {
                     $processContribution = true;
                 }
             }
         } else {
             if ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
                 // only pending contribution related object processed.
                 if ($previousContriStatusId && $previousContriStatusId != array_search('Pending', $contributionStatuses)) {
                     // this is case when we already processed contribution object.
                     return $updateResult;
                 } else {
                     if (!$previousContriStatusId && $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)) {
                         // this is case when we will going to process contribution object.
                         return $updateResult;
                     }
                 }
                 if ($membership) {
                     $format = '%Y%m%d';
                     require_once 'CRM/Member/BAO/MembershipType.php';
                     //CRM-4523
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     if ($currentMembership) {
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday = null);
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday = null);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id);
                     }
                     //get the status for membership.
                     require_once 'CRM/Member/BAO/MembershipStatus.php';
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', true);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, array_search('Current', $membershipStatuses)), 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format), 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format), 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format), 'reminder_date' => CRM_Utils_Date::customFormat($dates['reminder_date'], $format));
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                     $logStartDate = $logStartDate ? CRM_Utils_Date::isoToMysql($logStartDate) : $formatedParams['start_date'];
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     require_once 'CRM/Member/BAO/MembershipLog.php';
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'], '%B %E%f, %Y');
                     $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
                     if ($processContributionObject) {
                         $processContribution = true;
                     }
                 }
                 if ($participant) {
                     $updatedStatusId = array_search('Registered', $participantStatuses);
                     CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true);
                     $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
                     if ($processContributionObject) {
                         $processContribution = true;
                     }
                 }
                 if ($pledgePayment) {
                     CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
                     $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
                     if ($processContributionObject) {
                         $processContribution = true;
                     }
                 }
             }
         }
     }
     // process contribution object.
     if ($processContribution) {
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contributionParams = array();
         $fields = array('contact_id', 'total_amount', 'receive_date', 'is_test', 'payment_instrument_id', 'trxn_id', 'invoice_id', 'contribution_type_id', 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number');
         foreach ($fields as $field) {
             if (!CRM_Utils_Array::value($field, $params)) {
                 continue;
             }
             $contributionParams[$field] = $params[$field];
         }
         $ids = array('contribution' => $contributionId);
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contribution =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
     }
     return $updateResult;
 }
Esempio n. 3
0
 /**
  * takes an associative array and creates a pledge object
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  *
  * @return object CRM_Pledge_BAO_Pledge object 
  * @access public
  * @static
  */
 static function &create(&$params)
 {
     require_once 'CRM/Utils/Date.php';
     //FIXME: a cludgy hack to fix the dates to MySQL format
     $dateFields = array('start_date', 'create_date', 'acknowledge_date', 'modified_date', 'cancel_date', 'end_date');
     foreach ($dateFields as $df) {
         if (isset($params[$df])) {
             $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
         }
     }
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $paymentParams = array();
     $paymentParams['status_id'] = $params['status_id'];
     if (CRM_Utils_Array::value('installment_amount', $params)) {
         $params['amount'] = $params['installment_amount'] * $params['installments'];
     }
     //get All Payments status types.
     require_once 'CRM/Contribute/PseudoConstant.php';
     $paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(null, 'name');
     //update the pledge status only if it does NOT come from form
     if (!isset($params['pledge_status_id'])) {
         if (isset($params['contribution_id'])) {
             if ($params['installments'] > 1) {
                 $params['status_id'] = array_search('In Progress', $paymentStatusTypes);
             }
         } else {
             $params['status_id'] = array_search('Pending', $paymentStatusTypes);
         }
     }
     $pledge = self::add($params);
     if (is_a($pledge, 'CRM_Core_Error')) {
         $pledge->rollback();
         return $pledge;
     }
     //handle custom data.
     if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) {
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_pledge', $pledge->id);
     }
     // skip payment stuff inedit mode
     if (!isset($params['id']) || CRM_Utils_Array::value('is_pledge_pending', $params)) {
         require_once 'CRM/Pledge/BAO/Payment.php';
         //if pledge is pending delete all payments and recreate.
         if (CRM_Utils_Array::value('is_pledge_pending', $params)) {
             CRM_Pledge_BAO_Payment::deletePayments($pledge->id);
         }
         //building payment params
         $paymentParams['pledge_id'] = $pledge->id;
         $paymentKeys = array('amount', 'installments', 'scheduled_date', 'frequency_unit', 'frequency_day', 'frequency_interval', 'contribution_id', 'installment_amount', 'actual_amount');
         foreach ($paymentKeys as $key) {
             $paymentParams[$key] = CRM_Utils_Array::value($key, $params, null);
         }
         CRM_Pledge_BAO_Payment::create($paymentParams);
     }
     $transaction->commit();
     require_once 'CRM/Utils/Recent.php';
     require_once 'CRM/Contribute/PseudoConstant.php';
     require_once 'CRM/Contact/BAO/Contact.php';
     require_once 'CRM/Core/Config.php';
     $url = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home");
     $recentOther = array();
     if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::UPDATE)) {
         $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home");
     }
     if (CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::DELETE)) {
         $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home");
     }
     $config = CRM_Core_Config::singleton();
     require_once 'CRM/Utils/Money.php';
     $contributionTypes = CRM_Contribute_PseudoConstant::contributionType();
     $title = CRM_Contact_BAO_Contact::displayName($pledge->contact_id) . ' - (' . ts('Pledged') . ' ' . CRM_Utils_Money::format($pledge->amount) . ' - ' . $contributionTypes[$pledge->contribution_type_id] . ')';
     // add the recently created Pledge
     CRM_Utils_Recent::add($title, $url, $pledge->id, 'Pledge', $pledge->contact_id, null, $recentOther);
     return $pledge;
 }
Esempio n. 4
0
 /**
  * This function is the main function that is called when the page loads, it decides the which action has to be taken for the page.
  * 
  * return null
  * @access public
  */
 function run()
 {
     $contactID = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullArray);
     $context = CRM_Utils_Request::retrieve('context', 'String', $this);
     if ($context == 'standalone' && !$contactID) {
         $this->_action = CRM_Core_Action::ADD;
         $this->assign('action', $this->_action);
     } else {
         // we should call contact view, preprocess only for pledge in contact summary
         $this->preProcess();
     }
     if ($this->_permission == CRM_Core_Permission::EDIT && !CRM_Core_Permission::check('edit pledges')) {
         $this->_permission = CRM_Core_Permission::VIEW;
         // demote to view since user does not have edit pledge rights
         $this->assign('permission', 'view');
     }
     // check if we can process credit card registration
     $processors = CRM_Core_PseudoConstant::paymentProcessor(false, false, "billing_mode IN ( 1, 3 )");
     if (count($processors) > 0) {
         $this->assign('newCredit', true);
     } else {
         $this->assign('newCredit', false);
     }
     $this->setContext();
     if ($this->_action & CRM_Core_Action::VIEW) {
         $this->view();
     } else {
         if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::DELETE)) {
             $this->edit();
         } else {
             if ($this->_action & CRM_Core_Action::DETACH) {
                 require_once 'CRM/Pledge/BAO/Payment.php';
                 require_once 'CRM/Contribute/PseudoConstant.php';
                 CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($this->_id, null, null, array_search('Cancelled', CRM_Contribute_PseudoConstant::contributionStatus()));
                 $session =& CRM_Core_Session::singleton();
                 $session->setStatus(ts('Pledge has been Cancelled and all scheduled (not completed) payments have been cancelled.<br />'));
                 CRM_Utils_System::redirect($session->popUserContext());
             } else {
                 $this->browse();
             }
         }
     }
     return parent::run();
 }
Esempio n. 5
0
 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = false)
 {
     $contribution =& $objects['contribution'];
     $membership =& $objects['membership'];
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     $values = array();
     if ($input['component'] == 'contribute') {
         require_once 'CRM/Contribute/BAO/ContributionPage.php';
         CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
         $contribution->source = ts('Online Contribution') . ': ' . $values['title'];
         if ($values['is_email_receipt']) {
             $contribution->receipt_date = self::$_now;
         }
         if ($membership) {
             $format = '%Y%m%d';
             require_once 'CRM/Member/BAO/MembershipType.php';
             require_once 'CRM/Member/BAO/Membership.php';
             $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
             if ($currentMembership) {
                 /*
                  * Fixed FOR CRM-4433
                  * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status 
                  * when Contribution mode is notify and membership is for renewal ) 
                  */
                 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday = null);
                 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday = null);
                 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
             } else {
                 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id);
             }
             //get the status for membership.
             require_once 'CRM/Member/BAO/MembershipStatus.php';
             $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', true);
             $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format), 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format), 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format), 'reminder_date' => CRM_Utils_Date::customFormat($dates['reminder_date'], $format));
             $membership->copyValues($formatedParams);
             $membership->save();
             //updating the membership log
             $membershipLog = array();
             $membershipLog = $formatedParams;
             $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
             $logStartDate = $logStartDate ? CRM_Utils_Date::isoToMysql($logStartDate) : $formatedParams['start_date'];
             $membershipLog['start_date'] = $logStartDate;
             $membershipLog['membership_id'] = $membership->id;
             $membershipLog['modified_id'] = $membership->contact_id;
             $membershipLog['modified_date'] = date('Ymd');
             require_once 'CRM/Member/BAO/MembershipLog.php';
             CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
             //update related Memberships.
             CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
         }
     } else {
         // event
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         require_once 'CRM/Event/BAO/Event.php';
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         require_once 'CRM/Event/BAO/Event.php';
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
         require_once 'CRM/Core/BAO/Location.php';
         require_once 'CRM/Event/Form/ManageEvent/Location.php';
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         require_once 'CRM/Core/BAO/UFJoin.php';
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'weight' => 1);
         $values['custom_pre_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams);
         $ufJoinParams['weight'] = 2;
         $values['custom_post_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams);
         $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
         if ($values['event']['is_email_confirm']) {
             $contribution->receipt_date = self::$_now;
         }
         $participant->status_id = 1;
         $participant->save();
     }
     if ($input['net_amount'] == 0 && $input['fee_amount'] != 0) {
         $input['net_amount'] = $input['amount'] - $input['fee_amount'];
     }
     $contribution->contribution_status_id = 1;
     $contribution->is_test = $input['is_test'];
     $contribution->fee_amount = $input['fee_amount'];
     $contribution->net_amount = $input['net_amount'];
     $contribution->trxn_id = $input['trxn_id'];
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->cancel_date = 'null';
     if (CRM_Utils_Array::value('check_number', $input)) {
         $contribution->check_number = $input['check_number'];
     }
     if (CRM_Utils_Array::value('payment_instrument_id', $input)) {
         $contribution->payment_instrument_id = $input['payment_instrument_id'];
     }
     $contribution->save();
     // next create the transaction record
     if (isset($objects['paymentProcessor'])) {
         $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
     } else {
         $paymentProcessor = '';
     }
     if ($contribution->trxn_id) {
         $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => isset($input['trxn_date']) ? $input['trxn_date'] : self::$_now, 'trxn_type' => 'Debit', 'total_amount' => $input['amount'], 'fee_amount' => $contribution->fee_amount, 'net_amount' => $contribution->net_amount, 'currency' => $contribution->currency, 'payment_processor' => $paymentProcessor, 'trxn_id' => $contribution->trxn_id);
         require_once 'CRM/Contribute/BAO/FinancialTrxn.php';
         $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($trxnParams);
     }
     //update corresponding pledge payment record
     require_once 'CRM/Core/DAO.php';
     $returnProperties = array('id', 'pledge_id');
     if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_Payment', 'contribution_id', $contribution->id, $paymentDetails, $returnProperties)) {
         $paymentIDs = array();
         foreach ($paymentDetails as $key => $value) {
             $paymentIDs[] = $value['id'];
             $pledgeId = $value['pledge_id'];
         }
         // update pledge and corresponding payment statuses
         require_once 'CRM/Pledge/BAO/Payment.php';
         CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id);
     }
     // create an activity record
     require_once "CRM/Activity/BAO/Activity.php";
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = null;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, null, $targetContactID);
     } else {
         // event
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     self::sendMail($input, $ids, $objects, $values, $recur, false);
     CRM_Core_Error::debug_log_message("Success: Database updated and mail sent");
 }
Esempio n. 6
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  * @return None 
  */
 public function postProcess()
 {
     //get the submitted form values.
     $formValues = $this->controller->exportValues($this->_name);
     $params = array();
     $formValues['scheduled_date'] = CRM_Utils_Date::processDate($formValues['scheduled_date']);
     $params['scheduled_date'] = CRM_Utils_Date::format($formValues['scheduled_date']);
     $now = date('Ymd');
     if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($params['scheduled_date'], '%Y%m%d'), $now)) {
         $params['status_id'] = array_search('Overdue', CRM_Contribute_PseudoConstant::contributionStatus());
     } else {
         $params['status_id'] = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus());
     }
     $params['id'] = $this->_id;
     $pledgeId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Payment', $params['id'], 'pledge_id');
     require_once 'CRM/Pledge/BAO/Payment.php';
     CRM_Pledge_BAO_Payment::add($params);
     //update pledge status
     CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeId);
     $statusMsg = ts('Pledge Payment Schedule has been updated.<br />');
     CRM_Core_Session::setStatus($statusMsg);
 }
Esempio n. 7
0
 /**
  * Process the contribution
  *
  * @return void
  * @access public
  */
 static function processContribution(&$form, $params, $result, $contactID, $contributionType, $deductibleMode = true, $pending = false, $online = true)
 {
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $honorCId = $recurringContributionID = null;
     if ($online) {
         if ($form->get('honor_block_is_active')) {
             $honorCId = $form->createHonorContact();
         }
         $recurringContributionID = $form->processRecurringContribution($params, $contactID);
     } else {
         if (!$online && isset($params['honor_contact_id'])) {
             $honorCId = $params['honor_contact_id'];
         }
     }
     $config =& CRM_Core_Config::singleton();
     if (!$online && isset($params['non_deductible_amount'])) {
         $nonDeductibleAmount = $params['non_deductible_amount'];
     } else {
         $nonDeductibleAmount = $params['amount'];
     }
     if ($online && $contributionType->is_deductible && $deductibleMode) {
         $selectProduct = CRM_Utils_Array::value('selectProduct', $premiumParams);
         if ($selectProduct && $selectProduct != 'no_thanks') {
             require_once 'CRM/Contribute/DAO/Product.php';
             $productDAO =& new CRM_Contribute_DAO_Product();
             $productDAO->id = $selectProduct;
             $productDAO->find(true);
             if ($params['amount'] < $productDAO->price) {
                 $nonDeductibleAmount = $params['amount'];
             } else {
                 $nonDeductibleAmount = $productDAO->price;
             }
         } else {
             $nonDeductibleAmount = '0.00';
         }
     }
     $now = date('YmdHis');
     $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
     if (CRM_Utils_Array::value('is_email_receipt', $form->_values)) {
         $receiptDate = $now;
     }
     // check contribution Type
     // first create the contribution record
     $contribParams = array('contact_id' => $contactID, 'contribution_type_id' => $contributionType->id, 'contribution_page_id' => $online ? $form->_id : null, 'receive_date' => $now, 'non_deductible_amount' => $nonDeductibleAmount, 'total_amount' => $params['amount'], 'amount_level' => CRM_Utils_Array::value('amount_level', $params), 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], 'source' => !$online || CRM_Utils_Array::value('source', $params) ? CRM_Utils_Array::value('source', $params) : CRM_Utils_Array::value('description', $params), 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), 'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0), 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date::format($params['cancel_date']) : null, 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date::format($params['thankyou_date']) : null);
     if (!$online && isset($params['thankyou_date'])) {
         $contribParams['thankyou_date'] = $params['thankyou_date'];
     }
     if (!$online || $form->_values['is_monetary']) {
         if (!CRM_Utils_Array::value('is_pay_later', $params)) {
             $contribParams['payment_instrument_id'] = 1;
         }
     }
     if (!$pending && $result) {
         $contribParams += array('fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'trxn_id' => $result['trxn_id'], 'receipt_date' => $receiptDate, 'trxn_result_code' => $result['trxn_result_code'], 'payment_processor' => $result['payment_processor']);
     }
     if (isset($honorCId)) {
         $contribParams["honor_contact_id"] = $honorCId;
         $contribParams["honor_type_id"] = $params['honor_type_id'];
     }
     if ($recurringContributionID) {
         $contribParams['contribution_recur_id'] = $recurringContributionID;
     }
     $contribParams["contribution_status_id"] = $pending ? 2 : 1;
     if ($form->_mode == 'test') {
         $contribParams["is_test"] = 1;
     }
     $ids = array();
     if (isset($contribParams['invoice_id'])) {
         $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribParams['invoice_id'], 'id', 'invoice_id');
         if (isset($contribID)) {
             $ids['contribution'] = $contribID;
             $contribParams['id'] = $contribID;
         }
     }
     foreach (array('pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note') as $val) {
         if (CRM_Utils_Array::value($val, $params)) {
             $contribSoftParams[$val] = $params[$val];
         }
     }
     require_once 'CRM/Contribute/BAO/Contribution.php';
     //create an contribution address
     if ($form->_contributeMode != 'notify' && !CRM_Utils_Array::value('is_pay_later', $params)) {
         $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
     }
     // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
     require_once 'CRM/Utils/Money.php';
     $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' '));
     $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' '));
     //add contribution record
     $contribution =& CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
     // process price set, CRM-5095
     if ($contribution->id && $form->_priceSetId) {
         require_once 'CRM/Contribute/Form/AdditionalInfo.php';
         CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $form->_lineItem);
     }
     //add soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
     if (CRM_Utils_Array::value('pcp_made_through_id', $params) || CRM_Utils_Array::value('soft_credit_to', $params)) {
         $contribSoftParams['contribution_id'] = $contribution->id;
         $contribSoftParams['amount'] = $params['amount'];
         //if its due to pcp
         if (CRM_Utils_Array::value('pcp_made_through_id', $params)) {
             $contribSoftParams['pcp_id'] = $params['pcp_made_through_id'];
             $contribSoftParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_PCP', $params['pcp_made_through_id'], 'contact_id');
         } else {
             $contribSoftParams['contact_id'] = CRM_Utils_Array::value('soft_credit_to', $params);
         }
         $softContribution = CRM_Contribute_BAO_Contribution::addSoftContribution($contribSoftParams);
     }
     //handle pledge stuff.
     if (!CRM_Utils_Array::value('separate_membership_payment', $form->_params) && CRM_Utils_Array::value('pledge_block_id', $form->_values) && (CRM_Utils_Array::value('is_pledge', $form->_params) || CRM_Utils_Array::value('pledge_id', $form->_values))) {
         if (CRM_Utils_Array::value('pledge_id', $form->_values)) {
             //when user doing pledge payments.
             //update the schedule when payment(s) are made
             require_once 'CRM/Pledge/BAO/Payment.php';
             foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
                 $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id);
                 CRM_Pledge_BAO_Payment::add($pledgePaymentParams);
             }
             //update pledge status according to the new payment statuses
             CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($form->_values['pledge_id']);
         } else {
             //when user creating pledge record.
             $pledgeParams = array();
             $pledgeParams['contact_id'] = $contribution->contact_id;
             $pledgeParams['installment_amount'] = $contribution->total_amount;
             $pledgeParams['contribution_id'] = $contribution->id;
             $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
             $pledgeParams['contribution_type_id'] = $contribution->contribution_type_id;
             $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
             $pledgeParams['installments'] = $params['pledge_installments'];
             $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
             $pledgeParams['frequency_day'] = 1;
             $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
             $pledgeParams['status_id'] = $contribution->contribution_status_id;
             $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
             $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
             $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
             $pledgeParams['is_test'] = $contribution->is_test;
             $pledgeParams['acknowledge_date'] = date('Ymd');
             require_once 'CRM/Pledge/BAO/Pledge.php';
             $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
             $form->_params['pledge_id'] = $pledge->id;
             //send acknowledgment email. only when pledge is created
             if ($pledge->id) {
                 //build params to send acknowledgment.
                 $pledgeParams['id'] = $pledge->id;
                 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
                 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
                 //scheduled amount will be same as installment_amount.
                 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
                 //get total pledge amount.
                 $pledgeParams['total_pledge_amount'] = $pledge->amount;
                 require_once 'CRM/Pledge/BAO/Pledge.php';
                 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
             }
         }
     }
     if ($online) {
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_contribution', $contribution->id, 'Contribution');
     } else {
         //handle custom data.
         $params['contribution_id'] = $contribution->id;
         if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) {
             require_once 'CRM/Core/BAO/CustomValueTable.php';
             CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
         }
     }
     require_once "CRM/Contribute/BAO/Contribution/Utils.php";
     if (isset($params['related_contact'])) {
         $contactID = $params['related_contact'];
     } else {
         if (isset($params['cms_contactID'])) {
             $contactID = $params['cms_contactID'];
         }
     }
     CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $form->_bltID);
     // return if pending
     if ($pending) {
         return $contribution;
     }
     // next create the transaction record
     if ((!$online || $form->_values['is_monetary']) && $result['trxn_id']) {
         $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $params['amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'currency' => $params['currencyID'], 'payment_processor' => $form->_paymentProcessor['payment_processor_type'], 'trxn_id' => $result['trxn_id'], 'trxn_result_code' => $result['trxn_result_code']);
         require_once 'CRM/Contribute/BAO/FinancialTrxn.php';
         $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($trxnParams);
     }
     //create contribution activity w/ individual and target
     //activity w/ organisation contact id when onbelf, CRM-4027
     $targetContactID = null;
     if (CRM_Utils_Array::value('is_for_organization', $params)) {
         $targetContactID = $contribution->contact_id;
         $contribution->contact_id = $contactID;
     }
     // create an activity record
     require_once 'CRM/Activity/BAO/Activity.php';
     CRM_Activity_BAO_Activity::addActivity($contribution, null, $targetContactID);
     $transaction->commit();
     return $contribution;
 }
Esempio n. 8
0
/**
 * take the input parameter list as specified in the data model and 
 * convert it into the same format that we use in QF and BAO object
 *
 * @param array  $params       Associative array of property name/value
 *                             pairs to insert in new contact.
 * @param array  $values       The reformatted properties that we can use internally
 *                            '
 * @return array|CRM_Error
 * @access public
 */
function _civicrm_contribute_formatted_param(&$params, &$values, $create = false)
{
    // copy all the contribution fields as is
    $fields =& CRM_Contribute_DAO_Contribution::fields();
    _civicrm_store_values($fields, $params, $values);
    require_once 'CRM/Core/OptionGroup.php';
    $customFields = CRM_Core_BAO_CustomField::getFields('Contribution');
    foreach ($params as $key => $value) {
        // ignore empty values or empty arrays etc
        if (CRM_Utils_System::isNull($value)) {
            continue;
        }
        //Handling Custom Data
        if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
            $values[$key] = $value;
            $type = $customFields[$customFieldID]['html_type'];
            if ($type == 'CheckBox' || $type == 'Multi-Select') {
                $mulValues = explode(',', $value);
                $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                $values[$key] = array();
                foreach ($mulValues as $v1) {
                    foreach ($customOption as $customValueID => $customLabel) {
                        $customValue = $customLabel['value'];
                        if (strtolower($customLabel['label']) == strtolower(trim($v1)) || strtolower($customValue) == strtolower(trim($v1))) {
                            if ($type == 'CheckBox') {
                                $values[$key][$customValue] = 1;
                            } else {
                                $values[$key][] = $customValue;
                            }
                        }
                    }
                }
            } else {
                if ($type == 'Select' || $type == 'Radio') {
                    $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                    foreach ($customOption as $customValue => $customLabel) {
                        if (strtolower($customLabel) == strtolower(trim($v1)) || strtolower($customValue) == strtolower(trim($v1))) {
                            $values[$key] = $customValue;
                        }
                    }
                }
            }
        }
        switch ($key) {
            case 'contribution_contact_id':
                if (!CRM_Utils_Rule::integer($value)) {
                    return civicrm_create_error("contact_id not valid: {$value}");
                }
                $dao =& new CRM_Core_DAO();
                $qParams = array();
                $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = {$value}", $qParams);
                if (!$svq) {
                    return civicrm_create_error("Invalid Contact ID: There is no contact record with contact_id = {$value}.");
                }
                $values['contact_id'] = $values['contribution_contact_id'];
                unset($values['contribution_contact_id']);
                break;
            case 'contact_type':
                //import contribution record according to select contact type
                require_once 'CRM/Contact/DAO/Contact.php';
                $contactType =& new CRM_Contact_DAO_Contact();
                //when insert mode check contact id or external identifire
                if ($params['contribution_contact_id'] || $params['external_identifier']) {
                    if ($params['contribution_contact_id']) {
                        $contactType->id = $params['contribution_contact_id'];
                    } else {
                        if ($params['external_identifier']) {
                            $contactType->external_identifier = $params['external_identifier'];
                        }
                    }
                    if ($contactType->find(true)) {
                        if ($params['contact_type'] != $contactType->contact_type) {
                            return civicrm_create_error("Contact Type is wrong: {$contactType->contact_type}");
                        }
                    }
                } else {
                    if ($params['contribution_id'] || $params['trxn_id'] || $params['invoice_id']) {
                        //when update mode check contribution id or trxn id or
                        //invoice id
                        $contactId =& new CRM_Contribute_DAO_Contribution();
                        if ($params['contribution_id']) {
                            $contactId->id = $params['contribution_id'];
                        } else {
                            if ($params['trxn_id']) {
                                $contactId->trxn_id = $params['trxn_id'];
                            } else {
                                if ($params['invoice_id']) {
                                    $contactId->invoice_id = $params['invoice_id'];
                                }
                            }
                        }
                        if ($contactId->find(true)) {
                            $contactType->id = $contactId->contact_id;
                            if ($contactType->find(true)) {
                                if ($params['contact_type'] != $contactType->contact_type) {
                                    return civicrm_create_error("Contact Type is wrong: {$contactType->contact_type}");
                                }
                            }
                        }
                    }
                }
                break;
            case 'receive_date':
            case 'cancel_date':
            case 'receipt_date':
            case 'thankyou_date':
                if (!CRM_Utils_Rule::date($value)) {
                    return civicrm_create_error("{$key} not a valid date: {$value}");
                }
                break;
            case 'non_deductible_amount':
            case 'total_amount':
            case 'fee_amount':
            case 'net_amount':
                if (!CRM_Utils_Rule::money($value)) {
                    return civicrm_create_error("{$key} not a valid amount: {$value}");
                }
                break;
            case 'currency':
                if (!CRM_Utils_Rule::currencyCode($value)) {
                    return civicrm_create_error("currency not a valid code: {$value}");
                }
                break;
            case 'contribution_type':
                require_once 'CRM/Contribute/PseudoConstant.php';
                $values['contribution_type_id'] = CRM_Utils_Array::key(ucfirst($value), CRM_Contribute_PseudoConstant::contributionType());
                if (!CRM_Utils_Array::value('contribution_type_id', $values)) {
                    return civicrm_create_error("Contribution Type is not valid: {$value}");
                }
                break;
            case 'payment_instrument':
                require_once 'CRM/Core/OptionGroup.php';
                $values['payment_instrument_id'] = CRM_Core_OptionGroup::getValue('payment_instrument', $value);
                if (!CRM_Utils_Array::value('payment_instrument_id', $values)) {
                    return civicrm_create_error("Payment Instrument is not valid: {$value}");
                }
                break;
            case 'contribution_status_id':
                require_once 'CRM/Core/OptionGroup.php';
                if (!($values['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', $value))) {
                    return civicrm_create_error("Contribution Status is not valid: {$value}");
                }
                break;
            case 'honor_type_id':
                require_once 'CRM/Core/OptionGroup.php';
                $values['honor_type_id'] = CRM_Core_OptionGroup::getValue('honor_type', $value);
                if (!CRM_Utils_Array::value('honor_type_id', $values)) {
                    return civicrm_create_error("Honor Type is not valid: {$value}");
                }
                break;
            case 'soft_credit':
                //import contribution record according to select contact type
                // validate contact id and external identifier.
                $contactId = CRM_Utils_Array::value('contact_id', $params['soft_credit']);
                $externalId = CRM_Utils_Array::value('external_identifier', $params['soft_credit']);
                if ($contactId || $externalId) {
                    require_once 'CRM/Contact/DAO/Contact.php';
                    $contact =& new CRM_Contact_DAO_Contact();
                    $contact->id = $contactId;
                    $contact->external_identifier = $externalId;
                    $errorMsg = null;
                    if (!$contact->find(true)) {
                        $errorMsg = ts("No match found for specified Soft Credit contact data. Row was skipped.");
                    } else {
                        if ($params['contact_type'] != $contact->contact_type) {
                            $errorMsg = ts("Soft Credit Contact Type is wrong: %1", array(1 => $contact->contact_type));
                        }
                    }
                    if ($errorMsg) {
                        return civicrm_create_error($errorMsg, 'soft_credit');
                    }
                    // finally get soft credit contact id.
                    $values['soft_credit_to'] = $contact->id;
                } else {
                    // get the contact id from dupicate contact rule, if more than one contact is returned
                    // we should return error, since current interface allows only one-one mapping
                    $softParams = $params['soft_credit'];
                    $softParams['contact_type'] = $params['contact_type'];
                    $error = _civicrm_duplicate_formatted_contact($softParams);
                    if (isset($error['error_message']['params'][0])) {
                        $matchedIDs = explode(',', $error['error_message']['params'][0]);
                        // check if only one contact is found
                        if (count($matchedIDs) > 1) {
                            return civicrm_create_error($error['error_message']['message'], 'soft_credit');
                        } else {
                            $values['soft_credit_to'] = $matchedIDs[0];
                        }
                    } else {
                        return civicrm_create_error('No match found for specified Soft Credit contact data. Row was skipped.', 'soft_credit');
                    }
                }
                break;
            case 'pledge_payment':
            case 'pledge_id':
                //giving respect to pledge_payment flag.
                if (!CRM_Utils_Array::value('pledge_payment', $params)) {
                    continue;
                }
                //get total amount of from import fields
                $totalAmount = CRM_Utils_Array::value('total_amount', $params);
                $onDuplicate = CRM_Utils_Array::value('onDuplicate', $params);
                //we need to get contact id $contributionContactID to
                //retrieve pledge details as well as to validate pledge ID
                //first need to check for update mode
                if ($onDuplicate == CRM_Contribute_Import_Parser::DUPLICATE_UPDATE && ($params['contribution_id'] || $params['trxn_id'] || $params['invoice_id'])) {
                    $contribution =& new CRM_Contribute_DAO_Contribution();
                    if ($params['contribution_id']) {
                        $contribution->id = $params['contribution_id'];
                    } else {
                        if ($params['trxn_id']) {
                            $contribution->trxn_id = $params['trxn_id'];
                        } else {
                            if ($params['invoice_id']) {
                                $contribution->invoice_id = $params['invoice_id'];
                            }
                        }
                    }
                    if ($contribution->find(true)) {
                        $contributionContactID = $contribution->contact_id;
                        if (!$totalAmount) {
                            $totalAmount = $contribution->total_amount;
                        }
                    } else {
                        return civicrm_create_error('No match found for specified contact in contribution data. Row was skipped.', 'pledge_payment');
                    }
                } else {
                    // first get the contact id for given contribution record.
                    if (CRM_Utils_Array::value('contribution_contact_id', $params)) {
                        $contributionContactID = $params['contribution_contact_id'];
                    } else {
                        if (CRM_Utils_Array::value('external_identifier', $params)) {
                            require_once 'CRM/Contact/DAO/Contact.php';
                            $contact =& new CRM_Contact_DAO_Contact();
                            $contact->external_identifier = $params['external_identifier'];
                            if ($contact->find(true)) {
                                $contributionContactID = $params['contribution_contact_id'] = $values['contribution_contact_id'] = $contact->id;
                            } else {
                                return civicrm_create_error('No match found for specified contact in contribution data. Row was skipped.', 'pledge_payment');
                            }
                        } else {
                            // we  need to get contribution contact using de dupe
                            $error = civicrm_check_contact_dedupe($params);
                            if (isset($error['error_message']['params'][0])) {
                                $matchedIDs = explode(',', $error['error_message']['params'][0]);
                                // check if only one contact is found
                                if (count($matchedIDs) > 1) {
                                    return civicrm_create_error($error['error_message']['message'], 'pledge_payment');
                                } else {
                                    $contributionContactID = $params['contribution_contact_id'] = $values['contribution_contact_id'] = $matchedIDs[0];
                                }
                            } else {
                                return civicrm_create_error('No match found for specified contact in contribution data. Row was skipped.', 'pledge_payment');
                            }
                        }
                    }
                }
                if (CRM_Utils_Array::value('pledge_id', $params)) {
                    if (CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $params['pledge_id'], 'contact_id') != $contributionContactID) {
                        return civicrm_create_error('Invalid Pledge ID provided. Contribution row was skipped.', 'pledge_payment');
                    }
                    $values['pledge_id'] = $params['pledge_id'];
                } else {
                    //check if there are any pledge related to this contact, with payments pending or in progress
                    require_once 'CRM/Pledge/BAO/Pledge.php';
                    $pledgeDetails = CRM_Pledge_BAO_Pledge::getContactPledges($contributionContactID);
                    if (empty($pledgeDetails)) {
                        return civicrm_create_error('No open pledges found for this contact. Contribution row was skipped.', 'pledge_payment');
                    } else {
                        if (count($pledgeDetails) > 1) {
                            return civicrm_create_error('This contact has more than one open pledge. Unable to determine which pledge to apply the contribution to. Contribution row was skipped.', 'pledge_payment');
                        }
                    }
                    // this mean we have only one pending / in progress pledge
                    $values['pledge_id'] = $pledgeDetails[0];
                }
                //we need to check if oldest payment amount equal to contribution amount
                require_once 'CRM/Pledge/BAO/Payment.php';
                $pledgePaymentDetails = CRM_Pledge_BAO_Payment::getOldestPledgePayment($values['pledge_id']);
                if ($pledgePaymentDetails['amount'] == $totalAmount) {
                    $values['pledge_payment_id'] = $pledgePaymentDetails['id'];
                } else {
                    return civicrm_create_error('Contribution and Pledge Payment amount mismatch for this record. Contribution row was skipped.', 'pledge_payment');
                }
                break;
            default:
                break;
        }
    }
    if (array_key_exists('note', $params)) {
        $values['note'] = $params['note'];
    }
    if ($create) {
        // CRM_Contribute_BAO_Contribution::add() handles contribution_source
        // So, if $values contains contribution_source, convert it to source
        $changes = array('contribution_source' => 'source');
        foreach ($changes as $orgVal => $changeVal) {
            if (isset($values[$orgVal])) {
                $values[$changeVal] = $values[$orgVal];
                unset($values[$orgVal]);
            }
        }
    }
    return null;
}
Esempio n. 9
0
 /**
  * This function is the main function that is called when the page loads, it decides the which action has to be taken for the page.
  * 
  * return null
  * @access public
  */
 function run()
 {
     $this->preProcess();
     // check if we can process credit card registration
     $processors = CRM_Core_PseudoConstant::paymentProcessor(false, false, "billing_mode IN ( 1, 3 )");
     if (count($processors) > 0) {
         $this->assign('newCredit', true);
     } else {
         $this->assign('newCredit', false);
     }
     $this->setContext();
     if ($this->_action & CRM_Core_Action::VIEW) {
         $this->view();
     } else {
         if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::DELETE)) {
             $this->edit();
         } else {
             if ($this->_action & CRM_Core_Action::DETACH) {
                 require_once 'CRM/Pledge/BAO/Payment.php';
                 require_once 'CRM/Contribute/PseudoConstant.php';
                 CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($this->_id, null, null, array_search('Cancelled', CRM_Contribute_PseudoConstant::contributionStatus()));
                 $session =& CRM_Core_Session::singleton();
                 $session->setStatus(ts('Pledge has been Cancelled and all scheduled (not completed) payments have been cancelled.<br />'));
                 CRM_Utils_System::redirect($session->popUserContext());
             } else {
                 $this->browse();
             }
         }
     }
     return parent::run();
 }
Esempio n. 10
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  * @return None 
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         require_once 'CRM/Contribute/BAO/Contribution.php';
         CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
         return;
     }
     // get the submitted form values.
     $submittedValues = $this->controller->exportValues($this->_name);
     // process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = null;
     if ($priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues)) {
         require_once 'CRM/Price/BAO/Set.php';
         CRM_Price_BAO_Set::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]);
         $submittedValues['total_amount'] = $submittedValues['amount'];
     }
     if (!CRM_Utils_Array::value('total_amount', $submittedValues)) {
         $submittedValues['total_amount'] = $this->_values['total_amount'];
     }
     $this->assign('lineItem', !empty($lineItem) ? $lineItem : false);
     if (CRM_Utils_Array::value('soft_credit_to', $submittedValues)) {
         $submittedValues['soft_credit_to'] = $submittedValues['soft_contact_id'];
     }
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $submittedValues)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $submittedValues);
     }
     $config =& CRM_Core_Config::singleton();
     $session =& CRM_Core_Session::singleton();
     //Credit Card Contribution.
     if ($this->_mode) {
         $unsetParams = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'receive_date', 'cancel_date', 'cancel_reason');
         foreach ($unsetParams as $key) {
             if (isset($submittedValues[$key])) {
                 unset($submittedValues[$key]);
             }
         }
         //Get the rquire fields value only.
         $params = $this->_params = $submittedValues;
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = date('YmdHis');
         $fields = array();
         // we need to retrieve email address
         if ($this->_context == 'standalone' && CRM_Utils_Array::value('is_email_receipt', $submittedValues)) {
             require_once 'CRM/Contact/BAO/Contact/Location.php';
             list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
             $this->assign('displayName', $this->userDisplayName);
         }
         //set email for primary location.
         $fields["email-Primary"] = 1;
         $params["email-Primary"] = $this->userEmail;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = true;
             }
         }
         if (CRM_Utils_Array::value('source', $params)) {
             unset($params['source']);
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, null, null, $ctype);
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
             $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
             $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         }
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $this->_params['total_amount'];
         $this->_params['amount_level'] = 0;
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         if (CRM_Utils_Array::value('soft_credit_to', $params)) {
             $this->_params['soft_credit_to'] = $params['soft_credit_to'];
             $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
         }
         $this->_params['pcp_display_in_roll'] = $params['pcp_display_in_roll'];
         $this->_params['pcp_roll_nickname'] = $params['pcp_roll_nickname'];
         $this->_params['pcp_personal_note'] = $params['pcp_personal_note'];
         //Add common data to formatted params
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params);
         if (empty($this->_params['invoice_id'])) {
             $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         } else {
             $this->_params['invoiceID'] = $this->_params['invoice_id'];
         }
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $contributionType =& new CRM_Contribute_DAO_ContributionType();
         $contributionType->id = $params['contribution_type_id'];
         if (!$contributionType->find(true)) {
             CRM_Core_Error::fatal("Could not find a system table");
         }
         // add some contribution type details to the params list
         // if folks need to use it
         $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
         $paymentParams['contributionType_accounting_code'] = $this->_params['contributionType_accounting_code'] = $contributionType->accounting_code;
         $paymentParams['contributionPageID'] = null;
         if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $paymentParams['email'] = $this->userEmail;
         }
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Contribute', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             //set the contribution mode.
             $urlParams = "action=add&cid={$this->_contactID}";
             if ($this->_mode) {
                 $urlParams .= "&mode={$this->_mode}";
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $this->_params['receipt_date'] = $now;
         } else {
             if (!CRM_Utils_System::isNull($this->_params['receipt_date'])) {
                 $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date']);
             } else {
                 $this->_params['receipt_date'] = 'null';
             }
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         // result has all the stuff we need
         // lets archive it to a financial transaction
         if ($contributionType->is_deductible) {
             $this->assign('is_deductible', true);
             $this->set('is_deductible', true);
         }
         // set source if not set
         if (empty($this->_params['source'])) {
             $userID = $session->get('userID');
             $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name');
             $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
         }
         // build custom data getFields array
         $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', false, false, CRM_Utils_Array::value('contribution_type_id', $params));
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType, CRM_Core_BAO_CustomField::getFields('Contribution', false, false, null, null, true));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Contribution');
         require_once 'CRM/Contribute/Form/Contribution/Confirm.php';
         $contribution =& CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, false, false, false);
         // process line items, until no previous line items.
         if (empty($this->_lineItems) && $contribution->id && !empty($lineItem)) {
             CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $lineItem);
         }
         //send receipt mail.
         if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
             $this->_params['contact_id'] = $this->_contactID;
             $this->_params['contribution_id'] = $contribution->id;
             $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, true);
         }
         //process the note
         if ($contribution->id && isset($params['note'])) {
             CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, null);
         }
         //process premium
         if ($contribution->id && isset($params['product_name'][0])) {
             CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, null, $this->_options);
         }
         //update pledge payment status.
         if ($this->_ppID && $contribution->id) {
             //store contribution id in payment record.
             CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_Payment', $this->_ppID, 'contribution_id', $contribution->id);
             require_once 'CRM/Pledge/BAO/Payment.php';
             CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id);
         }
         if ($contribution->id) {
             $statusMsg = ts('The contribution record has been processed.');
             if (CRM_Utils_Array::value('is_email_receipt', $this->_params) && $sendReceipt) {
                 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
             }
             CRM_Core_Session::setStatus($statusMsg);
         }
         //submit credit card contribution ends.
     } else {
         //Offline Contribution.
         $unsetParams = array("payment_processor_id", "email-{$this->_bltID}", "hidden_buildCreditCard", "hidden_buildDirectDebit", "billing_first_name", "billing_middle_name", "billing_last_name", "street_address-5", "city-{$this->_bltID}", "state_province_id-{$this->_bltID}", "postal_code-{$this->_bltID}", "country_id-{$this->_bltID}", "credit_card_number", "cvv2", "credit_card_exp_date", "credit_card_type");
         foreach ($unsetParams as $key) {
             if (isset($submittedValues[$key])) {
                 unset($submittedValues[$key]);
             }
         }
         // get the required field value only.
         $formValues = $submittedValues;
         $params = $ids = array();
         $params['contact_id'] = $this->_contactID;
         $params['currency'] = $config->defaultCurrency;
         if ($currency = CRM_Utils_Array::value('currency', $this->_values)) {
             $params['currency'] = $currency;
         }
         $fields = array('contribution_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number', 'soft_credit_to', 'pcp_made_through_id', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note');
         foreach ($fields as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if ($softID = CRM_Utils_Array::value('softID', $this->_values)) {
             $params['softID'] = $softID;
         }
         $dates = array('receive_date', 'receipt_date', 'cancel_date');
         foreach ($dates as $d) {
             if (!CRM_Utils_System::isNull($formValues[$d])) {
                 $params[$d] = CRM_Utils_Date::processDate($formValues[$d]);
             } else {
                 if (array_key_exists($d, $formValues)) {
                     $params[$d] = 'null';
                 }
             }
         }
         if (CRM_Utils_Array::value('is_email_receipt', $formValues)) {
             $params['receipt_date'] = date("Y-m-d");
         }
         if ($params["contribution_status_id"] == 3) {
             if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
                 $params['cancel_date'] = date("Y-m-d");
             }
         } else {
             $params['cancel_date'] = 'null';
             $params['cancel_reason'] = 'null';
         }
         $ids['contribution'] = $params['id'] = $this->_id;
         //Add Additinal common information  to formatted params
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params);
         //create contribution.
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contribution =& CRM_Contribute_BAO_Contribution::create($params, $ids);
         // process line items, until no previous line items.
         if (empty($this->_lineItems) && $contribution->id && !empty($lineItem)) {
             CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $lineItem);
         }
         // process associated membership / participant, CRM-4395
         $relatedComponentStatusMsg = null;
         if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) {
             $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id, $contribution->contribution_status_id, CRM_Utils_Array::value('contribution_status_id', $this->_values));
         }
         //process  note
         if ($contribution->id && isset($formValues['note'])) {
             CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID);
         }
         //process premium
         if ($contribution->id && isset($formValues['product_name'][0])) {
             CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id, $this->_premiumID, $this->_options);
         }
         //send receipt mail.
         if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $formValues)) {
             $formValues['contact_id'] = $this->_contactID;
             $formValues['contribution_id'] = $contribution->id;
             $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues);
         }
         //update pledge payment status.
         if ($this->_ppID && $contribution->id && $this->_action & CRM_Core_Action::ADD) {
             //store contribution id in payment record.
             CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_Payment', $this->_ppID, 'contribution_id', $contribution->id);
             require_once 'CRM/Pledge/BAO/Payment.php';
             CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id);
         }
         $statusMsg = ts('The contribution record has been saved.');
         if (CRM_Utils_Array::value('is_email_receipt', $formValues) && $sendReceipt) {
             $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
         }
         if ($relatedComponentStatusMsg) {
             $statusMsg .= ' ' . $relatedComponentStatusMsg;
         }
         CRM_Core_Session::setStatus($statusMsg);
         //Offline Contribution ends.
     }
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context=contribution&cid={$this->_contactID}"));
         }
     }
 }
Esempio n. 11
0
 /**
  *  Function to process pledge payments
  */
 function processPledgePayments(&$formatted)
 {
     if (CRM_Utils_Array::value('pledge_payment_id', $formatted) && CRM_Utils_Array::value('pledge_id', $formatted)) {
         //get completed status
         $completeStatusID = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
         require_once 'CRM/Pledge/BAO/Payment.php';
         CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($formatted['pledge_id'], array($formatted['pledge_payment_id']), $completeStatusID);
         //need to update payment record to map contribution_id
         CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_Payment', $formatted['pledge_payment_id'], 'contribution_id', $formatted['contribution_id']);
         return CRM_Contribute_Import_Parser::PLEDGE_PAYMENT;
     }
 }
Esempio n. 12
0
 static function adjustPledgePayment($pledgeID, $actualAmount, $pledgeScheduledAmount, $paymentContributionId = null, $pPaymentId = null)
 {
     $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(null, 'name');
     $oldestPayment = self::getOldestPledgePayment($pledgeID);
     if (!$paymentContributionId) {
         // means we are editing payment scheduled payment, so get the second pending to update.
         $oldestPayment = self::getOldestPledgePayment($pledgeID, 2);
         if ($oldestPayment['count'] != 1 && $oldestPayment['id'] == $pPaymentId) {
             $oldestPayment = CRM_Pledge_BAO_Payment::getOldestPledgePayment($pledgeID);
         }
     }
     if ($oldestPayment) {
         // not the last scheduled payment and the actual amount is less than the expected , add it to oldest pending.
         if ($actualAmount != $pledgeScheduledAmount && ($actualAmount < $pledgeScheduledAmount || $actualAmount - $pledgeScheduledAmount < $oldestPayment['amount'])) {
             $oldScheduledAmount = $oldestPayment['amount'];
             $newScheduledAmount = $oldScheduledAmount + ($pledgeScheduledAmount - $actualAmount);
             //store new amount in oldest pending payment record.
             CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_Payment', $oldestPayment['id'], 'scheduled_amount', $newScheduledAmount);
         } elseif ($actualAmount > $pledgeScheduledAmount && $actualAmount - $pledgeScheduledAmount >= $oldestPayment['amount']) {
             // here the actual amount is greater than expected and also greater than the next installment amount, so update the next installment as complete and again add it to next subsequent pending payment
             // set the actual amount of the next pending to '0', set contribution Id to current contribution Id and status as completed
             $paymentId = array($oldestPayment['id']);
             self::updatePledgePayments($pledgeID, array_search('Completed', $allStatus), $paymentId, 0, $paymentContributionId);
             CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_Payment', $oldestPayment['id'], 'scheduled_amount', 0, 'id');
             $oldestPayment = self::getOldestPledgePayment($pledgeID);
             if (!$paymentContributionId) {
                 // means we are editing payment scheduled payment.
                 $oldestPaymentAmount = self::getOldestPledgePayment($pledgeID, 2);
             }
             $newActualAmount = $actualAmount - $pledgeScheduledAmount;
             $newPledgeScheduledAmount = $oldestPayment['amount'];
             if (!$paymentContributionId) {
                 $newActualAmount = $actualAmount - $pledgeScheduledAmount;
                 $newPledgeScheduledAmount = $oldestPaymentAmount['amount'];
                 // means we are editing payment scheduled payment, so update scheduled amount.
                 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_Payment', $oldestPaymentAmount['id'], 'scheduled_amount', $newActualAmount);
             }
             if ($newActualAmount > 0) {
                 self::adjustPledgePayment($pledgeID, $newActualAmount, $newPledgeScheduledAmount, $paymentContributionId);
             }
         }
     }
 }