3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
35 * This class generates form components for processing a pledge
37 class CRM_Pledge_Form_Pledge
extends CRM_Core_Form
{
41 * The id of the pledge that we are proceessing.
48 * The id of the contact associated with this pledge.
55 * The Pledge values if an existing pledge.
61 * The Pledge frequency Units.
67 * Is current pledge pending.
70 public $_isPending = FALSE;
73 * Set variables up before form is built.
75 public function preProcess() {
76 $this->_contactID
= CRM_Utils_Request
::retrieve('cid', 'Positive', $this);
77 $this->_action
= CRM_Utils_Request
::retrieve('action', 'String',
80 $this->_id
= CRM_Utils_Request
::retrieve('id', 'Positive', $this);
81 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
83 // check for action permissions.
84 if (!CRM_Core_Permission
::checkActionPermission('CiviPledge', $this->_action
)) {
85 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
88 $this->assign('action', $this->_action
);
89 $this->assign('context', $this->_context
);
90 if ($this->_action
& CRM_Core_Action
::DELETE
) {
94 $this->userDisplayName
= $this->userEmail
= NULL;
95 if ($this->_contactID
) {
96 list($this->userDisplayName
,
98 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
99 $this->assign('displayName', $this->userDisplayName
);
102 $this->setPageTitle(ts('Pledge'));
105 CRM_Custom_Form_CustomData
::preProcess($this, NULL, NULL, 1, 'Pledge', $this->_id
);
109 // get the contribution id
110 $this->_contributionID
= CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
111 $this->_id
, 'contribution_id', 'pledge_id'
113 $params = ['id' => $this->_id
];
114 CRM_Pledge_BAO_Pledge
::getValues($params, $this->_values
);
116 $this->_isPending
= (CRM_Pledge_BAO_Pledge
::pledgeHasFinancialTransactions($this->_id
, CRM_Utils_Array
::value('status_id', $this->_values
))) ?
FALSE : TRUE;
119 // get the pledge frequency units.
120 $this->_freqUnits
= CRM_Core_OptionGroup
::values('recur_frequency_units');
122 $this->_fromEmails
= CRM_Core_BAO_Email
::getFromEmail();
126 * Set default values for the form.
127 * The default values are retrieved from the database.
129 public function setDefaultValues() {
130 $defaults = $this->_values
;
132 if ($this->_action
& CRM_Core_Action
::DELETE
) {
136 if (!empty($defaults['is_test'])) {
137 $this->assign('is_test', TRUE);
141 // check is this pledge pending.
142 // fix the display of the monetary value, CRM-4038.
143 if ($this->_isPending
) {
144 $defaults['eachPaymentAmount'] = $this->_values
['amount'] / $this->_values
['installments'];
145 $defaults['eachPaymentAmount'] = CRM_Utils_Money
::format($defaults['eachPaymentAmount'], NULL, '%a');
148 // fix the display of the monetary value, CRM-4038
149 if (isset($this->_values
['amount'])) {
150 $defaults['amount'] = CRM_Utils_Money
::format($this->_values
['amount'], NULL, '%a');
152 $this->assign('amount', $this->_values
['amount']);
153 $this->assign('installments', $defaults['installments']);
157 $defaults['create_date'] = date('Y-m-d');
158 $defaults['start_date'] = date('Y-m-d');
159 $defaults['installments'] = 12;
160 $defaults['frequency_interval'] = 1;
161 $defaults['frequency_day'] = 1;
162 $defaults['initial_reminder_day'] = 5;
163 $defaults['max_reminders'] = 1;
164 $defaults['additional_reminder_day'] = 5;
165 $defaults['frequency_unit'] = array_search('month', $this->_freqUnits
);
166 $defaults['financial_type_id'] = array_search('Donation', CRM_Contribute_PseudoConstant
::financialType());
169 $pledgeStatus = CRM_Pledge_BAO_Pledge
::buildOptions('status_id');
170 $pledgeStatusNames = CRM_Core_OptionGroup
::values('pledge_status',
171 FALSE, FALSE, FALSE, NULL, 'name', TRUE
173 // get default status label (pending)
174 $defaultPledgeStatus = CRM_Utils_Array
::value(array_search('Pending', $pledgeStatusNames),
179 $this->assign('status', CRM_Utils_Array
::value(CRM_Utils_Array
::value('status_id', $this->_values
),
184 if (isset($this->userEmail
)) {
185 $this->assign('email', $this->userEmail
);
188 // custom data set defaults
189 $defaults +
= CRM_Custom_Form_CustomData
::setDefaultValues($this);
195 * Build the form object.
197 public function buildQuickForm() {
198 if ($this->_action
& CRM_Core_Action
::DELETE
) {
202 'name' => ts('Delete'),
203 'spacing' => ' ',
208 'name' => ts('Cancel'),
214 if ($this->_context
== 'standalone') {
215 $this->addEntityRef('contact_id', ts('Contact'), [
217 'api' => ['extra' => ['email']],
221 $showAdditionalInfo = FALSE;
222 $this->_formType
= CRM_Utils_Array
::value('formType', $_GET);
227 'Payment Reminders' => 'PaymentReminders',
229 foreach ($paneNames as $name => $type) {
230 $urlParams = "snippet=4&formType={$type}";
232 'url' => CRM_Utils_System
::url('civicrm/contact/view/pledge', $urlParams),
236 // see if we need to include this paneName in the current form
237 if ($this->_formType
== $type ||
!empty($_POST["hidden_{$type}"]) ||
238 CRM_Utils_Array
::value("hidden_{$type}", $defaults)
240 $showAdditionalInfo = TRUE;
241 $allPanes[$name]['open'] = 'true';
243 $fnName = "build{$type}";
244 CRM_Contribute_Form_AdditionalInfo
::$fnName($this);
247 $this->assign('allPanes', $allPanes);
248 $this->assign('showAdditionalInfo', $showAdditionalInfo);
250 if ($this->_formType
) {
251 $this->assign('formType', $this->_formType
);
255 $this->applyFilter('__ALL__', 'trim');
258 $attributes = CRM_Core_DAO
::getAttribute('CRM_Pledge_DAO_Pledge');
260 $this->assign('isPending', $this->_isPending
);
263 'onblur' => "calculatedPaymentAmount( );",
264 'onkeyup' => "calculatedPaymentAmount( );",
267 $amount = $this->addMoney('amount', ts('Total Pledge Amount'), TRUE,
268 array_merge($attributes['pledge_amount'], $js), TRUE,
269 'currency', NULL, $this->_id
&& !$this->_isPending
272 $installments = &$this->add('text', 'installments', ts('To be paid in'),
273 array_merge($attributes['installments'], $js), TRUE
275 $this->addRule('installments', ts('Please enter a valid number of installments.'), 'positiveInteger');
277 $frequencyInterval = $this->add('number', 'frequency_interval', ts('every'),
278 $attributes['pledge_frequency_interval'], TRUE
280 $this->addRule('frequency_interval', ts('Please enter a number for frequency (e.g. every "3" months).'), 'positiveInteger');
282 // Fix frequency unit display for use with frequency_interval
283 $freqUnitsDisplay = [];
284 foreach ($this->_freqUnits
as $val => $label) {
285 $freqUnitsDisplay[$val] = ts('%1(s)', [1 => $label]);
287 $frequencyUnit = $this->add('select', 'frequency_unit',
289 ['' => ts('- select -')] +
$freqUnitsDisplay,
293 $frequencyDay = $this->add('number', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], TRUE);
294 $this->addRule('frequency_day', ts('Please enter a valid payment due day.'), 'positiveInteger');
296 $this->add('text', 'eachPaymentAmount', ts('each'), [
298 'style' => "background-color:#EBECE4",
299 // WTF, preserved because its inexplicable
304 $createDate = $this->add('datepicker', 'create_date', ts('Pledge Made'), [], TRUE, ['time' => FALSE]);
305 $startDate = $this->add('datepicker', 'start_date', ts('Payments Start'), [], TRUE, ['time' => FALSE]);
307 if (!empty($this->_values
['currency'])) {
308 $this->assign('currency', $this->_values
['currency']);
310 elseif (!empty($this->_submitValues
['currency'])) {
311 $this->assign('currency', $this->_submitValues
['currency']);
314 if ($this->_id
&& !$this->_isPending
) {
316 $installments->freeze();
317 $createDate->freeze();
318 $startDate->freeze();
319 $frequencyInterval->freeze();
320 $frequencyUnit->freeze();
321 $frequencyDay->freeze();
322 $eachPaymentAmount = $this->_values
['original_installment_amount'];
323 $this->assign('eachPaymentAmount', $eachPaymentAmount);
326 if (CRM_Utils_Array
::value('status_id', $this->_values
) !=
327 CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled')
330 $this->addElement('checkbox', 'is_acknowledge', ts('Send Acknowledgment?'), NULL,
331 ['onclick' => "showHideByValue( 'is_acknowledge', '', 'acknowledgeDate', 'table-row', 'radio', true); showHideByValue( 'is_acknowledge', '', 'fromEmail', 'table-row', 'radio', false );"]
334 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
337 $this->add('datepicker', 'acknowledge_date', ts('Acknowledgment Date'), [], FALSE, ['time' => FALSE]);
339 $this->add('select', 'financial_type_id',
340 ts('Financial Type'),
341 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::financialType(),
345 // CRM-7362 --add campaigns.
346 CRM_Campaign_BAO_Campaign
::addCampaign($this, CRM_Utils_Array
::value('campaign_id', $this->_values
));
349 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgeBlock', 'entity_table',
350 'civicrm_contribution_page', $pageIds, ['entity_id']
352 $pages = CRM_Contribute_PseudoConstant
::contributionPage();
354 foreach ($pageIds as $key => $value) {
355 $pledgePages[$value['entity_id']] = $pages[$value['entity_id']];
357 $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'),
358 ['' => ts('- select -')] +
$pledgePages
361 $mailingInfo = Civi
::settings()->get('mailing_backend');
362 $this->assign('outBound_option', $mailingInfo['outBound_option']);
365 CRM_Custom_Form_CustomData
::buildQuickForm($this);
367 // make this form an upload since we dont know if the custom data injected dynamically
368 // is of type file etc $uploadNames = $this->get( 'uploadNames' );
372 'name' => ts('Save'),
373 'js' => ['onclick' => "return verify( );"],
378 'name' => ts('Save and New'),
379 'js' => ['onclick' => "return verify( );"],
384 'name' => ts('Cancel'),
388 $this->addFormRule(['CRM_Pledge_Form_Pledge', 'formRule'], $this);
390 if ($this->_action
& CRM_Core_Action
::VIEW
) {
398 * @param array $fields
399 * The input form values.
400 * @param array $files
401 * The uploaded files if any.
406 * true if no errors, else array of errors
408 public static function formRule($fields, $files, $self) {
411 if ($fields['amount'] <= 0) {
412 $errors['amount'] = ts('Total Pledge Amount should be greater than zero.');
414 if ($fields['installments'] <= 0) {
415 $errors['installments'] = ts('Installments should be greater than zero.');
418 if ($fields['frequency_unit'] != 'week') {
419 if ($fields['frequency_day'] > 31 ||
$fields['frequency_day'] == 0) {
420 $errors['frequency_day'] = ts('Please enter a valid frequency day ie. 1 through 31.');
423 elseif ($fields['frequency_unit'] == 'week') {
424 if ($fields['frequency_day'] > 7 ||
$fields['frequency_day'] == 0) {
425 $errors['frequency_day'] = ts('Please enter a valid frequency day ie. 1 through 7.');
432 * Process the form submission.
434 public function postProcess() {
435 if ($this->_action
& CRM_Core_Action
::DELETE
) {
436 CRM_Pledge_BAO_Pledge
::deletePledge($this->_id
);
440 // get the submitted form values.
441 $formValues = $this->controller
->exportValues($this->_name
);
443 // set the contact, when contact is selected
444 if (!empty($formValues['contact_id'])) {
445 $this->_contactID
= $formValues['contact_id'];
448 $session = CRM_Core_Session
::singleton();
452 'frequency_interval',
456 'initial_reminder_day',
458 'additional_reminder_day',
459 'contribution_page_id',
462 foreach ($fields as $f) {
463 $params[$f] = CRM_Utils_Array
::value($f, $formValues);
467 $params['amount'] = CRM_Utils_Rule
::cleanMoney(CRM_Utils_Array
::value('amount', $formValues));
468 $params['currency'] = CRM_Utils_Array
::value('currency', $formValues);
469 $params['original_installment_amount'] = ($params['amount'] / $params['installments']);
471 $dates = ['create_date', 'start_date', 'acknowledge_date', 'cancel_date'];
472 foreach ($dates as $d) {
473 if ($this->_id
&& (!$this->_isPending
) && !empty($this->_values
[$d])) {
474 if ($d == 'start_date') {
475 $params['scheduled_date'] = CRM_Utils_Date
::processDate($this->_values
[$d]);
477 $params[$d] = CRM_Utils_Date
::processDate($this->_values
[$d]);
479 elseif (!empty($formValues[$d]) && !CRM_Utils_System
::isNull($formValues[$d])) {
480 if ($d == 'start_date') {
481 $params['scheduled_date'] = CRM_Utils_Date
::processDate($formValues[$d]);
483 $params[$d] = CRM_Utils_Date
::processDate($formValues[$d]);
486 $params[$d] = 'null';
490 if (!empty($formValues['is_acknowledge'])) {
491 $params['acknowledge_date'] = date('Y-m-d');
494 // assign id only in update mode
495 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
496 $params['id'] = $this->_id
;
499 $params['contact_id'] = $this->_contactID
;
501 // format custom data
502 if (!empty($formValues['hidden_custom'])) {
503 $params['hidden_custom'] = 1;
505 $customFields = CRM_Core_BAO_CustomField
::getFields('Pledge');
506 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($formValues,
512 // handle pending pledge.
513 $params['is_pledge_pending'] = $this->_isPending
;
515 // create pledge record.
516 $pledge = CRM_Pledge_BAO_Pledge
::create($params);
521 // set the status msg.
522 if ($this->_action
& CRM_Core_Action
::ADD
) {
523 $statusMsg = ts('Pledge has been recorded and the payment schedule has been created.<br />');
525 elseif ($this->_action
& CRM_Core_Action
::UPDATE
) {
526 $statusMsg = ts('Pledge has been updated.<br />');
530 // handle Acknowledgment.
531 if (!empty($formValues['is_acknowledge']) && $pledge->id
) {
533 // calculate scheduled amount.
534 $params['scheduled_amount'] = round($params['amount'] / $params['installments']);
535 $params['total_pledge_amount'] = $params['amount'];
536 // get some required pledge values in params.
537 $params['id'] = $pledge->id
;
538 $params['acknowledge_date'] = $pledge->acknowledge_date
;
539 $params['is_test'] = $pledge->is_test
;
540 $params['currency'] = $pledge->currency
;
541 // retrieve 'from email id' for acknowledgement
542 $params['from_email_id'] = $formValues['from_email_address'];
544 $this->paymentId
= NULL;
545 // send Acknowledgment mail.
546 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($this, $params);
548 if (!isset($this->userEmail
)) {
549 list($this->userDisplayName
,
551 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
554 $statusMsg .= ' ' . ts("An acknowledgment email has been sent to %1.<br />", [1 => $this->userEmail
]);
556 // build the payment urls.
557 if ($this->paymentId
) {
558 $urlParams = "reset=1&action=add&cid={$this->_contactID}&ppid={$this->paymentId}&context=pledge";
559 $contribURL = CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams);
560 $urlParams .= "&mode=live";
561 $creditURL = CRM_Utils_System
::url('civicrm/contact/view/contribution', $urlParams);
563 // check if we can process credit card payment.
564 $processors = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE,
565 "billing_mode IN ( 1, 3 )"
567 if (count($processors) > 0) {
568 $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>.", [
574 $statusMsg .= ' ' . ts("If a payment is due now, you can record <a href='%1'>a check, EFT, or cash payment for this pledge</a>.", [1 => $contribURL]);
578 CRM_Core_Session
::setStatus($statusMsg, ts('Payment Due'), 'info');
580 $buttonName = $this->controller
->getButtonName();
581 if ($this->_context
== 'standalone') {
582 if ($buttonName == $this->getButtonName('upload', 'new')) {
583 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/pledge/add',
584 'reset=1&action=add&context=standalone'
588 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
589 "reset=1&cid={$this->_contactID}&selectedChild=pledge"
593 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
594 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/pledge',
595 "reset=1&action=add&context=pledge&cid={$this->_contactID}"