e489f103cbaa6f3491836a7e4c034af9e7b41cbb
[civicrm-core.git] / CRM / Contribute / Form / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 use Civi\Payment\Exception\PaymentProcessorException;
29
30 /**
31 * This class generates form components for processing a contribution.
32 */
33 class CRM_Contribute_Form_Contribution extends CRM_Contribute_Form_AbstractEditPayment {
34 /**
35 * The id of the contribution that we are processing.
36 *
37 * @var int
38 */
39 public $_id;
40
41 /**
42 * The id of the premium that we are processing.
43 *
44 * @var int
45 */
46 public $_premiumID = NULL;
47
48 /**
49 * @var CRM_Contribute_DAO_ContributionProduct
50 */
51 public $_productDAO = NULL;
52
53 /**
54 * The id of the note.
55 *
56 * @var int
57 */
58 public $_noteID;
59
60 /**
61 * The id of the contact associated with this contribution.
62 *
63 * @var int
64 */
65 public $_contactID;
66
67 /**
68 * The id of the pledge payment that we are processing.
69 *
70 * @var int
71 */
72 public $_ppID;
73
74 /**
75 * Is this contribution associated with an online.
76 * financial transaction
77 *
78 * @var boolean
79 */
80 public $_online = FALSE;
81
82 /**
83 * Stores all product options.
84 *
85 * @var array
86 */
87 public $_options;
88
89 /**
90 * Storage of parameters from form
91 *
92 * @var array
93 */
94 public $_params;
95
96 /**
97 * Store the contribution Type ID
98 *
99 * @var array
100 */
101 public $_contributionType;
102
103 /**
104 * The contribution values if an existing contribution
105 */
106 public $_values;
107
108 /**
109 * The pledge values if this contribution is associated with pledge
110 */
111 public $_pledgeValues;
112
113 public $_contributeMode = 'direct';
114
115 public $_context;
116
117 /**
118 * Parameter with confusing name.
119 * @todo what is it?
120 * @var string
121 */
122 public $_compContext;
123
124 public $_compId;
125
126 /**
127 * Possible From email addresses
128 * @var array
129 */
130 public $_fromEmails;
131
132 /**
133 * ID of from email
134 * @var integer
135 */
136 public $fromEmailId;
137
138 /**
139 * Store the line items if price set used.
140 */
141 public $_lineItems;
142
143 /**
144 * Line item
145 * @todo explain why we use lineItem & lineItems
146 * @var array
147 */
148 public $_lineItem;
149
150 /**
151 * @var array soft credit info
152 */
153 public $_softCreditInfo;
154
155 protected $_formType;
156
157 public $_honoreeProfileType;
158
159 /**
160 * Array of the payment fields to be displayed in the payment fieldset (pane) in billingBlock.tpl
161 * this contains all the information to describe these fields from quickform. See CRM_Core_Form_Payment getPaymentFormFieldsMetadata
162 *
163 * @var array
164 */
165 public $_paymentFields = array();
166 /**
167 * Logged in user's email.
168 * @var string
169 */
170 public $userEmail;
171
172 /**
173 * Price set ID
174 * @var integer
175 */
176 public $_priceSetId;
177
178 /**
179 * Price set as an array
180 * @var array
181 */
182 public $_priceSet;
183
184 /**
185 * User display name
186 *
187 * @var string
188 */
189 public $userDisplayName;
190
191 /**
192 * Status message to be shown to the user.
193 *
194 * @var array
195 */
196 protected $statusMessage = array();
197
198 /**
199 * Status message title to be shown to the user.
200 *
201 * Generally the payment processor message title is 'Complete' and offline is 'Saved'
202 * although this might not be a good fit with the broad range of processors.
203 *
204 * @var string
205 */
206 protected $statusMessageTitle;
207
208 /**
209 * Set variables up before form is built.
210 */
211 public function preProcess() {
212 // Check permission for action.
213 if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
214 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
215 }
216
217 parent::preProcess();
218
219 $this->_formType = CRM_Utils_Array::value('formType', $_GET);
220
221 // Get price set id.
222 $this->_priceSetId = CRM_Utils_Array::value('priceSetId', $_GET);
223 $this->set('priceSetId', $this->_priceSetId);
224 $this->assign('priceSetId', $this->_priceSetId);
225
226 // Get the pledge payment id
227 $this->_ppID = CRM_Utils_Request::retrieve('ppid', 'Positive', $this);
228
229 $this->assign('action', $this->_action);
230
231 // Get the contribution id if update
232 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
233 if (!empty($this->_id)) {
234 $this->assign('contribID', $this->_id);
235 }
236
237 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
238 $this->assign('context', $this->_context);
239
240 $this->_compId = CRM_Utils_Request::retrieve('compId', 'Positive', $this);
241
242 $this->_compContext = CRM_Utils_Request::retrieve('compContext', 'String', $this);
243
244 //set the contribution mode.
245 $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
246
247 $this->assign('contributionMode', $this->_mode);
248 if ($this->_action & CRM_Core_Action::DELETE) {
249 return;
250 }
251
252 $this->assign('showCheckNumber', TRUE);
253
254 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
255 $this->assignPaymentRelatedVariables();
256
257 if (in_array('CiviPledge', CRM_Core_Config::singleton()->enableComponents) && !$this->_formType) {
258 $this->preProcessPledge();
259 }
260
261 if ($this->_id) {
262 $this->showRecordLinkMesssage($this->_id);
263 }
264 $this->_values = array();
265
266 // Current contribution id.
267 if ($this->_id) {
268 $this->assignPremiumProduct($this->_id);
269 $this->buildValuesAndAssignOnline_Note_Type($this->_id, $this->_values);
270 }
271
272 // when custom data is included in this page
273 if (!empty($_POST['hidden_custom'])) {
274 $this->applyCustomData('Contribution', CRM_Utils_Array::value('financial_type_id', $_POST), $this->_id);
275 }
276
277 $this->_lineItems = array();
278 if ($this->_id) {
279 if (!empty($this->_compId) && $this->_compContext == 'participant') {
280 $this->assign('compId', $this->_compId);
281 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_compId);
282 }
283 else {
284 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution', 1, TRUE, TRUE);
285 }
286 empty($lineItem) ? NULL : $this->_lineItems[] = $lineItem;
287 }
288
289 $this->assign('lineItem', empty($this->_lineItems) ? FALSE : $this->_lineItems);
290
291 // Set title
292 if ($this->_mode) {
293 $this->setPageTitle($this->_ppID ? ts('Credit Card Pledge Payment') : ts('Credit Card Contribution'));
294 }
295 else {
296 $this->setPageTitle($this->_ppID ? ts('Pledge Payment') : ts('Contribution'));
297 }
298
299 if ($this->_id) {
300 CRM_Contribute_Form_SoftCredit::preprocess($this);
301 }
302 }
303
304 /**
305 * Set default values.
306 *
307 * @return array
308 */
309 public function setDefaultValues() {
310
311 $defaults = $this->_values;
312
313 // Set defaults for pledge payment.
314 if ($this->_ppID) {
315 $defaults['total_amount'] = CRM_Utils_Array::value('scheduled_amount', $this->_pledgeValues['pledgePayment']);
316 $defaults['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_pledgeValues);
317 $defaults['currency'] = CRM_Utils_Array::value('currency', $this->_pledgeValues);
318 $defaults['option_type'] = 1;
319 }
320
321 if ($this->_action & CRM_Core_Action::DELETE) {
322 return $defaults;
323 }
324
325 $defaults['frequency_interval'] = 1;
326 $defaults['frequency_unit'] = 'month';
327
328 // Set soft credit defaults.
329 CRM_Contribute_Form_SoftCredit::setDefaultValues($defaults, $this);
330
331 if ($this->_mode) {
332 $config = CRM_Core_Config::singleton();
333 // Set default country from config if no country set.
334 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
335 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
336 }
337
338 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
339 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
340 }
341
342 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
343 $defaults = array_merge($defaults, $billingDefaults);
344 }
345
346 if ($this->_id) {
347 $this->_contactID = $defaults['contact_id'];
348 }
349
350 // Set $newCredit variable in template to control whether link to credit card mode is included.
351 $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
352
353 // Fix the display of the monetary value, CRM-4038.
354 if (isset($defaults['total_amount'])) {
355 if (!empty($defaults['tax_amount'])) {
356 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
357 if (!(CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails))) {
358 $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'] - $defaults['tax_amount'], NULL, '%a');
359 }
360 }
361 else {
362 $defaults['total_amount'] = CRM_Utils_Money::format($defaults['total_amount'], NULL, '%a');
363 }
364 }
365
366 if (isset($defaults['non_deductible_amount'])) {
367 $defaults['non_deductible_amount'] = CRM_Utils_Money::format($defaults['non_deductible_amount'], NULL, '%a');
368 }
369
370 if (isset($defaults['fee_amount'])) {
371 $defaults['fee_amount'] = CRM_Utils_Money::format($defaults['fee_amount'], NULL, '%a');
372 }
373
374 if (isset($defaults['net_amount'])) {
375 $defaults['net_amount'] = CRM_Utils_Money::format($defaults['net_amount'], NULL, '%a');
376 }
377
378 if ($this->_contributionType) {
379 $defaults['financial_type_id'] = $this->_contributionType;
380 }
381
382 if (empty($defaults['payment_instrument_id'])) {
383 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
384 }
385
386 if (!empty($defaults['is_test'])) {
387 $this->assign('is_test', TRUE);
388 }
389
390 $this->assign('showOption', TRUE);
391 // For Premium section.
392 if ($this->_premiumID) {
393 $this->assign('showOption', FALSE);
394 $options = isset($this->_options[$this->_productDAO->product_id]) ? $this->_options[$this->_productDAO->product_id] : "";
395 if (!$options) {
396 $this->assign('showOption', TRUE);
397 }
398 $options_key = CRM_Utils_Array::key($this->_productDAO->product_option, $options);
399 if ($options_key) {
400 $defaults['product_name'] = array($this->_productDAO->product_id, trim($options_key));
401 }
402 else {
403 $defaults['product_name'] = array($this->_productDAO->product_id);
404 }
405 if ($this->_productDAO->fulfilled_date) {
406 list($defaults['fulfilled_date']) = CRM_Utils_Date::setDateDefaults($this->_productDAO->fulfilled_date);
407 }
408 }
409
410 if (isset($this->userEmail)) {
411 $this->assign('email', $this->userEmail);
412 }
413
414 if (!empty($defaults['is_pay_later'])) {
415 $this->assign('is_pay_later', TRUE);
416 }
417 $this->assign('contribution_status_id', CRM_Utils_Array::value('contribution_status_id', $defaults));
418
419 $dates = array(
420 'receive_date',
421 'receipt_date',
422 'cancel_date',
423 'thankyou_date',
424 );
425 foreach ($dates as $key) {
426 if (!empty($defaults[$key])) {
427 list($defaults[$key], $defaults[$key . '_time'])
428 = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value($key, $defaults), 'activityDateTime');
429 }
430 }
431
432 if (!$this->_id && empty($defaults['receive_date'])) {
433 list($defaults['receive_date'],
434 $defaults['receive_date_time']
435 ) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
436 }
437
438 $this->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $defaults),
439 CRM_Utils_Array::value('receive_date_time', $defaults)
440 ));
441 $currency = CRM_Utils_Array::value('currency', $defaults);
442 $this->assign('currency', $currency);
443 // Hack to get currency info to the js layer. CRM-11440.
444 CRM_Utils_Money::format(1);
445 $this->assign('currencySymbol', CRM_Utils_Array::value($currency, CRM_Utils_Money::$_currencySymbols));
446 $this->assign('totalAmount', CRM_Utils_Array::value('total_amount', $defaults));
447
448 // Inherit campaign from pledge.
449 if ($this->_ppID && !empty($this->_pledgeValues['campaign_id'])) {
450 $defaults['campaign_id'] = $this->_pledgeValues['campaign_id'];
451 }
452
453 $this->_defaults = $defaults;
454 return $defaults;
455 }
456
457 /**
458 * Build the form object.
459 */
460 public function buildQuickForm() {
461 // FIXME: This probably needs to be done in preprocess
462 if ($this->_action & CRM_Core_Action::UPDATE && CRM_Utils_Array::value('financial_type_id', $this->_values)) {
463 $financialTypeID = CRM_Contribute_PseudoConstant::financialType($this->_values['financial_type_id']);
464 CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($this->_id, 'edit');
465 if (!CRM_Core_Permission::check('edit contributions of type ' . $financialTypeID)) {
466 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
467 }
468 }
469 $allPanes = array();
470 $recurJs = NULL;
471 //tax rate from financialType
472 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
473 $this->assign('currencies', json_encode(CRM_Core_OptionGroup::values('currencies_enabled')));
474
475 // build price set form.
476 $buildPriceSet = FALSE;
477 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
478 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
479 $this->assign('invoicing', $invoicing);
480
481 // display tax amount on edit contribution page
482 if ($invoicing && $this->_action & CRM_Core_Action::UPDATE && isset($this->_values['tax_amount'])) {
483 $this->assign('totalTaxAmount', $this->_values['tax_amount']);
484 }
485
486 if (empty($this->_lineItems) &&
487 ($this->_priceSetId || !empty($_POST['price_set_id']))
488 ) {
489 $buildPriceSet = TRUE;
490 $getOnlyPriceSetElements = TRUE;
491 if (!$this->_priceSetId) {
492 $this->_priceSetId = $_POST['price_set_id'];
493 $getOnlyPriceSetElements = FALSE;
494 }
495
496 $this->set('priceSetId', $this->_priceSetId);
497 CRM_Price_BAO_PriceSet::buildPriceSet($this);
498
499 // get only price set form elements.
500 if ($getOnlyPriceSetElements) {
501 return;
502 }
503 }
504 // use to build form during form rule.
505 $this->assign('buildPriceSet', $buildPriceSet);
506
507 $defaults = $this->_values;
508 $additionalDetailFields = array(
509 'note',
510 'thankyou_date',
511 'invoice_id',
512 'non_deductible_amount',
513 'fee_amount',
514 'net_amount',
515 );
516 foreach ($additionalDetailFields as $key) {
517 if (!empty($defaults[$key])) {
518 $defaults['hidden_AdditionalDetail'] = 1;
519 break;
520 }
521 }
522
523 if ($this->_productDAO) {
524 if ($this->_productDAO->product_id) {
525 $defaults['hidden_Premium'] = 1;
526 }
527 }
528
529 if ($this->_noteID &&
530 isset($this->_values['note'])
531 ) {
532 $defaults['hidden_AdditionalDetail'] = 1;
533 }
534
535 $paneNames = array(
536 ts('Additional Details') => 'AdditionalDetail',
537 );
538
539 //Add Premium pane only if Premium is exists.
540 $dao = new CRM_Contribute_DAO_Product();
541 $dao->is_active = 1;
542
543 if ($dao->find(TRUE)) {
544 $paneNames[ts('Premium Information')] = 'Premium';
545 }
546
547 if ($this->_mode) {
548 if (CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE) == TRUE) {
549 if (!empty($this->_recurPaymentProcessors)) {
550 $buildRecurBlock = TRUE;
551 if ($this->_ppID) {
552 // ppID denotes a pledge payment.
553 foreach ($this->_paymentProcessors as $processor) {
554 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
555 $buildRecurBlock = TRUE;
556 break;
557 }
558 $buildRecurBlock = FALSE;
559 }
560 }
561 if ($buildRecurBlock) {
562 CRM_Contribute_Form_Contribution_Main::buildRecur($this);
563 $this->setDefaults(array('is_recur' => 0));
564 $this->assign('buildRecurBlock', TRUE);
565 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
566 }
567 }
568 }
569 }
570
571 foreach ($paneNames as $name => $type) {
572 $allPanes[$name] = $this->generatePane($type, $defaults);
573 }
574
575 $qfKey = $this->controller->_key;
576 $this->assign('qfKey', $qfKey);
577 $this->assign('allPanes', $allPanes);
578
579 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
580
581 if ($this->_formType) {
582 $this->assign('formType', $this->_formType);
583 return;
584 }
585
586 $this->applyFilter('__ALL__', 'trim');
587
588 if ($this->_action & CRM_Core_Action::DELETE) {
589 $this->addButtons(array(
590 array(
591 'type' => 'next',
592 'name' => ts('Delete'),
593 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
594 'isDefault' => TRUE,
595 ),
596 array(
597 'type' => 'cancel',
598 'name' => ts('Cancel'),
599 ),
600 )
601 );
602 return;
603 }
604
605 //need to assign custom data type and subtype to the template
606 $this->assign('customDataType', 'Contribution');
607 $this->assign('customDataSubType', $this->_contributionType);
608 $this->assign('entityID', $this->_id);
609
610 if ($this->_context == 'standalone') {
611 $this->addEntityRef('contact_id', ts('Contact'), array(
612 'create' => TRUE,
613 'api' => array('extra' => array('email')),
614 ), TRUE);
615 }
616
617 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
618
619 // Check permissions for financial type first
620 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, 'add');
621
622 $financialType = $this->add('select', 'financial_type_id',
623 ts('Financial Type'),
624 array('' => ts('- select -')) + $financialTypes,
625 TRUE,
626 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
627 );
628
629 $paymentInstrument = FALSE;
630 if (!$this->_mode) {
631 $paymentInstrument = $this->add('select', 'payment_instrument_id',
632 ts('Payment Method'),
633 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
634 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
635 );
636 }
637
638 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') + $attributes['trxn_id']);
639
640 //add receipt for offline contribution
641 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
642
643 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
644
645 $status = CRM_Contribute_PseudoConstant::contributionStatus();
646
647 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
648 $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
649 if ($this->_ppID) {
650 foreach (array(
651 'Cancelled',
652 'Failed',
653 'In Progress',
654 ) as $suppress) {
655 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
656 }
657 }
658 elseif ((!$this->_ppID && $this->_id) || !$this->_id) {
659 $suppressFlag = FALSE;
660 if ($this->_id) {
661 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
662 if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) {
663 $suppressFlag = TRUE;
664 }
665 }
666 if (!$suppressFlag) {
667 foreach (array(
668 'Overdue',
669 'In Progress',
670 ) as $suppress) {
671 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
672 }
673 }
674 else {
675 unset($status[CRM_Utils_Array::key('Overdue', $statusName)]);
676 }
677 }
678
679 if ($this->_id) {
680 $contributionStatus = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id, 'contribution_status_id');
681 $name = CRM_Utils_Array::value($contributionStatus, $statusName);
682 switch ($name) {
683 case 'Completed':
684 case 'Cancelled':
685 case 'Refunded':
686 unset($status[CRM_Utils_Array::key('In Progress', $statusName)]);
687 unset($status[CRM_Utils_Array::key('Pending', $statusName)]);
688 unset($status[CRM_Utils_Array::key('Failed', $statusName)]);
689 break;
690
691 case 'Pending':
692 case 'In Progress':
693 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
694 break;
695
696 case 'Failed':
697 foreach (array(
698 'Pending',
699 'Refunded',
700 'Completed',
701 'In Progress',
702 'Cancelled',
703 ) as $suppress) {
704 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
705 }
706 break;
707 }
708 }
709 else {
710 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
711 }
712
713 $this->add('select', 'contribution_status_id',
714 ts('Contribution Status'),
715 $status,
716 FALSE
717 );
718
719 // add various dates
720 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
721
722 if ($this->_online) {
723 $this->assign('hideCalender', TRUE);
724 }
725 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
726
727 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
728 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
729
730 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
731
732 $element = $this->add('select',
733 'payment_processor_id',
734 ts('Payment Processor'),
735 $this->_processors,
736 NULL,
737 $recurJs
738 );
739
740 if ($this->_online) {
741 $element->freeze();
742 }
743
744 $totalAmount = NULL;
745 if (empty($this->_lineItems)) {
746 $buildPriceSet = FALSE;
747 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
748 if (!empty($priceSets) && !$this->_ppID) {
749 $buildPriceSet = TRUE;
750 }
751
752 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
753 // and if we already have line items for that participant. CRM-5095
754 if ($buildPriceSet && $this->_id) {
755 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
756 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
757 $this->_id,
758 'id',
759 'contribution_id'
760 );
761 if ($pledgePaymentId) {
762 $buildPriceSet = FALSE;
763 }
764 if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) {
765 $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID);
766 if (!CRM_Utils_System::isNull($participantLI)) {
767 $buildPriceSet = FALSE;
768 }
769 }
770 }
771
772 $hasPriceSets = FALSE;
773 if ($buildPriceSet) {
774 $hasPriceSets = TRUE;
775 // CRM-16451: set financial type of 'Price Set' in back office contribution
776 // instead of selecting manually
777 $financialTypeIds = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
778 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
779 array(
780 '' => ts('Choose price set'),
781 ) + $priceSets,
782 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
783 );
784 if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
785 $element->freeze();
786 }
787 }
788 $this->assign('hasPriceSets', $hasPriceSets);
789 $currencyFreeze = FALSE;
790 if (!($this->_action & CRM_Core_Action::UPDATE)) {
791 if ($this->_online || $this->_ppID) {
792 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
793 'READONLY' => TRUE,
794 'style' => "background-color:#EBECE4",
795 ));
796 $optionTypes = array(
797 '1' => ts('Adjust Pledge Payment Schedule?'),
798 '2' => ts('Adjust Total Pledge Amount?'),
799 );
800 $this->addRadio('option_type',
801 NULL,
802 $optionTypes,
803 array(), '<br/>'
804 );
805
806 $currencyFreeze = TRUE;
807 }
808 }
809
810 $totalAmount = $this->addMoney('total_amount',
811 ts('Total Amount'),
812 ($hasPriceSets) ? FALSE : TRUE,
813 $attributes['total_amount'],
814 TRUE, 'currency', NULL, $currencyFreeze
815 );
816 }
817
818 $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes));
819
820 // CRM-7362 --add campaigns.
821 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
822
823 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
824
825 $js = NULL;
826 if (!$this->_mode) {
827 $js = array('onclick' => "return verify( );");
828 }
829
830 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
831 'mailing_backend'
832 );
833 $this->assign('outBound_option', $mailingInfo['outBound_option']);
834
835 $this->addButtons(array(
836 array(
837 'type' => 'upload',
838 'name' => ts('Save'),
839 'js' => $js,
840 'isDefault' => TRUE,
841 ),
842 array(
843 'type' => 'upload',
844 'name' => ts('Save and New'),
845 'js' => $js,
846 'subName' => 'new',
847 ),
848 array(
849 'type' => 'cancel',
850 'name' => ts('Cancel'),
851 ),
852 )
853 );
854
855 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
856 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
857 if ($this->_id && $this->_values['contribution_status_id'] == array_search('Cancelled', $statusName)) {
858 if ($totalAmount) {
859 $totalAmount->freeze();
860 }
861 $checkNumber->freeze();
862 $paymentInstrument->freeze();
863 $trxnId->freeze();
864 $financialType->freeze();
865 }
866
867 // if contribution is related to membership or participant freeze Financial Type, Amount
868 if ($this->_id && isset($this->_values['tax_amount'])) {
869 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
870 if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) {
871 if ($totalAmount) {
872 $totalAmount->freeze();
873 }
874 $financialType->freeze();
875 $this->assign('freezeFinancialType', TRUE);
876 }
877 }
878
879 if ($this->_action & CRM_Core_Action::VIEW) {
880 $this->freeze();
881 }
882 }
883
884 /**
885 * Global form rule.
886 *
887 * @param array $fields
888 * The input form values.
889 * @param array $files
890 * The uploaded files if any.
891 * @param $self
892 *
893 * @return bool|array
894 * true if no errors, else array of errors
895 */
896 public static function formRule($fields, $files, $self) {
897 $errors = array();
898 // Check for Credit Card Contribution.
899 if ($self->_mode) {
900 if (empty($fields['payment_processor_id'])) {
901 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
902 }
903 else {
904 // validate payment instrument (e.g. credit card number)
905 CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, $self);
906 }
907 }
908
909 // Do the amount validations.
910 if (empty($fields['total_amount']) && empty($self->_lineItems)) {
911 if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
912 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $fields, $errors);
913 }
914 }
915
916 $softErrors = CRM_Contribute_Form_SoftCredit::formRule($fields, $errors, $self);
917
918 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) || !empty($fields['fee_amount']))) {
919 $sum = CRM_Utils_Rule::cleanMoney($fields['net_amount']) + CRM_Utils_Rule::cleanMoney($fields['fee_amount']);
920 // For taxable contribution we need to deduct taxable amount from
921 // (net amount + fee amount) before comparing it with total amount
922 if (!empty($self->_values['tax_amount'])) {
923 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($self->_id);
924 if (!(CRM_Utils_Array::value('membership', $componentDetails) ||
925 CRM_Utils_Array::value('participant', $componentDetails))
926 ) {
927 $sum = CRM_Utils_Money::format($sum - $self->_values['tax_amount'], NULL, '%a');
928 }
929 }
930 if (CRM_Utils_Rule::cleanMoney($fields['total_amount']) != $sum) {
931 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
932 }
933 }
934
935 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
936 CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
937
938 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
939 if (($self->_action & CRM_Core_Action::UPDATE)
940 && $self->_id
941 && $self->_values['contribution_status_id'] != $fields['contribution_status_id']
942 ) {
943 CRM_Contribute_BAO_Contribution::checkStatusValidation($self->_values, $fields, $errors);
944 }
945 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
946 if (($self->_action & CRM_Core_Action::UPDATE)
947 && $self->_id
948 && $self->_values['financial_type_id'] != $fields['financial_type_id']
949 ) {
950 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange(NULL, $self->_id, $errors);
951 }
952 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
953 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($fields['financial_type_id'])) {
954 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
955 }
956
957 // $trxn_id must be unique CRM-13919
958 if (!empty($fields['trxn_id'])) {
959 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
960 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
961 if ($self->_id) {
962 $queryParams[2] = array((int) $self->_id, 'Integer');
963 $query .= ' and id !=%2';
964 }
965 $tCnt = CRM_Core_DAO::singleValueQuery($query, $queryParams);
966 if ($tCnt) {
967 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
968 }
969 }
970
971 $errors = array_merge($errors, $softErrors);
972 return $errors;
973 }
974
975 /**
976 * Process the form submission.
977 */
978 public function postProcess() {
979 if ($this->_action & CRM_Core_Action::DELETE) {
980 CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
981 CRM_Core_Session::singleton()->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
982 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
983 ));
984 return;
985 }
986 // Get the submitted form values.
987 $submittedValues = $this->controller->exportValues($this->_name);
988
989 try {
990 $contribution = $this->submit($submittedValues, $this->_action, $this->_ppID);
991 }
992 catch (PaymentProcessorException $e) {
993 // Set the contribution mode.
994 $urlParams = "action=add&cid={$this->_contactID}";
995 if ($this->_mode) {
996 $urlParams .= "&mode={$this->_mode}";
997 }
998 if (!empty($this->_ppID)) {
999 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1000 }
1001
1002 CRM_Core_Error::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
1003 }
1004 $session = CRM_Core_Session::singleton();
1005 $buttonName = $this->controller->getButtonName();
1006 if ($this->_context == 'standalone') {
1007 if ($buttonName == $this->getButtonName('upload', 'new')) {
1008 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add',
1009 'reset=1&action=add&context=standalone'
1010 ));
1011 }
1012 else {
1013 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1014 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1015 ));
1016 }
1017 }
1018 elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
1019 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1020 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"
1021 ));
1022 }
1023 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1024 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1025 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1026 ));
1027 }
1028
1029 //store contribution ID if not yet set (on create)
1030 if (empty($this->_id) && !empty($contribution->id)) {
1031 $this->_id = $contribution->id;
1032 }
1033 }
1034
1035 /**
1036 * Process credit card payment.
1037 *
1038 * @param array $submittedValues
1039 * @param array $lineItem
1040 *
1041 * @param int $contactID
1042 * Contact ID
1043 *
1044 * @return bool|\CRM_Contribute_DAO_Contribution
1045 * @throws \CRM_Core_Exception
1046 * @throws \Civi\Payment\Exception\PaymentProcessorException
1047 */
1048 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1049 $isTest = ($this->_mode == 'test') ? 1 : 0;
1050 // CRM-12680 set $_lineItem if its not set
1051 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1052 // It would be better to pass line item out to functions than $this->_lineItem as
1053 // we don't know what is being changed where.
1054 if (empty($this->_lineItem) && !empty($lineItem)) {
1055 $this->_lineItem = $lineItem;
1056 }
1057
1058 $this->_paymentObject = Civi\Payment\System::singleton()->getById($submittedValues['payment_processor_id']);
1059 $this->_paymentProcessor = $this->_paymentObject->getPaymentProcessor();
1060
1061 // Set source if not set
1062 if (empty($submittedValues['source'])) {
1063 $userID = CRM_Core_Session::singleton()->get('userID');
1064 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1065 'sort_name'
1066 );
1067 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1068 }
1069
1070 $params = $submittedValues;
1071 $this->_params = array_merge($this->_params, $submittedValues);
1072
1073 // Mapping requiring documentation.
1074 $this->_params['payment_processor'] = $submittedValues['payment_processor_id'];
1075
1076 $now = date('YmdHis');
1077
1078 // we need to retrieve email address
1079 if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1080 list($this->userDisplayName,
1081 $this->userEmail
1082 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
1083 $this->assign('displayName', $this->userDisplayName);
1084 }
1085
1086 $this->_contributorEmail = $this->userEmail;
1087 $this->_contributorContactID = $contactID;
1088 $this->processBillingAddress();
1089 if (!empty($params['source'])) {
1090 unset($params['source']);
1091 }
1092
1093 $this->_params['amount'] = $this->_params['total_amount'];
1094 $this->_params['amount_level'] = 0;
1095 $this->_params['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1096 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
1097 $this->_params,
1098 CRM_Core_Config::singleton()->defaultCurrency
1099 );
1100
1101 if (!empty($this->_params['receive_date'])) {
1102 $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
1103 }
1104
1105 $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
1106 $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
1107 $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
1108
1109 //Add common data to formatted params
1110 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
1111
1112 if (empty($this->_params['invoice_id'])) {
1113 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1114 }
1115 else {
1116 $this->_params['invoiceID'] = $this->_params['invoice_id'];
1117 }
1118
1119 // At this point we've created a contact and stored its address etc
1120 // all the payment processors expect the name and address to be in the
1121 // so we copy stuff over to first_name etc.
1122 $paymentParams = $this->_params;
1123 $paymentParams['contactID'] = $contactID;
1124 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
1125
1126 $financialType = new CRM_Financial_DAO_FinancialType();
1127 $financialType->id = $params['financial_type_id'];
1128
1129 // Add some financial type details to the params list
1130 // if folks need to use it.
1131 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $financialType->name;
1132 $paymentParams['contributionPageID'] = NULL;
1133
1134 if (!empty($this->_params['is_email_receipt'])) {
1135 $paymentParams['email'] = $this->userEmail;
1136 $paymentParams['is_email_receipt'] = 1;
1137 }
1138 else {
1139 $paymentParams['is_email_receipt'] = 0;
1140 $this->_params['is_email_receipt'] = 0;
1141 }
1142 if (!empty($this->_params['receive_date'])) {
1143 $paymentParams['receive_date'] = $this->_params['receive_date'];
1144 }
1145
1146 $this->_params['receive_date'] = $now;
1147
1148 if (!empty($this->_params['is_email_receipt'])) {
1149 $this->_params['receipt_date'] = $now;
1150 }
1151 else {
1152 $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'],
1153 $params['receipt_date_time'], TRUE
1154 );
1155 }
1156
1157 $this->set('params', $this->_params);
1158
1159 $this->assign('receive_date', $this->_params['receive_date']);
1160
1161 // Result has all the stuff we need
1162 // lets archive it to a financial transaction
1163 if ($financialType->is_deductible) {
1164 $this->assign('is_deductible', TRUE);
1165 $this->set('is_deductible', TRUE);
1166 }
1167 $contributionParams = array(
1168 'contact_id' => $contactID,
1169 'line_item' => $lineItem,
1170 'is_test' => $isTest,
1171 'campaign_id' => CRM_Utils_Array::value('campaign_id', $this->_params),
1172 'contribution_page_id' => CRM_Utils_Array::value('contribution_page_id', $this->_params),
1173 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
1174 'thankyou_date' => CRM_Utils_Array::value('thankyou_date', $this->_params),
1175 );
1176
1177 if (empty($paymentParams['is_pay_later'])) {
1178 // @todo look up payment_instrument_id on payment processor table.
1179 $contributionParams['payment_instrument_id'] = 1;
1180 }
1181
1182 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this,
1183 $this->_params,
1184 NULL,
1185 $contributionParams,
1186 $financialType,
1187 FALSE,
1188 $this->_bltID
1189 );
1190
1191 $paymentParams['contributionID'] = $contribution->id;
1192 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1193 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1194 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1195
1196 if ($paymentParams['amount'] > 0.0) {
1197 // force a re-get of the payment processor in case the form changed it, CRM-7179
1198 // NOTE - I expect this is obsolete.
1199 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
1200 try {
1201 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
1202 $result = $payment->doPayment($paymentParams, 'contribute');
1203 $this->assign('trxn_id', $result['trxn_id']);
1204 $contribution->trxn_id = $result['trxn_id'];
1205 /* Our scenarios here are
1206 * 1) the payment failed & an Exception should have been thrown
1207 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1208 * with a delayed start)
1209 * 3) the payment succeeded with an immediate payment.
1210 *
1211 * The doPayment function ensures that payment_status_id is always set
1212 * as historically we have had to guess from the context - ie doDirectPayment
1213 * = error or success, unless it is a recurring contribution in which case it is pending.
1214 */
1215 if ($result['payment_status_id'] == array_search('Completed', $statuses)) {
1216 try {
1217 civicrm_api3('contribution', 'completetransaction', array(
1218 'id' => $contribution->id,
1219 'trxn_id' => $result['trxn_id'],
1220 'payment_processor_id' => $this->_paymentProcessor['id'],
1221 'is_transactional' => FALSE,
1222 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
1223 ));
1224 // This has now been set to 1 in the DB - declare it here also
1225 $contribution->contribution_status_id = 1;
1226 }
1227 catch (CiviCRM_API3_Exception $e) {
1228 if ($e->getErrorCode() != 'contribution_completed') {
1229 throw new CRM_Core_Exception('Failed to update contribution in database');
1230 }
1231 }
1232 }
1233 else {
1234 // Save the trxn_id.
1235 $contribution->save();
1236 }
1237 }
1238 catch (PaymentProcessorException $e) {
1239 CRM_Contribute_BAO_Contribution::failPayment($contribution->id, $paymentParams['contactID'], $e->getMessage());
1240 throw new PaymentProcessorException($e->getMessage());
1241 }
1242 }
1243 // Send receipt mail.
1244 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
1245 if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
1246 $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
1247 $this->_params['contact_id'] = $contactID;
1248 $this->_params['contribution_id'] = $contribution->id;
1249 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE)) {
1250 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
1251 }
1252 }
1253
1254 return $contribution;
1255 }
1256
1257 /**
1258 * Generate the data to construct a snippet based pane.
1259 *
1260 * This form also assigns the showAdditionalInfo var based on historical code.
1261 * This appears to mean 'there is a pane to show'.
1262 *
1263 * @param string $type
1264 * Type of Pane - this is generally used to determine the function name used to build it
1265 * - e.g CreditCard, AdditionalDetail
1266 * @param array $defaults
1267 *
1268 * @return array
1269 * We aim to further refactor & simplify this but currently
1270 * - the panes array
1271 * - should additional info be shown?
1272 */
1273 protected function generatePane($type, $defaults) {
1274 $urlParams = "snippet=4&formType={$type}";
1275 if ($this->_mode) {
1276 $urlParams .= "&mode={$this->_mode}";
1277 }
1278
1279 $open = 'false';
1280 if ($type == 'CreditCard' ||
1281 $type == 'DirectDebit'
1282 ) {
1283 $open = 'true';
1284 }
1285
1286 $pane = array(
1287 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams),
1288 'open' => $open,
1289 'id' => $type,
1290 );
1291
1292 // See if we need to include this paneName in the current form.
1293 if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
1294 CRM_Utils_Array::value("hidden_{$type}", $defaults)
1295 ) {
1296 $this->assign('showAdditionalInfo', TRUE);
1297 $pane['open'] = 'true';
1298 }
1299
1300 if ($type == 'CreditCard' || $type == 'DirectDebit') {
1301 // @todo would be good to align tpl name with form name...
1302 // @todo document why this hidden variable is required.
1303 $this->add('hidden', 'hidden_' . $type, 1);
1304 return $pane;
1305 }
1306 else {
1307 $additionalInfoFormFunction = 'build' . $type;
1308 CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this);
1309 return $pane;
1310 }
1311 }
1312
1313 /**
1314 * Wrapper for unit testing the post process submit function.
1315 *
1316 * (If we expose through api we can get default additions 'for free').
1317 *
1318 * @param array $params
1319 * @param int $action
1320 * @param string|null $creditCardMode
1321 *
1322 * @throws \CiviCRM_API3_Exception
1323 */
1324 public function testSubmit($params, $action, $creditCardMode = NULL) {
1325 $defaults = array(
1326 'soft_credit_contact_id' => array(),
1327 'receipt_date' => '',
1328 'receipt_date_time' => '',
1329 'cancel_date' => '',
1330 'cancel_date_time' => '',
1331 'hidden_Premium' => 1,
1332 );
1333 $this->_bltID = 5;
1334 if (!empty($params['id'])) {
1335 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1336 'id' => $params['id'],
1337 ));
1338 $this->_id = $params['id'];
1339 }
1340 else {
1341 $existingContribution = array();
1342 }
1343
1344 $this->_defaults['contribution_status_id'] = CRM_Utils_Array::value('contribution_status_id',
1345 $existingContribution
1346 );
1347
1348 $this->_defaults['total_amount'] = CRM_Utils_Array::value('total_amount',
1349 $existingContribution
1350 );
1351
1352 if ($creditCardMode) {
1353 $this->_mode = $creditCardMode;
1354 }
1355
1356 // Required because processCreditCard calls set method on this.
1357 $_SERVER['REQUEST_METHOD'] = 'GET';
1358 $this->controller = new CRM_Core_Controller();
1359
1360 CRM_Contribute_Form_AdditionalInfo::buildPremium($this);
1361
1362 $this->_fields = array();
1363 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array::value('pledge_payment_id', $params));
1364
1365 }
1366
1367 /**
1368 * @param array $submittedValues
1369 *
1370 * @param int $action
1371 * Action constant
1372 * - CRM_Core_Action::UPDATE
1373 *
1374 * @param $pledgePaymentID
1375 *
1376 * @return array
1377 * @throws \Exception
1378 */
1379 protected function submit($submittedValues, $action, $pledgePaymentID) {
1380 $softParams = $softIDs = array();
1381 $pId = $contribution = $isRelatedId = FALSE;
1382 $this->_params = $submittedValues;
1383 $this->beginPostProcess();
1384
1385 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action::UPDATE) {
1386 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
1387 $lineID = key($line);
1388 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
1389 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1390 if ($quickConfig) {
1391 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1392 }
1393 }
1394
1395 // Process price set and get total amount and line items.
1396 $lineItem = array();
1397 $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
1398 if (empty($priceSetId) && !$this->_id) {
1399 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1400 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
1401 $fieldID = key($this->_priceSet['fields']);
1402 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
1403 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1404 $submittedValues['price_' . $fieldID] = 1;
1405 }
1406
1407 if ($priceSetId) {
1408 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1409 $submittedValues, $lineItem[$priceSetId]);
1410
1411 // Unset tax amount for offline 'is_quick_config' contribution.
1412 if ($this->_priceSet['is_quick_config'] &&
1413 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())
1414 ) {
1415 unset($submittedValues['tax_amount']);
1416 }
1417 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
1418 }
1419 if ($this->_id) {
1420 if ($this->_compId) {
1421 if ($this->_context == 'participant') {
1422 $pId = $this->_compId;
1423 }
1424 elseif ($this->_context == 'membership') {
1425 $isRelatedId = TRUE;
1426 }
1427 else {
1428 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
1429 }
1430 }
1431 else {
1432 $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1433 if (array_key_exists('membership', $contributionDetails)) {
1434 $isRelatedId = TRUE;
1435 }
1436 elseif (array_key_exists('participant', $contributionDetails)) {
1437 $pId = $contributionDetails['participant'];
1438 }
1439 }
1440 }
1441 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
1442 // CRM-10117 update the line items for participants.
1443 if ($pId) {
1444 $entityTable = 'participant';
1445 $entityID = $pId;
1446 $isRelatedId = FALSE;
1447 $participantParams = array(
1448 'fee_amount' => $submittedValues['total_amount'],
1449 'id' => $entityID,
1450 );
1451 CRM_Event_BAO_Participant::add($participantParams);
1452 if (empty($this->_lineItems)) {
1453 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
1454 }
1455 }
1456 else {
1457 $entityTable = 'contribution';
1458 $entityID = $this->_id;
1459 }
1460
1461 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1462 foreach (array_keys($lineItems) as $id) {
1463 $lineItems[$id]['id'] = $id;
1464 }
1465 $itemId = key($lineItems);
1466 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1467 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1468 }
1469
1470 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1471 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1472 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1473 if (!CRM_Utils_Array::value('membership', $componentDetails) || !CRM_Utils_Array::value('participant', $componentDetails)) {
1474 if (!($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1475 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1476 }
1477 }
1478
1479 // Update line total and total amount with tax on edit.
1480 $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
1481 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1482 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1483 }
1484 else {
1485 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1486 $submittedValues['tax_amount'] = 'null';
1487 }
1488 if ($lineItems[$itemId]['tax_rate']) {
1489 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1490 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
1491 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1492 }
1493 }
1494 // CRM-10117 update the line items for participants.
1495 if (!empty($lineItems[$itemId]['price_field_id'])) {
1496 $lineItem[$this->_priceSetId] = $lineItems;
1497 }
1498 }
1499
1500 $isQuickConfig = 0;
1501 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1502 $isQuickConfig = 1;
1503 }
1504 //CRM-11529 for quick config back office transactions
1505 //when financial_type_id is passed in form, update the
1506 //line items with the financial type selected in form
1507 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)
1508 ) {
1509 foreach ($lineItem[$this->_priceSetId] as &$values) {
1510 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1511 }
1512 }
1513
1514 if (!isset($submittedValues['total_amount'])) {
1515 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
1516 }
1517 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1518
1519 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1520 if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
1521 //Delete existing soft credit records if soft credit list is empty on update
1522 CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id, 'pcp_id' => 0));
1523 }
1524
1525 // set the contact, when contact is selected
1526 if (!empty($submittedValues['contact_id'])) {
1527 $this->_contactID = $submittedValues['contact_id'];
1528 }
1529
1530 $formValues = $submittedValues;
1531
1532 // Credit Card Contribution.
1533 if ($this->_mode) {
1534 $paramsSetByPaymentProcessingSubsystem = array(
1535 'trxn_id',
1536 'payment_instrument_id',
1537 'contribution_status_id',
1538 'cancel_date',
1539 'cancel_reason',
1540 );
1541 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1542 if (isset($formValues[$key])) {
1543 unset($formValues[$key]);
1544 }
1545 }
1546 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
1547 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1548 $formValues[$key] = $contribution->$key;
1549 }
1550 }
1551 else {
1552 // Offline Contribution.
1553 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1554
1555 // get the required field value only.
1556
1557 $params = $ids = array();
1558
1559 $params['contact_id'] = $this->_contactID;
1560 $params['currency'] = $this->getCurrency($submittedValues);
1561
1562 //format soft-credit/pcp param first
1563 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
1564 $params = array_merge($params, $submittedValues);
1565
1566 $fields = array(
1567 'financial_type_id',
1568 'contribution_status_id',
1569 'payment_instrument_id',
1570 'cancel_reason',
1571 'source',
1572 'check_number',
1573 );
1574 foreach ($fields as $f) {
1575 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1576 }
1577
1578 // CRM-5740 if priceset is used, no need to cleanup money.
1579 if ($priceSetId) {
1580 $params['skipCleanMoney'] = 1;
1581 }
1582
1583 $dates = array(
1584 'receive_date',
1585 'receipt_date',
1586 'cancel_date',
1587 );
1588
1589 foreach ($dates as $d) {
1590 $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1591 }
1592
1593 if (!empty($formValues['is_email_receipt'])) {
1594 $params['receipt_date'] = date("Y-m-d");
1595 }
1596
1597 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name')
1598 || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')
1599 ) {
1600 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
1601 $params['cancel_date'] = date('Y-m-d');
1602 }
1603 }
1604 else {
1605 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1606 }
1607
1608 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1609 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1610 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
1611 $params['is_pay_later'] = 1;
1612 }
1613 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
1614 $params['is_pay_later'] = 0;
1615 }
1616
1617 $ids['contribution'] = $params['id'] = $this->_id;
1618
1619 // Add Additional common information to formatted params.
1620 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1621 if ($pId) {
1622 $params['contribution_mode'] = 'participant';
1623 $params['participant_id'] = $pId;
1624 $params['skipLineItem'] = 1;
1625 }
1626 elseif ($isRelatedId) {
1627 $params['contribution_mode'] = 'membership';
1628 }
1629 $params['line_item'] = $lineItem;
1630 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
1631 if (isset($submittedValues['tax_amount'])) {
1632 $params['tax_amount'] = $submittedValues['tax_amount'];
1633 }
1634 //create contribution.
1635 if ($isQuickConfig) {
1636 $params['is_quick_config'] = 1;
1637 }
1638 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1639
1640 $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
1641
1642 // process associated membership / participant, CRM-4395
1643 if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
1644 $this->statusMessage[] = $this->updateRelatedComponent($contribution->id,
1645 $contribution->contribution_status_id,
1646 CRM_Utils_Array::value('contribution_status_id',
1647 $this->_values
1648 ),
1649 $contribution->receive_date
1650 );
1651 }
1652
1653 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
1654
1655 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1656
1657 //send receipt mail.
1658 if ($contribution->id && !empty($formValues['is_email_receipt'])) {
1659 $formValues['contact_id'] = $this->_contactID;
1660 $formValues['contribution_id'] = $contribution->id;
1661
1662 $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
1663
1664 // to get 'from email id' for send receipt
1665 $this->fromEmailId = $formValues['from_email_address'];
1666 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
1667 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
1668 }
1669 }
1670
1671 $this->statusMessageTitle = ts('Saved');
1672
1673 }
1674
1675 if ($contribution->id && !empty($formValues['product_name'][0])) {
1676 CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id,
1677 $this->_premiumID, $this->_options
1678 );
1679 }
1680
1681 if ($contribution->id && isset($submittedValues['note'])) {
1682 CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
1683 }
1684
1685 CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
1686
1687 CRM_Contribute_BAO_Contribution::updateRelatedPledge(
1688 $action,
1689 $pledgePaymentID,
1690 $contribution->id,
1691 (CRM_Utils_Array::value('option_type', $formValues) == 2) ? TRUE : FALSE,
1692 $formValues['total_amount'],
1693 CRM_Utils_Array::value('total_amount', $this->_defaults),
1694 $formValues['contribution_status_id'],
1695 CRM_Utils_Array::value('contribution_status_id', $this->_defaults)
1696 );
1697 return $contribution;
1698 }
1699
1700 /**
1701 * Assign tax calculations to contribution receipts.
1702 *
1703 * @param array $submittedValues
1704 * @param int $action
1705 * @param array $lineItem
1706 */
1707 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1708
1709 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
1710 if (!CRM_Utils_Array::value('invoicing', $invoiceSettings)) {
1711 return;
1712 }
1713 $taxRate = array();
1714 $getTaxDetails = FALSE;
1715 if ($action & CRM_Core_Action::ADD) {
1716 $line = $lineItem;
1717 }
1718 elseif ($action & CRM_Core_Action::UPDATE) {
1719 $line = $this->_lineItems;
1720 }
1721 foreach ($line as $key => $value) {
1722 foreach ($value as $v) {
1723 if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) {
1724 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v);
1725 }
1726 else {
1727 if (isset($v['tax_rate'])) {
1728 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v);
1729 $getTaxDetails = TRUE;
1730 }
1731 }
1732 }
1733 }
1734
1735 if ($action & CRM_Core_Action::UPDATE) {
1736 if (isset($submittedValues['tax_amount'])) {
1737 $totalTaxAmount = $submittedValues['tax_amount'];
1738 }
1739 else {
1740 $totalTaxAmount = $this->_values['tax_amount'];
1741 }
1742 $this->assign('totalTaxAmount', $totalTaxAmount);
1743 $this->assign('dataArray', $taxRate);
1744 }
1745 else {
1746 if (!empty($submittedValues['price_set_id'])) {
1747 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1748 $this->assign('getTaxDetails', $getTaxDetails);
1749 $this->assign('dataArray', $taxRate);
1750 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
1751 }
1752 else {
1753 $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
1754 }
1755 }
1756 }
1757
1758 /**
1759 * Calculate non deductible amount.
1760 *
1761 * CRM-11956
1762 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1763 * if non_deductible_amount does NOT exist - then calculate it depending on:
1764 * $financialType->is_deductible and whether there is a product (premium).
1765 *
1766 * @param $params
1767 * @param $formValues
1768 *
1769 * @return array
1770 */
1771 protected function calculateNonDeductibleAmount($params, $formValues) {
1772 if (!empty($params['non_deductible_amount'])) {
1773 return $params['non_deductible_amount'];
1774 }
1775
1776 $financialType = new CRM_Financial_DAO_FinancialType();
1777 $financialType->id = $params['financial_type_id'];
1778
1779 if ($financialType->is_deductible) {
1780
1781 if (isset($formValues['product_name'][0])) {
1782 $selectProduct = $formValues['product_name'][0];
1783 }
1784 // if there is a product - compare the value to the contribution amount
1785 if (isset($selectProduct)) {
1786 $productDAO = new CRM_Contribute_DAO_Product();
1787 $productDAO->id = $selectProduct;
1788 $productDAO->find(TRUE);
1789 // product value exceeds contribution amount
1790 if ($params['total_amount'] < $productDAO->price) {
1791 return $params['total_amount'];
1792 }
1793 // product value does NOT exceed contribution amount
1794 else {
1795 return $productDAO->price;
1796 }
1797 }
1798 // contribution is deductible - but there is no product
1799 else {
1800 return '0.00';
1801 }
1802 }
1803 // contribution is NOT deductible
1804 else {
1805 return $params['total_amount'];
1806 }
1807
1808 return 0;
1809 }
1810
1811 }