Calculate totals

@param Order    $transaction
@param Delivery $delivery

@return array
168791
public function calculateTotals(Transaction $transaction, $delivery=null)
    {
        if($transaction->getItems()->first()->getAdvert() instanceof  Advert){
            return $this->calculateTotalsAdvert($transaction);
        }
        if($transaction->getPaymentMethod() == Transaction::PAYMENT_METHOD_STORE_PICKUP){
            $totals['amount'] = $transaction->getTotalPrice();
            $totals['amount_clean'] = $transaction->getTotalPrice();
            $totals['delivery_expenses'] = 0;
            $totals['vat'] = 0;
            // return total
            return $totals;
        }
        $totals['delivery_expenses'] = 0;
        $totals['amount'] = $transaction->getTotalPrice();
        $totals['amount_clean'] = $transaction->getTotalPrice();
        $totals['vat'] = number_format($totals['amount_clean'] * $this->vat, 2);
        
        if(!is_null($delivery)){
            $totalPerDeliveryExpenses = $this->calculateTotalAmountForDeliveryExpenses($transaction);

            // calculate delivery expenses
            if ('by_percentage' === $this->deliveryExpensesType) {
                $totals['delivery_expenses'] = round($totalPerDeliveryExpenses * ($delivery->getExpenses() / 100),2);
            } else {
                $totals['delivery_expenses'] = $delivery->getExpenses();
            }
        }
        
        // calculate vat
        if(!is_null($transaction->getVat())){
            $vat = $transaction->getVat();
            $totals['vat'] = ($totals['amount'] + $totals['delivery_expenses']) * ($vat / 100);
        }
        // calculate amount
        $totals['amount'] += $totals['delivery_expenses'] + $totals['vat'];
        // return total
        return $totals;
    }
12601
static public function calculateForTransaction(Transaction $transaction)
    {
        // generate each content fee accordingly
        $msgFee = self::calculateForMessage($transaction->message());

        // default content fee is XEM amount transfer fee
        $contentFee = Fee::FEE_FACTOR * self::calculateForXEM($transaction->amount()->toMicro() / Amount::XEM);

        // get the Transaction extension fee
        $extensionFee = $transaction->extendFee();

        if ($extensionFee > 0) {
            $contentFee = (int) $extensionFee;
        }

        return $msgFee + $contentFee;
    }
442396
private function _buildRequestData(Transaction $transaction): array
    {
        $currency = Commerce::getInstance()->getCurrencies()->getCurrencyByIso($transaction->paymentCurrency);

        if (!$currency) {
            throw new NotSupportedException('The currency “' . $transaction->paymentCurrency . '” is not supported!');
        }

        $metadata = [
            'order_id' => $transaction->getOrder()->id,
            'order_number' => $transaction->getOrder()->number,
            'transaction_id' => $transaction->id,
            'transaction_reference' => $transaction->hash,
        ];

        $appRequest = Craft::$app->getRequest();
        if (!$appRequest->getIsConsoleRequest()) {
            $metadata['client_ip'] = $appRequest->getUserIP();
        }

        $request = [
            'amount' => $transaction->paymentAmount * (10 ** $currency->minorUnit),
            'currency' => $transaction->paymentCurrency,
            'description' => Craft::t('commerce-stripe', 'Order') . ' #' . $transaction->orderId,
            'metadata' => $metadata
        ];

        $event = new BuildGatewayRequestEvent([
            'transaction' => $transaction,
            'metadata' => $metadata,
            'request' => $request
        ]);

        $this->trigger(self::EVENT_BUILD_GATEWAY_REQUEST, $event);

        $request = array_merge($event->request, $request);
        $request['metadata'] = array_merge($event->metadata, $metadata);

        if ($this->sendReceiptEmail) {
            $request['receipt_email'] = $transaction->getOrder()->email;
        }

        return $request;
    }
149697
protected function getAvailableTotals()
    {
        $result = array(
            Meta::InvoiceAmountInc => $this->source['total'],
            Meta::InvoiceVatAmount => 0.0,
            Meta::InvoiceVatBreakdown => array(),
        );

        /** @noinspection PhpUnhandledExceptionInspection */
        $orderTotals = $this->getOrderTotalLines();
        foreach ($orderTotals as $totalLine) {
            if ($totalLine['code'] === 'tax') {
                $result[Meta::InvoiceVatBreakdown][] = $totalLine['title'] . ': ' . $totalLine['value'];
                $result[Meta::InvoiceVatAmount] += $totalLine['value'];
            }
        }
        return $result;
    }
1090221
public function calculateWeeks(string $deliveryDate, string $referenceDate): int
    {
        $timestampDeliveryDate = $this->DM->convertDateToTimestamp($deliveryDate);
        $timestampReferenceDate = $this->DM->convertDateToTimestamp($referenceDate);
        $timestampConceptionDate = $timestampDeliveryDate - $this->pregnancyDuration;
        return ceil(($timestampReferenceDate - $timestampConceptionDate) / $this->periodWeek);
    }
1185845
public static function transformFilterAmount($transaction)
    {
        // Process a single transaction
        if (isset($transaction->currency) && isset($transaction->amount)) {
            $transaction->amount = \Genesis\Utils\Currency::exponentToAmount(
                $transaction->amount,
                $transaction->currency
            );
        }
        return $transaction;
    }
159753
public function process(Request $request, Transaction $transaction, Delivery $delivery)
    {
        
        // in your controller
        $transactionService = $this->get('transaction');
        $data = $request->get('braintree');
        $nonce = $data['payment_method_nonce'];

        $result = $transactionService::sale([
            'amount' => $transaction->getTotalPrice(),
            'paymentMethodNonce' => $nonce
        ]);
        
        
        $em = $this->container->get('doctrine')->getManager();
        $pm = $em->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('braintree');
        if ($result->success || !is_null($result->transaction)) {
                        
            //UPDATE TRANSACTION
            $transaction->setStatus(Transaction::STATUS_PAID);
            $transaction->setPaymentMethod($pm);
            
            //details
            $details = new stdClass();
            $details->id = $result->transaction->id;
            $details->status = $result->transaction->status;
            $details->type = $result->transaction->type;
            $details->currencyIsoCode = $result->transaction->currencyIsoCode;
            $details->amount = $result->transaction->amount;
            $details->merchantAccountId = $result->transaction->merchantAccountId;
            $details->createdAt = $result->transaction->createdAt;
            $details->updatedAt = $result->transaction->updatedAt;
            $details->customer = $result->transaction->customer;
            $details->billing = $result->transaction->billing;
            $details->shipping = $result->transaction->shipping;
            
            $transaction->setPaymentDetails(json_encode($details));
            $em->persist($transaction);
            $em->flush();

            //confirmation payment
            $answer = new stdClass();
            $answer->redirectUrl = $this->container->get('router')->generate('ecommerce_checkout_confirmationpayment');

            return $answer;
       }else{
            //UPDATE TRANSACTION
            $transaction->setStatus(Transaction::STATUS_CANCELLED);
            $transaction->setPaymentMethod($pm);
            
            //details
            $errorString = "";
            foreach($result->errors->deepAll() as $error) {
               $errorString .= 'Error: ' . $error->code . ": " . $error->message . "\n";
            }
            $this->container->get('session')->getFlashBag()->add('error', $errorString);
            
            $transaction->setPaymentDetails(json_encode($errorString));
            $em->persist($transaction);
            $em->flush();

            //cancel payment
            $answer = new stdClass();
            $answer->redirectUrl = $this->container->get('router')->generate('ecommerce_checkout_cancelationpayment');

            return $answer;
        }
 
    }
632153
public function getAllDeliveryIds()
    {
        $returnValue = array();
        $sql = 'SELECT ' . self::RESULTS_TABLE_ID . ', ' . self::DELIVERY_COLUMN . ' FROM ' . self::RESULTS_TABLENAME;
        $results = $this->getPersistence()->query($sql);
        foreach ($results as $value) {
            $returnValue[] = array(
                "deliveryResultIdentifier" => $value[self::RESULTS_TABLE_ID],
                "deliveryIdentifier" => $value[self::DELIVERY_COLUMN]
            );
        }
        return $returnValue;
    }
1111371
public function processBraintree(Transaction $transaction, $delivery, $request)
    {
        // in your controller
        $transactionService = $this->braintreeFactory->get('transaction');
        $nonce = $request->get('payment_method_nonce');

        $result = $transactionService::sale([
            'amount' => $transaction->getTotalPrice(),
            'paymentMethodNonce' => $nonce
        ]);

        $pm = $this->manager->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('braintree');
        if ($result->success || !is_null($result->transaction)) {
            //UPDATE TRANSACTION
            $transaction->setStatus(Transaction::STATUS_PAID);
            $transaction->setPaymentMethod($pm);
            
            //details
            $details = new stdClass();
            $details->id = $result->transaction->id;
            $details->status = $result->transaction->status;
            $details->type = $result->transaction->type;
            $details->currencyIsoCode = $result->transaction->currencyIsoCode;
            $details->amount = $result->transaction->amount;
            $details->merchantAccountId = $result->transaction->merchantAccountId;
            $details->createdAt = $result->transaction->createdAt;
            $details->updatedAt = $result->transaction->updatedAt;
            $details->customer = $result->transaction->customer;
            $details->billing = $result->transaction->billing;
            $details->shipping = $result->transaction->shipping;
            
            $transaction->setPaymentDetails(json_encode($details));
            $this->manager->persist($transaction);
            $this->manager->flush();

            //confirmation payment
            $answer = new \stdClass();
            $answer->redirectUrl = $this->router->generate('ecommerce_checkout_confirmationpayment');

            return $answer;
       }else{
            //UPDATE TRANSACTION
            $transaction->setStatus(Transaction::STATUS_CANCELLED);
            $transaction->setPaymentMethod($pm);
            
            //details
            $errorString = "";
            foreach($result->errors->deepAll() as $error) {
               $errorString .= 'Error: ' . $error->code . ": " . $error->message . "\n";
            }
            $this->session->getFlashBag()->add('error', $errorString);
            
            $transaction->setPaymentDetails(json_encode($errorString));
            $this->manager->persist($transaction);
            $this->manager->flush();

            //cancel payment
            $answer = new \stdClass();
            $answer->redirectUrl = $this->paypalFactory->getCancelUrl();

            return $answer;
        }
 
    }
128730
public function calculateTotalDiscount(Basket $basket, Discount $discount, Money $total)
    {
        // Handle a ValueDiscount
        if ($discount instanceof ValueDiscount) {
            $total = $this->subtractValueDiscount($total, $discount);
        }

        // Handle a PercentageDiscount
        if ($discount instanceof PercentageDiscount) {
            $total = $this->subtractPercentageDiscount($total, $discount);
        }

        // Handle a QuantityDiscount
        if ($discount instanceof QuantityDiscount) {
            // Calculate the total quantity of items ordered
            $totalQuantity = 0;

            foreach ($basket->products() as $product) {
                $totalQuantity = $totalQuantity + $product->quantity;
            }

            $quantityDiscount = $discount->rate();

            // Handle a ValueDiscount within a QuantityDiscount
            if ($quantityDiscount instanceof ValueDiscount) {
                $total = $this->subtractValueDiscount($total, $quantityDiscount);
            }

            // Handle a PercentageDiscount within a QuantityDiscount
            if ($quantityDiscount instanceof PercentageDiscount) {
                $total = $this->subtractPercentageDiscount($total, $quantityDiscount);
            }
        }

        return $total;
    }
215914
public function totals()
    {
        setlocale(LC_MONETARY, config('cart_manager.LC_MONETARY'));

        $totals = ['Subtotal' => money_format('%n', $this->subtotal)];

        if ($this->discount > 0) {
            $totals['Discount'] = money_format('%n', $this->discount);
        }

        if ($this->shippingCharges > 0) {
            $totals['Shipping charges'] = money_format('%n', $this->shippingCharges);
        }

        if ($this->subtotal != $this->netTotal) {
            $totals['Net total'] = money_format('%n', $this->netTotal);
        }

        $totals['Tax'] = money_format('%n', $this->tax);

        if ($this->roundOff != 0) {
            $totals['Total'] = money_format('%n', $this->total);
            $totals['Round off'] = money_format('%n', $this->roundOff);
        }

        $totals['Payable'] = money_format('%n', $this->payable);

        return $totals;
    }
1372217
public static function paymentReceived(Purchase $purchase, $amount)
    {
        $purchase->received += $amount;

        if ($purchase->received >= $purchase->grandTotal) {
            $purchase->paid = time();

            $purchase->item->seller->sendEmail(
                'You have received a payment',
                'emails.item.paid',
                [
                    'total' => $purchase->received,
                    'item_name' => $purchase->item->name,
                    'buyer_name' => $purchase->name,
                    'buyer_street1' => $purchase->street1,
                    'buyer_street2' => $purchase->street2,
                    'buyer_city' => $purchase->city,
                    'buyer_county' => $purchase->county,
                    'buyer_postcode' => $purchase->postcode,
                    'buyer_country' => Iso3166::get($purchase->country)->name,
                    'has_delivery' => $purchase->hasDelivery(),
                    'has_address' => $purchase->hasAddress(),
                    'purchase_id' => $purchase->purchaseId,
                    'full' => $purchase->received == 0,
                ]
            );

            $purchase->buyer->sendEmail(
                'Receipt for your item',
                'emails.item.receipt',
                [
                    'total' => $purchase->received,
                    'item_name' => $purchase->item->name,
                    'seller_name' => $purchase->name,
                    'seller_street1' => $purchase->street1,
                    'seller_street2' => $purchase->street2,
                    'seller_city' => $purchase->city,
                    'seller_county' => $purchase->county,
                    'seller_postcode' => $purchase->postcode,
                    'seller_country' => Iso3166::get($purchase->country)->name,
                    'full' => $purchase->received == 0,
                    'has_delivery' => $purchase->hasDelivery(),
                    'has_address' => $purchase->hasAddress(),
                    'is_paid' => $purchase->isPaid()
                ]
            );
        }

        $purchase->save();
    }
679362
private function show_table( $order, $orderby, $items, $fields, $include_total ) {
		$table = new \cli\Table();

		$enabled = \cli\Colors::shouldColorize();
		if ( $enabled ) {
			\cli\Colors::disable( true );
		}

		$table->setHeaders( $fields );

		$totals = array_fill( 0, count( $fields ), null );
		if ( ! is_null( $this->total_cell_index ) ) {
			$totals[ $this->total_cell_index ] = 'total (' . count( $items ) . ')';
		}

		if ( $orderby ) {
			usort(
				$items,
				function( $a, $b ) use ( $order, $orderby ) {
					list( $first, $second ) = 'ASC' === $order ? array( $a, $b ) : array( $b, $a );

					if ( is_numeric( $first->$orderby ) && is_numeric( $second->$orderby ) ) {
						return $this->compare_float( $first->$orderby, $second->$orderby );
					}

					return strcmp( $first->$orderby, $second->$orderby );
				}
			);
		}

		$location_index = array_search( 'location', $fields );
		foreach ( $items as $item ) {
			$values = array_values( \WP_CLI\Utils\pick_fields( $item, $fields ) );
			foreach ( $values as $i => $value ) {
				if ( ! is_null( $this->total_cell_index ) && $this->total_cell_index === $i ) {
					continue;
				}

				// Ignore 'location' for hook profiling
				if ( false !== $location_index && $location_index === $i ) {
					continue;
				}

				if ( null === $totals[ $i ] ) {
					if ( stripos( $fields[ $i ], '_ratio' ) ) {
						$totals[ $i ] = array();
					} else {
						$totals[ $i ] = 0;
					}
				}
				if ( stripos( $fields[ $i ], '_ratio' ) ) {
					if ( ! is_null( $value ) ) {
						$totals[ $i ][] = $value;
					}
				} else {
					$totals[ $i ] += $value;
				}
				if ( stripos( $fields[ $i ], '_time' ) || 'time' === $fields[ $i ] ) {
					$values[ $i ] = round( $value, 4 ) . 's';
				}
			}
			$table->addRow( $values );
		}
		if ( $include_total ) {
			foreach ( $totals as $i => $value ) {
				if ( null === $value ) {
					continue;
				}
				if ( stripos( $fields[ $i ], '_time' ) || 'time' === $fields[ $i ] ) {
					$totals[ $i ] = round( $value, 4 ) . 's';
				}
				if ( is_array( $value ) ) {
					if ( ! empty( $value ) ) {
						$totals[ $i ] = round( ( array_sum( $value ) / count( $value ) ), 2 ) . '%';
					} else {
						$totals[ $i ] = null;
					}
				}
			}
			$table->setFooters( $totals );
		}

		foreach ( $table->getDisplayLines() as $line ) {
			\WP_CLI::line( $line );
		}

		if ( $enabled ) {
			\cli\Colors::enable( true );
		}
	}
850444
public function calc($tree, $orders, $params, $percents) {
        $result = [ ];
        $mapTreeExp = $this->_expandTree($tree);
        $mapRankById = $this->aRankQualifier->qualifyCustomers($tree, $params);
        foreach($orders as $order) {
            $custId = $order[Cfg::E_SALE_ORDER_A_CUSTOMER_ID];
            $orderId = $order[PvSale::A_SALE_ID];
            $pv = $order[PvSale::A_TOTAL];
            $path = $mapTreeExp[$custId][Snap::A_PATH];
            $parents = $this->hlpTree->getParentsFromPathReversed($path);
            $gen = 1;
            foreach($parents as $parentId) {
                if(isset($mapRankById[$parentId])) {
                    $parentRank = $mapRankById[$parentId];
                    if(isset($percents[$parentRank][$gen])) {
                        $percent = $percents[$parentRank][$gen];
                        $bonus = $pv * $percent;
                        $bonus = $this->hlpFormat->roundBonus($bonus);
                        $result[$parentId][$orderId] = $bonus;
                    }
                }
                $gen++;
            }

        }
        return $result;
    }
298736
public function processPaypalSale(Transaction $transaction, $delivery=null, $credtCard=null)
    {
        
        $totals = $this->calculateTotals($transaction, $delivery);
  
        $this->paypalToken();
        
        if(is_null($credtCard)){
            $paymentMehod = array("payment_method" => "paypal");
        }else{
            $paymentMehod = array(
            "payment_method" => "credit_card",
            "funding_instruments" => array(
                array(
                  "credit_card" => $credtCard
                )
              )
            );
        }
        
        $returnValues = array();
        foreach ($transaction->getItems() as $productPurchase) {
            $sub = array();
            $sub['quantity'] = $productPurchase->getQuantity();
            if($productPurchase->getProduct() instanceof Product){
                $sub['name'] = $productPurchase->getProduct()->getName();
                $sub['price'] = number_format($productPurchase->getProduct()->getPrice(), 2);
            }elseif($productPurchase->getAdvert() instanceof Advert){
                $sub['name'] = $productPurchase->getAdvert()->getTitle();
                $sub['price'] = number_format($this->advertUnitPrice, 2);
            }
            
            $sub['sku'] = $productPurchase->getId();
            $sub['currency'] = "EUR";
            $returnValues[] = $sub;
        }
        
        $host = $this->paypalFactory->getHost();
        $url = $host.'/v1/payments/payment';
        $payment = array(
                        'intent' => 'sale',
                        'payer' => $paymentMehod,
                        'transactions' => array (array(
                                        'amount' => array(
                                                'total' => number_format($totals['amount'], 2),
                                                'currency' => 'EUR',
                                                'details' =>  array(
                                                    "subtotal" => number_format($totals['amount_clean'], 2),
                                                    "tax" => number_format($totals['vat'], 2),
                                                    "shipping" => $totals['delivery_expenses']
                                                  )
                                                ),
                                        'description' => 'payment using a PayPal account',
                                        "item_list" => array (
                                                "items" => $returnValues
                                                ),
                                        )),
                        'redirect_urls' => array (
                                'return_url' => $this->paypalFactory->getReturnUrl(),
                                'cancel_url' => $this->paypalFactory->getCancelUrl()
                        )
                    );

        $json = json_encode($payment);
        $json_resp = $this->paypalCall('POST', $url, $json);
               
        if(!is_null($credtCard)){
            if($json_resp['state'] == 'approved'){
                 //UPDATE TRANSACTION
                $pm = $this->manager->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('paypal-direct-payment');
                $transaction->setStatus(Transaction::STATUS_PAID);
                $transaction->setPaymentMethod($pm);
                $transaction->setPaymentDetails(json_encode($json_resp));
                $this->manager->persist($transaction);
                $this->manager->flush();
                
                //confirmation payment
                $answer = new \stdClass();
                $answer->redirectUrl = $this->router->generate('ecommerce_checkout_confirmationpayment');

                return $answer;
            }else{
                //cancel payment
                $answer = new \stdClass();
                $answer->redirectUrl = $this->paypalFactory->getCancelUrl();

                return $answer;
            }
        }else{
            //UPDATE TRANSACTION
            $pm = $this->manager->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('paypal');
            $transaction->setStatus(Transaction::STATUS_PENDING);
            $transaction->setPaymentMethod($pm);
            $transaction->setPaymentDetails(json_encode($json_resp));
            $this->manager->persist($transaction);
            $this->manager->flush();


            foreach ($json_resp['links'] as $link) {
                    if($link['rel'] == 'execute'){
                            $payment_execute_url = $link['href'];
                            $payment_execute_method = $link['method'];
                    }elseif($link['rel'] == 'approval_url'){
                            $payment_approval_url = $link['href'];
                            $payment_approval_method = $link['method'];
                    }
            }

            $answer = new \stdClass();
            $answer->redirectUrl = $payment_approval_url;

            return $answer;
        }
        
    }
356791
def get_total_supply(self) -> int:
        
        func = InvokeFunction('totalSupply')
        response = self.__sdk.get_network().send_neo_vm_transaction_pre_exec(self.__hex_contract_address, None, func)
        try:
            total_supply = ContractDataParser.to_int(response['Result'])
        except SDKException:
            total_supply = 0
        return total_supply
125341
private function computeTotalCount($total, array $callableArgs = [])
    {
        if (null !== $this->totalCount) {
            return $this->totalCount;
        }

        $this->totalCount = \is_callable($total) ? \call_user_func_array($total, $callableArgs) : $total;

        return $this->totalCount;
    }