Aleksmorshen commited on
Commit
3b0bfca
·
verified ·
1 Parent(s): 311bae6

Update script.js

Browse files
Files changed (1) hide show
  1. script.js +132 -23
script.js CHANGED
@@ -57,7 +57,11 @@ document.addEventListener('DOMContentLoaded', function () {
57
  if (target.classList.contains('add-to-cart-btn')) {
58
  const quantityInput = row.querySelector('.quantity-input');
59
  const quantity = parseInt(quantityInput.value);
60
- addToCart(productId, quantity);
 
 
 
 
61
  } else if (target.classList.contains('add-stock-btn')) {
62
  addStock(productId);
63
  } else if (target.classList.contains('delete-btn')) {
@@ -162,32 +166,28 @@ document.addEventListener('DOMContentLoaded', function () {
162
 
163
  // Функция добавления товара в корзину
164
  function addToCart(productId, quantity) {
165
- if (quantity && quantity > 0) {
166
- const products = JSON.parse(localStorage.getItem('products')) || [];
167
- const product = products.find(p => p.id === productId);
168
-
169
- if (product && product.quantity >= quantity) {
170
- const cartItem = cart.find(item => item.id === productId);
171
 
172
- if (cartItem) {
173
- cartItem.quantity += quantity;
174
- } else {
175
- cart.push({
176
- id: productId,
177
- name: product.name,
178
- salePrice: product.salePrice,
179
- purchasePrice: product.purchasePrice,
180
- quantity: quantity
181
- });
182
- }
183
 
184
- localStorage.setItem('cart', JSON.stringify(cart));
185
- updateCartDisplay();
186
  } else {
187
- alert('Недостаточно товара на складе.');
 
 
 
 
 
 
188
  }
 
 
 
189
  } else {
190
- alert('Пожалуйста, введите корректное количество.');
191
  }
192
  }
193
 
@@ -210,4 +210,113 @@ document.addEventListener('DOMContentLoaded', function () {
210
  const options = { timeZone: 'Asia/Bishkek', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' };
211
  const receiptDateTime = now.toLocaleString('ru-RU', options);
212
 
213
- // Заполняем дату и время
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  if (target.classList.contains('add-to-cart-btn')) {
58
  const quantityInput = row.querySelector('.quantity-input');
59
  const quantity = parseInt(quantityInput.value);
60
+ if (quantity && quantity > 0) {
61
+ addToCart(productId, quantity);
62
+ } else {
63
+ alert('Пожалуйста, введите корректное количество.');
64
+ }
65
  } else if (target.classList.contains('add-stock-btn')) {
66
  addStock(productId);
67
  } else if (target.classList.contains('delete-btn')) {
 
166
 
167
  // Функция добавления товара в корзину
168
  function addToCart(productId, quantity) {
169
+ const products = JSON.parse(localStorage.getItem('products')) || [];
170
+ const product = products.find(p => p.id === productId);
 
 
 
 
171
 
172
+ if (product && product.quantity >= quantity) {
173
+ const cartItem = cart.find(item => item.id === productId);
 
 
 
 
 
 
 
 
 
174
 
175
+ if (cartItem) {
176
+ cartItem.quantity += quantity;
177
  } else {
178
+ cart.push({
179
+ id: productId,
180
+ name: product.name,
181
+ salePrice: product.salePrice,
182
+ purchasePrice: product.purchasePrice,
183
+ quantity: quantity
184
+ });
185
  }
186
+
187
+ localStorage.setItem('cart', JSON.stringify(cart));
188
+ updateCartDisplay();
189
  } else {
190
+ alert('Недостаточно товара на складе.');
191
  }
192
  }
193
 
 
210
  const options = { timeZone: 'Asia/Bishkek', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' };
211
  const receiptDateTime = now.toLocaleString('ru-RU', options);
212
 
213
+ // Заполняем дату и время в модальном окне
214
+ document.getElementById('receiptDateTime').textContent = receiptDateTime;
215
+
216
+ // Заполняем таблицу товаров в чеке
217
+ const receiptTable = document.getElementById('receiptTable').getElementsByTagName('tbody')[0];
218
+ receiptTable.innerHTML = ''; // Очищаем таблицу перед заполнением
219
+ let totalAmount = 0;
220
+
221
+ cart.forEach(item => {
222
+ const row = receiptTable.insertRow();
223
+ row.innerHTML = `
224
+ <td>${item.name}</td>
225
+ <td>${item.quantity}</td>
226
+ <td>${item.salePrice}</td>
227
+ <td>${item.quantity * item.salePrice}</td>
228
+ `;
229
+ totalAmount += item.quantity * item.salePrice;
230
+ });
231
+
232
+ // Отображаем общую сумму
233
+ document.getElementById('receiptTotal').textContent = totalAmount.toFixed(2);
234
+
235
+ // Показываем модальное окно
236
+ const modal = document.getElementById('receiptModal');
237
+ modal.style.display = 'flex';
238
+
239
+ // Обработка подтверждения продажи
240
+ document.getElementById('confirmSaleBtn').onclick = function () {
241
+ const products = JSON.parse(localStorage.getItem('products')) || [];
242
+
243
+ cart.forEach(cartItem => {
244
+ const product = products.find(p => p.id === cartItem.id);
245
+
246
+ if (product && product.quantity >= cartItem.quantity) {
247
+ product.quantity -= cartItem.quantity; // Уменьшаем остаток товара
248
+ totalSold += cartItem.quantity;
249
+ totalRevenue += cartItem.quantity * cartItem.salePrice;
250
+ totalProfit += cartItem.quantity * (cartItem.salePrice - cartItem.purchasePrice);
251
+ } else {
252
+ alert(`Недостаточно товара "${cartItem.name}" на складе.`);
253
+ }
254
+ });
255
+
256
+ // Сохраняем обновленные данные
257
+ localStorage.setItem('products', JSON.stringify(products));
258
+ localStorage.setItem('stats', JSON.stringify({ totalSold, totalRevenue, totalProfit }));
259
+ localStorage.removeItem('cart');
260
+
261
+ // Очищаем корзину и обновляем отображение
262
+ cart = [];
263
+ updateCartDisplay();
264
+ productTable.innerHTML = '';
265
+ loadProducts();
266
+ updateStatsDisplay();
267
+
268
+ // Закрываем модальное окно
269
+ modal.style.display = 'none';
270
+ };
271
+
272
+ // Обработка отмены продажи
273
+ document.getElementById('cancelSaleBtn').onclick = function () {
274
+ modal.style.display = 'none';
275
+ };
276
+
277
+ // Закрытие модального окна при клике на крестик
278
+ document.querySelector('.modal .close').onclick = function () {
279
+ modal.style.display = 'none';
280
+ };
281
+
282
+ // Закрытие модального окна при клике вне его области
283
+ window.onclick = function (event) {
284
+ if (event.target === modal) {
285
+ modal.style.display = 'none';
286
+ }
287
+ };
288
+ };
289
+
290
+ // Функция добавления остатков
291
+ function addStock(productId) {
292
+ const quantityToAdd = prompt('Введите количество для прихода:');
293
+ if (quantityToAdd && !isNaN(quantityToAdd) && quantityToAdd > 0) {
294
+ let products = JSON.parse(localStorage.getItem('products')) || [];
295
+ const productIndex = products.findIndex(p => p.id === productId);
296
+
297
+ if (productIndex !== -1) {
298
+ products[productIndex].quantity += parseInt(quantityToAdd);
299
+ localStorage.setItem('products', JSON.stringify(products));
300
+
301
+ // Обновляем таблицу
302
+ productTable.innerHTML = '';
303
+ loadProducts();
304
+ }
305
+ } else {
306
+ alert('Пожалуйста, введите корректное количество.');
307
+ }
308
+ }
309
+
310
+ // Функция удаления товара
311
+ function deleteProduct(productId) {
312
+ if (confirm('Вы уверены, что хотите удалить этот товар?')) {
313
+ let products = JSON.parse(localStorage.getItem('products')) || [];
314
+ products = products.filter(p => p.id !== productId);
315
+ localStorage.setItem('products', JSON.stringify(products));
316
+
317
+ // Обновляем таблицу
318
+ productTable.innerHTML = '';
319
+ loadProducts();
320
+ }
321
+ }
322
+ });