-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
229 lines (204 loc) · 7.56 KB
/
index.js
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
// Predefined products with initial prices (expanded list)
const predefinedProducts = {
'Хлеб белый': 40,
'Хлеб ржаной': 45,
'Молоко 2.5%': 89,
'Молоко 3.2%': 95,
'Яйца С1': 85,
'Яйца С0': 95,
'Сыр российский': 320,
'Сыр голландский': 340,
'Масло сливочное': 150,
'Масло подсолнечное': 120,
'Говядина': 400,
'Свинина': 380,
'Курица': 280,
'Минтай': 350,
'Треска': 420,
'Картофель': 45,
'Морковь': 35,
'Лук репчатый': 30,
'Капуста': 25,
'Огурцы': 180,
'Помидоры': 220,
'Яблоки': 130,
'Бананы': 110,
'Апельсины': 140,
'Рис': 90,
'Гречка': 85,
'Макароны': 65,
'Сахар': 55,
'Соль': 20,
'Чай черный': 160,
'Кофе молотый': 450,
'Печенье': 130,
'Конфеты': 280,
'Сметана': 140,
'Творог': 190,
'Кефир': 75
};
// Initialize shopping list from localStorage or empty array
let shoppingList = JSON.parse(localStorage.getItem('shoppingList')) || [];
// DOM Elements
const productSearch = document.getElementById('productSearch');
const searchResults = document.getElementById('searchResults');
const productList = document.getElementById('productList');
const totalPrice = document.getElementById('totalPrice');
const addProductBtn = document.getElementById('addProduct');
const refreshPricesBtn = document.getElementById('refreshPrices');
const clearListBtn = document.getElementById('clearList');
// Event Listeners
productSearch.addEventListener('input', handleSearch);
addProductBtn.addEventListener('click', handleAddProduct);
refreshPricesBtn.addEventListener('click', refreshPrices);
clearListBtn.addEventListener('click', clearList);
// Enhanced search functionality
function handleSearch(e) {
const searchTerm = e.target.value.toLowerCase();
if (!searchTerm) {
searchResults.style.display = 'none';
return;
}
const matches = Object.entries(predefinedProducts)
.filter(([product]) =>
product.toLowerCase().includes(searchTerm)
)
.sort(([a], [b]) => {
// Exact matches first, then by string length
const aStartsWith = a.toLowerCase().startsWith(searchTerm);
const bStartsWith = b.toLowerCase().startsWith(searchTerm);
if (aStartsWith && !bStartsWith) return -1;
if (!aStartsWith && bStartsWith) return 1;
return a.length - b.length;
})
.slice(0, 10); // Limit to top 10 matches
searchResults.innerHTML = '';
if (matches.length === 0) {
const div = document.createElement('div');
div.textContent = 'Продукт не найден. Нажмите +, чтобы добавить новый.';
div.className = 'no-results';
searchResults.appendChild(div);
} else {
matches.forEach(([product, price]) => {
const div = document.createElement('div');
div.className = 'search-result-item';
div.innerHTML = `
<span class="product-name">${product}</span>
<span class="product-price">${price}₽</span>
`;
div.addEventListener('click', () => {
addToList(product, price);
searchResults.style.display = 'none';
productSearch.value = '';
});
searchResults.appendChild(div);
});
}
searchResults.style.display = 'block';
}
// Add product to list
function handleAddProduct() {
const productName = productSearch.value.trim();
if (productName) {
const price = predefinedProducts[productName] || 0;
addToList(productName, price);
productSearch.value = '';
searchResults.style.display = 'none';
}
}
function addToList(name, price) {
const existingItem = shoppingList.find(item => item.name === name);
if (existingItem) {
existingItem.quantity++;
} else {
shoppingList.push({
name,
price,
quantity: 1
});
}
saveAndRenderList();
}
// Render shopping list
function renderList() {
productList.innerHTML = '';
let total = 0;
shoppingList.forEach((item, index) => {
const li = document.createElement('li');
li.className = 'list-item';
const itemTotal = item.price * item.quantity;
total += itemTotal;
li.innerHTML = `
<div class="item-info">
<span class="item-name">${item.name}</span>
<span class="item-price">${item.price}₽ × ${item.quantity} = ${itemTotal}₽</span>
</div>
<div class="item-actions">
<div class="quantity-controls">
<button class="quantity-btn" onclick="updateQuantity(${index}, -1)">-</button>
<span>${item.quantity}</span>
<button class="quantity-btn" onclick="updateQuantity(${index}, 1)">+</button>
</div>
<button class="delete-btn" onclick="removeItem(${index})">
<i class="fas fa-trash"></i>
</button>
</div>
`;
productList.appendChild(li);
});
totalPrice.textContent = total.toFixed(2);
}
// Update quantity
function updateQuantity(index, change) {
shoppingList[index].quantity += change;
if (shoppingList[index].quantity <= 0) {
shoppingList.splice(index, 1);
}
saveAndRenderList();
}
// Remove item
function removeItem(index) {
shoppingList.splice(index, 1);
saveAndRenderList();
}
// Clear list
function clearList() {
if (confirm('Вы уверены, что хотите очистить список?')) {
shoppingList = [];
saveAndRenderList();
}
}
// Refresh prices from bdex.ru
function refreshPrices() {
const refreshBtn = document.getElementById('refreshPrices');
refreshBtn.disabled = true;
refreshBtn.innerHTML = '<i class="fas fa-sync-alt fa-spin"></i> Обновление...';
// Fetch new prices from our API
fetch('/api/prices')
.then(response => response.json())
.then(newPrices => {
// Update predefined products with new prices
Object.assign(predefinedProducts, newPrices);
// Update prices in shopping list
shoppingList = shoppingList.map(item => ({
...item,
price: predefinedProducts[item.name] || item.price
}));
saveAndRenderList();
refreshBtn.disabled = false;
refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i> Обновить цены';
})
.catch(error => {
console.error('Error updating prices:', error);
alert('Ошибка при обновлении цен. Пожалуйста, попробуйте позже.');
refreshBtn.disabled = false;
refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i> Обновить цены';
});
}
// Save to localStorage and render
function saveAndRenderList() {
localStorage.setItem('shoppingList', JSON.stringify(shoppingList));
renderList();
}
// Initial render
renderList();