Description
/**
* KANALPHA – Fiche produit B2B (UX packs grammes -> total poids + total prix, AJAX add to cart)
*
* Shortcode:
* – Sur une page produit : [kanalpha_b2b_product]
* – Ou en forçant un produit : [kanalpha_b2b_product id= »881″]
*
* Hypothèse: le prix du produit est un « prix par gramme », et le stock est géré en « grammes » (qty = grammes).
*/
add_action(‘wp_ajax_kanalpha_b2b_add_to_cart’, ‘kanalpha_b2b_add_to_cart’);
add_action(‘wp_ajax_nopriv_kanalpha_b2b_add_to_cart’, ‘kanalpha_b2b_add_to_cart’);
function kanalpha_nbsp_int($n){
if (!is_numeric($n)) return »;
$s = number_format((float)$n, 0, », ‘ ‘);
return str_replace(‘ ‘, « \xC2\xA0″, $s);
}
function kanalpha_format_weight_label($grams){
$g = (int)$grams;
if ($g >= 1000 && $g % 1000 === 0){
$kg = (int)($g / 1000);
return $kg . » kg »;
}
return $g . » g »;
}
function kanalpha_money($amount){
// format € FR (simple)
return number_format((float)$amount, 2, ‘,’, ‘ ‘) . » € »;
}
function kanalpha_b2b_add_to_cart(){
$nonce = isset($_POST[‘nonce’]) ? sanitize_text_field($_POST[‘nonce’]) : »;
if (!wp_verify_nonce($nonce, ‘kanalpha_b2b_product_nonce’)) {
wp_send_json_error(array(‘message’=>’bad_nonce’));
}
if (!class_exists(‘WC’)) wp_send_json_error(array(‘message’=>’no_wc’));
$product_id = isset($_POST[‘product_id’]) ? (int)$_POST[‘product_id’] : 0;
$grams = isset($_POST[‘grams’]) ? (int)$_POST[‘grams’] : 0;
if (!$product_id || $grams < 1) {
wp_send_json_error(array(‘message’=>’bad_params’));
}
$product = wc_get_product($product_id);
if (!$product || !$product->is_purchasable()) {
wp_send_json_error(array(‘message’=>’not_purchasable’));
}
// Contrôle stock si géré
if ($product->managing_stock() && !$product->backorders_allowed()) {
$stock_qty = (int)$product->get_stock_quantity();
if ($stock_qty >= 0 && $grams > $stock_qty) {
wp_send_json_error(array(‘message’=>’not_enough_stock’));
}
}
$added = WC()->cart->add_to_cart($product_id, $grams);
if (!$added) {
wp_send_json_error(array(‘message’=>’add_failed’));
}
// Réponse légère (tu peux afficher ça où tu veux côté front)
wp_send_json_success(array(
‘count’ => WC()->cart->get_cart_contents_count(),
‘total’ => strip_tags(WC()->cart->get_cart_total()),
));
}
add_shortcode(‘kanalpha_b2b_product’, function($atts){
if (!class_exists(‘WooCommerce’)) return »;
$atts = shortcode_atts(array(
‘id’ => »,
‘pack_1’ => ‘100’,
‘pack_2’ => ‘500’,
‘pack_3’ => ‘1000’,
‘bg’ => ‘#000’,
‘fg’ => ‘#fff’,
), $atts, ‘kanalpha_b2b_product’);
global $product;
$product_id = (int)$atts[‘id’];
if (!$product_id && $product instanceof WC_Product) {
$product_id = $product->get_id();
}
if (!$product_id) return ‘<div>Produit introuvable.</div>’;
$product = wc_get_product($product_id);
if (!$product) return ‘<div>Produit introuvable.</div>’;
$uid = ‘kb2bp_’ . wp_generate_password(8, false, false);
$nonce = wp_create_nonce(‘kanalpha_b2b_product_nonce’);
// Données produit
$title = $product->get_name();
$short_desc = wp_kses_post(wpautop($product->get_short_description()));
$long_desc = wp_kses_post(wpautop($product->get_description()));
$per_gram_raw = (float) wc_get_price_to_display($product); // prix TTC affiché
$currency = get_woocommerce_currency_symbol();
// Stock en grammes (si géré)
$managing = $product->managing_stock();
$in_stock = $product->is_in_stock();
$stock_qty = null;
if ($managing) {
$sq = $product->get_stock_quantity();
if (is_numeric($sq)) $stock_qty = (int)$sq;
}
// Packs
$packs = array_unique(array(
max(1, (int)$atts[‘pack_1’]),
max(1, (int)$atts[‘pack_2’]),
max(1, (int)$atts[‘pack_3’]),
));
sort($packs);
// Images
$main_img_id = $product->get_image_id();
$gallery_ids = $product->get_gallery_image_ids();
$all_imgs = array();
if ($main_img_id) $all_imgs[] = $main_img_id;
foreach ($gallery_ids as $gid) {
if ($gid && $gid !== $main_img_id) $all_imgs[] = $gid;
}
if (empty($all_imgs)) {
// fallback : placeholder Woo
$all_imgs[] = 0;
}
// Attributs (table infos)
$attrs_rows = »;
$attributes = $product->get_attributes();
if (!empty($attributes)) {
foreach ($attributes as $attr) {
if ($attr->get_variation()) continue;
$name = wc_attribute_label($attr->get_name());
$values = array();
if ($attr->is_taxonomy()) {
$terms = wc_get_product_terms($product_id, $attr->get_name(), array(‘fields’ => ‘names’));
if (!is_wp_error($terms) && !empty($terms)) $values = $terms;
} else {
$values = $attr->get_options();
}
if (empty($values)) continue;
$attrs_rows .= ‘<tr><th>’.esc_html($name).'</th><td>’.esc_html(implode(‘, ‘, $values)).'</td></tr>’;
}
}
// B2BKing (si tu veux afficher la table existante — elle est souvent en double dans le DOM, donc on la scope)
// Sélecteur utile pour le style/JS si besoin : table.b2bking_tiered_price_table (vu dans ta base) :contentReference[oaicite:0]{index=0}
$b2bking_html = »;
if (shortcode_exists(‘b2bking_tiered_pricing_table’)) {
$b2bking_html = do_shortcode(‘[b2bking_tiered_pricing_table]’);
}
// Labels stock
$stock_line = »;
if ($in_stock) {
if ($managing && is_int($stock_qty)) {
$stock_line = ‘En stock : ‘ . kanalpha_nbsp_int($stock_qty) . ‘ g’;
} else {
$stock_line = ‘En stock’;
}
} else {
$stock_line = ‘Rupture’;
}
ob_start(); ?>
<section id= »<?php echo esc_attr($uid); ?> » class= »kb2bp » data-product-id= »<?php echo (int)$product_id; ?> »>
<div class= »kb2bp-wrap »>
<div class= »kb2bp-grid »>
<!– LEFT: images –>
<div class= »kb2bp-media »>
<div class= »kb2bp-mainimg » aria-label= »Image principale »>
<?php
$first = $all_imgs[0];
if ($first) {
$src = wp_get_attachment_image_url($first, ‘large’);
$alt = get_post_meta($first, ‘_wp_attachment_image_alt’, true);
echo ‘<img src= »‘.esc_url($src).' » alt= »‘.esc_attr($alt ?: $title).' »>’;
} else {
echo wc_placeholder_img(‘large’);
}
?>
</div>
<?php if (count($all_imgs) > 1): ?>
<div class= »kb2bp-thumbs » aria-label= »Miniatures »>
<?php foreach ($all_imgs as $i => $img_id): ?>
<?php
$thumb_src = $img_id ? wp_get_attachment_image_url($img_id, ‘woocommerce_thumbnail’) : wc_placeholder_img_src(‘woocommerce_thumbnail’);
$full_src = $img_id ? wp_get_attachment_image_url($img_id, ‘large’) : wc_placeholder_img_src(‘large’);
?>
<button type= »button »
class= »kb2bp-thumb <?php echo $i===0 ? ‘is-active’: »; ?> »
data-full= »<?php echo esc_url($full_src); ?> »
aria-label= »Voir image <?php echo (int)($i+1); ?> »>
<img src= »<?php echo esc_url($thumb_src); ?> » alt= » »>
</button>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<!– RIGHT: content –>
<div class= »kb2bp-content »>
<div class= »kb2bp-kicker »>Fiche produit B2B</div>
<h1 class= »kb2bp-title »><?php echo esc_html($title); ?></h1>
<div class= »kb2bp-meta »>
<div class= »kb2bp-pricegram »>
<span class= »kb2bp-pricegram-label »>Prix indicatif</span>
<span class= »kb2bp-pricegram-val »><?php echo esc_html(kanalpha_money($per_gram_raw)); ?> / g</span>
</div>
<div class= »kb2bp-stock »><?php echo esc_html($stock_line); ?></div>
</div>
<?php if (!empty($short_desc)): ?>
<div class= »kb2bp-short »><?php echo $short_desc; ?></div>
<?php endif; ?>
<div class= »kb2bp-buybox » aria-label= »Commande rapide »>
<div class= »kb2bp-row »>
<div class= »kb2bp-label »>Conditionnement</div>
<div class= »kb2bp-packs » role= »group » aria-label= »Choix du conditionnement »>
<?php foreach ($packs as $idx => $g): ?>
<?php
$disabled = false;
if ($managing && is_int($stock_qty) && $stock_qty >= 0) {
if ($g > $stock_qty) $disabled = true;
}
?>
<button type= »button »
class= »kb2bp-pack <?php echo $idx===0 ? ‘is-active’: »; ?> »
data-grams= »<?php echo (int)$g; ?> »
<?php echo $disabled ? ‘disabled’: »; ?>>
<?php echo esc_html(kanalpha_format_weight_label($g)); ?>
</button>
<?php endforeach; ?>
</div>
</div>
<div class= »kb2bp-row »>
<div class= »kb2bp-label »>Quantité (packs)</div>
<div class= »kb2bp-qty »>
<button type= »button » class= »kb2bp-qbtn » data-dir= »-1″ aria-label= »Diminuer »>−</button>
<input type= »number » class= »kb2bp-qinput » value= »1″ min= »1″ step= »1″ inputmode= »numeric »>
<button type= »button » class= »kb2bp-qbtn » data-dir= »1″ aria-label= »Augmenter »>+</button>
</div>
</div>
<div class= »kb2bp-totals » aria-label= »Totaux »>
<div class= »kb2bp-total »>
<div class= »kb2bp-total-label »>Poids total</div>
<div class= »kb2bp-total-val » data-kb2bp-total-grams>—</div>
</div>
<div class= »kb2bp-total »>
<div class= »kb2bp-total-label »>Total</div>
<div class= »kb2bp-total-val » data-kb2bp-total-price>—</div>
</div>
</div>
<div class= »kb2bp-actions »>
<button type= »button » class= »kb2bp-add » data-kb2bp-add>
Ajouter au panier
</button>
<div class= »kb2bp-status » data-kb2bp-status></div>
</div>
</div>
<?php if (!empty($b2bking_html)): ?>
<div class= »kb2bp-tierwrap » aria-label= »Paliers de prix »>
<div class= »kb2bp-tier-title »>Tarifs dégressifs</div>
<div class= »kb2bp-tier »><?php echo $b2bking_html; ?></div>
</div>
<?php endif; ?>
<div class= »kb2bp-tabs » aria-label= »Détails »>
<div class= »kb2bp-tabhead »>
<button type= »button » class= »kb2bp-tab is-active » data-tab= »desc »>Description</button>
<button type= »button » class= »kb2bp-tab » data-tab= »info »>Informations</button>
</div>
<div class= »kb2bp-tabpanes »>
<div class= »kb2bp-pane is-active » data-pane= »desc »>
<?php echo $long_desc ?: ‘<p>—</p>’; ?>
</div>
<div class= »kb2bp-pane » data-pane= »info »>
<?php if (!empty($attrs_rows)): ?>
<div class= »kb2bp-tablewrap »>
<table class= »kb2bp-table »>
<tbody><?php echo $attrs_rows; ?></tbody>
</table>
</div>
<?php else: ?>
<p>—</p>
<?php endif; ?>
</div>
</div>
</div>
</div>
</div>
</div>
<style>
/* Scope strict */
#<?php echo esc_attr($uid); ?>{ background:#000; color:#fff; padding:72px 0; }
#<?php echo esc_attr($uid); ?> .kb2bp-wrap{ width:min(1180px, 92%); margin:0 auto; }
#<?php echo esc_attr($uid); ?> .kb2bp-grid{
display:grid;
grid-template-columns: 1.05fr 0.95fr;
gap:48px;
align-items:start;
}
/* Media */
#<?php echo esc_attr($uid); ?> .kb2bp-mainimg{
border-radius:12px;
overflow:hidden;
background:#fff;
}
#<?php echo esc_attr($uid); ?> .kb2bp-mainimg img{
width:100%;
height:auto;
display:block;
aspect-ratio: 1 / 1;
object-fit:cover;
}
#<?php echo esc_attr($uid); ?> .kb2bp-thumbs{
margin-top:14px;
display:flex;
gap:10px;
flex-wrap:wrap;
}
#<?php echo esc_attr($uid); ?> .kb2bp-thumb{
padding:0;
border:0;
background:transparent;
cursor:pointer;
border-radius:10px;
overflow:hidden;
}
#<?php echo esc_attr($uid); ?> .kb2bp-thumb img{
width:58px; height:58px; object-fit:cover; display:block;
border-radius:10px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-thumb.is-active img{
outline: 1px solid rgba(255,255,255,0.55);
outline-offset: 2px;
}
/* Content */
#<?php echo esc_attr($uid); ?> .kb2bp-kicker{
font-family:’Inter’,sans-serif;
font-size:12px;
letter-spacing:0.14em;
text-transform:uppercase;
opacity:0.72;
margin-bottom:10px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-title{
margin:0 0 14px 0;
font-family:’Cormorant Garamond’,serif;
font-weight:600;
letter-spacing:0.04em;
text-transform:uppercase;
font-size:44px;
line-height:1.05;
}
#<?php echo esc_attr($uid); ?> .kb2bp-meta{
display:flex;
gap:16px;
align-items:flex-end;
justify-content:space-between;
padding-bottom:16px;
border-bottom:1px solid rgba(255,255,255,0.10);
margin-bottom:18px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-pricegram-label{
font-family:’Inter’,sans-serif;
font-size:12px;
letter-spacing:0.12em;
text-transform:uppercase;
opacity:0.65;
display:block;
margin-bottom:6px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-pricegram-val{
font-family:’Inter’,sans-serif;
font-size:16px;
opacity:0.92;
}
#<?php echo esc_attr($uid); ?> .kb2bp-stock{
font-family:’Inter’,sans-serif;
font-size:13px;
opacity:0.75;
text-align:right;
white-space:nowrap;
}
#<?php echo esc_attr($uid); ?> .kb2bp-short{
font-family:’Inter’,sans-serif;
font-size:16px;
line-height:1.7;
opacity:0.92;
margin-bottom:22px;
}
/* Buy box */
#<?php echo esc_attr($uid); ?> .kb2bp-buybox{
background: rgba(255,255,255,0.03);
border: 1px solid rgba(255,255,255,0.10);
border-radius:12px;
padding:18px;
margin: 8px 0 22px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-row{
display:flex;
align-items:center;
justify-content:space-between;
gap:16px;
padding:12px 0;
border-bottom:1px solid rgba(255,255,255,0.08);
}
#<?php echo esc_attr($uid); ?> .kb2bp-row:last-of-type{
border-bottom:0;
}
#<?php echo esc_attr($uid); ?> .kb2bp-label{
font-family:’Inter’,sans-serif;
font-size:12px;
letter-spacing:0.12em;
text-transform:uppercase;
opacity:0.68;
min-width:150px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-packs{
display:flex; gap:10px; flex-wrap:wrap; justify-content:flex-end;
}
#<?php echo esc_attr($uid); ?> .kb2bp-pack{
height:40px;
padding:0 12px;
border-radius:8px; /* moins arrondi */
border:1px solid rgba(255,255,255,0.35);
background:transparent;
color:#fff;
cursor:pointer;
font-family:’Inter’,sans-serif;
font-size:13px;
letter-spacing:0.02em;
}
#<?php echo esc_attr($uid); ?> .kb2bp-pack.is-active{
border-color: rgba(255,255,255,0.85);
}
#<?php echo esc_attr($uid); ?> .kb2bp-pack:disabled{
opacity:0.35;
cursor:not-allowed;
}
#<?php echo esc_attr($uid); ?> .kb2bp-qty{
display:flex;
align-items:center;
gap:10px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-qbtn{
width:40px; height:40px;
border-radius:8px;
border:1px solid rgba(255,255,255,0.35);
background:transparent;
color:#fff;
cursor:pointer;
font-size:18px;
line-height:1;
}
#<?php echo esc_attr($uid); ?> .kb2bp-qinput{
width:72px; height:40px;
border-radius:8px;
border:1px solid rgba(255,255,255,0.35);
background:transparent;
color:#fff;
text-align:center;
font-family:’Inter’,sans-serif;
font-size:14px;
outline:none;
}
#<?php echo esc_attr($uid); ?> .kb2bp-totals{
display:grid;
grid-template-columns: 1fr 1fr;
gap:12px;
margin-top:14px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-total{
background: rgba(255,255,255,0.03);
border:1px solid rgba(255,255,255,0.08);
border-radius:12px;
padding:12px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-total-label{
font-family:’Inter’,sans-serif;
font-size:12px;
letter-spacing:0.12em;
text-transform:uppercase;
opacity:0.65;
margin-bottom:8px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-total-val{
font-family:’Inter’,sans-serif;
font-size:16px;
opacity:0.92;
}
#<?php echo esc_attr($uid); ?> .kb2bp-actions{
display:flex;
align-items:center;
justify-content:space-between;
gap:14px;
margin-top:16px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-add{
height:46px;
padding:0 16px;
border-radius:8px;
border:1px solid rgba(255,255,255,0.85);
background:transparent;
color:#fff;
cursor:pointer;
font-family:’Inter’,sans-serif;
font-size:14px;
letter-spacing:0.02em;
white-space:nowrap;
}
#<?php echo esc_attr($uid); ?> .kb2bp-status{
font-family:’Inter’,sans-serif;
font-size:13px;
opacity:0.80;
text-align:right;
min-height:18px;
}
/* Tiered pricing */
#<?php echo esc_attr($uid); ?> .kb2bp-tierwrap{
margin-top:18px;
padding-top:18px;
border-top:1px solid rgba(255,255,255,0.10);
}
#<?php echo esc_attr($uid); ?> .kb2bp-tier-title{
font-family:’Cormorant Garamond’,serif;
font-weight:600;
letter-spacing:0.04em;
text-transform:uppercase;
font-size:18px;
margin-bottom:10px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-tier{
overflow-x:auto;
-webkit-overflow-scrolling: touch;
}
#<?php echo esc_attr($uid); ?> table.b2bking_tiered_price_table{
width:100%;
border-collapse:collapse;
font-family:’Inter’,sans-serif;
font-size:13px;
}
#<?php echo esc_attr($uid); ?> table.b2bking_tiered_price_table th,
#<?php echo esc_attr($uid); ?> table.b2bking_tiered_price_table td{
padding:10px 12px;
border-bottom:1px solid rgba(255,255,255,0.10);
color:#fff;
}
/* Tabs */
#<?php echo esc_attr($uid); ?> .kb2bp-tabs{
margin-top:22px;
border-top:1px solid rgba(255,255,255,0.10);
padding-top:18px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-tabhead{
display:flex;
gap:10px;
flex-wrap:wrap;
margin-bottom:14px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-tab{
height:40px;
padding:0 12px;
border-radius:8px;
border:1px solid rgba(255,255,255,0.35);
background:transparent;
color:#fff;
cursor:pointer;
font-family:’Inter’,sans-serif;
font-size:13px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-tab.is-active{
border-color: rgba(255,255,255,0.85);
}
#<?php echo esc_attr($uid); ?> .kb2bp-pane{
display:none;
font-family:’Inter’,sans-serif;
font-size:15px;
line-height:1.75;
opacity:0.92;
}
#<?php echo esc_attr($uid); ?> .kb2bp-pane.is-active{ display:block; }
#<?php echo esc_attr($uid); ?> .kb2bp-tablewrap{
overflow-x:auto;
-webkit-overflow-scrolling:touch;
}
#<?php echo esc_attr($uid); ?> .kb2bp-table{
width:100%;
border-collapse:collapse;
font-family:’Inter’,sans-serif;
font-size:13px;
}
#<?php echo esc_attr($uid); ?> .kb2bp-table th,
#<?php echo esc_attr($uid); ?> .kb2bp-table td{
padding:10px 12px;
border-bottom:1px solid rgba(255,255,255,0.10);
text-align:left;
vertical-align:top;
}
#<?php echo esc_attr($uid); ?> .kb2bp-table th{ width:38%; opacity:0.78; font-weight:500; }
/* Responsive */
@media (max-width:980px){
#<?php echo esc_attr($uid); ?>{ padding:56px 0; }
#<?php echo esc_attr($uid); ?> .kb2bp-grid{ grid-template-columns: 1fr; gap:22px; }
#<?php echo esc_attr($uid); ?> .kb2bp-title{ font-size:34px; }
#<?php echo esc_attr($uid); ?> .kb2bp-label{ min-width:120px; }
#<?php echo esc_attr($uid); ?> .kb2bp-meta{ align-items:flex-start; }
#<?php echo esc_attr($uid); ?> .kb2bp-stock{ text-align:left; }
}
</style>
<script>
(function(){
const root = document.getElementById(‘<?php echo esc_js($uid); ?>’);
if(!root) return;
const ajaxUrl = « <?php echo esc_js(admin_url(‘admin-ajax.php’)); ?> »;
const nonce = « <?php echo esc_js($nonce); ?> »;
const productId = parseInt(root.getAttribute(‘data-product-id’), 10);
const pricePerGram = <?php echo json_encode($per_gram_raw); ?>; // float
const currency = <?php echo json_encode($currency); ?>;
const mainImg = root.querySelector(‘.kb2bp-mainimg img’);
const thumbs = Array.from(root.querySelectorAll(‘.kb2bp-thumb’));
const packBtns = Array.from(root.querySelectorAll(‘.kb2bp-pack’));
const qtyInput = root.querySelector(‘.kb2bp-qinput’);
const qtyBtns = Array.from(root.querySelectorAll(‘.kb2bp-qbtn’));
const totalGramsEl = root.querySelector(‘[data-kb2bp-total-grams]’);
const totalPriceEl = root.querySelector(‘[data-kb2bp-total-price]’);
const addBtn = root.querySelector(‘[data-kb2bp-add]’);
const statusEl = root.querySelector(‘[data-kb2bp-status]’);
const tabBtns = Array.from(root.querySelectorAll(‘.kb2bp-tab’));
const panes = Array.from(root.querySelectorAll(‘.kb2bp-pane’));
function nfMoney(v){
try{
return new Intl.NumberFormat(‘fr-FR’, { style:’currency’, currency:’EUR’ }).format(v);
}catch(e){
return (Math.round(v*100)/100).toFixed(2) + ‘ ‘ + currency;
}
}
function formatWeight(grams){
const g = Math.max(0, parseInt(grams||0,10));
if(g >= 1000 && g % 1000 === 0) return (g/1000) + ‘ kg’;
return g.toLocaleString(‘fr-FR’) + ‘ g’;
}
function getActivePack(){
const b = packBtns.find(x => x.classList.contains(‘is-active’));
return b ? parseInt(b.getAttribute(‘data-grams’),10) : parseInt(packBtns[0]?.getAttribute(‘data-grams’)||’100′,10);
}
function setStatus(msg){
if(statusEl) statusEl.textContent = msg || »;
}
function clampQty(){
let q = parseInt(qtyInput.value||’1′,10);
if(!Number.isFinite(q) || q < 1) q = 1;
qtyInput.value = String(q);
return q;
}
function updateTotals(){
const pack = getActivePack();
const q = clampQty();
const grams = pack * q;
const total = grams * pricePerGram;
if(totalGramsEl) totalGramsEl.textContent = formatWeight(grams);
if(totalPriceEl) totalPriceEl.textContent = nfMoney(total);
}
// Thumbs
thumbs.forEach(btn=>{
btn.addEventListener(‘click’, ()=>{
const full = btn.getAttribute(‘data-full’);
if(mainImg && full){
mainImg.src = full;
}
thumbs.forEach(t=>t.classList.remove(‘is-active’));
btn.classList.add(‘is-active’);
});
});
// Packs
packBtns.forEach(b=>{
b.addEventListener(‘click’, ()=>{
if(b.disabled) return;
packBtns.forEach(x=>x.classList.remove(‘is-active’));
b.classList.add(‘is-active’);
updateTotals();
});
});
// Qty
qtyBtns.forEach(b=>{
b.addEventListener(‘click’, ()=>{
const dir = parseInt(b.getAttribute(‘data-dir’)||’0′,10);
let q = clampQty();
q = q + dir;
if(q < 1) q = 1;
qtyInput.value = String(q);
updateTotals();
});
});
qtyInput.addEventListener(‘input’, updateTotals);
qtyInput.addEventListener(‘change’, updateTotals);
// Tabs
tabBtns.forEach(btn=>{
btn.addEventListener(‘click’, ()=>{
const tab = btn.getAttribute(‘data-tab’);
tabBtns.forEach(x=>x.classList.remove(‘is-active’));
btn.classList.add(‘is-active’);
panes.forEach(p=>{
p.classList.toggle(‘is-active’, p.getAttribute(‘data-pane’) === tab);
});
});
});
// Add to cart (grams total)
addBtn.addEventListener(‘click’, async ()=>{
setStatus( »);
addBtn.disabled = true;
const pack = getActivePack();
const q = clampQty();
const grams = pack * q;
const form = new FormData();
form.append(‘action’, ‘kanalpha_b2b_add_to_cart’);
form.append(‘nonce’, nonce);
form.append(‘product_id’, String(productId));
form.append(‘grams’, String(grams));
try{
const res = await fetch(ajaxUrl, { method:’POST’, body: form });
const json = await res.json();
if(json && json.success){
setStatus(‘Ajouté au panier.’);
} else {
const m = (json && json.data && json.data.message) ? json.data.message : ‘Erreur’;
if(m === ‘not_enough_stock’) setStatus(‘Stock insuffisant pour cette quantité.’);
else if(m === ‘not_purchasable’) setStatus(‘Produit indisponible.’);
else setStatus(‘Erreur lors de l’ajout.’);
}
}catch(e){
setStatus(‘Erreur lors de l’ajout.’);
}
addBtn.disabled = false;
});
updateTotals();
})();
</script>
</section>
<?php
return ob_get_clean();
});

Avis
Il n’y a pas encore d’avis.