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