3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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
71 public $_honorID = NULL;
74 * The Pledge frequency Units
80 * is current pledge pending.
83 public $_isPending = FALSE;
86 * Function to set variables up before form is built
91 public function preProcess() {
92 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
93 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String',
96 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
97 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
99 // check for action permissions.
100 if (!CRM_Core_Permission
::checkActionPermission('CiviPledge', $this->_action
)) {
101 CRM_Core_Error
::fatal(ts('You do not have permission to access this page'));
104 $this->assign('action', $this->_action
);
105 $this->assign('context', $this->_context
);
106 if ($this->_action
& CRM_Core_Action
::DELETE
) {
110 $this->userDisplayName
= $this->userEmail
= NULL;
111 if ($this->_contactID
) {
112 list($this->userDisplayName
,
114 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
115 $this->assign('displayName', $this->userDisplayName
);
117 // set title to "Pledge - "+Contact Name
118 $displayName = $this->userDisplayName
;
119 $pageTitle = ts('Pledge by'). ' ' . $displayName;
120 $this->assign('pageTitle', $pageTitle);
121 CRM_Utils_System
::setTitle($pageTitle);
125 CRM_Custom_Form_CustomData
::preProcess($this, NULL, NULL, 1, 'Pledge', $this->_id
);
127 $this->_values
= array();
130 //get the contribution id
131 $this->_contributionID
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
132 $this->_id
, 'contribution_id', 'pledge_id'
134 $params = array('id' => $this->_id
);
135 CRM_Pledge_BAO_Pledge
::getValues($params, $this->_values
);
138 $this->_honorID
= CRM_Utils_Array
::value('honor_contact_id', $this->_values
);
140 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
142 //check for pending pledge.
143 if (CRM_Utils_Array
::value('status_id', $this->_values
) ==
144 array_search('Pending', $paymentStatusTypes)
146 $this->_isPending
= TRUE;
148 elseif (CRM_Utils_Array
::value('status_id', $this->_values
) ==
149 array_search('Overdue', $paymentStatusTypes)
152 $allPledgePayments = array();
153 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment',
160 foreach ($allPledgePayments as $key => $value) {
161 $allStatus[$value['id']] = $paymentStatusTypes[$value['status_id']];
164 if (count(array_count_values($allStatus)) <= 2) {
165 if (CRM_Utils_Array
::value('Pending', array_count_values($allStatus))) {
166 $this->_isPending
= TRUE;
172 //get the pledge frequency units.
173 $this->_freqUnits
= CRM_Core_OptionGroup
::values('recur_frequency_units');
175 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
179 * This function sets the default values for the form.
180 * the default values are retrieved from the database
186 function setDefaultValues() {
187 $defaults = $this->_values
;
190 if ($this->_action
& CRM_Core_Action
::DELETE
) {
194 if (CRM_Utils_Array
::value('is_test', $defaults)) {
195 $this->assign('is_test', TRUE);
199 $startDate = CRM_Utils_Array
::value('start_date', $this->_values
);
200 $createDate = CRM_Utils_Array
::value('create_date', $this->_values
);
201 list($defaults['start_date']) = CRM_Utils_Date
::setDateDefaults($startDate);
202 list($defaults['create_date']) = CRM_Utils_Date
::setDateDefaults($createDate);
204 if ($ackDate = CRM_Utils_Array
::value('acknowledge_date', $this->_values
)) {
205 list($defaults['acknowledge_date']) = CRM_Utils_Date
::setDateDefaults($ackDate);
208 //check is this pledge pending
209 // fix the display of the monetary value, CRM-4038
210 if ($this->_isPending
) {
211 $defaults['eachPaymentAmount'] = $this->_values
['amount'] / $this->_values
['installments'];
212 $defaults['eachPaymentAmount'] = CRM_Utils_Money
::format($defaults['eachPaymentAmount'], NULL, '%a');
215 $this->assign('start_date', $startDate);
216 $this->assign('create_date', $createDate);
218 // fix the display of the monetary value, CRM-4038
219 if (isset($this->_values
['amount'])) {
220 $defaults['amount'] = CRM_Utils_Money
::format($this->_values
['amount'], NULL, '%a');
222 $this->assign('amount', $this->_values
['amount']);
223 $this->assign('installments', $defaults['installments']);
227 list($now) = CRM_Utils_Date
::setDateDefaults();
228 $defaults['create_date'] = $now;
229 $defaults['start_date'] = $now;
230 $defaults['installments'] = 12;
231 $defaults['frequency_interval'] = 1;
232 $defaults['frequency_day'] = 1;
233 $defaults['initial_reminder_day'] = 5;
234 $defaults['max_reminders'] = 1;
235 $defaults['additional_reminder_day'] = 5;
236 $defaults['frequency_unit'] = array_search('month', $this->_freqUnits
);
237 $defaults['financial_type_id'] = array_search( 'Donation', CRM_Contribute_PseudoConstant
::financialType() );
240 $pledgeStatus = CRM_Contribute_PseudoConstant
::contributionStatus();
241 $pledgeStatusNames = CRM_Core_OptionGroup
::values('contribution_status',
242 FALSE, FALSE, FALSE, NULL, 'name', TRUE
244 // get default status label (pending)
245 $defaultPledgeStatus = CRM_Utils_Array
::value(array_search('Pending', $pledgeStatusNames),
250 $this->assign('status', CRM_Utils_Array
::value(CRM_Utils_Array
::value('status_id', $this->_values
),
256 if ($this->_honorID
) {
257 $honorDefault = array();
258 $idParams = array('contact_id' => $this->_honorID
);
259 CRM_Contact_BAO_Contact
::retrieve($idParams, $honorDefault);
260 $honorType = CRM_Core_PseudoConstant
::get('CRM_Pledge_DAO_Pledge', 'honor_type_id');
261 $defaults['honor_prefix_id'] = $honorDefault['prefix_id'];
262 $defaults['honor_first_name'] = CRM_Utils_Array
::value('first_name', $honorDefault);
263 $defaults['honor_last_name'] = CRM_Utils_Array
::value('last_name', $honorDefault);
264 $defaults['honor_email'] = CRM_Utils_Array
::value('email', $honorDefault['email'][1]);
265 $defaults['honor_type'] = $honorType[$defaults['honor_type_id']];
268 if (isset($this->userEmail
)) {
269 $this->assign('email', $this->userEmail
);
272 // custom data set defaults
273 $defaults +
= CRM_Custom_Form_CustomData
::setDefaultValues($this);
279 * Function to build the form
284 public function buildQuickForm() {
285 if ($this->_action
& CRM_Core_Action
::DELETE
) {
286 $this->addButtons(array(
289 'name' => ts('Delete'),
290 'spacing' => ' ',
295 'name' => ts('Cancel'),
302 if ($this->_context
== 'standalone') {
303 CRM_Contact_Form_NewContact
::buildQuickForm($this);
306 $showAdditionalInfo = FALSE;
307 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
309 //fix to load honoree pane on edit.
311 if ($this->_honorID
) {
312 $defaults['hidden_Honoree'] = 1;
316 'Honoree Information' => 'Honoree',
317 'Payment Reminders' => 'PaymentReminders',
319 foreach ($paneNames as $name => $type) {
320 $urlParams = "snippet=4&formType={$type}";
321 $allPanes[$name] = array('url' => CRM_Utils_System
::url('civicrm/contact/view/pledge', $urlParams),
325 //see if we need to include this paneName in the current form
326 if ($this->_formType
== $type ||
327 CRM_Utils_Array
::value("hidden_{$type}", $_POST) ||
328 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
330 $showAdditionalInfo = TRUE;
331 $allPanes[$name]['open'] = 'true';
333 eval('CRM_Contribute_Form_AdditionalInfo::build' . $type . '( $this );');
336 $this->assign('allPanes', $allPanes);
337 $this->assign('showAdditionalInfo', $showAdditionalInfo);
339 if ($this->_formType
) {
340 $this->assign('formType', $this->_formType
);
344 $this->applyFilter('__ALL__', 'trim');
347 $attributes = CRM_Core_DAO
::getAttribute('CRM_Pledge_DAO_Pledge');
349 $this->assign('isPending', $this->_isPending
);
352 'onblur' => "calculatedPaymentAmount( );",
353 'onkeyup' => "calculatedPaymentAmount( );",
356 $currencyFreeze = FALSE;
360 $currencyFreeze = TRUE;
363 $element = $this->addMoney('amount', ts('Total Pledge Amount'), TRUE,
364 array_merge($attributes['pledge_amount'], $js), TRUE,
365 'currency', NULL, $currencyFreeze
374 $element = &$this->add('text', 'installments', ts('To be paid in'),
375 array_merge($attributes['installments'], $js), TRUE
377 $this->addRule('installments', ts('Please enter a valid number of installments.'), 'positiveInteger');
384 $element = &$this->add('text', 'frequency_interval', ts('every'),
385 $attributes['pledge_frequency_interval'], TRUE
387 $this->addRule('frequency_interval', ts('Please enter a number for frequency (e.g. every "3" months).'), 'positiveInteger');
394 // Fix frequency unit display for use with frequency_interval
395 $freqUnitsDisplay = array();
396 foreach ($this->_freqUnits
as $val => $label) {
397 $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
399 $element = &$this->add('select', 'frequency_unit',
402 '' => ts('- select -')) +
$freqUnitsDisplay,
412 $element = &$this->add('text', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], TRUE);
413 $this->addRule('frequency_day', ts('Please enter a valid payment due day.'), 'positiveInteger');
420 $this->add('text', 'eachPaymentAmount', ts('each'), array('size' => 10, 'style' => "background-color:#EBECE4", 'READONLY'));
423 if (!$this->_id ||
$this->_isPending
) {
424 $this->addDate('create_date', ts('Pledge Made'), TRUE);
425 $this->addDate('start_date', ts('Payments Start'), TRUE);
431 $eachPaymentAmount = $this->_values
['original_installment_amount'];
432 $this->assign('currency', $this->_values
['currency']);
433 $this->assign('eachPaymentAmount', $eachPaymentAmount);
434 $this->assign('hideCalender', TRUE);
437 if (CRM_Utils_Array
::value('status_id', $this->_values
) !=
438 array_search('Cancelled', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
441 $this->addElement('checkbox', 'is_acknowledge', ts('Send Acknowledgment?'), NULL,
442 array('onclick' => "showHideByValue( 'is_acknowledge', '', 'acknowledgeDate', 'table-row', 'radio', true); showHideByValue( 'is_acknowledge', '', 'fromEmail', 'table-row', 'radio', false );")
445 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
448 $this->addDate('acknowledge_date', ts('Acknowledgment Date'));
450 $this->add('select', 'financial_type_id',
451 ts( 'Financial Type' ),
452 array(''=>ts( '- select -' )) + CRM_Contribute_PseudoConstant
::financialType( ),
456 //CRM-7362 --add campaigns.
457 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
460 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgeBlock', 'entity_table',
461 'civicrm_contribution_page', $pageIds, array('entity_id')
463 $pages = CRM_Contribute_PseudoConstant
::contributionPage();
464 $pledgePages = array();
465 foreach ($pageIds as $key => $value) {
466 $pledgePages[$value['entity_id']] = $pages[$value['entity_id']];
468 $ele = $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'),
470 '' => ts('- select -')) +
$pledgePages
473 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
476 $this->assign('outBound_option', $mailingInfo['outBound_option']);
479 CRM_Custom_Form_CustomData
::buildQuickForm($this);
481 // make this form an upload since we dont know if the custom data injected dynamically
482 // is of type file etc $uploadNames = $this->get( 'uploadNames' );
483 $this->addButtons(array(
486 'name' => ts('Save'),
487 'js' => array('onclick' => "return verify( );"),
492 'name' => ts('Save and New'),
493 'js' => array('onclick' => "return verify( );"),
498 'name' => ts('Cancel'),
503 $this->addFormRule(array('CRM_Pledge_Form_Pledge', 'formRule'), $this);
505 if ($this->_action
& CRM_Core_Action
::VIEW
) {
513 * @param array $fields the input form values
514 * @param array $files the uploaded files if any
515 * @param array $options additional user data
517 * @return true if no errors, else array of errors
521 static function formRule($fields, $files, $self) {
524 //check if contact is selected in standalone mode
525 if (isset($fields['contact_select_id'][1]) && !$fields['contact_select_id'][1]) {
526 $errors['contact[1]'] = ts('Please select a contact or create new contact');
529 if (isset($fields['honor_type_id'])) {
530 if (!((CRM_Utils_Array
::value('honor_first_name', $fields) &&
531 CRM_Utils_Array
::value('honor_last_name', $fields)
533 CRM_Utils_Array
::value('honor_email', $fields)
535 $errors['honor_first_name'] = ts('Honor First Name and Last Name OR an email should be set.');
538 if ($fields['amount'] <= 0) {
539 $errors['amount'] = ts('Total Pledge Amount should be greater than zero.');
541 if ($fields['installments'] <= 0) {
542 $errors['installments'] = ts('Installments should be greater than zero.');
545 if ($fields['frequency_unit'] != 'week') {
546 if ($fields['frequency_day'] > 31 ||
$fields['frequency_day'] == 0) {
547 $errors['frequency_day'] = ts('Please enter a valid frequency day ie. 1 through 31.');
550 elseif ($fields['frequency_unit'] == 'week') {
551 if ($fields['frequency_day'] > 7 ||
$fields['frequency_day'] == 0) {
552 $errors['frequency_day'] = ts('Please enter a valid frequency day ie. 1 through 7.');
559 * Function to process the form
565 public function postProcess() {
566 if ($this->_action
& CRM_Core_Action
::DELETE
) {
567 CRM_Pledge_BAO_Pledge
::deletePledge($this->_id
);
571 //get the submitted form values.
572 $formValues = $this->controller
->exportValues($this->_name
);
574 // set the contact, when contact is selected
575 if (CRM_Utils_Array
::value('contact_select_id', $formValues)) {
576 $this->_contactID
= $formValues['contact_select_id'][1];
579 $config = CRM_Core_Config
::singleton();
580 $session = CRM_Core_Session
::singleton();
582 //get All Payments status types.
583 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
587 'frequency_interval',
591 'initial_reminder_day',
593 'additional_reminder_day',
599 'contribution_page_id',
602 foreach ($fields as $f) {
603 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
606 //defaults status is "Pending".
607 //if update get status.
609 $params['pledge_status_id'] = $params['status_id'] = $this->_values
['status_id'];
612 $params['pledge_status_id'] = $params['status_id'] = array_search('Pending', $paymentStatusTypes);
615 $params['amount'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('amount', $formValues));
616 $params['currency'] = CRM_Utils_Array
::value('currency', $formValues);
617 $params['original_installment_amount'] = ($params['amount'] / $params['installments']);
619 $dates = array('create_date', 'start_date', 'acknowledge_date', 'cancel_date');
620 foreach ($dates as $d) {
621 if ($this->_id
&& (!$this->_isPending
) && CRM_Utils_Array
::value($d, $this->_values
)) {
622 if ($d == 'start_date') {
623 $params['scheduled_date'] = CRM_Utils_Date
::processDate($this->_values
[$d]);
625 $params[$d] = CRM_Utils_Date
::processDate($this->_values
[$d]);
627 elseif (CRM_Utils_Array
::value($d, $formValues) && !CRM_Utils_System
::isNull($formValues[$d])) {
628 if ($d == 'start_date') {
629 $params['scheduled_date'] = CRM_Utils_Date
::processDate($formValues[$d]);
631 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d]);
634 $params[$d] = 'null';
638 if (CRM_Utils_Array
::value('is_acknowledge', $formValues)) {
639 $params['acknowledge_date'] = date('Y-m-d');
642 // assign id only in update mode
643 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
644 $params['id'] = $this->_id
;
647 $params['contact_id'] = $this->_contactID
;
649 //handle Honoree contact.
650 if (CRM_Utils_Array
::value('honor_type_id', $params)) {
651 if ($this->_honorID
) {
652 $honorID = CRM_Contribute_BAO_Contribution
::createHonorContact($params, $this->_honorID
);
655 $honorID = CRM_Contribute_BAO_Contribution
::createHonorContact($params);
657 $params['honor_contact_id'] = $honorID;
660 $params['honor_contact_id'] = 'null';
664 if (CRM_Utils_Array
::value('hidden_custom', $formValues)) {
665 $params['hidden_custom'] = 1;
667 $customFields = CRM_Core_BAO_CustomField
::getFields('Pledge');
668 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($formValues,
675 //handle pending pledge.
676 $params['is_pledge_pending'] = $this->_isPending
;
678 //create pledge record.
679 $pledge = CRM_Pledge_BAO_Pledge
::create($params);
684 //set the status msg.
685 if ($this->_action
& CRM_Core_Action
::ADD
) {
686 $statusMsg = ts('Pledge has been recorded and the payment schedule has been created.<br />');
688 elseif ($this->_action
& CRM_Core_Action
::UPDATE
) {
689 $statusMsg = ts('Pledge has been updated.<br />');
693 //handle Acknowledgment.
694 if (CRM_Utils_Array
::value('is_acknowledge', $formValues) && $pledge->id
) {
696 //calculate scheduled amount.
697 $params['scheduled_amount'] = round($params['amount'] / $params['installments']);
698 $params['total_pledge_amount'] = $params['amount'];
699 //get some required pledge values in params.
700 $params['id'] = $pledge->id
;
701 $params['acknowledge_date'] = $pledge->acknowledge_date
;
702 $params['is_test'] = $pledge->is_test
;
703 $params['currency'] = $pledge->currency
;
704 // retrieve 'from email id' for acknowledgement
705 $params['from_email_id'] = $formValues['from_email_address'];
707 $this->paymentId
= NULL;
708 //send Acknowledgment mail.
709 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($this, $params);
711 if (!isset($this->userEmail
)) {
712 list($this->userDisplayName
,
714 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
717 $statusMsg .= ' ' . ts("An acknowledgment email has been sent to %1.<br />", array(1 => $this->userEmail
));
719 //build the payment urls.
720 if ($this->paymentId
) {
721 $urlParams = "reset=1&action=add&cid={$this->_contactID}&ppid={$this->paymentId}&context=pledge";
722 $contribURL = CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams);
723 $urlParams .= "&mode=live";
724 $creditURL = CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams);
726 //check if we can process credit card payment.
727 $processors = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE,
728 "billing_mode IN ( 1, 3 )"
730 if (count($processors) > 0) {
731 $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));
734 $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));
738 CRM_Core_Session
::setStatus($statusMsg, ts('Payment Due'), 'info');
740 $buttonName = $this->controller
->getButtonName();
741 if ($this->_context
== 'standalone') {
742 if ($buttonName == $this->getButtonName('upload', 'new')) {
743 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/pledge/add',
744 'reset=1&action=add&context=standalone'
748 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
749 "reset=1&cid={$this->_contactID}&selectedChild=pledge"
753 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
754 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/pledge',
755 "reset=1&action=add&context=pledge&cid={$this->_contactID}"