/** * Delete a pledge * * @param array $params array included 'pledge_id' of pledge to delete * * @return boolean true if success, else false * @static void * {@getfields pledge_delete} * @example PledgeDelete.php * @access public */ function civicrm_api3_pledge_delete($params) { if (CRM_Pledge_BAO_Pledge::deletePledge($params['id'])) { return civicrm_api3_create_success(array('id' => $params['id']), $params, 'pledge', 'delete'); } else { return civicrm_api3_create_error('Could not delete pledge'); } }
/** * process the form after the input has been submitted and validated * * @access public * * @return void */ public function postProcess() { $deletedPledges = 0; foreach ($this->_pledgeIds as $pledgeId) { if (CRM_Pledge_BAO_Pledge::deletePledge($pledgeId)) { $deletedPledges++; } } $status = ts('Deleted Pledge(s): %1 (Total Selected: %2) ', array(1 => $deletedPledges, 2 => count($this->_pledgeIds))); CRM_Core_Session::setStatus($status, '', 'info'); }
/** * process the form after the input has been submitted and validated * * @access public * @return None */ public function postProcess() { $deletedPledges = 0; require_once 'CRM/Pledge/BAO/Pledge.php'; foreach ($this->_pledgeIds as $pledgeId) { if (CRM_Pledge_BAO_Pledge::deletePledge($pledgeId)) { $deletedPledges++; } } $status = array(ts('Deleted Pledge(s): %1', array(1 => $deletedPledges)), ts('Total Selected Pledge(s): %1', array(1 => count($this->_pledgeIds)))); CRM_Core_Session::setStatus($status); }
/** * Function to set variables up before form is built * * @return void * @access public */ public function preProcess() { $values = $ids = array(); $params = array('id' => $this->get('id')); CRM_Pledge_BAO_Pledge::getValues($params, $values, $ids); $values['frequencyUnit'] = ts('%1(s)', array(1 => $values['frequency_unit'])); if (isset($values["honor_contact_id"]) && $values["honor_contact_id"]) { $sql = "SELECT display_name FROM civicrm_contact WHERE id = " . $values["honor_contact_id"]; $dao = new CRM_Core_DAO(); $dao->query($sql); if ($dao->fetch()) { $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$values['honor_contact_id']}"); $values["honor_display"] = "<A href = {$url}>" . $dao->display_name . "</A>"; } $honor = CRM_Core_PseudoConstant::get('CRM_Pledge_DAO_Pledge', 'honor_type_id'); $values['honor_type'] = $honor[$values['honor_type_id']]; } //handle custom data. $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', $this, $params['id']); CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree); if (!empty($values['contribution_page_id'])) { $values['contribution_page'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $values['contribution_page_id'], 'title'); } $values['financial_type'] = CRM_Utils_Array::value($values['financial_type_id'], CRM_Contribute_PseudoConstant::financialType()); if ($values['status_id']) { $values['pledge_status'] = CRM_Utils_Array::value($values['status_id'], CRM_Contribute_PseudoConstant::contributionStatus()); } $url = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=view&reset=1&id={$values['id']}&cid={$values['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={$values['id']}&cid={$values['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={$values['id']}&cid={$values['contact_id']}&context=home"); } $displayName = CRM_Contact_BAO_Contact::displayName($values['contact_id']); $this->assign('displayName', $displayName); $title = $displayName . ' - (' . ts('Pledged') . ' ' . CRM_Utils_Money::format($values['pledge_amount']) . ' - ' . $values['financial_type'] . ')'; // add Pledge to Recent Items CRM_Utils_Recent::add($title, $url, $values['id'], 'Pledge', $values['contact_id'], NULL, $recentOther); // Check if this is default domain contact CRM-10482 if (CRM_Contact_BAO_Contact::checkDomainContact($values['contact_id'])) { $displayName .= ' (' . ts('default organization') . ')'; } // omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container CRM_Utils_System::setTitle(ts('View Pledge by') . ' ' . $displayName); //do check for campaigns if ($campaignId = CRM_Utils_Array::value('campaign_id', $values)) { $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId); $values['campaign'] = $campaigns[$campaignId]; } $this->assign($values); }
/** * Function to set variables up before form is built * * @return void * @access public */ public function preProcess() { require_once 'CRM/Pledge/BAO/Pledge.php'; $values = $ids = array(); $params = array('id' => $this->get('id')); CRM_Pledge_BAO_Pledge::getValues($params, $values, $ids); $values['frequencyUnit'] = ts('%1(s)', array(1 => $values['frequency_unit'])); if (isset($values["honor_contact_id"]) && $values["honor_contact_id"]) { $sql = "SELECT display_name FROM civicrm_contact WHERE id = " . $values["honor_contact_id"]; $dao = new CRM_Core_DAO(); $dao->query($sql); if ($dao->fetch()) { $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$values['honor_contact_id']}"); $values["honor_display"] = "<A href = {$url}>" . $dao->display_name . "</A>"; } $honor = CRM_Core_PseudoConstant::honor(); $values['honor_type'] = $honor[$values['honor_type_id']]; } //handle custom data. $groupTree =& CRM_Core_BAO_CustomGroup::getTree('Pledge', $this, $params['id']); CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree); if (CRM_Utils_Array::value('contribution_page_id', $values)) { $values['contribution_page'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $values['contribution_page_id'], 'title'); } $values['contribution_type'] = CRM_Utils_Array::value($values['contribution_type_id'], CRM_Contribute_PseudoConstant::contributionType()); if ($values['status_id']) { $values['pledge_status'] = CRM_Utils_Array::value($values['status_id'], CRM_Contribute_PseudoConstant::contributionStatus()); } require_once 'CRM/Utils/Recent.php'; require_once 'CRM/Contact/BAO/Contact.php'; $url = CRM_Utils_System::url('civicrm/contact/view/pledge', "action=view&reset=1&id={$values['id']}&cid={$values['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={$values['id']}&cid={$values['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={$values['id']}&cid={$values['contact_id']}&context=home"); } require_once 'CRM/Utils/Money.php'; $displayName = CRM_Contact_BAO_Contact::displayName($values['contact_id']); $this->assign('displayName', $displayName); $title = $displayName . ' - (' . ts('Pledged') . ' ' . CRM_Utils_Money::format($values['pledge_amount']) . ' - ' . $values['contribution_type'] . ')'; // add Pledge to Recent Items CRM_Utils_Recent::add($title, $url, $values['id'], 'Pledge', $values['contact_id'], null, $recentOther); $this->assign($values); }
/** * Process the form after the input has been submitted and validated. * * * @return void */ public function postProcess() { $deleted = $failed = 0; foreach ($this->_pledgeIds as $pledgeId) { if (CRM_Pledge_BAO_Pledge::deletePledge($pledgeId)) { $deleted++; } else { $failed++; } } if ($deleted) { $msg = ts('%count pledge deleted.', array('plural' => '%count pledges deleted.', 'count' => $deleted)); CRM_Core_Session::setStatus($msg, ts('Removed'), 'success'); } if ($failed) { CRM_Core_Session::setStatus(ts('1 could not be deleted.', array('plural' => '%count could not be deleted.', 'count' => $failed)), ts('Error'), 'error'); } }
/** * Heart of the viewing process. The runner gets all the meta data for * the contact and calls the appropriate type of page to view. * * @return void * @access public * */ function preProcess() { CRM_Utils_System::setTitle(ts('CiviPledge')); $startToDate = array(); $yearToDate = array(); $monthToDate = array(); $previousToDate = array(); $prefixes = array('start', 'month', 'year', 'previous'); $status = array('Completed', 'Cancelled', 'Pending', 'In Progress', 'Overdue'); // cumulative (since inception) - prefix = 'start' $startDate = null; $startDateEnd = null; // current year - prefix = 'year' $config =& CRM_Core_Config::singleton(); $yearDate = $config->fiscalYearStart; $year = array('Y' => date('Y')); $this->assign('curYear', $year['Y']); $yearDate = array_merge($year, $yearDate); $yearDate = CRM_Utils_Date::format($yearDate); $yearDate = $yearDate . '000000'; $yearDateEnd = $year['Y'] . '1231235959'; // current month - prefix = 'month' $currentMonth = date("F Y", mktime(0, 0, 0, date("m"), 01, date("Y"))); $this->assign('currentMonthYear', $currentMonth); $monthDate = date('Ym') . '01000000'; $monthDateEnd = CRM_Utils_Date::customFormat(date("Y-m-t", mktime(0, 0, 0, date("m"), 01, date("Y"))), '%Y%m%d') . '235959'; // previous month - prefix = 'previous' $previousDate = CRM_Utils_Date::customFormat(date("Y-m-d", mktime(0, 0, 0, date("m") - 1, 01, date("Y"))), '%Y%m%d') . '000000'; $previousDateEnd = CRM_Utils_Date::customFormat(date("Y-m-t", mktime(0, 0, 0, date("m") - 1, 01, date("Y"))), '%Y%m%d') . '235959'; $previousMonth = date("F Y", mktime(0, 0, 0, date("m") - 1, 01, date("Y"))); $this->assign('previousMonthYear', $previousMonth); require_once 'CRM/Pledge/BAO/Pledge.php'; foreach ($prefixes as $prefix) { $aName = $prefix . 'ToDate'; $startName = $prefix . 'Date'; $endName = $prefix . 'DateEnd'; foreach ($status as $s) { ${$aName}[str_replace(" ", "", $s)] = CRM_Pledge_BAO_Pledge::getTotalAmountAndCount($s, ${$startName}, ${$endName}); } $this->assign($aName, ${$aName}); } }
/** * This function is called when action is browse * * return null * @access public */ function listPledges() { $controller =& new CRM_Core_Controller_Simple('CRM_Pledge_Form_Search', ts('Pledges'), null); $controller->setEmbedded(true); $controller->reset(); $controller->set('limit', 12); $controller->set('cid', $this->_contactId); $controller->set('context', 'user'); $controller->set('force', 1); $controller->process(); $controller->run(); //add honor block. require_once 'CRM/Pledge/BAO/Pledge.php'; $honorParams = array(); $honorParams = CRM_Pledge_BAO_Pledge::getHonorContacts($this->_contactId); if (!empty($honorParams)) { // assign vars to templates $this->assign('pledgeHonorRows', $honorParams); $this->assign('pledgeHonor', true); } }
/** * called when action is browse. */ public function listPledges() { $controller = new CRM_Core_Controller_Simple('CRM_Pledge_Form_Search', ts('Pledges'), NULL, FALSE, FALSE, TRUE, FALSE); $controller->setEmbedded(TRUE); $controller->reset(); $controller->set('limit', 12); $controller->set('cid', $this->_contactId); $controller->set('context', 'user'); $controller->set('force', 1); $controller->process(); $controller->run(); // add honor block. $honorParams = array(); $honorParams = CRM_Pledge_BAO_Pledge::getHonorContacts($this->_contactId); if (!empty($honorParams)) { // assign vars to templates $this->assign('pledgeHonorRows', $honorParams); $this->assign('pledgeHonor', TRUE); } $session = CRM_Core_Session::singleton(); $loggedUserID = $session->get('userID'); $this->assign('loggedUserID', $loggedUserID); }
/** * Given the component name and returns the count of participation of contact. * * @param string $component * Input component name. * @param int $contactId * Input contact id. * @param string $tableName * Optional tableName if component is custom group. * * @return int * total number in database */ public static function getCountComponent($component, $contactId, $tableName = NULL) { $object = NULL; switch ($component) { case 'tag': return CRM_Core_BAO_EntityTag::getContactTags($contactId, TRUE); case 'rel': $result = CRM_Contact_BAO_Relationship::getRelationship($contactId, CRM_Contact_BAO_Relationship::CURRENT, 0, 1); return $result; case 'group': return CRM_Contact_BAO_GroupContact::getContactGroup($contactId, "Added", NULL, TRUE); case 'log': if (CRM_Core_BAO_Log::useLoggingReport()) { return FALSE; } return CRM_Core_BAO_Log::getContactLogCount($contactId); case 'note': return CRM_Core_BAO_Note::getContactNoteCount($contactId); case 'contribution': return CRM_Contribute_BAO_Contribution::contributionCount($contactId); case 'membership': return CRM_Member_BAO_Membership::getContactMembershipCount($contactId, TRUE); case 'participant': return CRM_Event_BAO_Participant::getContactParticipantCount($contactId); case 'pledge': return CRM_Pledge_BAO_Pledge::getContactPledgeCount($contactId); case 'case': return CRM_Case_BAO_Case::caseCount($contactId); case 'grant': return CRM_Grant_BAO_Grant::getContactGrantCount($contactId); case 'activity': $input = array('contact_id' => $contactId, 'admin' => FALSE, 'caseId' => NULL, 'context' => 'activity'); return CRM_Activity_BAO_Activity::getActivitiesCount($input); case 'mailing': $params = array('contact_id' => $contactId); return CRM_Mailing_BAO_Mailing::getContactMailingsCount($params); default: $custom = explode('_', $component); if ($custom['0'] = 'custom') { if (!$tableName) { $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $custom['1'], 'table_name'); } $queryString = "SELECT count(id) FROM {$tableName} WHERE entity_id = {$contactId}"; return CRM_Core_DAO::singleValueQuery($queryString); } } }
/** * @return array */ public static function &getFields() { $fields = CRM_Pledge_BAO_Pledge::exportableFields(); return $fields; }
/** * combine all the exportable fields from the lower levels object * * @return array array of exportable Fields * @access public * @static */ static function &exportableFields() { if (!self::$_exportableFields) { if (!self::$_exportableFields) { self::$_exportableFields = array(); } $fields = CRM_Pledge_DAO_Pledge::export(); $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment::export()); //set title to calculated fields $calculatedFields = array('pledge_total_paid' => array('title' => ts('Total Paid')), 'pledge_balance_amount' => array('title' => ts('Balance Amount')), 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')), 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')), 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')), 'pledge_payment_paid_date' => array('title' => ts('Paid Date')), 'pledge_payment_status' => array('title' => ts('Pledge Payment Status'), 'name' => 'pledge_payment_status', 'data_type' => CRM_Utils_Type::T_STRING)); $pledgeFields = array('pledge_status' => array('title' => 'Pledge Status', 'name' => 'pledge_status', 'data_type' => CRM_Utils_Type::T_STRING), 'pledge_frequency_unit' => array('title' => 'Pledge Frequency Unit', 'name' => 'pledge_frequency_unit', 'data_type' => CRM_Utils_Type::T_ENUM), 'pledge_frequency_interval' => array('title' => 'Pledge Frequency Interval', 'name' => 'pledge_frequency_interval', 'data_type' => CRM_Utils_Type::T_INT), 'pledge_contribution_page_id' => array('title' => 'Pledge Contribution Page Id', 'name' => 'pledge_contribution_page_id', 'data_type' => CRM_Utils_Type::T_INT)); $fields = array_merge($fields, $pledgeFields, $calculatedFields); // add custom data $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Pledge')); self::$_exportableFields = $fields; } return self::$_exportableFields; }
/** * Delete a pledge * * @param array $params array included 'pledge_id' of pledge to delete * * @return boolean true if success, else false * @static void * @access public */ function civicrm_pledge_delete(&$params) { if (!empty($params['id'])) { //handle field name or unique db name $params['pledge_id'] = $params['id']; } $pledgeID = CRM_Utils_Array::value('pledge_id', $params); if (!$pledgeID) { return civicrm_create_error('Could not find pledge_id in input parameters'); } require_once 'CRM/Pledge/BAO/Pledge.php'; if (CRM_Pledge_BAO_Pledge::deletePledge($pledgeID)) { return civicrm_create_success(); } else { return civicrm_create_error('Could not delete pledge'); } }
public function preProcessPledge() { //get the payment values associated with given pledge payment id OR check for payments due. $this->_pledgeValues = array(); if ($this->_ppID) { $payParams = array('id' => $this->_ppID); CRM_Pledge_BAO_PledgePayment::retrieve($payParams, $this->_pledgeValues['pledgePayment']); $this->_pledgeID = CRM_Utils_Array::value('pledge_id', $this->_pledgeValues['pledgePayment']); $paymentStatusID = CRM_Utils_Array::value('status_id', $this->_pledgeValues['pledgePayment']); $this->_id = CRM_Utils_Array::value('contribution_id', $this->_pledgeValues['pledgePayment']); //get all status $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); if (!($paymentStatusID == array_search('Pending', $allStatus) || $paymentStatusID == array_search('Overdue', $allStatus))) { CRM_Core_Error::fatal(ts("Pledge payment status should be 'Pending' or 'Overdue'.")); } //get the pledge values associated with given pledge payment. $ids = array(); $pledgeParams = array('id' => $this->_pledgeID); CRM_Pledge_BAO_Pledge::getValues($pledgeParams, $this->_pledgeValues, $ids); $this->assign('ppID', $this->_ppID); } else { // Not making a pledge payment, so if adding a new contribution we should check if pledge payment(s) are due for this contact so we can alert the user. CRM-5206 if (isset($this->_contactID)) { $contactPledges = CRM_Pledge_BAO_Pledge::getContactPledges($this->_contactID); if (!empty($contactPledges)) { $payments = $paymentsDue = NULL; $multipleDue = FALSE; foreach ($contactPledges as $key => $pledgeId) { $payments = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId); if ($payments) { if ($paymentsDue) { $multipleDue = TRUE; break; } else { $paymentsDue = $payments; } } } if ($multipleDue) { // Show link to pledge tab since more than one pledge has a payment due $pledgeTab = CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge"); CRM_Core_Session::setStatus(ts('This contact has pending or overdue pledge payments. <a href="%1">Click here to view their Pledges tab</a> and verify whether this contribution should be applied as a pledge payment.', array(1 => $pledgeTab)), ts('Notice'), 'alert'); } elseif ($paymentsDue) { // Show user link to oldest Pending or Overdue pledge payment $ppAmountDue = CRM_Utils_Money::format($payments['amount'], $payments['currency']); $ppSchedDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date')); if ($this->_mode) { $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live"); } else { $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge"); } CRM_Core_Session::setStatus(ts('This contact has a pending or overdue pledge payment of %2 which is scheduled for %3. <a href="%1">Click here to enter a pledge payment</a>.', array(1 => $ppUrl, 2 => $ppAmountDue, 3 => $ppSchedDate)), ts('Notice'), 'alert'); } } } } }
/** * Reset the various system caches and some important static variables. */ public static function flushCache() { // flush out all cache entries so we can reload new data // a bit aggressive, but livable for now $cache = CRM_Utils_Cache::singleton(); $cache->flush(); // also reset the various static memory caches // reset the memory or array cache CRM_Core_BAO_Cache::deleteGroup('contact fields', NULL, FALSE); // reset ACL cache CRM_ACL_BAO_Cache::resetCache(); // reset various static arrays used here CRM_Contact_BAO_Contact::$_importableFields = CRM_Contact_BAO_Contact::$_exportableFields = CRM_Contribute_BAO_Contribution::$_importableFields = CRM_Contribute_BAO_Contribution::$_exportableFields = CRM_Pledge_BAO_Pledge::$_exportableFields = CRM_Contribute_BAO_Query::$_contributionFields = CRM_Core_BAO_CustomField::$_importFields = CRM_Core_BAO_Cache::$_cache = CRM_Core_DAO::$_dbColumnValueCache = NULL; CRM_Core_OptionGroup::flushAll(); CRM_Utils_PseudoConstant::flushAll(); }
/** * Build the mapping form. * * @param CRM_Core_Form $form * @param string $mappingType * (Export/Import/Search Builder). * @param int $mappingId * @param int $columnNo * @param int $blockCount * (no of blocks shown). * @param NULL $exportMode * * @return void */ public static function buildMappingForm(&$form, $mappingType = 'Export', $mappingId = NULL, $columnNo, $blockCount = 3, $exportMode = NULL) { if ($mappingType == 'Export') { $name = "Map"; $columnCount = array('1' => $columnNo); } elseif ($mappingType == 'Search Builder') { $name = "Builder"; $columnCount = $columnNo; } //get the saved mapping details if ($mappingType == 'Export') { $form->applyFilter('saveMappingName', 'trim'); //to save the current mappings if (!isset($mappingId)) { $saveDetailsName = ts('Save this field mapping'); $form->add('text', 'saveMappingName', ts('Name')); $form->add('text', 'saveMappingDesc', ts('Description')); } else { $form->assign('loadedMapping', $mappingId); $params = array('id' => $mappingId); $temp = array(); $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp); $form->assign('savedName', $mappingDetails->name); $form->add('hidden', 'mappingId', $mappingId); $form->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL); $saveDetailsName = ts('Save as a new field mapping'); $form->add('text', 'saveMappingName', ts('Name')); $form->add('text', 'saveMappingDesc', ts('Description')); } $form->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)")); $form->addFormRule(array('CRM_Export_Form_Map', 'formRule'), $form->get('mappingTypeId')); } elseif ($mappingType == 'Search Builder') { $form->addElement('submit', 'addBlock', ts('Also include contacts where'), array('class' => 'submit-link')); } $defaults = array(); $hasLocationTypes = array(); $hasRelationTypes = array(); $fields = array(); if ($mappingType == 'Export') { $required = TRUE; } elseif ($mappingType == 'Search Builder') { $required = FALSE; } $contactType = array('Individual', 'Household', 'Organization'); foreach ($contactType as $value) { $contactFields = CRM_Contact_BAO_Contact::exportableFields($value, FALSE, $required); $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook::singleton()->getFields()); // exclude the address options disabled in the Address Settings $fields[$value] = CRM_Core_BAO_Address::validateAddressOptions($contactFields); ksort($fields[$value]); if ($mappingType == 'Export') { $relationships = array(); $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $value); asort($relationshipTypes); foreach ($relationshipTypes as $key => $var) { list($type) = explode('_', $key); $relationships[$key]['title'] = $var; $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/'; $relationships[$key]['export'] = TRUE; $relationships[$key]['relationship_type_id'] = $type; $relationships[$key]['related'] = TRUE; $relationships[$key]['hasRelationType'] = 1; } if (!empty($relationships)) { $fields[$value] = array_merge($fields[$value], array('related' => array('title' => ts('- related contact info -'))), $relationships); } } } //get the current employer for mapping. if ($required) { $fields['Individual']['current_employer']['title'] = ts('Current Employer'); } // add component fields $compArray = array(); //we need to unset groups, tags, notes for component export if ($exportMode != CRM_Export_Form_Select::CONTACT_EXPORT) { foreach (array('groups', 'tags', 'notes') as $value) { unset($fields['Individual'][$value]); unset($fields['Household'][$value]); unset($fields['Organization'][$value]); } } if ($mappingType == 'Search Builder') { //build the common contact fields array. $fields['Contact'] = array(); foreach ($fields['Individual'] as $key => $value) { if (!empty($fields['Household'][$key]) && !empty($fields['Organization'][$key])) { $fields['Contact'][$key] = $value; unset($fields['Organization'][$key], $fields['Household'][$key], $fields['Individual'][$key]); } } if (array_key_exists('note', $fields['Contact'])) { $noteTitle = $fields['Contact']['note']['title']; $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject'); $fields['Contact']['note_body'] = array('title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body'); $fields['Contact']['note_subject'] = array('title' => $noteTitle . ': ' . ts('Subject Only'), 'name' => 'note_subject'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) { if (CRM_Core_Permission::access('CiviContribute')) { $fields['Contribution'] = CRM_Contribute_BAO_Contribution::exportableFields(); foreach (array('contribution_contact_id', 'contribution_soft_credit_name', 'contribution_soft_credit_amount', 'contribution_soft_credit_type', 'contribution_soft_credit_contribution_id') as $element) { unset($fields['Contribution'][$element]); } $compArray['Contribution'] = ts('Contribution'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { if (CRM_Core_Permission::access('CiviEvent')) { $fields['Participant'] = CRM_Event_BAO_Participant::exportableFields(); //get the component payment fields if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { $componentPaymentFields = array(); foreach (CRM_Export_BAO_Export::componentPaymentFields() as $payField => $payTitle) { $componentPaymentFields[$payField] = array('title' => $payTitle); } $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields); } $compArray['Participant'] = ts('Participant'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) { if (CRM_Core_Permission::access('CiviMember')) { $fields['Membership'] = CRM_Member_BAO_Membership::getMembershipFields($exportMode); unset($fields['Membership']['membership_contact_id']); $compArray['Membership'] = ts('Membership'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) { if (CRM_Core_Permission::access('CiviPledge')) { $fields['Pledge'] = CRM_Pledge_BAO_Pledge::exportableFields(); unset($fields['Pledge']['pledge_contact_id']); $compArray['Pledge'] = ts('Pledge'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::CASE_EXPORT) { if (CRM_Core_Permission::access('CiviCase')) { $fields['Case'] = CRM_Case_BAO_Case::exportableFields(); $compArray['Case'] = ts('Case'); $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Case'); $compArray['Activity'] = ts('Case Activity'); unset($fields['Case']['case_contact_id']); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::GRANT_EXPORT) { if (CRM_Core_Permission::access('CiviGrant')) { $fields['Grant'] = CRM_Grant_BAO_Grant::exportableFields(); unset($fields['Grant']['grant_contact_id']); if ($mappingType == 'Search Builder') { unset($fields['Grant']['grant_type_id']); } $compArray['Grant'] = ts('Grant'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) { $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Activity'); $compArray['Activity'] = ts('Activity'); } //Contact Sub Type For export $contactSubTypes = array(); $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo(); foreach ($subTypes as $subType => $val) { //adding subtype specific relationships CRM-5256 $csRelationships = array(); if ($mappingType == 'Export') { $subTypeRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'], FALSE, 'label', TRUE, $subType); foreach ($subTypeRelationshipTypes as $key => $var) { if (!array_key_exists($key, $fields[$val['parent']])) { list($type) = explode('_', $key); $csRelationships[$key]['title'] = $var; $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/'; $csRelationships[$key]['export'] = TRUE; $csRelationships[$key]['relationship_type_id'] = $type; $csRelationships[$key]['related'] = TRUE; $csRelationships[$key]['hasRelationType'] = 1; } } } $fields[$subType] = $fields[$val['parent']] + $csRelationships; //custom fields for sub type $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($subType); $fields[$subType] += $subTypeFields; if (!empty($subTypeFields) || !empty($csRelationships)) { $contactSubTypes[$subType] = $val['label']; } } unset($subTypes); foreach ($fields as $key => $value) { foreach ($value as $key1 => $value1) { //CRM-2676, replacing the conflict for same custom field name from different custom group. $customGroupName = self::getCustomGroupName($key1); if ($customGroupName) { $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title']; } else { $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title']; } if (isset($value1['hasLocationType'])) { $hasLocationTypes[$key][$key1] = $value1['hasLocationType']; } if (isset($value1['hasRelationType'])) { $hasRelationTypes[$key][$key1] = $value1['hasRelationType']; unset($relatedMapperFields[$key][$key1]); } } if (array_key_exists('related', $relatedMapperFields[$key])) { unset($relatedMapperFields[$key]['related']); } } $mapperKeys = array_keys($mapperFields); $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); // FIXME: dirty hack to make the default option show up first. This // avoids a mozilla browser bug with defaults on dynamically constructed // selector widgets. if ($defaultLocationType) { $defaultLocation = $locationTypes[$defaultLocationType->id]; unset($locationTypes[$defaultLocationType->id]); $locationTypes = array($defaultLocationType->id => $defaultLocation) + $locationTypes; } $locationTypes = array(' ' => ts('Primary')) + $locationTypes; // since we need a hierarchical list to display contact types & subtypes, // this is what we going to display in first selector $contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE); if ($mappingType == 'Search Builder') { $contactTypes = array('Contact' => ts('Contacts')) + $contactTypes; } $sel1 = array('' => ts('- select record type -')) + $contactTypes + $compArray; foreach ($sel1 as $key => $sel) { if ($key) { // sort everything BUT the contactType which is sorted seperately by // an initial commit of CRM-13278 (check ksort above) if (!in_array($key, $contactType)) { asort($mapperFields[$key]); } $sel2[$key] = array('' => ts('- select field -')) + $mapperFields[$key]; } } $sel3[''] = NULL; $sel5[''] = NULL; $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); asort($phoneTypes); foreach ($sel1 as $k => $sel) { if ($k) { foreach ($locationTypes as $key => $value) { if (trim($key) != '') { $sel4[$k]['phone'][$key] =& $phoneTypes; $sel4[$k]['im'][$key] =& $imProviders; } } } } foreach ($sel1 as $k => $sel) { if ($k) { foreach ($mapperFields[$k] as $key => $value) { if (isset($hasLocationTypes[$k][$key])) { $sel3[$k][$key] = $locationTypes; } else { $sel3[$key] = NULL; } } } } // Array for core fields and relationship custom data $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE); if ($mappingType == 'Export') { foreach ($sel1 as $k => $sel) { if ($k) { foreach ($mapperFields[$k] as $field => $dontCare) { if (isset($hasRelationTypes[$k][$field])) { list($id, $first, $second) = explode('_', $field); // FIX ME: For now let's not expose custom data related to relationship $relationshipCustomFields = array(); //$relationshipCustomFields = self::getRelationTypeCustomGroupData( $id ); //asort($relationshipCustomFields); $relationshipType = new CRM_Contact_BAO_RelationshipType(); $relationshipType->id = $id; if ($relationshipType->find(TRUE)) { $direction = "contact_sub_type_{$second}"; if (isset($relationshipType->{$direction})) { $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->{$direction}], (array) $relationshipCustomFields); } else { $target_type = 'contact_type_' . $second; $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->{$target_type}], (array) $relationshipCustomFields); } } $relationshipType->free(); asort($relatedFields); $sel5[$k][$field] = $relatedFields; } } } } //Location Type for relationship fields foreach ($sel5 as $k => $v) { if ($v) { foreach ($v as $rel => $fields) { foreach ($fields as $field => $fieldLabel) { if (isset($hasLocationTypes[$k][$field])) { $sel6[$k][$rel][$field] = $locationTypes; } } } } } //PhoneTypes for relationship fields $sel7[''] = NULL; foreach ($sel6 as $k => $rel) { if ($k) { foreach ($rel as $phonekey => $phonevalue) { foreach ($locationTypes as $locType => $loc) { if (trim($locType) != '') { $sel7[$k][$phonekey]['phone'][$locType] =& $phoneTypes; $sel7[$k][$phonekey]['im'][$locType] =& $imProviders; } } } } } } //special fields that have location, hack for primary location $specialFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im'); if (isset($mappingId)) { $colCnt = 0; list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider, $mappingRelation, $mappingOperator, $mappingValue) = CRM_Core_BAO_Mapping::getMappingFields($mappingId); $blkCnt = count($mappingName); if ($blkCnt >= $blockCount) { $blockCount = $blkCnt + 1; } for ($x = 1; $x < $blockCount; $x++) { if (isset($mappingName[$x])) { $colCnt = count($mappingName[$x]); if ($colCnt >= $columnCount[$x]) { $columnCount[$x] = $colCnt; } } } } $form->_blockCount = $blockCount; $form->_columnCount = $columnCount; $form->set('blockCount', $form->_blockCount); $form->set('columnCount', $form->_columnCount); $defaults = $noneArray = $nullArray = array(); //used to warn for mismatch column count or mismatch mapping $warning = 0; for ($x = 1; $x < $blockCount; $x++) { for ($i = 0; $i < $columnCount[$x]; $i++) { $sel =& $form->addElement('hierselect', "mapper[{$x}][{$i}]", ts('Mapper for Field %1', array(1 => $i)), NULL); $jsSet = FALSE; if (isset($mappingId)) { $locationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0; if (isset($mappingName[$x][$i])) { if (is_array($mapperFields[$mappingContactType[$x][$i]])) { if (isset($mappingRelation[$x][$i])) { $contactDetails = strtolower(str_replace(" ", "_", $mappingName[$x][$i])); $relLocationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0; if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) { $relLocationId = " "; } $relPhoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL; $defaults["mapper[{$x}][{$i}]"] = array($mappingContactType[$x][$i], $mappingRelation[$x][$i], $locationId, $phoneType, $mappingName[$x][$i], $relLocationId, $relPhoneType); if (!$locationId) { $noneArray[] = array($x, $i, 2); } if (!$phoneType && !$imProvider) { $noneArray[] = array($x, $i, 3); } if (!$mappingName[$x][$i]) { $noneArray[] = array($x, $i, 4); } if (!$relLocationId) { $noneArray[] = array($x, $i, 5); } if (!$relPhoneType) { $noneArray[] = array($x, $i, 6); } $noneArray[] = array($x, $i, 2); } else { $phoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL; $imProvider = isset($mappingImProvider[$x][$i]) ? $mappingImProvider[$x][$i] : NULL; if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) { $locationId = " "; } $defaults["mapper[{$x}][{$i}]"] = array($mappingContactType[$x][$i], $mappingName[$x][$i], $locationId, $phoneType); if (!$mappingName[$x][$i]) { $noneArray[] = array($x, $i, 1); } if (!$locationId) { $noneArray[] = array($x, $i, 2); } if (!$phoneType && !$imProvider) { $noneArray[] = array($x, $i, 3); } $noneArray[] = array($x, $i, 4); $noneArray[] = array($x, $i, 5); $noneArray[] = array($x, $i, 6); } $jsSet = TRUE; if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingOperator))) { $defaults["operator[{$x}][{$i}]"] = CRM_Utils_Array::value($i, $mappingOperator[$x]); } if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingValue))) { $defaults["value[{$x}][{$i}]"] = CRM_Utils_Array::value($i, $mappingValue[$x]); } } } } //Fix for Search Builder if ($mappingType == 'Export') { $j = 7; } else { $j = 4; } $formValues = $form->exportValues(); if (!$jsSet) { if (empty($formValues)) { // Incremented length for third select box(relationship type) for ($k = 1; $k < $j; $k++) { $noneArray[] = array($x, $i, $k); } } else { if (!empty($formValues['mapper'][$x])) { foreach ($formValues['mapper'][$x] as $value) { for ($k = 1; $k < $j; $k++) { if (!isset($formValues['mapper'][$x][$i][$k]) || !$formValues['mapper'][$x][$i][$k]) { $noneArray[] = array($x, $i, $k); } else { $nullArray[] = array($x, $i, $k); } } } } else { for ($k = 1; $k < $j; $k++) { $noneArray[] = array($x, $i, $k); } } } } //Fix for Search Builder if ($mappingType == 'Export') { if (!isset($mappingId) || $i >= count(reset($mappingName))) { if (isset($formValues['mapper']) && isset($formValues['mapper'][$x][$i][1]) && array_key_exists($formValues['mapper'][$x][$i][1], $relationshipTypes)) { $sel->setOptions(array($sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4)); } else { $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7)); } } else { $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7)); } } else { $sel->setOptions(array($sel1, $sel2, $sel3, $sel4)); } if ($mappingType == 'Search Builder') { //CRM -2292, restricted array set $operatorArray = array('' => ts('-operator-')) + CRM_Core_SelectValues::getSearchBuilderOperators(); $form->add('select', "operator[{$x}][{$i}]", '', $operatorArray); $form->add('text', "value[{$x}][{$i}]", ''); } } //end of columnCnt for if ($mappingType == 'Search Builder') { $title = ts('Another search field'); } else { $title = ts('Select more fields'); } $form->addElement('submit', "addMore[{$x}]", $title, array('class' => 'submit-link')); } //end of block for $js = "<script type='text/javascript'>\n"; $formName = "document.{$name}"; if (!empty($nullArray)) { $js .= "var nullArray = ["; $elements = array(); $seen = array(); foreach ($nullArray as $element) { $key = "{$element[0]}, {$element[1]}, {$element[2]}"; if (!isset($seen[$key])) { $elements[] = "[{$key}]"; $seen[$key] = 1; } } $js .= implode(', ', $elements); $js .= "]"; $js .= "\n for (var i=0;i<nullArray.length;i++) {\n if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {\n {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';\n }\n }\n"; } if (!empty($noneArray)) { $js .= "var noneArray = ["; $elements = array(); $seen = array(); foreach ($noneArray as $element) { $key = "{$element[0]}, {$element[1]}, {$element[2]}"; if (!isset($seen[$key])) { $elements[] = "[{$key}]"; $seen[$key] = 1; } } $js .= implode(', ', $elements); $js .= "]"; $js .= "\n for (var i=0;i<noneArray.length;i++) {\n if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {\n {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';\n }\n }\n"; } $js .= "</script>\n"; $form->assign('initHideBoxes', $js); $form->assign('columnCount', $columnCount); $form->assign('blockCount', $blockCount); $form->setDefaults($defaults); $form->setDefaultAction('refresh'); }
/** * Process the contribution * * @param $form * @param $params * @param $result * @param $contactID * @param $contributionType * @param bool $deductibleMode * @param bool $pending * @param bool $online * * @return CRM_Contribute_DAO_Contribution * @access public */ static function processContribution(&$form, $params, $result, $contactID, $contributionType, $deductibleMode = TRUE, $pending = FALSE, $online = TRUE) { $transaction = new CRM_Core_Transaction(); $className = get_class($form); $recurringContributionID = NULL; // add these values for the recurringContrib function ,CRM-10188 $params['financial_type_id'] = $contributionType->id; //@todo - this is being set from the form to resolve CRM-10188 - an // eNotice caused by it not being set @ the front end // however, we then get it being over-written with null for backend contributions // a better fix would be to set the values in the respective forms rather than require // a function being shared by two forms to deal with their respective values // moving it to the BAO & not taking the $form as a param would make sense here. if (!isset($params['is_email_receipt'])) { $params['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $form->_values); } $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $contributionType, $online); $config = CRM_Core_Config::singleton(); // CRM-11885 // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it. if (isset($params['non_deductible_amount']) && !empty($params['non_deductible_amount'])) { $nonDeductibleAmount = $params['non_deductible_amount']; } else { //if ($contributionType->is_deductible && $deductibleMode) { if ($contributionType->is_deductible) { if ($online && isset($params['selectProduct'])) { $selectProduct = CRM_Utils_Array::value('selectProduct', $params); } if (!$online && isset($params['product_name'][0])) { $selectProduct = $params['product_name'][0]; } // if there is a product - compare the value to the contribution amount if (isset($selectProduct) && $selectProduct != 'no_thanks') { $productDAO = new CRM_Contribute_DAO_Product(); $productDAO->id = $selectProduct; $productDAO->find(TRUE); // product value exceeds contribution amount if ($params['amount'] < $productDAO->price) { $nonDeductibleAmount = $params['amount']; } else { $nonDeductibleAmount = $productDAO->price; } } else { $nonDeductibleAmount = '0.00'; } } else { $nonDeductibleAmount = $params['amount']; } } $now = date('YmdHis'); $receiptDate = CRM_Utils_Array::value('receipt_date', $params); if (!empty($form->_values['is_email_receipt'])) { $receiptDate = $now; } //get the contrib page id. $campaignId = $contributionPageId = NULL; if ($online) { $contributionPageId = $form->_id; $campaignId = CRM_Utils_Array::value('campaign_id', $params); if (!array_key_exists('campaign_id', $params)) { $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values); } } else { //also for offline we do support - CRM-7290 $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params); $campaignId = CRM_Utils_Array::value('campaign_id', $params); } // first create the contribution record $contribParams = array('contact_id' => $contactID, 'financial_type_id' => $contributionType->id, 'contribution_page_id' => $contributionPageId, 'receive_date' => CRM_Utils_Array::value('receive_date', $params) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'), '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 || !empty($params['source']) ? 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, 'campaign_id' => $campaignId); if (!$online && isset($params['thankyou_date'])) { $contribParams['thankyou_date'] = $params['thankyou_date']; } if (!$online || $form->_values['is_monetary']) { if (empty($params['is_pay_later'])) { $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' => CRM_Utils_Array::value('trxn_result_code', $result), 'payment_processor' => CRM_Utils_Array::value('payment_processor', $result)); } if ($recurringContributionID) { $contribParams['contribution_recur_id'] = $recurringContributionID; } $contribParams['contribution_status_id'] = $pending ? 2 : 1; $contribParams['is_test'] = 0; 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; } } //create an contribution address if ($form->_contributeMode != 'notify' && empty($params['is_pay_later']) && !empty($form->_values['is_monetary'])) { $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 $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' ')); $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' ')); // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin. if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) { // if its due to pcp if (!empty($params['pcp_made_through_id'])) { $contribSoftContactId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $params['pcp_made_through_id'], 'contact_id'); } else { $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params); } // Pass these details onto with the contribution to make them // available at hook_post_process, CRM-8908 $contribParams['soft_credit_to'] = $params['soft_credit_to'] = $contribSoftContactId; } if (isset($params['amount'])) { $contribParams['line_item'] = $form->_lineItem; //add contribution record $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids); if (is_a($contribution, 'CRM_Core_Error')) { $message = CRM_Core_Error::getMessages($contribution); CRM_Core_Error::fatal($message); } // lets store it in the form variable so postProcess hook can get to this and use it $form->_contributionID = $contribution->id; } //CRM-13981, processing honor contact into soft-credit contribution CRM_Contact_Form_ProfileContact::postProcess($form); // process soft credit / pcp pages CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution); //handle pledge stuff. if (empty($form->_params['separate_membership_payment']) && !empty($form->_values['pledge_block_id']) && (!empty($form->_params['is_pledge']) || !empty($form->_values['pledge_id']))) { if (!empty($form->_values['pledge_id'])) { //when user doing pledge payments. //update the schedule when payment(s) are made foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) { $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id'); $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $scheduledAmount); CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams); } //update pledge status according to the new payment statuses CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']); } else { //when user creating pledge record. $pledgeParams = array(); $pledgeParams['contact_id'] = $contribution->contact_id; $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount; $pledgeParams['contribution_id'] = $contribution->id; $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id; $pledgeParams['financial_type_id'] = $contribution->financial_type_id; $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval']; $pledgeParams['installments'] = $params['pledge_installments']; $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit']; if ($pledgeParams['frequency_unit'] == 'month') { $pledgeParams['frequency_day'] = intval(date("d")); } else { $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'); $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount']; //inherit campaign from contirb page. $pledgeParams['campaign_id'] = $campaignId; $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; CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams); } } } if ($online && $contribution) { CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_contribution', $contribution->id, 'Contribution'); } elseif ($contribution) { //handle custom data. $params['contribution_id'] = $contribution->id; if (!empty($params['custom']) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) { CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id); } } // Save note if ($contribution && !empty($params['contribution_note'])) { $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['contribution_note'], 'entity_id' => $contribution->id, 'contact_id' => $contribution->contact_id, 'modified_date' => date('Ymd')); CRM_Core_BAO_Note::add($noteParams, array()); } if (isset($params['related_contact'])) { $contactID = $params['related_contact']; } elseif (isset($params['cms_contactID'])) { $contactID = $params['cms_contactID']; } //create contribution activity w/ individual and target //activity w/ organisation contact id when onbelf, CRM-4027 $targetContactID = NULL; if (!empty($params['hidden_onbehalf_profile'])) { $targetContactID = $contribution->contact_id; $contribution->contact_id = $contactID; } // create an activity record if ($contribution) { CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID); } $transaction->commit(); // CRM-13074 - create the CMSUser after the transaction is completed as it // is not appropriate to delete a valid contribution if a user create problem occurs CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $form->_bltID); return $contribution; }
/** * Test that payment retrieve wrks based on known pledge id */ function testRetrieveKnownPledgeID() { $params = array('contact_id' => $this->_contactId, 'frequency_unit' => 'month', 'frequency_interval' => 1, 'frequency_day' => 1, 'original_installment_amount' => 25.0, 'installments' => 12, 'financial_type_id' => 1, 'create_date' => '20100513000000', 'acknowledge_date' => '20100513000000', 'start_date' => '20100513000000', 'status_id' => 2, 'currency' => 'USD', 'amount' => 300); $pledge = CRM_Pledge_BAO_Pledge::add($params); $defaults = array(); $pledgeParams = array('pledge_id' => $pledge->id); $pledgeId = CRM_Pledge_BAO_Pledge::retrieve($pledgeParams, $defaults); $this->assertEquals(count($pledgeId), 1, "Pledge was retrieved"); }
/** * combine all the exportable fields from the lower levels object * * @return array array of exportable Fields * @access public */ function &exportableFields() { if (!self::$_exportableFields) { if (!self::$_exportableFields) { self::$_exportableFields = array(); } require_once 'CRM/Pledge/DAO/Pledge.php'; $fields = CRM_Pledge_DAO_Pledge::export(); require_once 'CRM/Pledge/DAO/Payment.php'; $fields = array_merge($fields, CRM_Pledge_DAO_Payment::export()); //set title to calculated fields $calculatedFields = array('pledge_total_paid' => array('title' => ts('Total Paid')), 'pledge_balance_amount' => array('title' => ts('Balance Amount')), 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')), 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')), 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')), 'pledge_payment_paid_date' => array('title' => ts('Paid Date'))); $fields = array_merge($fields, $calculatedFields); // add custom data $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Pledge')); self::$_exportableFields = $fields; } return self::$_exportableFields; }
/** * Pass Zero Id for a payment deletion for one pledge */ function testDeletePaymentsZeroId() { $payment = CRM_Core_DAO::createTestObject('CRM_Pledge_BAO_PledgePayment'); $paymentid = CRM_Pledge_BAO_PledgePayment::deletePayments(0); $result = CRM_Pledge_BAO_Pledge::deletePledge($payment->pledge_id); }
/** * Build Pledge Block in Contribution Pages. * * @param CRM_Core_Form $form */ public static function buildPledgeBlock($form) { //build pledge payment fields. if (!empty($form->_values['pledge_id'])) { //get all payments required details. $allPayments = array(); $returnProperties = array('status_id', 'scheduled_date', 'scheduled_amount', 'currency', 'pledge_start_date'); CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $form->_values['pledge_id'], $allPayments, $returnProperties); // get all status $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); $nextPayment = array(); $isNextPayment = FALSE; $overduePayments = array(); foreach ($allPayments as $payID => $value) { if ($allStatus[$value['status_id']] == 'Overdue') { $overduePayments[$payID] = array('id' => $payID, 'scheduled_amount' => CRM_Utils_Rule::cleanMoney($value['scheduled_amount']), 'scheduled_amount_currency' => $value['currency'], 'scheduled_date' => CRM_Utils_Date::customFormat($value['scheduled_date'], '%B %d')); } elseif (!$isNextPayment && $allStatus[$value['status_id']] == 'Pending') { // get the next payment. $nextPayment = array('id' => $payID, 'scheduled_amount' => CRM_Utils_Rule::cleanMoney($value['scheduled_amount']), 'scheduled_amount_currency' => $value['currency'], 'scheduled_date' => CRM_Utils_Date::customFormat($value['scheduled_date'], '%B %d')); $isNextPayment = TRUE; } } // build check box array for payments. $payments = array(); if (!empty($overduePayments)) { foreach ($overduePayments as $id => $payment) { $label = ts("%1 - due on %2 (overdue)", array(1 => CRM_Utils_Money::format(CRM_Utils_Array::value('scheduled_amount', $payment), CRM_Utils_Array::value('scheduled_amount_currency', $payment)), 2 => CRM_Utils_Array::value('scheduled_date', $payment))); $paymentID = CRM_Utils_Array::value('id', $payment); $payments[] = $form->createElement('checkbox', $paymentID, NULL, $label, array('amount' => CRM_Utils_Array::value('scheduled_amount', $payment))); } } if (!empty($nextPayment)) { $label = ts("%1 - due on %2", array(1 => CRM_Utils_Money::format(CRM_Utils_Array::value('scheduled_amount', $nextPayment), CRM_Utils_Array::value('scheduled_amount_currency', $nextPayment)), 2 => CRM_Utils_Array::value('scheduled_date', $nextPayment))); $paymentID = CRM_Utils_Array::value('id', $nextPayment); $payments[] = $form->createElement('checkbox', $paymentID, NULL, $label, array('amount' => CRM_Utils_Array::value('scheduled_amount', $nextPayment))); } // give error if empty or build form for payment. if (empty($payments)) { CRM_Core_Error::fatal(ts("Oops. It looks like there is no valid payment status for online payment.")); } else { $form->assign('is_pledge_payment', TRUE); $form->addGroup($payments, 'pledge_amount', ts('Make Pledge Payment(s):'), '<br />'); } } else { $pledgeBlock = self::getPledgeBlock($form->_id); // build form for pledge creation. $pledgeOptions = array('0' => ts('I want to make a one-time contribution'), '1' => ts('I pledge to contribute this amount every')); $form->addRadio('is_pledge', ts('Pledge Frequency Interval'), $pledgeOptions, NULL, array('<br/>')); $form->addElement('text', 'pledge_installments', ts('Installments'), array('size' => 3)); if (!empty($pledgeBlock['is_pledge_interval'])) { $form->assign('is_pledge_interval', CRM_Utils_Array::value('is_pledge_interval', $pledgeBlock)); $form->addElement('text', 'pledge_frequency_interval', NULL, array('size' => 3)); } else { $form->add('hidden', 'pledge_frequency_interval', 1); } // Frequency unit drop-down label suffixes switch from *ly to *(s) $freqUnitVals = explode(CRM_Core_DAO::VALUE_SEPARATOR, $pledgeBlock['pledge_frequency_unit']); $freqUnits = array(); $frequencyUnits = CRM_Core_OptionGroup::values('recur_frequency_units'); foreach ($freqUnitVals as $key => $val) { if (array_key_exists($val, $frequencyUnits)) { $freqUnits[$val] = !empty($pledgeBlock['is_pledge_interval']) ? "{$frequencyUnits[$val]}(s)" : $frequencyUnits[$val]; } } $form->addElement('select', 'pledge_frequency_unit', NULL, $freqUnits); // CRM-18854 if (CRM_Utils_Array::value('is_pledge_start_date_visible', $pledgeBlock)) { if (CRM_Utils_Array::value('pledge_start_date', $pledgeBlock)) { $defaults = array(); $date = (array) json_decode($pledgeBlock['pledge_start_date']); list($field, $value) = each($date); switch ($field) { case 'contribution_date': $form->addDate('start_date', ts('First installment payment')); $paymentDate = $value = date('d/m/Y'); list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($value); $form->assign('is_date', TRUE); break; case 'calendar_date': $form->addDate('start_date', ts('First installment payment')); list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($value); $form->assign('is_date', TRUE); $paymentDate = $value; break; case 'calendar_month': $month = CRM_Utils_Date::getCalendarDayOfMonth(); $form->add('select', 'start_date', ts('Day of month installments paid'), $month); $paymentDate = CRM_Pledge_BAO_Pledge::getPaymentDate($value); list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($paymentDate); break; default: break; } $form->setDefaults($defaults); $form->assign('start_date_display', $paymentDate); $form->assign('start_date_editable', FALSE); if (CRM_Utils_Array::value('is_pledge_start_date_editable', $pledgeBlock)) { $form->assign('start_date_editable', TRUE); if ($field == 'calendar_month') { $form->assign('is_date', FALSE); $form->setDefaults(array('start_date' => $value)); } } } } } }
/** * 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; }
/** * Build the form object. * * * @return void */ 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'] == $batchTypes['Contribution']) { CRM_Utils_System::setTitle(ts('Batch Data Entry for Contributions')); $customFields = CRM_Core_BAO_CustomField::getFields('Contribution'); } 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); // remove file type field and then limit fields $suppressFields = FALSE; $removehtmlTypes = array('File', 'Autocomplete-Select'); foreach ($this->_fields as $name => $field) { if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && in_array($this->_fields[$name]['html_type'], $removehtmlTypes)) { $suppressFields = TRUE; unset($this->_fields[$name]); } //fix to reduce size as we are using this field in grid if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) { //shrink class to "form-text-medium" $this->_fields[$name]['attributes']['size'] = 19; } } $this->addFormRule(array('CRM_Batch_Form_Entry', 'formRule'), $this); // add the force save button $forceSave = $this->getButtonName('upload', 'force'); $this->addElement('submit', $forceSave, ts('Ignore Mismatch & Process the Batch?')); $this->addButtons(array(array('type' => 'upload', 'name' => ts('Validate & Process the Batch'), 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Save & Continue Later')))); $this->assign('rowCount', $this->_batchInfo['item_count'] + 1); $fileFieldExists = FALSE; $preserveDefaultsArray = array('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 -'))); // special field specific to membership batch udpate if ($this->_batchInfo['type_id'] == 2) { $options = array(1 => ts('Add Membership'), 2 => ts('Renew Membership')); $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)) { $fld = explode('-', $field['name']); $contactReturnProperties[$field['name']] = $fld[0]; } CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber); if (in_array($field['name'], $preserveDefaultsArray)) { $this->_preserveDefault = FALSE; } } } $this->assign('fields', $this->_fields); CRM_Core_Resources::singleton()->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 Excluded'), 'info'); } }
/** * @param CRM_Core_Form $form */ public static function buildSearchForm(&$form) { // pledge related dates CRM_Core_Form_Date::buildDateRange($form, 'pledge_start_date', 1, '_low', '_high', ts('From'), FALSE); CRM_Core_Form_Date::buildDateRange($form, 'pledge_end_date', 1, '_low', '_high', ts('From'), FALSE); CRM_Core_Form_Date::buildDateRange($form, 'pledge_create_date', 1, '_low', '_high', ts('From'), FALSE); // pledge payment related dates CRM_Core_Form_Date::buildDateRange($form, 'pledge_payment_date', 1, '_low', '_high', ts('From'), FALSE); $form->addYesNo('pledge_test', ts('Pledge is a Test?'), TRUE); $form->add('text', 'pledge_amount_low', ts('From'), array('size' => 8, 'maxlength' => 8)); $form->addRule('pledge_amount_low', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('9.99', ' '))), 'money'); $form->add('text', 'pledge_amount_high', ts('To'), array('size' => 8, 'maxlength' => 8)); $form->addRule('pledge_amount_high', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money'); $form->add('select', 'pledge_status_id', ts('Pledge Status'), CRM_Pledge_BAO_Pledge::buildOptions('status_id'), FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple')); $form->addYesNo('pledge_acknowledge_date_is_not_null', ts('Acknowledgement sent?'), TRUE); $form->add('text', 'pledge_installments_low', ts('From'), array('size' => 8, 'maxlength' => 8)); $form->addRule('pledge_installments_low', ts('Please enter a number'), 'integer'); $form->add('text', 'pledge_installments_high', ts('To'), array('size' => 8, 'maxlength' => 8)); $form->addRule('pledge_installments_high', ts('Please enter number.'), 'integer'); $form->add('select', 'pledge_payment_status_id', ts('Pledge Payment Status'), CRM_Pledge_BAO_PledgePayment::buildOptions('status_id'), FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple')); $form->add('select', 'pledge_financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(), FALSE, array('class' => 'crm-select2')); $form->add('select', 'pledge_contribution_page_id', ts('Contribution Page'), array('' => ts('- any -')) + CRM_Contribute_PseudoConstant::contributionPage(), FALSE, array('class' => 'crm-select2')); // add fields for pledge frequency $form->add('text', 'pledge_frequency_interval', ts('Every'), array('size' => 8, 'maxlength' => 8)); $form->addRule('pledge_frequency_interval', ts('Please enter valid Pledge Frequency Interval'), 'integer'); $frequencies = CRM_Core_OptionGroup::values('recur_frequency_units'); foreach ($frequencies as $val => $label) { $freqUnitsDisplay["'{$val}'"] = ts('%1(s)', array(1 => $label)); } $form->add('select', 'pledge_frequency_unit', ts('Pledge Frequency'), array('' => ts('- any -')) + $freqUnitsDisplay); // add all the custom searchable fields $pledge = array('Pledge'); $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $pledge); if ($groupDetails) { $form->assign('pledgeGroupTree', $groupDetails); foreach ($groupDetails as $group) { foreach ($group['fields'] as $field) { $fieldId = $field['id']; $elementName = 'custom_' . $fieldId; CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, FALSE, TRUE); } } } CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'pledge_campaign_id'); $form->assign('validCiviPledge', TRUE); $form->setDefaults(array('pledge_test' => 0)); }
/** * the main function that is called when the page loads, it decides the which action has to be taken for the page. * * @return null */ public function run() { $this->preProcess(); // check if we can process credit card registration $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments()); self::setContext($this); if ($this->_action & CRM_Core_Action::VIEW) { $this->view(); } elseif ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::DELETE)) { $this->edit(); } elseif ($this->_action & CRM_Core_Action::DETACH) { CRM_Pledge_BAO_Pledge::cancel($this->_id); $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(); }
/** * Process the form submission. */ public function postProcess() { if ($this->_action & CRM_Core_Action::DELETE) { CRM_Pledge_BAO_Pledge::deletePledge($this->_id); return; } // get the submitted form values. $formValues = $this->controller->exportValues($this->_name); // set the contact, when contact is selected if (!empty($formValues['contact_id'])) { $this->_contactID = $formValues['contact_id']; } $session = CRM_Core_Session::singleton(); // get All Payments status types. $paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); $fields = array('frequency_unit', 'frequency_interval', 'frequency_day', 'installments', 'financial_type_id', 'initial_reminder_day', 'max_reminders', 'additional_reminder_day', 'contribution_page_id', 'campaign_id'); foreach ($fields as $f) { $params[$f] = CRM_Utils_Array::value($f, $formValues); } // defaults status is "Pending". // if update get status. if ($this->_id) { $params['pledge_status_id'] = $params['status_id'] = $this->_values['status_id']; } else { $params['pledge_status_id'] = $params['status_id'] = array_search('Pending', $paymentStatusTypes); } // format amount $params['amount'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('amount', $formValues)); $params['currency'] = CRM_Utils_Array::value('currency', $formValues); $params['original_installment_amount'] = $params['amount'] / $params['installments']; $dates = array('create_date', 'start_date', 'acknowledge_date', 'cancel_date'); foreach ($dates as $d) { if ($this->_id && !$this->_isPending && !empty($this->_values[$d])) { if ($d == 'start_date') { $params['scheduled_date'] = CRM_Utils_Date::processDate($this->_values[$d]); } $params[$d] = CRM_Utils_Date::processDate($this->_values[$d]); } elseif (!empty($formValues[$d]) && !CRM_Utils_System::isNull($formValues[$d])) { if ($d == 'start_date') { $params['scheduled_date'] = CRM_Utils_Date::processDate($formValues[$d]); } $params[$d] = CRM_Utils_Date::processDate($formValues[$d]); } else { $params[$d] = 'null'; } } if (!empty($formValues['is_acknowledge'])) { $params['acknowledge_date'] = date('Y-m-d'); } // assign id only in update mode if ($this->_action & CRM_Core_Action::UPDATE) { $params['id'] = $this->_id; } $params['contact_id'] = $this->_contactID; // format custom data if (!empty($formValues['hidden_custom'])) { $params['hidden_custom'] = 1; $customFields = CRM_Core_BAO_CustomField::getFields('Pledge'); $params['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $this->_id, 'Pledge'); } // handle pending pledge. $params['is_pledge_pending'] = $this->_isPending; // create pledge record. $pledge = CRM_Pledge_BAO_Pledge::create($params); $statusMsg = NULL; if ($pledge->id) { // set the status msg. if ($this->_action & CRM_Core_Action::ADD) { $statusMsg = ts('Pledge has been recorded and the payment schedule has been created.<br />'); } elseif ($this->_action & CRM_Core_Action::UPDATE) { $statusMsg = ts('Pledge has been updated.<br />'); } } // handle Acknowledgment. if (!empty($formValues['is_acknowledge']) && $pledge->id) { // calculate scheduled amount. $params['scheduled_amount'] = round($params['amount'] / $params['installments']); $params['total_pledge_amount'] = $params['amount']; // get some required pledge values in params. $params['id'] = $pledge->id; $params['acknowledge_date'] = $pledge->acknowledge_date; $params['is_test'] = $pledge->is_test; $params['currency'] = $pledge->currency; // retrieve 'from email id' for acknowledgement $params['from_email_id'] = $formValues['from_email_address']; $this->paymentId = NULL; // send Acknowledgment mail. CRM_Pledge_BAO_Pledge::sendAcknowledgment($this, $params); if (!isset($this->userEmail)) { list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID); } $statusMsg .= ' ' . ts("An acknowledgment email has been sent to %1.<br />", array(1 => $this->userEmail)); // build the payment urls. if ($this->paymentId) { $urlParams = "reset=1&action=add&cid={$this->_contactID}&ppid={$this->paymentId}&context=pledge"; $contribURL = CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams); $urlParams .= "&mode=live"; $creditURL = CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams); // check if we can process credit card payment. $processors = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, "billing_mode IN ( 1, 3 )"); if (count($processors) > 0) { $statusMsg .= ' ' . ts("If a payment is due now, you can record <a href='%1'>a check, EFT, or cash payment for this pledge</a> OR <a href='%2'>submit a credit card payment</a>.", array(1 => $contribURL, 2 => $creditURL)); } else { $statusMsg .= ' ' . ts("If a payment is due now, you can record <a href='%1'>a check, EFT, or cash payment for this pledge</a>.", array(1 => $contribURL)); } } } CRM_Core_Session::setStatus($statusMsg, ts('Payment Due'), 'info'); $buttonName = $this->controller->getButtonName(); if ($this->_context == 'standalone') { if ($buttonName == $this->getButtonName('upload', 'new')) { $session->replaceUserContext(CRM_Utils_System::url('civicrm/pledge/add', 'reset=1&action=add&context=standalone')); } else { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=pledge")); } } elseif ($buttonName == $this->getButtonName('upload', 'new')) { $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/pledge', "reset=1&action=add&context=pledge&cid={$this->_contactID}")); } }
/** * Process the contribution. * * @param CRM_Core_Form $form * @param array $params * @param array $result * @param array $contributionParams * Parameters to be passed to contribution create action. * This differs from params in that we are currently adding params to it and 1) ensuring they are being * passed consistently & 2) documenting them here. * - contact_id * - line_item * - is_test * - campaign_id * - contribution_page_id * - source * - payment_type_id * - thankyou_date (not all forms will set this) * * @param CRM_Financial_DAO_FinancialType $financialType * @param bool $online * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form. * * @param int $billingLocationID * ID of billing location type. * @param bool $isRecur * Is this recurring? * * @return \CRM_Contribute_DAO_Contribution * @throws \Exception */ public static function processFormContribution(&$form, $params, $result, $contributionParams, $financialType, $online, $billingLocationID, $isRecur) { $transaction = new CRM_Core_Transaction(); $contactID = $contributionParams['contact_id']; $isEmailReceipt = !empty($form->_values['is_email_receipt']); $isSeparateMembershipPayment = empty($params['separate_membership_payment']) ? FALSE : TRUE; $pledgeID = !empty($params['pledge_id']) ? $params['pledge_id'] : CRM_Utils_Array::value('pledge_id', $form->_values); if (!$isSeparateMembershipPayment && !empty($form->_values['pledge_block_id']) && (!empty($params['is_pledge']) || $pledgeID)) { $isPledge = TRUE; } else { $isPledge = FALSE; } // add these values for the recurringContrib function ,CRM-10188 $params['financial_type_id'] = $financialType->id; $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $billingLocationID); //@todo - this is being set from the form to resolve CRM-10188 - an // eNotice caused by it not being set @ the front end // however, we then get it being over-written with null for backend contributions // a better fix would be to set the values in the respective forms rather than require // a function being shared by two forms to deal with their respective values // moving it to the BAO & not taking the $form as a param would make sense here. if (!isset($params['is_email_receipt']) && $isEmailReceipt) { $params['is_email_receipt'] = $isEmailReceipt; } $params['is_recur'] = $isRecur; $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType); $nonDeductibleAmount = self::getNonDeductibleAmount($params, $financialType, $online); $now = date('YmdHis'); $receiptDate = CRM_Utils_Array::value('receipt_date', $params); if ($isEmailReceipt) { $receiptDate = $now; } if (isset($params['amount'])) { $contributionParams = array_merge(self::getContributionParams($params, $financialType->id, $nonDeductibleAmount, TRUE, $result, $receiptDate, $recurringContributionID), $contributionParams); $contribution = CRM_Contribute_BAO_Contribution::add($contributionParams); $invoiceSettings = Civi::settings()->get('contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings); if ($invoicing) { $dataArray = array(); // @todo - interrogate the line items passed in on the params array. // No reason to assume line items will be set on the form. foreach ($form->_lineItem as $lineItemKey => $lineItemValue) { foreach ($lineItemValue as $key => $value) { if (isset($value['tax_amount']) && isset($value['tax_rate'])) { if (isset($dataArray[$value['tax_rate']])) { $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value); } else { $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value); } } } } $smarty = CRM_Core_Smarty::singleton(); $smarty->assign('dataArray', $dataArray); $smarty->assign('totalTaxAmount', $params['tax_amount']); } if (is_a($contribution, 'CRM_Core_Error')) { $message = CRM_Core_Error::getMessages($contribution); CRM_Core_Error::fatal($message); } // lets store it in the form variable so postProcess hook can get to this and use it $form->_contributionID = $contribution->id; } // process soft credit / pcp params first CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form); //CRM-13981, processing honor contact into soft-credit contribution CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution); //handle pledge stuff. if ($isPledge) { if ($pledgeID) { //when user doing pledge payments. //update the schedule when payment(s) are made $amount = $params['amount']; $pledgePaymentParams = array(); foreach ($params['pledge_amount'] as $paymentId => $dontCare) { $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id'); $pledgePayment = $amount >= $scheduledAmount ? $scheduledAmount : $amount; if ($pledgePayment > 0) { $pledgePaymentParams[] = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $pledgePayment); $amount -= $pledgePayment; } } if ($amount > 0 && count($pledgePaymentParams)) { $pledgePaymentParams[count($pledgePaymentParams) - 1]['actual_amount'] += $amount; } foreach ($pledgePaymentParams as $p) { CRM_Pledge_BAO_PledgePayment::add($p); } //update pledge status according to the new payment statuses CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID); } else { //when user creating pledge record. $pledgeParams = array(); $pledgeParams['contact_id'] = $contribution->contact_id; $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount; $pledgeParams['contribution_id'] = $contribution->id; $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id; $pledgeParams['financial_type_id'] = $contribution->financial_type_id; $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval']; $pledgeParams['installments'] = $params['pledge_installments']; $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit']; if ($pledgeParams['frequency_unit'] == 'month') { $pledgeParams['frequency_day'] = intval(date("d")); } else { $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'); $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount']; //inherit campaign from contirb page. $pledgeParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $contributionParams); $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; CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams); } } } if ($online && $contribution) { CRM_Core_BAO_CustomValueTable::postProcess($params, 'civicrm_contribution', $contribution->id, 'Contribution'); } elseif ($contribution) { //handle custom data. $params['contribution_id'] = $contribution->id; if (!empty($params['custom']) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) { CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id); } } // Save note if ($contribution && !empty($params['contribution_note'])) { $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['contribution_note'], 'entity_id' => $contribution->id, 'contact_id' => $contribution->contact_id, 'modified_date' => date('Ymd')); CRM_Core_BAO_Note::add($noteParams, array()); } if (isset($params['related_contact'])) { $contactID = $params['related_contact']; } elseif (isset($params['cms_contactID'])) { $contactID = $params['cms_contactID']; } //create contribution activity w/ individual and target //activity w/ organisation contact id when onbelf, CRM-4027 $targetContactID = NULL; if (!empty($params['hidden_onbehalf_profile'])) { $targetContactID = $contribution->contact_id; $contribution->contact_id = $contactID; } // create an activity record if ($contribution) { CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID); } $transaction->commit(); // CRM-13074 - create the CMSUser after the transaction is completed as it // is not appropriate to delete a valid contribution if a user create problem occurs CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $billingLocationID); return $contribution; }
/** * @param $data * @param $row * @param $type */ public function _fillData($data, $row, $type) { if (!empty($data['contact'])) { $this->select2("s2id_primary_contact_id_{$row}", $data['contact']['email']); } else { $email = $data['first_name'] . '@example.com'; $this->webtestNewDialogContact($data['first_name'], $data['last_name'], $email, 4, "s2id_primary_contact_id_{$row}", $row, 'primary'); } if ($type == "Pledge Payment") { $this->select("field_{$row}_financial_type", $data['financial_type']); $this->type("field_{$row}_total_amount", $data['amount']); $this->webtestFillDateTime("field_{$row}_receive_date", "+1 week"); $this->type("field_{$row}_contribution_source", substr(sha1(rand()), 0, 10)); $this->select("field_{$row}_payment_instrument", "Check"); $this->type("field_{$row}_check_number", rand()); $this->click("field[{$row}][send_receipt]"); $this->click("field_{$row}_invoice_id"); $this->type("field_{$row}_invoice_id", substr(sha1(rand()), 0, 10)); $softcreditemail = $data['soft_credit_first_name'] . '@example.com'; $this->webtestNewDialogContact($data['soft_credit_first_name'], $data['soft_credit_last_name'], $softcreditemail, 4, "s2id_soft_credit_contact_id_{$row}", $row, 'soft_credit'); $this->type("soft_credit_amount_{$row}", $data['soft_credit_amount']); $this->select("soft_credit_type_{$row}", $data['soft_credit_type']); if (!empty($data['contact'])) { $pledgeID = CRM_Pledge_BAO_Pledge::getContactPledges($data['contact']['id']); $this->select("open_pledges_{$row}", "value={$pledgeID[0]}"); $this->click("css=span#{$row}.pledge-adjust-option a"); sleep(5); $this->select("option_type_{$row}", "value=1"); $this->click("css=span#{$row}.pledge-adjust-option a"); $this->type("field_{$row}_total_amount", $data['amount']); } } elseif ($type == "Contribution") { $this->select("field_{$row}_financial_type", $data['financial_type']); $this->type("field_{$row}_total_amount", $data['amount']); $this->webtestFillDateTime("field_{$row}_receive_date", "+1 week"); $this->type("field_{$row}_contribution_source", substr(sha1(rand()), 0, 10)); $this->select("field_{$row}_payment_instrument", "Check"); $this->type("field_{$row}_check_number", rand()); $this->click("field[{$row}][send_receipt]"); $this->click("field_{$row}_invoice_id"); $this->type("field_{$row}_invoice_id", substr(sha1(rand()), 0, 10)); $softcreditemail = $data['soft_credit_first_name'] . '@example.com'; $this->webtestNewDialogContact($data['soft_credit_first_name'], $data['soft_credit_last_name'], $softcreditemail, 4, "s2id_soft_credit_contact_id_{$row}", $row, 'soft_credit'); $this->type("soft_credit_amount_{$row}", $data['soft_credit_amount']); $this->select("soft_credit_type_{$row}", $data['soft_credit_type']); } elseif ($type == "Membership") { $this->select("field[{$row}][membership_type][0]", "value=1"); $this->select("field[{$row}][membership_type][1]", $data['membership_type']); $this->webtestFillDate("field_{$row}_join_date", "now"); $this->webtestFillDate("field_{$row}_membership_start_date", "now"); $this->webtestFillDate("field_{$row}_membership_end_date", "+1 month"); $this->type("field_{$row}_membership_source", substr(sha1(rand()), 0, 10)); $this->click("field[{$row}][send_receipt]"); $this->select("field_{$row}_financial_type", $data['financial_type']); $this->webtestFillDateTime("field_{$row}_receive_date", "+1 week"); $this->select("field_{$row}_payment_instrument", "Check"); $this->type("field_{$row}_check_number", rand()); $this->select("field_{$row}_contribution_status_id", "Completed"); $softcreditemail = $data['soft_credit_first_name'] . '@example.com'; $this->webtestNewDialogContact($data['soft_credit_first_name'], $data['soft_credit_last_name'], $softcreditemail, 4, "s2id_soft_credit_contact_id_{$row}", $row, 'soft_credit'); $this->type("soft_credit_amount_{$row}", $data['soft_credit_amount']); $this->select("soft_credit_type_{$row}", $data['soft_credit_type']); } }
/** * 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. * ' * * @param bool $create * @param null $onDuplicate * * @return array|CRM_Error */ function _civicrm_api3_deprecated_formatted_param($params, &$values, $create = FALSE, $onDuplicate = NULL) { // copy all the contribution fields as is $fields = CRM_Contribute_DAO_Contribution::fields(); _civicrm_api3_store_values($fields, $params, $values); require_once 'CRM/Core/OptionGroup.php'; $customFields = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE); 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; } } } } } elseif ($type == 'Select' || $type == 'Radio' || $type == 'Autocomplete-Select' && $customFields[$customFieldID]['data_type'] == 'String') { $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE); foreach ($customOption as $customFldID => $customValue) { $val = CRM_Utils_Array::value('value', $customValue); $label = CRM_Utils_Array::value('label', $customValue); $label = strtolower($label); $value = strtolower(trim($value)); if ($value == $label || $value == strtolower($val)) { $values[$key] = $val; } } } } switch ($key) { case 'contribution_contact_id': if (!CRM_Utils_Rule::integer($value)) { return civicrm_api3_create_error("contact_id not valid: {$value}"); } $dao = new CRM_Core_DAO(); $qParams = array(); $svq = $dao->singleValueQuery("SELECT is_deleted FROM civicrm_contact WHERE id = {$value}", $qParams); if (!isset($svq)) { return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = {$value}."); } elseif ($svq == 1) { return civicrm_api3_create_error("Invalid Contact ID: contact_id {$value} is a soft-deleted contact."); } $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 identifier if (!empty($params['contribution_contact_id']) || !empty($params['external_identifier'])) { if (!empty($params['contribution_contact_id'])) { $contactType->id = CRM_Utils_Array::value('contribution_contact_id', $params); } elseif (!empty($params['external_identifier'])) { $contactType->external_identifier = $params['external_identifier']; } if ($contactType->find(TRUE)) { if ($params['contact_type'] != $contactType->contact_type) { return civicrm_api3_create_error("Contact Type is wrong: {$contactType->contact_type}"); } } } elseif (!empty($params['contribution_id']) || !empty($params['trxn_id']) || !empty($params['invoice_id'])) { // when update mode check contribution id or trxn id or // invoice id $contactId = new CRM_Contribute_DAO_Contribution(); if (!empty($params['contribution_id'])) { $contactId->id = $params['contribution_id']; } elseif (!empty($params['trxn_id'])) { $contactId->trxn_id = $params['trxn_id']; } elseif (!empty($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_api3_create_error("Contact Type is wrong: {$contactType->contact_type}"); } } } } else { if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) { return civicrm_api3_create_error("Empty Contribution and Invoice and Transaction ID. Row was skipped."); } else { return civicrm_api3_create_error("Empty Contact and External ID. Row was skipped."); } } break; case 'receive_date': case 'cancel_date': case 'receipt_date': case 'thankyou_date': if (!CRM_Utils_Rule::dateTime($value)) { return civicrm_api3_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_api3_create_error("{$key} not a valid amount: {$value}"); } break; case 'currency': if (!CRM_Utils_Rule::currencyCode($value)) { return civicrm_api3_create_error("currency not a valid code: {$value}"); } break; case 'financial_type': require_once 'CRM/Contribute/PseudoConstant.php'; $contriTypes = CRM_Contribute_PseudoConstant::financialType(); foreach ($contriTypes as $val => $type) { if (strtolower($value) == strtolower($type)) { $values['financial_type_id'] = $val; break; } } if (empty($values['financial_type_id'])) { return civicrm_api3_create_error("Financial 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 (empty($values['payment_instrument_id'])) { return civicrm_api3_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_api3_create_error("Contribution Status is not valid: {$value}"); } break; case 'soft_credit': // import contribution record according to select contact type // validate contact id and external identifier. $value[$key] = $mismatchContactType = $softCreditContactIds = ''; if (isset($params[$key]) && is_array($params[$key])) { foreach ($params[$key] as $softKey => $softParam) { $contactId = CRM_Utils_Array::value('contact_id', $softParam); $externalId = CRM_Utils_Array::value('external_identifier', $softParam); $email = CRM_Utils_Array::value('email', $softParam); 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)) { $field = $contactId ? ts('Contact ID') : ts('External ID'); $errorMsg = ts("Soft Credit %1 - %2 doesn't exist. Row was skipped.", array(1 => $field, 2 => $contactId ? $contactId : $externalId)); } if ($errorMsg) { return civicrm_api3_create_error($errorMsg, $value[$key]); } // finally get soft credit contact id. $values[$key][$softKey] = $softParam; $values[$key][$softKey]['contact_id'] = $contact->id; } elseif ($email) { if (!CRM_Utils_Rule::email($email)) { return civicrm_api3_create_error("Invalid email address {$email} provided for Soft Credit. Row was skipped"); } // get the contact id from duplicate contact rule, if more than one contact is returned // we should return error, since current interface allows only one-one mapping $emailParams = array('email' => $email, 'contact_type' => $params['contact_type']); $checkDedupe = _civicrm_api3_deprecated_duplicate_formatted_contact($emailParams); if (!$checkDedupe['is_error']) { return civicrm_api3_create_error("Invalid email address(doesn't exist) {$email} for Soft Credit. Row was skipped"); } else { $matchingContactIds = explode(',', $checkDedupe['error_message']['params'][0]); if (count($matchingContactIds) > 1) { return civicrm_api3_create_error("Invalid email address(duplicate) {$email} for Soft Credit. Row was skipped"); } elseif (count($matchingContactIds) == 1) { $contactId = $matchingContactIds[0]; unset($softParam['email']); $values[$key][$softKey] = $softParam + array('contact_id' => $contactId); } } } } } break; case 'pledge_payment': case 'pledge_id': // giving respect to pledge_payment flag. if (empty($params['pledge_payment'])) { 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_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']; } elseif ($params['trxn_id']) { $contribution->trxn_id = $params['trxn_id']; } elseif ($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_api3_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 (!empty($params['contribution_contact_id'])) { $contributionContactID = $params['contribution_contact_id']; } elseif (!empty($params['external_identifier'])) { 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_api3_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_api3_deprecated_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_api3_create_error($error['error_message']['message'], 'pledge_payment'); } else { $contributionContactID = $params['contribution_contact_id'] = $values['contribution_contact_id'] = $matchedIDs[0]; } } else { return civicrm_api3_create_error('No match found for specified contact in contribution data. Row was skipped.', 'pledge_payment'); } } } if (!empty($params['pledge_id'])) { if (CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $params['pledge_id'], 'contact_id') != $contributionContactID) { return civicrm_api3_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_api3_create_error('No open pledges found for this contact. Contribution row was skipped.', 'pledge_payment'); } elseif (count($pledgeDetails) > 1) { return civicrm_api3_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/PledgePayment.php'; $pledgePaymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($values['pledge_id']); if ($pledgePaymentDetails['amount'] == $totalAmount) { $values['pledge_payment_id'] = $pledgePaymentDetails['id']; } else { return civicrm_api3_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; }
/** * Mass update pledge statuses. * * @param array $params * * @return array */ function civicrm_api3_job_process_pledge($params) { // *** Uncomment the next line if you want automated reminders to be sent // $params['send_reminders'] = true; $result = CRM_Pledge_BAO_Pledge::updatePledgeStatus($params); if ($result['is_error'] == 0) { // experiment: detailed execution log is a result here return civicrm_api3_create_success($result['messages']); } else { return civicrm_api3_create_error($result['error_message']); } }