Files
dine-order/js/store.js
T
2026-11-17 12:29:33 +08:00

189 lines
5.6 KiB
JavaScript

// 本地状态:桌号、购物车、订单。同一台手机同一浏览器内,顾客页和后厨页实时同步。
const K_TABLE = 'dine.table.v1'
const K_CART = 'dine.cart.v1'
const K_ORDERS = 'dine.orders.v1'
const K_NO = 'dine.no.v1'
const channel = typeof BroadcastChannel === 'function' ? new BroadcastChannel('dine-sync') : null
function readJSON(key, fallback) {
try {
const raw = localStorage.getItem(key)
return raw === null ? fallback : JSON.parse(raw)
} catch {
return fallback
}
}
function writeJSON(key, value) {
localStorage.setItem(key, JSON.stringify(value))
channel?.postMessage(key)
}
/** 订阅其他标签页的改动(顾客页 ↔ 后厨页)。 */
export function watch(callback) {
const handler = (event) => {
if (event?.key && event.key.startsWith('dine.')) callback(event.key)
}
window.addEventListener('storage', handler)
const onMessage = (event) => callback(event.data)
channel?.addEventListener('message', (event) => onMessage(event))
return () => window.removeEventListener('storage', handler)
}
export function money(cents) {
return `¥${(cents / 100).toFixed(2).replace(/\.00$/, '')}`
}
export function clock(ts) {
return new Date(ts).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}
/** 桌号:优先取链接参数 ?table=A3,其次本地记住的,最后让顾客自己选。 */
export function getTable() {
const fromUrl = new URLSearchParams(location.search).get('table')
if (fromUrl) {
localStorage.setItem(K_TABLE, fromUrl.trim().toUpperCase())
return fromUrl.trim().toUpperCase()
}
return localStorage.getItem(K_TABLE) ?? ''
}
export function setTable(table) {
localStorage.setItem(K_TABLE, String(table).trim().toUpperCase())
}
// ---------- 购物车 ----------
export function emptyCart() {
return { items: [], note: '', utensils: 0 }
}
export function readCart() {
const cart = readJSON(K_CART, emptyCart())
return { ...emptyCart(), ...cart }
}
export function writeCart(cart) {
writeJSON(K_CART, cart)
}
export function itemKey(dish, spec, extras) {
const parts = Object.entries(spec ?? {}).sort(([a], [b]) => a.localeCompare(b))
const ex = [...(extras ?? [])].sort()
return [dish.id, JSON.stringify(parts), JSON.stringify(ex)].join('|')
}
export function priceOf(dish, spec, extras) {
let cents = dish.price
for (const group of dish.specs ?? []) {
const chosen = spec?.[group.name]
if (chosen == null) continue
const index = group.options.indexOf(chosen)
const delta = Array.isArray(group.price) ? group.price[index] ?? 0 : 0
cents += delta
}
for (const name of extras ?? []) {
const extra = (dish.extras ?? []).find((e) => e.name === name)
if (extra) cents += extra.price
}
return cents
}
export function addToCart(dish, { spec = {}, extras = [], qty = 1, note = '' } = {}) {
const cart = readCart()
const key = itemKey(dish, spec, extras)
const existing = cart.items.find((item) => item.key === key && item.note === note)
if (existing) {
existing.qty += qty
} else {
cart.items.push({
key, id: dish.id, name: dish.name, emoji: dish.emoji,
spec: { ...spec }, extras: [...extras], note, qty, price: priceOf(dish, spec, extras),
})
}
writeCart(cart)
return cart
}
export function changeQty(key, note, delta) {
const cart = readCart()
const item = cart.items.find((i) => i.key === key && i.note === note)
if (!item) return cart
item.qty += delta
if (item.qty <= 0) cart.items = cart.items.filter((i) => i !== item)
writeCart(cart)
return cart
}
export function clearCart() {
writeCart(emptyCart())
}
/** 满减:取满足条件里优惠最大的一档。 */
export function totals(cart, promotions) {
const subtotal = cart.items.reduce((sum, item) => sum + item.price * item.qty, 0)
const count = cart.items.reduce((sum, item) => sum + item.qty, 0)
const promo = [...promotions].sort((a, b) => b.threshold - a.threshold)
.find((p) => subtotal >= p.threshold) ?? null
const discount = promo ? promo.off : 0
return { count, subtotal, discount, payable: Math.max(0, subtotal - discount), promo }
}
// ---------- 订单 ----------
export function readOrders() {
return readJSON(K_ORDERS, [])
}
function nextNo() {
const today = new Date().toISOString().slice(0, 10)
const state = readJSON(K_NO, { date: today, seq: 0 })
const seq = state.date === today ? state.seq + 1 : 1
localStorage.setItem(K_NO, JSON.stringify({ date: today, seq }))
return String(seq).padStart(3, '0')
}
export function submitOrder(cart, { table, promotions }) {
const sum = totals(cart, promotions)
const now = Date.now()
const order = {
id: `o${now}${Math.floor(Math.random() * 90 + 10)}`,
no: nextNo(),
table,
items: cart.items.map((item) => ({ ...item })),
note: cart.note,
utensils: cart.utensils,
subtotal: sum.subtotal,
discount: sum.discount,
payable: sum.payable,
promoLabel: sum.promo?.label ?? '',
status: 'new',
createdAt: now,
updatedAt: now,
}
const orders = readOrders()
orders.unshift(order)
writeJSON(K_ORDERS, orders.slice(0, 200))
clearCart()
return order
}
export function updateOrder(id, patch) {
const orders = readOrders().map((order) =>
order.id === id ? { ...order, ...patch, updatedAt: Date.now() } : order)
writeJSON(K_ORDERS, orders)
return orders
}
export function orderById(id) {
return readOrders().find((order) => order.id === id) ?? null
}
export const STATUS = {
new: { text: '待接单', tone: 'warn' },
cooking: { text: '制作中', tone: 'info' },
served: { text: '已上齐', tone: 'good' },
closed: { text: '已结账', tone: 'muted' },
}