function calcNewQuantityBook($currentValue, $trigger, $value){ let $newQty = 0; switch ($trigger.trim().toLowerCase()){ case 'btn-add': $newQty = $currentValue + $value; break; case 'btn-remove': $newQty = $currentValue - $value; break; case 'input-book': $newQty = $currentValue; break; } return $newQty; } function aDecimaleSemplice(valore) { const num = Number(valore); if (isNaN(num)) return valore; return Math.trunc(num); } function adjustQuantityBooks($qty, $min_qty, $max_qty){ if(aDecimaleSemplice($qty) > $max_qty){ return { qty: $max_qty, message_adjust_qty: `${$qty} items are not available. \n We have updated your quantity to ${$max_qty} , the maximum orderable quantity for this book.` }; } else if (aDecimaleSemplice($qty) < $min_qty){ return { qty: $min_qty, message_adjust_qty: `${$qty} items are not available. \n We have updated your quantity to ${$min_qty} , the minimum orderable quantity for this book.` }; } else { return { qty: aDecimaleSemplice($qty), message_adjust_qty: `` }; } } function updateInputQty($qty, $el){ $el.val( $qty ); } function updateBtnBooks($el, $btns){ if($btns.disable.add.value == true){ $("." + $btns.disable.add.el).prop("disabled", true).addClass("disabled-btn-book"); } if($btns.disable.remove.value == true){ $("." + $btns.disable.remove.el).prop("disabled", true).addClass("disabled-btn-book"); } if($btns.disable.add.value == false){ $("." + $btns.disable.add.el).prop("disabled", false).removeClass("disabled-btn-book"); } if($btns.disable.remove.value == false){ $("." + $btns.disable.remove.el).prop("disabled", false).removeClass("disabled-btn-book"); } } function updateCountBook(count_book){ $('.js-count-items-cart').html(count_book); } function updateAllInputSameBook($book_id, $newQtyConfirmed){ $(".inputQtyBook"+$book_id).val($newQtyConfirmed); } function updateDocumentElementsWithBookCartId($book_id, $book_cart_id){ $(".inputQtyBook"+$book_id).data("book-cart-id", $book_cart_id); $(".btnAddBook"+$book_id).data("book-cart-id", $book_cart_id); $(".btnRemoveBook"+$book_id).data("book-cart-id", $book_cart_id); $(".inputQtyBook"+$book_id).attr("data-book-cart-id", $book_cart_id); $(".btnAddBook"+$book_id).attr("data-book-cart-id", $book_cart_id); $(".btnRemoveBook"+$book_id).attr("data-book-cart-id", $book_cart_id); } function updateBookQty($warehouse_id, $book_id, $newQtyConfirmed, $input_qta_book_id, $el, $max_qty, $modal_alert, $book_name, $book_cart_id, $loader, $page){ $.ajax({ url: 'https://staging-fabrics.piacenza1733.com/assets/ajax/cartBookUpdate.php', type: 'POST', data: { book_id: $book_id, book_cart_id: $book_cart_id, warehouse_id: $warehouse_id, company_address_id: -1, quantity: $newQtyConfirmed.qty, message_adjust_qty: $newQtyConfirmed.message_adjust_qty, max_qty: $max_qty, book_name: $book_name, page: $page }, beforeSend: function (data) { if(typeof $loader != "undefined" && $loader != null && $loader != "" && $loader){ toogleWaitingOn(0.2); } }, }) .then(function(response) { if(typeof $loader != "undefined" && $loader != null && $loader != "" && $loader){ hideSpinner(); } if(response.status == 'success'){ updateInputQty($newQtyConfirmed.qty, $input_qta_book_id); updateBtnBooks($el, response.btns); updateCountBook(response.book_count); updateAllInputSameBook($book_id, $newQtyConfirmed.qty); if($page == "book_indice"){ updateDocumentElementsWithBookCartId($book_id, response.book_cart_id); } if($modal_alert == true) { swal({ type: response.icon_message, text: response.message, timer: response.timer_message, timerProgressBar: true, showConfirmButton: response.confirm_message }) } } else { swal({ type: 'error', title: response.title, text: response.message, timerProgressBar: true, showConfirmButton: true }); } }); } function transformStringToOneQuantity($val) { if (typeof $val === 'string' && /^[a-zA-Z0-9]+$/.test($val) && /[a-zA-Z]/.test($val)) { return 1; } return $val; } function triggerMultiBooks(el){ let $warehouse_id = $(el).data('warehouse-id'); let $trigger = $(el).data('trigger'); let $value = parseInt( $(el).data('value') ); let $id_el = $(el).data('id-el'); let $book_id = $(el).data('book-id'); let $book_cart_id = $(el).data('book-cart-id'); let $input_qty_book_id = $(el).data('input-qty-book-id'); let $min_qty = $(el).data('min-qty'); let $max_qty = $(el).data('max-qty'); let $modal_alert = $(el).data('modal-alert'); let $book_name = $(el).data('book-name'); let $loader = $(el).data('loader'); let $page = $(el).data('page'); let $newQtyConfirmed = adjustQuantityBooks ( calcNewQuantityBook( parseInt( transformStringToOneQuantity ( $("#"+$input_qty_book_id).val() ) ), $trigger, $value), $min_qty, $max_qty); if ( parseInt($newQtyConfirmed.qty) > 0 ){ updateBookQty($warehouse_id, $book_id, $newQtyConfirmed, $("#"+$input_qty_book_id), $id_el, $max_qty, $modal_alert, $book_name, $book_cart_id, $loader, $page); } else { return $.ajax({ url: 'https://staging-fabrics.piacenza1733.com/assets/ajax/cartBookRemove.php', type: 'POST', data: { book_id: $book_id, company_address_id: -1, force_remove: true, book_cart_id: $book_cart_id }, beforeSend: function() { toogleWaitingOn(0.2); } }) .then(function(response) { hideSpinner(); $(".btnRemoveBook" + $book_id).prop("disabled", true).addClass("disabled-btn-book"); $(".inputQtyBook" + $book_id).val(0); }) .catch(function(error) { console.error('Errore in asyncRemoveBook:', error); return false; }); } } function onTriggerBtnUpdateBooks() { $(document).on('click', '.js-btn-update-books', function (e) { e.preventDefault(); triggerMultiBooks(this); }); } // Oggetto per tenere traccia dei timer per ogni singolo input (evita conflitti tra più campi) const debounceTimers = {}; function onTriggerInputUpdateBooks() { $(document).on('keyup', '.js-input-update-books', function (e) { const key = e.key; let $input_qty_book_id = $(this).data('input-qty-book-id'); const isNumericKey = /^[0-9]$/.test(key); const isDeleteKey = (key === 'Backspace' || key === 'Delete'); if (!isNumericKey && !isDeleteKey) { e.preventDefault(); return; } if (isDeleteKey) { if (typeof $("#" + $input_qty_book_id).val() == "undefined" || $("#" + $input_qty_book_id).val() == null || $("#" + $input_qty_book_id).val().trim() == '') { return; } } e.preventDefault(); const self = this; // Cancella il timer precedente per questo input, se esiste if (debounceTimers[$input_qty_book_id]) { clearTimeout(debounceTimers[$input_qty_book_id]); } // Imposta un nuovo timer: la chiamata parte solo dopo 1.5s di inattività debounceTimers[$input_qty_book_id] = setTimeout(function () { triggerMultiBooks(self); delete debounceTimers[$input_qty_book_id]; }, 1500); }); } function enable_disable_buttons_books(){ const inputQtysCart = document.querySelectorAll('.js-input-update-books.cart'); inputQtysCart.forEach(function(item) { let max_qty = parseInt(item.dataset.maxQty); let min_qty = parseInt(item.dataset.minQty); let current_value = parseInt(item.value); let $book_cart_row_id = parseInt(item.dataset.bookCartId); if(current_value == max_qty || current_value > max_qty){ $(".btnAddBook"+$book_cart_row_id).prop("disabled", true).addClass("disabled-btn-book"); } else { $(".btnAddBook"+$book_cart_row_id).prop("disabled", false).removeClass("disabled-btn-book"); } if (current_value == min_qty || current_value < min_qty){ $(".btnRemoveBook"+$book_cart_row_id).prop("disabled", true).addClass("disabled-btn-book"); } else { $(".btnRemoveBook"+$book_cart_row_id).prop("disabled", false).removeClass("disabled-btn-book"); } }); const inputQtysBookIndice = document.querySelectorAll('.js-input-update-books.book_indice'); inputQtysBookIndice.forEach(function(item) { let max_qty = parseInt(item.dataset.maxQty); let min_qty = parseInt(item.dataset.minQty); let current_value = parseInt(item.value); let $book_id = parseInt(item.dataset.bookId); if(current_value == max_qty || current_value > max_qty){ $(".btnAddBook"+$book_id).prop("disabled", true).addClass("disabled-btn-book"); } else { $(".btnAddBook"+$book_id).prop("disabled", false).removeClass("disabled-btn-book"); } if (current_value == min_qty || current_value < min_qty){ $(".btnRemoveBook"+$book_id).prop("disabled", true).addClass("disabled-btn-book"); } else { $(".btnRemoveBook"+$book_id).prop("disabled", false).removeClass("disabled-btn-book"); } }); } function createNewRowBook($newBookDuplicated, $book_cart_id){ let $html = ``; let $book_id = $newBookDuplicated.book_id; let $book_type = ''; let $quantity = $newBookDuplicated.quantity; let $book_cart_id_duplicated = $newBookDuplicated.book_cart_id; let $book_image = $newBookDuplicated.book_image; let $book_name = $newBookDuplicated.book_name; let $book_stock_quanity = $newBookDuplicated.book_stock_quantity; let $url_book = $newBookDuplicated.url_book; switch ($newBookDuplicated.book_type.trim()){ case 'travel_set': $book_type = 'Travel Book'; break; case 'book': $book_type = 'Book'; break; } let $select_html = ``; let $company_id_address_selected = $("#js-select-dest-book-"+$book_cart_id).val(); $newBookDuplicated.company_addresses.forEach(($address, $index) => { let $seleted_option = ""; let $note = ""; let $info_aggiungitve; if(parseInt($company_id_address_selected) == parseInt($address.id)){ $seleted_option = "selected"; } if($address.type.trim() == "billing"){ $note = "Ship to billing address: "; $info_aggiungitve = " - " + $address.cap + " " + $address.municipality; } else { $note = $address.note + " - "; $info_aggiungitve = ""; } $select_html += ``; }); $html += `
book
${$book_name} (${$book_type})
`; return $html; } function updateCartDuplicateBook($book_cart_id, $newBookDuplicated){ const $row = createNewRowBook($newBookDuplicated, $book_cart_id); const $commentNode = findCommentNode('DUPLICATE_BOOK_CART_ID_' + $book_cart_id); if ($commentNode) { const $range = document.createRange(); $range.selectNode($commentNode); const $fragment = $range.createContextualFragment($row); $commentNode.parentNode.insertBefore($fragment, $commentNode.nextSibling); onTriggerBtnUpdateBooks(); onTriggerInputUpdateBooks(); enable_disable_buttons_books(); hideSpinner(); } } function findCommentNode(text) { const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_COMMENT); let node; while (node = walker.nextNode()) { if (node.nodeValue.trim() === text) { return node; } } return null; } function asyncDuplicateRowsBooks($book_cart_id, el){ $.ajax({ url: 'https://staging-fabrics.piacenza1733.com/assets/ajax/cartBookDuplicate.php', type: 'POST', data: { book_cart_id: $book_cart_id }, beforeSend: function (data) { toogleWaitingOn(0.2); }, }) .then(function(response) { if(response.status == 'success'){ /** * Inserisco la riga duplicata appena sotto quella originale */ updateCartDuplicateBook($book_cart_id, response.data); } else { hideSpinner(); swal({ type: 'error', text: response.message, timerProgressBar: true, showConfirmButton: true }); } }); } function triggerDuplicateRowsBooks(el){ let $book_cart_id = $(el).data('book-cart-id'); if(typeof $book_cart_id != "undefined" && $book_cart_id != null && $book_cart_id != ""){ asyncDuplicateRowsBooks($book_cart_id, el); } } $(document).on('click', '.js-duplicate-row-books', function(e){ e.preventDefault(); triggerDuplicateRowsBooks(this); }); $(document).ready(function() { enable_disable_buttons_books(); onTriggerBtnUpdateBooks(); onTriggerInputUpdateBooks(); });