@inheritdoc

WooCommerce has general fee lines, so we have to override this method to
add these general fees (type unknown to us)
504203
protected function getFeeLines()
    {
        $result = parent::getFeeLines();

        // So far, all amounts found on refunds are negative, so we probably
        // don't need to correct the sign on these lines either: but this has
        // not been tested yet!.
        foreach ($this->invoiceSource->getSource()->get_fees() as $feeLine) {
            $line = $this->getFeeLine($feeLine);
            $line = $this->addLineType($line, static::LineType_Other);
            $result[] = $line;
        }
        return $result;
    }
1366964
public function addOnAmount()
    {
        $totalAddOn = 0;

        foreach ($this->transaction->addOns as $addOn) {
            $totalAddOn += $addOn->amount * ($addOn->quantity ?? 1);
        }

        return (float) $totalAddOn;
    }
1069274
public function add(Price $addend)
    {
        if (!$this->hasSameCurrency($addend)) {
            throw new InvalidCurrencyException($this->currency(), $addend->currency());
        }

        if ($this->precision !== $addend->precision) {
            throw new DifferentPricePrecisionException();
        }

        return new self($this->amount + $addend->amount, $this->currency(), $this->precision);
    }
998615
public function updateOrderPayment($order, $transaction = null, $reference = null, $hookType = null)
    {
        // Fetch transaction info if transaction is not passed as a parameter
        if ($reference && !$transaction) {
            $transaction = $this->fetchTransactionInfo($reference);
        } else {
            $reference = $transaction->reference;
        }

        /** @var OrderPaymentInterface $payment */
        $payment = $order->getPayment();

        $this->checkPaymentMethod($payment);

        // Check for total amount mismatch between magento and bolt order.
        $this->holdOnTotalsMismatch($order, $transaction);

        // Get the last stored transaction parameters
        $prevTransactionState = $payment->getAdditionalInformation('transaction_state');
        $prevTransactionReference = $payment->getAdditionalInformation('transaction_reference');

        // Get the transaction state
        $transactionState = $this->getTransactionState($transaction, $payment, $hookType);

        $newCapture = in_array($transactionState, [self::TS_CAPTURED, self::TS_COMPLETED])
            ? $this->getUnprocessedCapture($payment, $transaction)
            : null;

        // Skip if there is no state change (i.e. fetch transaction call from admin panel / Payment model)
        // Reference check and $newCapture were added to support multiple refunds and captures,
        // valid same state transitions
        if (
            $transactionState == $prevTransactionState &&
            $reference == $prevTransactionReference &&
            !$newCapture
        ) {
            if ($this->isAnAllowedUpdateFromAdminPanel($order, $transactionState)){
                $payment->setIsTransactionApproved(true);
            }
            return;
        }

        if (!$this->validateTransition($prevTransactionState, $transactionState)) {
            throw new LocalizedException(__(
                'Invalid transaction state transition: %1 -> %2',
                $prevTransactionState,
                $transactionState
            ));
        }

        // preset default payment / transaction values
        // before more specific changes below
        if ($newCapture) {
            $amount = $newCapture->amount->amount;
        } else {
            $amount = $transaction->amount->amount;
        }
        $transactionId = $transaction->id;

        $realTransactionId = $parentTransactionId = $payment->getAdditionalInformation('real_transaction_id');
        $realTransactionId = $realTransactionId ?: $transaction->id;
        $paymentAuthorized = (bool)$payment->getAdditionalInformation('authorized');

        $processedCaptures = $this->getProcessedCaptures($payment);
        $processedRefunds = $this->getProcessedRefunds($payment);

        switch ($transactionState) {

            case self::TS_ZERO_AMOUNT:
                $orderState = OrderModel::STATE_PROCESSING;
                $transactionType = Transaction::TYPE_ORDER;
                break;

            case self::TS_PENDING:
                $orderState = OrderModel::STATE_PAYMENT_REVIEW;
                $transactionType = Transaction::TYPE_ORDER;
                break;

            case self::TS_AUTHORIZED:
                $orderState = OrderModel::STATE_PROCESSING;
                $transactionType = Transaction::TYPE_AUTH;
                $transactionId = $transaction->id.'-auth';
                break;

            case self::TS_CAPTURED:
                if (!$newCapture) return;
                $orderState = OrderModel::STATE_PROCESSING;
                $transactionType = Transaction::TYPE_CAPTURE;
                $transactionId = $transaction->id.'-capture-'.$newCapture->id;
                $parentTransactionId = $transaction->id.'-auth';
                break;

            case self::TS_PARTIAL_VOIDED:
                $authorizationTransaction = $payment->getAuthorizationTransaction();
                $authorizationTransaction->closeAuthorization();
                $order->addCommentToStatusHistory($this->getVoidMessage($payment));
                $order->save();
                return;

            case self::TS_COMPLETED:
                if (!$newCapture) return;
                $orderState = OrderModel::STATE_PROCESSING;
                $transactionType = Transaction::TYPE_CAPTURE;
                if ($paymentAuthorized) {
                    $transactionId = $transaction->id.'-capture-'.$newCapture->id;
                    $parentTransactionId = $transaction->id.'-auth';
                } else {
                    $transactionId = $transaction->id.'-payment';
                }
                break;

            case self::TS_CANCELED:
                $orderState = OrderModel::STATE_CANCELED;
                $transactionType = Transaction::TYPE_VOID;
                $transactionId = $transaction->id.'-void';
                $parentTransactionId = $paymentAuthorized ? $transaction->id.'-auth' : $transaction->id;
                break;

            case self::TS_REJECTED_REVERSIBLE:
                $orderState = OrderModel::STATE_HOLDED;
                $transactionType = Transaction::TYPE_ORDER;
                $transactionId = $transaction->id.'-rejected_reversible';
                break;

            case self::TS_REJECTED_IRREVERSIBLE:
                $orderState = OrderModel::STATE_CANCELED;
                $transactionType = Transaction::TYPE_ORDER;
                $transactionId = $transaction->id.'-rejected_irreversible';
                break;

            case self::TS_CREDIT_COMPLETED:
                if (in_array($transaction->id, $processedRefunds)) return;
                $transactionType = Transaction::TYPE_REFUND;
                $transactionId = $transaction->id.'-refund';
                if (Hook::$fromBolt) {
                    // Refunds need to be initiated from the store admin (Invoice -> Credit Memo)
                    // If called from Bolt merchant dashboard there is no enough info to sync the totals
                    $orderState = OrderModel::STATE_HOLDED;
                } else {
                    $orderState = OrderModel::STATE_PROCESSING;
                }
                break;

            default:
                throw new LocalizedException(__(
                    'Unhandled transaction state : %1',
                    $transactionState
                ));
                break;
        }

        // set order state and status
        $this->setOrderState($order, $orderState);

        // format the last transaction data for storing within the order payment record instance

        if ($newCapture) {
            array_push($processedCaptures, $newCapture->id);
        }

        if ($transactionState == self::TS_CREDIT_COMPLETED) {
            array_push($processedRefunds, $transaction->id);
        }

        $paymentData = [
            'real_transaction_id' => $realTransactionId,
            'transaction_reference' => $transaction->reference,
            'transaction_state' => $transactionState,
            'authorized' => $paymentAuthorized || in_array($transactionState, [self::TS_AUTHORIZED, self::TS_CAPTURED]),
            'captures' => implode(',', $processedCaptures),
            'refunds' => implode(',', $processedRefunds)
        ];

        // format the price with currency symbol
        $formattedPrice = $order->getBaseCurrency()->formatTxt($amount / 100);

        $message = __(
            'BOLTPAY INFO :: PAYMENT Status: %1 Amount: %2<br>Bolt transaction: %3',
            $this->getBoltTransactionStatus($transactionState),
            $formattedPrice,
            $this->formatReferenceUrl($transaction->reference)
        );

        $transactionData = $this->formatTransactionData($order, $transaction, $amount);

        // update order payment instance
        $payment->setParentTransactionId($parentTransactionId);
        $payment->setTransactionId($transactionId);
        $payment->setLastTransId($transactionId);
        $payment->setAdditionalInformation($paymentData);
        $payment->setIsTransactionClosed($transactionType != Transaction::TYPE_AUTH);

        // We will create an invoice if we have zero amount or new capture.
        if ($this->isCaptureHookRequest($newCapture) || $this->isZeroAmountHook($transactionState)) {
            $this->validateCaptureAmount($order, $amount / 100);
            $invoice = $this->createOrderInvoice($order, $realTransactionId, $amount / 100);
        }

        if (!$order->getTotalDue()) {
            $payment->setShouldCloseParentTransaction(true);
        }

        if ($newCapture && @$invoice) {
            $this->_eventManager->dispatch(
                'sales_order_payment_capture',
                ['payment' => $payment, 'invoice' => $invoice]
            );
        }

        // build a new transaction record and assign it to the order and payment
        /** @var Transaction $payment_transaction */
        $payment_transaction = $this->transactionBuilder->setPayment($payment)
            ->setOrder($order)
            ->setTransactionId($transactionId)
            ->setAdditionalInformation([
                Transaction::RAW_DETAILS => $transactionData
            ])
            ->setFailSafe(true)
            ->build($transactionType);

        $payment->addTransactionCommentsToOrder(
            $payment_transaction,
            $message
        );

        $payment_transaction->save();

        // save payment and order
        $payment->save();
        $order->save();
    }
588747
protected function wizardAddCart()
    {
        // Required
        $this->validatePrompt('user_id', $this->text('User ID'), 'cart');
        $this->validatePrompt('product_id', $this->text('Product ID'), 'cart');
        $this->validatePrompt('sku', $this->text('Product SKU'), 'cart');
        $this->validatePrompt('store_id', $this->text('Store ID'), 'cart');

        // Optional
        $this->validatePrompt('quantity', $this->text('Quantity'), 'cart', 1);
        $this->validatePrompt('order_id', $this->text('Order ID'), 'cart', 0);
        $this->validatePrompt('data', $this->text('Data'), 'cart');

        $this->setSubmittedJson('data');
        $this->validateComponent('cart');
        $this->addAddCart();
    }
1233853
public function filters() {

		global $wpdb;

		if ( self::get_current_post_type() !== $this->cpt->post_type ) {
			return;
		}

		$pto = get_post_type_object( $this->cpt->post_type );

		foreach ( $this->args['admin_filters'] as $filter_key => $filter ) {

			if ( isset( $filter['cap'] ) && ! current_user_can( $filter['cap'] ) ) {
				continue;
			}

			if ( isset( $filter['taxonomy'] ) ) {

				$tax = get_taxonomy( $filter['taxonomy'] );

				if ( empty( $tax ) ) {
					continue;
				}

				require_once __DIR__ . '/class-walker-extendedtaxonomydropdown.php';

				$walker = new Walker_ExtendedTaxonomyDropdown( [
					'field' => 'slug',
				] );

				# If we haven't specified a title, use the all_items label from the taxonomy:
				if ( ! isset( $filter['title'] ) ) {
					$filter['title'] = $tax->labels->all_items;
				}

				# Output the dropdown:
				wp_dropdown_categories( [
					'show_option_all' => $filter['title'],
					'hide_empty'      => false,
					'hide_if_empty'   => true,
					'hierarchical'    => true,
					'show_count'      => false,
					'orderby'         => 'name',
					'selected_cats'   => get_query_var( $tax->query_var ),
					'id'              => 'filter_' . $filter_key,
					'name'            => $tax->query_var,
					'taxonomy'        => $filter['taxonomy'],
					'walker'          => $walker,
				] );

			} elseif ( isset( $filter['meta_key'] ) ) {

				# If we haven't specified a title, generate one from the meta key:
				if ( ! isset( $filter['title'] ) ) {
					$filter['title'] = str_replace( [
						'-',
						'_',
					], ' ', $filter['meta_key'] );
					$filter['title'] = ucwords( $filter['title'] ) . 's';
					$filter['title'] = sprintf( 'All %s', $filter['title'] );
				}

				if ( ! isset( $filter['options'] ) ) {
					# Fetch all the values for our meta key:
					# @TODO AND m.meta_value != null ?
					// @codingStandardsIgnoreStart
					$filter['options'] = $wpdb->get_col( $wpdb->prepare( "
						SELECT DISTINCT meta_value
						FROM {$wpdb->postmeta} as m
						JOIN {$wpdb->posts} as p ON ( p.ID = m.post_id )
						WHERE m.meta_key = %s
						AND m.meta_value != ''
						AND p.post_type = %s
						ORDER BY m.meta_value ASC
					", $filter['meta_key'], $this->cpt->post_type ) );
					// @codingStandardsIgnoreEnd
				} elseif ( is_callable( $filter['options'] ) ) {
					$filter['options'] = call_user_func( $filter['options'] );
				}

				if ( empty( $filter['options'] ) ) {
					continue;
				}

				$selected = wp_unslash( get_query_var( $filter_key ) );

				$use_key = false;

				foreach ( $filter['options'] as $k => $v ) {
					if ( ! is_numeric( $k ) ) {
						$use_key = true;
						break;
					}
				}

				# Output the dropdown:
				?>
				<select name="<?php echo esc_attr( $filter_key ); ?>" id="filter_<?php echo esc_attr( $filter_key ); ?>">
					<option value=""><?php echo esc_html( $filter['title'] ); ?></option>
					<?php
					foreach ( $filter['options'] as $k => $v ) {
						$key = ( $use_key ? $k : $v );
						?>
						<option value="<?php echo esc_attr( $key ); ?>" <?php selected( $selected, $key ); ?>><?php echo esc_html( $v ); ?></option>
					<?php } ?>
				</select>
				<?php

			} elseif ( isset( $filter['meta_search_key'] ) ) {

				# If we haven't specified a title, generate one from the meta key:
				if ( ! isset( $filter['title'] ) ) {
					$filter['title'] = str_replace( [
						'-',
						'_',
					], ' ', $filter['meta_search_key'] );
					$filter['title'] = ucwords( $filter['title'] );
				}

				$value = wp_unslash( get_query_var( $filter_key ) );

				# Output the search box:
				?>
				<label><?php printf( '%s:', esc_html( $filter['title'] ) ); ?>&nbsp;<input type="text" name="<?php echo esc_attr( $filter_key ); ?>" id="filter_<?php echo esc_attr( $filter_key ); ?>" value="<?php echo esc_attr( $value ); ?>" /></label>
				<?php

			} elseif ( isset( $filter['meta_exists'] ) ) {

				# If we haven't specified a title, use the all_items label from the post type:
				if ( ! isset( $filter['title'] ) ) {
					$filter['title'] = $pto->labels->all_items;
				}

				$selected = wp_unslash( get_query_var( $filter_key ) );

				if ( 1 === count( $filter['meta_exists'] ) ) {

					# Output a checkbox:
					foreach ( $filter['meta_exists'] as $v => $t ) {
						?>
						<label><input type="checkbox" name="<?php echo esc_attr( $filter_key ); ?>" id="filter_<?php echo esc_attr( $filter_key ); ?>" value="<?php echo esc_attr( $v ); ?>" <?php checked( $selected, $v ); ?>>&nbsp;<?php echo esc_html( $t ); ?></label>
						<?php
					}
				} else {

					# Output a dropdown:
					?>
					<select name="<?php echo esc_attr( $filter_key ); ?>" id="filter_<?php echo esc_attr( $filter_key ); ?>">
						<option value=""><?php echo esc_html( $filter['title'] ); ?></option>
						<?php foreach ( $filter['meta_exists'] as $v => $t ) { ?>
							<option value="<?php echo esc_attr( $v ); ?>" <?php selected( $selected, $v ); ?>><?php echo esc_html( $t ); ?></option>
						<?php } ?>
					</select>
					<?php

				}
			}
		}

	}
38247
public function addType($type)
    {
        if (is_string($type)) {
            $type = array($type);
        }

        foreach($type as $typ) {
            if (defined('self::' . strtoupper($typ)) && !in_array($typ, $this->_type)) {
                $this->_type[] = $typ;
            }

            if (($typ == self::ALL)) {
                $this->_type = array_keys($this->_cardLength);
            }
        }

        return $this;
    }
16363
def outlay(self, q):
        
        fee = self.commission(q, self._price * self.multiplier)
        outlay = q * self._price * self.multiplier
        return outlay + fee, outlay, fee
779018
private function doProcessType()
	{
		$type = new Type($this->payment->type, $this->payment->toArray());

		switch ($type->sid()) {

			case Type::CITY:

				break;

			case Type::FEE:

				break;

			case Type::CHECK:

				// todo check 'check' request

				// register check request
				$this->payment->status = Status::ENABLED;

				break;

			case Type::PAY:


				// pay after 'check' request
				$payment = self::findCheck(
					$this->payment->term,
					$this->payment->city,
					$this->payment->amount,
					$this->payment->to,
					Status::ENABLED
				);

				if (!$payment) {
					throw new ProcessorException(ProcessorException::RC_CHECK_NOT_FOUND);
				}

				// close 'check' request
				$payment->status = Status::PAY;
				$payment->saveByType();

				// processed 'payment' request
				$this->payment->status = Status::PROCESSED;
				$this->payment->code = uniqid();

				break;

			case Type::CANCEL:

				// find pay in status 'processed'
				$payment = self::findPayTo(
					$this->payment->term,
					$this->payment->code,
					$this->payment->to,
					Status::PROCESSED
				);

				if ($payment) {

					// cancel 'pay' request
					$payment->status = Status::CANCELED;
					$payment->saveByType();

					// save cancel request in 'processed'
					$this->payment->status = Status::PROCESSED;
					$this->payment->amount = $payment->amount;
					$this->payment->name = $payment->name;
					$this->payment->to = $payment->to;

				} else {
					throw new ProcessorException(ProcessorException::RC_PAY_NOT_FOUND);
				}

				break;

			case Type::STATUS:

				// status for pay
				$payment = self::findPayTo(
					$this->payment->term,
					$this->payment->code,
					$this->payment->to
				);

				// init data from 'pay' request into current 'status' request
				if ($payment) {
					$this->payment->id = $payment->id;
					$this->payment->status = $payment->status;
					$this->payment->amount = $payment->amount;
					$this->payment->to = $payment->to;
					$this->payment->name = $payment->name;
				} else {
					throw new ProcessorException(ProcessorException::RC_PAY_NOT_FOUND);
				}

				break;

		}

		return '00';

	}
359414
protected function addAddCart()
    {
        if (!$this->isError()) {
            $id = $this->cart->add($this->getSubmitted());
            if (empty($id)) {
                $this->errorAndExit($this->text('Unexpected result'));
            }
            $this->line($id);
        }
    }
721146
protected function _initTotals()
    {
        parent::_initTotals();

        if (((float)$this->getSource()->getPaymentFeeAmount()) != 0) {
            $this->addTotal(
                new Varien_Object(
                    array(
                        'code' => 'payment_fee',
                        'strong' => false,
                        'value' => $this->getSource()->getPaymentFeeAmount(),
                        'base_value' => $this->getSource()->getBasePaymentFeeAmount(),
                        'label' => $this->helper('adyen')->__('Payment Fee'),
                        'area' => '',
                    )
                ),
                'subtotal'
            );
        }

        if (((float)$this->getSource()->getPaymentPercentageFee()) != 0) {
            $this->addTotal(
                new Varien_Object(
                    array(
                        'code' => 'payment_percentage_fee',
                        'strong' => false,
                        'value' => $this->getSource()->getPaymentPercentageFee(),
                        'base_value' => $this->getSource()->getBasePaymentPercentageFee(),
                        'label' => $this->helper('adyen')->__('Payment Percentage Fee'),
                        'area' => '',
                    )
                ),
                'subtotal'
            );
        }

        if (((float)$this->getSource()->getPaymentInstallmentFeeAmount()) != 0) {
            $this->addTotal(
                new Varien_Object(
                    array(
                        'code' => 'payment_installment_fee',
                        'strong' => false,
                        'value' => $this->getSource()->getPaymentInstallmentFeeAmount(),
                        'base_value' => $this->getSource()->getBasePaymentInstallmentFeeAmount(),
                        'label' => $this->helper('adyen')->__('Payment Fee Installments'),
                        'area' => '',
                    )
                ),
                'subtotal'
            );
        }

        return $this;
    }
707110
function addScalar($val, $type='string')
		{
			$typeof=@$GLOBALS['xmlrpcTypes'][$type];
			if($typeof!=1)
			{
				error_log("XML-RPC: ".__METHOD__.": not a scalar type ($type)");
				return 0;
			}

			// coerce booleans into correct values
			// NB: we should either do it for datetimes, integers and doubles, too,
			// or just plain remove this check, implemented on booleans only...
			if($type==$GLOBALS['xmlrpcBoolean'])
			{
				if(strcasecmp($val,'true')==0 || $val==1 || ($val==true && strcasecmp($val,'false')))
				{
					$val=true;
				}
				else
				{
					$val=false;
				}
			}

			switch($this->mytype)
			{
				case 1:
					error_log('XML-RPC: '.__METHOD__.': scalar xmlrpcval can have only one value');
					return 0;
				case 3:
					error_log('XML-RPC: '.__METHOD__.': cannot add anonymous scalar to struct xmlrpcval');
					return 0;
				case 2:
					// we're adding a scalar value to an array here
					//$ar=$this->me['array'];
					//$ar[]=new xmlrpcval($val, $type);
					//$this->me['array']=$ar;
					// Faster (?) avoid all the costly array-copy-by-val done here...
					$this->me['array'][]=new xmlrpcval($val, $type);
					return 1;
				default:
					// a scalar, so set the value and remember we're scalar
					$this->me[$type]=$val;
					$this->mytype=$typeof;
					return 1;
			}
		}
542550
public function getAddonPrices()
    {
        $addonPrices = [];
        if ($this->addonPrices) {
            foreach ($this->addonPrices as $addonPrice) {
                $addonPrices[] = new AddonPrice($addonPrice, $this->locale, $this->priceFormatter);
            }
        }

        return $addonPrices;
    }
209924
function paypalwpp() {
    include_once(zen_get_file_directory(DIR_FS_CATALOG . DIR_WS_LANGUAGES . $_SESSION['language'] . '/modules/payment/', 'paypalwpp.php', 'false'));
    global $order;
    $this->code = 'paypalwpp';
    $this->codeTitle = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_EC;
    $this->codeVersion = '1.5.1';
    $this->enableDirectPayment = FALSE;
    $this->enabled = (MODULE_PAYMENT_PAYPALWPP_STATUS == 'True');
    // Set the title & description text based on the mode we're in ... EC vs US/UK vs admin
    if (IS_ADMIN_FLAG === true) {
      $this->description = sprintf(MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_DESCRIPTION, ' (rev' . $this->codeVersion . ')');
      switch (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE) {
        case ('PayPal'):
          $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_EC;
        break;
        case ('Payflow-UK'):
          $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_PRO20;
        break;
        case ('Payflow-US'):
          if (defined('MODULE_PAYMENT_PAYPALWPP_PAYFLOW_EC') && MODULE_PAYMENT_PAYPALWPP_PAYFLOW_EC == 'Yes') {
            $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_PF_EC;
          } else {
            $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_PF_GATEWAY;
          }
        break;
        default:
          $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_EC;
      }
      if ($this->enabled) {
        if ( (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE == 'PayPal' && (MODULE_PAYMENT_PAYPALWPP_APISIGNATURE == '' || MODULE_PAYMENT_PAYPALWPP_APIUSERNAME == '' || MODULE_PAYMENT_PAYPALWPP_APIPASSWORD == ''))
          || (substr(MODULE_PAYMENT_PAYPALWPP_MODULE_MODE,0,7) == 'Payflow' && (MODULE_PAYMENT_PAYPALWPP_PFPARTNER == '' || MODULE_PAYMENT_PAYPALWPP_PFVENDOR == '' || MODULE_PAYMENT_PAYPALWPP_PFUSER == '' || MODULE_PAYMENT_PAYPALWPP_PFPASSWORD == ''))
          ) $this->title .= '<span class="alert"><strong> NOT CONFIGURED YET</strong></span>';
        if (MODULE_PAYMENT_PAYPALWPP_SERVER =='sandbox') $this->title .= '<strong><span class="alert"> (sandbox active)</span></strong>';
        if (MODULE_PAYMENT_PAYPALWPP_DEBUGGING =='Log File' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING =='Log and Email') $this->title .= '<strong> (Debug)</strong>';
        if (!function_exists('curl_init')) $this->title .= '<strong><span class="alert"> CURL NOT FOUND. Cannot Use.</span></strong>';
      }
    } else {
      $this->description = MODULE_PAYMENT_PAYPALWPP_TEXT_DESCRIPTION;
      $this->title = MODULE_PAYMENT_PAYPALWPP_EC_TEXT_TITLE; //pp
    }

    if ((!defined('PAYPAL_OVERRIDE_CURL_WARNING') || (defined('PAYPAL_OVERRIDE_CURL_WARNING') && PAYPAL_OVERRIDE_CURL_WARNING != 'True')) && !function_exists('curl_init')) $this->enabled = false;

    $this->enableDebugging = (MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Log File' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING =='Log and Email');
    $this->emailAlerts = (MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Log File' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING =='Log and Email' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Alerts Only');
    $this->doDPonly = (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE =='Payflow-US' && !(defined('MODULE_PAYMENT_PAYPALWPP_PAYFLOW_EC') && MODULE_PAYMENT_PAYPALWPP_PAYFLOW_EC == 'Yes'));
    $this->showPaymentPage = (MODULE_PAYMENT_PAYPALWPP_SKIP_PAYMENT_PAGE == 'No') ? true : false;
    $this->sort_order = MODULE_PAYMENT_PAYPALWPP_SORT_ORDER;

    $this->buttonSourceEC = 'ZenCart-EC_us';
    $this->buttonSourceDP = 'ZenCart-DP_us';
    if (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE == 'Payflow-UK') {
      $this->buttonSourceEC = 'ZenCart-EC_uk';
      $this->buttonSourceDP = 'ZenCart-DP_uk';
    }
    if (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE == 'Payflow-US') {
      $this->buttonSourceEC = 'ZenCart-ECGW_us';
      $this->buttonSourceDP = 'ZenCart-GW_us';
    }

    $this->order_pending_status = MODULE_PAYMENT_PAYPALWPP_ORDER_PENDING_STATUS_ID;
    if ((int)MODULE_PAYMENT_PAYPALWPP_ORDER_STATUS_ID > 0) {
      $this->order_status = MODULE_PAYMENT_PAYPALWPP_ORDER_STATUS_ID;
    }
    $this->new_acct_notify = MODULE_PAYMENT_PAYPALWPP_NEW_ACCT_NOTIFY;
    $this->zone = (int)MODULE_PAYMENT_PAYPALWPP_ZONE;
    if (is_object($order)) $this->update_status();

    if (PROJECT_VERSION_MAJOR != '1' && substr(PROJECT_VERSION_MINOR, 0, 3) != '5.0') $this->enabled = false;

    $this->cards = array();
    // if operating in markflow mode, start EC process when submitting order
    if (!$this->in_special_checkout()) {
      $this->form_action_url = zen_href_link('ipn_main_handler.php', 'type=ec&markflow=1&clearSess=1&stage=final', 'SSL', true, true, true);
    }

    // debug setup
    if (!@is_writable($this->_logDir)) $this->_logDir = DIR_FS_CATALOG . $this->_logDir;
    if (!@is_writable($this->_logDir)) $this->_logDir = DIR_FS_SQL_CACHE;
    // Regular mode:
    if ($this->enableDebugging) $this->_logLevel = 2;
    // DEV MODE:
    if (defined('PAYPAL_DEV_MODE') && PAYPAL_DEV_MODE == 'true') $this->_logLevel = 3;

    if (IS_ADMIN_FLAG === true) $this->tableCheckup();

  }
452762
protected function _initTotals()
    {
        parent::_initTotals();

        $store = $this->getOrder()->getStore()->getId();
        $taxConfig = Mage::getModel('adyen_fee/tax_config');

        if ($taxConfig->displaySalesPaymentFeeBoth($store)) {
            $this->addPaymentFeeWithTax(true);
            $this->addPaymentFeeWithoutTax(true);
        } elseif ($taxConfig->displaySalesPaymentFeeInclTax($store)) {
            $this->addPaymentFeeWithTax();
        } else {
            $this->addPaymentFeeWithoutTax();
        }

        if ($this->getSource()->getPaymentPercentageFee() != 0) {
            $this->addTotal(
                new Varien_Object(
                    array(
                        'code' => 'payment_percentage_fee',
                        'strong' => false,
                        'value' => $this->getSource()->getPaymentPercentageFee(),
                        'base_value' => $this->getSource()->getBasePaymentPercentageFee(),
                        'label' => $this->helper('adyen')->__('Payment Percentage Fee'),
                        'area' => '',
                    )
                ),
                'subtotal'
            );
        }

        if ($this->getSource()->getPaymentInstallmentFeeAmount() != 0) {
            $this->addTotal(
                new Varien_Object(
                    array(
                        'code' => 'payment_installment_fee',
                        'strong' => false,
                        'value' => $this->getSource()->getPaymentInstallmentFeeAmount(),
                        'base_value' => $this->getSource()->getBasePaymentInstallmentFeeAmount(),
                        'label' => $this->helper('adyen')->__('Payment Fee Installments'),
                        'area' => '',
                    )
                ),
                'subtotal'
            );
        }

        return $this;
    }
99402
protected function submitAddPriceRule()
    {
        $this->setSubmitted(null, $this->getParam());
        $this->validateComponent('price_rule');
        $this->addPriceRule();
    }
1349285
public static function placeOrders($type_order)
    {
        $cart = self::ofType($type_order)
            ->where('user_id', Auth::user()->id)
            ->orderBy('id', 'desc')
            ->first();

        $show_order_route = 'orders.show_cart';

        $cartDetail = OrderDetail::where('order_id', $cart->id)->get();

        $address_id = 0;

        //When address is invalid, it is because it comes from the creation of a free product. You must have a user direction (Default)
        if (is_null($cart->address_id)) {
            $useraddress = Address::auth()->orderBy('default', 'DESC')->first();
            if ($useraddress) {
                $address_id = $useraddress->address_id;
            } else {
                return trans('address.no_registered');
            }
        } else {
            $address_id = $cart->address_id;
        }

        $address = Address::where('id', $address_id)->first();

        //Checks if the user has points for the cart price and the store has stock
        //and set the order prices to the current ones if different
        //Creates the lists or sellers to send mail to
        $total_points = 0;
        $seller_email = [];
        foreach ($cartDetail as $orderDetail) {
            $product = Product::find($orderDetail->product_id);
            $seller = User::find($product->updated_by);

            // dd($product, $seller);

            if (!in_array($seller->email, $seller_email)) {
                $seller_email[] = $seller->email;
            }
            $total_points += $orderDetail->quantity * $product->price;
            if ($orderDetail->price != $product->price) {
                $orderDetail->price = $product->price;
                $orderDetail->save();
            }

            if ($product->stock < $orderDetail->quantity) {
                return trans('store.insufficientStock');
            }
        }

        //Checks if the user has points for the cart price
        $user = Auth::user();
        if ($user->current_points < $total_points && config('app.payment_method') == 'Points') {
            return trans('store.cart_view.insufficient_funds');
        }

        if (config('app.payment_method') == 'Points') {
            $negativeTotal = -1 * $total_points;
            //7 is the action type id for order checkout
            // $pointsModified = $user->modifyPoints($negativeTotal, 7, $cart->id);
            // while refactoring
        } else {
            $pointsModified = true;
        }

        if ($pointsModified) {
            //Separate the order for each seller
            //Looks for all the different sellers in the cart
            $sellers = [];
            foreach ($cartDetail as $orderDetail) {
                if (!in_array($orderDetail->product->updated_by, $sellers)) {
                    $sellers[] = $orderDetail->product->updated_by;
                }
            }
            foreach ($sellers as $seller) {
                //Creates a new order and address for each seller
                $newOrder = new self();
                $newOrder->user_id = $user->id;
                $newOrder->address_id = $address->id;
                $newOrder->status = ($type_order == 'freeproduct') ? 'paid' : 'open';
                $newOrder->type = ($type_order == 'freeproduct') ? 'freeproduct' : 'order';
                $newOrder->seller_id = $seller;
                $newOrder->save();

                $newOrder->seller->notify(new OrderWasUpdated($newOrder));

                //moves the details to the new orders
                foreach ($cartDetail as $orderDetail) {
                    if ($orderDetail->product->updated_by == $seller) {
                        $orderDetail->order_id = $newOrder->id;
                        $orderDetail->save();
                    }

                    //Increasing product counters.
                    (new ProductsRepository)->increment('sale_counts', $orderDetail->product);

                    //saving tags in users preferences
                    if (trim($orderDetail->product->tags) != '' && auth()->check()) {
                        auth()->user()->updatePreferences('product_purchased', $product->tags);
                    }
                }
            }

            //Changes the stock of each product in the order
            foreach ($cartDetail as $orderDetail) {
                $product = Product::find($orderDetail->product_id);
                $product->stock = $product->stock - $orderDetail->quantity;
                $product->save();
            }
            foreach ($seller_email as $email) {
                $mailed_order = self::where('id', $newOrder->id)->with('details')->get()->first();

                //Send a mail to the user: Order has been placed
                $data = [
                    'orderId' => $newOrder->id,
                    'order'   => $mailed_order,
                ];
                //dd($data['order']->details,$newOrder->id);
                $title = trans('email.new_order_for_user.subject')." (#$newOrder->id)";
                Mail::send('emails.neworder', compact('data', 'title'), function ($message) use ($user) {
                    $message->to($user->email)->subject(trans('email.new_order_for_user.subject'));
                });
                //Send a mail to the seller: Order has been placed
                $title = trans('email.new_order_for_seller.subject')." (#$newOrder->id)";
                Mail::send('emails.sellerorder', compact('data', 'title'), function ($message) use ($email) {
                    $message->to($email)->subject(trans('email.new_order_for_seller.subject'));
                });
            }

            return;
        } else {
            return trans('store.insufficientFunds');
        }
    }