webdna / commerce-bulk-pricing

Other
2 stars 2 forks source link

Getting the bulk discount (sale) price if it is part of a sale? #11

Open terryupton opened 2 years ago

terryupton commented 2 years ago

Is there a way get the bulk discount sale price for showing this in a template? Similar to the native selectedVariant.salePrice ? If not could it be possible to add a twig variable to get this value, so it can be used on the front-end templates?

Thanks, Terry

terryupton commented 2 years ago

Hi Guys. Ate there any thoughts on this please? is it possible? Is this plugin still maintained?

Thanks.

mcjackson18 commented 2 years ago

@terryupton, the plugin doesn't have this feature at the moment, we can add this feature request to the roadmap.

In the meantime, this can be done by creating a variable in a custom module.

Not fully tested but a method like this should work:

public function getSalePrice($purcharchableId,$qty,$currency)
{    
    $price = 0;    
    $purchasable = Variant::find()
                    ->id($purcharchableId)
                    ->one();

    if($purchasable) {

        $price = $purchasable->salePrice;

        if($product = $purchasable->getProduct()) { // you only need this line if the bulk pricing field is on a product and not the variant
            foreach($product->getFieldValues() as $key => $field) { //change this to $purchasable->getFieldValues() if the bulk pricing field is on the variant and not the product
                if( (get_class(Craft::$app->getFields()->getFieldByHandle($key)) == 'kuriousagency\\commerce\\bulkpricing\\fields\\BulkPricingField') && (is_array($field)) && (array_key_exists($currency,$field)) ) {
                    foreach ($field[$currency] as $fieldQty => $value) {                        
                        if ($fieldQty != 'iso' && $qty >= $fieldQty && $value != '') {
                            $price = $value;
                        }
                    }
                    continue;
                }
            }
        }
    }

    return $price;

}

In your twig template:

{% set salePrice = craft.moduleName.getSalePrice(purcharchableId,qty,currency) %}