Jump to content

RockCommerce gross prices by default - my implementation


gebeer
 Share

Recommended Posts

Hi @bernhard,

in the docs-old folder of the module there is a nice section about prices. It says that we can switch to gross prices with a config setting.

I was not so sure whether that still applies and how it works with the cart calculations. So I just wanted to share my custom implementation, so that editors can enter gross price and net price will be calculated.

I added a field (type RockMoney) "price_gross" in addition to the "rockcommerce_net" field to my product template. And in my ProductPage class, I have a saveReady hook that calculates the net price from the gross price and the vat for that product.

 

    /**
     * Calculates the taxrate of the product
     * based on the taxrate field of the product
     * if no custom taxrate is set, the global taxrate is used
     *
     * @return float
     */
    public function getTaxrate(): float
    {
        return (float) $this->rockcommerce_taxrate ? $this->rockcommerce_taxrate/100 : $this->taxrate();
    }


    /**
     * Executes when the page is ready to be saved.
     * 
     * Only executes if price_gross is given and field rockcommerce_net is present. 
     * Calculates the net price and VAT based on the gross price
     * and tax rate, if a gross price is provided.
     * It saves the net price to rockcommerce_net.
     *
     * @return void
     */
    public function onSaveReady(): void
    {  
        // only execute if we have price_gross
        if ($this->price_gross && $this->template->hasField('rockcommerce_net')) {
            // take price_gross and calculate vat and net price from it using taxrate
            $taxrate = $this->getTaxrate();
            $vat = rockmoney()->parse($this->price_gross)->times($taxrate / (1 + $taxrate));
            /** @var \RockMoney\Money */
            $priceNet = rockmoney()->parse($this->price_gross)->minus($vat);
            $this->rockcommerce_net = $priceNet->getFloat();
        }
    }

I also use a custom getTaxrate() method from my page class, in case a custom rate is set for that product.

Page edit screen

image.thumb.png.4efec4952a42be8d44471166239bd4c5.png

  • Like 2
  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...