264 lines
7.8 KiB
JavaScript
264 lines
7.8 KiB
JavaScript
/**
|
||
* Модуль редактирования товара в корзине POS-терминала
|
||
* Отвечает за открытие модалки и сохранение изменений
|
||
*/
|
||
|
||
(function() {
|
||
'use strict';
|
||
|
||
let editingCartKey = null;
|
||
let basePrice = 0;
|
||
|
||
/**
|
||
* Округление цены до 2 знаков
|
||
*/
|
||
function roundPrice(value) {
|
||
if (value === null || value === undefined || isNaN(value)) return '0.00';
|
||
return (Number(value)).toFixed(2);
|
||
}
|
||
|
||
/**
|
||
* Округление количества
|
||
*/
|
||
function roundQty(value, decimals = 3) {
|
||
if (value === null || value === undefined || isNaN(value)) return 0;
|
||
return Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals);
|
||
}
|
||
|
||
/**
|
||
* Форматирование денег
|
||
*/
|
||
function fmtMoney(value) {
|
||
const num = Number(value);
|
||
if (isNaN(num)) return '0.00';
|
||
return num.toFixed(2);
|
||
}
|
||
|
||
/**
|
||
* Открытие модалки редактирования
|
||
* @param {string} cartKey - ключ товара в корзине
|
||
*/
|
||
function openModal(cartKey) {
|
||
const cart = window.cart;
|
||
if (!cart) {
|
||
console.error('CartItemEditor: window.cart not found!');
|
||
return;
|
||
}
|
||
|
||
const item = cart.get(cartKey);
|
||
if (!item) {
|
||
console.error('CartItemEditor: Item not found for key:', cartKey);
|
||
return;
|
||
}
|
||
|
||
// Проверяем наличие модалки
|
||
const modalEl = document.getElementById('editCartItemModal');
|
||
if (!modalEl) {
|
||
console.error('CartItemEditor: Modal element not found!');
|
||
return;
|
||
}
|
||
|
||
editingCartKey = cartKey;
|
||
basePrice = parseFloat(item.price) || 0;
|
||
|
||
// Проверяем, является ли товар витринным комплектом
|
||
const isShowcaseKit = item.type === 'showcase_kit';
|
||
|
||
// Заполнение полей
|
||
const nameEl = document.getElementById('editModalProductName');
|
||
const basePriceEl = document.getElementById('editModalBasePrice');
|
||
const priceInput = document.getElementById('editModalPrice');
|
||
const qtyInput = document.getElementById('editModalQuantity');
|
||
|
||
if (nameEl) nameEl.textContent = item.name || '—';
|
||
if (basePriceEl) basePriceEl.textContent = fmtMoney(basePrice) + ' руб.';
|
||
if (priceInput) priceInput.value = roundPrice(basePrice);
|
||
if (qtyInput) qtyInput.value = item.qty || 1;
|
||
|
||
// Для витринных комплектов блокируем изменение количества
|
||
const qtyHint = document.getElementById('editModalQtyHint');
|
||
if (isShowcaseKit) {
|
||
if (qtyInput) qtyInput.disabled = true;
|
||
if (qtyHint) qtyHint.style.display = 'block';
|
||
} else {
|
||
if (qtyInput) qtyInput.disabled = false;
|
||
if (qtyHint) qtyHint.style.display = 'none';
|
||
}
|
||
|
||
// Бейдж единицы измерения
|
||
const unitBadge = document.getElementById('editModalUnitBadge');
|
||
if (unitBadge) {
|
||
if (item.unit_name) {
|
||
unitBadge.textContent = item.unit_name;
|
||
unitBadge.style.display = 'inline-block';
|
||
} else {
|
||
unitBadge.style.display = 'none';
|
||
}
|
||
}
|
||
|
||
updateTotal();
|
||
|
||
// Показ модалки
|
||
const modal = new bootstrap.Modal(modalEl);
|
||
modal.show();
|
||
|
||
console.log('CartItemEditor: Modal opened for', item.name);
|
||
}
|
||
|
||
/**
|
||
* Обновление суммы в модалке
|
||
*/
|
||
function updateTotal() {
|
||
const priceInput = document.getElementById('editModalPrice');
|
||
const qtyInput = document.getElementById('editModalQuantity');
|
||
const totalEl = document.getElementById('editModalTotal');
|
||
const warningEl = document.getElementById('editModalPriceWarning');
|
||
|
||
if (!priceInput || !qtyInput) return;
|
||
|
||
const price = parseFloat(priceInput.value) || 0;
|
||
const qty = parseFloat(qtyInput.value) || 0;
|
||
|
||
if (totalEl) {
|
||
totalEl.textContent = fmtMoney(price * qty) + ' руб.';
|
||
}
|
||
|
||
// Индикатор изменения цены
|
||
if (warningEl) {
|
||
if (Math.abs(price - basePrice) > 0.01) {
|
||
warningEl.style.display = 'block';
|
||
} else {
|
||
warningEl.style.display = 'none';
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Сохранение изменений
|
||
*/
|
||
function saveChanges() {
|
||
if (!editingCartKey) return;
|
||
|
||
const priceInput = document.getElementById('editModalPrice');
|
||
const qtyInput = document.getElementById('editModalQuantity');
|
||
|
||
if (!priceInput) return;
|
||
|
||
const newPrice = parseFloat(priceInput.value) || 0;
|
||
const newQty = parseFloat(qtyInput?.value) || 1;
|
||
|
||
const cart = window.cart;
|
||
if (!cart) {
|
||
console.error('CartItemEditor: window.cart not found during save!');
|
||
return;
|
||
}
|
||
|
||
const item = cart.get(editingCartKey);
|
||
if (item) {
|
||
const isShowcaseKit = item.type === 'showcase_kit';
|
||
|
||
item.price = newPrice;
|
||
// Для витринных комплектов не меняем количество
|
||
if (!isShowcaseKit) {
|
||
item.qty = roundQty(newQty, 3);
|
||
}
|
||
item.price_overridden = Math.abs(newPrice - basePrice) > 0.01;
|
||
|
||
// Обновляем в корзине
|
||
cart.items.set(editingCartKey, item);
|
||
|
||
// Уведомляем слушателей
|
||
cart._notify();
|
||
|
||
// Планируем сохранение
|
||
cart.scheduleSave();
|
||
|
||
// Перерисовка корзины
|
||
if (typeof window.renderCart === 'function') {
|
||
window.renderCart();
|
||
}
|
||
|
||
console.log('CartItemEditor: Changes saved for', item.name);
|
||
}
|
||
|
||
// Закрытие модалки
|
||
const modalEl = document.getElementById('editCartItemModal');
|
||
const modal = bootstrap.Modal.getInstance(modalEl);
|
||
if (modal) modal.hide();
|
||
}
|
||
|
||
/**
|
||
* Сброс состояния модалки
|
||
*/
|
||
function reset() {
|
||
editingCartKey = null;
|
||
basePrice = 0;
|
||
}
|
||
|
||
/**
|
||
* Инициализация модуля
|
||
*/
|
||
function init() {
|
||
const priceInput = document.getElementById('editModalPrice');
|
||
const qtyInput = document.getElementById('editModalQuantity');
|
||
const confirmBtn = document.getElementById('confirmEditCartItem');
|
||
|
||
if (!priceInput || !confirmBtn) {
|
||
console.warn('CartItemEditor: Required elements not found, deferring init...');
|
||
// Повторная попытка через короткое время
|
||
setTimeout(init, 100);
|
||
return;
|
||
}
|
||
|
||
console.log('CartItemEditor: Initialized successfully');
|
||
|
||
// Обновление суммы при изменении полей
|
||
priceInput.addEventListener('input', updateTotal);
|
||
if (qtyInput) qtyInput.addEventListener('input', updateTotal);
|
||
|
||
// Авто-выделение всего текста при фокусе
|
||
priceInput.addEventListener('focus', function() {
|
||
this.select();
|
||
});
|
||
if (qtyInput) {
|
||
qtyInput.addEventListener('focus', function() {
|
||
this.select();
|
||
});
|
||
}
|
||
|
||
// Кнопка сохранения
|
||
confirmBtn.addEventListener('click', saveChanges);
|
||
|
||
// Сброс при закрытии модалки
|
||
const modalEl = document.getElementById('editCartItemModal');
|
||
if (modalEl) {
|
||
modalEl.addEventListener('hidden.bs.modal', reset);
|
||
}
|
||
|
||
// Enter для сохранения
|
||
priceInput.addEventListener('keypress', function(e) {
|
||
if (e.key === 'Enter') saveChanges();
|
||
});
|
||
if (qtyInput) {
|
||
qtyInput.addEventListener('keypress', function(e) {
|
||
if (e.key === 'Enter') saveChanges();
|
||
});
|
||
}
|
||
}
|
||
|
||
// Экспорт функций для использования из terminal.js
|
||
window.CartItemEditor = {
|
||
openModal: openModal,
|
||
init: init
|
||
};
|
||
|
||
console.log('CartItemEditor: Module loaded');
|
||
|
||
// Автоинициализация при загрузке
|
||
if (document.readyState === 'loading') {
|
||
document.addEventListener('DOMContentLoaded', init);
|
||
} else {
|
||
init();
|
||
}
|
||
})();
|