[英]How to apply discount after tax programatically for a Magento 2 order?
I have created an order programatically in Magento 2. I am provided with data:我在 Magento 2 中以编程方式创建了一个订单。我提供了数据:
Now taxes are inclusive product prices, so by default in Magento 2:现在税是包含产品价格,所以在 Magento 2 中默认:
Grand total is not same as provided.总计与提供的不同。 I want to add discount after tax calculation.我想在计算税后添加折扣。
For Tax configuration, there are two ways to fix this.对于税务配置,有两种方法可以解决此问题。 In backend configuration: Apply Customer Tax ->set 'Before Discount';在后端配置中:应用客户税 -> 设置“折扣前”; This should fix your problem I guess.我想这应该可以解决您的问题。
You can customize the code as well for same : In your di.xml, add as below:您也可以为相同的代码自定义代码:在您的 di.xml 中,添加如下:
<preference for="Magento\Tax\Model\Sales\Total\Quote\Tax" type="<yournamespace>\<yourModule>\Model\Sales\Total\Quote\Tax"/>
Now create your class file Tax.php and add below code:现在创建您的类文件 Tax.php 并添加以下代码:
namespace <yournamespace>\<yourModule>\Model\Sales\Total\Quote;
class Tax extends \Magento\Tax\Model\Sales\Total\Quote\Tax
{
/* override code here */
public function __construct(
/* add dependency classes here */ ) {
parent::__construct(
/* parent class objects here */
);
}
/**
* Custom Collect tax totals for quote address
*
* @param Quote $quote
* @param ShippingAssignmentInterface $shippingAssignment
* @param Address\Total $total
* @return $this
*/
public function collect(
\Magento\Quote\Model\Quote $quote,
\Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment,
\Magento\Quote\Model\Quote\Address\Total $total
) {
/* your calculation here goes here */
$total->setTaxAmount($set_your_tax_here);
return $this;
}
}
Hope this helps!希望这可以帮助!
Yes you can.... You can use default FPT and can modify tax amount as per your need.是的,您可以....您可以使用默认的 FPT 并可以根据需要修改税额。 you can use sales_quote_collect_totals_after event to change product tax amount programmatically.您可以使用 sales_quote_collect_totals_after 事件以编程方式更改产品税额。
This answer you can also try inside above overrided Tax model , it works fine.您也可以在上面覆盖的税收模型中尝试这个答案,它工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.