Spaces:
Running
Running
File size: 7,861 Bytes
e2876c9 60ad812 830abe8 fff872d c8eeee8 fff872d 830abe8 e1c0916 e2876c9 fff872d 830abe8 e2876c9 60ad812 c8eeee8 e1c0916 c8eeee8 e1c0916 c8eeee8 e1c0916 e2876c9 2a46e2b 830abe8 2a46e2b 830abe8 2a46e2b e1c0916 830abe8 e1c0916 830abe8 e1c0916 830abe8 e1c0916 830abe8 e1c0916 830abe8 e1c0916 830abe8 2a46e2b c8eeee8 e1c0916 c8eeee8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
document.addEventListener('DOMContentLoaded', function () {
const productForm = document.getElementById('productForm');
const productTable = document.getElementById('productTable').getElementsByTagName('tbody')[0];
const searchInput = document.getElementById('searchInput');
const cartTable = document.getElementById('cartTable').getElementsByTagName('tbody')[0];
const totalSoldElement = document.getElementById('totalSold');
const totalRevenueElement = document.getElementById('totalRevenue');
const modal = document.getElementById('modal');
const closeModal = document.querySelector('.close');
let totalSold = 0; // Общее количество проданных товаров
let totalRevenue = 0; // Общая выручка
let cart = []; // Корзина
let selectedProductId = null; // ID выбранного товара
// Загрузка данных из localStorage при загрузке страницы
loadProducts();
loadStats();
loadCart();
// Обработка добавления товара
productForm.addEventListener('submit', function (e) {
e.preventDefault();
const productName = document.getElementById('productName').value;
const purchasePrice = parseFloat(document.getElementById('purchasePrice').value);
const salePrice = parseFloat(document.getElementById('salePrice').value);
const quantity = parseInt(document.getElementById('quantity').value);
if (productName && !isNaN(purchasePrice) && !isNaN(salePrice) && !isNaN(quantity)) {
addProduct(productName, purchasePrice, salePrice, quantity);
productForm.reset(); // Очистка формы после добавления
} else {
alert('Пожалуйста, заполните все поля корректно.');
}
});
// Поиск по товарам
searchInput.addEventListener('input', function () {
const searchTerm = searchInput.value.toLowerCase();
const rows = productTable.getElementsByTagName('tr');
for (let row of rows) {
const name = row.getElementsByTagName('td')[0]?.textContent.toLowerCase();
if (name) {
row.style.display = name.includes(searchTerm) ? '' : 'none';
}
}
});
// Открытие модального окна при клике на товар
productTable.addEventListener('click', function (e) {
const row = e.target.closest('tr');
if (row) {
selectedProductId = parseInt(row.getAttribute('data-id'));
modal.style.display = 'flex';
}
});
// Закрытие модального окна
closeModal.addEventListener('click', function () {
modal.style.display = 'none';
});
// Закрытие модального окна при клике вне его
window.addEventListener('click', function (e) {
if (e.target === modal) {
modal.style.display = 'none';
}
});
// Функция добавления товара
function addProduct(name, purchasePrice, salePrice, quantity) {
const product = {
id: Date.now(), // Уникальный ID на основе времени
name,
purchasePrice,
salePrice,
quantity
};
// Получаем текущие товары из localStorage
let products = JSON.parse(localStorage.getItem('products')) || [];
products.push(product); // Добавляем новый товар
localStorage.setItem('products', JSON.stringify(products)); // Сохраняем в localStorage
// Добавляем товар в таблицу
addProductToTable(product);
}
// Функция добавления товара в таблицу
function addProductToTable(product) {
const row = productTable.insertRow();
row.setAttribute('data-id', product.id);
row.innerHTML = `
<td>${product.name}</td>
<td>${product.purchasePrice}</td>
<td>${product.salePrice}</td>
<td>${product.quantity}</td>
`;
}
// Функция загрузки товаров из localStorage
function loadProducts() {
const products = JSON.parse(localStorage.getItem('products')) || [];
productTable.innerHTML = ''; // Очищаем таблицу перед загрузкой
products.forEach(product => addProductToTable(product));
}
// Функция загрузки статистики из localStorage
function loadStats() {
const stats = JSON.parse(localStorage.getItem('stats')) || { totalSold: 0, totalRevenue: 0 };
totalSold = stats.totalSold;
totalRevenue = stats.totalRevenue;
updateStatsDisplay();
}
// Функция загрузки корзины из localStorage
function loadCart() {
cart = JSON.parse(localStorage.getItem('cart')) || [];
updateCartDisplay();
}
// Функция обновления отображения статистики
function updateStatsDisplay() {
totalSoldElement.textContent = totalSold;
totalRevenueElement.textContent = totalRevenue.toFixed(2);
}
// Функция обновления отображения корзины
function updateCartDisplay() {
cartTable.innerHTML = ''; // Очищаем корзину перед обновлением
cart.forEach(item => {
const row = cartTable.insertRow();
row.innerHTML = `
<td>${item.name}</td>
<td>${item.quantity}</td>
<td>${item.salePrice}</td>
<td>${item.quantity * item.salePrice}</td>
<td><button class="delete-btn" onclick="removeFromCart(${item.id})">Удалить</button></td>
`;
});
}
// Обработчик добавления в корзину
window.handleAddToCart = function () {
const quantity = prompt('Введите количество для добавления в корзину:');
if (quantity && !isNaN(quantity) && quantity > 0) {
const products = JSON.parse(localStorage.getItem('products')) || [];
const product = products.find(p => p.id === selectedProductId);
if (product && product.quantity >= quantity) {
const cartItem = cart.find(item => item.id === selectedProductId);
if (cartItem) {
cartItem.quantity += parseInt(quantity);
} else {
cart.push({
id: selectedProductId,
name: product.name,
salePrice: product.salePrice,
quantity: parseInt(quantity)
});
}
localStorage.setItem('cart', JSON.stringify(cart));
updateCartDisplay();
} else {
alert('Недостаточно товара на складе.');
}
} else {
alert('Пожалуйста, введите корректное количество.');
}
modal.style.display = 'none';
};
// Обработчик прихода товара
window.handleAddStock = function () {
const quantityToAdd = prompt('Введите количество для прихода:');
if (quantityToAdd && !isNaN(quantityToAdd) && quantityToAdd > 0) {
let products = JSON.parse(localStorage.getItem('products')) || [];
const productIndex = products.findIndex(p => |