Merge pull request #7256 from esantanche/esantanche-patch-regex
[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 (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
463 && $this->_action & CRM_Core_Action::UPDATE
464 && CRM_Utils_Array::value('financial_type_id', $this->_values)
465 ) {
466 $financialTypeID = CRM_Contribute_PseudoConstant::financialType($this->_values['financial_type_id']);
467 CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($this->_id, 'edit');
468 if (!CRM_Core_Permission::check('edit contributions of type ' . $financialTypeID)) {
469 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
470 }
471 }
472 $allPanes = array();
473 $recurJs = NULL;
474 //tax rate from financialType
475 $this->assign('taxRates', json_encode(CRM_Core_PseudoConstant::getTaxRates()));
476 $this->assign('currencies', json_encode(CRM_Core_OptionGroup::values('currencies_enabled')));
477
478 // build price set form.
479 $buildPriceSet = FALSE;
480 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
481 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
482 $this->assign('invoicing', $invoicing);
483
484 // display tax amount on edit contribution page
485 if ($invoicing && $this->_action & CRM_Core_Action::UPDATE && isset($this->_values['tax_amount'])) {
486 $this->assign('totalTaxAmount', $this->_values['tax_amount']);
487 }
488
489 if (empty($this->_lineItems) &&
490 ($this->_priceSetId || !empty($_POST['price_set_id']))
491 ) {
492 $buildPriceSet = TRUE;
493 $getOnlyPriceSetElements = TRUE;
494 if (!$this->_priceSetId) {
495 $this->_priceSetId = $_POST['price_set_id'];
496 $getOnlyPriceSetElements = FALSE;
497 }
498
499 $this->set('priceSetId', $this->_priceSetId);
500 CRM_Price_BAO_PriceSet::buildPriceSet($this);
501
502 // get only price set form elements.
503 if ($getOnlyPriceSetElements) {
504 return;
505 }
506 }
507 // use to build form during form rule.
508 $this->assign('buildPriceSet', $buildPriceSet);
509
510 $defaults = $this->_values;
511 $additionalDetailFields = array(
512 'note',
513 'thankyou_date',
514 'invoice_id',
515 'non_deductible_amount',
516 'fee_amount',
517 'net_amount',
518 );
519 foreach ($additionalDetailFields as $key) {
520 if (!empty($defaults[$key])) {
521 $defaults['hidden_AdditionalDetail'] = 1;
522 break;
523 }
524 }
525
526 if ($this->_productDAO) {
527 if ($this->_productDAO->product_id) {
528 $defaults['hidden_Premium'] = 1;
529 }
530 }
531
532 if ($this->_noteID &&
533 isset($this->_values['note'])
534 ) {
535 $defaults['hidden_AdditionalDetail'] = 1;
536 }
537
538 $paneNames = array(
539 ts('Additional Details') => 'AdditionalDetail',
540 );
541
542 //Add Premium pane only if Premium is exists.
543 $dao = new CRM_Contribute_DAO_Product();
544 $dao->is_active = 1;
545
546 if ($dao->find(TRUE)) {
547 $paneNames[ts('Premium Information')] = 'Premium';
548 }
549
550 if ($this->_mode) {
551 if (CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE) == TRUE) {
552 if (!empty($this->_recurPaymentProcessors)) {
553 $buildRecurBlock = TRUE;
554 if ($this->_ppID) {
555 // ppID denotes a pledge payment.
556 foreach ($this->_paymentProcessors as $processor) {
557 if (!empty($processor['is_recur']) && !empty($processor['object']) && $processor['object']->supports('recurContributionsForPledges')) {
558 $buildRecurBlock = TRUE;
559 break;
560 }
561 $buildRecurBlock = FALSE;
562 }
563 }
564 if ($buildRecurBlock) {
565 CRM_Contribute_Form_Contribution_Main::buildRecur($this);
566 $this->setDefaults(array('is_recur' => 0));
567 $this->assign('buildRecurBlock', TRUE);
568 $recurJs = array('onChange' => "buildRecurBlock( this.value ); return false;");
569 }
570 }
571 }
572 }
573
574 foreach ($paneNames as $name => $type) {
575 $allPanes[$name] = $this->generatePane($type, $defaults);
576 }
577
578 $qfKey = $this->controller->_key;
579 $this->assign('qfKey', $qfKey);
580 $this->assign('allPanes', $allPanes);
581
582 $this->addFormRule(array('CRM_Contribute_Form_Contribution', 'formRule'), $this);
583
584 if ($this->_formType) {
585 $this->assign('formType', $this->_formType);
586 return;
587 }
588
589 $this->applyFilter('__ALL__', 'trim');
590
591 if ($this->_action & CRM_Core_Action::DELETE) {
592 $this->addButtons(array(
593 array(
594 'type' => 'next',
595 'name' => ts('Delete'),
596 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
597 'isDefault' => TRUE,
598 ),
599 array(
600 'type' => 'cancel',
601 'name' => ts('Cancel'),
602 ),
603 )
604 );
605 return;
606 }
607
608 //need to assign custom data type and subtype to the template
609 $this->assign('customDataType', 'Contribution');
610 $this->assign('customDataSubType', $this->_contributionType);
611 $this->assign('entityID', $this->_id);
612
613 if ($this->_context == 'standalone') {
614 $this->addEntityRef('contact_id', ts('Contact'), array(
615 'create' => TRUE,
616 'api' => array('extra' => array('email')),
617 ), TRUE);
618 }
619
620 $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
621
622 // Check permissions for financial type first
623 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action);
624 if (empty($financialTypes)) {
625 CRM_Core_Error::statusBounce(ts('You do not have all the permissions needed for this page.'));
626 }
627 $financialType = $this->add('select', 'financial_type_id',
628 ts('Financial Type'),
629 array('' => ts('- select -')) + $financialTypes,
630 TRUE,
631 array('onChange' => "CRM.buildCustomData( 'Contribution', this.value );")
632 );
633
634 $paymentInstrument = FALSE;
635 if (!$this->_mode) {
636 $paymentInstrument = $this->add('select', 'payment_instrument_id',
637 ts('Payment Method'),
638 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
639 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
640 );
641 }
642
643 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') + $attributes['trxn_id']);
644
645 //add receipt for offline contribution
646 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
647
648 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
649
650 $status = CRM_Contribute_PseudoConstant::contributionStatus();
651
652 // suppressing contribution statuses that are NOT relevant to pledges (CRM-5169)
653 $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
654 if ($this->_ppID) {
655 foreach (array(
656 'Cancelled',
657 'Failed',
658 'In Progress',
659 ) as $suppress) {
660 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
661 }
662 }
663 elseif ((!$this->_ppID && $this->_id) || !$this->_id) {
664 $suppressFlag = FALSE;
665 if ($this->_id) {
666 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
667 if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) {
668 $suppressFlag = TRUE;
669 }
670 }
671 if (!$suppressFlag) {
672 foreach (array(
673 'Overdue',
674 'In Progress',
675 ) as $suppress) {
676 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
677 }
678 }
679 else {
680 unset($status[CRM_Utils_Array::key('Overdue', $statusName)]);
681 }
682 }
683
684 if ($this->_id) {
685 $contributionStatus = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_id, 'contribution_status_id');
686 $name = CRM_Utils_Array::value($contributionStatus, $statusName);
687 switch ($name) {
688 case 'Completed':
689 case 'Cancelled':
690 case 'Refunded':
691 unset($status[CRM_Utils_Array::key('In Progress', $statusName)]);
692 unset($status[CRM_Utils_Array::key('Pending', $statusName)]);
693 unset($status[CRM_Utils_Array::key('Failed', $statusName)]);
694 break;
695
696 case 'Pending':
697 case 'In Progress':
698 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
699 break;
700
701 case 'Failed':
702 foreach (array(
703 'Pending',
704 'Refunded',
705 'Completed',
706 'In Progress',
707 'Cancelled',
708 ) as $suppress) {
709 unset($status[CRM_Utils_Array::key($suppress, $statusName)]);
710 }
711 break;
712 }
713 }
714 else {
715 unset($status[CRM_Utils_Array::key('Refunded', $statusName)]);
716 }
717
718 $this->add('select', 'contribution_status_id',
719 ts('Contribution Status'),
720 $status,
721 FALSE
722 );
723
724 // add various dates
725 $this->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
726
727 if ($this->_online) {
728 $this->assign('hideCalender', TRUE);
729 }
730 $checkNumber = $this->add('text', 'check_number', ts('Check Number'), $attributes['check_number']);
731
732 $this->addDateTime('receipt_date', ts('Receipt Date'), FALSE, array('formatType' => 'activityDateTime'));
733 $this->addDateTime('cancel_date', ts('Cancelled / Refunded Date'), FALSE, array('formatType' => 'activityDateTime'));
734
735 $this->add('textarea', 'cancel_reason', ts('Cancellation / Refund Reason'), $attributes['cancel_reason']);
736
737 $element = $this->add('select',
738 'payment_processor_id',
739 ts('Payment Processor'),
740 $this->_processors,
741 NULL,
742 $recurJs
743 );
744
745 if ($this->_online) {
746 $element->freeze();
747 }
748
749 $totalAmount = NULL;
750 if (empty($this->_lineItems)) {
751 $buildPriceSet = FALSE;
752 $priceSets = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
753 if (!empty($priceSets) && !$this->_ppID) {
754 $buildPriceSet = TRUE;
755 }
756
757 // don't allow price set for contribution if it is related to participant, or if it is a pledge payment
758 // and if we already have line items for that participant. CRM-5095
759 if ($buildPriceSet && $this->_id) {
760 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
761 $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
762 $this->_id,
763 'id',
764 'contribution_id'
765 );
766 if ($pledgePaymentId) {
767 $buildPriceSet = FALSE;
768 }
769 if ($participantID = CRM_Utils_Array::value('participant', $componentDetails)) {
770 $participantLI = CRM_Price_BAO_LineItem::getLineItems($participantID);
771 if (!CRM_Utils_System::isNull($participantLI)) {
772 $buildPriceSet = FALSE;
773 }
774 }
775 }
776
777 $hasPriceSets = FALSE;
778 if ($buildPriceSet) {
779 $hasPriceSets = TRUE;
780 // CRM-16451: set financial type of 'Price Set' in back office contribution
781 // instead of selecting manually
782 $financialTypeIds = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute', 'financial_type_id');
783 $element = $this->add('select', 'price_set_id', ts('Choose price set'),
784 array(
785 '' => ts('Choose price set'),
786 ) + $priceSets,
787 NULL, array('onchange' => "buildAmount( this.value, " . json_encode($financialTypeIds) . ");")
788 );
789 if ($this->_online && !($this->_action & CRM_Core_Action::UPDATE)) {
790 $element->freeze();
791 }
792 }
793 $this->assign('hasPriceSets', $hasPriceSets);
794 $currencyFreeze = FALSE;
795 if (!($this->_action & CRM_Core_Action::UPDATE)) {
796 if ($this->_online || $this->_ppID) {
797 $attributes['total_amount'] = array_merge($attributes['total_amount'], array(
798 'READONLY' => TRUE,
799 'style' => "background-color:#EBECE4",
800 ));
801 $optionTypes = array(
802 '1' => ts('Adjust Pledge Payment Schedule?'),
803 '2' => ts('Adjust Total Pledge Amount?'),
804 );
805 $this->addRadio('option_type',
806 NULL,
807 $optionTypes,
808 array(), '<br/>'
809 );
810
811 $currencyFreeze = TRUE;
812 }
813 }
814
815 $totalAmount = $this->addMoney('total_amount',
816 ts('Total Amount'),
817 ($hasPriceSets) ? FALSE : TRUE,
818 $attributes['total_amount'],
819 TRUE, 'currency', NULL, $currencyFreeze
820 );
821 }
822
823 $this->add('text', 'source', ts('Source'), CRM_Utils_Array::value('source', $attributes));
824
825 // CRM-7362 --add campaigns.
826 CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
827
828 CRM_Contribute_Form_SoftCredit::buildQuickForm($this);
829
830 $js = NULL;
831 if (!$this->_mode) {
832 $js = array('onclick' => "return verify( );");
833 }
834
835 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
836 'mailing_backend'
837 );
838 $this->assign('outBound_option', $mailingInfo['outBound_option']);
839
840 $this->addButtons(array(
841 array(
842 'type' => 'upload',
843 'name' => ts('Save'),
844 'js' => $js,
845 'isDefault' => TRUE,
846 ),
847 array(
848 'type' => 'upload',
849 'name' => ts('Save and New'),
850 'js' => $js,
851 'subName' => 'new',
852 ),
853 array(
854 'type' => 'cancel',
855 'name' => ts('Cancel'),
856 ),
857 )
858 );
859
860 // if status is Cancelled freeze Amount, Payment Instrument, Check #, Financial Type,
861 // Net and Fee Amounts are frozen in AdditionalInfo::buildAdditionalDetail
862 if ($this->_id && $this->_values['contribution_status_id'] == array_search('Cancelled', $statusName)) {
863 if ($totalAmount) {
864 $totalAmount->freeze();
865 }
866 $checkNumber->freeze();
867 $paymentInstrument->freeze();
868 $trxnId->freeze();
869 $financialType->freeze();
870 }
871
872 // if contribution is related to membership or participant freeze Financial Type, Amount
873 if ($this->_id && isset($this->_values['tax_amount'])) {
874 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
875 if (CRM_Utils_Array::value('membership', $componentDetails) || CRM_Utils_Array::value('participant', $componentDetails)) {
876 if ($totalAmount) {
877 $totalAmount->freeze();
878 }
879 $financialType->freeze();
880 $this->assign('freezeFinancialType', TRUE);
881 }
882 }
883
884 if ($this->_action & CRM_Core_Action::VIEW) {
885 $this->freeze();
886 }
887 }
888
889 /**
890 * Global form rule.
891 *
892 * @param array $fields
893 * The input form values.
894 * @param array $files
895 * The uploaded files if any.
896 * @param $self
897 *
898 * @return bool|array
899 * true if no errors, else array of errors
900 */
901 public static function formRule($fields, $files, $self) {
902 $errors = array();
903 // Check for Credit Card Contribution.
904 if ($self->_mode) {
905 if (empty($fields['payment_processor_id'])) {
906 $errors['payment_processor_id'] = ts('Payment Processor is a required field.');
907 }
908 else {
909 // validate payment instrument (e.g. credit card number)
910 CRM_Core_Payment_Form::validatePaymentInstrument($fields['payment_processor_id'], $fields, $errors, NULL);
911 }
912 }
913
914 // Do the amount validations.
915 if (empty($fields['total_amount']) && empty($self->_lineItems)) {
916 if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
917 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $fields, $errors);
918 }
919 }
920
921 $softErrors = CRM_Contribute_Form_SoftCredit::formRule($fields, $errors, $self);
922
923 if (!empty($fields['total_amount']) && (!empty($fields['net_amount']) || !empty($fields['fee_amount']))) {
924 $sum = CRM_Utils_Rule::cleanMoney($fields['net_amount']) + CRM_Utils_Rule::cleanMoney($fields['fee_amount']);
925 // For taxable contribution we need to deduct taxable amount from
926 // (net amount + fee amount) before comparing it with total amount
927 if (!empty($self->_values['tax_amount'])) {
928 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($self->_id);
929 if (!(CRM_Utils_Array::value('membership', $componentDetails) ||
930 CRM_Utils_Array::value('participant', $componentDetails))
931 ) {
932 $sum = CRM_Utils_Money::format($sum - $self->_values['tax_amount'], NULL, '%a');
933 }
934 }
935 if (CRM_Utils_Rule::cleanMoney($fields['total_amount']) != $sum) {
936 $errors['total_amount'] = ts('The sum of fee amount and net amount must be equal to total amount');
937 }
938 }
939
940 //CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
941 CRM_Contribute_BAO_ContributionRecur::validateRecurContribution($fields, $files, $self, $errors);
942
943 // Form rule for status http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
944 if (($self->_action & CRM_Core_Action::UPDATE)
945 && $self->_id
946 && $self->_values['contribution_status_id'] != $fields['contribution_status_id']
947 ) {
948 CRM_Contribute_BAO_Contribution::checkStatusValidation($self->_values, $fields, $errors);
949 }
950 // CRM-16015, add form-rule to restrict change of financial type if using price field of different financial type
951 if (($self->_action & CRM_Core_Action::UPDATE)
952 && $self->_id
953 && $self->_values['financial_type_id'] != $fields['financial_type_id']
954 ) {
955 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange(NULL, $self->_id, $errors);
956 }
957 //FIXME FOR NEW DATA FLOW http://wiki.civicrm.org/confluence/display/CRM/CiviAccounts+4.3+Data+Flow
958 if (!empty($fields['fee_amount']) && !empty($fields['financial_type_id']) && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($fields['financial_type_id'])) {
959 $errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
960 }
961
962 // $trxn_id must be unique CRM-13919
963 if (!empty($fields['trxn_id'])) {
964 $queryParams = array(1 => array($fields['trxn_id'], 'String'));
965 $query = 'select count(*) from civicrm_contribution where trxn_id = %1';
966 if ($self->_id) {
967 $queryParams[2] = array((int) $self->_id, 'Integer');
968 $query .= ' and id !=%2';
969 }
970 $tCnt = CRM_Core_DAO::singleValueQuery($query, $queryParams);
971 if ($tCnt) {
972 $errors['trxn_id'] = ts('Transaction ID\'s must be unique. Transaction \'%1\' already exists in your database.', array(1 => $fields['trxn_id']));
973 }
974 }
975
976 $errors = array_merge($errors, $softErrors);
977 return $errors;
978 }
979
980 /**
981 * Process the form submission.
982 */
983 public function postProcess() {
984 if ($this->_action & CRM_Core_Action::DELETE) {
985 CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
986 CRM_Core_Session::singleton()->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
987 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
988 ));
989 return;
990 }
991 // Get the submitted form values.
992 $submittedValues = $this->controller->exportValues($this->_name);
993
994 try {
995 $contribution = $this->submit($submittedValues, $this->_action, $this->_ppID);
996 }
997 catch (PaymentProcessorException $e) {
998 // Set the contribution mode.
999 $urlParams = "action=add&cid={$this->_contactID}";
1000 if ($this->_mode) {
1001 $urlParams .= "&mode={$this->_mode}";
1002 }
1003 if (!empty($this->_ppID)) {
1004 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
1005 }
1006
1007 CRM_Core_Error::statusBounce($e->getMessage(), $urlParams, ts('Payment Processor Error'));
1008 }
1009 $session = CRM_Core_Session::singleton();
1010 $buttonName = $this->controller->getButtonName();
1011 if ($this->_context == 'standalone') {
1012 if ($buttonName == $this->getButtonName('upload', 'new')) {
1013 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add',
1014 'reset=1&action=add&context=standalone'
1015 ));
1016 }
1017 else {
1018 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1019 "reset=1&cid={$this->_contactID}&selectedChild=contribute"
1020 ));
1021 }
1022 }
1023 elseif ($this->_context == 'contribution' && $this->_mode && $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}&mode={$this->_mode}"
1026 ));
1027 }
1028 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1029 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution',
1030 "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"
1031 ));
1032 }
1033
1034 //store contribution ID if not yet set (on create)
1035 if (empty($this->_id) && !empty($contribution->id)) {
1036 $this->_id = $contribution->id;
1037 }
1038 }
1039
1040 /**
1041 * Process credit card payment.
1042 *
1043 * @param array $submittedValues
1044 * @param array $lineItem
1045 *
1046 * @param int $contactID
1047 * Contact ID
1048 *
1049 * @return bool|\CRM_Contribute_DAO_Contribution
1050 * @throws \CRM_Core_Exception
1051 * @throws \Civi\Payment\Exception\PaymentProcessorException
1052 */
1053 protected function processCreditCard($submittedValues, $lineItem, $contactID) {
1054 $isTest = ($this->_mode == 'test') ? 1 : 0;
1055 // CRM-12680 set $_lineItem if its not set
1056 // @todo - I don't believe this would ever BE set. I can't find anywhere in the code.
1057 // It would be better to pass line item out to functions than $this->_lineItem as
1058 // we don't know what is being changed where.
1059 if (empty($this->_lineItem) && !empty($lineItem)) {
1060 $this->_lineItem = $lineItem;
1061 }
1062
1063 $this->_paymentObject = Civi\Payment\System::singleton()->getById($submittedValues['payment_processor_id']);
1064 $this->_paymentProcessor = $this->_paymentObject->getPaymentProcessor();
1065
1066 // Set source if not set
1067 if (empty($submittedValues['source'])) {
1068 $userID = CRM_Core_Session::singleton()->get('userID');
1069 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
1070 'sort_name'
1071 );
1072 $submittedValues['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
1073 }
1074
1075 $params = $submittedValues;
1076 $this->_params = array_merge($this->_params, $submittedValues);
1077
1078 // Mapping requiring documentation.
1079 $this->_params['payment_processor'] = $submittedValues['payment_processor_id'];
1080
1081 $now = date('YmdHis');
1082
1083 // we need to retrieve email address
1084 if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
1085 list($this->userDisplayName,
1086 $this->userEmail
1087 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
1088 $this->assign('displayName', $this->userDisplayName);
1089 }
1090
1091 $this->_contributorEmail = $this->userEmail;
1092 $this->_contributorContactID = $contactID;
1093 $this->processBillingAddress();
1094 if (!empty($params['source'])) {
1095 unset($params['source']);
1096 }
1097
1098 $this->_params['amount'] = $this->_params['total_amount'];
1099 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1100 // function to get correct amount level consistently. Remove setting of the amount level in
1101 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1102 // to cover all variants.
1103 $this->_params['amount_level'] = 0;
1104 $this->_params['description'] = ts("Contribution submitted by a staff person using contributor's credit card");
1105 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
1106 $this->_params,
1107 CRM_Core_Config::singleton()->defaultCurrency
1108 );
1109
1110 if (!empty($this->_params['receive_date'])) {
1111 $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
1112 }
1113
1114 $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
1115 $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
1116 $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
1117
1118 //Add common data to formatted params
1119 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
1120
1121 if (empty($this->_params['invoice_id'])) {
1122 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1123 }
1124 else {
1125 $this->_params['invoiceID'] = $this->_params['invoice_id'];
1126 }
1127
1128 // At this point we've created a contact and stored its address etc
1129 // all the payment processors expect the name and address to be in the
1130 // so we copy stuff over to first_name etc.
1131 $paymentParams = $this->_params;
1132 $paymentParams['contactID'] = $contactID;
1133 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
1134
1135 $financialType = new CRM_Financial_DAO_FinancialType();
1136 $financialType->id = $params['financial_type_id'];
1137 $financialType->find(TRUE);
1138
1139 // Add some financial type details to the params list
1140 // if folks need to use it.
1141 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $financialType->name;
1142 $paymentParams['contributionPageID'] = NULL;
1143
1144 if (!empty($this->_params['is_email_receipt'])) {
1145 $paymentParams['email'] = $this->userEmail;
1146 $paymentParams['is_email_receipt'] = 1;
1147 }
1148 else {
1149 $paymentParams['is_email_receipt'] = 0;
1150 $this->_params['is_email_receipt'] = 0;
1151 }
1152 if (!empty($this->_params['receive_date'])) {
1153 $paymentParams['receive_date'] = $this->_params['receive_date'];
1154 }
1155
1156 $this->_params['receive_date'] = $now;
1157
1158 if (!empty($this->_params['is_email_receipt'])) {
1159 $this->_params['receipt_date'] = $now;
1160 }
1161 else {
1162 $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'],
1163 $params['receipt_date_time'], TRUE
1164 );
1165 }
1166
1167 $this->set('params', $this->_params);
1168
1169 $this->assign('receive_date', $this->_params['receive_date']);
1170
1171 // Result has all the stuff we need
1172 // lets archive it to a financial transaction
1173 if ($financialType->is_deductible) {
1174 $this->assign('is_deductible', TRUE);
1175 $this->set('is_deductible', TRUE);
1176 }
1177 $contributionParams = array(
1178 'contact_id' => $contactID,
1179 'line_item' => $lineItem,
1180 'is_test' => $isTest,
1181 'campaign_id' => CRM_Utils_Array::value('campaign_id', $this->_params),
1182 'contribution_page_id' => CRM_Utils_Array::value('contribution_page_id', $this->_params),
1183 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
1184 'thankyou_date' => CRM_Utils_Array::value('thankyou_date', $this->_params),
1185 );
1186
1187 if (empty($paymentParams['is_pay_later'])) {
1188 // @todo look up payment_instrument_id on payment processor table.
1189 $contributionParams['payment_instrument_id'] = 1;
1190 }
1191
1192 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this,
1193 $this->_params,
1194 NULL,
1195 $contributionParams,
1196 $financialType,
1197 FALSE,
1198 $this->_bltID
1199 );
1200
1201 $paymentParams['contributionID'] = $contribution->id;
1202 $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
1203 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
1204 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
1205
1206 if ($paymentParams['amount'] > 0.0) {
1207 // force a re-get of the payment processor in case the form changed it, CRM-7179
1208 // NOTE - I expect this is obsolete.
1209 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
1210 try {
1211 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
1212 $result = $payment->doPayment($paymentParams, 'contribute');
1213 $this->assign('trxn_id', $result['trxn_id']);
1214 $contribution->trxn_id = $result['trxn_id'];
1215 /* Our scenarios here are
1216 * 1) the payment failed & an Exception should have been thrown
1217 * 2) the payment succeeded but the payment is not immediate (for example a recurring payment
1218 * with a delayed start)
1219 * 3) the payment succeeded with an immediate payment.
1220 *
1221 * The doPayment function ensures that payment_status_id is always set
1222 * as historically we have had to guess from the context - ie doDirectPayment
1223 * = error or success, unless it is a recurring contribution in which case it is pending.
1224 */
1225 if ($result['payment_status_id'] == array_search('Completed', $statuses)) {
1226 try {
1227 civicrm_api3('contribution', 'completetransaction', array(
1228 'id' => $contribution->id,
1229 'trxn_id' => $result['trxn_id'],
1230 'payment_processor_id' => $this->_paymentProcessor['id'],
1231 'is_transactional' => FALSE,
1232 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result),
1233 ));
1234 // This has now been set to 1 in the DB - declare it here also
1235 $contribution->contribution_status_id = 1;
1236 }
1237 catch (CiviCRM_API3_Exception $e) {
1238 if ($e->getErrorCode() != 'contribution_completed') {
1239 throw new CRM_Core_Exception('Failed to update contribution in database');
1240 }
1241 }
1242 }
1243 else {
1244 // Save the trxn_id.
1245 $contribution->save();
1246 }
1247 }
1248 catch (PaymentProcessorException $e) {
1249 CRM_Contribute_BAO_Contribution::failPayment($contribution->id, $paymentParams['contactID'], $e->getMessage());
1250 throw new PaymentProcessorException($e->getMessage());
1251 }
1252 }
1253 // Send receipt mail.
1254 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
1255 if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
1256 $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
1257 $this->_params['contact_id'] = $contactID;
1258 $this->_params['contribution_id'] = $contribution->id;
1259 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE)) {
1260 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
1261 }
1262 }
1263
1264 return $contribution;
1265 }
1266
1267 /**
1268 * Generate the data to construct a snippet based pane.
1269 *
1270 * This form also assigns the showAdditionalInfo var based on historical code.
1271 * This appears to mean 'there is a pane to show'.
1272 *
1273 * @param string $type
1274 * Type of Pane - this is generally used to determine the function name used to build it
1275 * - e.g CreditCard, AdditionalDetail
1276 * @param array $defaults
1277 *
1278 * @return array
1279 * We aim to further refactor & simplify this but currently
1280 * - the panes array
1281 * - should additional info be shown?
1282 */
1283 protected function generatePane($type, $defaults) {
1284 $urlParams = "snippet=4&formType={$type}";
1285 if ($this->_mode) {
1286 $urlParams .= "&mode={$this->_mode}";
1287 }
1288
1289 $open = 'false';
1290 if ($type == 'CreditCard' ||
1291 $type == 'DirectDebit'
1292 ) {
1293 $open = 'true';
1294 }
1295
1296 $pane = array(
1297 'url' => CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams),
1298 'open' => $open,
1299 'id' => $type,
1300 );
1301
1302 // See if we need to include this paneName in the current form.
1303 if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
1304 CRM_Utils_Array::value("hidden_{$type}", $defaults)
1305 ) {
1306 $this->assign('showAdditionalInfo', TRUE);
1307 $pane['open'] = 'true';
1308 }
1309
1310 if ($type == 'CreditCard' || $type == 'DirectDebit') {
1311 // @todo would be good to align tpl name with form name...
1312 // @todo document why this hidden variable is required.
1313 $this->add('hidden', 'hidden_' . $type, 1);
1314 return $pane;
1315 }
1316 else {
1317 $additionalInfoFormFunction = 'build' . $type;
1318 CRM_Contribute_Form_AdditionalInfo::$additionalInfoFormFunction($this);
1319 return $pane;
1320 }
1321 }
1322
1323 /**
1324 * Wrapper for unit testing the post process submit function.
1325 *
1326 * (If we expose through api we can get default additions 'for free').
1327 *
1328 * @param array $params
1329 * @param int $action
1330 * @param string|null $creditCardMode
1331 *
1332 * @throws \CiviCRM_API3_Exception
1333 */
1334 public function testSubmit($params, $action, $creditCardMode = NULL) {
1335 $defaults = array(
1336 'soft_credit_contact_id' => array(),
1337 'receipt_date' => '',
1338 'receipt_date_time' => '',
1339 'cancel_date' => '',
1340 'cancel_date_time' => '',
1341 'hidden_Premium' => 1,
1342 );
1343 $this->_bltID = 5;
1344 if (!empty($params['id'])) {
1345 $existingContribution = civicrm_api3('contribution', 'getsingle', array(
1346 'id' => $params['id'],
1347 ));
1348 $this->_id = $params['id'];
1349 }
1350 else {
1351 $existingContribution = array();
1352 }
1353
1354 $this->_defaults['contribution_status_id'] = CRM_Utils_Array::value('contribution_status_id',
1355 $existingContribution
1356 );
1357
1358 $this->_defaults['total_amount'] = CRM_Utils_Array::value('total_amount',
1359 $existingContribution
1360 );
1361
1362 if ($creditCardMode) {
1363 $this->_mode = $creditCardMode;
1364 }
1365
1366 // Required because processCreditCard calls set method on this.
1367 $_SERVER['REQUEST_METHOD'] = 'GET';
1368 $this->controller = new CRM_Core_Controller();
1369
1370 CRM_Contribute_Form_AdditionalInfo::buildPremium($this);
1371
1372 $this->_fields = array();
1373 $this->submit(array_merge($defaults, $params), $action, CRM_Utils_Array::value('pledge_payment_id', $params));
1374
1375 }
1376
1377 /**
1378 * @param array $submittedValues
1379 *
1380 * @param int $action
1381 * Action constant
1382 * - CRM_Core_Action::UPDATE
1383 *
1384 * @param $pledgePaymentID
1385 *
1386 * @return array
1387 * @throws \Exception
1388 */
1389 protected function submit($submittedValues, $action, $pledgePaymentID) {
1390 $softParams = $softIDs = array();
1391 $pId = $contribution = $isRelatedId = FALSE;
1392 $this->_params = $submittedValues;
1393 $this->beginPostProcess();
1394
1395 if (!empty($submittedValues['price_set_id']) && $action & CRM_Core_Action::UPDATE) {
1396 $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
1397 $lineID = key($line);
1398 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
1399 $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1400 // Why do we do this? Seems like a like a wrapper for old functionality - but single line price sets & quick
1401 // config should be treated the same.
1402 if ($quickConfig) {
1403 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
1404 }
1405 }
1406
1407 // Process price set and get total amount and line items.
1408 $lineItem = array();
1409 $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
1410 if (empty($priceSetId) && !$this->_id) {
1411 $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
1412 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
1413 $fieldID = key($this->_priceSet['fields']);
1414 $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
1415 $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
1416 $submittedValues['price_' . $fieldID] = 1;
1417 }
1418
1419 // Every contribution has a price-set - the only reason it shouldn't be set is if we are dealing with
1420 // quick config (very very arguably) & yet we see that this could still be quick config so this should be understood
1421 // as a point of fragility rather than a logical 'if' clause.
1422 if ($priceSetId) {
1423 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
1424 $submittedValues, $lineItem[$priceSetId]);
1425 // Unset tax amount for offline 'is_quick_config' contribution.
1426 // @todo WHY - quick config was conceived as a quick way to configure contribution forms.
1427 // this is an example of 'other' functionality being hung off it.
1428 if ($this->_priceSet['is_quick_config'] &&
1429 !array_key_exists($submittedValues['financial_type_id'], CRM_Core_PseudoConstant::getTaxRates())
1430 ) {
1431 unset($submittedValues['tax_amount']);
1432 }
1433 $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
1434 }
1435 if ($this->_id) {
1436 if ($this->_compId) {
1437 if ($this->_context == 'participant') {
1438 $pId = $this->_compId;
1439 }
1440 elseif ($this->_context == 'membership') {
1441 $isRelatedId = TRUE;
1442 }
1443 else {
1444 $pId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
1445 }
1446 }
1447 else {
1448 $contributionDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1449 if (array_key_exists('membership', $contributionDetails)) {
1450 $isRelatedId = TRUE;
1451 }
1452 elseif (array_key_exists('participant', $contributionDetails)) {
1453 $pId = $contributionDetails['participant'];
1454 }
1455 }
1456 }
1457
1458 if (!$priceSetId && !empty($submittedValues['total_amount']) && $this->_id) {
1459 // CRM-10117 update the line items for participants.
1460 // @todo - if we are completing a contribution then the api call
1461 // civicrm_api3('Contribution', 'completetransaction') should take care of
1462 // all associated updates rather than replicating them on the form layer.
1463 if ($pId) {
1464 $entityTable = 'participant';
1465 $entityID = $pId;
1466 $isRelatedId = FALSE;
1467 $participantParams = array(
1468 'fee_amount' => $submittedValues['total_amount'],
1469 'id' => $entityID,
1470 );
1471 CRM_Event_BAO_Participant::add($participantParams);
1472 if (empty($this->_lineItems)) {
1473 $this->_lineItems[] = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
1474 }
1475 }
1476 else {
1477 $entityTable = 'contribution';
1478 $entityID = $this->_id;
1479 }
1480
1481 $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable, NULL, TRUE, $isRelatedId);
1482 foreach (array_keys($lineItems) as $id) {
1483 $lineItems[$id]['id'] = $id;
1484 }
1485 $itemId = key($lineItems);
1486 if ($itemId && !empty($lineItems[$itemId]['price_field_id'])) {
1487 $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1488 }
1489
1490 // @todo see above - new functionality has been inappropriately added to the quick config concept
1491 // and new functionality has been added onto the form layer rather than the BAO :-(
1492 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1493 //CRM-16833: Ensure tax is applied only once for membership conribution, when status changed.(e.g Pending to Completed).
1494 $componentDetails = CRM_Contribute_BAO_Contribution::getComponentDetails($this->_id);
1495 if (!CRM_Utils_Array::value('membership', $componentDetails) || !CRM_Utils_Array::value('participant', $componentDetails)) {
1496 if (!($this->_action & CRM_Core_Action::UPDATE && (($this->_defaults['contribution_status_id'] != $submittedValues['contribution_status_id'])))) {
1497 $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
1498 }
1499 }
1500
1501 // Update line total and total amount with tax on edit.
1502 $financialItemsId = CRM_Core_PseudoConstant::getTaxRates();
1503 if (array_key_exists($submittedValues['financial_type_id'], $financialItemsId)) {
1504 $lineItems[$itemId]['tax_rate'] = $financialItemsId[$submittedValues['financial_type_id']];
1505 }
1506 else {
1507 $lineItems[$itemId]['tax_rate'] = $lineItems[$itemId]['tax_amount'] = "";
1508 $submittedValues['tax_amount'] = 'null';
1509 }
1510 if ($lineItems[$itemId]['tax_rate']) {
1511 $lineItems[$itemId]['tax_amount'] = ($lineItems[$itemId]['tax_rate'] / 100) * $lineItems[$itemId]['line_total'];
1512 $submittedValues['total_amount'] = $lineItems[$itemId]['line_total'] + $lineItems[$itemId]['tax_amount'];
1513 $submittedValues['tax_amount'] = $lineItems[$itemId]['tax_amount'];
1514 }
1515 }
1516 // CRM-10117 update the line items for participants.
1517 if (!empty($lineItems[$itemId]['price_field_id'])) {
1518 $lineItem[$this->_priceSetId] = $lineItems;
1519 }
1520 }
1521
1522 $isQuickConfig = 0;
1523 if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
1524 $isQuickConfig = 1;
1525 }
1526 //CRM-11529 for quick config back office transactions
1527 //when financial_type_id is passed in form, update the
1528 //line items with the financial type selected in form
1529 // NOTE that this IS still a legitimate use of 'quick-config' for contributions under the current DB but
1530 // we should look at having a price field per contribution type & then there would be little reason
1531 // for the back-office contribution form postProcess to know if it is a quick-config form.
1532 if ($isQuickConfig && !empty($submittedValues['financial_type_id']) && CRM_Utils_Array::value($this->_priceSetId, $lineItem)
1533 ) {
1534 foreach ($lineItem[$this->_priceSetId] as &$values) {
1535 $values['financial_type_id'] = $submittedValues['financial_type_id'];
1536 }
1537 }
1538
1539 if (!isset($submittedValues['total_amount'])) {
1540 $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
1541 }
1542 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
1543
1544 $isEmpty = array_keys(array_flip($submittedValues['soft_credit_contact_id']));
1545 if ($this->_id && count($isEmpty) == 1 && key($isEmpty) == NULL) {
1546 //Delete existing soft credit records if soft credit list is empty on update
1547 CRM_Contribute_BAO_ContributionSoft::del(array('contribution_id' => $this->_id, 'pcp_id' => 0));
1548 }
1549
1550 // set the contact, when contact is selected
1551 if (!empty($submittedValues['contact_id'])) {
1552 $this->_contactID = $submittedValues['contact_id'];
1553 }
1554
1555 $formValues = $submittedValues;
1556
1557 // Credit Card Contribution.
1558 if ($this->_mode) {
1559 $paramsSetByPaymentProcessingSubsystem = array(
1560 'trxn_id',
1561 'payment_instrument_id',
1562 'contribution_status_id',
1563 'cancel_date',
1564 'cancel_reason',
1565 );
1566 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1567 if (isset($formValues[$key])) {
1568 unset($formValues[$key]);
1569 }
1570 }
1571 $contribution = $this->processCreditCard($formValues, $lineItem, $this->_contactID);
1572 foreach ($paramsSetByPaymentProcessingSubsystem as $key) {
1573 $formValues[$key] = $contribution->$key;
1574 }
1575 }
1576 else {
1577 // Offline Contribution.
1578 $submittedValues = $this->unsetCreditCardFields($submittedValues);
1579
1580 // get the required field value only.
1581
1582 $params = $ids = array();
1583
1584 $params['contact_id'] = $this->_contactID;
1585 $params['currency'] = $this->getCurrency($submittedValues);
1586
1587 //format soft-credit/pcp param first
1588 CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($submittedValues, $this);
1589 $params = array_merge($params, $submittedValues);
1590
1591 $fields = array(
1592 'financial_type_id',
1593 'contribution_status_id',
1594 'payment_instrument_id',
1595 'cancel_reason',
1596 'source',
1597 'check_number',
1598 );
1599 foreach ($fields as $f) {
1600 $params[$f] = CRM_Utils_Array::value($f, $formValues);
1601 }
1602
1603 // CRM-5740 if priceset is used, no need to cleanup money.
1604 if ($priceSetId) {
1605 $params['skipCleanMoney'] = 1;
1606 }
1607
1608 $dates = array(
1609 'receive_date',
1610 'receipt_date',
1611 'cancel_date',
1612 );
1613
1614 foreach ($dates as $d) {
1615 $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
1616 }
1617
1618 if (!empty($formValues['is_email_receipt'])) {
1619 $params['receipt_date'] = date("Y-m-d");
1620 }
1621
1622 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name')
1623 || $params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name')
1624 ) {
1625 if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
1626 $params['cancel_date'] = date('Y-m-d');
1627 }
1628 }
1629 else {
1630 $params['cancel_date'] = $params['cancel_reason'] = 'null';
1631 }
1632
1633 // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
1634 // else if contribution_status is changed to Completed is_pay_later flag is changed to 0, CRM-15041
1635 if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
1636 $params['is_pay_later'] = 1;
1637 }
1638 elseif ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
1639 $params['is_pay_later'] = 0;
1640 }
1641
1642 $ids['contribution'] = $params['id'] = $this->_id;
1643
1644 // Add Additional common information to formatted params.
1645 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params, $this);
1646 if ($pId) {
1647 $params['contribution_mode'] = 'participant';
1648 $params['participant_id'] = $pId;
1649 $params['skipLineItem'] = 1;
1650 }
1651 elseif ($isRelatedId) {
1652 $params['contribution_mode'] = 'membership';
1653 }
1654 $params['line_item'] = $lineItem;
1655 $params['payment_processor_id'] = $params['payment_processor'] = CRM_Utils_Array::value('id', $this->_paymentProcessor);
1656 if (isset($submittedValues['tax_amount'])) {
1657 $params['tax_amount'] = $submittedValues['tax_amount'];
1658 }
1659 //create contribution.
1660 if ($isQuickConfig) {
1661 $params['is_quick_config'] = 1;
1662 }
1663 $params['non_deductible_amount'] = $this->calculateNonDeductibleAmount($params, $formValues);
1664
1665 // we are already handling note below, so to avoid duplicate notes against $contribution
1666 if (!empty($params['note']) && !empty($submittedValues['note'])) {
1667 unset($params['note']);
1668 }
1669 $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
1670
1671 // process associated membership / participant, CRM-4395
1672 if ($contribution->id && $action & CRM_Core_Action::UPDATE) {
1673 $this->statusMessage[] = $this->updateRelatedComponent($contribution->id,
1674 $contribution->contribution_status_id,
1675 CRM_Utils_Array::value('contribution_status_id',
1676 $this->_values
1677 ),
1678 $contribution->receive_date
1679 );
1680 }
1681
1682 array_unshift($this->statusMessage, ts('The contribution record has been saved.'));
1683
1684 $this->invoicingPostProcessHook($submittedValues, $action, $lineItem);
1685
1686 //send receipt mail.
1687 if ($contribution->id && !empty($formValues['is_email_receipt'])) {
1688 $formValues['contact_id'] = $this->_contactID;
1689 $formValues['contribution_id'] = $contribution->id;
1690
1691 $formValues += CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id);
1692
1693 // to get 'from email id' for send receipt
1694 $this->fromEmailId = $formValues['from_email_address'];
1695 if (CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues)) {
1696 $this->statusMessage[] = ts('A receipt has been emailed to the contributor.');
1697 }
1698 }
1699
1700 $this->statusMessageTitle = ts('Saved');
1701
1702 }
1703
1704 if ($contribution->id && isset($formValues['product_name'][0])) {
1705 CRM_Contribute_Form_AdditionalInfo::processPremium($submittedValues, $contribution->id,
1706 $this->_premiumID, $this->_options
1707 );
1708 }
1709
1710 if ($contribution->id && !empty($submittedValues['note'])) {
1711 CRM_Contribute_Form_AdditionalInfo::processNote($submittedValues, $this->_contactID, $contribution->id, $this->_noteID);
1712 }
1713
1714 CRM_Core_Session::setStatus(implode(' ', $this->statusMessage), $this->statusMessageTitle, 'success');
1715
1716 CRM_Contribute_BAO_Contribution::updateRelatedPledge(
1717 $action,
1718 $pledgePaymentID,
1719 $contribution->id,
1720 (CRM_Utils_Array::value('option_type', $formValues) == 2) ? TRUE : FALSE,
1721 $formValues['total_amount'],
1722 CRM_Utils_Array::value('total_amount', $this->_defaults),
1723 $formValues['contribution_status_id'],
1724 CRM_Utils_Array::value('contribution_status_id', $this->_defaults)
1725 );
1726 return $contribution;
1727 }
1728
1729 /**
1730 * Assign tax calculations to contribution receipts.
1731 *
1732 * @param array $submittedValues
1733 * @param int $action
1734 * @param array $lineItem
1735 */
1736 protected function invoicingPostProcessHook($submittedValues, $action, $lineItem) {
1737
1738 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
1739 if (!CRM_Utils_Array::value('invoicing', $invoiceSettings)) {
1740 return;
1741 }
1742 $taxRate = array();
1743 $getTaxDetails = FALSE;
1744 if ($action & CRM_Core_Action::ADD) {
1745 $line = $lineItem;
1746 }
1747 elseif ($action & CRM_Core_Action::UPDATE) {
1748 $line = $this->_lineItems;
1749 }
1750 foreach ($line as $key => $value) {
1751 foreach ($value as $v) {
1752 if (isset($taxRate[(string) CRM_Utils_Array::value('tax_rate', $v)])) {
1753 $taxRate[(string) $v['tax_rate']] = $taxRate[(string) $v['tax_rate']] + CRM_Utils_Array::value('tax_amount', $v);
1754 }
1755 else {
1756 if (isset($v['tax_rate'])) {
1757 $taxRate[(string) $v['tax_rate']] = CRM_Utils_Array::value('tax_amount', $v);
1758 $getTaxDetails = TRUE;
1759 }
1760 }
1761 }
1762 }
1763
1764 if ($action & CRM_Core_Action::UPDATE) {
1765 if (isset($submittedValues['tax_amount'])) {
1766 $totalTaxAmount = $submittedValues['tax_amount'];
1767 }
1768 else {
1769 $totalTaxAmount = $this->_values['tax_amount'];
1770 }
1771 $this->assign('totalTaxAmount', $totalTaxAmount);
1772 $this->assign('dataArray', $taxRate);
1773 }
1774 else {
1775 if (!empty($submittedValues['price_set_id'])) {
1776 $this->assign('totalTaxAmount', $submittedValues['tax_amount']);
1777 $this->assign('getTaxDetails', $getTaxDetails);
1778 $this->assign('dataArray', $taxRate);
1779 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
1780 }
1781 else {
1782 $this->assign('totalTaxAmount', CRM_Utils_Array::value('tax_amount', $submittedValues));
1783 }
1784 }
1785 }
1786
1787 /**
1788 * Calculate non deductible amount.
1789 *
1790 * CRM-11956
1791 * if non_deductible_amount exists i.e. Additional Details field set was opened [and staff typed something] -
1792 * if non_deductible_amount does NOT exist - then calculate it depending on:
1793 * $financialType->is_deductible and whether there is a product (premium).
1794 *
1795 * @param $params
1796 * @param $formValues
1797 *
1798 * @return array
1799 */
1800 protected function calculateNonDeductibleAmount($params, $formValues) {
1801 if (!empty($params['non_deductible_amount'])) {
1802 return $params['non_deductible_amount'];
1803 }
1804
1805 $financialType = new CRM_Financial_DAO_FinancialType();
1806 $financialType->id = $params['financial_type_id'];
1807 $financialType->find(TRUE);
1808
1809 if ($financialType->is_deductible) {
1810
1811 if (isset($formValues['product_name'][0])) {
1812 $selectProduct = $formValues['product_name'][0];
1813 }
1814 // if there is a product - compare the value to the contribution amount
1815 if (isset($selectProduct)) {
1816 $productDAO = new CRM_Contribute_DAO_Product();
1817 $productDAO->id = $selectProduct;
1818 $productDAO->find(TRUE);
1819 // product value exceeds contribution amount
1820 if ($params['total_amount'] < $productDAO->price) {
1821 return $params['total_amount'];
1822 }
1823 // product value does NOT exceed contribution amount
1824 else {
1825 return $productDAO->price;
1826 }
1827 }
1828 // contribution is deductible - but there is no product
1829 else {
1830 return '0.00';
1831 }
1832 }
1833 // contribution is NOT deductible
1834 else {
1835 return $params['total_amount'];
1836 }
1837
1838 return 0;
1839 }
1840
1841 }