File size: 11,391 Bytes
e2876c9
 
 
60ad812
830abe8
fff872d
 
e1998b1
fff872d
 
 
e1998b1
830abe8
e2876c9
 
 
fff872d
830abe8
e2876c9
 
 
 
 
 
 
 
 
4a07d88
e2876c9
4a07d88
 
e2876c9
 
 
 
 
 
60ad812
 
 
 
 
 
 
 
 
 
 
 
 
cf89e57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2876c9
4a07d88
e2876c9
 
 
 
 
4a07d88
 
e2876c9
 
 
 
 
 
 
 
 
 
 
 
 
2a46e2b
 
 
 
 
 
 
 
4a07d88
e256951
 
cf89e57
 
 
e256951
2a46e2b
 
 
 
 
 
 
 
 
 
 
 
e1998b1
2a46e2b
 
e1998b1
2a46e2b
 
 
830abe8
 
 
 
 
 
2a46e2b
 
 
 
e1998b1
2a46e2b
 
830abe8
 
 
 
 
cf89e57
830abe8
 
 
 
 
cf89e57
830abe8
 
 
2a46e2b
e256951
cf89e57
e256951
830abe8
e256951
830abe8
 
e256951
830abe8
 
e256951
830abe8
 
e256951
830abe8
 
e1998b1
e256951
830abe8
 
 
 
 
 
96d309a
 
 
 
 
cf89e57
96d309a
 
cf89e57
96d309a
 
 
cf89e57
96d309a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf89e57
96d309a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf89e57
96d309a
 
cf89e57
96d309a
 
 
 
 
 
 
 
 
cf89e57
96d309a
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
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 totalProfitElement = document.getElementById('totalProfit');

    let totalSold = 0; // Общее количество проданных товаров
    let totalRevenue = 0; // Общая выручка
    let totalProfit = 0; // Общая прибыль
    let cart = []; // Корзина

    // Загрузка данных из 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);
        const itemsPerPack = parseInt(document.getElementById('itemsPerPack').value);

        if (productName && !isNaN(purchasePrice) && !isNaN(salePrice) && !isNaN(quantity) && !isNaN(itemsPerPack)) {
            addProduct(productName, purchasePrice, salePrice, quantity, itemsPerPack);
            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 target = e.target;
        const row = target.closest('tr');
        const productId = parseInt(row.getAttribute('data-id'));

        if (target.classList.contains('add-to-cart-btn')) {
            const quantityInput = row.querySelector('.quantity-input');
            const quantity = parseInt(quantityInput.value);
            addToCart(productId, quantity);
        } else if (target.classList.contains('add-stock-btn')) {
            addStock(productId);
        } else if (target.classList.contains('delete-btn')) {
            deleteProduct(productId);
        }
    });

    // Делегирование событий для кнопок в корзине
    cartTable.addEventListener('click', function (e) {
        const target = e.target;
        if (target.classList.contains('delete-btn')) {
            const row = target.closest('tr');
            const productId = parseInt(row.getAttribute('data-id'));
            removeFromCart(productId);
        }
    });

    // Функция добавления товара
    function addProduct(name, purchasePrice, salePrice, quantity, itemsPerPack) {
        const product = {
            id: Date.now(), // Уникальный ID на основе времени
            name,
            purchasePrice,
            salePrice,
            quantity,
            itemsPerPack
        };

        // Получаем текущие товары из 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>
            <td>${product.itemsPerPack}</td>
            <td class="actions">
                <input type="number" min="1" max="${product.quantity}" class="quantity-input" placeholder="Количество">
                <button class="add-to-cart-btn">Добавить в корзину</button>
                <button class="add-stock-btn">Приход</button>
                <button class="delete-btn">Удалить</button>
            </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, totalProfit: 0 };
        totalSold = stats.totalSold;
        totalRevenue = stats.totalRevenue;
        totalProfit = stats.totalProfit;
        updateStatsDisplay();
    }

    // Функция загрузки корзины из localStorage
    function loadCart() {
        cart = JSON.parse(localStorage.getItem('cart')) || [];
        updateCartDisplay();
    }

    // Функция обновления отображения статистики
    function updateStatsDisplay() {
        totalSoldElement.textContent = totalSold;
        totalRevenueElement.textContent = totalRevenue.toFixed(2);
        totalProfitElement.textContent = totalProfit.toFixed(2);
    }

    // Функция обновления отображения корзины
    function updateCartDisplay() {
        cartTable.innerHTML = ''; // Очищаем корзину перед обновлением
        cart.forEach(item => {
            const row = cartTable.insertRow();
            row.setAttribute('data-id', item.id);
            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">Удалить</button></td>
            `;
        });
    }

    // Функция добавления товара в корзину
    function addToCart(productId, quantity) {
        if (quantity && quantity > 0) {
            const products = JSON.parse(localStorage.getItem('products')) || [];
            const product = products.find(p => p.id === productId);

            if (product && product.quantity >= quantity) {
                const cartItem = cart.find(item => item.id === productId);

                if (cartItem) {
                    cartItem.quantity += quantity;
                } else {
                    cart.push({
                        id: productId,
                        name: product.name,
                        salePrice: product.salePrice,
                        purchasePrice: product.purchasePrice,
                        quantity: quantity
                    });
                }

                localStorage.setItem('cart', JSON.stringify(cart));
                updateCartDisplay();
            } else {
                alert('Недостаточно товара на складе.');
            }
        } else {
            alert('Пожалуйста, введите корректное количество.');
        }
    }

    // Функция удаления товара из корзины
    function removeFromCart(productId) {
        cart = cart.filter(item => item.id !== productId);
        localStorage.setItem('cart', JSON.stringify(cart));
        updateCartDisplay();
    }

    // Функция продажи товаров из корзины
    window.sellCart = function () {
        if (cart.length === 0) {
            alert('Корзина пуста.');
            return;
        }

        const products = JSON.parse(localStorage.getItem('products')) || [];

        cart.forEach(cartItem => {
            const product = products.find(p => p.id === cartItem.id);

            if (product && product.quantity >= cartItem.quantity) {
                product.quantity -= cartItem.quantity;
                totalSold += cartItem.quantity;
                totalRevenue += cartItem.quantity * cartItem.salePrice;
                totalProfit += cartItem.quantity * (cartItem.salePrice - cartItem.purchasePrice);
            } else {
                alert(`Недостаточно товара "${cartItem.name}" на складе.`);
            }
        });

        localStorage.setItem('products', JSON.stringify(products));
        localStorage.setItem('stats', JSON.stringify({ totalSold, totalRevenue, totalProfit }));
        localStorage.removeItem('cart');

        cart = [];
        updateCartDisplay();
        productTable.innerHTML = '';
        loadProducts();
        updateStatsDisplay();
    };

    // Функция добавления остатков
    function addStock(productId) {
        const quantityToAdd = prompt('Введите количество для прихода:');
        if (quantityToAdd && !isNaN(quantityToAdd) && quantityToAdd > 0) {
            let products = JSON.parse(localStorage.getItem('products')) || [];
            const productIndex = products.findIndex(p => p.id === productId);

            if (productIndex !== -1) {
                products[productIndex].quantity += parseInt(quantityToAdd);
                localStorage.setItem('products', JSON.stringify(products));

                // Обновляем таблицу
                productTable.innerHTML = '';
                loadProducts();
            }
        } else {
            alert('Пожалуйста, введите корректное количество.');
        }
    }

    // Функция удаления товара
    function deleteProduct(productId) {
        if (confirm('Вы уверены, что хотите удалить этот товар?')) {
            let products = JSON.parse(localStorage.getItem('products')) || [];
            products = products.filter(p => p.id !== productId);
            localStorage.setItem('products', JSON.stringify(products));

            // Обновляем таблицу
            productTable.innerHTML = '';
            loadProducts();
        }
    }
});