Aleksmorshen commited on
Commit
77b52b6
·
verified ·
1 Parent(s): c7ccf7e

Update script.js

Browse files
Files changed (1) hide show
  1. script.js +73 -80
script.js CHANGED
@@ -12,10 +12,14 @@ document.addEventListener('DOMContentLoaded', function () {
12
  let totalProfit = 0; // Общая прибыль
13
  let cart = []; // Корзина
14
 
 
 
 
15
  // Загрузка данных из localStorage при загрузке страницы
16
  loadProducts();
17
  loadStats();
18
  loadCart();
 
19
 
20
  // Обработка добавления товара
21
  productForm.addEventListener('submit', function (e) {
@@ -214,96 +218,85 @@ document.addEventListener('DOMContentLoaded', function () {
214
  const options = { timeZone: 'Asia/Bishkek', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' };
215
  const receiptDateTime = now.toLocaleString('ru-RU', options);
216
 
217
- // Заполняем дату и время в модальном окне
218
- document.getElementById('receiptDateTime').textContent = receiptDateTime;
219
-
220
- // Заполняем таблицу товаров в чеке
221
- const receiptTable = document.getElementById('receiptTable').getElementsByTagName('tbody')[0];
222
- receiptTable.innerHTML = ''; // Очищаем таблицу перед заполнением
223
- let totalAmount = 0;
224
-
225
- cart.forEach(item => {
226
- const products = JSON.parse(localStorage.getItem('products')) || [];
227
- const product = products.find(p => p.id === item.id);
228
-
229
- if (product) {
230
- const row = receiptTable.insertRow();
231
- row.innerHTML = `
232
- <td>${item.name}</td>
233
- <td>${item.quantity}</td>
234
- <td>${product.itemsPerPack}</td>
235
- <td>${item.salePrice}</td>
236
- <td>${item.quantity * item.salePrice}</td>
237
- `;
238
- totalAmount += item.quantity * item.salePrice;
239
- }
240
- });
241
-
242
- // Отображаем общую сумму, скидку и итоговую сумму
243
- document.getElementById('receiptTotal').textContent = totalAmount.toFixed(2);
244
- document.getElementById('receiptDiscount').textContent = discount.toFixed(2);
245
- document.getElementById('receiptFinalTotal').textContent = (totalAmount - discount).toFixed(2);
246
-
247
- // Показываем модальное окно
248
- const modal = document.getElementById('receiptModal');
249
- modal.style.display = 'flex';
250
-
251
- // Обработка подтверждения продажи
252
- document.getElementById('confirmSaleBtn').onclick = function () {
253
- const products = JSON.parse(localStorage.getItem('products')) || [];
254
 
255
- cart.forEach(cartItem => {
256
- const product = products.find(p => p.id === cartItem.id);
257
 
258
- if (product && product.quantity >= cartItem.quantity) {
259
- product.quantity -= cartItem.quantity; // Уменьшаем остаток товара
260
- totalSold += cartItem.quantity;
261
- totalRevenue += cartItem.quantity * cartItem.salePrice;
262
- totalProfit += cartItem.quantity * (cartItem.salePrice - cartItem.purchasePrice);
263
- } else {
264
- alert(`Недостаточно товара "${cartItem.name}" на складе.`);
265
- }
266
- });
267
 
268
- // Вычитаем скидку из прибыли
269
- totalProfit -= discount;
 
270
 
271
- // Сохраняем обновленные данные
272
- localStorage.setItem('products', JSON.stringify(products));
273
- localStorage.setItem('stats', JSON.stringify({ totalSold, totalRevenue, totalProfit }));
274
- localStorage.removeItem('cart');
 
 
275
 
276
- // Очищаем корзину и обновляем отображение
277
- cart = [];
278
- updateCartDisplay();
279
- productTable.innerHTML = '';
280
- loadProducts();
281
- updateStatsDisplay();
 
 
 
 
 
 
 
282
 
283
- // Сбрасываем поле скидки
284
- discountInput.value = '';
 
 
 
285
 
286
- // Закрываем модальное окно
287
- modal.style.display = 'none';
288
- };
289
 
290
- // Обработка отмены продажи
291
- document.getElementById('cancelSaleBtn').onclick = function () {
292
- modal.style.display = 'none';
293
- };
 
 
 
 
 
 
 
 
 
 
294
 
295
- // Закрытие модального окна при клике на крестик
296
- document.querySelector('.modal .close').onclick = function () {
297
- modal.style.display = 'none';
298
- };
299
 
300
- // Закрытие модального окна при клике вне его области
301
- window.onclick = function (event) {
302
- if (event.target === modal) {
303
- modal.style.display = 'none';
304
- }
305
- };
306
- };
307
 
308
  // Функция добавления остатков
309
  function addStock(productId) {
 
12
  let totalProfit = 0; // Общая прибыль
13
  let cart = []; // Корзина
14
 
15
+ // Массив для хранения чеков
16
+ let receipts = JSON.parse(localStorage.getItem('receipts')) || [];
17
+
18
  // Загрузка данных из localStorage при загрузке страницы
19
  loadProducts();
20
  loadStats();
21
  loadCart();
22
+ updateReceiptsList();
23
 
24
  // Обработка добавления товара
25
  productForm.addEventListener('submit', function (e) {
 
218
  const options = { timeZone: 'Asia/Bishkek', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' };
219
  const receiptDateTime = now.toLocaleString('ru-RU', options);
220
 
221
+ // Создаем чек
222
+ const receipt = {
223
+ dateTime: receiptDateTime,
224
+ items: cart.map(item => ({
225
+ name: item.name,
226
+ quantity: item.quantity,
227
+ salePrice: item.salePrice,
228
+ itemsPerPack: item.itemsPerPack
229
+ })),
230
+ discount: discount
231
+ };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
 
233
+ // Сохраняем чек
234
+ saveReceipt(receipt);
235
 
236
+ // Очищаем корзину и обновляем отображение
237
+ cart = [];
238
+ updateCartDisplay();
239
+ productTable.innerHTML = '';
240
+ loadProducts();
241
+ updateStatsDisplay();
 
 
 
242
 
243
+ // Сбрасываем поле скидки
244
+ discountInput.value = '';
245
+ };
246
 
247
+ // Функция для сохранения чека
248
+ function saveReceipt(receipt) {
249
+ receipts.push(receipt);
250
+ localStorage.setItem('receipts', JSON.stringify(receipts));
251
+ updateReceiptsList();
252
+ }
253
 
254
+ // Функция для обновления списка чеков
255
+ function updateReceiptsList() {
256
+ const receiptsList = document.getElementById('receiptsList');
257
+ receiptsList.innerHTML = ''; // Очищаем список перед обновлением
258
+
259
+ receipts.forEach((receipt, index) => {
260
+ const receiptItem = document.createElement('div');
261
+ receiptItem.className = 'receipt-item';
262
+ receiptItem.textContent = `Чек от ${receipt.dateTime}`;
263
+ receiptItem.onclick = () => openReceipt(index);
264
+ receiptsList.appendChild(receiptItem);
265
+ });
266
+ }
267
 
268
+ // Функция для открытия чека
269
+ function openReceipt(index) {
270
+ const receipt = receipts[index];
271
+ const modal = document.getElementById('receiptModal');
272
+ const receiptTable = document.getElementById('receiptTable').getElementsByTagName('tbody')[0];
273
 
274
+ // Заполняем дату и время
275
+ document.getElementById('receiptDateTime').textContent = receipt.dateTime;
 
276
 
277
+ // Заполняем таблицу товаров
278
+ receiptTable.innerHTML = '';
279
+ let totalAmount = 0;
280
+ receipt.items.forEach(item => {
281
+ const row = receiptTable.insertRow();
282
+ row.innerHTML = `
283
+ <td>${item.name}</td>
284
+ <td>${item.quantity}</td>
285
+ <td>${item.itemsPerPack}</td>
286
+ <td>${item.salePrice}</td>
287
+ <td>${item.quantity * item.salePrice}</td>
288
+ `;
289
+ totalAmount += item.quantity * item.salePrice;
290
+ });
291
 
292
+ // Отображаем общую сумму, скидку и итоговую сумму
293
+ document.getElementById('receiptTotal').textContent = totalAmount.toFixed(2);
294
+ document.getElementById('receiptDiscount').textContent = receipt.discount.toFixed(2);
295
+ document.getElementById('receiptFinalTotal').textContent = (totalAmount - receipt.discount).toFixed(2);
296
 
297
+ // Показываем модальное окно
298
+ modal.style.display = 'flex';
299
+ }
 
 
 
 
300
 
301
  // Функция добавления остатков
302
  function addStock(productId) {