406 lines
14 KiB
JavaScript
406 lines
14 KiB
JavaScript
import { SHOP, CATEGORIES, DISHES, PROMOTIONS } from './menu.js'
|
||
import {
|
||
money, clock, getTable, setTable,
|
||
readCart, writeCart, addToCart, changeQty, clearCart, totals, priceOf,
|
||
submitOrder, updateOrder, orderById, readOrders, watch, STATUS,
|
||
} from './store.js'
|
||
|
||
const $ = (id) => document.getElementById(id)
|
||
const esc = (text) => String(text ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]))
|
||
|
||
let table = ''
|
||
let currentDish = null
|
||
let draft = { spec: {}, extras: [], qty: 1 }
|
||
let activeOrderId = null
|
||
let toastTimer = null
|
||
|
||
// ---------- 基础 UI ----------
|
||
|
||
function toast(text) {
|
||
const el = $('toast')
|
||
el.textContent = text
|
||
el.hidden = false
|
||
clearTimeout(toastTimer)
|
||
toastTimer = setTimeout(() => { el.hidden = true }, 1800)
|
||
}
|
||
|
||
function openSheet(id) { $(id).hidden = false }
|
||
function closeSheet(id) { $(id).hidden = true }
|
||
|
||
document.addEventListener('click', (event) => {
|
||
const close = event.target.closest('[data-close]')
|
||
if (close) closeSheet(close.dataset.close)
|
||
})
|
||
|
||
// ---------- 顶部信息 ----------
|
||
|
||
function paintShop() {
|
||
$('shopName').textContent = SHOP.name
|
||
$('slogan').textContent = SHOP.slogan
|
||
$('notice').textContent = SHOP.notice
|
||
$('tableLabel').textContent = table ? `${table} 桌` : '选桌号'
|
||
}
|
||
|
||
function paintCats() {
|
||
$('cats').innerHTML = CATEGORIES.map((cat) =>
|
||
`<button class="cat" type="button" data-cat="${cat.id}">${cat.icon} ${esc(cat.name)}</button>`).join('')
|
||
}
|
||
|
||
// ---------- 菜单 ----------
|
||
|
||
function paintMenu() {
|
||
$('menu').innerHTML = CATEGORIES.map((cat) => {
|
||
const dishes = DISHES.filter((dish) => dish.cat === cat.id)
|
||
if (dishes.length === 0) return ''
|
||
return `
|
||
<div id="sec-${cat.id}">
|
||
<div class="section-title">${cat.icon} ${esc(cat.name)} <small>${dishes.length} 道</small></div>
|
||
${dishes.map(dishCard).join('')}
|
||
</div>`
|
||
}).join('')
|
||
}
|
||
|
||
function dishCard(dish) {
|
||
const tag = dish.tags[0] ? `<span class="badge">${esc(dish.tags[0])}</span>` : ''
|
||
const extras = dish.extras?.length ? '· 可加料' : ''
|
||
return `
|
||
<article class="dish" data-dish="${dish.id}">
|
||
<div class="dish-art">${dish.emoji}</div>
|
||
<div class="dish-body">
|
||
<div class="dish-name">${esc(dish.name)} ${tag}</div>
|
||
<p class="dish-desc">${esc(dish.desc)}</p>
|
||
<div class="dish-foot">
|
||
<div>
|
||
<span class="price">${money(dish.price)}</span>
|
||
<div class="meta">${dish.hot ? '🔥 热门' : esc(dish.tags[1] ?? '')} ${extras}</div>
|
||
</div>
|
||
<button class="add" type="button" aria-label="加购 ${esc(dish.name)}">+</button>
|
||
</div>
|
||
</div>
|
||
</article>`
|
||
}
|
||
|
||
$('menu').addEventListener('click', (event) => {
|
||
const card = event.target.closest('[data-dish]')
|
||
if (!card) return
|
||
const dish = DISHES.find((d) => d.id === card.dataset.dish)
|
||
if (dish) openDish(dish)
|
||
})
|
||
|
||
$('cats').addEventListener('click', (event) => {
|
||
const button = event.target.closest('[data-cat]')
|
||
if (!button) return
|
||
document.querySelectorAll('.cat').forEach((el) => el.classList.toggle('on', el === button))
|
||
document.getElementById(`sec-${button.dataset.cat}`)?.scrollIntoView({ behavior: 'smooth', block: 'start' })
|
||
})
|
||
|
||
// ---------- 菜品详情 ----------
|
||
|
||
function openDish(dish) {
|
||
currentDish = dish
|
||
draft = { spec: {}, extras: [], qty: 1 }
|
||
for (const group of dish.specs ?? []) draft.spec[group.name] = group.options[0]
|
||
|
||
$('dishEmoji').textContent = dish.emoji
|
||
$('dishName').textContent = dish.name
|
||
$('dishDesc').textContent = dish.desc
|
||
$('dishTags').innerHTML = dish.tags.map((tag) => `<span class="badge">${esc(tag)}</span>`).join('')
|
||
$('dishNote').value = ''
|
||
$('dishQty').textContent = '1'
|
||
|
||
const groups = (dish.specs ?? []).map((group) => `
|
||
<div class="opt-group">
|
||
<h3>${esc(group.name)}</h3>
|
||
<div class="opts" data-group="${esc(group.name)}">
|
||
${group.options.map((option, index) => {
|
||
const delta = Array.isArray(group.price) ? group.price[index] ?? 0 : 0
|
||
return `<button class="opt${option === draft.spec[group.name] ? ' on' : ''}" type="button" data-opt="${esc(option)}">
|
||
${esc(option)}${delta ? ` +${money(delta)}` : ''}</button>`
|
||
}).join('')}
|
||
</div>
|
||
</div>`).join('')
|
||
|
||
const extras = dish.extras?.length ? `
|
||
<div class="opt-group">
|
||
<h3>加料(可多选)</h3>
|
||
<div class="opts">
|
||
${dish.extras.map((extra) => `<button class="opt" type="button" data-extra="${esc(extra.name)}">
|
||
${esc(extra.name)} +${money(extra.price)}</button>`).join('')}
|
||
</div>
|
||
</div>` : ''
|
||
|
||
$('specArea').innerHTML = groups + extras
|
||
paintDishFoot()
|
||
openSheet('dishSheet')
|
||
}
|
||
|
||
function paintDishFoot() {
|
||
const cents = priceOf(currentDish, draft.spec, draft.extras) * draft.qty
|
||
$('dishQty').textContent = String(draft.qty)
|
||
$('addToCart').textContent = `加入购物车 · ${money(cents)}`
|
||
}
|
||
|
||
$('specArea').addEventListener('click', (event) => {
|
||
const option = event.target.closest('[data-opt]')
|
||
if (option) {
|
||
const group = option.closest('[data-group]').dataset.group
|
||
draft.spec[group] = option.dataset.opt
|
||
option.closest('.opts').querySelectorAll('.opt').forEach((el) => el.classList.toggle('on', el === option))
|
||
paintDishFoot()
|
||
return
|
||
}
|
||
const extra = event.target.closest('[data-extra]')
|
||
if (extra) {
|
||
const name = extra.dataset.extra
|
||
const index = draft.extras.indexOf(name)
|
||
if (index >= 0) draft.extras.splice(index, 1)
|
||
else draft.extras.push(name)
|
||
extra.classList.toggle('on', index < 0)
|
||
paintDishFoot()
|
||
}
|
||
})
|
||
|
||
document.querySelectorAll('[data-qty]').forEach((button) => {
|
||
button.addEventListener('click', () => {
|
||
draft.qty = Math.max(1, draft.qty + Number(button.dataset.qty))
|
||
paintDishFoot()
|
||
})
|
||
})
|
||
|
||
$('addToCart').addEventListener('click', () => {
|
||
addToCart(currentDish, { ...draft, note: $('dishNote').value.trim() })
|
||
closeSheet('dishSheet')
|
||
paintCartBar()
|
||
toast(`已加入:${currentDish.name} × ${draft.qty}`)
|
||
})
|
||
|
||
// ---------- 购物车 ----------
|
||
|
||
function paintCartBar() {
|
||
const cart = readCart()
|
||
const sum = totals(cart, PROMOTIONS)
|
||
$('cartbar').hidden = sum.count === 0
|
||
$('cartCount').textContent = String(sum.count)
|
||
$('cartTotal').textContent = money(sum.payable)
|
||
$('cartHint').textContent = sum.discount
|
||
? `已选 ${sum.count} 件 · 已减 ${money(sum.discount)}`
|
||
: `已选 ${sum.count} 件`
|
||
}
|
||
|
||
function paintCartSheet() {
|
||
const cart = readCart()
|
||
const sum = totals(cart, PROMOTIONS)
|
||
$('orderNote').value = cart.note ?? ''
|
||
$('utensilsCount').textContent = String(cart.utensils ?? 0)
|
||
|
||
$('cartList').innerHTML = cart.items.length === 0
|
||
? '<p class="tip">购物车是空的,先点几道菜吧。</p>'
|
||
: cart.items.map((item, index) => {
|
||
const spec = [Object.entries(item.spec).map(([k, v]) => `${k}:${v}`).join(' '), item.extras.join(' ')]
|
||
.filter(Boolean).join(' · ')
|
||
return `
|
||
<div class="cart-line">
|
||
<div class="art">${item.emoji}</div>
|
||
<div class="info">
|
||
<b>${esc(item.name)}</b>
|
||
<small>${esc(spec)}${item.note ? ` · ${esc(item.note)}` : ''}</small>
|
||
</div>
|
||
<span class="price">${money(item.price * item.qty)}</span>
|
||
<div class="stepper small">
|
||
<button type="button" data-minus="${index}" aria-label="减少">−</button>
|
||
<b>${item.qty}</b>
|
||
<button type="button" data-plus="${index}" aria-label="增加">+</button>
|
||
</div>
|
||
</div>`
|
||
}).join('')
|
||
|
||
$('cartSums').innerHTML = `
|
||
<div><span>小计</span><span>${money(sum.subtotal)}</span></div>
|
||
${sum.promo ? `<div class="off"><span>${esc(sum.promo.label)}</span><span>−${money(sum.discount)}</span></div>` : ''}
|
||
<div><span>餐具</span><span>${cart.utensils ?? 0} 份</span></div>`
|
||
|
||
$('cartPayable').textContent = money(sum.payable)
|
||
$('submitOrder').disabled = cart.items.length === 0
|
||
}
|
||
|
||
$('cartList').addEventListener('click', (event) => {
|
||
const cart = readCart()
|
||
const minus = event.target.closest('[data-minus]')
|
||
const plus = event.target.closest('[data-plus]')
|
||
const index = Number((minus ?? plus)?.dataset?.[minus ? 'minus' : 'plus'])
|
||
if (Number.isNaN(index)) return
|
||
const item = cart.items[index]
|
||
if (!item) return
|
||
changeQty(item.key, item.note, minus ? -1 : 1)
|
||
paintCartSheet()
|
||
paintCartBar()
|
||
})
|
||
|
||
$('orderNote').addEventListener('input', () => {
|
||
const cart = readCart()
|
||
cart.note = $('orderNote').value
|
||
writeCart(cart)
|
||
})
|
||
|
||
$('utensilsPlus').addEventListener('click', () => {
|
||
const cart = readCart()
|
||
cart.utensils = Math.min(20, (cart.utensils ?? 0) + 1)
|
||
writeCart(cart)
|
||
$('utensilsCount').textContent = String(cart.utensils)
|
||
paintCartSheet()
|
||
})
|
||
|
||
$('utensilsMinus').addEventListener('click', () => {
|
||
const cart = readCart()
|
||
cart.utensils = Math.max(0, (cart.utensils ?? 0) - 1)
|
||
writeCart(cart)
|
||
$('utensilsCount').textContent = String(cart.utensils)
|
||
paintCartSheet()
|
||
})
|
||
|
||
$('clearCart').addEventListener('click', () => {
|
||
clearCart()
|
||
paintCartSheet()
|
||
paintCartBar()
|
||
toast('购物车已清空')
|
||
})
|
||
|
||
$('cartbarMain').addEventListener('click', () => {
|
||
if (!table) return chooseTable()
|
||
paintCartSheet()
|
||
openSheet('cartSheet')
|
||
})
|
||
|
||
$('checkout').addEventListener('click', () => {
|
||
if (!table) return chooseTable()
|
||
paintCartSheet()
|
||
openSheet('cartSheet')
|
||
})
|
||
|
||
$('submitOrder').addEventListener('click', () => {
|
||
const cart = readCart()
|
||
if (cart.items.length === 0) return
|
||
if (!table) return chooseTable()
|
||
cart.note = $('orderNote').value.trim()
|
||
writeCart(cart)
|
||
const order = submitOrder(cart, { table, promotions: PROMOTIONS })
|
||
closeSheet('cartSheet')
|
||
paintCartBar()
|
||
showOrder(order.id)
|
||
toast(`下单成功,单号 ${order.no}`)
|
||
})
|
||
|
||
// ---------- 选桌 ----------
|
||
|
||
function chooseTable() {
|
||
const tables = ['A1', 'A2', 'A3', 'A4', 'B1', 'B2', 'B3', 'B4', 'C1', 'C2', '大厅 5', '包间 1']
|
||
const html = tables.map((name) => `<button class="opt" type="button" data-table="${esc(name)}">${esc(name)}</button>`).join('')
|
||
openSheet('historySheet')
|
||
$('historyList').innerHTML = `
|
||
<p class="tip">扫桌上的码会自动带出桌号;也可以手动选:</p>
|
||
<div class="opts">${html}</div>`
|
||
$('historyList').onclick = (event) => {
|
||
const button = event.target.closest('[data-table]')
|
||
if (!button) return
|
||
table = button.dataset.table
|
||
setTable(table)
|
||
paintShop()
|
||
closeSheet('historySheet')
|
||
toast(`已选 ${table} 桌`)
|
||
if (readCart().items.length) { paintCartSheet(); openSheet('cartSheet') }
|
||
}
|
||
}
|
||
|
||
$('tableBtn').addEventListener('click', chooseTable)
|
||
|
||
// ---------- 订单页 ----------
|
||
|
||
function showOrder(id) {
|
||
activeOrderId = id
|
||
paintOrder()
|
||
$('orderPage').hidden = false
|
||
}
|
||
|
||
function paintOrder() {
|
||
const order = orderById(activeOrderId)
|
||
if (!order) { $('orderPage').hidden = true; return }
|
||
const status = STATUS[order.status] ?? STATUS.new
|
||
const steps = [['new', '已下单'], ['cooking', '制作中'], ['served', '已上齐']]
|
||
const index = steps.findIndex(([key]) => key === order.status)
|
||
const stepHtml = steps.map(([key, label], i) => `
|
||
<div class="step${i <= index ? ' done' : ''}"><div class="bar"></div><small>${label}</small></div>`).join('')
|
||
|
||
$('statusCard').innerHTML = `
|
||
<h3>${esc(status.text)}</h3>
|
||
<p>${order.table} 桌 · 单号 ${order.no} · ${clock(order.createdAt)} 下单</p>
|
||
<div class="steps">${stepHtml}</div>`
|
||
|
||
$('orderDetail').innerHTML = `
|
||
<h4>菜品</h4>
|
||
${order.items.map((item) => {
|
||
const spec = [Object.entries(item.spec).map(([k, v]) => `${k}:${v}`).join(' '), item.extras.join(' ')]
|
||
.filter(Boolean).join(' · ')
|
||
return `<div class="kv"><span>${esc(item.name)}${spec ? ` <small class="meta">${esc(spec)}</small>` : ''} × ${item.qty}</span>
|
||
<span>${money(item.price * item.qty)}</span></div>`
|
||
}).join('')}
|
||
${order.note ? `<div class="kv"><span>备注</span><span>${esc(order.note)}</span></div>` : ''}
|
||
<div class="kv"><span>小计</span><span>${money(order.subtotal)}</span></div>
|
||
${order.discount ? `<div class="kv"><span>${esc(order.promoLabel)}</span><span>−${money(order.discount)}</span></div>` : ''}
|
||
<div class="kv total"><span>应付</span><span>${money(order.payable)}</span></div>`
|
||
|
||
$('urge').disabled = order.status === 'served' || order.status === 'closed'
|
||
}
|
||
|
||
$('orderBack').addEventListener('click', () => { $('orderPage').hidden = true })
|
||
$('addMore').addEventListener('click', () => {
|
||
$('orderPage').hidden = true
|
||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||
})
|
||
$('urge').addEventListener('click', () => {
|
||
const order = orderById(activeOrderId)
|
||
if (!order) return
|
||
updateOrder(order.id, { urgedAt: Date.now() })
|
||
toast('已经提醒后厨,请稍等')
|
||
})
|
||
|
||
$('orderList').addEventListener('click', () => {
|
||
const orders = readOrders().filter((order) => order.table === table)
|
||
$('historyList').innerHTML = orders.length === 0
|
||
? '<p class="tip">本桌还没有订单。</p>'
|
||
: orders.map((order) => {
|
||
const status = STATUS[order.status] ?? STATUS.new
|
||
return `<div class="hist-item" data-open="${order.id}">
|
||
<div><b>${order.no} 号单</b><small>${clock(order.createdAt)} · ${order.items.length} 个菜 · ${money(order.payable)}</small></div>
|
||
<span class="pill ${status.tone}">${status.text}</span>
|
||
</div>`
|
||
}).join('')
|
||
$('historyList').onclick = (event) => {
|
||
const row = event.target.closest('[data-open]')
|
||
if (!row) return
|
||
closeSheet('historySheet')
|
||
showOrder(row.dataset.open)
|
||
}
|
||
openSheet('historySheet')
|
||
})
|
||
|
||
// ---------- 同步 ----------
|
||
|
||
watch(() => {
|
||
paintCartBar()
|
||
if (!$('cartSheet').hidden) paintCartSheet()
|
||
if (activeOrderId && !$('orderPage').hidden) paintOrder()
|
||
})
|
||
|
||
// ---------- 启动 ----------
|
||
|
||
table = getTable()
|
||
paintShop()
|
||
paintCats()
|
||
paintMenu()
|
||
paintCartBar()
|
||
if (!table) setTimeout(chooseTable, 400)
|
||
if (readCart().items.length) toast(`购物车里还有 ${totals(readCart(), PROMOTIONS).count} 件,继续点`)
|
||
|
||
// 分类栏默认高亮第一个
|
||
document.querySelector('.cat')?.classList.add('on')
|