Magento 2에서 총 주문 비용을 추가하는 방법


39

다음 링크는 설명합니다

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

마 젠토 1에서 총 주문 비용을 추가합니다.

이제이 기능은 Magento 2의 Quote 모듈 로 옮겨졌습니다 .

여전히 수집 및 페치 메소드와 같은 개념을 생각합니다. Magento 2에서 이것을 시도한 사람이 있습니까?


인용에서 주문까지 magneto2 filedset에서 제거되거나 작동하지 않지만, 총계에 대해 확실하지 않습니다
— Pradeep Kumar

2
이 질문이 너무 광범위하므로 더 구체적으로 시도하십시오. 지금까지 뭐 해봤 어?
— Sander Mangel


1
총 주문에 추가 비용을 추가 할 수있는 모듈을 개발했습니다. 이 추가 요금은 주문, 송장 및 대변 메모로 표시됩니다. GitHub에서 다운로드 할 수 있습니다 : github.com/mageprince/magento2-extrafee
— Prince Patel

모든 결제 수단 및 배송 국가에서 작동하는 다음 모듈을 사용할 수 있습니다.- scommerce
— mage.com

답변:


101

아래 단계를 따르면 도움이 될 것입니다. 내 모듈에서 방금 수수료 열
을 추가했습니다. 이것은 요금이라는 장바구니 총계에 한 행을 추가하고 결제 페이지의 사이드 바를
추가하고 총 금액에 수수료 금액을 추가했습니다 (수수료 정적 값은 100으로 유지함) ) 주문이 완료되면 총 수수료가 부과되며 주문보기에서 앞에 로그인하면 총 블록에서 수수료의 새 행을 볼 수 있지만 누군가가 구현하면 관리자 측이 아직 구현되지 않은 경우 해당 답변을 게시 할 수 있습니다

모듈 etc 폴더에 sales.xml을 작성하십시오.

<?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 \ Sugarcode \ Test \ view \ frontend \ web \ js \ view \ checkout \ cart \ totals \ fee.js

/**
 * 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 \ view \ frontend \ web \ js \ view \ checkout \ summary \ 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 \ view \ frontend \ web \ template \ checkout \ summary \ 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 \ view \ frontend \ web \ template \ checkout \ cart \ totals \ 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 \ Model \ Total \ 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 \ Sugarcode \ Test \ view \ 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 \ Sugarcode \ Test \ view \ 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 \ Sugarcode \ Test \ view \ 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 \ Block \ Sales \ 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;
    }

}

위의 단계가 명령 아래에서 실행되면 중요합니다. 그렇지 않으면 js 및 html 파일이 pub / static 폴더에서 누락됩니다. 따라서 pub / static 폴더에 js 및 html 파일을 만드는 아래 명령을 실행하십시오.

bin \ magento 설정 : 정적 내용 : 배포

작품이 다른 사람들을 돕는 내 대답을 받아들이면


16
당신은 모듈을 썼습니다 ... 인상적! +1
— Sander Mangel

4
잘 했어요 praseep
— Amit Bera

4
안녕하세요 Pradeep Kumar, 훌륭한 기사이지만 해당 코드에는 한 가지 문제가 있습니다. 수수료는 총합에 두 번 추가됩니다. 이에 대한 해결책이 있습니까?
— Sunil Patel

3
위의 코드에서 두 번 적용되는 버그를 수정 한 사람이 있습니까?
— Pallavi

4
죄송합니다. 사과해야합니다. "Two Times Fee"-버그는 아마도 app \ code \ Sugarcode \ Test \ Model \ Total \ Fee.php가 \ Magento \ Quote \ Model \ Quote \ Address \ Total \ AbstractTotal을 확장한다는 사실에 기인합니다. 결제에 일반적으로 두 개의 주소 (청구 및 배송)가 있으므로 견적 저장은 두 번 호출됩니다. M1에서도 비슷한 행동이 있었지만 불행히도 M1-Fix는 적용 할 수 없습니다.
— mybinaryromance

8

주문에 추가 비용을 추가 할 수있는 맞춤형 모듈을 개발했습니다.

추가 요금은 장바구니 페이지, 결제 페이지, 송장 및 크레딧 메모에 표시 됩니다. 관리자 구성에서 고정 가격 유형과 백분율 을 선택할 수도 있습니다.

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


텍스트 상자에서 수수료를 추가하는 방법 prnt.sc/hfsni5
— nagendra

이 확장 프로그램은 특정 결제 수단에 대해서만 수수료를 추가합니까?
— Piyush

여전히이 기능은이 모듈에 포함되어 있지 않습니다. 다음 버전의 모듈에서이 기능을 추가하겠습니다.
— 프린스 파텔

이 확장 프로그램은 특정 지불 방법에 대해서만 수수료를 추가하는 데 효과가
— Mano M

수수료 값이 변경되면 추가 요금이 결제 페이지에 반영되지 않습니다.
— 마노 M

3

Pradeep의 답변은 매우 도움이되지만 중요한 요점을 놓치고 있습니다.

Sugarcode \ Test \ Model \ Total :: collect () 함수는 각 주소마다 한 번씩 Magento의 Magento \ Quote \ Model \ QuoteTotalsCollector :: collect ()에 의해 두 번 호출됩니다. 이때 견적 테이블에 저장된 총계가 생성됩니다. 주문시 또는 체크 아웃시 웹 사이트에 표시되지 않습니다.

이러한 이유로 collect ()가 호출 된 경우 한 번만 수수료를 징수하는 것이 중요합니다. 배송 가능한 품목이 있는지 확인하여 수행 할 수 있습니다.

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

Sugarcode \ Test \ Model \ Total :: collect () 변형의 시작 부분에이 코드를 추가하십시오.


2
여전히 두 번 추가
— nagendra

이것에 대한 업데이트? 여전히 수수료를 두 번 추가하고 있습니다. 불행히도 작동하지 않습니다.
— hallleron


1

의견을주세요

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

폼 응용 프로그램 \ 코드 \ Sugarcode \ 테스트 \ 모델 \ 총 \ Fee.php 이중 사용자 정의 수수료 문제에 대한

그것이 당신을 도울 것입니다 희망 !!

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.