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 $fnName = "build{$type}";
334 CRM_Contribute_Form_AdditionalInfo
::$fnName($this);
337 $this->assign('allPanes', $allPanes);
338 $this->assign('showAdditionalInfo', $showAdditionalInfo);
340 if ($this->_formType
) {
341 $this->assign('formType', $this->_formType
);
345 $this->applyFilter('__ALL__', 'trim');
348 $attributes = CRM_Core_DAO
::getAttribute('CRM_Pledge_DAO_Pledge');
350 $this->assign('isPending', $this->_isPending
);
353 'onblur' => "calculatedPaymentAmount( );",
354 'onkeyup' => "calculatedPaymentAmount( );",
357 $currencyFreeze = FALSE;
361 $currencyFreeze = TRUE;
364 $element = $this->addMoney('amount', ts('Total Pledge Amount'), TRUE,
365 array_merge($attributes['pledge_amount'], $js), TRUE,
366 'currency', NULL, $currencyFreeze
375 $element = &$this->add('text', 'installments', ts('To be paid in'),
376 array_merge($attributes['installments'], $js), TRUE
378 $this->addRule('installments', ts('Please enter a valid number of installments.'), 'positiveInteger');
385 $element = &$this->add('text', 'frequency_interval', ts('every'),
386 $attributes['pledge_frequency_interval'], TRUE
388 $this->addRule('frequency_interval', ts('Please enter a number for frequency (e.g. every "3" months).'), 'positiveInteger');
395 // Fix frequency unit display for use with frequency_interval
396 $freqUnitsDisplay = array();
397 foreach ($this->_freqUnits
as $val => $label) {
398 $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
400 $element = &$this->add('select', 'frequency_unit',
403 '' => ts('- select -')) +
$freqUnitsDisplay,
413 $element = &$this->add('text', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], TRUE);
414 $this->addRule('frequency_day', ts('Please enter a valid payment due day.'), 'positiveInteger');
421 $this->add('text', 'eachPaymentAmount', ts('each'), array('size' => 10, 'style' => "background-color:#EBECE4", 'READONLY'));
424 if (!$this->_id ||
$this->_isPending
) {
425 $this->addDate('create_date', ts('Pledge Made'), TRUE);
426 $this->addDate('start_date', ts('Payments Start'), TRUE);
432 $eachPaymentAmount = $this->_values
['original_installment_amount'];
433 $this->assign('currency', $this->_values
['currency']);
434 $this->assign('eachPaymentAmount', $eachPaymentAmount);
435 $this->assign('hideCalender', TRUE);
438 if (CRM_Utils_Array
::value('status_id', $this->_values
) !=
439 array_search('Cancelled', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
442 $this->addElement('checkbox', 'is_acknowledge', ts('Send Acknowledgment?'), NULL,
443 array('onclick' => "showHideByValue( 'is_acknowledge', '', 'acknowledgeDate', 'table-row', 'radio', true); showHideByValue( 'is_acknowledge', '', 'fromEmail', 'table-row', 'radio', false );")
446 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
449 $this->addDate('acknowledge_date', ts('Acknowledgment Date'));
451 $this->add('select', 'financial_type_id',
452 ts( 'Financial Type' ),
453 array(''=>ts( '- select -' )) + CRM_Contribute_PseudoConstant
::financialType( ),
457 //CRM-7362 --add campaigns.
458 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
461 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgeBlock', 'entity_table',
462 'civicrm_contribution_page', $pageIds, array('entity_id')
464 $pages = CRM_Contribute_PseudoConstant
::contributionPage();
465 $pledgePages = array();
466 foreach ($pageIds as $key => $value) {
467 $pledgePages[$value['entity_id']] = $pages[$value['entity_id']];
469 $ele = $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'),
471 '' => ts('- select -')) +
$pledgePages
474 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
477 $this->assign('outBound_option', $mailingInfo['outBound_option']);
480 CRM_Custom_Form_CustomData
::buildQuickForm($this);
482 // make this form an upload since we dont know if the custom data injected dynamically
483 // is of type file etc $uploadNames = $this->get( 'uploadNames' );
484 $this->addButtons(array(
487 'name' => ts('Save'),
488 'js' => array('onclick' => "return verify( );"),
493 'name' => ts('Save and New'),
494 'js' => array('onclick' => "return verify( );"),
499 'name' => ts('Cancel'),
504 $this->addFormRule(array('CRM_Pledge_Form_Pledge', 'formRule'), $this);
506 if ($this->_action
& CRM_Core_Action
::VIEW
) {
514 * @param array $fields the input form values
515 * @param array $files the uploaded files if any
516 * @param array $options additional user data
518 * @return true if no errors, else array of errors
522 static function formRule($fields, $files, $self) {
525 //check if contact is selected in standalone mode
526 if (isset($fields['contact_select_id'][1]) && !$fields['contact_select_id'][1]) {
527 $errors['contact[1]'] = ts('Please select a contact or create new contact');
530 if (isset($fields['honor_type_id'])) {
531 if (!((CRM_Utils_Array
::value('honor_first_name', $fields) &&
532 CRM_Utils_Array
::value('honor_last_name', $fields)
534 CRM_Utils_Array
::value('honor_email', $fields)
536 $errors['honor_first_name'] = ts('Honor First Name and Last Name OR an email should be set.');
539 if ($fields['amount'] <= 0) {
540 $errors['amount'] = ts('Total Pledge Amount should be greater than zero.');
542 if ($fields['installments'] <= 0) {
543 $errors['installments'] = ts('Installments should be greater than zero.');
546 if ($fields['frequency_unit'] != 'week') {
547 if ($fields['frequency_day'] > 31 ||
$fields['frequency_day'] == 0) {
548 $errors['frequency_day'] = ts('Please enter a valid frequency day ie. 1 through 31.');
551 elseif ($fields['frequency_unit'] == 'week') {
552 if ($fields['frequency_day'] > 7 ||
$fields['frequency_day'] == 0) {
553 $errors['frequency_day'] = ts('Please enter a valid frequency day ie. 1 through 7.');
560 * Function to process the form
566 public function postProcess() {
567 if ($this->_action
& CRM_Core_Action
::DELETE
) {
568 CRM_Pledge_BAO_Pledge
::deletePledge($this->_id
);
572 //get the submitted form values.
573 $formValues = $this->controller
->exportValues($this->_name
);
575 // set the contact, when contact is selected
576 if (CRM_Utils_Array
::value('contact_select_id', $formValues)) {
577 $this->_contactID
= $formValues['contact_select_id'][1];
580 $config = CRM_Core_Config
::singleton();
581 $session = CRM_Core_Session
::singleton();
583 //get All Payments status types.
584 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
588 'frequency_interval',
592 'initial_reminder_day',
594 'additional_reminder_day',
600 'contribution_page_id',
603 foreach ($fields as $f) {
604 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
607 //defaults status is "Pending".
608 //if update get status.
610 $params['pledge_status_id'] = $params['status_id'] = $this->_values
['status_id'];
613 $params['pledge_status_id'] = $params['status_id'] = array_search('Pending', $paymentStatusTypes);
616 $params['amount'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('amount', $formValues));
617 $params['currency'] = CRM_Utils_Array
::value('currency', $formValues);
618 $params['original_installment_amount'] = ($params['amount'] / $params['installments']);
620 $dates = array('create_date', 'start_date', 'acknowledge_date', 'cancel_date');
621 foreach ($dates as $d) {
622 if ($this->_id
&& (!$this->_isPending
) && CRM_Utils_Array
::value($d, $this->_values
)) {
623 if ($d == 'start_date') {
624 $params['scheduled_date'] = CRM_Utils_Date
::processDate($this->_values
[$d]);
626 $params[$d] = CRM_Utils_Date
::processDate($this->_values
[$d]);
628 elseif (CRM_Utils_Array
::value($d, $formValues) && !CRM_Utils_System
::isNull($formValues[$d])) {
629 if ($d == 'start_date') {
630 $params['scheduled_date'] = CRM_Utils_Date
::processDate($formValues[$d]);
632 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d]);
635 $params[$d] = 'null';
639 if (CRM_Utils_Array
::value('is_acknowledge', $formValues)) {
640 $params['acknowledge_date'] = date('Y-m-d');
643 // assign id only in update mode
644 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
645 $params['id'] = $this->_id
;
648 $params['contact_id'] = $this->_contactID
;
650 //handle Honoree contact.
651 if (CRM_Utils_Array
::value('honor_type_id', $params)) {
652 if ($this->_honorID
) {
653 $honorID = CRM_Contribute_BAO_Contribution
::createHonorContact($params, $this->_honorID
);
656 $honorID = CRM_Contribute_BAO_Contribution
::createHonorContact($params);
658 $params['honor_contact_id'] = $honorID;
661 $params['honor_contact_id'] = 'null';
665 if (CRM_Utils_Array
::value('hidden_custom', $formValues)) {
666 $params['hidden_custom'] = 1;
668 $customFields = CRM_Core_BAO_CustomField
::getFields('Pledge');
669 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($formValues,
676 //handle pending pledge.
677 $params['is_pledge_pending'] = $this->_isPending
;
679 //create pledge record.
680 $pledge = CRM_Pledge_BAO_Pledge
::create($params);
685 //set the status msg.
686 if ($this->_action
& CRM_Core_Action
::ADD
) {
687 $statusMsg = ts('Pledge has been recorded and the payment schedule has been created.<br />');
689 elseif ($this->_action
& CRM_Core_Action
::UPDATE
) {
690 $statusMsg = ts('Pledge has been updated.<br />');
694 //handle Acknowledgment.
695 if (CRM_Utils_Array
::value('is_acknowledge', $formValues) && $pledge->id
) {
697 //calculate scheduled amount.
698 $params['scheduled_amount'] = round($params['amount'] / $params['installments']);
699 $params['total_pledge_amount'] = $params['amount'];
700 //get some required pledge values in params.
701 $params['id'] = $pledge->id
;
702 $params['acknowledge_date'] = $pledge->acknowledge_date
;
703 $params['is_test'] = $pledge->is_test
;
704 $params['currency'] = $pledge->currency
;
705 // retrieve 'from email id' for acknowledgement
706 $params['from_email_id'] = $formValues['from_email_address'];
708 $this->paymentId
= NULL;
709 //send Acknowledgment mail.
710 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($this, $params);
712 if (!isset($this->userEmail
)) {
713 list($this->userDisplayName
,
715 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
718 $statusMsg .= ' ' . ts("An acknowledgment email has been sent to %1.<br />", array(1 => $this->userEmail
));
720 //build the payment urls.
721 if ($this->paymentId
) {
722 $urlParams = "reset=1&action=add&cid={$this->_contactID}&ppid={$this->paymentId}&context=pledge";
723 $contribURL = CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams);
724 $urlParams .= "&mode=live";
725 $creditURL = CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams);
727 //check if we can process credit card payment.
728 $processors = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE,
729 "billing_mode IN ( 1, 3 )"
731 if (count($processors) > 0) {
732 $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));
735 $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));
739 CRM_Core_Session
::setStatus($statusMsg, ts('Payment Due'), 'info');
741 $buttonName = $this->controller
->getButtonName();
742 if ($this->_context
== 'standalone') {
743 if ($buttonName == $this->getButtonName('upload', 'new')) {
744 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/pledge/add',
745 'reset=1&action=add&context=standalone'
749 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
750 "reset=1&cid={$this->_contactID}&selectedChild=pledge"
754 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
755 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/pledge',
756 "reset=1&action=add&context=pledge&cid={$this->_contactID}"