Разделение налога Woocommerce на один и тот же продуктPhp

Кемеровские программисты php общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Разделение налога Woocommerce на один и тот же продукт

Сообщение Anonymous »

Из-за некоторых сложных налоговых правил нам необходимо разделить налоги внутри одного продукта Woocommerce. Речь идет об онлайн-курсах, которые сочетают в себе уроки вживую и по запросу, где живая часть не облагается налогом, а часть по запросу имеет определенную налоговую ставку. Ставка налога варьируется в зависимости от страны и статуса пользователя (частный/бизнес).
например. обычная цена продукта составляет 750 евро, цена продажи 700. Налогооблагаемая часть обычной цены составляет 200 евро, налогооблагаемая часть продажной цены составляет 150 евро. Таким образом, продукт должен облагаться налогом 0% на 550 евро и налогом 19% (или ставкой соответствующей страны) на 200 евро (или 150 евро при продаже).
Мой подход на данный момент таков. реализовать дополнительные поля в мета-продукте, чтобы определить налогооблагаемую часть цены продукта (одно для части обычной цены и одно для части продажной цены) и объединить их со стандартными налоговыми ставками, поддерживаемыми в Woocommerce. Таким образом, я могу пересчитать налог в корзине и при оформлении заказа, но это конфликтует в представлении заказа администратора и в других местах.
есть идеи, как подойти к этому более разумно? Спасибо за вашу помощь!
Это мой подход на данный момент:
// Debugging und Initialisierung
add_action('init', 'check_hook_registration');
function check_hook_registration()
{
error_log('Hooks registered: ' . (has_filter('woocommerce_cart_totals_taxes_total_html', 'ysf_adjust_cart_totals_taxes') ? 'Yes' : 'No'));
}

// Hinzufügen der benutzerdefinierten Felder zum Produkt
add_action('woocommerce_product_options_pricing', 'ysf_add_tax_free_fields');
function ysf_add_tax_free_fields()
{
woocommerce_wp_text_input(array(
'id' => 'tax_free_regular_price',
'class' => 'wc_input_price short',
'label' => __('Steuerfreier Anteil regulärer Preis in €', 'yogafox'),
'description' => __('Gib den steuerfreien Anteil des regulären Preises in € ein', 'yogafox'),
'desc_tip' => true,
'type' => 'number',
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
));

woocommerce_wp_text_input(array(
'id' => 'tax_free_sale_price',
'class' => 'wc_input_price short',
'label' => __('Steuerfreier Anteil Angebotspreis in €', 'yogafox'),
'description' => __('Gib den steuerfreien Anteil des Angebotspreises in € ein', 'yogafox'),
'desc_tip' => true,
'type' => 'number',
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
));

woocommerce_wp_text_input(array(
'id' => 'tax_free_description',
'class' => 'short',
'label' => __('Beschreibung steuerfreier Anteil', 'yogafox'),
'description' => __('Beschreibe den steuerfreien Anteil', 'yogafox'),
'desc_tip' => true,
'type' => 'text',
));

woocommerce_wp_text_input(array(
'id' => 'taxable_description',
'class' => 'short',
'label' => __('Beschreibung steuerpflichtiger Anteil', 'yogafox'),
'description' => __('Beschreibe den steuerpflichtigen Anteil', 'yogafox'),
'desc_tip' => true,
'type' => 'text',
));
}

// Speichern der benutzerdefinierten Felder im Produkt
add_action('woocommerce_admin_process_product_object', 'ysf_save_tax_free_fields');
function ysf_save_tax_free_fields($product)
{
if (isset($_POST['tax_free_regular_price'])) {
$product->update_meta_data('tax_free_regular_price', sanitize_text_field($_POST['tax_free_regular_price']));
}
if (isset($_POST['tax_free_sale_price'])) {
$product->update_meta_data('tax_free_sale_price', sanitize_text_field($_POST['tax_free_sale_price']));
}
if (isset($_POST['tax_free_description'])) {
$product->update_meta_data('tax_free_description', sanitize_text_field($_POST['tax_free_description']));
}
if (isset($_POST['taxable_description'])) {
$product->update_meta_data('taxable_description', sanitize_text_field($_POST['taxable_description']));
}
}

// Überprüfen, ob ein Produkt steuerfreie Beträge hat
function ysf_has_tax_free_amount($product)
{
$tax_free_amount = floatval($product->get_meta('tax_free_' . ($product->is_on_sale() ? 'sale' : 'regular') . '_price'));
return $tax_free_amount > 0;
}

// Berechnung der angepassten Steuer
function ysf_calculate_adjusted_tax($price, $tax_free_amount, $tax_rate)
{
$taxable_amount = $price - $tax_free_amount;
return $taxable_amount * ($tax_rate / (1 + $tax_rate));
}

// Anpassung der Steuerberechnung für Warenkorb-Artikel
add_filter('woocommerce_product_get_price_including_tax', 'ysf_adjust_product_price_including_tax', 10, 3);
function ysf_adjust_product_price_including_tax($price, $qty, $product)
{
if (ysf_has_tax_free_amount($product)) {
$tax_free_amount = floatval($product->get_meta('tax_free_' . ($product->is_on_sale() ? 'sale' : 'regular') . '_price'));
$tax_rates = WC_Tax::get_rates($product->get_tax_class());
$tax_rate = reset($tax_rates)['rate'] / 100;

$adjusted_tax = ysf_calculate_adjusted_tax($price, $tax_free_amount, $tax_rate);
return $price - ($price - $tax_free_amount) + $adjusted_tax;
}
return $price;
}

// Anpassung der Anzeige der Warenkorb-Artikelpreise
add_filter('woocommerce_cart_item_price', 'ysf_adjust_cart_item_price', 10, 3);
function ysf_adjust_cart_item_price($price_html, $cart_item, $cart_item_key)
{
$product = $cart_item['data'];
if (ysf_has_tax_free_amount($product)) {
$price = $product->get_price();
$tax_free_amount = floatval($product->get_meta('tax_free_' . ($product->is_on_sale() ? 'sale' : 'regular') . '_price'));
$tax_rates = WC_Tax::get_rates($product->get_tax_class());
$tax_rate = reset($tax_rates)['rate'] / 100;

$adjusted_tax = ysf_calculate_adjusted_tax($price, $tax_free_amount, $tax_rate);

$tax_free_description = $product->get_meta('tax_free_description');
$taxable_description = $product->get_meta('taxable_description');

$price_html .= '
';
$price_html .= sprintf(__('%s: %s', 'yogafox'), $tax_free_description, wc_price($tax_free_amount)) . '
';
$price_html .= sprintf(
__('%s: %s (inkl. %s%% MwSt: %s)', 'yogafox'),
$taxable_description,
wc_price($price - $tax_free_amount),
number_format($tax_rate * 100, 2),
wc_price($adjusted_tax)
);
$price_html .= '';
}
return $price_html;
}

// Anpassung der Steuerberechnung für den gesamten Warenkorb
add_filter('woocommerce_cart_get_taxes', 'ysf_adjust_cart_taxes', 10, 2);
function ysf_adjust_cart_taxes($taxes, $cart)
{
$adjusted_taxes = array();
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
$product = $cart_item['data'];
if (ysf_has_tax_free_amount($product)) {
$price = $product->get_price();
$tax_free_amount = floatval($product->get_meta('tax_free_' . ($product->is_on_sale() ? 'sale' : 'regular') . '_price'));
$tax_rates = WC_Tax::get_rates($product->get_tax_class());
$tax_rate = reset($tax_rates)['rate'] / 100;

$adjusted_tax = ysf_calculate_adjusted_tax($price, $tax_free_amount, $tax_rate) * $cart_item['quantity'];

$rate_id = key($tax_rates);
if (!isset($adjusted_taxes[$rate_id])) {
$adjusted_taxes[$rate_id] = 0;
}
$adjusted_taxes[$rate_id] += $adjusted_tax;
} else {
$item_taxes = WC_Tax::calc_tax($cart_item['line_total'], WC_Tax::get_rates($product->get_tax_class()), true);
foreach ($item_taxes as $rate_id => $tax) {
if (!isset($adjusted_taxes[$rate_id])) {
$adjusted_taxes[$rate_id] = 0;
}
$adjusted_taxes[$rate_id] += $tax;
}
}
}
return $adjusted_taxes;
}

// Anpassung der Steueranzeige im Warenkorb und an der Kasse
add_filter('woocommerce_cart_totals_taxes_total_html', 'ysf_adjust_cart_totals_taxes', 10, 2);
function ysf_adjust_cart_totals_taxes($tax_total_html, $cart)
{
$adjusted_taxes = ysf_adjust_cart_taxes(array(), $cart);
$adjusted_tax_total = array_sum($adjusted_taxes);
return wc_price($adjusted_tax_total);
}



Подробнее здесь: https://stackoverflow.com/questions/787 ... me-product
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Php»