3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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
51 * The id of the contact associated with this pledge
58 * The Pledge values if an existing pledge
63 * The Pledge frequency Units
68 * Is current pledge pending.
70 public $_isPending = FALSE;
73 * Set variables up before form is built
77 public function preProcess() {
78 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
79 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String',
82 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
83 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
85 // check for action permissions.
86 if (!CRM_Core_Permission
::checkActionPermission('CiviPledge', $this->_action
)) {
87 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
90 $this->assign('action', $this->_action
);
91 $this->assign('context', $this->_context
);
92 if ($this->_action
& CRM_Core_Action
::DELETE
) {
96 $this->userDisplayName
= $this->userEmail
= NULL;
97 if ($this->_contactID
) {
98 list($this->userDisplayName
,
100 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
101 $this->assign('displayName', $this->userDisplayName
);
104 $this->setPageTitle(ts('Pledge'));
107 CRM_Custom_Form_CustomData
::preProcess($this, NULL, NULL, 1, 'Pledge', $this->_id
);
108 $this->_values
= array();
111 //get the contribution id
112 $this->_contributionID
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
113 $this->_id
, 'contribution_id', 'pledge_id'
115 $params = array('id' => $this->_id
);
116 CRM_Pledge_BAO_Pledge
::getValues($params, $this->_values
);
118 $this->_isPending
= (CRM_Pledge_BAO_Pledge
::pledgeHasFinancialTransactions($this->_id
, CRM_Utils_Array
::value('status_id', $this->_values
))) ?
FALSE : T
;
121 //get the pledge frequency units.
122 $this->_freqUnits
= CRM_Core_OptionGroup
::values('recur_frequency_units');
124 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
129 * Set default values for the form.
130 * the default values are retrieved from the database
135 public function setDefaultValues() {
136 $defaults = $this->_values
;
139 if ($this->_action
& CRM_Core_Action
::DELETE
) {
143 if (!empty($defaults['is_test'])) {
144 $this->assign('is_test', TRUE);
148 $startDate = CRM_Utils_Array
::value('start_date', $this->_values
);
149 $createDate = CRM_Utils_Array
::value('create_date', $this->_values
);
150 list($defaults['start_date']) = CRM_Utils_Date
::setDateDefaults($startDate);
151 list($defaults['create_date']) = CRM_Utils_Date
::setDateDefaults($createDate);
153 if ($ackDate = CRM_Utils_Array
::value('acknowledge_date', $this->_values
)) {
154 list($defaults['acknowledge_date']) = CRM_Utils_Date
::setDateDefaults($ackDate);
157 //check is this pledge pending
158 // fix the display of the monetary value, CRM-4038
159 if ($this->_isPending
) {
160 $defaults['eachPaymentAmount'] = $this->_values
['amount'] / $this->_values
['installments'];
161 $defaults['eachPaymentAmount'] = CRM_Utils_Money
::format($defaults['eachPaymentAmount'], NULL, '%a');
164 $this->assign('start_date', $startDate);
165 $this->assign('create_date', $createDate);
167 // fix the display of the monetary value, CRM-4038
168 if (isset($this->_values
['amount'])) {
169 $defaults['amount'] = CRM_Utils_Money
::format($this->_values
['amount'], NULL, '%a');
171 $this->assign('amount', $this->_values
['amount']);
172 $this->assign('installments', $defaults['installments']);
176 list($now) = CRM_Utils_Date
::setDateDefaults();
177 $defaults['create_date'] = $now;
178 $defaults['start_date'] = $now;
179 $defaults['installments'] = 12;
180 $defaults['frequency_interval'] = 1;
181 $defaults['frequency_day'] = 1;
182 $defaults['initial_reminder_day'] = 5;
183 $defaults['max_reminders'] = 1;
184 $defaults['additional_reminder_day'] = 5;
185 $defaults['frequency_unit'] = array_search('month', $this->_freqUnits
);
186 $defaults['financial_type_id'] = array_search( 'Donation', CRM_Contribute_PseudoConstant
::financialType() );
189 $pledgeStatus = CRM_Contribute_PseudoConstant
::contributionStatus();
190 $pledgeStatusNames = CRM_Core_OptionGroup
::values('contribution_status',
191 FALSE, FALSE, FALSE, NULL, 'name', TRUE
193 // get default status label (pending)
194 $defaultPledgeStatus = CRM_Utils_Array
::value(array_search('Pending', $pledgeStatusNames),
199 $this->assign('status', CRM_Utils_Array
::value(CRM_Utils_Array
::value('status_id', $this->_values
),
204 if (isset($this->userEmail
)) {
205 $this->assign('email', $this->userEmail
);
208 // custom data set defaults
209 $defaults +
= CRM_Custom_Form_CustomData
::setDefaultValues($this);
215 * Build the form object
219 public function buildQuickForm() {
220 if ($this->_action
& CRM_Core_Action
::DELETE
) {
221 $this->addButtons(array(
224 'name' => ts('Delete'),
225 'spacing' => ' ',
230 'name' => ts('Cancel'),
237 if ($this->_context
== 'standalone') {
238 $this->addEntityRef('contact_id', ts('Contact'), array('create' => TRUE, 'api' => array('extra' => array('email'))), TRUE);
241 $showAdditionalInfo = FALSE;
242 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
247 'Payment Reminders' => 'PaymentReminders',
249 foreach ($paneNames as $name => $type) {
250 $urlParams = "snippet=4&formType={$type}";
251 $allPanes[$name] = array('url' => CRM_Utils_System
::url('civicrm/contact/view/pledge', $urlParams),
255 //see if we need to include this paneName in the current form
256 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
257 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
259 $showAdditionalInfo = TRUE;
260 $allPanes[$name]['open'] = 'true';
262 $fnName = "build{$type}";
263 CRM_Contribute_Form_AdditionalInfo
::$fnName($this);
266 $this->assign('allPanes', $allPanes);
267 $this->assign('showAdditionalInfo', $showAdditionalInfo);
269 if ($this->_formType
) {
270 $this->assign('formType', $this->_formType
);
274 $this->applyFilter('__ALL__', 'trim');
277 $attributes = CRM_Core_DAO
::getAttribute('CRM_Pledge_DAO_Pledge');
279 $this->assign('isPending', $this->_isPending
);
282 'onblur' => "calculatedPaymentAmount( );",
283 'onkeyup' => "calculatedPaymentAmount( );",
286 $currencyFreeze = FALSE;
290 $currencyFreeze = TRUE;
293 $element = $this->addMoney('amount', ts('Total Pledge Amount'), TRUE,
294 array_merge($attributes['pledge_amount'], $js), TRUE,
295 'currency', NULL, $currencyFreeze
304 $element = &$this->add('text', 'installments', ts('To be paid in'),
305 array_merge($attributes['installments'], $js), TRUE
307 $this->addRule('installments', ts('Please enter a valid number of installments.'), 'positiveInteger');
314 $element = &$this->add('text', 'frequency_interval', ts('every'),
315 $attributes['pledge_frequency_interval'], TRUE
317 $this->addRule('frequency_interval', ts('Please enter a number for frequency (e.g. every "3" months).'), 'positiveInteger');
324 // Fix frequency unit display for use with frequency_interval
325 $freqUnitsDisplay = array();
326 foreach ($this->_freqUnits
as $val => $label) {
327 $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
329 $element = &$this->add('select', 'frequency_unit',
332 '' => ts('- select -')) +
$freqUnitsDisplay,
342 $element = &$this->add('text', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], TRUE);
343 $this->addRule('frequency_day', ts('Please enter a valid payment due day.'), 'positiveInteger');
350 $this->add('text', 'eachPaymentAmount', ts('each'), array('size' => 10, 'style' => "background-color:#EBECE4", 'READONLY'));
353 if (!$this->_id ||
$this->_isPending
) {
354 $this->addDate('create_date', ts('Pledge Made'), TRUE);
355 $this->addDate('start_date', ts('Payments Start'), TRUE);
361 $eachPaymentAmount = $this->_values
['original_installment_amount'];
362 $this->assign('currency', $this->_values
['currency']);
363 $this->assign('eachPaymentAmount', $eachPaymentAmount);
364 $this->assign('hideCalender', TRUE);
367 if (CRM_Utils_Array
::value('status_id', $this->_values
) !=
368 array_search('Cancelled', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
371 $this->addElement('checkbox', 'is_acknowledge', ts('Send Acknowledgment?'), NULL,
372 array('onclick' => "showHideByValue( 'is_acknowledge', '', 'acknowledgeDate', 'table-row', 'radio', true); showHideByValue( 'is_acknowledge', '', 'fromEmail', 'table-row', 'radio', false );")
375 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
378 $this->addDate('acknowledge_date', ts('Acknowledgment Date'));
380 $this->add('select', 'financial_type_id',
381 ts( 'Financial Type' ),
382 array(''=>ts( '- select -' )) + CRM_Contribute_PseudoConstant
::financialType( ),
386 //CRM-7362 --add campaigns.
387 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
390 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgeBlock', 'entity_table',
391 'civicrm_contribution_page', $pageIds, array('entity_id')
393 $pages = CRM_Contribute_PseudoConstant
::contributionPage();
394 $pledgePages = array();
395 foreach ($pageIds as $key => $value) {
396 $pledgePages[$value['entity_id']] = $pages[$value['entity_id']];
398 $ele = $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'),
400 '' => ts('- select -')) +
$pledgePages
403 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
406 $this->assign('outBound_option', $mailingInfo['outBound_option']);
409 CRM_Custom_Form_CustomData
::buildQuickForm($this);
411 // make this form an upload since we dont know if the custom data injected dynamically
412 // is of type file etc $uploadNames = $this->get( 'uploadNames' );
413 $this->addButtons(array(
416 'name' => ts('Save'),
417 'js' => array('onclick' => "return verify( );"),
422 'name' => ts('Save and New'),
423 'js' => array('onclick' => "return verify( );"),
428 'name' => ts('Cancel'),
433 $this->addFormRule(array('CRM_Pledge_Form_Pledge', 'formRule'), $this);
435 if ($this->_action
& CRM_Core_Action
::VIEW
) {
443 * @param array $fields the input form values
444 * @param array $files the uploaded files if any
448 * @return true if no errors, else array of errors
451 public static function formRule($fields, $files, $self) {
454 if ($fields['amount'] <= 0) {
455 $errors['amount'] = ts('Total Pledge Amount should be greater than zero.');
457 if ($fields['installments'] <= 0) {
458 $errors['installments'] = ts('Installments should be greater than zero.');
461 if ($fields['frequency_unit'] != 'week') {
462 if ($fields['frequency_day'] > 31 ||
$fields['frequency_day'] == 0) {
463 $errors['frequency_day'] = ts('Please enter a valid frequency day ie. 1 through 31.');
466 elseif ($fields['frequency_unit'] == 'week') {
467 if ($fields['frequency_day'] > 7 ||
$fields['frequency_day'] == 0) {
468 $errors['frequency_day'] = ts('Please enter a valid frequency day ie. 1 through 7.');
475 * Process the form submission
480 public function postProcess() {
481 if ($this->_action
& CRM_Core_Action
::DELETE
) {
482 CRM_Pledge_BAO_Pledge
::deletePledge($this->_id
);
486 //get the submitted form values.
487 $formValues = $this->controller
->exportValues($this->_name
);
489 // set the contact, when contact is selected
490 if (!empty($formValues['contact_id'])) {
491 $this->_contactID
= $formValues['contact_id'];
494 $session = CRM_Core_Session
::singleton();
496 //get All Payments status types.
497 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
501 'frequency_interval',
505 'initial_reminder_day',
507 'additional_reminder_day',
508 'contribution_page_id',
511 foreach ($fields as $f) {
512 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
515 //defaults status is "Pending".
516 //if update get status.
518 $params['pledge_status_id'] = $params['status_id'] = $this->_values
['status_id'];
521 $params['pledge_status_id'] = $params['status_id'] = array_search('Pending', $paymentStatusTypes);
524 $params['amount'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('amount', $formValues));
525 $params['currency'] = CRM_Utils_Array
::value('currency', $formValues);
526 $params['original_installment_amount'] = ($params['amount'] / $params['installments']);
528 $dates = array('create_date', 'start_date', 'acknowledge_date', 'cancel_date');
529 foreach ($dates as $d) {
530 if ($this->_id
&& (!$this->_isPending
) && !empty($this->_values
[$d])) {
531 if ($d == 'start_date') {
532 $params['scheduled_date'] = CRM_Utils_Date
::processDate($this->_values
[$d]);
534 $params[$d] = CRM_Utils_Date
::processDate($this->_values
[$d]);
536 elseif (!empty($formValues[$d]) && !CRM_Utils_System
::isNull($formValues[$d])) {
537 if ($d == 'start_date') {
538 $params['scheduled_date'] = CRM_Utils_Date
::processDate($formValues[$d]);
540 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d]);
543 $params[$d] = 'null';
547 if (!empty($formValues['is_acknowledge'])) {
548 $params['acknowledge_date'] = date('Y-m-d');
551 // assign id only in update mode
552 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
553 $params['id'] = $this->_id
;
556 $params['contact_id'] = $this->_contactID
;
559 if (!empty($formValues['hidden_custom'])) {
560 $params['hidden_custom'] = 1;
562 $customFields = CRM_Core_BAO_CustomField
::getFields('Pledge');
563 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($formValues,
570 //handle pending pledge.
571 $params['is_pledge_pending'] = $this->_isPending
;
573 //create pledge record.
574 $pledge = CRM_Pledge_BAO_Pledge
::create($params);
579 //set the status msg.
580 if ($this->_action
& CRM_Core_Action
::ADD
) {
581 $statusMsg = ts('Pledge has been recorded and the payment schedule has been created.<br />');
583 elseif ($this->_action
& CRM_Core_Action
::UPDATE
) {
584 $statusMsg = ts('Pledge has been updated.<br />');
588 //handle Acknowledgment.
589 if (!empty($formValues['is_acknowledge']) && $pledge->id
) {
591 //calculate scheduled amount.
592 $params['scheduled_amount'] = round($params['amount'] / $params['installments']);
593 $params['total_pledge_amount'] = $params['amount'];
594 //get some required pledge values in params.
595 $params['id'] = $pledge->id
;
596 $params['acknowledge_date'] = $pledge->acknowledge_date
;
597 $params['is_test'] = $pledge->is_test
;
598 $params['currency'] = $pledge->currency
;
599 // retrieve 'from email id' for acknowledgement
600 $params['from_email_id'] = $formValues['from_email_address'];
602 $this->paymentId
= NULL;
603 //send Acknowledgment mail.
604 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($this, $params);
606 if (!isset($this->userEmail
)) {
607 list($this->userDisplayName
,
609 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
612 $statusMsg .= ' ' . ts("An acknowledgment email has been sent to %1.<br />", array(1 => $this->userEmail
));
614 //build the payment urls.
615 if ($this->paymentId
) {
616 $urlParams = "reset=1&action=add&cid={$this->_contactID}&ppid={$this->paymentId}&context=pledge";
617 $contribURL = CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams);
618 $urlParams .= "&mode=live";
619 $creditURL = CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams);
621 //check if we can process credit card payment.
622 $processors = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE,
623 "billing_mode IN ( 1, 3 )"
625 if (count($processors) > 0) {
626 $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));
629 $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));
633 CRM_Core_Session
::setStatus($statusMsg, ts('Payment Due'), 'info');
635 $buttonName = $this->controller
->getButtonName();
636 if ($this->_context
== 'standalone') {
637 if ($buttonName == $this->getButtonName('upload', 'new')) {
638 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/pledge/add',
639 'reset=1&action=add&context=standalone'
643 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
644 "reset=1&cid={$this->_contactID}&selectedChild=pledge"
648 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
649 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/pledge',
650 "reset=1&action=add&context=pledge&cid={$this->_contactID}"