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 (CRM_Utils_Array
::value('is_test', $defaults)) {
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 ||
298 CRM_Utils_Array
::value("hidden_{$type}", $_POST) ||
299 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
301 $showAdditionalInfo = TRUE;
302 $allPanes[$name]['open'] = 'true';
304 $fnName = "build{$type}";
305 CRM_Contribute_Form_AdditionalInfo
::$fnName($this);
308 $this->assign('allPanes', $allPanes);
309 $this->assign('showAdditionalInfo', $showAdditionalInfo);
311 if ($this->_formType
) {
312 $this->assign('formType', $this->_formType
);
316 $this->applyFilter('__ALL__', 'trim');
319 $attributes = CRM_Core_DAO
::getAttribute('CRM_Pledge_DAO_Pledge');
321 $this->assign('isPending', $this->_isPending
);
324 'onblur' => "calculatedPaymentAmount( );",
325 'onkeyup' => "calculatedPaymentAmount( );",
328 $currencyFreeze = FALSE;
332 $currencyFreeze = TRUE;
335 $element = $this->addMoney('amount', ts('Total Pledge Amount'), TRUE,
336 array_merge($attributes['pledge_amount'], $js), TRUE,
337 'currency', NULL, $currencyFreeze
346 $element = &$this->add('text', 'installments', ts('To be paid in'),
347 array_merge($attributes['installments'], $js), TRUE
349 $this->addRule('installments', ts('Please enter a valid number of installments.'), 'positiveInteger');
356 $element = &$this->add('text', 'frequency_interval', ts('every'),
357 $attributes['pledge_frequency_interval'], TRUE
359 $this->addRule('frequency_interval', ts('Please enter a number for frequency (e.g. every "3" months).'), 'positiveInteger');
366 // Fix frequency unit display for use with frequency_interval
367 $freqUnitsDisplay = array();
368 foreach ($this->_freqUnits
as $val => $label) {
369 $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
371 $element = &$this->add('select', 'frequency_unit',
374 '' => ts('- select -')) +
$freqUnitsDisplay,
384 $element = &$this->add('text', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], TRUE);
385 $this->addRule('frequency_day', ts('Please enter a valid payment due day.'), 'positiveInteger');
392 $this->add('text', 'eachPaymentAmount', ts('each'), array('size' => 10, 'style' => "background-color:#EBECE4", 'READONLY'));
395 if (!$this->_id ||
$this->_isPending
) {
396 $this->addDate('create_date', ts('Pledge Made'), TRUE);
397 $this->addDate('start_date', ts('Payments Start'), TRUE);
403 $eachPaymentAmount = $this->_values
['original_installment_amount'];
404 $this->assign('currency', $this->_values
['currency']);
405 $this->assign('eachPaymentAmount', $eachPaymentAmount);
406 $this->assign('hideCalender', TRUE);
409 if (CRM_Utils_Array
::value('status_id', $this->_values
) !=
410 array_search('Cancelled', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
413 $this->addElement('checkbox', 'is_acknowledge', ts('Send Acknowledgment?'), NULL,
414 array('onclick' => "showHideByValue( 'is_acknowledge', '', 'acknowledgeDate', 'table-row', 'radio', true); showHideByValue( 'is_acknowledge', '', 'fromEmail', 'table-row', 'radio', false );")
417 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
420 $this->addDate('acknowledge_date', ts('Acknowledgment Date'));
422 $this->add('select', 'financial_type_id',
423 ts( 'Financial Type' ),
424 array(''=>ts( '- select -' )) + CRM_Contribute_PseudoConstant
::financialType( ),
428 //CRM-7362 --add campaigns.
429 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
432 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgeBlock', 'entity_table',
433 'civicrm_contribution_page', $pageIds, array('entity_id')
435 $pages = CRM_Contribute_PseudoConstant
::contributionPage();
436 $pledgePages = array();
437 foreach ($pageIds as $key => $value) {
438 $pledgePages[$value['entity_id']] = $pages[$value['entity_id']];
440 $ele = $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'),
442 '' => ts('- select -')) +
$pledgePages
445 $mailingInfo = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
448 $this->assign('outBound_option', $mailingInfo['outBound_option']);
451 CRM_Custom_Form_CustomData
::buildQuickForm($this);
453 // make this form an upload since we dont know if the custom data injected dynamically
454 // is of type file etc $uploadNames = $this->get( 'uploadNames' );
455 $this->addButtons(array(
458 'name' => ts('Save'),
459 'js' => array('onclick' => "return verify( );"),
464 'name' => ts('Save and New'),
465 'js' => array('onclick' => "return verify( );"),
470 'name' => ts('Cancel'),
475 $this->addFormRule(array('CRM_Pledge_Form_Pledge', 'formRule'), $this);
477 if ($this->_action
& CRM_Core_Action
::VIEW
) {
485 * @param array $fields the input form values
486 * @param array $files the uploaded files if any
487 * @param array $options additional user data
489 * @return true if no errors, else array of errors
493 static function formRule($fields, $files, $self) {
496 //check if contact is selected in standalone mode
497 if (isset($fields['contact_select_id'][1]) && !$fields['contact_select_id'][1]) {
498 $errors['contact[1]'] = ts('Please select a contact or create new contact');
501 if ($fields['amount'] <= 0) {
502 $errors['amount'] = ts('Total Pledge Amount should be greater than zero.');
504 if ($fields['installments'] <= 0) {
505 $errors['installments'] = ts('Installments should be greater than zero.');
508 if ($fields['frequency_unit'] != 'week') {
509 if ($fields['frequency_day'] > 31 ||
$fields['frequency_day'] == 0) {
510 $errors['frequency_day'] = ts('Please enter a valid frequency day ie. 1 through 31.');
513 elseif ($fields['frequency_unit'] == 'week') {
514 if ($fields['frequency_day'] > 7 ||
$fields['frequency_day'] == 0) {
515 $errors['frequency_day'] = ts('Please enter a valid frequency day ie. 1 through 7.');
522 * Function to process the form
528 public function postProcess() {
529 if ($this->_action
& CRM_Core_Action
::DELETE
) {
530 CRM_Pledge_BAO_Pledge
::deletePledge($this->_id
);
534 //get the submitted form values.
535 $formValues = $this->controller
->exportValues($this->_name
);
537 // set the contact, when contact is selected
538 if (CRM_Utils_Array
::value('contact_select_id', $formValues)) {
539 $this->_contactID
= $formValues['contact_select_id'][1];
542 $config = CRM_Core_Config
::singleton();
543 $session = CRM_Core_Session
::singleton();
545 //get All Payments status types.
546 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
550 'frequency_interval',
554 'initial_reminder_day',
556 'additional_reminder_day',
557 'contribution_page_id',
560 foreach ($fields as $f) {
561 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
564 //defaults status is "Pending".
565 //if update get status.
567 $params['pledge_status_id'] = $params['status_id'] = $this->_values
['status_id'];
570 $params['pledge_status_id'] = $params['status_id'] = array_search('Pending', $paymentStatusTypes);
573 $params['amount'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('amount', $formValues));
574 $params['currency'] = CRM_Utils_Array
::value('currency', $formValues);
575 $params['original_installment_amount'] = ($params['amount'] / $params['installments']);
577 $dates = array('create_date', 'start_date', 'acknowledge_date', 'cancel_date');
578 foreach ($dates as $d) {
579 if ($this->_id
&& (!$this->_isPending
) && CRM_Utils_Array
::value($d, $this->_values
)) {
580 if ($d == 'start_date') {
581 $params['scheduled_date'] = CRM_Utils_Date
::processDate($this->_values
[$d]);
583 $params[$d] = CRM_Utils_Date
::processDate($this->_values
[$d]);
585 elseif (CRM_Utils_Array
::value($d, $formValues) && !CRM_Utils_System
::isNull($formValues[$d])) {
586 if ($d == 'start_date') {
587 $params['scheduled_date'] = CRM_Utils_Date
::processDate($formValues[$d]);
589 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d]);
592 $params[$d] = 'null';
596 if (CRM_Utils_Array
::value('is_acknowledge', $formValues)) {
597 $params['acknowledge_date'] = date('Y-m-d');
600 // assign id only in update mode
601 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
602 $params['id'] = $this->_id
;
605 $params['contact_id'] = $this->_contactID
;
608 if (CRM_Utils_Array
::value('hidden_custom', $formValues)) {
609 $params['hidden_custom'] = 1;
611 $customFields = CRM_Core_BAO_CustomField
::getFields('Pledge');
612 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($formValues,
619 //handle pending pledge.
620 $params['is_pledge_pending'] = $this->_isPending
;
622 //create pledge record.
623 $pledge = CRM_Pledge_BAO_Pledge
::create($params);
628 //set the status msg.
629 if ($this->_action
& CRM_Core_Action
::ADD
) {
630 $statusMsg = ts('Pledge has been recorded and the payment schedule has been created.<br />');
632 elseif ($this->_action
& CRM_Core_Action
::UPDATE
) {
633 $statusMsg = ts('Pledge has been updated.<br />');
637 //handle Acknowledgment.
638 if (CRM_Utils_Array
::value('is_acknowledge', $formValues) && $pledge->id
) {
640 //calculate scheduled amount.
641 $params['scheduled_amount'] = round($params['amount'] / $params['installments']);
642 $params['total_pledge_amount'] = $params['amount'];
643 //get some required pledge values in params.
644 $params['id'] = $pledge->id
;
645 $params['acknowledge_date'] = $pledge->acknowledge_date
;
646 $params['is_test'] = $pledge->is_test
;
647 $params['currency'] = $pledge->currency
;
648 // retrieve 'from email id' for acknowledgement
649 $params['from_email_id'] = $formValues['from_email_address'];
651 $this->paymentId
= NULL;
652 //send Acknowledgment mail.
653 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($this, $params);
655 if (!isset($this->userEmail
)) {
656 list($this->userDisplayName
,
658 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
661 $statusMsg .= ' ' . ts("An acknowledgment email has been sent to %1.<br />", array(1 => $this->userEmail
));
663 //build the payment urls.
664 if ($this->paymentId
) {
665 $urlParams = "reset=1&action=add&cid={$this->_contactID}&ppid={$this->paymentId}&context=pledge";
666 $contribURL = CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams);
667 $urlParams .= "&mode=live";
668 $creditURL = CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams);
670 //check if we can process credit card payment.
671 $processors = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE,
672 "billing_mode IN ( 1, 3 )"
674 if (count($processors) > 0) {
675 $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));
678 $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));
682 CRM_Core_Session
::setStatus($statusMsg, ts('Payment Due'), 'info');
684 $buttonName = $this->controller
->getButtonName();
685 if ($this->_context
== 'standalone') {
686 if ($buttonName == $this->getButtonName('upload', 'new')) {
687 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/pledge/add',
688 'reset=1&action=add&context=standalone'
692 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
693 "reset=1&cid={$this->_contactID}&selectedChild=pledge"
697 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
698 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/pledge',
699 "reset=1&action=add&context=pledge&cid={$this->_contactID}"