Come aggiungere una commissione per ordinare i totali in Magento 2


39

Il seguente link descriverà

http://excellencemagentoblog.com/blog/2012/01/27/magento-add-fee-discount-order-total/

per aggiungere una commissione per ordinare i totali in Magento 1.

Ora questa funzionalità viene spostata nel modulo Quote in Magento 2.

Penso ancora lo stesso concetto dei metodi di raccolta e recupero. Qualcuno ha provato questo in Magento 2?


in magneto2 archiviato dal preventivo all'ordine viene rimosso o non funzionante, ma non sono sicuro di raccogliere i totali
— Pradeep Kumar,

2
Questa domanda è troppo ampia, cerca di essere più specifico. Cosa hai provato fino ad ora?
— Sander Mangel


1
Ho sviluppato un modulo per aggiungere costi aggiuntivi al totale dell'ordine. Questa tariffa aggiuntiva verrà visualizzata in ordine, fattura e creditmemo. puoi scaricare da GitHub: github.com/mageprince/magento2-extrafee
— Prince Patel,

Potrebbe utilizzare il seguente modulo che funziona con tutti i metodi di pagamento e paese di spedizione - scommerce-mage.com/magento2-surcharge-or-additional-fee.html
— user2804

Risposte:


102

segui i passaggi seguenti che ti aiuteranno, nel mio modulo ho appena aggiunto la colonna delle commissioni
che aggiungerà una riga nel totale del carrello chiamato commissione e anche la barra laterale nella pagina di checkout
e inoltre ha aggiunto l'importo della commissione all'importo totale (valore statico della commissione che ho mantenuto come 100 ) una volta che l'ordine è stato effettuato, il totale sarà a pagamento e se si è effettuato il login fronteggiato nella vista dell'ordine, è possibile vedere la nuova riga della commissione nel blocco totale ma il lato amministratore non è ancora implementato se qualcuno implementa, è possibile pubblicare quella risposta

crea sales.xml nella cartella del tuo modulo ecc

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Sales:etc/sales.xsd">
    <section name="quote">
        <group name="totals">

            <item name="fee" instance="Sugarcode\Test\Model\Total\Fee" sort_order="150"/>

        </group>  
    </section>
</config>

app \ code \ \ Vista Vista \ frontend \ web \ js \ \ \ checkout carrello \ totali \ fee.js Sugarcode \ test

/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
define(
    [
        'Sugarcode_Test/js/view/checkout/summary/fee'
    ],
    function (Component) {
        'use strict';

        return Component.extend({

            /**
             * @override
             */
            isDisplayed: function () {
                return true;
            }
        });
    }
);

App \ code \ Sugarcode \ Test \ vista \ vista frontend \ web \ js \ \ cassa \ sintesi \ fee.js

/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
/*jshint browser:true jquery:true*/
/*global alert*/
define(
    [
        'Magento_Checkout/js/view/summary/abstract-total',
        'Magento_Checkout/js/model/quote',
        'Magento_Catalog/js/price-utils',
        'Magento_Checkout/js/model/totals'
    ],
    function (Component, quote, priceUtils, totals) {
        "use strict";
        return Component.extend({
            defaults: {
                isFullTaxSummaryDisplayed: window.checkoutConfig.isFullTaxSummaryDisplayed || false,
                template: 'Sugarcode_Test/checkout/summary/fee'
            },
            totals: quote.getTotals(),
            isTaxDisplayedInGrandTotal: window.checkoutConfig.includeTaxInGrandTotal || false,
            isDisplayed: function() {
                return this.isFullMode();
            },
            getValue: function() {
                var price = 0;
                if (this.totals()) {
                    price = totals.getSegment('fee').value;
                }
                return this.getFormattedPrice(price);
            },
            getBaseValue: function() {
                var price = 0;
                if (this.totals()) {
                    price = this.totals().base_fee;
                }
                return priceUtils.formatPrice(price, quote.getBasePriceFormat());
            }
        });
    }
);

App \ code \ Sugarcode \ Test \ vista \ frontend \ web \ template \ cassa \ sintesi \ fee.html

<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<!-- ko -->

  <tr class="totals fee excl">
        <th class="mark" scope="row">
            <span class="label" data-bind="text: title"></span>
            <span class="value" data-bind="text: getValue()"></span>
        </th>
        <td class="amount">

            <span class="price"
                  data-bind="text: getValue(), attr: {'data-th': title}"></span>


        </td>
    </tr>   

<!-- /ko -->

App \ code \ Sugarcode \ Test \ vista \ frontend \ web \ template \ cassa \ carrello \ ammonta \ fee.html

<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<!-- ko -->
<tr class="totals fee excl">
    <th class="mark" colspan="1" scope="row" data-bind="text: title"></th>
    <td class="amount">
        <span class="price" data-bind="text: getValue()"></span>
    </td>
</tr>
<!-- /ko -->

App \ code \ Sugarcode \ Test \ modello \ totale \ Fee.php

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Sugarcode\Test\Model\Total;


class Fee extends \Magento\Quote\Model\Quote\Address\Total\AbstractTotal
{
   /**
     * Collect grand total address amount
     *
     * @param \Magento\Quote\Model\Quote $quote
     * @param \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment
     * @param \Magento\Quote\Model\Quote\Address\Total $total
     * @return $this
     */
    protected $quoteValidator = null; 

    public function __construct(\Magento\Quote\Model\QuoteValidator $quoteValidator)
    {
        $this->quoteValidator = $quoteValidator;
    }
  public function collect(
        \Magento\Quote\Model\Quote $quote,
        \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment,
        \Magento\Quote\Model\Quote\Address\Total $total
    ) {
        parent::collect($quote, $shippingAssignment, $total);


        $exist_amount = 0; //$quote->getFee(); 
        $fee = 100; //Excellence_Fee_Model_Fee::getFee();
        $balance = $fee - $exist_amount;

        $total->setTotalAmount('fee', $balance);
        $total->setBaseTotalAmount('fee', $balance);

        $total->setFee($balance);
        $total->setBaseFee($balance);

        $total->setGrandTotal($total->getGrandTotal() + $balance);
        $total->setBaseGrandTotal($total->getBaseGrandTotal() + $balance);


        return $this;
    } 

    protected function clearValues(Address\Total $total)
    {
        $total->setTotalAmount('subtotal', 0);
        $total->setBaseTotalAmount('subtotal', 0);
        $total->setTotalAmount('tax', 0);
        $total->setBaseTotalAmount('tax', 0);
        $total->setTotalAmount('discount_tax_compensation', 0);
        $total->setBaseTotalAmount('discount_tax_compensation', 0);
        $total->setTotalAmount('shipping_discount_tax_compensation', 0);
        $total->setBaseTotalAmount('shipping_discount_tax_compensation', 0);
        $total->setSubtotalInclTax(0);
        $total->setBaseSubtotalInclTax(0);
    }
    /**
     * @param \Magento\Quote\Model\Quote $quote
     * @param Address\Total $total
     * @return array|null
     */
    /**
     * Assign subtotal amount and label to address object
     *
     * @param \Magento\Quote\Model\Quote $quote
     * @param Address\Total $total
     * @return array
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function fetch(\Magento\Quote\Model\Quote $quote, \Magento\Quote\Model\Quote\Address\Total $total)
    {
        return [
            'code' => 'fee',
            'title' => 'Fee',
            'value' => 100
        ];
    }

    /**
     * Get Subtotal label
     *
     * @return \Magento\Framework\Phrase
     */
    public function getLabel()
    {
        return __('Fee');
    }
}

App \ code \ Sugarcode \ Test \ etc \ Module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Sugarcode_Test" setup_version="2.0.6" schema_version="2.0.6">
        <sequence>
            <module name="Magento_Sales"/>
            <module name="Magento_Quote"/>
            <module name="Magento_Checkout"/>
        </sequence>
    </module>
</config>

App \ code \ vista Sugarcode \ Test \ \ frontend \ layout \ checkout_cart_index.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="checkout.cart.totals">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="block-totals" xsi:type="array">
                            <item name="children" xsi:type="array">


                                <item name="fee" xsi:type="array">
                                    <item name="component"  xsi:type="string">Sugarcode_Test/js/view/checkout/cart/totals/fee</item>
                                    <item name="sortOrder" xsi:type="string">20</item>
                                    <item name="config" xsi:type="array">
                                         <item name="template" xsi:type="string">Sugarcode_Test/checkout/cart/totals/fee</item>
                                        <item name="title" xsi:type="string" translate="true">Fee</item>
                                    </item>
                                </item>

                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

App \ code \ vista Sugarcode \ Test \ \ frontend \ layout \ checkout_index_index.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="checkout.root">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="checkout" xsi:type="array">
                            <item name="children" xsi:type="array">

                                <item name="sidebar" xsi:type="array">
                                    <item name="children" xsi:type="array">
                                        <item name="summary" xsi:type="array">
                                            <item name="children" xsi:type="array">
                                                <item name="totals" xsi:type="array">
                                                    <item name="children" xsi:type="array">
                                                       <item name="fee" xsi:type="array">
                                                            <item name="component"  xsi:type="string">Sugarcode_Test/js/view/checkout/cart/totals/fee</item>
                                                            <item name="sortOrder" xsi:type="string">20</item>
                                                            <item name="config" xsi:type="array">
                                                                 <item name="template" xsi:type="string">Sugarcode_Test/checkout/cart/totals/fee</item>
                                                                <item name="title" xsi:type="string" translate="true">Fee</item>
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                                <item name="cart_items" xsi:type="array">
                                                    <item name="children" xsi:type="array">
                                                        <item name="details" xsi:type="array">
                                                            <item name="children" xsi:type="array">
                                                                <item name="subtotal" xsi:type="array">
                                                                    <item name="component" xsi:type="string">Magento_Tax/js/view/checkout/summary/item/details/subtotal</item>
                                                                </item>
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>
                                        </item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

App \ code \ vista Sugarcode \ Test \ \ frontend \ layout \ sales_order_view.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    <body>        
        <referenceContainer name="order_totals">
            <block class="Sugarcode\Test\Block\Sales\Order\Fee" name="fee"/>
        </referenceContainer>
    </body>
</page>

App \ code \ Sugarcode \ Test \ Blocco \ vendite \ Order \ Fee.php

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * Tax totals modification block. Can be used just as subblock of \Magento\Sales\Block\Order\Totals
 */
namespace Sugarcode\Test\Block\Sales\Order;



class Fee extends \Magento\Framework\View\Element\Template
{
    /**
     * Tax configuration model
     *
     * @var \Magento\Tax\Model\Config
     */
    protected $_config;

    /**
     * @var Order
     */
    protected $_order;

    /**
     * @var \Magento\Framework\DataObject
     */
    protected $_source;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Tax\Model\Config $taxConfig
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Tax\Model\Config $taxConfig,
        array $data = []
    ) {
        $this->_config = $taxConfig;
        parent::__construct($context, $data);
    }

    /**
     * Check if we nedd display full tax total info
     *
     * @return bool
     */
    public function displayFullSummary()
    {
        return true;
    }

    /**
     * Get data (totals) source model
     *
     * @return \Magento\Framework\DataObject
     */
    public function getSource()
    {
        return $this->_source;
    } 
    public function getStore()
    {
        return $this->_order->getStore();
    }

      /**
     * @return Order
     */
    public function getOrder()
    {
        return $this->_order;
    }

    /**
     * @return array
     */
    public function getLabelProperties()
    {
        return $this->getParentBlock()->getLabelProperties();
    }

    /**
     * @return array
     */
    public function getValueProperties()
    {
        return $this->getParentBlock()->getValueProperties();
    }

    /**
     * Initialize all order totals relates with tax
     *
     * @return \Magento\Tax\Block\Sales\Order\Tax
     */
     public function initTotals()
    {

        $parent = $this->getParentBlock();
        $this->_order = $parent->getOrder();
        $this->_source = $parent->getSource();

        $store = $this->getStore();

        $fee = new \Magento\Framework\DataObject(
                [
                    'code' => 'fee',
                    'strong' => false,
                    'value' => 100,
                    //'value' => $this->_source->getFee(),
                    'label' => __('Fee'),
                ]
            );

            $parent->addTotal($fee, 'fee');
           // $this->_addTax('grand_total');
            $parent->addTotal($fee, 'fee');


            return $this;
    }

}

una volta che i passaggi precedenti sono stati eseguiti, esegui sotto il comando, questo è importante, altrimenti i tuoi file js & html mancheranno dalla cartella pub / static. Quindi, esegui sotto il comando che creerà il file js e html nella cartella pub / static

bin \ magento setup: static-content: deploy

se funziona accetta la mia risposta che aiuta gli altri


16
hai scritto il modulo ... impressionante! +1 per quello
— Sander Mangel

4
ben fatto praseep
— Amit Bera

4
ciao Pradeep Kumar, ottimo articolo, ma c'è un problema con quel codice, la commissione si aggiunge due volte al totale generale, c'è qualche soluzione per questo?
— Sunil Patel,

3
Qualcuno ha corretto il bug applicato per due commissioni nel codice sopra?
— Pallavi,

4
Mi dispiace, devo scusarmi. Il bug "Two Times Fee" è probabilmente dovuto al fatto che app \ code \ Sugarcode \ Test \ Model \ Total \ Fee.php estende \ Magento \ Quote \ Model \ Quote \ Address \ Total \ AbstractTotal. Dato che normalmente hai due indirizzi in cassa (fatturazione e spedizione), il salvataggio del preventivo viene chiamato due volte. C'è stato un comportamento simile in M1, sfortunatamente M1-Fix non è applicabile qui ...
— mybinaryromance

7

Ho sviluppato un modulo personalizzato per aggiungere costi aggiuntivi per ordinare.

Il costo aggiuntivo verrà visualizzato nella pagina del carrello, nella pagina di pagamento, nella fattura e in creditmemo . Puoi anche selezionare il tipo di prezzo su fisso e percentuale dalla configurazione dell'amministratore.

https://github.com/mageprince/magento2-extrafee/


Come aggiungere una commissione dalla casella di testo prnt.sc/hfsni5
— nagendra

Questa estensione funzionerà per aggiungere commissioni solo per un particolare metodo di pagamento?
— Piyush,

Questa funzionalità non è ancora inclusa in questo modulo. Aggiungerò questa funzionalità nella prossima versione del modulo.
— Prince Patel,

Questa estensione funzionerà per aggiungere una commissione per un particolare metodo di pagamento solo .....
— Mano M

se si modifica il valore della commissione, la tariffa aggiuntiva non si riflette nella pagina di pagamento.
— Mano M,

3

La risposta di Pradeep è molto utile, ma manca un punto importante.

La funzione Sugarcode \ Test \ Model \ Total :: collect () viene chiamata due volte da Magento \ Quote \ Model \ QuoteTotalsCollector :: collect () di Magento, una volta per ciascun indirizzo. A quel punto crea un totale combinato che viene memorizzato nella tabella delle quotazioni. Non viene visualizzato nell'ordine, né sul sito Web nel checkout.

Per questo motivo è importante riscuotere la commissione solo in una delle volte in cui viene chiamato collect (). Questo può essere fatto controllando se ci sono articoli spediti disponibili:

    $items = $shippingAssignment->getItems();
    if (!count($items)) {
        return $this;
    }

Aggiungi questo codice all'inizio della variante di Sugarcode \ Test \ Model \ Total :: collect ()


2
ancora aggiungendo due volte
— nagendra il

Qualche aggiornamento a questo proposito? Aggiunge ancora la tassa due volte. Purtroppo non riesco a farlo funzionare.
— Hallleron,


1

per favore, commenta

        $total->setGrandTotal($total->getGrandTotal() + $balance);

modulo app \ code \ Sugarcode \ Test \ Model \ Total \ Fee.php per doppia emissione di commissioni personalizzate

Spero che ti possa aiutare !!

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.