Last active
October 22, 2022 23:31
-
-
Save hassamulhaq/2dd7ab0e8056f92ea1dcce99e94f1989 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Helpers; | |
class VAT_Helper | |
{ | |
const VAT_PERCENTAGE = 20; | |
} | |
// ------------------------------------- | |
?> | |
<?php | |
namespace App\Traits; | |
use App\Helpers\VAT_Helper; | |
trait VAT_Trait | |
{ | |
public function calcAddVatToAmount(float $amount, int $vat_percentage = VAT_Helper::VAT_PERCENTAGE): float|int | |
{ | |
return round($amount * (1 + $vat_percentage / 100), 2); | |
// e.g Gross amount: 10.80 | |
} | |
public function calcVatAddedValue(float $amount, int $vat_percentage = VAT_Helper::VAT_PERCENTAGE): float | |
{ | |
$amount_including_vat = $this->calcAddVatToAmount($amount, $vat_percentage); | |
return round($amount_including_vat - $amount, 2); | |
// e.g VAT added: 1.80 | |
} | |
public function calcExcludeVatFromAmount(float $amount, int $vat_percentage = VAT_Helper::VAT_PERCENTAGE): float|int | |
{ | |
return round($amount - $amount / (1 + $vat_percentage / 100), 2); | |
// e.g Net amount: 7.50 | |
} | |
public function calcVatExcludedValue(float $amount, int $vat_percentage = VAT_Helper::VAT_PERCENTAGE): float|int | |
{ | |
return round($amount - $amount / (1 + $vat_percentage / 100), 2); | |
// e.g VAT excluded: 1.50 | |
} | |
} | |
// --------------------------------------------------- | |
?> | |
<!-- How to use --> | |
<?php | |
namespace App\Http\Services; | |
use App\Helpers\VAT_Helper; | |
class CartService | |
{ | |
use VAT_Trait; | |
const VAT_PERCENTAGE = 20; // you can skip this because default VAT percentage added i VAT_Trait. | |
public function createCartItem(Request $request) | |
{ | |
$product_price = $request->input('product_price'); // e.g 9$ | |
$cartItem = CartItem::create([ | |
'product_id' => $request->input('product_id'), | |
'sku' => $request->input('sku'), | |
'total_weight' => $request->input('weight') * $request->input('quantity'), | |
// single amount | |
'price' => (float) $this->calcAddVatToAmount($product_price, VAT_Helper::VAT_PERCENTAGE), // 2nd parameter is optional | |
// single amount * quantity | |
'total' => (float) $this->calcAddVatToAmount($product_price * 5, VAT_Helper::VAT_PERCENTAGE), | |
// check how much VAT added on single amount | |
'tax_amount' => (float) $this->calcVatAddedValue($product_price, VAT_Helper::VAT_PERCENTAGE), | |
// check how much VAT added on (single amount * quantity) | |
'total_tax_amount' => (float) $this->calcVatAddedValue($product_price * 5, VAT_Helper::VAT_PERCENTAGE), | |
]); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment