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