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