Оформить заказ
const SUPABASE_URL = 'supabase.co';
const SUPABASE_ANON_KEY = 'ВСТАВЬТЕ_СЮДА_ВАШ_PUBLISHABLE_KEY';
const db = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
let products = [];
let groups = [];
let activeCategory = 'Все';
let selectedVariants = {};
let cart = [];
let currentUser = JSON.parse(localStorage.getItem('nut_user') || 'null');
let deferredPrompt;
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js').catch(() => {});
}
window.addEventListener('beforeinstallprompt', (e) => {
e.preventDefault();
deferredPrompt = e;
document.getElementById('installPwaBtn').style.display = 'inline-block';
});
function installPWA() {
if (deferredPrompt) { deferredPrompt.prompt(); deferredPrompt = null; }
}
async function detectMessengerEnvironment() {
if (window.Telegram?.WebApp?.initDataUnsafe?.user) {
const u = window.Telegram.WebApp.initDataUnsafe.user;
window.Telegram.WebApp.ready();
window.Telegram.WebApp.expand();
await syncProfile({ telegram_id: String(u.id), full_name: ${u.first_name || ''} ${u.last_name || ''}.trim() });
return;
}
if (window.WebApp?.initDataUnsafe?.user) {
const u = window.WebApp.initDataUnsafe.user;
await syncProfile({ max_id: String(u.id), full_name: ${u.first_name || ''} ${u.last_name || ''}.trim() });
return;
}
if (window.vkBridge && window.location.search.includes('vk_user_id')) {
window.vkBridge.send('VKWebAppInit');
const u = await window.vkBridge.send('VKWebAppGetUserInfo');
await syncProfile({ vk_id: String(u.id), full_name: ${u.first_name} ${u.last_name}.trim() });
}
}
async function syncProfile(userData) {
const queryCol = userData.telegram_id ? 'telegram_id' : userData.max_id ? 'max_id' : userData.vk_id ? 'vk_id' : 'phone';
const queryVal = userData[queryCol];
if (!queryVal) return;
let { data: profile } = await db.from('profiles').select('*').eq(queryCol, queryVal).maybeSingle();
if (!profile) {
const { data: created } = await db.from('profiles').insert(userData).select().single();
profile = created;
}
if (profile) {
currentUser = profile;
localStorage.setItem('nut_user', JSON.stringify(profile));
updateUserUI();
}
}
function updateUserUI() {
if (!currentUser) return;
document.getElementById('authBadge').textContent = '👤 ' + (currentUser.full_name || currentUser.phone || 'Профиль');
if (currentUser.full_name) document.getElementById('clientName').value = currentUser.full_name;
if (currentUser.phone) document.getElementById('clientPhone').value = currentUser.phone;
}
async function init() {
await detectMessengerEnvironment();
updateUserUI();
const [{ data: prods }, { data: grps }] = await Promise.all([
db.from('products').select('').eq('is_active', true).order('sort_order'),
db.from('pickup_groups').select('').eq('is_active', true)
]);
products = prods || [];
groups = grps || [];
products.forEach(p => { selectedVariants[p.id] = 0; });
renderCategories();
populateGroups();
renderProducts();
}
function renderCategories() {
const cats = ['Все', ...new Set(products.map(p => p.category))];
document.getElementById('catsBar').innerHTML = cats.map(c =>
${c}
).join('');
}
function setCategory(cat) {
activeCategory = cat;
renderCategories();
renderProducts();
}
function populateGroups() {
const select = document.getElementById('groupSelect');
select.innerHTML = '-- Выберите вашу группу --' +
groups.map(g =>
).join('');
const urlGroup = new URLSearchParams(window.location.search).get('group') || currentUser?.default_group_id;
if (urlGroup && groups.some(g => g.id === urlGroup)) select.value = urlGroup;
onGroupChange();
}
function onGroupChange() {
const gId = document.getElementById('groupSelect').value;
const group = groups.find(g => g.id === gId);
const badge = document.getElementById('groupBadge');
const banner = document.getElementById('deliveryBanner');
if (group) {
badge.textContent = group.name;
banner.innerHTML = 📍
${group.name} (${group.address || ''})
Сбор до:
${group.collect_until} • Выдача:
${group.delivery_date};
} else {
badge.textContent = 'Выбрать группу';
banner.innerHTML = '👆 Выберите вашу группу, чтобы увидеть точную дату и адрес выдачи';
}
}
function renderProducts() {
const q = document.getElementById('searchInput').value.toLowerCase().trim();
const grid = document.getElementById('productsGrid');
grid.innerHTML = products
.filter(p => (activeCategory === 'Все' || p.category === activeCategory) &&
(p.name.toLowerCase().includes(q) || (p.description || '').toLowerCase().includes(q)))
.map(p => {
const vIdx = selectedVariants[p.id] || 0;
const v = p.variants[vIdx];
const inStock = Number(p.stock_kg) > 0;
return
${p.name}
${inStock ?В наличии: ${p.stock_kg} кг: 'Нет в наличии'}
${p.description || ''}
${p.variants.map((item, i) =>${item.size}).join('')}
;
}).join('');
}
function selectVariant(id, idx) { selectedVariants[id] = idx; renderProducts(); }
function addToCart(id) {
const p = products.find(x => x.id === id);
const v = p.variants[selectedVariants[id] || 0];
const ex = cart.find(c => c.id === id && c.size === v.size);
if (ex) ex.qty++;
else cart.push({ id: p.id, name: p.name, size: v.size, price: v.price, weight_kg: v.weight_kg, qty: 1 });
updateCartBar();
}
function updateCartBar() {
const bar = document.getElementById('cartBar');
if (!cart.length) { bar.classList.add('hidden'); return; }
document.getElementById('cartCount').textContent = В корзине: ${cart.reduce((s, i) => s + i.qty, 0)} шт.;
document.getElementById('cartTotal').textContent = ${cart.reduce((s, i) => s + i.price * i.qty, 0)} ₽ →;
bar.classList.remove('hidden');
}
function openAuth() { document.getElementById('authModal').classList.add('open'); }
function openCart() { renderCartItems(); document.getElementById('cartModal').classList.add('open'); }
function closeModal(id) { document.getElementById(id).classList.remove('open'); }
function renderCartItems() {
const list = document.getElementById('cartItemsList');
if (!cart.length) { list.innerHTML = 'Корзина пуста'; return; }
list.innerHTML = cart.map((item, idx) =>
${item.name} (${item.size})
${item.price} ₽ × ${item.qty} = ${item.price * item.qty} ₽
${item.qty}
).join('');
}
function changeQty(idx, d) {
cart[idx].qty += d;
if (cart[idx].qty <= 0) cart.splice(idx, 1);
renderCartItems();
updateCartBar();
}
async function loginViaPhone() {
const phone = document.getElementById('phoneLoginInput').value.trim();
const name = document.getElementById('nameLoginInput').value.trim();
if (!phone) return alert('Введите номер телефона');
await syncProfile({ phone, full_name: name });
closeModal('authModal');
}
function loginViaMessenger(type) {
alert(Для автоматического входа в 1 клик откройте витрину через кнопку меню вашего бота в ${type === 'max' ? 'MAX' : 'Telegram'}.);
}
function loginViaVK() { db.auth.signInWithOAuth({ provider: 'vk' }); }
function loginViaYandex() { alert('Подключите Client ID Яндекс OAuth в настройках Supabase Auth.'); }
async function submitOrder(e) {
e.preventDefault();
if (!cart.length) return alert('Корзина пуста');
const btn = document.getElementById('submitBtn');
btn.disabled = true; btn.textContent = 'Оформляем...';
const gId = document.getElementById('groupSelect').value;
const name = document.getElementById('clientName').value.trim();
const phone = document.getElementById('clientPhone').value.trim();
const total = cart.reduce((s, i) => s + i.price * i.qty, 0);
if (!currentUser) await syncProfile({ phone, full_name: name, default_group_id: gId });
const { data, error } = await db.rpc('create_order_and_deduct_stock', {
p_user_id: currentUser?.id || null,
p_group_id: gId,
p_name: name,
p_phone: phone,
p_items: cart,
p_total: total,
p_payment: document.getElementById('paymentSelect').value,
p_comment: document.getElementById('clientComment').value.trim()
});
btn.disabled = false; btn.textContent = 'Оформить заказ';
if (error) return alert('Ошибка: ' + error.message);
alert(✅ Заказ ${data.order_number} оформлен на сумму ${total} ₽!);
cart = [];
updateCartBar();
closeModal('cartModal');
init();
}
init();