Commit 65759c55 authored by mattwire's avatar mattwire
Browse files

Major cleanup and refactor. Calculate gift aid amount when creating/updating contribution

parent 72b60122
<?php
/**
* https://civicrm.org/license
*/
class CRM_Civigiftaid_BAO_BatchSettings extends CRM_Civigiftaid_DAO_BatchSettings {
......@@ -7,7 +10,9 @@ class CRM_Civigiftaid_BAO_BatchSettings extends CRM_Civigiftaid_DAO_BatchSetting
*
* @param array $params key-value pairs
*
* @return CRM_Civigiftaid_DAO_BatchSettings|NULL
* @return \CRM_Civigiftaid_BAO_BatchSettings
* @throws \CRM_Extension_Exception
* @throws \CiviCRM_API3_Exception
*/
public static function create($params) {
static::addDefaults($params);
......@@ -40,20 +45,26 @@ class CRM_Civigiftaid_BAO_BatchSettings extends CRM_Civigiftaid_DAO_BatchSetting
/**
* Add default value of certain params, if not provided.
*
* @param $params
* @param array $params
*
* @throws \CRM_Extension_Exception
* @throws \CiviCRM_API3_Exception
*/
private static function addDefaults(&$params) {
if (!isset($params['financial_types_enabled'])) {
$params['financial_types_enabled'] = CRM_Civigiftaid_Form_Admin::getFinancialTypesEnabled();
$params['financial_types_enabled'] = (array) CRM_Civigiftaid_Settings::getValue('financial_types_enabled');
}
if (!isset($params['globally_enabled'])) {
$params['globally_enabled'] = CRM_Civigiftaid_Form_Admin::isGloballyEnabled();
$params['globally_enabled'] = (bool) CRM_Civigiftaid_Settings::getValue('globally_enabled');
}
if (!isset($params['basic_rate_tax'])) {
$params['basic_rate_tax'] = CRM_Civigiftaid_Utils_Contribution::getBasicRateTax();
}
}
/**
* @param array $params
*/
private static function preProcessParams(&$params) {
if (is_array($params['financial_types_enabled'])) {
$params['financial_types_enabled'] = serialize($params['financial_types_enabled']);
......
<?php
require_once 'CRM/Core/Form.php';
/**
* Form controller class
*
* @see http://wiki.civicrm.org/confluence/display/CRMDOC43/QuickForm+Reference
*/
class CRM_Civigiftaid_Form_Admin extends CRM_Core_Form {
/**
* Maintains a cache of settings in order to avoid hitting the database on
* subsequent requests.
*
* @var null|array
*/
private static $settings;
////////////////////
// Public Methods //
////////////////////
/**
* {@inheritdoc}
*/
public function buildQuickForm() {
CRM_Utils_System::setTitle(ts('Gift Aid - Settings'));
$this->add('checkbox', 'globally_enabled', 'Globally Enabled?');
$this->add(
'select',
'financial_types_enabled',
'Enabled Financial Types',
$this->getFinancialTypes(),
FALSE,
['multiple' => TRUE]
);
$this->addButtons([
['type' => 'submit', 'name' => ts('Save'), 'isDefault' => TRUE],
['type' => 'cancel', 'name' => ts('Cancel')],
]);
$this->assign('elementNames', $this->getRenderableElementNames());
parent::buildQuickForm();
}
/**
* {@inheritdoc}
*/
public function postProcess() {
$values = $this->exportValues();
$settings = new stdClass();
$settings->globally_enabled = empty($values['globally_enabled']) ? 0 : 1;
$settings->financial_types_enabled = $values['financial_types_enabled'];
CRM_Core_BAO_Setting::setItem(
$settings,
'Extension',
'uk.co.compucorp.civicrm.giftaid:settings'
);
CRM_Core_Session::setStatus(ts('Settings saved'), '', 'success');
parent::postProcess();
}
/**
* Initialise settings
*
* {@inheritdoc}
*/
public function setDefaultValues() {
return static::getSettings();
}
/**
* Get the fields/elements defined in this form.
*
* @return array (string)
*/
public function getRenderableElementNames() {
// The _elements list includes some items which should not be
// auto-rendered in the loop -- such as "qfKey" and "buttons". These
// items don't have labels. We'll identify renderable by filtering on
// the 'label'.
$elementNames = [];
foreach ($this->_elements as $element) {
/** @var HTML_QuickForm_Element $element */
$label = $element->getLabel();
if (!empty($label)) {
$elementNames[] = $element->getName();
}
}
return $elementNames;
}
///////////////////////////
// Public Static Methods //
///////////////////////////
/**
* @return array
*/
public static function getSettings() {
if (is_null(static::$settings)) {
static::$settings = (array) CRM_Core_BAO_Setting::getItem(
'Extension',
'uk.co.compucorp.civicrm.giftaid:settings'
);
}
return static::$settings;
}
/**
* @return bool
*/
public static function isGloballyEnabled() {
$settings = static::getSettings();
return (bool) $settings['globally_enabled'];
}
/**
* @return array
*/
public static function getFinancialTypesEnabled() {
$settings = static::getSettings();
return (array) $settings['financial_types_enabled'];
}
/////////////////////
// Private Methods //
/////////////////////
/**
* Get an array of financial types
*
* @return array
* @throws \CiviCRM_API3_Exception
*/
private function getFinancialTypes() {
$result = civicrm_api3('FinancialType', 'get',
[
'sequential' => 1,
'is_active' => 1,
'options' => ['limit' => 0],
]
);
$types = [];
foreach ($result['values'] as $type) {
$types[$type['id']] = $type['name'];
}
return $types;
}
}
<?php
/*--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+-------------------------------------------------------------------*/
use CRM_Civigiftaid_ExtensionUtil as E;
/**
* Form controller class
*
* @see http://wiki.civicrm.org/confluence/display/CRMDOC43/QuickForm+Reference
*/
class CRM_Civigiftaid_Form_Settings extends CRM_Core_Form {
function buildQuickForm() {
parent::buildQuickForm();
$className = E::CLASS_PREFIX . '_Settings';
CRM_Utils_System::setTitle($className::TITLE . ' - ' . E::ts('Settings'));
$className = E::CLASS_PREFIX . '_Form_SettingsCustom';
if (method_exists($className, 'buildQuickFormPre')) {
$className::buildQuickFormPre($this);
}
$settings = $this->getFormSettings();
foreach ($settings as $name => $setting) {
if (isset($setting['html_type'])) {
Switch (strtolower($setting['html_type'])) {
case 'text':
$this->addElement('text', $name, ts($setting['description']), $setting['html_attributes'], []);
break;
case 'checkbox':
$this->addElement('checkbox', $name, ts($setting['description']), '', '');
break;
case 'datepicker':
foreach ($setting['html_extra'] as $key => $value) {
if ($key == 'minDate') {
$minDate = new DateTime('now');
$minDate->modify($value);
$setting['html_extra'][$key] = $minDate->format('Y-m-d');
}
}
$this->add('datepicker', $name, ts($setting['description']), $setting['html_attributes'], FALSE, $setting['html_extra']);
break;
case 'select2':
$className = E::CLASS_PREFIX . '_Form_SettingsCustom';
if (method_exists($className, 'addSelect2Element')) {
$className::addSelect2Element($this, $name, $setting);
}
break;
case 'select':
$className = E::CLASS_PREFIX . '_Form_SettingsCustom';
if (method_exists($className, 'addSelectElement')) {
$className::addSelectElement($this, $name, $setting);
}
break;
case 'hidden':
$hidden = TRUE;
}
if (isset($hidden)) {
continue;
}
$adminGroup = isset($setting['admin_group']) ? $setting['admin_group'] : 'default';
$elementGroups[$adminGroup]['elementNames'][] = $name;
// Title and description may not be defined on all elements (they only need to be on one)
if (!empty($setting['admin_grouptitle'])) {
$elementGroups[$setting['admin_group']]['title'] = $setting['admin_grouptitle'];
}
if (!empty($setting['admin_groupdescription'])) {
$elementGroups[$setting['admin_group']]['description'] = $setting['admin_groupdescription'];
}
}
}
$this->addButtons([
[
'type' => 'submit',
'name' => ts('Submit'),
'isDefault' => TRUE,
],
[
'type' => 'cancel',
'name' => ts('Cancel'),
]
]);
// export form elements
$this->assign('elementGroups', $elementGroups);
}
function postProcess() {
$className = E::CLASS_PREFIX . '_Settings';
$changed = $this->_submitValues;
$settings = $this->getFormSettings(TRUE);
foreach ($settings as &$setting) {
if ($setting['html_type'] == 'Checkbox') {
$setting = false;
}
else {
$setting = NULL;
}
}
// Make sure we have all settings elements set (boolean settings will be unset by default and wouldn't be saved)
$settingsToSave = array_merge($settings, array_intersect_key($changed, $settings));
$className::save($settingsToSave);
parent::postProcess();
CRM_Core_Session::singleton()->setStatus('Configuration Updated', $className::TITLE, 'success');
}
/**
* Get the settings we are going to allow to be set on this form.
*
* @return array
*/
function getFormSettings($metadata=TRUE) {
$className = E::CLASS_PREFIX . '_Settings';
$unprefixedSettings = [];
$settings = civicrm_api3('setting', 'getfields', ['filters' => $className::getFilter()]);
if (!empty($settings['values'])) {
foreach ($settings['values'] as $name => $values) {
if ($metadata) {
$unprefixedSettings[$className::getName($name, FALSE)] = $values;
}
else {
$unprefixedSettings[$className::getName($name, FALSE)] = NULL;
}
}
}
return $unprefixedSettings;
}
/**
* Set defaults for form.
*
* @see CRM_Core_Form::setDefaultValues()
*/
function setDefaultValues() {
$className = E::CLASS_PREFIX . '_Settings';
$settings = $this->getFormSettings(FALSE);
$defaults = [];
$existing = $className::get(array_keys($settings));
if ($existing) {
foreach ($existing as $name => $value) {
$defaults[$name] = $value;
}
}
return $defaults;
}
}
<?php
/*--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+-------------------------------------------------------------------*/
use CRM_Civigiftaid_ExtensionUtil as E;
/**
* Form controller class
*
* @see http://wiki.civicrm.org/confluence/display/CRMDOC43/QuickForm+Reference
*/
class CRM_Civigiftaid_Form_SettingsCustom extends CRM_Civigiftaid_Form_Settings {
/**
* @param \CRM_Core_Form $form
* @param string $name
* @param array $setting
*
* @throws \CiviCRM_API3_Exception
*/
public static function addSelect2Element(&$form, $name, $setting) {
switch ($name) {
case 'financial_types_enabled':
$financialTypes = civicrm_api3('FinancialType', 'get', [
'is_active' => 1,
'options' => ['limit' => 0, 'sort' => "name ASC"],
]);
$types = [];
foreach ($financialTypes['values'] as $type) {
$types[] = [
'id' => $type['id'],
'text' => $type['name'],
];
}
$form->add('select2', $name, $setting['description'], $types, FALSE, $setting['html_attributes']);
break;
}
}
}
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.3 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2011 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2011
* $Id$
*
* https://civicrm.org/license
*/
require_once 'CRM/Contribute/Form/Task.php';
use CRM_Civigiftaid_ExtensionUtil as E;
/**
* This class provides the functionality to add a group of contribution to a batch.
*/
require_once 'CRM/Utils/String.php';
class CRM_Civigiftaid_Form_Task_AddToBatch extends CRM_Contribute_Form_Task {
protected $_id = NULL;
/**
* build all the data structures needed to build the form
*
* @return void
* @access public
* @var int
*/
function preProcess() {
protected $_id = NULL;
public function preProcess() {
parent::preProcess();
require_once 'CRM/Civigiftaid/Utils/Contribution.php';
list($total, $added, $alreadyAdded, $notValid) =
CRM_Civigiftaid_Utils_Contribution::validateContributionToBatch($this->_contributionIds);
$this->assign('selectedContributions', $total);
......@@ -82,20 +48,14 @@ class CRM_Civigiftaid_Form_Task_AddToBatch extends CRM_Contribute_Form_Task {
$this->assign('contributionsNotValid', $contributionsNotValid);
}
/**
* Build the form
*
* @access public
* @return void
*/
function buildQuickForm() {
public function buildQuickForm() {
$attributes = CRM_Core_DAO::getAttribute('CRM_Batch_DAO_Batch');
$this->add('text', 'title', ts('Batch Title'), $attributes['title'], TRUE);
$this->add('text', 'title', E::ts('Batch Title'), $attributes['title'], TRUE);
$this->addRule(
'title',
ts('Label already exists in Database.'),
E::ts('Label already exists in Database.'),
'objectExists',
['CRM_Batch_DAO_Batch', $this->_id, 'title']
);
......@@ -103,25 +63,18 @@ class CRM_Civigiftaid_Form_Task_AddToBatch extends CRM_Contribute_Form_Task {
$this->add(
'textarea',
'description',
ts('Description:') . ' ',
E::ts('Description:') . ' ',
$attributes['description']
);
require_once 'CRM/Batch/BAO/Batch.php';
$batchName = CRM_Batch_BAO_Batch::generateBatchName();
$defaults = ['title' => ts('GiftAid ' . $batchName)];
$defaults = ['title' => E::ts('GiftAid ' . $batchName)];
$this->setDefaults($defaults);
$this->addDefaultButtons(ts('Add to batch'));
$this->addDefaultButtons(E::ts('Add to batch'));
}
/**
* process the form after the input has been submitted and validated
*
* @access public
* @return None
*/
public function postProcess() {
$params = $this->controller->exportValues();
$batchParams = [];
......@@ -145,11 +98,8 @@ class CRM_Civigiftaid_Form_Task_AddToBatch extends CRM_Contribute_Form_Task {
$batchParams['modified_date'] = date('YmdHis');
$batchParams['modified_id'] = $session->get('userID');
require_once 'CRM/Core/Transaction.php';
$transaction = new CRM_Core_Transaction();
//require_once 'CRM/Core/BAO/Batch.php'; //version 4.2
require_once 'CRM/Batch/BAO/Batch.php';
$createdBatch = CRM_Batch_BAO_Batch::create($batchParams);
$batchID = $createdBatch->id;
......@@ -158,7 +108,6 @@ class CRM_Civigiftaid_Form_Task_AddToBatch extends CRM_Contribute_Form_Task {
// Save current settings for the batch
CRM_Civigiftaid_BAO_BatchSettings::create(['batch_id' => $batchID]);
require_once 'CRM/Civigiftaid/Utils/Contribution.php';
list($total, $added, $notAdded) =
CRM_Civigiftaid_Utils_Contribution::addContributionToBatch(
$this->_contributionIds,
......@@ -168,24 +117,24 @@ class CRM_Civigiftaid_Form_Task_AddToBatch extends CRM_Contribute_Form_Task {
if ($added <= 0) {
// rollback since there were no contributions added, and we might not want to keep an empty batch
$transaction->rollback();
$status = ts(
$status = E::ts(
'Could not create batch "%1", as there were no valid contribution(s) to be added.',
[1 => $batchLabel]
);
}
else {
$status = [
ts('Added Contribution(s) to %1', [1 => $batchLabel]),
ts('Total Selected Contribution(s): %1', [1 => $total])
E::ts('Added Contribution(s) to %1', [1 => $batchLabel]),
E::ts('Total Selected Contribution(s): %1', [1 => $total])
];
if ($added) {
$status[] = ts(
$status[] = E::ts(
'Total Contribution(s) added to batch: %1',
[1 => $added]
);
}
if ($notAdded) {