First commit

This commit is contained in:
Theodotos Andreou 2018-01-14 13:10:16 +00:00
commit c6e2478c40
13918 changed files with 2303184 additions and 0 deletions

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,351 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Pledge_BAO_PledgeBlock extends CRM_Pledge_DAO_PledgeBlock {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Retrieve DB object based on input parameters.
*
* It also stores all the retrieved values in the default array.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Pledge_BAO_PledgeBlock
*/
public static function retrieve(&$params, &$defaults) {
$pledgeBlock = new CRM_Pledge_DAO_PledgeBlock();
$pledgeBlock->copyValues($params);
if ($pledgeBlock->find(TRUE)) {
CRM_Core_DAO::storeValues($pledgeBlock, $defaults);
return $pledgeBlock;
}
return NULL;
}
/**
* Takes an associative array and creates a pledgeBlock object.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return CRM_Pledge_BAO_PledgeBlock
*/
public static function &create(&$params) {
$transaction = new CRM_Core_Transaction();
$pledgeBlock = self::add($params);
if (is_a($pledgeBlock, 'CRM_Core_Error')) {
$pledgeBlock->rollback();
return $pledgeBlock;
}
$params['id'] = $pledgeBlock->id;
$transaction->commit();
return $pledgeBlock;
}
/**
* Add pledgeBlock.
*
* @param array $params
* Reference array contains the values submitted by the form.
*
*
* @return object
*/
public static function add(&$params) {
if (!empty($params['id'])) {
CRM_Utils_Hook::pre('edit', 'PledgeBlock', $params['id'], $params);
}
else {
CRM_Utils_Hook::pre('create', 'PledgeBlock', NULL, $params);
}
$pledgeBlock = new CRM_Pledge_DAO_PledgeBlock();
// fix for pledge_frequency_unit
$freqUnits = CRM_Utils_Array::value('pledge_frequency_unit', $params);
if ($freqUnits && is_array($freqUnits)) {
unset($params['pledge_frequency_unit']);
$newFreqUnits = array();
foreach ($freqUnits as $k => $v) {
if ($v) {
$newFreqUnits[$k] = $v;
}
}
$freqUnits = $newFreqUnits;
if (is_array($freqUnits) && !empty($freqUnits)) {
$freqUnits = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($freqUnits));
$pledgeBlock->pledge_frequency_unit = $freqUnits;
}
else {
$pledgeBlock->pledge_frequency_unit = '';
}
}
$pledgeBlock->copyValues($params);
$result = $pledgeBlock->save();
if (!empty($params['id'])) {
CRM_Utils_Hook::post('edit', 'PledgeBlock', $pledgeBlock->id, $pledgeBlock);
}
else {
CRM_Utils_Hook::post('create', 'Pledge', $pledgeBlock->id, $pledgeBlock);
}
return $result;
}
/**
* Delete the pledgeBlock.
*
* @param int $id
* PledgeBlock id.
*
* @return mixed|null
*/
public static function deletePledgeBlock($id) {
CRM_Utils_Hook::pre('delete', 'PledgeBlock', $id, CRM_Core_DAO::$_nullArray);
$transaction = new CRM_Core_Transaction();
$results = NULL;
$dao = new CRM_Pledge_DAO_PledgeBlock();
$dao->id = $id;
$results = $dao->delete();
$transaction->commit();
CRM_Utils_Hook::post('delete', 'PledgeBlock', $dao->id, $dao);
return $results;
}
/**
* Return Pledge Block info in Contribution Pages.
*
* @param int $pageID
* Contribution page id.
*
* @return array
*/
public static function getPledgeBlock($pageID) {
$pledgeBlock = array();
$dao = new CRM_Pledge_DAO_PledgeBlock();
$dao->entity_table = 'civicrm_contribution_page';
$dao->entity_id = $pageID;
if ($dao->find(TRUE)) {
CRM_Core_DAO::storeValues($dao, $pledgeBlock);
}
return $pledgeBlock;
}
/**
* 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('m/d/Y');
list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults(NULL);
$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));
}
}
}
}
}
}
}

View file

@ -0,0 +1,904 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Pledge_BAO_PledgePayment extends CRM_Pledge_DAO_PledgePayment {
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Get pledge payment details.
*
* @param int $pledgeId
* Pledge id.
*
* @return array
* associated array of pledge payment details
*/
public static function getPledgePayments($pledgeId) {
$query = "
SELECT civicrm_pledge_payment.id id,
scheduled_amount,
scheduled_date,
reminder_date,
reminder_count,
actual_amount,
receive_date,
civicrm_pledge_payment.currency,
civicrm_option_value.name as status,
civicrm_option_value.label as label,
civicrm_contribution.id as contribution_id
FROM civicrm_pledge_payment
LEFT JOIN civicrm_contribution ON civicrm_pledge_payment.contribution_id = civicrm_contribution.id
LEFT JOIN civicrm_option_group ON ( civicrm_option_group.name = 'contribution_status' )
LEFT JOIN civicrm_option_value ON ( civicrm_pledge_payment.status_id = civicrm_option_value.value AND
civicrm_option_group.id = civicrm_option_value.option_group_id )
WHERE pledge_id = %1
";
$params[1] = array($pledgeId, 'Integer');
$payment = CRM_Core_DAO::executeQuery($query, $params);
$paymentDetails = array();
while ($payment->fetch()) {
$paymentDetails[$payment->id]['scheduled_amount'] = $payment->scheduled_amount;
$paymentDetails[$payment->id]['scheduled_date'] = $payment->scheduled_date;
$paymentDetails[$payment->id]['reminder_date'] = $payment->reminder_date;
$paymentDetails[$payment->id]['reminder_count'] = $payment->reminder_count;
$paymentDetails[$payment->id]['total_amount'] = $payment->actual_amount;
$paymentDetails[$payment->id]['receive_date'] = $payment->receive_date;
$paymentDetails[$payment->id]['status'] = $payment->status;
$paymentDetails[$payment->id]['label'] = $payment->label;
$paymentDetails[$payment->id]['id'] = $payment->id;
$paymentDetails[$payment->id]['contribution_id'] = $payment->contribution_id;
$paymentDetails[$payment->id]['currency'] = $payment->currency;
}
return $paymentDetails;
}
/**
* @param array $params
*
* @return pledge
*/
public static function create($params) {
$transaction = new CRM_Core_Transaction();
$overdueStatusID = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_PledgePayment', 'status_id', 'Overdue');
$pendingStatusId = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_PledgePayment', 'status_id', 'Pending');
//calculate the scheduled date for every installment
$now = date('Ymd') . '000000';
$statues = $prevScheduledDate = array();
$prevScheduledDate[1] = CRM_Utils_Date::processDate($params['scheduled_date']);
if (CRM_Utils_Date::overdue($prevScheduledDate[1], $now)) {
$statues[1] = $overdueStatusID;
}
else {
$statues[1] = $pendingStatusId;
}
for ($i = 1; $i < $params['installments']; $i++) {
$prevScheduledDate[$i + 1] = self::calculateNextScheduledDate($params, $i);
if (CRM_Utils_Date::overdue($prevScheduledDate[$i + 1], $now)) {
$statues[$i + 1] = $overdueStatusID;
}
else {
$statues[$i + 1] = $pendingStatusId;
}
}
if ($params['installment_amount']) {
$params['scheduled_amount'] = $params['installment_amount'];
}
else {
$params['scheduled_amount'] = round(($params['amount'] / $params['installments']), 2);
}
for ($i = 1; $i <= $params['installments']; $i++) {
// calculate the scheduled amount for every installment.
if ($i == $params['installments']) {
$params['scheduled_amount'] = $params['amount'] - ($i - 1) * $params['scheduled_amount'];
}
if (!isset($params['contribution_id']) && $params['installments'] > 1) {
$params['status_id'] = $statues[$i];
}
$params['scheduled_date'] = $prevScheduledDate[$i];
$payment = self::add($params);
if (is_a($payment, 'CRM_Core_Error')) {
$transaction->rollback();
return $payment;
}
// we should add contribution id to only first payment record
if (isset($params['contribution_id'])) {
unset($params['contribution_id']);
unset($params['actual_amount']);
}
}
// update pledge status
self::updatePledgePaymentStatus($params['pledge_id']);
$transaction->commit();
return $payment;
}
/**
* Add pledge payment.
*
* @param array $params
* Associate array of field.
*
* @return CRM_Pledge_DAO_PledgePayment
* pledge payment id
*/
public static function add($params) {
if (!empty($params['id'])) {
CRM_Utils_Hook::pre('edit', 'PledgePayment', $params['id'], $params);
}
else {
CRM_Utils_Hook::pre('create', 'PledgePayment', NULL, $params);
}
$payment = new CRM_Pledge_DAO_PledgePayment();
$payment->copyValues($params);
// set currency for CRM-1496
if (!isset($payment->currency)) {
$payment->currency = CRM_Core_Config::singleton()->defaultCurrency;
}
$result = $payment->save();
if (!empty($params['id'])) {
CRM_Utils_Hook::post('edit', 'PledgePayment', $payment->id, $payment);
}
else {
CRM_Utils_Hook::post('create', 'PledgePayment', $payment->id, $payment);
}
return $result;
}
/**
* Retrieve DB object based on input parameters.
*
* It also stores all the retrieved values in the default array.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Pledge_BAO_PledgePayment
*/
public static function retrieve(&$params, &$defaults) {
$payment = new CRM_Pledge_BAO_PledgePayment();
$payment->copyValues($params);
if ($payment->find(TRUE)) {
CRM_Core_DAO::storeValues($payment, $defaults);
return $payment;
}
return NULL;
}
/**
* Delete pledge payment.
*
* @param int $id
*
* @return int
* pledge payment id
*/
public static function del($id) {
$payment = new CRM_Pledge_DAO_PledgePayment();
$payment->id = $id;
if ($payment->find()) {
$payment->fetch();
CRM_Utils_Hook::pre('delete', 'PledgePayment', $id, $payment);
$result = $payment->delete();
CRM_Utils_Hook::post('delete', 'PledgePayment', $id, $payment);
return $result;
}
else {
return FALSE;
}
}
/**
* Delete all pledge payments.
*
* @param int $id
* Pledge id.
*
* @return bool
*/
public static function deletePayments($id) {
if (!CRM_Utils_Rule::positiveInteger($id)) {
return FALSE;
}
$transaction = new CRM_Core_Transaction();
$payment = new CRM_Pledge_DAO_PledgePayment();
$payment->pledge_id = $id;
if ($payment->find()) {
while ($payment->fetch()) {
//also delete associated contribution.
if ($payment->contribution_id) {
CRM_Contribute_BAO_Contribution::deleteContribution($payment->contribution_id);
}
self::del($payment->id);
}
}
$transaction->commit();
return TRUE;
}
/**
* On delete contribution record update associated pledge payment and pledge.
*
* @param int $contributionID
* Contribution id.
*
* @return bool
*/
public static function resetPledgePayment($contributionID) {
$transaction = new CRM_Core_Transaction();
$payment = new CRM_Pledge_DAO_PledgePayment();
$payment->contribution_id = $contributionID;
if ($payment->find(TRUE)) {
$payment->contribution_id = 'null';
$payment->status_id = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
$payment->scheduled_date = NULL;
$payment->reminder_date = NULL;
$payment->scheduled_amount = $payment->actual_amount;
$payment->actual_amount = 'null';
$payment->save();
//update pledge status.
$pledgeID = $payment->pledge_id;
$pledgeStatusID = self::calculatePledgeStatus($pledgeID);
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_Pledge', $pledgeID, 'status_id', $pledgeStatusID);
$payment->free();
}
$transaction->commit();
return TRUE;
}
/**
* Update Pledge Payment Status.
*
* @param int $pledgeID
* Id of pledge.
* @param array $paymentIDs
* Ids of pledge payment(s) to update.
* @param int $paymentStatusID
* Payment status to set.
* @param int $pledgeStatusID
* Pledge status to change (if needed).
* @param float|int $actualAmount , actual amount being paid
* @param bool $adjustTotalAmount
* Is amount being paid different from scheduled amount?.
* @param bool $isScriptUpdate
* Is function being called from bin script?.
*
* @return int
* $newStatus, updated status id (or 0)
*/
public static function updatePledgePaymentStatus(
$pledgeID,
$paymentIDs = NULL,
$paymentStatusID = NULL,
$pledgeStatusID = NULL,
$actualAmount = 0,
$adjustTotalAmount = FALSE,
$isScriptUpdate = FALSE
) {
$totalAmountClause = '';
$paymentContributionId = NULL;
$editScheduled = FALSE;
// get all statuses
$allStatus = CRM_Core_OptionGroup::values('pledge_status',
FALSE, FALSE, FALSE, NULL, 'name', TRUE
);
// if we get do not get contribution id means we are editing the scheduled payment.
if (!empty($paymentIDs)) {
$editScheduled = FALSE;
$payments = implode(',', $paymentIDs);
$paymentContributionId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
$payments,
'contribution_id',
'id'
);
if (!$paymentContributionId) {
$editScheduled = TRUE;
}
}
// if payment ids are passed, we update payment table first, since payments statuses are not dependent on pledge status
$pledgeStatusName = CRM_Core_PseudoConstant::getName('CRM_Pledge_BAO_Pledge', 'status_id', $pledgeStatusID);
if ((!empty($paymentIDs) || $pledgeStatusName == 'Cancelled') && (!$editScheduled || $isScriptUpdate)) {
if ($pledgeStatusName == 'Cancelled') {
$paymentStatusID = $pledgeStatusID;
}
self::updatePledgePayments($pledgeID, $paymentStatusID, $paymentIDs, $actualAmount, $paymentContributionId, $isScriptUpdate);
}
if (!empty($paymentIDs) && $actualAmount) {
$payments = implode(',', $paymentIDs);
$pledgeScheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
$payments,
'scheduled_amount',
'id'
);
$pledgeStatusId = self::calculatePledgeStatus($pledgeID);
// Actual Pledge Amount
$actualPledgeAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge',
$pledgeID,
'amount',
'id'
);
// while editing scheduled we need to check if we are editing last pending
$lastPending = FALSE;
if (!$paymentContributionId) {
$checkPendingCount = self::getOldestPledgePayment($pledgeID, 2);
if ($checkPendingCount['count'] == 1) {
$lastPending = TRUE;
}
}
// check if this is the last payment and adjust the actual amount.
if ($pledgeStatusId && $pledgeStatusId == array_search('Completed', $allStatus) || $lastPending) {
// last scheduled payment
if ($actualAmount >= $pledgeScheduledAmount) {
$adjustTotalAmount = TRUE;
}
elseif (!$adjustTotalAmount) {
// actual amount is less than the scheduled amount, so enter new pledge payment record
$pledgeFrequencyUnit = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeID, 'frequency_unit', 'id');
$pledgeFrequencyInterval = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeID, 'frequency_interval', 'id');
$pledgeScheduledDate = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments, 'scheduled_date', 'id');
$scheduled_date = CRM_Utils_Date::processDate($pledgeScheduledDate);
$date['year'] = (int) substr($scheduled_date, 0, 4);
$date['month'] = (int) substr($scheduled_date, 4, 2);
$date['day'] = (int) substr($scheduled_date, 6, 2);
$newDate = date('YmdHis', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
$ScheduledDate = CRM_Utils_Date::format(CRM_Utils_Date::intervalAdd($pledgeFrequencyUnit,
$pledgeFrequencyInterval, $newDate
));
$pledgeParams = array(
'status_id' => array_search('Pending', $allStatus),
'pledge_id' => $pledgeID,
'scheduled_amount' => ($pledgeScheduledAmount - $actualAmount),
'scheduled_date' => $ScheduledDate,
);
$payment = self::add($pledgeParams);
// while editing schedule, after adding a new pledge payemnt update the scheduled amount of the current payment
if (!$paymentContributionId) {
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $payments, 'scheduled_amount', $actualAmount);
}
}
}
elseif (!$adjustTotalAmount) {
// not last schedule amount and also not selected to adjust Total
$paymentContributionId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
$payments,
'contribution_id',
'id'
);
self::adjustPledgePayment($pledgeID, $actualAmount, $pledgeScheduledAmount, $paymentContributionId, $payments, $paymentStatusID);
// while editing schedule, after adding a new pledge payemnt update the scheduled amount of the current payment
if (!$paymentContributionId) {
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $payments, 'scheduled_amount', $actualAmount);
}
// after adjusting all payments check if the actual amount was greater than the actual remaining amount , if so then update the total pledge amount.
$pledgeStatusId = self::calculatePledgeStatus($pledgeID);
$balanceQuery = "
SELECT sum( civicrm_pledge_payment.actual_amount )
FROM civicrm_pledge_payment
WHERE civicrm_pledge_payment.pledge_id = %1
AND civicrm_pledge_payment.status_id = 1
";
$totalPaidParams = array(1 => array($pledgeID, 'Integer'));
$totalPaidAmount = CRM_Core_DAO::singleValueQuery($balanceQuery, $totalPaidParams);
$remainingTotalAmount = ($actualPledgeAmount - $totalPaidAmount);
if (($pledgeStatusId && $pledgeStatusId == array_search('Completed', $allStatus)) && (($actualAmount > $remainingTotalAmount) || ($actualAmount >= $actualPledgeAmount))) {
$totalAmountClause = ", civicrm_pledge.amount = {$totalPaidAmount}";
}
}
if ($adjustTotalAmount) {
$newTotalAmount = ($actualPledgeAmount + ($actualAmount - $pledgeScheduledAmount));
$totalAmountClause = ", civicrm_pledge.amount = {$newTotalAmount}";
if (!$paymentContributionId) {
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $payments, 'scheduled_amount', $actualAmount);
}
}
}
$cancelDateClause = $endDateClause = NULL;
// update pledge and payment status if status is Completed/Cancelled.
if ($pledgeStatusID && $pledgeStatusID == array_search('Cancelled', $allStatus)) {
$paymentStatusID = $pledgeStatusID;
$cancelDateClause = ", civicrm_pledge.cancel_date = CURRENT_TIMESTAMP ";
}
else {
// get pledge status
$pledgeStatusID = self::calculatePledgeStatus($pledgeID);
}
if ($pledgeStatusID == array_search('Completed', $allStatus)) {
$endDateClause = ", civicrm_pledge.end_date = CURRENT_TIMESTAMP ";
}
// update pledge status
$query = "
UPDATE civicrm_pledge
SET civicrm_pledge.status_id = %1
{$cancelDateClause} {$endDateClause} {$totalAmountClause}
WHERE civicrm_pledge.id = %2
";
$params = array(
1 => array($pledgeStatusID, 'Integer'),
2 => array($pledgeID, 'Integer'),
);
CRM_Core_DAO::executeQuery($query, $params);
return $pledgeStatusID;
}
/**
* Calculate the base scheduled date. This function effectively 'rounds' the $params['scheduled_date'] value
* to the first payment date with respect to the frequency day - ie. if payments are on the 15th of the month the date returned
* will be the 15th of the relevant month. Then to calculate the payments you can use intervalAdd ie.
* CRM_Utils_Date::intervalAdd( $params['frequency_unit'], $i * ($params['frequency_interval']) , calculateBaseScheduledDate( &$params )))
*
* @param array $params
*
* @return array
* Next scheduled date as an array
*/
public static function calculateBaseScheduleDate(&$params) {
$date = array();
$scheduled_date = CRM_Utils_Date::processDate($params['scheduled_date']);
$date['year'] = (int) substr($scheduled_date, 0, 4);
$date['month'] = (int) substr($scheduled_date, 4, 2);
$date['day'] = (int) substr($scheduled_date, 6, 2);
// calculation of schedule date according to frequency day of period
// frequency day is not applicable for daily installments
if ($params['frequency_unit'] != 'day' && $params['frequency_unit'] != 'year') {
if ($params['frequency_unit'] != 'week') {
// CRM-18316: To calculate pledge scheduled dates at the end of a month.
$date['day'] = $params['frequency_day'];
$lastDayOfMonth = date('t', mktime(0, 0, 0, $date['month'], 1, $date['year']));
if ($lastDayOfMonth < $date['day']) {
$date['day'] = $lastDayOfMonth;
}
}
elseif ($params['frequency_unit'] == 'week') {
// for week calculate day of week ie. Sunday,Monday etc. as next payment date
$dayOfWeek = date('w', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
$frequencyDay = $params['frequency_day'] - $dayOfWeek;
$scheduleDate = explode("-", date('n-j-Y', mktime(0, 0, 0, $date['month'],
$date['day'] + $frequencyDay, $date['year']
)));
$date['month'] = $scheduleDate[0];
$date['day'] = $scheduleDate[1];
$date['year'] = $scheduleDate[2];
}
}
$newdate = date('YmdHis', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
return $newdate;
}
/**
* Calculate next scheduled pledge payment date. Function calculates next pledge payment date.
*
* @param array $params
* must include frequency unit & frequency interval
* @param int $paymentNo
* number of payment in sequence (e.g. 1 for first calculated payment (treat initial payment as 0)
* @param string $basePaymentDate
* date to calculate payments from. This would normally be the
* first day of the pledge (default) & is calculated off the 'scheduled date' param. Returned date will
* be equal to basePaymentDate normalised to fit the 'pledge pattern' + number of installments
*
* @return string
* formatted date
*/
public static function calculateNextScheduledDate(&$params, $paymentNo, $basePaymentDate = NULL) {
$interval = $paymentNo * ($params['frequency_interval']);
if (!$basePaymentDate) {
$basePaymentDate = self::calculateBaseScheduleDate($params);
}
//CRM-18316 - change $basePaymentDate for the end dates of the month eg: 29, 30 or 31.
if ($params['frequency_unit'] == 'month' && in_array($params['frequency_day'], array(29, 30, 31))) {
$frequency = $params['frequency_day'];
extract(date_parse($basePaymentDate));
$lastDayOfMonth = date('t', mktime($hour, $minute, $second, $month + $interval, 1, $year));
// Take the last day in case the current month is Feb or frequency_day is set to 31.
if (in_array($lastDayOfMonth, array(28, 29)) || $frequency == 31) {
$frequency = 0;
$interval++;
}
$basePaymentDate = array(
'M' => $month,
'd' => $frequency,
'Y' => $year,
);
}
return CRM_Utils_Date::format(
CRM_Utils_Date::intervalAdd(
$params['frequency_unit'],
$interval,
$basePaymentDate
)
);
}
/**
* Calculate the pledge status.
*
* @param int $pledgeId
* Pledge id.
*
* @return int
* $statusId calculated status id of pledge
*/
public static function calculatePledgeStatus($pledgeId) {
$paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$pledgeStatusTypes = CRM_Pledge_BAO_Pledge::buildOptions('status_id', 'validate');
//return if the pledge is cancelled.
$currentPledgeStatusId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeId, 'status_id', 'id', TRUE);
if ($currentPledgeStatusId == array_search('Cancelled', $pledgeStatusTypes)) {
return $currentPledgeStatusId;
}
// retrieve all pledge payments for this particular pledge
$allPledgePayments = $allStatus = array();
$returnProperties = array('status_id');
CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $pledgeId, $allPledgePayments, $returnProperties);
// build pledge payment statuses
foreach ($allPledgePayments as $key => $value) {
$allStatus[$value['id']] = $paymentStatusTypes[$value['status_id']];
}
if (array_search('Overdue', $allStatus)) {
$statusId = array_search('Overdue', $pledgeStatusTypes);
}
elseif (array_search('Completed', $allStatus)) {
if (count(array_count_values($allStatus)) == 1) {
$statusId = array_search('Completed', $pledgeStatusTypes);
}
else {
$statusId = array_search('In Progress', $pledgeStatusTypes);
}
}
else {
$statusId = array_search('Pending', $pledgeStatusTypes);
}
return $statusId;
}
/**
* Update pledge payment table.
*
* @param int $pledgeId
* Pledge id.
* @param int $paymentStatusId
* Payment status id to set.
* @param array $paymentIds
* Payment ids to be updated.
* @param float|int $actualAmount , actual amount being paid
* @param int $contributionId
* , Id of associated contribution when payment is recorded.
* @param bool $isScriptUpdate
* , is function being called from bin script?.
*
*/
public static function updatePledgePayments(
$pledgeId,
$paymentStatusId,
$paymentIds = NULL,
$actualAmount = 0,
$contributionId = NULL,
$isScriptUpdate = FALSE
) {
$allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$paymentClause = NULL;
if (!empty($paymentIds)) {
$payments = implode(',', $paymentIds);
$paymentClause = " AND civicrm_pledge_payment.id IN ( {$payments} )";
}
elseif ($paymentStatusId == array_search('Cancelled', $allStatus)) {
$completedStatus = array_search('Completed', $allStatus);
$paymentClause = " AND civicrm_pledge_payment.status_id != {$completedStatus}";
}
$actualAmountClause = NULL;
$contributionIdClause = NULL;
if (isset($contributionId) && !$isScriptUpdate) {
$contributionIdClause = ", civicrm_pledge_payment.contribution_id = {$contributionId}";
$actualAmountClause = ", civicrm_pledge_payment.actual_amount = {$actualAmount}";
}
$query = "
UPDATE civicrm_pledge_payment
SET civicrm_pledge_payment.status_id = {$paymentStatusId}
{$actualAmountClause} {$contributionIdClause}
WHERE civicrm_pledge_payment.pledge_id = %1
{$paymentClause}
";
CRM_Core_DAO::executeQuery($query, array(1 => array($pledgeId, 'Integer')));
}
/**
* Update pledge payment table when reminder is sent.
*
* @param int $paymentId
* Payment id.
*/
public static function updateReminderDetails($paymentId) {
$query = "
UPDATE civicrm_pledge_payment
SET civicrm_pledge_payment.reminder_date = CURRENT_TIMESTAMP,
civicrm_pledge_payment.reminder_count = civicrm_pledge_payment.reminder_count + 1
WHERE civicrm_pledge_payment.id = {$paymentId}
";
$dao = CRM_Core_DAO::executeQuery($query);
}
/**
* Get oldest pending or in progress pledge payments.
*
* @param int $pledgeID
* Pledge id.
*
* @param int $limit
*
* @return array
* associated array of pledge details
*/
public static function getOldestPledgePayment($pledgeID, $limit = 1) {
// get pending / overdue statuses
$pledgeStatuses = CRM_Core_OptionGroup::values('pledge_status',
FALSE, FALSE, FALSE, NULL, 'name'
);
// get pending and overdue payments
$status[] = array_search('Pending', $pledgeStatuses);
$status[] = array_search('Overdue', $pledgeStatuses);
$statusClause = " IN (" . implode(',', $status) . ")";
$query = "
SELECT civicrm_pledge_payment.id id, civicrm_pledge_payment.scheduled_amount amount, civicrm_pledge_payment.currency, civicrm_pledge_payment.scheduled_date,civicrm_pledge.financial_type_id
FROM civicrm_pledge, civicrm_pledge_payment
WHERE civicrm_pledge.id = civicrm_pledge_payment.pledge_id
AND civicrm_pledge_payment.status_id {$statusClause}
AND civicrm_pledge.id = %1
ORDER BY civicrm_pledge_payment.scheduled_date ASC
LIMIT 0, %2
";
$params[1] = array($pledgeID, 'Integer');
$params[2] = array($limit, 'Integer');
$payment = CRM_Core_DAO::executeQuery($query, $params);
$count = 1;
$paymentDetails = array();
while ($payment->fetch()) {
$paymentDetails[] = array(
'id' => $payment->id,
'amount' => $payment->amount,
'currency' => $payment->currency,
'schedule_date' => $payment->scheduled_date,
'financial_type_id' => $payment->financial_type_id,
'count' => $count,
);
$count++;
}
return end($paymentDetails);
}
/**
* @param int $pledgeID
* @param $actualAmount
* @param $pledgeScheduledAmount
* @param int $paymentContributionId
* @param int $pPaymentId
* @param int $paymentStatusID
*/
public static function adjustPledgePayment($pledgeID, $actualAmount, $pledgeScheduledAmount, $paymentContributionId = NULL, $pPaymentId = NULL, $paymentStatusID = NULL) {
$allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$paymentStatusName = CRM_Core_PseudoConstant::getName('CRM_Pledge_BAO_PledgePayment', 'status_id', $paymentStatusID);
if ($paymentStatusName == 'Cancelled'|| $paymentStatusName == 'Refunded') {
$query = "
SELECT civicrm_pledge_payment.id id
FROM civicrm_pledge_payment
WHERE civicrm_pledge_payment.contribution_id = {$paymentContributionId}
";
$paymentsAffected = CRM_Core_DAO::executeQuery($query);
$paymentIDs = array();
while ($paymentsAffected->fetch()) {
$paymentIDs[] = $paymentsAffected->id;
}
// Reset the affected values by the amount paid more than the scheduled amount
foreach ($paymentIDs as $key => $value) {
$payment = new CRM_Pledge_DAO_PledgePayment();
$payment->id = $value;
if ($payment->find(TRUE)) {
$payment->contribution_id = 'null';
$payment->status_id = array_search('Pending', $allStatus);
$payment->scheduled_date = NULL;
$payment->reminder_date = NULL;
$payment->scheduled_amount = $pledgeScheduledAmount;
$payment->actual_amount = 'null';
$payment->save();
}
}
// Cancel the initial paid amount
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', reset($paymentIDs), 'status_id', $paymentStatusID, 'id');
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', reset($paymentIDs), 'actual_amount', $actualAmount, 'id');
// Add new payment after the last payment for the pledge
$allPayments = self::getPledgePayments($pledgeID);
$lastPayment = array_pop($allPayments);
$pledgeFrequencyUnit = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeID, 'frequency_unit', 'id');
$pledgeFrequencyInterval = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeID, 'frequency_interval', 'id');
$pledgeScheduledDate = $lastPayment['scheduled_date'];
$scheduled_date = CRM_Utils_Date::processDate($pledgeScheduledDate);
$date['year'] = (int) substr($scheduled_date, 0, 4);
$date['month'] = (int) substr($scheduled_date, 4, 2);
$date['day'] = (int) substr($scheduled_date, 6, 2);
$newDate = date('YmdHis', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
$ScheduledDate = CRM_Utils_Date::format(CRM_Utils_Date::intervalAdd($pledgeFrequencyUnit, $pledgeFrequencyInterval, $newDate));
$pledgeParams = array(
'status_id' => array_search('Pending', $allStatus),
'pledge_id' => $pledgeID,
'scheduled_amount' => $pledgeScheduledAmount,
'scheduled_date' => $ScheduledDate,
);
$payment = self::add($pledgeParams);
}
else {
$nextPledgeInstallmentDue = self::getOldestPledgePayment($pledgeID);
if (!$paymentContributionId) {
// means we are editing payment scheduled payment, so get the second pending to update.
$nextPledgeInstallmentDue = self::getOldestPledgePayment($pledgeID, 2);
if (($nextPledgeInstallmentDue['count'] != 1) && ($nextPledgeInstallmentDue['id'] == $pPaymentId)) {
$nextPledgeInstallmentDue = self::getOldestPledgePayment($pledgeID);
}
}
if ($nextPledgeInstallmentDue) {
// not the last scheduled payment and the actual amount is less than the expected , add it to oldest pending.
if (($actualAmount != $pledgeScheduledAmount) && (($actualAmount < $pledgeScheduledAmount) || (($actualAmount - $pledgeScheduledAmount) < $nextPledgeInstallmentDue['amount']))) {
$oldScheduledAmount = $nextPledgeInstallmentDue['amount'];
$newScheduledAmount = $oldScheduledAmount + ($pledgeScheduledAmount - $actualAmount);
// store new amount in oldest pending payment record.
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment',
$nextPledgeInstallmentDue['id'],
'scheduled_amount',
$newScheduledAmount
);
if (CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $nextPledgeInstallmentDue['id'], 'contribution_id', 'id')) {
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment',
$nextPledgeInstallmentDue['id'],
'contribution_id',
$paymentContributionId
);
}
}
elseif (($actualAmount > $pledgeScheduledAmount) && (($actualAmount - $pledgeScheduledAmount) >= $nextPledgeInstallmentDue['amount'])) {
// here the actual amount is greater than expected and also greater than the next installment amount, so update the next installment as complete and again add it to next subsequent pending payment
// set the actual amount of the next pending to '0', set contribution Id to current contribution Id and status as completed
$paymentId = array($nextPledgeInstallmentDue['id']);
self::updatePledgePayments($pledgeID, array_search('Completed', $allStatus), $paymentId, 0, $paymentContributionId);
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $nextPledgeInstallmentDue['id'], 'scheduled_amount', 0, 'id');
if (!$paymentContributionId) {
// means we are editing payment scheduled payment.
$oldestPaymentAmount = self::getOldestPledgePayment($pledgeID, 2);
}
$newActualAmount = round(($actualAmount - $pledgeScheduledAmount), CRM_Utils_Money::getCurrencyPrecision());
$newPledgeScheduledAmount = $nextPledgeInstallmentDue['amount'];
if (!$paymentContributionId) {
$newActualAmount = ($actualAmount - $pledgeScheduledAmount);
$newPledgeScheduledAmount = $oldestPaymentAmount['amount'];
// means we are editing payment scheduled payment, so update scheduled amount.
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment',
$oldestPaymentAmount['id'],
'scheduled_amount',
$newActualAmount
);
}
if ($newActualAmount > 0) {
self::adjustPledgePayment($pledgeID, $newActualAmount, $newPledgeScheduledAmount, $paymentContributionId);
}
}
}
}
}
/**
* Override buildOptions to hack out some statuses.
*
* @todo instead of using & hacking the shared optionGroup contribution_status use a separate one.
*
* @param string $fieldName
* @param string $context
* @param array $props
*
* @return array|bool
*/
public static function buildOptions($fieldName, $context = NULL, $props = array()) {
$result = parent::buildOptions($fieldName, $context, $props);
if ($fieldName == 'status_id') {
$result = CRM_Pledge_BAO_Pledge::buildOptions($fieldName, $context, $props);
$result = array_diff($result, array('Failed', 'In Progress'));
}
return $result;
}
}

View file

@ -0,0 +1,605 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Pledge_BAO_Query extends CRM_Core_BAO_Query {
/**
* Get pledge fields.
*
* @param bool $checkPermission
*
* @return array
*/
public static function getFields($checkPermission = TRUE) {
return CRM_Pledge_BAO_Pledge::exportableFields($checkPermission);
}
/**
* Build select for Pledge.
*
* @param CRM_Contact_BAO_Query $query
*/
public static function select(&$query) {
$statusId = implode(',', array_keys(CRM_Core_PseudoConstant::accountOptionValues("contribution_status", NULL, " AND v.name IN ('Pending', 'Overdue')")));
if (($query->_mode & CRM_Contact_BAO_Query::MODE_PLEDGE) || !empty($query->_returnProperties['pledge_id'])) {
$query->_select['pledge_id'] = 'civicrm_pledge.id as pledge_id';
$query->_element['pledge_id'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
// add pledge select
if (!empty($query->_returnProperties['pledge_amount'])) {
$query->_select['pledge_amount'] = 'civicrm_pledge.amount as pledge_amount';
$query->_element['pledge_amount'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
if (!empty($query->_returnProperties['pledge_original_installment_amount'])) {
$query->_select['pledge_original_installment_amount'] = 'civicrm_pledge.original_installment_amount as pledge_original_installment_amount';
$query->_element['pledge_original_installment_amount'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
if (!empty($query->_returnProperties['installments'])) {
$query->_select['installments'] = 'civicrm_pledge.installments as installments';
$query->_element['installments'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
if (!empty($query->_returnProperties['pledge_create_date'])) {
$query->_select['pledge_create_date'] = 'civicrm_pledge.create_date as pledge_create_date';
$query->_element['pledge_create_date'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
if (!empty($query->_returnProperties['pledge_start_date'])) {
$query->_select['pledge_start_date'] = 'civicrm_pledge.start_date as pledge_start_date';
$query->_element['pledge_start_date'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
if (!empty($query->_returnProperties['pledge_status_id'])) {
$query->_select['pledge_status_id'] = 'pledge_status.value as pledge_status_id';
$query->_element['pledge_status'] = 1;
$query->_tables['pledge_status'] = $query->_whereTables['pledge_status'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
if (!empty($query->_returnProperties['pledge_status'])) {
$query->_select['pledge_status'] = 'pledge_status.label as pledge_status';
$query->_element['pledge_status'] = 1;
$query->_tables['pledge_status'] = $query->_whereTables['pledge_status'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
if (!empty($query->_returnProperties['pledge_total_paid'])) {
$query->_select['pledge_total_paid'] = ' (SELECT sum(civicrm_pledge_payment.actual_amount) FROM civicrm_pledge_payment WHERE civicrm_pledge_payment.pledge_id = civicrm_pledge.id AND civicrm_pledge_payment.status_id = 1 ) as pledge_total_paid';
$query->_element['pledge_total_paid'] = 1;
}
if (!empty($query->_returnProperties['pledge_next_pay_date'])) {
$query->_select['pledge_next_pay_date'] = " (SELECT civicrm_pledge_payment.scheduled_date FROM civicrm_pledge_payment WHERE civicrm_pledge_payment.pledge_id = civicrm_pledge.id AND civicrm_pledge_payment.status_id IN ({$statusId}) ORDER BY civicrm_pledge_payment.scheduled_date ASC LIMIT 0, 1) as pledge_next_pay_date";
$query->_element['pledge_next_pay_date'] = 1;
}
if (!empty($query->_returnProperties['pledge_next_pay_amount'])) {
$query->_select['pledge_next_pay_amount'] = " (SELECT civicrm_pledge_payment.scheduled_amount FROM civicrm_pledge_payment WHERE civicrm_pledge_payment.pledge_id = civicrm_pledge.id AND civicrm_pledge_payment.status_id IN ({$statusId}) ORDER BY civicrm_pledge_payment.scheduled_date ASC LIMIT 0, 1) as pledge_next_pay_amount";
$query->_element['pledge_next_pay_amount'] = 1;
$query->_select['pledge_outstanding_amount'] = " (SELECT sum(civicrm_pledge_payment.scheduled_amount) FROM civicrm_pledge_payment WHERE civicrm_pledge_payment.pledge_id = civicrm_pledge.id AND civicrm_pledge_payment.status_id = 6 ) as pledge_outstanding_amount";
$query->_element['pledge_outstanding_amount'] = 1;
}
if (!empty($query->_returnProperties['pledge_financial_type'])) {
$query->_select['pledge_financial_type'] = "(SELECT civicrm_financial_type.name FROM civicrm_financial_type WHERE civicrm_financial_type.id = civicrm_pledge.financial_type_id) as pledge_financial_type";
$query->_element['pledge_financial_type'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
if (!empty($query->_returnProperties['pledge_contribution_page_id'])) {
$query->_select['pledge_contribution_page_id'] = 'civicrm_pledge.contribution_page_id as pledge_contribution_page_id';
$query->_element['pledge_contribution_page_id'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
if (!empty($query->_returnProperties['pledge_payment_id'])) {
$query->_select['pledge_payment_id'] = 'civicrm_pledge_payment.id as pledge_payment_id';
$query->_element['pledge_payment_id'] = 1;
$query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
}
if (!empty($query->_returnProperties['pledge_payment_scheduled_amount'])) {
$query->_select['pledge_payment_scheduled_amount'] = 'civicrm_pledge_payment.scheduled_amount as pledge_payment_scheduled_amount';
$query->_element['pledge_payment_scheduled_amount'] = 1;
$query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
}
if (!empty($query->_returnProperties['pledge_payment_scheduled_date'])) {
$query->_select['pledge_payment_scheduled_date'] = 'civicrm_pledge_payment.scheduled_date as pledge_payment_scheduled_date';
$query->_element['pledge_payment_scheduled_date'] = 1;
$query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
}
if (!empty($query->_returnProperties['pledge_payment_paid_amount'])) {
$query->_select['pledge_payment_paid_amount'] = 'civicrm_pledge_payment.actual_amount as pledge_payment_paid_amount';
$query->_element['pledge_payment_paid_amount'] = 1;
$query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
}
if (!empty($query->_returnProperties['pledge_payment_paid_date'])) {
$query->_select['pledge_payment_paid_date'] = 'payment_contribution.receive_date as pledge_payment_paid_date';
$query->_element['pledge_payment_paid_date'] = 1;
$query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
$query->_tables['payment_contribution'] = $query->_whereTables['payment_contribution'] = 1;
}
if (!empty($query->_returnProperties['pledge_payment_reminder_date'])) {
$query->_select['pledge_payment_reminder_date'] = 'civicrm_pledge_payment.reminder_date as pledge_payment_reminder_date';
$query->_element['pledge_payment_reminder_date'] = 1;
$query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
}
if (!empty($query->_returnProperties['pledge_payment_reminder_count'])) {
$query->_select['pledge_payment_reminder_count'] = 'civicrm_pledge_payment.reminder_count as pledge_payment_reminder_count';
$query->_element['pledge_payment_reminder_count'] = 1;
$query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
}
if (!empty($query->_returnProperties['pledge_payment_status_id'])) {
$query->_select['pledge_payment_status_id'] = 'payment_status.name as pledge_payment_status_id';
$query->_element['pledge_payment_status_id'] = 1;
$query->_tables['payment_status'] = $query->_whereTables['payment_status'] = 1;
$query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
}
if (!empty($query->_returnProperties['pledge_payment_status'])) {
$query->_select['pledge_payment_status'] = 'payment_status.label as pledge_payment_status';
$query->_element['pledge_payment_status'] = 1;
$query->_tables['payment_status'] = $query->_whereTables['payment_status'] = 1;
$query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
}
if (!empty($query->_returnProperties['pledge_frequency_interval'])) {
$query->_select['pledge_frequency_interval'] = 'civicrm_pledge.frequency_interval as pledge_frequency_interval';
$query->_element['pledge_frequency_interval'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
if (!empty($query->_returnProperties['pledge_frequency_unit'])) {
$query->_select['pledge_frequency_unit'] = 'civicrm_pledge.frequency_unit as pledge_frequency_unit';
$query->_element['pledge_frequency_unit'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
if (!empty($query->_returnProperties['pledge_is_test'])) {
$query->_select['pledge_is_test'] = 'civicrm_pledge.is_test as pledge_is_test';
$query->_element['pledge_is_test'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
if (!empty($query->_returnProperties['pledge_campaign_id'])) {
$query->_select['pledge_campaign_id'] = 'civicrm_pledge.campaign_id as pledge_campaign_id';
$query->_element['pledge_campaign_id'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
if (!empty($query->_returnProperties['pledge_currency'])) {
$query->_select['pledge_currency'] = 'civicrm_pledge.currency as pledge_currency';
$query->_element['pledge_currency'] = 1;
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
}
/**
* @param $query
*/
public static function where(&$query) {
$grouping = NULL;
foreach (array_keys($query->_params) as $id) {
if (empty($query->_params[$id][0])) {
continue;
}
if (substr($query->_params[$id][0], 0, 7) == 'pledge_') {
if ($query->_mode == CRM_Contact_BAO_QUERY::MODE_CONTACTS) {
$query->_useDistinct = TRUE;
}
$grouping = $query->_params[$id][3];
self::whereClauseSingle($query->_params[$id], $query);
}
}
}
/**
* @param $values
* @param $query
*/
public static function whereClauseSingle(&$values, &$query) {
list($name, $op, $value, $grouping, $wildcard) = $values;
switch ($name) {
case 'pledge_create_date_low':
case 'pledge_create_date_high':
// process to / from date
$query->dateQueryBuilder($values,
'civicrm_pledge', 'pledge_create_date', 'create_date', 'Pledge Made'
);
case 'pledge_start_date_low':
case 'pledge_start_date_high':
// process to / from date
$query->dateQueryBuilder($values,
'civicrm_pledge', 'pledge_start_date', 'start_date', 'Pledge Start Date'
);
return;
case 'pledge_end_date_low':
case 'pledge_end_date_high':
// process to / from date
$query->dateQueryBuilder($values,
'civicrm_pledge', 'pledge_end_date', 'end_date', 'Pledge End Date'
);
return;
case 'pledge_payment_date_low':
case 'pledge_payment_date_high':
// process to / from date
$query->dateQueryBuilder($values,
'civicrm_pledge_payment', 'pledge_payment_date', 'scheduled_date', 'Payment Scheduled'
);
return;
case 'pledge_amount':
case 'pledge_amount_low':
case 'pledge_amount_high':
// process min/max amount
$query->numberRangeBuilder($values,
'civicrm_pledge', 'pledge_amount', 'amount', 'Pledge Amount'
);
return;
case 'pledge_installments_low':
case 'pledge_installments_high':
// process min/max amount
$query->numberRangeBuilder($values,
'civicrm_pledge', 'pledge_installments', 'installments', 'Number of Installments'
);
return;
case 'pledge_acknowledge_date_is_not_null':
if ($value) {
$op = "IS NOT NULL";
$query->_qill[$grouping][] = ts('Pledge Acknowledgement Sent');
}
else {
$op = "IS NULL";
$query->_qill[$grouping][] = ts('Pledge Acknowledgement Not Sent');
}
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_pledge.acknowledge_date", $op);
return;
case 'pledge_payment_status_id':
case 'pledge_status_id':
if ($name == 'pledge_status_id') {
$tableName = 'civicrm_pledge';
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
$label = "Pledge Status";
$qillDAO = 'CRM_Pledge_DAO_Pledge';
$qillField = 'status_id';
}
else {
$tableName = 'civicrm_pledge_payment';
$query->_tables['civicrm_pledge_payment'] = $query->_whereTables['civicrm_pledge_payment'] = 1;
$label = "Pledge Payment Status";
$qillDAO = 'CRM_Contribute_DAO_Contribution';
$qillField = 'contribution_status_id';
}
$name = 'status_id';
if (!empty($value) && is_array($value) && !in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
$value = array('IN' => $value);
}
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("$tableName.$name",
$op,
$value,
'Integer'
);
list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue($qillDAO, $qillField, $value, $op);
$query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $label, 2 => $qillop, 3 => $qillVal));
return;
case 'pledge_test':
case 'pledge_is_test':
// We dont want to include all tests for sql OR CRM-7827
if (!$value || $query->getOperator() != 'OR') {
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_pledge.is_test',
$op,
$value,
'Boolean'
);
if ($value) {
$query->_qill[$grouping][] = ts('Pledge is a Test');
}
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
}
return;
case 'pledge_financial_type_id':
$type = CRM_Contribute_PseudoConstant::financialType($value);
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_pledge.financial_type_id',
$op,
$value,
'Integer'
);
$query->_qill[$grouping][] = ts('Financial Type - %1', array(1 => $type));
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
return;
case 'pledge_contribution_page_id':
$page = CRM_Contribute_PseudoConstant::contributionPage($value);
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause('civicrm_pledge.contribution_page_id',
$op,
$value,
'Integer'
);
$query->_qill[$grouping][] = ts('Financial Page - %1', array(1 => $page));
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
return;
case 'pledge_id':
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_pledge.id",
$op,
$value,
"Integer"
);
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
return;
case 'pledge_frequency_interval':
$query->_where[$grouping][] = "civicrm_pledge.frequency_interval $op $value";
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
return;
case 'pledge_frequency_unit':
$query->_where[$grouping][] = "civicrm_pledge.frequency_unit $op $value";
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
return;
case 'pledge_contact_id':
case 'pledge_campaign_id':
$name = str_replace('pledge_', '', $name);
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_pledge.$name", $op, $value, 'Integer');
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Pledge_DAO_Pledge', $name, $value, $op);
$label = ($name == 'campaign_id') ? 'Campaign' : 'Contact ID';
$query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $label, 2 => $op, 3 => $value));
$query->_tables['civicrm_pledge'] = $query->_whereTables['civicrm_pledge'] = 1;
return;
}
}
/**
* From clause.
*
* @param string $name
* @param string $mode
* @param string $side
*
* @return null|string
*/
public static function from($name, $mode, $side) {
$from = NULL;
switch ($name) {
case 'civicrm_pledge':
$from = " $side JOIN civicrm_pledge ON civicrm_pledge.contact_id = contact_a.id ";
break;
case 'pledge_status':
$from .= " $side JOIN civicrm_option_group option_group_pledge_status ON (option_group_pledge_status.name = 'pledge_status')";
$from .= " $side JOIN civicrm_option_value pledge_status ON (civicrm_pledge.status_id = pledge_status.value AND option_group_pledge_status.id = pledge_status.option_group_id ) ";
break;
case 'pledge_financial_type':
$from .= " $side JOIN civicrm_financial_type ON civicrm_pledge.financial_type_id = civicrm_financial_type.id ";
break;
case 'civicrm_pledge_payment':
$from .= " $side JOIN civicrm_pledge_payment ON civicrm_pledge_payment.pledge_id = civicrm_pledge.id ";
break;
case 'payment_contribution':
$from .= " $side JOIN civicrm_contribution payment_contribution ON civicrm_pledge_payment.contribution_id = payment_contribution.id ";
break;
case 'payment_status':
$from .= " $side JOIN civicrm_option_group option_group_payment_status ON (option_group_payment_status.name = 'contribution_status')";
$from .= " $side JOIN civicrm_option_value payment_status ON (civicrm_pledge_payment.status_id = payment_status.value AND option_group_payment_status.id = payment_status.option_group_id ) ";
break;
}
return $from;
}
/**
* Ideally this function should include fields that are displayed in the selector.
*
* @param int $mode
* @param bool $includeCustomFields
*
* @return array|null
*/
public static function defaultReturnProperties(
$mode,
$includeCustomFields = TRUE
) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_PLEDGE) {
$properties = array(
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
'display_name' => 1,
'pledge_id' => 1,
'pledge_amount' => 1,
'pledge_total_paid' => 1,
'pledge_create_date' => 1,
'pledge_start_date' => 1,
'pledge_next_pay_date' => 1,
'pledge_next_pay_amount' => 1,
'pledge_status' => 1,
'pledge_status_id' => 1,
'pledge_is_test' => 1,
'pledge_contribution_page_id' => 1,
'pledge_financial_type' => 1,
'pledge_frequency_interval' => 1,
'pledge_frequency_unit' => 1,
'pledge_currency' => 1,
'pledge_campaign_id' => 1,
);
}
return $properties;
}
/**
* This includes any extra fields that might need for export etc.
*
* @param string $mode
*
* @return array|null
*/
public static function extraReturnProperties($mode) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_PLEDGE) {
$properties = array(
'pledge_balance_amount' => 1,
'pledge_payment_id' => 1,
'pledge_payment_scheduled_amount' => 1,
'pledge_payment_scheduled_date' => 1,
'pledge_payment_paid_amount' => 1,
'pledge_payment_paid_date' => 1,
'pledge_payment_reminder_date' => 1,
'pledge_payment_reminder_count' => 1,
'pledge_payment_status_id' => 1,
'pledge_payment_status' => 1,
);
// also get all the custom pledge properties
$fields = CRM_Core_BAO_CustomField::getFieldsForImport('Pledge');
if (!empty($fields)) {
foreach ($fields as $name => $dontCare) {
$properties[$name] = 1;
}
}
}
return $properties;
}
/**
* @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
);
self::addCustomFormFields($form, array('Pledge'));
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'pledge_campaign_id');
$form->assign('validCiviPledge', TRUE);
$form->setDefaults(array('pledge_test' => 0));
}
/**
* @param $tables
*/
public static function tableNames(&$tables) {
// add status table
if (!empty($tables['pledge_status']) || !empty($tables['civicrm_pledge_payment'])) {
$tables = array_merge(array('civicrm_pledge' => 1), $tables);
}
}
}

View file

@ -0,0 +1,67 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is used by the Search functionality.
*
* - the search controller is used for building/processing multiform
* searches.
*
* Typically the first form will display the search criteria and its results.
*
* The second form is used to process search results with the associated actions.
*/
class CRM_Pledge_Controller_Search extends CRM_Core_Controller {
/**
* Class constructor.
*
* @param string $title
* @param bool|int $action
* @param bool $modal
*/
public function __construct($title = NULL, $action = CRM_Core_Action::NONE, $modal = TRUE) {
parent::__construct($title, $modal);
$this->_stateMachine = new CRM_Pledge_StateMachine_Search($this, $action);
// create and instantiate the pages
$this->addPages($this->_stateMachine, $action);
// add all the actions
$config = CRM_Core_Config::singleton();
$this->addActions();
}
}

View file

@ -0,0 +1,679 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Pledge/Pledge.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:0e2129564a1877226e6dfce2840ce831)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Pledge_DAO_Pledge constructor.
*/
class CRM_Pledge_DAO_Pledge extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_pledge';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Pledge ID
*
* @var int unsigned
*/
public $id;
/**
* Foreign key to civicrm_contact.id .
*
* @var int unsigned
*/
public $contact_id;
/**
* FK to Financial Type
*
* @var int unsigned
*/
public $financial_type_id;
/**
* The Contribution Page which triggered this contribution
*
* @var int unsigned
*/
public $contribution_page_id;
/**
* Total pledged amount.
*
* @var float
*/
public $amount;
/**
* Original amount for each of the installments.
*
* @var float
*/
public $original_installment_amount;
/**
* 3 character string, value from config setting or input via user.
*
* @var string
*/
public $currency;
/**
* Time units for recurrence of pledge payments.
*
* @var string
*/
public $frequency_unit;
/**
* Number of time units for recurrence of pledge payments.
*
* @var int unsigned
*/
public $frequency_interval;
/**
* Day in the period when the pledge payment is due e.g. 1st of month, 15th etc. Use this to set the scheduled dates for pledge payments.
*
* @var int unsigned
*/
public $frequency_day;
/**
* Total number of payments to be made.
*
* @var int unsigned
*/
public $installments;
/**
* The date the first scheduled pledge occurs.
*
* @var datetime
*/
public $start_date;
/**
* When this pledge record was created.
*
* @var datetime
*/
public $create_date;
/**
* When a pledge acknowledgement message was sent to the contributor.
*
* @var datetime
*/
public $acknowledge_date;
/**
* Last updated date for this pledge record.
*
* @var datetime
*/
public $modified_date;
/**
* Date this pledge was cancelled by contributor.
*
* @var datetime
*/
public $cancel_date;
/**
* Date this pledge finished successfully (total pledge payments equal to or greater than pledged amount).
*
* @var datetime
*/
public $end_date;
/**
* The maximum number of payment reminders to send for any given payment.
*
* @var int unsigned
*/
public $max_reminders;
/**
* Send initial reminder this many days prior to the payment due date.
*
* @var int unsigned
*/
public $initial_reminder_day;
/**
* Send additional reminder this many days after last one sent, up to maximum number of reminders.
*
* @var int unsigned
*/
public $additional_reminder_day;
/**
* Implicit foreign key to civicrm_option_values in the pledge_status option group.
*
* @var int unsigned
*/
public $status_id;
/**
*
* @var boolean
*/
public $is_test;
/**
* The campaign for which this pledge has been initiated.
*
* @var int unsigned
*/
public $campaign_id;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_pledge';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_page_id', 'civicrm_contribution_page', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'pledge_id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Pledge ID') ,
'description' => 'Pledge ID',
'required' => true,
'import' => true,
'where' => 'civicrm_pledge.id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
) ,
'pledge_contact_id' => array(
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contact ID') ,
'description' => 'Foreign key to civicrm_contact.id .',
'required' => true,
'import' => true,
'where' => 'civicrm_pledge.contact_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
'html' => array(
'type' => 'EntityRef',
) ,
) ,
'pledge_financial_type_id' => array(
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Type') ,
'description' => 'FK to Financial Type',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
)
) ,
'pledge_contribution_page_id' => array(
'name' => 'contribution_page_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Pledge Contribution Page') ,
'description' => 'The Contribution Page which triggered this contribution',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_ContributionPage',
) ,
'pledge_amount' => array(
'name' => 'amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Total Pledged') ,
'description' => 'Total pledged amount.',
'required' => true,
'precision' => array(
20,
2
) ,
'import' => true,
'where' => 'civicrm_pledge.amount',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'pledge_original_installment_amount' => array(
'name' => 'original_installment_amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Original Installment Amount') ,
'description' => 'Original amount for each of the installments.',
'required' => true,
'precision' => array(
20,
2
) ,
'export' => true,
'where' => 'civicrm_pledge.original_installment_amount',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'currency' => array(
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Pledge Currency') ,
'description' => '3 character string, value from config setting or input via user.',
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
'default' => 'NULL',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
)
) ,
'pledge_frequency_unit' => array(
'name' => 'frequency_unit',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Pledge Frequency Unit') ,
'description' => 'Time units for recurrence of pledge payments.',
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'default' => 'month',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'recur_frequency_units',
'keyColumn' => 'name',
'optionEditPath' => 'civicrm/admin/options/recur_frequency_units',
)
) ,
'pledge_frequency_interval' => array(
'name' => 'frequency_interval',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Pledge Frequency Interval') ,
'description' => 'Number of time units for recurrence of pledge payments.',
'required' => true,
'default' => '1',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'frequency_day' => array(
'name' => 'frequency_day',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Pledge day') ,
'description' => 'Day in the period when the pledge payment is due e.g. 1st of month, 15th etc. Use this to set the scheduled dates for pledge payments.',
'required' => true,
'default' => '3',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
) ,
'installments' => array(
'name' => 'installments',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Pledge Number of Installments') ,
'description' => 'Total number of payments to be made.',
'export' => true,
'where' => 'civicrm_pledge.installments',
'headerPattern' => '',
'dataPattern' => '',
'default' => '1',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'start_date' => array(
'name' => 'start_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Pledge Start Date') ,
'description' => 'The date the first scheduled pledge occurs.',
'required' => true,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
) ,
) ,
'pledge_create_date' => array(
'name' => 'create_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Pledge Made') ,
'description' => 'When this pledge record was created.',
'required' => true,
'import' => true,
'where' => 'civicrm_pledge.create_date',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
) ,
) ,
'acknowledge_date' => array(
'name' => 'acknowledge_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Pledge Acknowledged') ,
'description' => 'When a pledge acknowledgement message was sent to the contributor.',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
) ,
) ,
'modified_date' => array(
'name' => 'modified_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Pledge Modified Date') ,
'description' => 'Last updated date for this pledge record.',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
) ,
'cancel_date' => array(
'name' => 'cancel_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Pledge Cancelled Date') ,
'description' => 'Date this pledge was cancelled by contributor.',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
) ,
) ,
'end_date' => array(
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Pledge End Date') ,
'description' => 'Date this pledge finished successfully (total pledge payments equal to or greater than pledged amount).',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
) ,
) ,
'max_reminders' => array(
'name' => 'max_reminders',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Maximum Number of Reminders') ,
'description' => 'The maximum number of payment reminders to send for any given payment.',
'default' => '1',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'initial_reminder_day' => array(
'name' => 'initial_reminder_day',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Initial Reminder Day') ,
'description' => 'Send initial reminder this many days prior to the payment due date.',
'default' => '5',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
) ,
'additional_reminder_day' => array(
'name' => 'additional_reminder_day',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Additional Reminder Days') ,
'description' => 'Send additional reminder this many days after last one sent, up to maximum number of reminders.',
'default' => '5',
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'pledge_status_id' => array(
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Pledge Status Id') ,
'description' => 'Implicit foreign key to civicrm_option_values in the pledge_status option group.',
'import' => true,
'where' => 'civicrm_pledge.status_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => false,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'pseudoconstant' => array(
'optionGroupName' => 'pledge_status',
'optionEditPath' => 'civicrm/admin/options/pledge_status',
)
) ,
'pledge_is_test' => array(
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Test') ,
'import' => true,
'where' => 'civicrm_pledge.is_test',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'html' => array(
'type' => 'CheckBox',
) ,
) ,
'pledge_campaign_id' => array(
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Campaign') ,
'description' => 'The campaign for which this pledge has been initiated.',
'import' => true,
'where' => 'civicrm_pledge.campaign_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_pledge',
'entity' => 'Pledge',
'bao' => 'CRM_Pledge_BAO_Pledge',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
)
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'index_status' => array(
'name' => 'index_status',
'field' => array(
0 => 'status_id',
) ,
'localizable' => false,
'sig' => 'civicrm_pledge::0::status_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,343 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Pledge/PledgeBlock.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:27ee8365a58c51c15fcf0ae78b2f5f32)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Pledge_DAO_PledgeBlock constructor.
*/
class CRM_Pledge_DAO_PledgeBlock extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_pledge_block';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Pledge ID
*
* @var int unsigned
*/
public $id;
/**
* physical tablename for entity being joined to pledge, e.g. civicrm_contact
*
* @var string
*/
public $entity_table;
/**
* FK to entity table specified in entity_table column.
*
* @var int unsigned
*/
public $entity_id;
/**
* Delimited list of supported frequency units
*
* @var string
*/
public $pledge_frequency_unit;
/**
* Is frequency interval exposed on the contribution form.
*
* @var boolean
*/
public $is_pledge_interval;
/**
* The maximum number of payment reminders to send for any given payment.
*
* @var int unsigned
*/
public $max_reminders;
/**
* Send initial reminder this many days prior to the payment due date.
*
* @var int unsigned
*/
public $initial_reminder_day;
/**
* Send additional reminder this many days after last one sent, up to maximum number of reminders.
*
* @var int unsigned
*/
public $additional_reminder_day;
/**
* The date the first scheduled pledge occurs.
*
* @var string
*/
public $pledge_start_date;
/**
* If true - recurring start date is shown.
*
* @var boolean
*/
public $is_pledge_start_date_visible;
/**
* If true - recurring start date is editable.
*
* @var boolean
*/
public $is_pledge_start_date_editable;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_pledge_block';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Pledge Block ID') ,
'description' => 'Pledge ID',
'required' => true,
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
) ,
'entity_table' => array(
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Entity Table') ,
'description' => 'physical tablename for entity being joined to pledge, e.g. civicrm_contact',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
) ,
'entity_id' => array(
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Entity Id') ,
'description' => 'FK to entity table specified in entity_table column.',
'required' => true,
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
) ,
'pledge_frequency_unit' => array(
'name' => 'pledge_frequency_unit',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Pledge Frequency Unit') ,
'description' => 'Delimited list of supported frequency units',
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
) ,
'is_pledge_interval' => array(
'name' => 'is_pledge_interval',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Expose Frequency Interval?') ,
'description' => 'Is frequency interval exposed on the contribution form.',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
) ,
'max_reminders' => array(
'name' => 'max_reminders',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Maximum Number of Reminders') ,
'description' => 'The maximum number of payment reminders to send for any given payment.',
'default' => '1',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
) ,
'initial_reminder_day' => array(
'name' => 'initial_reminder_day',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Initial Reminder Day') ,
'description' => 'Send initial reminder this many days prior to the payment due date.',
'default' => '5',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
) ,
'additional_reminder_day' => array(
'name' => 'additional_reminder_day',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Additional Reminder Days') ,
'description' => 'Send additional reminder this many days after last one sent, up to maximum number of reminders.',
'default' => '5',
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
) ,
'pledge_start_date' => array(
'name' => 'pledge_start_date',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Pledge Start Date') ,
'description' => 'The date the first scheduled pledge occurs.',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
) ,
'is_pledge_start_date_visible' => array(
'name' => 'is_pledge_start_date_visible',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Show Recurring Donation Start Date?') ,
'description' => 'If true - recurring start date is shown.',
'required' => true,
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
) ,
'is_pledge_start_date_editable' => array(
'name' => 'is_pledge_start_date_editable',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Allow Edits to Recurring Donation Start Date?') ,
'description' => 'If true - recurring start date is editable.',
'required' => true,
'table_name' => 'civicrm_pledge_block',
'entity' => 'PledgeBlock',
'bao' => 'CRM_Pledge_BAO_PledgeBlock',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge_block', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge_block', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'index_entity' => array(
'name' => 'index_entity',
'field' => array(
0 => 'entity_table',
1 => 'entity_id',
) ,
'localizable' => false,
'sig' => 'civicrm_pledge_block::0::entity_table::entity_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,384 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Pledge/PledgePayment.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:37953335e5e08db4328298ec003c97a8)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Pledge_DAO_PledgePayment constructor.
*/
class CRM_Pledge_DAO_PledgePayment extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_pledge_payment';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
*
* @var int unsigned
*/
public $id;
/**
* FK to Pledge table
*
* @var int unsigned
*/
public $pledge_id;
/**
* FK to contribution table.
*
* @var int unsigned
*/
public $contribution_id;
/**
* Pledged amount for this payment (the actual contribution amount might be different).
*
* @var float
*/
public $scheduled_amount;
/**
* Actual amount that is paid as the Pledged installment amount.
*
* @var float
*/
public $actual_amount;
/**
* 3 character string, value from config setting or input via user.
*
* @var string
*/
public $currency;
/**
* The date the pledge payment is supposed to happen.
*
* @var datetime
*/
public $scheduled_date;
/**
* The date that the most recent payment reminder was sent.
*
* @var datetime
*/
public $reminder_date;
/**
* The number of payment reminders sent.
*
* @var int unsigned
*/
public $reminder_count;
/**
*
* @var int unsigned
*/
public $status_id;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_pledge_payment';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'pledge_id', 'civicrm_pledge', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_id', 'civicrm_contribution', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'pledge_payment_id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Payment ID') ,
'required' => true,
'import' => true,
'where' => 'civicrm_pledge_payment.id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
) ,
'pledge_id' => array(
'name' => 'pledge_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Pledge') ,
'description' => 'FK to Pledge table',
'required' => true,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
'FKClassName' => 'CRM_Pledge_DAO_Pledge',
) ,
'contribution_id' => array(
'name' => 'contribution_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contribution') ,
'description' => 'FK to contribution table.',
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_Contribution',
) ,
'pledge_payment_scheduled_amount' => array(
'name' => 'scheduled_amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Scheduled Amount') ,
'description' => 'Pledged amount for this payment (the actual contribution amount might be different).',
'required' => true,
'precision' => array(
20,
2
) ,
'import' => true,
'where' => 'civicrm_pledge_payment.scheduled_amount',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
) ,
'pledge_payment_actual_amount' => array(
'name' => 'actual_amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Actual Amount') ,
'description' => 'Actual amount that is paid as the Pledged installment amount.',
'precision' => array(
20,
2
) ,
'import' => true,
'where' => 'civicrm_pledge_payment.actual_amount',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
) ,
'currency' => array(
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Currency') ,
'description' => '3 character string, value from config setting or input via user.',
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
'default' => 'NULL',
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
)
) ,
'pledge_payment_scheduled_date' => array(
'name' => 'scheduled_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Scheduled Date') ,
'description' => 'The date the pledge payment is supposed to happen.',
'required' => true,
'import' => true,
'where' => 'civicrm_pledge_payment.scheduled_date',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
) ,
'pledge_payment_reminder_date' => array(
'name' => 'reminder_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Last Reminder') ,
'description' => 'The date that the most recent payment reminder was sent.',
'import' => true,
'where' => 'civicrm_pledge_payment.reminder_date',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
) ,
'pledge_payment_reminder_count' => array(
'name' => 'reminder_count',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Reminders Sent') ,
'description' => 'The number of payment reminders sent.',
'import' => true,
'where' => 'civicrm_pledge_payment.reminder_count',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
) ,
'pledge_payment_status_id' => array(
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Payment Status') ,
'import' => true,
'where' => 'civicrm_pledge_payment.status_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => false,
'table_name' => 'civicrm_pledge_payment',
'entity' => 'PledgePayment',
'bao' => 'CRM_Pledge_BAO_PledgePayment',
'localizable' => 0,
'pseudoconstant' => array(
'optionGroupName' => 'contribution_status',
'optionEditPath' => 'civicrm/admin/options/contribution_status',
)
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'pledge_payment', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'pledge_payment', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'index_contribution_pledge' => array(
'name' => 'index_contribution_pledge',
'field' => array(
0 => 'contribution_id',
1 => 'pledge_id',
) ,
'localizable' => false,
'sig' => 'civicrm_pledge_payment::0::contribution_id::pledge_id',
) ,
'index_status' => array(
'name' => 'index_status',
'field' => array(
0 => 'status_id',
) ,
'localizable' => false,
'sig' => 'civicrm_pledge_payment::0::status_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,175 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for processing a pledge payment.
*/
class CRM_Pledge_Form_Payment extends CRM_Core_Form {
/**
* The id of the pledge payment that we are proceessing.
*
* @var int
*/
public $_id;
/**
* Set variables up before form is built.
*/
public function preProcess() {
// check for edit permission
if (!CRM_Core_Permission::check('edit pledges')) {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
$this->_id = CRM_Utils_Request::retrieve('ppId', 'Positive', $this);
CRM_Utils_System::setTitle(ts('Edit Scheduled Pledge Payment'));
}
/**
* Set default values for the form.
* the default values are retrieved from the database.
*/
public function setDefaultValues() {
$defaults = array();
if ($this->_id) {
$params['id'] = $this->_id;
CRM_Pledge_BAO_PledgePayment::retrieve($params, $defaults);
list($defaults['scheduled_date']) = CRM_Utils_Date::setDateDefaults($defaults['scheduled_date']);
if (isset($defaults['contribution_id'])) {
$this->assign('pledgePayment', TRUE);
}
$status = CRM_Core_PseudoConstant::getName('CRM_Pledge_BAO_Pledge', 'status_id', $defaults['status_id']);
$this->assign('status', $status);
}
$defaults['option_type'] = 1;
return $defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
// add various dates
$this->addDate('scheduled_date', ts('Scheduled Date'), TRUE);
$this->addMoney('scheduled_amount',
ts('Scheduled Amount'), TRUE,
array('readonly' => TRUE),
TRUE,
'currency',
NULL,
TRUE
);
$optionTypes = array(
'1' => ts('Adjust Pledge Payment Schedule?'),
'2' => ts('Adjust Total Pledge Amount?'),
);
$element = $this->addRadio('option_type',
NULL,
$optionTypes,
array(), '<br/>'
);
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Save'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
/**
* Process the form submission.
*/
public function postProcess() {
// get the submitted form values.
$formValues = $this->controller->exportValues($this->_name);
$params = array();
$formValues['scheduled_date'] = CRM_Utils_Date::processDate($formValues['scheduled_date']);
$params['scheduled_date'] = CRM_Utils_Date::format($formValues['scheduled_date']);
$params['currency'] = CRM_Utils_Array::value('currency', $formValues);
$now = date('Ymd');
if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($params['scheduled_date'], '%Y%m%d'), $now)) {
$params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Overdue');
}
else {
$params['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
}
$params['id'] = $this->_id;
$pledgeId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $params['id'], 'pledge_id');
CRM_Pledge_BAO_PledgePayment::add($params);
$adjustTotalAmount = FALSE;
if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
$adjustTotalAmount = TRUE;
}
$pledgeScheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
$params['id'],
'scheduled_amount',
'id'
);
$oldestPaymentAmount = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId, 2);
if (($oldestPaymentAmount['count'] != 1) && ($oldestPaymentAmount['id'] == $params['id'])) {
$oldestPaymentAmount = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
}
if (($formValues['scheduled_amount'] - $pledgeScheduledAmount) >= $oldestPaymentAmount['amount']) {
$adjustTotalAmount = TRUE;
}
// update pledge status
CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId,
array($params['id']),
$params['status_id'],
NULL,
$formValues['scheduled_amount'],
$adjustTotalAmount
);
$statusMsg = ts('Pledge Payment Schedule has been updated.');
CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
}
}

View file

@ -0,0 +1,645 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for processing a pledge
*/
class CRM_Pledge_Form_Pledge extends CRM_Core_Form {
public $_action;
/**
* The id of the pledge that we are proceessing.
*
* @var int
*/
public $_id;
/**
* The id of the contact associated with this pledge.
*
* @var int
*/
public $_contactID;
/**
* The Pledge values if an existing pledge.
*/
public $_values;
/**
* The Pledge frequency Units.
*/
public $_freqUnits;
/**
* Is current pledge pending.
*/
public $_isPending = FALSE;
/**
* Set variables up before form is built.
*/
public function preProcess() {
$this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
$this->_action = CRM_Utils_Request::retrieve('action', 'String',
$this, FALSE, 'add'
);
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
$this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
// check for action permissions.
if (!CRM_Core_Permission::checkActionPermission('CiviPledge', $this->_action)) {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
$this->assign('action', $this->_action);
$this->assign('context', $this->_context);
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
$this->userDisplayName = $this->userEmail = NULL;
if ($this->_contactID) {
list($this->userDisplayName,
$this->userEmail
) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
$this->assign('displayName', $this->userDisplayName);
}
$this->setPageTitle(ts('Pledge'));
// build custom data
CRM_Custom_Form_CustomData::preProcess($this, NULL, NULL, 1, 'Pledge', $this->_id);
$this->_values = array();
// current pledge id
if ($this->_id) {
// get the contribution id
$this->_contributionID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
$this->_id, 'contribution_id', 'pledge_id'
);
$params = array('id' => $this->_id);
CRM_Pledge_BAO_Pledge::getValues($params, $this->_values);
$this->_isPending = (CRM_Pledge_BAO_Pledge::pledgeHasFinancialTransactions($this->_id, CRM_Utils_Array::value('status_id', $this->_values))) ? FALSE : TRUE;
}
// get the pledge frequency units.
$this->_freqUnits = CRM_Core_OptionGroup::values('recur_frequency_units');
$this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
}
/**
* Set default values for the form.
* The default values are retrieved from the database.
*/
public function setDefaultValues() {
$defaults = $this->_values;
$fields = array();
if ($this->_action & CRM_Core_Action::DELETE) {
return $defaults;
}
if (!empty($defaults['is_test'])) {
$this->assign('is_test', TRUE);
}
if ($this->_id) {
$startDate = CRM_Utils_Array::value('start_date', $this->_values);
$createDate = CRM_Utils_Array::value('create_date', $this->_values);
list($defaults['start_date']) = CRM_Utils_Date::setDateDefaults($startDate);
list($defaults['create_date']) = CRM_Utils_Date::setDateDefaults($createDate);
if ($ackDate = CRM_Utils_Array::value('acknowledge_date', $this->_values)) {
list($defaults['acknowledge_date']) = CRM_Utils_Date::setDateDefaults($ackDate);
}
// check is this pledge pending.
// fix the display of the monetary value, CRM-4038.
if ($this->_isPending) {
$defaults['eachPaymentAmount'] = $this->_values['amount'] / $this->_values['installments'];
$defaults['eachPaymentAmount'] = CRM_Utils_Money::format($defaults['eachPaymentAmount'], NULL, '%a');
}
else {
$this->assign('start_date', $startDate);
$this->assign('create_date', $createDate);
}
// fix the display of the monetary value, CRM-4038
if (isset($this->_values['amount'])) {
$defaults['amount'] = CRM_Utils_Money::format($this->_values['amount'], NULL, '%a');
}
$this->assign('amount', $this->_values['amount']);
$this->assign('installments', $defaults['installments']);
}
else {
// default values.
list($now) = CRM_Utils_Date::setDateDefaults();
$defaults['create_date'] = $now;
$defaults['start_date'] = $now;
$defaults['installments'] = 12;
$defaults['frequency_interval'] = 1;
$defaults['frequency_day'] = 1;
$defaults['initial_reminder_day'] = 5;
$defaults['max_reminders'] = 1;
$defaults['additional_reminder_day'] = 5;
$defaults['frequency_unit'] = array_search('month', $this->_freqUnits);
$defaults['financial_type_id'] = array_search('Donation', CRM_Contribute_PseudoConstant::financialType());
}
$pledgeStatus = CRM_Pledge_BAO_Pledge::buildOptions('status_id');
$pledgeStatusNames = CRM_Core_OptionGroup::values('pledge_status',
FALSE, FALSE, FALSE, NULL, 'name', TRUE
);
// get default status label (pending)
$defaultPledgeStatus = CRM_Utils_Array::value(array_search('Pending', $pledgeStatusNames),
$pledgeStatus
);
// assign status.
$this->assign('status', CRM_Utils_Array::value(CRM_Utils_Array::value('status_id', $this->_values),
$pledgeStatus,
$defaultPledgeStatus
));
if (isset($this->userEmail)) {
$this->assign('email', $this->userEmail);
}
// custom data set defaults
$defaults += CRM_Custom_Form_CustomData::setDefaultValues($this);
return $defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
if ($this->_action & CRM_Core_Action::DELETE) {
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Delete'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
return;
}
if ($this->_context == 'standalone') {
$this->addEntityRef('contact_id', ts('Contact'), array(
'create' => TRUE,
'api' => array('extra' => array('email')),
), TRUE);
}
$showAdditionalInfo = FALSE;
$this->_formType = CRM_Utils_Array::value('formType', $_GET);
$defaults = array();
$paneNames = array(
'Payment Reminders' => 'PaymentReminders',
);
foreach ($paneNames as $name => $type) {
$urlParams = "snippet=4&formType={$type}";
$allPanes[$name] = array(
'url' => CRM_Utils_System::url('civicrm/contact/view/pledge', $urlParams),
'open' => 'false',
'id' => $type,
);
// see if we need to include this paneName in the current form
if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
CRM_Utils_Array::value("hidden_{$type}", $defaults)
) {
$showAdditionalInfo = TRUE;
$allPanes[$name]['open'] = 'true';
}
$fnName = "build{$type}";
CRM_Contribute_Form_AdditionalInfo::$fnName($this);
}
$this->assign('allPanes', $allPanes);
$this->assign('showAdditionalInfo', $showAdditionalInfo);
if ($this->_formType) {
$this->assign('formType', $this->_formType);
return;
}
$this->applyFilter('__ALL__', 'trim');
// pledge fields.
$attributes = CRM_Core_DAO::getAttribute('CRM_Pledge_DAO_Pledge');
$this->assign('isPending', $this->_isPending);
$js = array(
'onblur' => "calculatedPaymentAmount( );",
'onkeyup' => "calculatedPaymentAmount( );",
);
$currencyFreeze = FALSE;
if ($this->_id &&
!$this->_isPending
) {
$currencyFreeze = TRUE;
}
$element = $this->addMoney('amount', ts('Total Pledge Amount'), TRUE,
array_merge($attributes['pledge_amount'], $js), TRUE,
'currency', NULL, $currencyFreeze
);
if ($this->_id &&
!$this->_isPending
) {
$element->freeze();
}
$element = &$this->add('text', 'installments', ts('To be paid in'),
array_merge($attributes['installments'], $js), TRUE
);
$this->addRule('installments', ts('Please enter a valid number of installments.'), 'positiveInteger');
if ($this->_id &&
!$this->_isPending
) {
$element->freeze();
}
$element = &$this->add('text', 'frequency_interval', ts('every'),
$attributes['pledge_frequency_interval'], TRUE
);
$this->addRule('frequency_interval', ts('Please enter a number for frequency (e.g. every "3" months).'), 'positiveInteger');
if ($this->_id &&
!$this->_isPending
) {
$element->freeze();
}
// Fix frequency unit display for use with frequency_interval
$freqUnitsDisplay = array();
foreach ($this->_freqUnits as $val => $label) {
$freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
}
$element = &$this->add('select', 'frequency_unit',
ts('Frequency'),
array('' => ts('- select -')) + $freqUnitsDisplay,
TRUE
);
if ($this->_id &&
!$this->_isPending
) {
$element->freeze();
}
$element = &$this->add('text', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], TRUE);
$this->addRule('frequency_day', ts('Please enter a valid payment due day.'), 'positiveInteger');
if ($this->_id &&
!$this->_isPending
) {
$element->freeze();
}
$this->add('text', 'eachPaymentAmount', ts('each'), array(
'size' => 10,
'style' => "background-color:#EBECE4",
0 => 'READONLY', // WTF, preserved because its inexplicable
));
// add various dates
if (!$this->_id || $this->_isPending) {
$this->addDate('create_date', ts('Pledge Made'), TRUE);
$this->addDate('start_date', ts('Payments Start'), TRUE);
}
if (!empty($this->_values['currency'])) {
$this->assign('currency', $this->_values['currency']);
}
elseif (!empty($this->_submitValues['currency'])) {
$this->assign('currency', $this->_submitValues['currency']);
}
if ($this->_id &&
!$this->_isPending
) {
$eachPaymentAmount = $this->_values['original_installment_amount'];
$this->assign('eachPaymentAmount', $eachPaymentAmount);
$this->assign('hideCalender', TRUE);
}
if (CRM_Utils_Array::value('status_id', $this->_values) !=
CRM_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled')
) {
$this->addElement('checkbox', 'is_acknowledge', ts('Send Acknowledgment?'), NULL,
array('onclick' => "showHideByValue( 'is_acknowledge', '', 'acknowledgeDate', 'table-row', 'radio', true); showHideByValue( 'is_acknowledge', '', 'fromEmail', 'table-row', 'radio', false );")
);
$this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
}
$this->addDate('acknowledge_date', ts('Acknowledgment Date'));
$this->add('select', 'financial_type_id',
ts('Financial Type'),
array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(),
TRUE
);
// CRM-7362 --add campaigns.
CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
$pageIds = array();
CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgeBlock', 'entity_table',
'civicrm_contribution_page', $pageIds, array('entity_id')
);
$pages = CRM_Contribute_PseudoConstant::contributionPage();
$pledgePages = array();
foreach ($pageIds as $key => $value) {
$pledgePages[$value['entity_id']] = $pages[$value['entity_id']];
}
$ele = $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'),
array('' => ts('- select -')) + $pledgePages
);
$mailingInfo = Civi::settings()->get('mailing_backend');
$this->assign('outBound_option', $mailingInfo['outBound_option']);
// build custom data
CRM_Custom_Form_CustomData::buildQuickForm($this);
// make this form an upload since we dont know if the custom data injected dynamically
// is of type file etc $uploadNames = $this->get( 'uploadNames' );
$this->addButtons(array(
array(
'type' => 'upload',
'name' => ts('Save'),
'js' => array('onclick' => "return verify( );"),
'isDefault' => TRUE,
),
array(
'type' => 'upload',
'name' => ts('Save and New'),
'js' => array('onclick' => "return verify( );"),
'subName' => 'new',
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
$this->addFormRule(array('CRM_Pledge_Form_Pledge', 'formRule'), $this);
if ($this->_action & CRM_Core_Action::VIEW) {
$this->freeze();
}
}
/**
* Global form rule.
*
* @param array $fields
* The input form values.
* @param array $files
* The uploaded files if any.
* @param $self
*
*
* @return bool|array
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
$errors = array();
if ($fields['amount'] <= 0) {
$errors['amount'] = ts('Total Pledge Amount should be greater than zero.');
}
if ($fields['installments'] <= 0) {
$errors['installments'] = ts('Installments should be greater than zero.');
}
if ($fields['frequency_unit'] != 'week') {
if ($fields['frequency_day'] > 31 || $fields['frequency_day'] == 0) {
$errors['frequency_day'] = ts('Please enter a valid frequency day ie. 1 through 31.');
}
}
elseif ($fields['frequency_unit'] == 'week') {
if ($fields['frequency_day'] > 7 || $fields['frequency_day'] == 0) {
$errors['frequency_day'] = ts('Please enter a valid frequency day ie. 1 through 7.');
}
}
return $errors;
}
/**
* 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();
$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);
}
// 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}"
));
}
}
}

View file

@ -0,0 +1,143 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for Pledge
*/
class CRM_Pledge_Form_PledgeView extends CRM_Core_Form {
/**
* Set variables up before form is built.
*/
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', NULL, $params['id']);
CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $params['id']);
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_Core_PseudoConstant::getKey('CRM_Pledge_BAO_Pledge', 'status_id', $values['status_id']);
}
$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);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Done'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
)
);
}
}

View file

@ -0,0 +1,415 @@
<?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
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This file is for Pledge search
*/
class CRM_Pledge_Form_Search extends CRM_Core_Form_Search {
/**
* The params that are sent to the query.
*
* @var array
*/
protected $_queryParams;
/**
* Are we restricting ourselves to a single contact.
*
* @var boolean
*/
protected $_single = FALSE;
/**
* Are we restricting ourselves to a single contact.
*
* @var boolean
*/
protected $_limit = NULL;
/**
* Prefix for the controller.
*/
protected $_prefix = "pledge_";
/**
* Processing needed for buildForm and later.
*/
public function preProcess() {
$this->_searchButtonName = $this->getButtonName('refresh');
$this->_actionButtonName = $this->getButtonName('next', 'action');
$this->_done = FALSE;
$this->defaults = array();
// we allow the controller to set force/reset externally, useful when we are being
// driven by the wizard framework
$this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
$this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
$this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
$this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
$this->assign("context", $this->_context);
// get user submitted values
// get it from controller only if form has been submitted, else preProcess has set this
if (!empty($_POST) && !$this->controller->isModal()) {
$this->_formValues = $this->controller->exportValues($this->_name);
}
else {
$this->_formValues = $this->get('formValues');
}
if (empty($this->_formValues)) {
if (isset($this->_ssID)) {
$this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
}
}
if ($this->_force) {
$this->postProcess();
$this->set('force', 0);
}
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
$selector = new CRM_Pledge_Selector_Search($this->_queryParams,
$this->_action,
NULL,
$this->_single,
$this->_limit,
$this->_context
);
$prefix = NULL;
if ($this->_context == 'user') {
$prefix = $this->_prefix;
}
$this->assign("{$prefix}limit", $this->_limit);
$this->assign("{$prefix}single", $this->_single);
$controller = new CRM_Core_Selector_Controller($selector,
$this->get(CRM_Utils_Pager::PAGE_ID),
$sortID,
CRM_Core_Action::VIEW,
$this,
CRM_Core_Selector_Controller::TRANSFER,
$prefix
);
$controller->setEmbedded(TRUE);
$controller->moveFromSessionToTemplate();
$this->assign('summary', $this->get('summary'));
}
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
$this->addSortNameField();
CRM_Pledge_BAO_Query::buildSearchForm($this);
$rows = $this->get('rows');
if (is_array($rows)) {
if (!$this->_single) {
$this->addRowSelectors($rows);
}
$permission = CRM_Core_Permission::getPermission();
$this->addTaskMenu(CRM_Pledge_Task::permissionedTaskTitles($permission));
}
}
/**
* Get the label for the sortName field if email searching is on.
*
* (email searching is a setting under search preferences).
*
* @return string
*/
protected function getSortNameLabelWithEmail() {
return ts('Pledger Name or Email');
}
/**
* Get the label for the sortName field if email searching is off.
*
* (email searching is a setting under search preferences).
*
* @return string
*/
protected function getSortNameLabelWithOutEmail() {
return ts('Pledger Name');
}
/**
* The post processing of the form gets done here.
*
* Key things done during post processing are
* - check for reset or next request. if present, skip post procesing.
* - now check if user requested running a saved search, if so, then
* the form values associated with the saved search are used for searching.
* - if user has done a submit with new values the regular post submissing is
* done.
* The processing consists of using a Selector / Controller framework for getting the
* search results.
*/
public function postProcess() {
if ($this->_done) {
return;
}
$this->_done = TRUE;
$this->_formValues = $this->controller->exportValues($this->_name);
$this->fixFormValues();
// We don't show test records in summaries or dashboards
if (empty($this->_formValues['pledge_test']) && $this->_force) {
$this->_formValues["pledge_test"] = 0;
}
foreach (array('pledge_amount_low', 'pledge_amount_high') as $f) {
if (isset($this->_formValues[$f])) {
$this->_formValues[$f] = CRM_Utils_Rule::cleanMoney($this->_formValues[$f]);
}
}
if (isset($this->_ssID) && empty($_POST)) {
// if we are editing / running a saved search and the form has not been posted
$this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
}
CRM_Core_BAO_CustomValue::fixCustomFieldValue($this->_formValues);
$this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
$this->set('formValues', $this->_formValues);
$this->set('queryParams', $this->_queryParams);
$buttonName = $this->controller->getButtonName();
if ($buttonName == $this->_actionButtonName) {
// check actionName and if next, then do not repeat a search, since we are going to the next page
// hack, make sure we reset the task values
$stateMachine = $this->controller->getStateMachine();
$formName = $stateMachine->getTaskFormName();
$this->controller->resetPage($formName);
return;
}
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
$selector = new CRM_Pledge_Selector_Search($this->_queryParams,
$this->_action,
NULL,
$this->_single,
$this->_limit,
$this->_context
);
$selector->setKey($this->controller->_key);
$prefix = NULL;
if ($this->_context == 'user') {
$prefix = $this->_prefix;
}
$this->assign("{$prefix}limit", $this->_limit);
$this->assign("{$prefix}single", $this->_single);
$controller = new CRM_Core_Selector_Controller($selector,
$this->get(CRM_Utils_Pager::PAGE_ID),
$sortID,
CRM_Core_Action::VIEW,
$this,
CRM_Core_Selector_Controller::SESSION,
$prefix
);
$controller->setEmbedded(TRUE);
$query = &$selector->getQuery();
if ($this->_context == 'user') {
$query->setSkipPermission(TRUE);
}
$controller->run();
}
/**
* add the rules (mainly global rules) for form.
* All local rules are added near the element
*
* @see valid_date
*/
public function addRules() {
$this->addFormRule(array('CRM_Pledge_Form_Search', 'formRule'));
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
*
* @return array|bool
*/
public static function formRule($fields) {
$errors = array();
if (!empty($errors)) {
return $errors;
}
return TRUE;
}
/**
* Set the default form values.
*
*
* @return array
* the default array reference
*/
public function setDefaultValues() {
$defaults = array();
$defaults = $this->_formValues;
return $defaults;
}
public function fixFormValues() {
if (!$this->_force) {
return;
}
// set pledge payment related fields
$status = CRM_Utils_Request::retrieve('status', 'String');
if ($status) {
$this->_formValues['pledge_payment_status_id'] = array($status => 1);
$this->_defaults['pledge_payment_status_id'] = array($status => 1);
}
$fromDate = CRM_Utils_Request::retrieve('start', 'Date');
if ($fromDate) {
list($date) = CRM_Utils_Date::setDateDefaults($fromDate);
$this->_formValues['pledge_payment_date_low'] = $date;
$this->_defaults['pledge_payment_date_low'] = $date;
}
$toDate = CRM_Utils_Request::retrieve('end', 'Date');
if ($toDate) {
list($date) = CRM_Utils_Date::setDateDefaults($toDate);
$this->_formValues['pledge_payment_date_high'] = $date;
$this->_defaults['pledge_payment_date_high'] = $date;
}
// set pledge related fields
$pledgeStatus = CRM_Utils_Request::retrieve('pstatus', 'String');
if ($pledgeStatus) {
$statusValues = CRM_Pledge_BAO_Pledge::buildOptions('status_id');
// we need set all statuses except Cancelled
unset($statusValues[$pledgeStatus]);
$statuses = array();
foreach ($statusValues as $statusId => $value) {
$statuses[$statusId] = 1;
}
$this->_formValues['pledge_status_id'] = $statuses;
$this->_defaults['pledge_status_id'] = $statuses;
}
$pledgeFromDate = CRM_Utils_Request::retrieve('pstart', 'Date');
if ($pledgeFromDate) {
list($date) = CRM_Utils_Date::setDateDefaults($pledgeFromDate);
$this->_formValues['pledge_create_date_low'] = $this->_defaults['pledge_create_date_low'] = $date;
}
$pledgeToDate = CRM_Utils_Request::retrieve('pend', 'Date');
if ($pledgeToDate) {
list($date) = CRM_Utils_Date::setDateDefaults($pledgeToDate);
$this->_formValues['pledge_create_date_high'] = $this->_defaults['pledge_create_date_high'] = $date;
}
$cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
if ($cid) {
$cid = CRM_Utils_Type::escape($cid, 'Integer');
if ($cid > 0) {
$this->_formValues['contact_id'] = $cid;
list($display, $image) = CRM_Contact_BAO_Contact::getDisplayAndImage($cid);
$this->_defaults['sort_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid,
'sort_name'
);
// also assign individual mode to the template
$this->_single = TRUE;
}
}
}
/**
* @return null
*/
public function getFormValues() {
return NULL;
}
/**
* Return a descriptive name for the page, used in wizard header
*
* @return string
*/
public function getTitle() {
return ts('Find Pledges');
}
}

View file

@ -0,0 +1,168 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates task actions for CiviEvent.
*/
class CRM_Pledge_Form_Task extends CRM_Core_Form {
/**
* The task being performed.
*
* @var int
*/
protected $_task;
/**
* The additional clause that we restrict the search with.
*
* @var string
*/
protected $_componentClause = NULL;
/**
* The array that holds all the component ids.
*
* @var array
*/
protected $_componentIds;
/**
* The array that holds all the pledge ids.
*
* @var array
*/
protected $_pledgeIds;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
self::preProcessCommon($this);
}
/**
* Common pre-processing.
*
* @param CRM_Core_Form $form
* @param bool $useTable
*/
public static function preProcessCommon(&$form, $useTable = FALSE) {
$form->_pledgeIds = array();
$values = $form->controller->exportValues('Search');
$form->_task = $values['task'];
$pledgeTasks = CRM_Pledge_Task::tasks();
$form->assign('taskName', $pledgeTasks[$form->_task]);
$ids = array();
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
$ids[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
}
}
}
else {
$queryParams = $form->get('queryParams');
$sortOrder = NULL;
if ($form->get(CRM_Utils_Sort::SORT_ORDER)) {
$sortOrder = $form->get(CRM_Utils_Sort::SORT_ORDER);
}
$query = new CRM_Contact_BAO_Query($queryParams, NULL, NULL, FALSE, FALSE,
CRM_Contact_BAO_Query::MODE_PLEDGE
);
$query->_distinctComponentClause = ' civicrm_pledge.id';
$query->_groupByComponentClause = ' GROUP BY civicrm_pledge.id ';
$result = $query->searchQuery(0, 0, $sortOrder);
while ($result->fetch()) {
$ids[] = $result->pledge_id;
}
}
if (!empty($ids)) {
$form->_componentClause = ' civicrm_pledge.id IN ( ' . implode(',', $ids) . ' ) ';
$form->assign('totalSelectedPledges', count($ids));
}
$form->_pledgeIds = $form->_componentIds = $ids;
// set the context for redirection for any task actions
$qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form);
$urlParams = 'force=1';
if (CRM_Utils_Rule::qfKey($qfKey)) {
$urlParams .= "&qfKey=$qfKey";
}
$session = CRM_Core_Session::singleton();
$session->replaceUserContext(CRM_Utils_System::url('civicrm/pledge/search', $urlParams));
}
/**
* Given the signer id, compute the contact id
* since its used for things like send email
*/
public function setContactIDs() {
$this->_contactIds = &CRM_Core_DAO::getContactIDsFromComponent($this->_pledgeIds,
'civicrm_pledge'
);
}
/**
* Simple shell that derived classes can call to add buttons to
* the form with a customized title for the main Submit
*
* @param string $title
* Title of the main button.
* @param string $nextType
* @param string $backType
* @param bool $submitOnce
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
$this->addButtons(array(
array(
'type' => $nextType,
'name' => $title,
'isDefault' => TRUE,
),
array(
'type' => $backType,
'name' => ts('Cancel'),
),
)
);
}
}

View file

@ -0,0 +1,91 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to delete a group of
* participations. This class provides functionality for the actual
* deletion.
*/
class CRM_Pledge_Form_Task_Delete extends CRM_Pledge_Form_Task {
/**
* Are we operating in "single mode", i.e. deleting one
* specific pledge?
*
* @var boolean
*/
protected $_single = FALSE;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
//check for delete
if (!CRM_Core_Permission::checkActionPermission('CiviPledge', CRM_Core_Action::DELETE)) {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
parent::preProcess();
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addDefaultButtons(ts('Delete Pledges'), 'done');
}
/**
* Process the form after the input has been submitted and validated.
*/
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');
}
}
}

View file

@ -0,0 +1,94 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to save a search
* Saved Searches are used for saving frequently used queries
*/
class CRM_Pledge_Form_Task_Print extends CRM_Pledge_Form_Task {
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preprocess();
// set print view, so that print templates are called
$this->controller->setPrint(1);
// get the formatted params
$queryParams = $this->get('queryParams');
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$selector = new CRM_Pledge_Selector_Search($queryParams, $this->_action, $this->_componentClause);
$controller = new CRM_Core_Selector_Controller($selector, NULL, $sortID, CRM_Core_Action::VIEW, $this, CRM_Core_Selector_Controller::SCREEN);
$controller->setEmbedded(TRUE);
$controller->run();
}
/**
* Build the form object - it consists of
* - displaying the QILL (query in local language)
* - displaying elements for saving the search.
*/
public function buildQuickForm() {
// just need to add a javacript to popup the window for printing
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Print Pledge List'),
'js' => array('onclick' => 'window.print()'),
'isDefault' => TRUE,
),
array(
'type' => 'back',
'name' => ts('Done'),
),
)
);
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
// redirect to the main search page after printing is over
}
}

View file

@ -0,0 +1,59 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Used for displaying results.
*/
class CRM_Pledge_Form_Task_Result extends CRM_Pledge_Form_Task {
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
),
)
);
}
}

View file

@ -0,0 +1,82 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to save a search
* Saved Searches are used for saving frequently used queries
*/
class CRM_Pledge_Form_Task_SearchTaskHookSample extends CRM_Pledge_Form_Task {
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preProcess();
$rows = array();
// display name and pledge details of all selected contacts
$pledgeIDs = implode(',', $this->_pledgeIds);
$query = "
SELECT plg.amount as amount,
plg.create_date as create_date,
ct.display_name as display_name
FROM civicrm_pledge plg
INNER JOIN civicrm_contact ct ON ( plg.contact_id = ct.id )
WHERE plg.id IN ( $pledgeIDs )";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$rows[] = array(
'display_name' => $dao->display_name,
'amount' => $dao->amount,
'create_date' => CRM_Utils_Date::customFormat($dao->create_date),
);
}
$this->assign('rows', $rows);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
),
)
);
}
}

View file

@ -0,0 +1,188 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
* This class introduces component to the system and provides all the
* information about it. It needs to extend CRM_Core_Component_Info
* abstract class.
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Pledge_Info extends CRM_Core_Component_Info {
/**
* @inheritDoc
*/
protected $keyword = 'pledge';
/**
* Provides base information about the component.
* Needs to be implemented in component's information
* class.
*
* @return array
* collection of required component settings
*/
public function getInfo() {
return array(
'name' => 'CiviPledge',
'translatedName' => ts('CiviPledge'),
'title' => ts('CiviCRM Pledge Engine'),
'search' => 1,
'showActivitiesInCore' => 1,
);
}
/**
* @inheritDoc
* Provides permissions that are used by component.
* Needs to be implemented in component's information
* class.
*
* NOTE: if using conditionally permission return,
* implementation of $getAllUnconditionally is required.
*
* @param bool $getAllUnconditionally
* @param bool $descriptions
* Whether to return permission descriptions
*
* @return array|null
* collection of permissions, null if none
*/
public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) {
$permissions = array(
'access CiviPledge' => array(
ts('access CiviPledge'),
ts('View pledges'),
),
'edit pledges' => array(
ts('edit pledges'),
ts('Create and update pledges'),
),
'delete in CiviPledge' => array(
ts('delete in CiviPledge'),
ts('Delete pledges'),
),
);
if (!$descriptions) {
foreach ($permissions as $name => $attr) {
$permissions[$name] = array_shift($attr);
}
}
return $permissions;
}
/**
* @inheritDoc
* Provides information about user dashboard element
* offered by this component.
*
* @return array|null
* collection of required dashboard settings,
* null if no element offered
*/
public function getUserDashboardElement() {
return array(
'name' => ts('Pledges'),
'title' => ts('Your Pledge(s)'),
// we need to check this permission since you can click on contribution page link for making payment
'perm' => array('make online contributions'),
'weight' => 15,
);
}
/**
* @inheritDoc
* Provides information about user dashboard element
* offered by this component.
*
* @return array|null
* collection of required dashboard settings,
* null if no element offered
*/
public function registerTab() {
return array(
'title' => ts('Pledges'),
'url' => 'pledge',
'weight' => 25,
);
}
/**
* @inheritDoc
* Provides information about advanced search pane
* offered by this component.
*
* @return array|null
* collection of required pane settings,
* null if no element offered
*/
public function registerAdvancedSearchPane() {
return array(
'title' => ts('Pledges'),
'weight' => 25,
);
}
/**
* @inheritDoc
* Provides potential activity types that this
* component might want to register in activity history.
* Needs to be implemented in component's information
* class.
*
* @return array|null
* collection of activity types
*/
public function getActivityTypes() {
return NULL;
}
/**
* add shortcut to Create New.
* @param $shortCuts
*/
public function creatNewShortcut(&$shortCuts) {
if (CRM_Core_Permission::check('access CiviPledge') &&
CRM_Core_Permission::check('edit pledges')
) {
$shortCuts = array_merge($shortCuts, array(
array(
'path' => 'civicrm/pledge/add',
'query' => 'reset=1&action=add&context=standalone',
'ref' => 'new-pledge',
'title' => ts('Pledge'),
),
));
}
}
}

View file

@ -0,0 +1,52 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class contains all the function that are called using AJAX
*/
class CRM_Pledge_Page_AJAX {
/**
* Function to setDefaults according to Pledge Id
* for batch entry pledges
*/
public function getPledgeDefaults() {
$details = array();
if (!empty($_POST['pid'])) {
$pledgeID = CRM_Utils_Type::escape($_POST['pid'], 'Integer');
$details = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeID);
}
CRM_Utils_JSON::output($details);
}
}

View file

@ -0,0 +1,116 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This page is for the Pledge Dashboard.
*/
class CRM_Pledge_Page_DashBoard extends CRM_Core_Page {
/**
* Heart of the viewing process.
*
* The runner gets all the meta data for the contact and calls the appropriate type of page to view.
*/
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'
$yearDate = \Civi::settings()->get('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);
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);
}
}
/**
* The main function that is called when the page loads.
*
* it decides which action has to be taken for the page.
*
* @return null
*/
public function run() {
$this->preProcess();
$controller = new CRM_Core_Controller_Simple('CRM_Pledge_Form_Search',
ts('Pledge'),
NULL
);
$controller->setEmbedded(TRUE);
$controller->reset();
$controller->set('limit', 10);
$controller->set('force', 1);
$controller->set('context', 'dashboard');
$controller->process();
$controller->run();
return parent::run();
}
}

View file

@ -0,0 +1,96 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Pledge_Page_Payment extends CRM_Core_Page {
/**
* 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->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
$this->assign('action', $this->_action);
$this->assign('context', $this->_context);
$this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
CRM_Pledge_Page_Tab::setContext($this);
if ($this->_action & CRM_Core_Action::UPDATE) {
$this->edit();
}
else {
$pledgeId = CRM_Utils_Request::retrieve('pledgeId', 'Positive', $this);
$paymentDetails = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId);
$this->assign('rows', $paymentDetails);
$this->assign('pledgeId', $pledgeId);
$this->assign('contactId', $this->_contactId);
// check if we can process credit card contributions
$this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
// check is the user has view/edit signer permission
$permission = 'view';
if (CRM_Core_Permission::check('edit pledges')) {
$permission = 'edit';
}
$this->assign('permission', $permission);
}
return parent::run();
}
/**
* called when action is update or new.
*
* @return null
*/
public function edit() {
$controller = new CRM_Core_Controller_Simple('CRM_Pledge_Form_Payment',
'Update Pledge Payment',
$this->_action
);
$pledgePaymentId = CRM_Utils_Request::retrieve('ppId', 'Positive', $this);
$controller->setEmbedded(TRUE);
$controller->set('id', $pledgePaymentId);
return $controller->run();
}
}

View file

@ -0,0 +1,220 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Pledge_Page_Tab extends CRM_Core_Page {
public $_permission = NULL;
public $_contactId = NULL;
/**
* called when action is browse.
*/
public function browse() {
$controller = new CRM_Core_Controller_Simple('CRM_Pledge_Form_Search', ts('Pledges'), $this->_action);
$controller->setEmbedded(TRUE);
$controller->reset();
$controller->set('cid', $this->_contactId);
$controller->set('context', 'pledge');
$controller->set('limit', '25');
$controller->process();
$controller->run();
if ($this->_contactId) {
$displayName = CRM_Contact_BAO_Contact::displayName($this->_contactId);
$this->assign('displayName', $displayName);
$this->ajaxResponse['tabCount'] = CRM_Contact_BAO_Contact::getCountComponent('pledge', $this->_contactId);
// Refresh other tabs with related data
$this->ajaxResponse['updateTabs'] = array(
'#tab_contribute' => CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId),
'#tab_activity' => CRM_Contact_BAO_Contact::getCountComponent('activity', $this->_contactId),
);
}
}
/**
* called when action is view.
*
* @return null
*/
public function view() {
$controller = new CRM_Core_Controller_Simple('CRM_Pledge_Form_PledgeView',
'View Pledge',
$this->_action
);
$controller->setEmbedded(TRUE);
$controller->set('id', $this->_id);
$controller->set('cid', $this->_contactId);
return $controller->run();
}
/**
* called when action is update or new.
*
* @return null
*/
public function edit() {
$controller = new CRM_Core_Controller_Simple('CRM_Pledge_Form_Pledge',
'Create Pledge',
$this->_action
);
$controller->setEmbedded(TRUE);
$controller->set('id', $this->_id);
$controller->set('cid', $this->_contactId);
return $controller->run();
}
public function preProcess() {
$context = CRM_Utils_Request::retrieve('context', 'String', $this);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
if ($context == 'standalone') {
$this->_action = CRM_Core_Action::ADD;
}
else {
$this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
$this->assign('contactId', $this->_contactId);
// check logged in url permission
CRM_Contact_Page_View::checkUserPermission($this);
}
$this->assign('action', $this->_action);
if ($this->_permission == CRM_Core_Permission::EDIT && !CRM_Core_Permission::check('edit pledges')) {
// demote to view since user does not have edit pledge rights
$this->_permission = CRM_Core_Permission::VIEW;
$this->assign('permission', 'view');
}
}
/**
* 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();
}
/**
* Get context.
*
* @param $form
*/
public static function setContext(&$form) {
$context = CRM_Utils_Request::retrieve('context', 'String', $form, FALSE, 'search');
$qfKey = CRM_Utils_Request::retrieve('key', 'String', $form);
// validate the qfKey
if (!CRM_Utils_Rule::qfKey($qfKey)) {
$qfKey = NULL;
}
switch ($context) {
case 'dashboard':
case 'pledgeDashboard':
$url = CRM_Utils_System::url('civicrm/pledge', 'reset=1');
break;
case 'search':
$urlParams = 'force=1';
if ($qfKey) {
$urlParams .= "&qfKey=$qfKey";
}
$url = CRM_Utils_System::url('civicrm/pledge/search', $urlParams);
break;
case 'user':
$url = CRM_Utils_System::url('civicrm/user', 'reset=1');
break;
case 'pledge':
$url = CRM_Utils_System::url('civicrm/contact/view',
"reset=1&force=1&cid={$form->_contactId}&selectedChild=pledge"
);
break;
case 'home':
$url = CRM_Utils_System::url('civicrm/dashboard', 'force=1');
break;
case 'activity':
$url = CRM_Utils_System::url('civicrm/contact/view',
"reset=1&force=1&cid={$form->_contactId}&selectedChild=activity"
);
break;
case 'standalone':
$url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
break;
default:
$cid = NULL;
if ($form->_contactId) {
$cid = '&cid=' . $form->_contactId;
}
$url = CRM_Utils_System::url('civicrm/pledge/search',
'force=1' . $cid
);
break;
}
$session = CRM_Core_Session::singleton();
$session->pushUserContext($url);
}
}

View file

@ -0,0 +1,76 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Pledge_Page_UserDashboard extends CRM_Contact_Page_View_UserDashBoard {
/**
* 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);
}
/**
* the main function that is called when the page
* loads, it decides the which action has to be taken for the page.
*/
public function run() {
parent::preProcess();
$this->listPledges();
}
}

View file

@ -0,0 +1,464 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is used to retrieve and display a range of
* contacts that match the given criteria (specifically for
* results of advanced search options.
*/
class CRM_Pledge_Selector_Search extends CRM_Core_Selector_Base {
/**
* This defines two actions- View and Edit.
*
* @var array
*/
static $_links = NULL;
/**
* We use desc to remind us what that column is, name is used in the tpl
*
* @var array
*/
static $_columnHeaders;
/**
* Properties of contact we're interested in displaying
*
* @var array
*/
static $_properties = array(
'contact_id',
'sort_name',
'display_name',
'pledge_id',
'pledge_amount',
'pledge_create_date',
'pledge_total_paid',
'pledge_next_pay_date',
'pledge_next_pay_amount',
'pledge_outstanding_amount',
'pledge_status_id',
'pledge_status',
'pledge_is_test',
'pledge_contribution_page_id',
'pledge_financial_type',
'pledge_campaign_id',
'pledge_currency',
);
/**
* Are we restricting ourselves to a single contact
*
* @var boolean
*/
protected $_single = FALSE;
/**
* Are we restricting ourselves to a single contact
*
* @var boolean
*/
protected $_limit = NULL;
/**
* What context are we being invoked from
*
* @var string
*/
protected $_context = NULL;
/**
* QueryParams is the array returned by exportValues called on
* the HTML_QuickForm_Controller for that page.
*
* @var array
*/
public $_queryParams;
/**
* Represent the type of selector
*
* @var int
*/
protected $_action;
/**
* The additional clause that we restrict the search with
*
* @var string
*/
protected $_additionalClause = NULL;
/**
* The query object
*
* @var string
*/
protected $_query;
/**
* Class constructor.
*
* @param array $queryParams
* Array of parameters for query.
* @param \const|int $action - action of search basic or advanced.
* @param string $additionalClause
* If the caller wants to further restrict the search (used in participations).
* @param bool $single
* Are we dealing only with one contact?.
* @param int $limit
* How many signers do we want returned.
*
* @param string $context
*
* @return \CRM_Pledge_Selector_Search
*/
public function __construct(
&$queryParams,
$action = CRM_Core_Action::NONE,
$additionalClause = NULL,
$single = FALSE,
$limit = NULL,
$context = 'search'
) {
// submitted form values
$this->_queryParams = &$queryParams;
$this->_single = $single;
$this->_limit = $limit;
$this->_context = $context;
$this->_additionalClause = $additionalClause;
// type of selector
$this->_action = $action;
$this->_query = new CRM_Contact_BAO_Query($this->_queryParams, NULL, NULL, FALSE, FALSE,
CRM_Contact_BAO_Query::MODE_PLEDGE
);
$this->_query->_distinctComponentClause = "civicrm_pledge.id";
$this->_query->_groupByComponentClause = " GROUP BY civicrm_pledge.id ";
}
/**
* This method returns the links that are given for each search row.
*
* Currently the links added for each row are:
* - View
* - Edit
*
* @return array
*/
public static function &links() {
$args = func_get_args();
$hideOption = CRM_Utils_Array::value(0, $args);
$key = CRM_Utils_Array::value(1, $args);
$extraParams = ($key) ? "&key={$key}" : NULL;
$cancelExtra = ts('Cancelling this pledge will also cancel any scheduled (and not completed) pledge payments.') . ' ' . ts('This action cannot be undone.') . ' ' . ts('Do you want to continue?');
self::$_links = array(
CRM_Core_Action::VIEW => array(
'name' => ts('View'),
'url' => 'civicrm/contact/view/pledge',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=pledge' . $extraParams,
'title' => ts('View Pledge'),
),
CRM_Core_Action::UPDATE => array(
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/pledge',
'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Edit Pledge'),
),
CRM_Core_Action::DETACH => array(
'name' => ts('Cancel'),
'url' => 'civicrm/contact/view/pledge',
'qs' => 'reset=1&action=detach&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'extra' => 'onclick = "return confirm(\'' . $cancelExtra . '\');"',
'title' => ts('Cancel Pledge'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/pledge',
'qs' => 'reset=1&action=delete&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Delete Pledge'),
),
);
if (in_array('Cancel', $hideOption)) {
unset(self::$_links[CRM_Core_Action::DETACH]);
}
return self::$_links;
}
/**
* Getter for array of the parameters required for creating pager.
*
* @param $action
* @param array $params
*/
public function getPagerParams($action, &$params) {
$params['status'] = ts('Pledge') . ' %%StatusMessage%%';
$params['csvString'] = NULL;
if ($this->_limit) {
$params['rowCount'] = $this->_limit;
}
else {
$params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
}
$params['buttonTop'] = 'PagerTopButton';
$params['buttonBottom'] = 'PagerBottomButton';
}
/**
* Returns total number of rows for the query.
*
* @param int $action
*
* @return int
* Total number of rows
*/
public function getTotalCount($action) {
return $this->_query->searchQuery(0, 0, NULL,
TRUE, FALSE,
FALSE, FALSE,
FALSE,
$this->_additionalClause
);
}
/**
* Returns all the rows in the given offset and rowCount.
*
* @param string $action
* The action being performed.
* @param int $offset
* The row number to start from.
* @param int $rowCount
* The number of rows to return.
* @param string $sort
* The sql string that describes the sort order.
* @param string $output
* What should the result set include (web/email/csv).
*
* @return int
* the total number of rows for this action
*/
public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$result = $this->_query->searchQuery($offset, $rowCount, $sort,
FALSE, FALSE,
FALSE, FALSE,
FALSE,
$this->_additionalClause
);
// process the result of the query
$rows = array();
// get all pledge status
$pledgeStatuses = CRM_Pledge_BAO_Pledge::buildOptions('status_id');
// get all campaigns.
$allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
// CRM-4418 check for view, edit and delete
$permissions = array(CRM_Core_Permission::VIEW);
if (CRM_Core_Permission::check('edit pledges')) {
$permissions[] = CRM_Core_Permission::EDIT;
}
if (CRM_Core_Permission::check('delete in CiviPledge')) {
$permissions[] = CRM_Core_Permission::DELETE;
}
$mask = CRM_Core_Action::mask($permissions);
while ($result->fetch()) {
$row = array();
// the columns we are interested in
foreach (self::$_properties as $property) {
if (isset($result->$property)) {
$row[$property] = $result->$property;
}
}
// carry campaign on selectors.
$row['campaign'] = CRM_Utils_Array::value($result->pledge_campaign_id, $allCampaigns);
$row['campaign_id'] = $result->pledge_campaign_id;
// add pledge status name
$row['pledge_status_name'] = CRM_Utils_Array::value($row['pledge_status_id'],
$pledgeStatuses
);
// append (test) to status label
if (!empty($row['pledge_is_test'])) {
$row['pledge_status'] .= ' (test)';
}
$hideOption = array();
if (CRM_Utils_Array::key('Cancelled', $row) ||
CRM_Utils_Array::key('Completed', $row)
) {
$hideOption[] = 'Cancel';
}
$row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->pledge_id;
$row['action'] = CRM_Core_Action::formLink(self::links($hideOption, $this->_key),
$mask,
array(
'id' => $result->pledge_id,
'cid' => $result->contact_id,
'cxt' => $this->_context,
),
ts('more'),
FALSE,
'pledge.selector.row',
'Pledge',
$result->pledge_id
);
$row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id
);
$rows[] = $row;
}
return $rows;
}
/**
* Get qill (display what was searched on).
*
* @inheritDoc
*/
public function getQILL() {
return $this->_query->qill();
}
/**
* Returns the column headers as an array of tuples.
*
* Keys are name, sortName, key to the sort array
*
* @param string $action
* The action being performed.
* @param string $output
* What should the result set include (web/email/csv).
*
* @return array
* the column headers that need to be displayed
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if (!isset(self::$_columnHeaders)) {
self::$_columnHeaders = array(
array(
'name' => ts('Pledged'),
'sort' => 'pledge_amount',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Total Paid'),
'sort' => 'pledge_total_paid',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Balance'),
),
array(
'name' => ts('Pledged For'),
'sort' => 'pledge_financial_type',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Pledge Made'),
'sort' => 'pledge_create_date',
'direction' => CRM_Utils_Sort::DESCENDING,
),
array(
'name' => ts('Next Pay Date'),
'sort' => 'pledge_next_pay_date',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Next Amount'),
'sort' => 'pledge_next_pay_amount',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Status'),
'sort' => 'pledge_status',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array('desc' => ts('Actions')),
);
if (!$this->_single) {
$pre = array(
array('desc' => ts('Contact ID')),
array(
'name' => ts('Name'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::DONTCARE,
),
);
self::$_columnHeaders = array_merge($pre, self::$_columnHeaders);
}
}
return self::$_columnHeaders;
}
/**
* Get sql query string.
*
* @return string
*/
public function &getQuery() {
return $this->_query;
}
/**
* Name of export file.
*
* @param string $output
* Type of output.
*
* @return string
* name of the file
*/
public function getExportFileName($output = 'csv') {
return ts('Pledge Search');
}
}

View file

@ -0,0 +1,113 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
class CRM_Pledge_StateMachine_Search extends CRM_Core_StateMachine {
/**
* The task that the wizard is currently processing
*
* @var string
*/
protected $_task;
/**
* Class constructor.
*
* @param object $controller
* @param \const|int $action
*/
public function __construct($controller, $action = CRM_Core_Action::NONE) {
parent::__construct($controller, $action);
$this->_pages = array();
$this->_pages['CRM_Pledge_Form_Search'] = NULL;
list($task, $result) = $this->taskName($controller, 'Search');
$this->_task = $task;
if (is_array($task)) {
foreach ($task as $t) {
$this->_pages[$t] = NULL;
}
}
else {
$this->_pages[$task] = NULL;
}
if ($result) {
$this->_pages['CRM_Pledge_Form_Task_Result'] = NULL;
}
$this->addSequentialPages($this->_pages, $action);
}
/**
* Determine the form name based on the action. This allows us
* to avoid using conditional state machine, much more efficient
* and simpler
*
* @param CRM_Core_Controller $controller
* The controller object.
*
* @param string $formName
*
* @return string
* the name of the form that will handle the task
*/
public function taskName($controller, $formName = 'Search') {
// total hack, check POST vars and then session to determine stuff
$value = CRM_Utils_Array::value('task', $_POST);
if (!isset($value)) {
$value = $this->_controller->get('task');
}
$this->_controller->set('task', $value);
return CRM_Pledge_Task::getTask($value);
}
/**
* Return the form name of the task.
*
* @return string
*/
public function getTaskFormName() {
return CRM_Utils_String::getClassName($this->_task);
}
/**
* Since this is a state machine for search and we want to come back to the same state
* we dont want to issue a reset of the state session when we are done processing a task
*/
public function shouldReset() {
return FALSE;
}
}

View file

@ -0,0 +1,171 @@
<?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 |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* class to represent the actions that can be performed on a group of contacts
* used by the search forms.
*/
class CRM_Pledge_Task {
const DELETE_PLEDGES = 1, PRINT_PLEDGES = 2, EXPORT_PLEDGES = 3;
/**
* The task array
*
* @var array
*/
static $_tasks = NULL;
/**
* The optional task array
*
* @var array
*/
static $_optionalTasks = NULL;
/**
* These tasks are the core set of tasks that the user can perform
* on a contact / group of contacts
*
* @return array
* the set of tasks for a group of contacts
*/
public static function &tasks() {
if (!self::$_tasks) {
self::$_tasks = array(
1 => array(
'title' => ts('Delete pledges'),
'class' => 'CRM_Pledge_Form_Task_Delete',
'result' => FALSE,
),
2 => array(
'title' => ts('Print selected rows'),
'class' => 'CRM_Pledge_Form_Task_Print',
'result' => FALSE,
),
3 => array(
'title' => ts('Export pledges'),
'class' => array(
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
),
'result' => FALSE,
),
);
// CRM-4418, check for delete
if (!CRM_Core_Permission::check('delete in CiviPledge')) {
unset(self::$_tasks[1]);
}
CRM_Utils_Hook::searchTasks('pledge', self::$_tasks);
asort(self::$_tasks);
}
return self::$_tasks;
}
/**
* These tasks are the core set of task titles.
*
* @return array
* the set of task titles
*/
public static function &taskTitles() {
self::tasks();
$titles = array();
foreach (self::$_tasks as $id => $value) {
$titles[$id] = $value['title'];
}
return $titles;
}
/**
* These tasks get added based on the context the user is in.
*
* @return array
* the set of optional tasks for a group of contacts
*/
public static function &optionalTaskTitle() {
$tasks = array();
return $tasks;
}
/**
* Show tasks selectively based on the permission level
* of the user
*
* @param int $permission
*
* @return array
* set of tasks that are valid for the user
*/
public static function &permissionedTaskTitles($permission) {
$tasks = array();
if (($permission == CRM_Core_Permission::EDIT)
|| CRM_Core_Permission::check('edit pledges')
) {
$tasks = self::taskTitles();
}
else {
$tasks = array(
3 => self::$_tasks[3]['title'],
);
//CRM-4418,
if (CRM_Core_Permission::check('delete in CiviPledge')) {
$tasks[1] = self::$_tasks[1]['title'];
}
}
return $tasks;
}
/**
* These tasks are the core set of tasks that the user can perform
* on pledges.
*
* @param int $value
*
* @return array
* the set of tasks for a group of pledge holders
*/
public static function getTask($value) {
self::tasks();
if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
// make the print task by default
$value = 2;
}
return array(
self::$_tasks[$value]['class'],
self::$_tasks[$value]['result'],
);
}
}

View file

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="iso-8859-1" ?>
<menu>
<item>
<path>civicrm/pledge</path>
<title>CiviPledge Dashboard</title>
<page_callback>CRM_Pledge_Page_DashBoard</page_callback>
<access_arguments>access CiviPledge</access_arguments>
<page_type>1</page_type>
<weight>550</weight>
<component>CiviPledge</component>
</item>
<item>
<path>civicrm/pledge/search</path>
<title>Find Pledges</title>
<page_callback>CRM_Pledge_Controller_Search</page_callback>
<access_arguments>access CiviPledge</access_arguments>
<page_type>1</page_type>
<weight>560</weight>
</item>
<item>
<path>civicrm/contact/view/pledge</path>
<path_arguments>force=1,cid=%%cid%%</path_arguments>
<title>Pledges</title>
<page_callback>CRM_Pledge_Page_Tab</page_callback>
<access_arguments>access CiviPledge</access_arguments>
<weight>570</weight>
</item>
<item>
<path>civicrm/pledge/add</path>
<path_arguments>action=add</path_arguments>
<title>New Pledge</title>
<page_callback>CRM_Pledge_Page_Tab</page_callback>
<access_arguments>access CiviPledge</access_arguments>
<page_type>1</page_type>
<component>CiviPledge</component>
</item>
<item>
<path>civicrm/pledge/payment</path>
<title>Pledge Payments</title>
<page_callback>CRM_Pledge_Page_Payment</page_callback>
<access_arguments>access CiviPledge</access_arguments>
<weight>580</weight>
</item>
<item>
<path>civicrm/ajax/pledgeAmount</path>
<page_callback>CRM_Pledge_Page_AJAX::getPledgeDefaults</page_callback>
<access_arguments>access CiviPledge,administer CiviCRM</access_arguments>
</item>
</menu>