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