3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
37 * This class generates form components for processing a pledge
40 class CRM_Pledge_Form_Pledge
extends CRM_Core_Form
{
44 * the id of the pledge that we are proceessing
52 * the id of the contact associated with this pledge
60 * The Pledge values if an existing pledge
66 * The Pledge frequency Units
72 * is current pledge pending.
75 public $_isPending = FALSE;
78 * Function to set variables up before form is built
83 public function preProcess() {
84 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
85 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String',
88 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
89 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
91 // check for action permissions.
92 if (!CRM_Core_Permission
::checkActionPermission('CiviPledge', $this->_action
)) {
93 CRM_Core_Error
::fatal(ts('You do not have permission to access this page'));
96 $this->assign('action', $this->_action
);
97 $this->assign('context', $this->_context
);
98 if ($this->_action
& CRM_Core_Action
::DELETE
) {
102 $this->userDisplayName
= $this->userEmail
= NULL;
103 if ($this->_contactID
) {
104 list($this->userDisplayName
,
106 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
107 $this->assign('displayName', $this->userDisplayName
);
109 // set title to "Pledge - "+Contact Name
110 $displayName = $this->userDisplayName
;
111 $pageTitle = ts('Pledge by'). ' ' . $displayName;
112 $this->assign('pageTitle', $pageTitle);
113 CRM_Utils_System
::setTitle($pageTitle);
117 CRM_Custom_Form_CustomData
::preProcess($this, NULL, NULL, 1, 'Pledge', $this->_id
);
119 $this->_values
= array();
122 //get the contribution id
123 $this->_contributionID
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
124 $this->_id
, 'contribution_id', 'pledge_id'
126 $params = array('id' => $this->_id
);
127 CRM_Pledge_BAO_Pledge
::getValues($params, $this->_values
);
129 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
131 //check for pending pledge.
132 if (CRM_Utils_Array
::value('status_id', $this->_values
) ==
133 array_search('Pending', $paymentStatusTypes)
135 $this->_isPending
= TRUE;
137 elseif (CRM_Utils_Array
::value('status_id', $this->_values
) ==
138 array_search('Overdue', $paymentStatusTypes)
141 $allPledgePayments = array();
142 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment',
149 foreach ($allPledgePayments as $key => $value) {
150 $allStatus[$value['id']] = $paymentStatusTypes[$value['status_id']];
153 if (count(array_count_values($allStatus)) <= 2) {
154 if (CRM_Utils_Array
::value('Pending', array_count_values($allStatus))) {
155 $this->_isPending
= TRUE;
161 //get the pledge frequency units.
162 $this->_freqUnits
= CRM_Core_OptionGroup
::values('recur_frequency_units');
164 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
168 * This function sets the default values for the form.
169 * the default values are retrieved from the database
175 function setDefaultValues() {
176 $defaults = $this->_values
;
179 if ($this->_action
& CRM_Core_Action
::DELETE
) {
183 if (!empty($defaults['is_test'])) {
184 $this->assign('is_test', TRUE);
188 $startDate = CRM_Utils_Array
::value('start_date', $this->_values
);
189 $createDate = CRM_Utils_Array
::value('create_date', $this->_values
);
190 list($defaults['start_date']) = CRM_Utils_Date
::setDateDefaults($startDate);
191 list($defaults['create_date']) = CRM_Utils_Date
::setDateDefaults($createDate);
193 if ($ackDate = CRM_Utils_Array
::value('acknowledge_date', $this->_values
)) {
194 list($defaults['acknowledge_date']) = CRM_Utils_Date
::setDateDefaults($ackDate);
197 //check is this pledge pending
198 // fix the display of the monetary value, CRM-4038
199 if ($this->_isPending
) {
200 $defaults['eachPaymentAmount'] = $this->_values
['amount'] / $this->_values
['installments'];
201 $defaults['eachPaymentAmount'] = CRM_Utils_Money
::format($defaults['eachPaymentAmount'], NULL, '%a');
204 $this->assign('start_date', $startDate);
205 $this->assign('create_date', $createDate);
207 // fix the display of the monetary value, CRM-4038
208 if (isset($this->_values
['amount'])) {
209 $defaults['amount'] = CRM_Utils_Money
::format($this->_values
['amount'], NULL, '%a');
211 $this->assign('amount', $this->_values
['amount']);
212 $this->assign('installments', $defaults['installments']);
216 list($now) = CRM_Utils_Date
::setDateDefaults();
217 $defaults['create_date'] = $now;
218 $defaults['start_date'] = $now;
219 $defaults['installments'] = 12;
220 $defaults['frequency_interval'] = 1;
221 $defaults['frequency_day'] = 1;
222 $defaults['initial_reminder_day'] = 5;
223 $defaults['max_reminders'] = 1;
224 $defaults['additional_reminder_day'] = 5;
225 $defaults['frequency_unit'] = array_search('month', $this->_freqUnits
);
226 $defaults['financial_type_id'] = array_search( 'Donation', CRM_Contribute_PseudoConstant
::financialType() );
229 $pledgeStatus = CRM_Contribute_PseudoConstant
::contributionStatus();
230 $pledgeStatusNames = CRM_Core_OptionGroup
::values('contribution_status',
231 FALSE, FALSE, FALSE, NULL, 'name', TRUE
233 // get default status label (pending)
234 $defaultPledgeStatus = CRM_Utils_Array
::value(array_search('Pending', $pledgeStatusNames),
239 $this->assign('status', CRM_Utils_Array
::value(CRM_Utils_Array
::value('status_id', $this->_values
),
244 if (isset($this->userEmail
)) {
245 $this->assign('email', $this->userEmail
);
248 // custom data set defaults
249 $defaults +
= CRM_Custom_Form_CustomData
::setDefaultValues($this);
255 * Function to build the form
260 public function buildQuickForm() {
261 if ($this->_action
& CRM_Core_Action
::DELETE
) {
262 $this->addButtons(array(
265 'name' => ts('Delete'),
266 'spacing' => ' ',
271 'name' => ts('Cancel'),
278 if ($this->_context
== 'standalone') {
279 CRM_Contact_Form_NewContact
::buildQuickForm($this);
282 $showAdditionalInfo = FALSE;
283 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
288 'Payment Reminders' => 'PaymentReminders',
290 foreach ($paneNames as $name => $type) {
291 $urlParams = "snippet=4&formType={$type}";
292 $allPanes[$name] = array('url' => CRM_Utils_System
::url('civicrm/contact/view/pledge', $urlParams),
296 //see if we need to include this paneName in the current form
297 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
298 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
300 $showAdditionalInfo = TRUE;
301 $allPanes[$name]['open'] = 'true';
303 $fnName = "build{$type}";
304 CRM_Contribute_Form_AdditionalInfo
::$fnName($this);
307 $this->assign('allPanes', $allPanes);
308 $this->assign('showAdditionalInfo', $showAdditionalInfo);
310 if ($this->_formType
) {
311 $this->assign('formType', $this->_formType
);
315 $this->applyFilter('__ALL__', 'trim');
318 $attributes = CRM_Core_DAO
::getAttribute('CRM_Pledge_DAO_Pledge');
320 $this->assign('isPending', $this->_isPending
);
323 'onblur' => "calculatedPaymentAmount( );",
324 'onkeyup' => "calculatedPaymentAmount( );",
327 $currencyFreeze = FALSE;
331 $currencyFreeze = TRUE;
334 $element = $this->addMoney('amount', ts('Total Pledge Amount'), TRUE,
335 array_merge($attributes['pledge_amount'], $js), TRUE,
336 'currency', NULL, $currencyFreeze
345 $element = &$this->add('text', 'installments', ts('To be paid in'),
346 array_merge($attributes['installments'], $js), TRUE
348 $this->addRule('installments', ts('Please enter a valid number of installments.'), 'positiveInteger');
355 $element = &$this->add('text', 'frequency_interval', ts('every'),
356 $attributes['pledge_frequency_interval'], TRUE
358 $this->addRule('frequency_interval', ts('Please enter a number for frequency (e.g. every "3" months).'), 'positiveInteger');
365 // Fix frequency unit display for use with frequency_interval
366 $freqUnitsDisplay = array();
367 foreach ($this->_freqUnits
as $val => $label) {
368 $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
370 $element = &$this->add('select', 'frequency_unit',
373 '' => ts('- select -')) +
$freqUnitsDisplay,
383 $element = &$this->add('text', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], TRUE);
384 $this->addRule('frequency_day', ts('Please enter a valid payment due day.'), 'positiveInteger');
391 $this->add('text', 'eachPaymentAmount', ts('each'), array('size' => 10, 'style' => "background-color:#EBECE4", 'READONLY'));
394 if (!$this->_id ||
$this->_isPending
) {
395 $this->addDate('create_date', ts('Pledge Made'), TRUE);
396 $this->addDate('start_date', ts('Payments Start'), TRUE);
402 $eachPaymentAmount = $this->_values
['original_installment_amount'];
403 $this->assign('currency', $this->_values
['currency']);
404 $this->assign('eachPaymentAmount', $eachPaymentAmount);
405 $this->assign('hideCalender', TRUE);
408 if (CRM_Utils_Array
::value('status_id', $this->_values
) !=
409 array_search('Cancelled', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
412 $this->addElement('checkbox', 'is_acknowledge', ts('Send Acknowledgment?'), NULL,
413 array('onclick' => "showHideByValue( 'is_acknowledge', '', 'acknowledgeDate', 'table-row', 'radio', true); showHideByValue( 'is_acknowledge', '', 'fromEmail', 'table-row', 'radio', false );")
416 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
419 $this->addDate('acknowledge_date', ts('Acknowledgment Date'));
421 $this->add('select', 'financial_type_id',
422 ts( 'Financial Type' ),
423 array(''=>ts( '- select -' )) + CRM_Contribute_PseudoConstant
::financialType( ),
427 //CRM-7362 --add campaigns.
428 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
431 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgeBlock', 'entity_table',
432 'civicrm_contribution_page', $pageIds, array('entity_id')
434 $pages = CRM_Contribute_PseudoConstant
::contributionPage();
435 $pledgePages = array();
436 foreach ($pageIds as $key => $value) {
437 $pledgePages[$value['entity_id']] = $pages[$value['entity_id']];
439 $ele = $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'),
441 '' => ts('- select -')) +
$pledgePages
444 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
447 $this->assign('outBound_option', $mailingInfo['outBound_option']);
450 CRM_Custom_Form_CustomData
::buildQuickForm($this);
452 // make this form an upload since we dont know if the custom data injected dynamically
453 // is of type file etc $uploadNames = $this->get( 'uploadNames' );
454 $this->addButtons(array(
457 'name' => ts('Save'),
458 'js' => array('onclick' => "return verify( );"),
463 'name' => ts('Save and New'),
464 'js' => array('onclick' => "return verify( );"),
469 'name' => ts('Cancel'),
474 $this->addFormRule(array('CRM_Pledge_Form_Pledge', 'formRule'), $this);
476 if ($this->_action
& CRM_Core_Action
::VIEW
) {
484 * @param array $fields the input form values
485 * @param array $files the uploaded files if any
486 * @param array $options additional user data
488 * @return true if no errors, else array of errors
492 static function formRule($fields, $files, $self) {
495 //check if contact is selected in standalone mode
496 if (isset($fields['contact_select_id'][1]) && !$fields['contact_select_id'][1]) {
497 $errors['contact[1]'] = ts('Please select a contact or create new contact');
500 if ($fields['amount'] <= 0) {
501 $errors['amount'] = ts('Total Pledge Amount should be greater than zero.');
503 if ($fields['installments'] <= 0) {
504 $errors['installments'] = ts('Installments should be greater than zero.');
507 if ($fields['frequency_unit'] != 'week') {
508 if ($fields['frequency_day'] > 31 ||
$fields['frequency_day'] == 0) {
509 $errors['frequency_day'] = ts('Please enter a valid frequency day ie. 1 through 31.');
512 elseif ($fields['frequency_unit'] == 'week') {
513 if ($fields['frequency_day'] > 7 ||
$fields['frequency_day'] == 0) {
514 $errors['frequency_day'] = ts('Please enter a valid frequency day ie. 1 through 7.');
521 * Function to process the form
527 public function postProcess() {
528 if ($this->_action
& CRM_Core_Action
::DELETE
) {
529 CRM_Pledge_BAO_Pledge
::deletePledge($this->_id
);
533 //get the submitted form values.
534 $formValues = $this->controller
->exportValues($this->_name
);
536 // set the contact, when contact is selected
537 if (!empty($formValues['contact_select_id'])) {
538 $this->_contactID
= $formValues['contact_select_id'][1];
541 $config = CRM_Core_Config
::singleton();
542 $session = CRM_Core_Session
::singleton();
544 //get All Payments status types.
545 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
549 'frequency_interval',
553 'initial_reminder_day',
555 'additional_reminder_day',
556 'contribution_page_id',
559 foreach ($fields as $f) {
560 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
563 //defaults status is "Pending".
564 //if update get status.
566 $params['pledge_status_id'] = $params['status_id'] = $this->_values
['status_id'];
569 $params['pledge_status_id'] = $params['status_id'] = array_search('Pending', $paymentStatusTypes);
572 $params['amount'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('amount', $formValues));
573 $params['currency'] = CRM_Utils_Array
::value('currency', $formValues);
574 $params['original_installment_amount'] = ($params['amount'] / $params['installments']);
576 $dates = array('create_date', 'start_date', 'acknowledge_date', 'cancel_date');
577 foreach ($dates as $d) {
578 if ($this->_id
&& (!$this->_isPending
) && !empty($this->_values
[$d])) {
579 if ($d == 'start_date') {
580 $params['scheduled_date'] = CRM_Utils_Date
::processDate($this->_values
[$d]);
582 $params[$d] = CRM_Utils_Date
::processDate($this->_values
[$d]);
584 elseif (!empty($formValues[$d]) && !CRM_Utils_System
::isNull($formValues[$d])) {
585 if ($d == 'start_date') {
586 $params['scheduled_date'] = CRM_Utils_Date
::processDate($formValues[$d]);
588 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d]);
591 $params[$d] = 'null';
595 if (!empty($formValues['is_acknowledge'])) {
596 $params['acknowledge_date'] = date('Y-m-d');
599 // assign id only in update mode
600 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
601 $params['id'] = $this->_id
;
604 $params['contact_id'] = $this->_contactID
;
607 if (!empty($formValues['hidden_custom'])) {
608 $params['hidden_custom'] = 1;
610 $customFields = CRM_Core_BAO_CustomField
::getFields('Pledge');
611 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($formValues,
618 //handle pending pledge.
619 $params['is_pledge_pending'] = $this->_isPending
;
621 //create pledge record.
622 $pledge = CRM_Pledge_BAO_Pledge
::create($params);
627 //set the status msg.
628 if ($this->_action
& CRM_Core_Action
::ADD
) {
629 $statusMsg = ts('Pledge has been recorded and the payment schedule has been created.<br />');
631 elseif ($this->_action
& CRM_Core_Action
::UPDATE
) {
632 $statusMsg = ts('Pledge has been updated.<br />');
636 //handle Acknowledgment.
637 if (!empty($formValues['is_acknowledge']) && $pledge->id
) {
639 //calculate scheduled amount.
640 $params['scheduled_amount'] = round($params['amount'] / $params['installments']);
641 $params['total_pledge_amount'] = $params['amount'];
642 //get some required pledge values in params.
643 $params['id'] = $pledge->id
;
644 $params['acknowledge_date'] = $pledge->acknowledge_date
;
645 $params['is_test'] = $pledge->is_test
;
646 $params['currency'] = $pledge->currency
;
647 // retrieve 'from email id' for acknowledgement
648 $params['from_email_id'] = $formValues['from_email_address'];
650 $this->paymentId
= NULL;
651 //send Acknowledgment mail.
652 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($this, $params);
654 if (!isset($this->userEmail
)) {
655 list($this->userDisplayName
,
657 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
660 $statusMsg .= ' ' . ts("An acknowledgment email has been sent to %1.<br />", array(1 => $this->userEmail
));
662 //build the payment urls.
663 if ($this->paymentId
) {
664 $urlParams = "reset=1&action=add&cid={$this->_contactID}&ppid={$this->paymentId}&context=pledge";
665 $contribURL = CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams);
666 $urlParams .= "&mode=live";
667 $creditURL = CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams);
669 //check if we can process credit card payment.
670 $processors = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE,
671 "billing_mode IN ( 1, 3 )"
673 if (count($processors) > 0) {
674 $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));
677 $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));
681 CRM_Core_Session
::setStatus($statusMsg, ts('Payment Due'), 'info');
683 $buttonName = $this->controller
->getButtonName();
684 if ($this->_context
== 'standalone') {
685 if ($buttonName == $this->getButtonName('upload', 'new')) {
686 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/pledge/add',
687 'reset=1&action=add&context=standalone'
691 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
692 "reset=1&cid={$this->_contactID}&selectedChild=pledge"
696 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
697 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/pledge',
698 "reset=1&action=add&context=pledge&cid={$this->_contactID}"