feat(ordering): orders priced by the server (platform-v2 step 4.4)
The waiter app (and the manager's ordering tab) send what was chosen, by id; the
server prices it with the counter's code. No app sends a price any more.
- POST /api/orders/{id}/items takes `lines` (pos_cart's line + course_id,
price_adjustment, is_service_item): sales point checked first, refusals name the
product and line (order.line.*, order.not_sold_here); prices or selected_options in a
line -> order.line.client_price, the old `items` shape -> order.lines_required; a
by-hand price change needs ordering.prices.modify or a manager's approval (audited
PRICE_SET_BY_HAND). add_priced_items is the one writer of priced items (pos too).
- POST /api/orders/quote: the cart's total before sending; /api/pos/quote shares
pos_cart.quote().
- pos_cart: a preference set left out takes its default; a set at its free default
isn't stored; a default that costs is charged (the waiter never sent it: fixed);
an extra's sub-choice is charged per extra (the counter charged it once: fixed).
- @xenia/api lines.js: lineFromOptions / wireLine / estimate / LineError.
- Waiter: lines on send; cart total from the quote ("≈ estimate" offline); summary
shows the same prices; offline orders queued by id, priced on sync, refused lines
shown on a "Δεν στάλθηκαν" sheet (no empty order opened); dead ItemOptionsModal gone.
- Tests: test_order_lines.py (14), lines.test.mjs, waiter e2e +6.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -27,6 +27,7 @@ import OrderLogPage from './pages/OrderLogPage'
|
||||
import { NotificationProvider } from './context/NotificationContext'
|
||||
import { LiveProvider } from './context/LiveContext'
|
||||
import ConnectivityBar from './components/ConnectivityBar'
|
||||
import RefusedLines from './components/RefusedLines'
|
||||
import AppShell from './components/AppShell'
|
||||
import UpdatePrompt from './components/UpdatePrompt'
|
||||
import InstallAppDialog from './components/InstallAppDialog'
|
||||
@@ -473,6 +474,7 @@ function Routed() {
|
||||
<LiveProvider>
|
||||
<NotificationProvider>
|
||||
<ConnectivityBar />
|
||||
<RefusedLines />
|
||||
{/* Native builds ship their UI in the app bundle — no service worker to update */}
|
||||
{deliveryMode() !== 'native' && <UpdatePrompt />}
|
||||
<InstallAppDialog />
|
||||
|
||||
@@ -1,521 +0,0 @@
|
||||
import { useState, useRef } from 'react'
|
||||
|
||||
// Unit metadata: step, min, quick-preset values, quick ± offset buttons
|
||||
const UNIT_CONFIG = {
|
||||
kg: { step: 0.1, min: 0.1, presets: [0.2, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0], offsets: [0.2, 0.5, 1.0], label: 'kg' },
|
||||
liter: { step: 0.1, min: 0.1, presets: [0.2, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0], offsets: [0.2, 0.5, 1.0], label: 'L' },
|
||||
gram: { step: 10, min: 10, presets: [50, 100, 150, 200, 250, 300, 400, 500], offsets: [50, 100, 200], label: 'g' },
|
||||
ml: { step: 5, min: 5, presets: [25, 50, 100, 150, 200, 250, 300, 500], offsets: [25, 50, 100], label: 'mL' },
|
||||
}
|
||||
const DECIMAL_UNITS = new Set(Object.keys(UNIT_CONFIG))
|
||||
|
||||
function fmtQty(qty, unitCfg) {
|
||||
if (!unitCfg) return String(qty)
|
||||
if (unitCfg.label === 'kg' || unitCfg.label === 'L') return Number(qty).toFixed(1)
|
||||
return String(qty)
|
||||
}
|
||||
|
||||
export default function ItemOptionsModal({ product, onAdd, onClose }) {
|
||||
const [selectedOptions, setSelectedOptions] = useState([])
|
||||
const [removedIngredients, setRemovedIngredients] = useState([])
|
||||
const [notes, setNotes] = useState('')
|
||||
|
||||
const unitCfg = UNIT_CONFIG[product.unit_type] ?? null
|
||||
const isDecimal = DECIMAL_UNITS.has(product.unit_type)
|
||||
const [quantity, setQuantity] = useState(isDecimal ? (unitCfg?.presets[0] ?? 0.1) : 1)
|
||||
const [qtyInput, setQtyInput] = useState('')
|
||||
const [editingQty, setEditingQty] = useState(false)
|
||||
const qtyRef = useRef(null)
|
||||
|
||||
const options = product.options || []
|
||||
const ingredients = product.ingredients || []
|
||||
const preferenceSets = product.preference_sets || []
|
||||
|
||||
// selectedPreferences: { [setId]: choice | null } (single-select sets)
|
||||
const [selectedPreferences, setSelectedPreferences] = useState(() =>
|
||||
Object.fromEntries(
|
||||
preferenceSets.filter(ps => !ps.allow_multi_select).map(ps => {
|
||||
const def = ps.default_choice_id != null
|
||||
? ps.choices.find(c => c.id === ps.default_choice_id) ?? null
|
||||
: null
|
||||
return [ps.id, def]
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
// multiPreferences: { [setId]: Array<{choice, qty}> } (multi-select sets)
|
||||
const [multiPreferences, setMultiPreferences] = useState(() =>
|
||||
Object.fromEntries(
|
||||
preferenceSets.filter(ps => ps.allow_multi_select).map(ps => {
|
||||
const def = ps.default_choice_id != null
|
||||
? ps.choices.find(c => c.id === ps.default_choice_id) ?? null
|
||||
: null
|
||||
return [ps.id, def ? [{ choice: def, qty: 1 }] : []]
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
// Per-preference-choice inline sub-choices: { [choiceId]: subChoice | null }
|
||||
const [selectedSubChoices, setSelectedSubChoices] = useState(() => {
|
||||
const init = {}
|
||||
preferenceSets.filter(ps => !ps.allow_multi_select).forEach(ps => {
|
||||
const def = ps.default_choice_id != null
|
||||
? ps.choices.find(c => c.id === ps.default_choice_id) ?? null
|
||||
: null
|
||||
if (def && def.sub_choices?.length > 0) {
|
||||
const subDef = def.sub_choices.find(s => s.is_default) ?? def.sub_choices[0]
|
||||
init[def.id] = subDef
|
||||
}
|
||||
})
|
||||
return init
|
||||
})
|
||||
|
||||
// Shared-subset selections: { [setId]: subChoice | null }
|
||||
const [selectedSharedSubs, setSelectedSharedSubs] = useState(() => {
|
||||
const init = {}
|
||||
preferenceSets.filter(ps => !ps.allow_multi_select).forEach(ps => {
|
||||
if (ps.shared_subset?.choices?.length > 0) {
|
||||
const selectedChoice = ps.default_choice_id != null
|
||||
? ps.choices.find(c => c.id === ps.default_choice_id) ?? null
|
||||
: null
|
||||
if (!selectedChoice || !selectedChoice.disables_subset) {
|
||||
const subDef = ps.shared_subset.choices.find(s => s.is_default) ?? ps.shared_subset.choices[0]
|
||||
init[ps.id] = subDef
|
||||
}
|
||||
}
|
||||
})
|
||||
return init
|
||||
})
|
||||
|
||||
// Option sub-choices: { [optionId]: subChoice | null }
|
||||
// Initialise with any option that has a default sub-choice pre-selected — but only
|
||||
// if the option itself is checked by default (options are all unchecked initially).
|
||||
const [selectedOptionSubs, setSelectedOptionSubs] = useState({})
|
||||
|
||||
function selectPreference(setId, choice) {
|
||||
setSelectedPreferences(prev => ({ ...prev, [setId]: choice }))
|
||||
if (choice && choice.sub_choices?.length > 0) {
|
||||
const subDef = choice.sub_choices.find(s => s.is_default) ?? choice.sub_choices[0]
|
||||
setSelectedSubChoices(prev => ({ ...prev, [choice.id]: subDef }))
|
||||
}
|
||||
const ps = preferenceSets.find(p => p.id === setId)
|
||||
if (ps?.shared_subset?.choices?.length > 0 && !choice?.disables_subset) {
|
||||
setSelectedSharedSubs(prev => {
|
||||
if (prev[setId] != null) return prev
|
||||
const subDef = ps.shared_subset.choices.find(s => s.is_default) ?? ps.shared_subset.choices[0]
|
||||
return { ...prev, [setId]: subDef }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function toggleMultiChoice(setId, choice) {
|
||||
setMultiPreferences(prev => {
|
||||
const current = prev[setId] ?? []
|
||||
const idx = current.findIndex(e => e.choice.id === choice.id)
|
||||
if (idx >= 0) return { ...prev, [setId]: current.filter((_, i) => i !== idx) }
|
||||
return { ...prev, [setId]: [...current, { choice, qty: 1 }] }
|
||||
})
|
||||
}
|
||||
|
||||
function setMultiChoiceQty(setId, choiceId, delta) {
|
||||
setMultiPreferences(prev => {
|
||||
const current = prev[setId] ?? []
|
||||
return {
|
||||
...prev,
|
||||
[setId]: current.map(e =>
|
||||
e.choice.id === choiceId ? { ...e, qty: Math.max(1, e.qty + delta) } : e
|
||||
),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function selectSubChoice(parentChoiceId, sub) {
|
||||
setSelectedSubChoices(prev => ({ ...prev, [parentChoiceId]: sub }))
|
||||
}
|
||||
|
||||
function selectSharedSub(setId, sub) {
|
||||
setSelectedSharedSubs(prev => ({ ...prev, [setId]: sub }))
|
||||
}
|
||||
|
||||
function toggleOption(opt) {
|
||||
setSelectedOptions(prev => {
|
||||
const exists = prev.find(o => o.id === opt.id)
|
||||
if (exists) {
|
||||
// Deselecting: also clear its sub-choice selection
|
||||
setSelectedOptionSubs(s => { const n = { ...s }; delete n[opt.id]; return n })
|
||||
return prev.filter(o => o.id !== opt.id)
|
||||
}
|
||||
// Selecting: pre-select default sub-choice if any
|
||||
if (opt.sub_choices?.length > 0) {
|
||||
const subDef = opt.sub_choices.find(s => s.is_default) ?? opt.sub_choices[0]
|
||||
setSelectedOptionSubs(s => ({ ...s, [opt.id]: subDef }))
|
||||
}
|
||||
return [...prev, { id: opt.id, name: opt.name, price_delta: opt.extra_cost ?? 0 }]
|
||||
})
|
||||
}
|
||||
|
||||
function selectOptionSub(optId, sub) {
|
||||
setSelectedOptionSubs(prev => ({ ...prev, [optId]: sub }))
|
||||
}
|
||||
|
||||
function toggleIngredient(ing) {
|
||||
setRemovedIngredients(prev =>
|
||||
prev.includes(ing.name) ? prev.filter(n => n !== ing.name) : [...prev, ing.name]
|
||||
)
|
||||
}
|
||||
|
||||
// Check whether any checked option with sub_choices is missing its sub-choice selection
|
||||
const optionSubsMissing = selectedOptions.some(o => {
|
||||
const full = options.find(opt => opt.id === o.id)
|
||||
return full?.sub_choices?.length > 0 && selectedOptionSubs[o.id] == null
|
||||
})
|
||||
|
||||
function isPrefSetComplete(ps) {
|
||||
if (ps.allow_multi_select) {
|
||||
return (multiPreferences[ps.id] ?? []).length > 0
|
||||
}
|
||||
const choice = selectedPreferences[ps.id]
|
||||
if (choice == null) return false
|
||||
if (choice.sub_choices?.length > 0 && selectedSubChoices[choice.id] == null) return false
|
||||
if (ps.shared_subset?.choices?.length > 0 && !choice.disables_subset && selectedSharedSubs[ps.id] == null) return false
|
||||
return true
|
||||
}
|
||||
|
||||
const allPrefsSelected = preferenceSets.every(isPrefSetComplete)
|
||||
const unselectedPrefs = preferenceSets.filter(ps => !isPrefSetComplete(ps))
|
||||
const canAdd = allPrefsSelected && !optionSubsMissing
|
||||
|
||||
const prefExtra = preferenceSets.reduce((s, ps) => {
|
||||
if (ps.allow_multi_select) {
|
||||
return s + (multiPreferences[ps.id] ?? []).reduce((acc, { choice, qty }) => acc + (choice.extra_cost ?? 0) * qty, 0)
|
||||
}
|
||||
const choice = selectedPreferences[ps.id]
|
||||
if (!choice) return s
|
||||
const inlineSub = choice.sub_choices?.length > 0 ? (selectedSubChoices[choice.id] ?? null) : null
|
||||
const sharedSub = (ps.shared_subset?.choices?.length > 0 && !choice.disables_subset)
|
||||
? (selectedSharedSubs[ps.id] ?? null) : null
|
||||
return s + (choice.extra_cost ?? 0) + (inlineSub?.extra_cost ?? 0) + (sharedSub?.extra_cost ?? 0)
|
||||
}, 0)
|
||||
const optionExtra = selectedOptions.reduce((s, o) => {
|
||||
const subExtra = selectedOptionSubs[o.id]?.extra_cost ?? 0
|
||||
return s + (o.price_delta ?? 0) + subExtra
|
||||
}, 0)
|
||||
const totalPrice = (product.base_price + optionExtra + prefExtra) * quantity
|
||||
|
||||
function handleAdd() {
|
||||
if (!canAdd) return
|
||||
const prefChoices = preferenceSets.flatMap(ps => {
|
||||
if (ps.allow_multi_select) {
|
||||
return (multiPreferences[ps.id] ?? []).map(({ choice, qty }) => ({
|
||||
id: choice.id,
|
||||
name: qty > 1 ? `${choice.name} x${qty}` : choice.name,
|
||||
price_delta: (choice.extra_cost ?? 0) * qty,
|
||||
type: 'pref',
|
||||
}))
|
||||
}
|
||||
const choice = selectedPreferences[ps.id]
|
||||
if (!choice) return []
|
||||
const entries = [{ id: choice.id, name: choice.name, price_delta: choice.extra_cost ?? 0, type: 'pref' }]
|
||||
const inlineSub = choice.sub_choices?.length > 0 ? (selectedSubChoices[choice.id] ?? null) : null
|
||||
if (inlineSub) entries.push({ id: null, name: inlineSub.name, price_delta: inlineSub.extra_cost ?? 0, type: 'pref_sub' })
|
||||
if (ps.shared_subset?.choices?.length > 0 && !choice.disables_subset) {
|
||||
const sharedSub = selectedSharedSubs[ps.id] ?? null
|
||||
if (sharedSub) entries.push({ id: null, name: sharedSub.name, price_delta: sharedSub.extra_cost ?? 0, type: 'pref_sub' })
|
||||
}
|
||||
return entries
|
||||
})
|
||||
|
||||
const optionEntries = selectedOptions.flatMap(o => {
|
||||
const entries = [{ id: o.id, name: o.name, price_delta: o.price_delta ?? 0, type: 'extra' }]
|
||||
const sub = selectedOptionSubs[o.id]
|
||||
if (sub) entries.push({ id: null, name: sub.name, price_delta: sub.extra_cost ?? 0, type: 'extra_sub' })
|
||||
return entries
|
||||
})
|
||||
|
||||
onAdd({
|
||||
product_id: product.id,
|
||||
quantity,
|
||||
selected_options: [...optionEntries, ...prefChoices],
|
||||
removed_ingredients: removedIngredients,
|
||||
notes,
|
||||
})
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="modal-overlay" onClick={onClose}>
|
||||
<div className="modal-sheet" onClick={e => e.stopPropagation()}>
|
||||
<div className="modal-handle" />
|
||||
<h2 className="modal-title">{product.name}</h2>
|
||||
<p className="modal-price">{Number(totalPrice).toFixed(2)} €</p>
|
||||
|
||||
{/* ── Checkbox options with optional sub-choices ── */}
|
||||
{options.length > 0 && (
|
||||
<section className="modal-section">
|
||||
<h3>Επιλογές</h3>
|
||||
{options.map(opt => {
|
||||
const isChecked = !!selectedOptions.find(o => o.id === opt.id)
|
||||
const hasSubs = opt.sub_choices?.length > 0
|
||||
const subMissing = isChecked && hasSubs && selectedOptionSubs[opt.id] == null
|
||||
return (
|
||||
<div key={opt.id}>
|
||||
<label className="modal-option">
|
||||
<input type="checkbox" checked={isChecked} onChange={() => toggleOption(opt)} />
|
||||
<span>{opt.name}</span>
|
||||
{(opt.extra_cost ?? 0) !== 0 && (
|
||||
<span className="option-price">{opt.extra_cost > 0 ? '+' : ''}{Number(opt.extra_cost).toFixed(2)} €</span>
|
||||
)}
|
||||
</label>
|
||||
{isChecked && hasSubs && (
|
||||
<div style={{
|
||||
marginLeft: 24, marginTop: 4, marginBottom: 6,
|
||||
padding: '8px 12px', borderRadius: 8,
|
||||
borderLeft: `3px solid ${subMissing ? '#ef4444' : '#6366f1'}`,
|
||||
}}>
|
||||
{subMissing && <p style={{ fontSize: 12, color: '#ef4444', margin: '0 0 4px' }}>— απαιτείται επιλογή</p>}
|
||||
{opt.sub_choices.map((sub, si) => (
|
||||
<label key={si} className="modal-option" style={{ fontSize: 14 }}>
|
||||
<input type="radio" name={`optsub-${opt.id}`}
|
||||
checked={selectedOptionSubs[opt.id]?.name === sub.name}
|
||||
onChange={() => selectOptionSub(opt.id, sub)} />
|
||||
<span>{sub.name}</span>
|
||||
{(sub.extra_cost ?? 0) !== 0 && (
|
||||
<span className="option-price">{sub.extra_cost > 0 ? '+' : ''}{Number(sub.extra_cost).toFixed(2)} €</span>
|
||||
)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* ── Preference sets ── */}
|
||||
{preferenceSets.map(ps => {
|
||||
const missing = !isPrefSetComplete(ps)
|
||||
|
||||
if (ps.allow_multi_select) {
|
||||
const selected = multiPreferences[ps.id] ?? []
|
||||
return (
|
||||
<section key={ps.id} className="modal-section"
|
||||
style={missing ? { border: '1.5px solid #ef4444', borderRadius: 10, padding: '10px 12px' } : {}}>
|
||||
<h3 style={{ color: missing ? '#ef4444' : undefined }}>
|
||||
{ps.name}
|
||||
{missing && <span style={{ fontSize: 12, marginLeft: 6, fontWeight: 400 }}>— επιλέξτε τουλάχιστον μία</span>}
|
||||
</h3>
|
||||
{ps.choices.map(ch => {
|
||||
const entry = selected.find(e => e.choice.id === ch.id)
|
||||
const isChecked = !!entry
|
||||
return (
|
||||
<div key={ch.id} style={{ marginBottom: 6 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<label className="modal-option" style={{ flex: 1 }}>
|
||||
<input type="checkbox" checked={isChecked}
|
||||
onChange={() => toggleMultiChoice(ps.id, ch)} />
|
||||
<span>{ch.name}</span>
|
||||
{(ch.extra_cost ?? 0) !== 0 && (
|
||||
<span className="option-price">{ch.extra_cost > 0 ? '+' : ''}{Number(ch.extra_cost).toFixed(2)} €</span>
|
||||
)}
|
||||
</label>
|
||||
{isChecked && ps.allow_choice_quantity && (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
|
||||
<button className="qty-btn" style={{ width: 28, height: 28, fontSize: 16 }}
|
||||
onClick={() => setMultiChoiceQty(ps.id, ch.id, -1)}>−</button>
|
||||
<span style={{ minWidth: 20, textAlign: 'center', fontWeight: 600, fontSize: 15 }}>{entry.qty}</span>
|
||||
<button className="qty-btn" style={{ width: 28, height: 28, fontSize: 16 }}
|
||||
onClick={() => setMultiChoiceQty(ps.id, ch.id, 1)}>+</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
const selectedChoice = selectedPreferences[ps.id] ?? null
|
||||
const showSharedSubset = ps.shared_subset?.choices?.length > 0
|
||||
&& selectedChoice != null
|
||||
&& !selectedChoice.disables_subset
|
||||
const sharedMissing = showSharedSubset && selectedSharedSubs[ps.id] == null
|
||||
|
||||
return (
|
||||
<section key={ps.id} className="modal-section"
|
||||
style={missing ? { border: '1.5px solid #ef4444', borderRadius: 10, padding: '10px 12px' } : {}}>
|
||||
<h3 style={{ color: missing ? '#ef4444' : undefined }}>
|
||||
{ps.name}
|
||||
{missing && <span style={{ fontSize: 12, marginLeft: 6, fontWeight: 400 }}>— απαιτείται επιλογή</span>}
|
||||
</h3>
|
||||
|
||||
{ps.choices.map(ch => {
|
||||
const isSelected = selectedPreferences[ps.id]?.id === ch.id
|
||||
const hasSubs = ch.sub_choices?.length > 0
|
||||
const subMissing = isSelected && hasSubs && selectedSubChoices[ch.id] == null
|
||||
return (
|
||||
<div key={ch.id}>
|
||||
<label className="modal-option">
|
||||
<input type="radio" name={`pref-${ps.id}`} checked={isSelected}
|
||||
onChange={() => selectPreference(ps.id, ch)} />
|
||||
<span>{ch.name}</span>
|
||||
{(ch.extra_cost ?? 0) !== 0 && (
|
||||
<span className="option-price">{ch.extra_cost > 0 ? '+' : ''}{Number(ch.extra_cost).toFixed(2)} €</span>
|
||||
)}
|
||||
</label>
|
||||
{isSelected && hasSubs && (
|
||||
<div style={{
|
||||
marginLeft: 24, marginTop: 4, marginBottom: 6,
|
||||
padding: '8px 12px', borderRadius: 8,
|
||||
borderLeft: `3px solid ${subMissing ? '#ef4444' : '#6366f1'}`,
|
||||
}}>
|
||||
{subMissing && <p style={{ fontSize: 12, color: '#ef4444', margin: '0 0 4px' }}>— απαιτείται επιλογή</p>}
|
||||
{ch.sub_choices.map((sub, si) => (
|
||||
<label key={si} className="modal-option" style={{ fontSize: 14 }}>
|
||||
<input type="radio" name={`sub-${ch.id}`}
|
||||
checked={selectedSubChoices[ch.id]?.name === sub.name}
|
||||
onChange={() => selectSubChoice(ch.id, sub)} />
|
||||
<span>{sub.name}</span>
|
||||
{(sub.extra_cost ?? 0) !== 0 && (
|
||||
<span className="option-price">{sub.extra_cost > 0 ? '+' : ''}{Number(sub.extra_cost).toFixed(2)} €</span>
|
||||
)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{showSharedSubset && (
|
||||
<div style={{
|
||||
marginTop: 8, marginLeft: 8, padding: '8px 12px', borderRadius: 8,
|
||||
borderLeft: `3px solid ${sharedMissing ? '#ef4444' : '#6366f1'}`,
|
||||
}}>
|
||||
<p style={{ fontSize: 13, fontWeight: 600, marginBottom: 6, color: sharedMissing ? '#ef4444' : '#4338ca' }}>
|
||||
{ps.shared_subset.name}
|
||||
{sharedMissing && <span style={{ fontSize: 12, marginLeft: 6, fontWeight: 400 }}>— απαιτείται επιλογή</span>}
|
||||
</p>
|
||||
{ps.shared_subset.choices.map((sub, si) => (
|
||||
<label key={si} className="modal-option" style={{ fontSize: 14 }}>
|
||||
<input type="radio" name={`shared-${ps.id}`}
|
||||
checked={selectedSharedSubs[ps.id]?.name === sub.name}
|
||||
onChange={() => selectSharedSub(ps.id, sub)} />
|
||||
<span>{sub.name}</span>
|
||||
{(sub.extra_cost ?? 0) !== 0 && (
|
||||
<span className="option-price">{sub.extra_cost > 0 ? '+' : ''}{Number(sub.extra_cost).toFixed(2)} €</span>
|
||||
)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* ── Remove ingredients ── */}
|
||||
{ingredients.length > 0 && (
|
||||
<section className="modal-section">
|
||||
<h3>Αφαίρεση υλικών</h3>
|
||||
{ingredients.map(ing => (
|
||||
<label key={ing.id} className="modal-option modal-option--remove">
|
||||
<input type="checkbox" checked={removedIngredients.includes(ing.name)}
|
||||
onChange={() => toggleIngredient(ing)} />
|
||||
<span>χωρίς {ing.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="modal-section">
|
||||
<h3>Σημείωση</h3>
|
||||
<textarea className="modal-notes" placeholder="π.χ. χωρίς αλάτι..."
|
||||
value={notes} onChange={e => setNotes(e.target.value)} rows={2} />
|
||||
</section>
|
||||
|
||||
{isDecimal ? (
|
||||
<div className="qty-decimal-panel">
|
||||
{/* Main ‒ / value / + row */}
|
||||
<div className="modal-qty">
|
||||
<button className="qty-btn" onClick={() => setQuantity(q => Math.max(unitCfg.min, Math.round((q - unitCfg.step) * 1000) / 1000))}>−</button>
|
||||
{editingQty ? (
|
||||
<input
|
||||
ref={qtyRef}
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
className="qty-decimal-input"
|
||||
value={qtyInput}
|
||||
onChange={e => setQtyInput(e.target.value)}
|
||||
onBlur={() => {
|
||||
const v = parseFloat(qtyInput)
|
||||
if (!isNaN(v) && v >= unitCfg.min) setQuantity(Math.round(v * 1000) / 1000)
|
||||
setEditingQty(false)
|
||||
}}
|
||||
onKeyDown={e => { if (e.key === 'Enter') e.target.blur() }}
|
||||
autoFocus
|
||||
/>
|
||||
) : (
|
||||
<span className="qty-value" style={{ cursor: 'text', minWidth: 64 }}
|
||||
onClick={() => { setQtyInput(String(quantity)); setEditingQty(true) }}>
|
||||
{fmtQty(quantity, unitCfg)} <span style={{ fontSize: 14, fontWeight: 500, opacity: 0.7 }}>{unitCfg.label}</span>
|
||||
</span>
|
||||
)}
|
||||
<button className="qty-btn" onClick={() => setQuantity(q => Math.round((q + unitCfg.step) * 1000) / 1000)}>+</button>
|
||||
</div>
|
||||
|
||||
{/* Quick preset values */}
|
||||
<div className="qty-presets">
|
||||
{unitCfg.presets.map(v => (
|
||||
<button key={v} className={`qty-preset-btn${quantity === v ? ' qty-preset-btn--active' : ''}`}
|
||||
onClick={() => setQuantity(v)}>
|
||||
{fmtQty(v, unitCfg)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Quick ± offset buttons */}
|
||||
<div className="qty-offsets">
|
||||
{unitCfg.offsets.map(off => (
|
||||
<button key={`+${off}`} className="qty-offset-btn qty-offset-btn--add"
|
||||
onClick={() => setQuantity(q => Math.round((q + off) * 1000) / 1000)}>
|
||||
+{fmtQty(off, unitCfg)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="qty-offsets">
|
||||
{unitCfg.offsets.map(off => (
|
||||
<button key={`-${off}`} className="qty-offset-btn qty-offset-btn--sub"
|
||||
onClick={() => setQuantity(q => Math.max(unitCfg.min, Math.round((q - off) * 1000) / 1000))}>
|
||||
−{fmtQty(off, unitCfg)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="modal-qty">
|
||||
<button className="qty-btn" onClick={() => setQuantity(q => Math.max(1, q - 1))}>−</button>
|
||||
<span className="qty-value">{quantity}</span>
|
||||
<button className="qty-btn" onClick={() => setQuantity(q => q + 1)}>+</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!allPrefsSelected && (
|
||||
<p style={{ color: '#ef4444', fontSize: 13, textAlign: 'center', marginTop: 8 }}>
|
||||
Επιλέξτε: {unselectedPrefs.map(ps => ps.name).join(', ')}
|
||||
</p>
|
||||
)}
|
||||
{optionSubsMissing && (
|
||||
<p style={{ color: '#ef4444', fontSize: 13, textAlign: 'center', marginTop: 4 }}>
|
||||
Επιλέξτε υπο-επιλογή για τις επιλεγμένες επιλογές
|
||||
</p>
|
||||
)}
|
||||
|
||||
<button className="btn btn--primary btn--lg" onClick={handleAdd} disabled={!canAdd}
|
||||
style={{ width: '100%', marginTop: 16, opacity: canAdd ? 1 : 0.45 }}>
|
||||
Προσθήκη στην παραγγελία
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1508,7 +1508,7 @@ export default function OrderDrawer({ product, isOpen, onClose, onAdd, initialSt
|
||||
<button onClick={() => setQty(q => q + 1)} style={{ width: 52, height: 52, border: 'none', background: 'transparent', fontSize: 22, fontWeight: 500, cursor: 'pointer', color: 'var(--text)' }}>+</button>
|
||||
</div>
|
||||
)}
|
||||
<button onClick={handleAdd} disabled={!canAdd} style={{
|
||||
<button data-testid="drawer-add" onClick={handleAdd} disabled={!canAdd} style={{
|
||||
flex: 1, height: 52, borderRadius: 26,
|
||||
background: canAdd ? 'var(--accent)' : 'var(--bg3)',
|
||||
border: 'none', color: canAdd ? 'var(--accent-fg)' : 'var(--muted)',
|
||||
|
||||
@@ -21,8 +21,7 @@ function describeOptions(selected_options) {
|
||||
}).filter(Boolean)
|
||||
}
|
||||
|
||||
function CartItemSummaryRow({ item, product, onEdit }) {
|
||||
const price = (item.unit_price ?? product?.base_price ?? 0) * item.quantity
|
||||
function CartItemSummaryRow({ item, product, price, estimated, onEdit }) {
|
||||
const opts = describeOptions(item.selected_options)
|
||||
const removed = item.removed_ingredients || []
|
||||
|
||||
@@ -58,7 +57,7 @@ function CartItemSummaryRow({ item, product, onEdit }) {
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8, flexShrink: 0 }}>
|
||||
<span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{fmtEUR(price)}</span>
|
||||
<span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{estimated ? '≈ ' : ''}{fmtEUR(price)}</span>
|
||||
{onEdit && (
|
||||
<button
|
||||
onClick={onEdit}
|
||||
@@ -73,11 +72,11 @@ function CartItemSummaryRow({ item, product, onEdit }) {
|
||||
)
|
||||
}
|
||||
|
||||
export default function OrderSummaryModal({ cart, products, orderNote, setOrderNote, onSend, onClose, sending }) {
|
||||
// prices / total: the server's (POST /api/orders/quote, plan step 4.4) or, offline, the menu's
|
||||
// estimate (`estimated`); priceError: a line the server would refuse.
|
||||
export default function OrderSummaryModal({ cart, products, prices, total, estimated, priceError, orderNote, setOrderNote, onSend, onClose, sending }) {
|
||||
const [noteEditing, setNoteEditing] = useState(false)
|
||||
|
||||
const total = cart.reduce((s, item) => s + (item.unit_price ?? 0) * item.quantity, 0)
|
||||
|
||||
function getProduct(id) { return products.find(p => p.id === id) }
|
||||
|
||||
return (
|
||||
@@ -103,7 +102,7 @@ export default function OrderSummaryModal({ cart, products, orderNote, setOrderN
|
||||
}}>
|
||||
<div>
|
||||
<div style={{ fontSize: 17, fontWeight: 800, color: 'var(--text)' }}>Επισκόπηση Παραγγελίας</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>{cart.length} {cart.length === 1 ? 'προϊόν' : 'προϊόντα'} · {fmtEUR(total)}</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>{cart.length} {cart.length === 1 ? 'προϊόν' : 'προϊόντα'} · {estimated ? '≈ ' : ''}{fmtEUR(total)}</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
@@ -116,11 +115,13 @@ export default function OrderSummaryModal({ cart, products, orderNote, setOrderN
|
||||
{/* Item list */}
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: '12px 12px 0' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{cart.map(item => (
|
||||
{cart.map((item, i) => (
|
||||
<CartItemSummaryRow
|
||||
key={item._key}
|
||||
item={item}
|
||||
product={getProduct(item.product_id)}
|
||||
price={prices?.[i] ?? 0}
|
||||
estimated={estimated}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -178,9 +179,10 @@ export default function OrderSummaryModal({ cart, products, orderNote, setOrderN
|
||||
|
||||
{/* Total */}
|
||||
<div style={{ marginTop: 12, marginBottom: 4, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 4px', borderTop: '1px solid var(--border)' }}>
|
||||
<span style={{ fontSize: 14, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.6 }}>Σύνολο</span>
|
||||
<span style={{ fontSize: 20, fontWeight: 800, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{fmtEUR(total)}</span>
|
||||
<span style={{ fontSize: 14, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.6 }}>{estimated ? 'Σύνολο (εκτίμηση)' : 'Σύνολο'}</span>
|
||||
<span data-testid="summary-total" data-estimated={estimated ? 'true' : 'false'} style={{ fontSize: 20, fontWeight: 800, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{estimated ? '≈ ' : ''}{fmtEUR(total)}</span>
|
||||
</div>
|
||||
{priceError && <div style={{ fontSize: 12, color: 'var(--danger)', padding: '0 4px 8px' }}>{priceError}</div>}
|
||||
</div>
|
||||
|
||||
{/* Footer — Send button */}
|
||||
|
||||
@@ -190,6 +190,8 @@ function ProductCard({ product, onOpen, onQuickAdd, onShowDetail }) {
|
||||
return (
|
||||
<div
|
||||
className="product-btn"
|
||||
data-testid="product-card"
|
||||
data-name={product.name}
|
||||
style={{ position: 'relative' }}
|
||||
onClick={handleClick}
|
||||
{...longPress.handlers}
|
||||
@@ -223,6 +225,7 @@ function ProductCard({ product, onOpen, onQuickAdd, onShowDetail }) {
|
||||
alignItems: 'center', justifyContent: 'center',
|
||||
}}>
|
||||
<button
|
||||
data-testid="product-quick-add"
|
||||
onPointerDown={e => e.stopPropagation()}
|
||||
onClick={e => { e.stopPropagation(); onQuickAdd(product) }}
|
||||
style={{
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import db from '../db/posdb'
|
||||
import { clearRefusedLines, refusedLines } from '../services/offlineOrders'
|
||||
import useAuthStore from '../store/authStore'
|
||||
|
||||
// Lines of an order taken offline that the server refused when the phone came back (plan
|
||||
// step 4.4): a product taken off the menu meanwhile, an option deleted, a price change not
|
||||
// allowed. They are never dropped silently: this sheet lists them, with the reason, until the
|
||||
// waiter confirms they've seen them (and dealt with the table).
|
||||
export default function RefusedLines() {
|
||||
const token = useAuthStore(s => s.token)
|
||||
const [lines, setLines] = useState([])
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return undefined
|
||||
const load = () => refusedLines().then(async list => {
|
||||
const named = await Promise.all(list.map(async l => {
|
||||
const t = l.tableId != null ? await db.pos_tables.get(Number(l.tableId)).catch(() => null) : null
|
||||
return { ...l, table: t ? (t.label || `T${t.number}`) : null }
|
||||
}))
|
||||
setLines(named)
|
||||
}).catch(() => {})
|
||||
load()
|
||||
window.addEventListener('refused-lines', load)
|
||||
return () => window.removeEventListener('refused-lines', load)
|
||||
}, [token])
|
||||
|
||||
if (!token || lines.length === 0) return null
|
||||
return (
|
||||
<div className="modal-overlay" data-testid="refused-lines">
|
||||
<div className="modal-sheet" onClick={e => e.stopPropagation()}>
|
||||
<div className="modal-handle" />
|
||||
<h2 className="modal-title">Δεν στάλθηκαν</h2>
|
||||
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 14px' }}>
|
||||
Τα παρακάτω πάρθηκαν χωρίς σύνδεση και ο server δεν τα δέχτηκε. Ελέγξτε τα τραπέζια.
|
||||
</p>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16, maxHeight: '45vh', overflowY: 'auto' }}>
|
||||
{lines.map((l, i) => (
|
||||
<div key={i} data-testid="refused-line" style={{ background: 'var(--bg3)', border: '1px solid var(--border)', borderRadius: 12, padding: '10px 12px' }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>
|
||||
{l.product} ×{l.quantity}
|
||||
{l.table && <span style={{ color: 'var(--muted)', fontWeight: 500 }}> · {l.table}</span>}
|
||||
</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--danger)', marginTop: 3 }}>{l.reason}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<button className="btn btn--primary" style={{ width: '100%' }} data-testid="refused-lines-ok" onClick={() => clearRefusedLines()}>
|
||||
Το είδα
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -13,6 +13,11 @@ import useConnectionStore from '../store/connectionStore'
|
||||
import useAuthStore from '../store/authStore'
|
||||
import { queueOfflineOrder } from '../services/offlineOrders'
|
||||
import { assetUrl } from '../config/server'
|
||||
import { LineError, estimate, wireLine } from '@xenia/api'
|
||||
|
||||
// A cart item whose option is not on the menu any more (4.4: lines go by id)
|
||||
const lineErrorText = err => `«${err.product}»: το «${err.what}» δεν υπάρχει πια στο μενού. Αφαιρέστε το και προσθέστε το ξανά.`
|
||||
const money = v => `${Number(v || 0).toFixed(2)} €`
|
||||
|
||||
// ─── Global Course Modal ──────────────────────────────────────────────────────
|
||||
|
||||
@@ -110,6 +115,28 @@ function CustomerCountModal({ value, onChange, onClose }) {
|
||||
)
|
||||
}
|
||||
|
||||
// ─── The cart's total (4.4) ───────────────────────────────────────────────────
|
||||
// The server's price (POST /api/orders/quote) when online; offline, or until it answers, the
|
||||
// menu's prices as an estimate. A line the server would refuse shows its reason here.
|
||||
|
||||
function CartTotal({ priced, estimatedTotal, offline }) {
|
||||
const exact = !!priced?.data
|
||||
return (
|
||||
<div data-testid="cart-total" data-estimated={exact ? 'false' : 'true'}
|
||||
style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
|
||||
<span style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 600 }}>
|
||||
{exact ? 'Σύνολο' : offline ? 'Σύνολο (εκτίμηση, χωρίς σύνδεση)' : 'Σύνολο (εκτίμηση)'}
|
||||
</span>
|
||||
<span style={{ fontSize: 17, fontWeight: 800, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>
|
||||
{exact ? money(priced.data.total) : `≈ ${money(estimatedTotal)}`}
|
||||
</span>
|
||||
</div>
|
||||
{priced?.error && <div data-testid="cart-total-error" style={{ fontSize: 12, color: 'var(--danger)' }}>{priced.error}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const _AI_UNIT_LABELS = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' }
|
||||
@@ -156,6 +183,7 @@ export default function AddItemsPage() {
|
||||
const [dealOffers, setDealOffers] = useState([]) // pending deal prompts from server
|
||||
const [activeDealOffer, setActiveDealOffer] = useState(null) // currently shown offer
|
||||
const quickToastTimer = useRef(null)
|
||||
const [quote, setQuote] = useState(null) // { key, data, error } — the server's price of the cart (4.4)
|
||||
|
||||
useEffect(() => {
|
||||
async function load() {
|
||||
@@ -283,6 +311,34 @@ export default function AddItemsPage() {
|
||||
setEditItem(null)
|
||||
}
|
||||
|
||||
// The cart as the lines the server prices (4.4): what was chosen, by id — never a price
|
||||
function cartLines() {
|
||||
return cart.map(({ _key, _drawerState, ...item }) => wireLine(item, getProduct(item.product_id)))
|
||||
}
|
||||
const estimates = cart.map(item => estimate(item, getProduct(item.product_id)))
|
||||
const estimatedTotal = estimates.reduce((s, v) => s + v, 0)
|
||||
|
||||
// The server's price of the cart while it's on screen (debounced); offline → the estimate
|
||||
const showPrices = (cartOpen || summaryOpen) && cart.length > 0 && !isOffline
|
||||
const quoteKey = showPrices ? JSON.stringify([orderId, cart.map(({ _key, _drawerState, ...i }) => i)]) : null
|
||||
useEffect(() => {
|
||||
if (!quoteKey) return undefined
|
||||
let lines
|
||||
try { lines = cartLines() } catch (err) {
|
||||
const t = setTimeout(() => setQuote({ key: quoteKey, data: null, error: err instanceof LineError ? lineErrorText(err) : String(err) }), 0)
|
||||
return () => clearTimeout(t)
|
||||
}
|
||||
const t = setTimeout(() => {
|
||||
client.post('/api/orders/quote', {
|
||||
lines, order_id: orderId ?? undefined, order_type: isStandalone ? orderType : 'here',
|
||||
}, { noOverride: true })
|
||||
.then(r => setQuote({ key: quoteKey, data: r.data, error: null }))
|
||||
.catch(err => setQuote({ key: quoteKey, data: null, error: apiError(err, '') }))
|
||||
}, 250)
|
||||
return () => clearTimeout(t)
|
||||
}, [quoteKey]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const priced = quote && quote.key === quoteKey ? quote : null
|
||||
|
||||
async function sendOrder() {
|
||||
if (cart.length === 0) return
|
||||
setSending(true)
|
||||
@@ -293,12 +349,14 @@ export default function AddItemsPage() {
|
||||
// ── Offline path (not supported for standalone orders) ────────────────────
|
||||
if (isOffline && !isStandalone) {
|
||||
try {
|
||||
// queued by id; the server prices them when the phone is back (the menu's price is shown as an estimate)
|
||||
const items = cart.map(({ _key, _drawerState, ...item }) => {
|
||||
const product = products.find(p => p.id === item.product_id)
|
||||
return {
|
||||
...item,
|
||||
_wire: wireLine(item, product),
|
||||
_productSnapshot: product ? { name: product.name } : null,
|
||||
_unitPrice: product?.base_price ?? 0,
|
||||
_unitPrice: estimate({ ...item, quantity: 1 }, product),
|
||||
_unitType: product?.unit_type ?? null,
|
||||
}
|
||||
})
|
||||
@@ -312,7 +370,7 @@ export default function AddItemsPage() {
|
||||
setTimeout(() => navigate('/tables'), 1200)
|
||||
} catch (err) {
|
||||
console.error('[offline order] save failed:', err)
|
||||
setError('Σφάλμα αποθήκευσης offline παραγγελίας')
|
||||
setError(err instanceof LineError ? lineErrorText(err) : 'Σφάλμα αποθήκευσης offline παραγγελίας')
|
||||
} finally {
|
||||
setSending(false)
|
||||
}
|
||||
@@ -321,6 +379,12 @@ export default function AddItemsPage() {
|
||||
|
||||
// ── Online path ───────────────────────────────────────────────────────────
|
||||
try {
|
||||
let lines
|
||||
try { lines = cartLines() } catch (err) {
|
||||
if (!(err instanceof LineError)) throw err
|
||||
setError(lineErrorText(err))
|
||||
return
|
||||
}
|
||||
let activeOrderId = orderId
|
||||
if (!activeOrderId) {
|
||||
const orderPayload = isStandalone
|
||||
@@ -332,7 +396,7 @@ export default function AddItemsPage() {
|
||||
}
|
||||
|
||||
const res = await client.post(`/api/orders/${activeOrderId}/items`, {
|
||||
items: cart.map(({ _key, _drawerState, ...item }) => item),
|
||||
lines,
|
||||
order_note: orderNote || null,
|
||||
customer_count: customerCount ?? null,
|
||||
})
|
||||
@@ -542,6 +606,7 @@ export default function AddItemsPage() {
|
||||
{/* Cart button with badge */}
|
||||
<button
|
||||
className="icon-btn"
|
||||
data-testid="cart-open"
|
||||
style={{ position: 'relative' }}
|
||||
onClick={() => setCartOpen(true)}
|
||||
>
|
||||
@@ -801,6 +866,9 @@ export default function AddItemsPage() {
|
||||
|
||||
{/* Drawer footer */}
|
||||
<div style={{ padding: '0 12px 20px', borderTop: '1px solid var(--border)', paddingTop: 12, flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{cart.length > 0 && (
|
||||
<CartTotal priced={priced} estimatedTotal={estimatedTotal} offline={isOffline} />
|
||||
)}
|
||||
<button
|
||||
className="btn btn--primary btn--lg"
|
||||
style={{ width: '100%' }}
|
||||
@@ -831,6 +899,10 @@ export default function AddItemsPage() {
|
||||
<OrderSummaryModal
|
||||
cart={cart}
|
||||
products={products}
|
||||
prices={priced?.data ? priced.data.lines.map(l => l.total) : estimates}
|
||||
total={priced?.data ? priced.data.total : estimatedTotal}
|
||||
estimated={!priced?.data}
|
||||
priceError={priced?.error ?? null}
|
||||
orderNote={orderNote}
|
||||
setOrderNote={setOrderNote}
|
||||
onSend={() => { setSummaryOpen(false); sendOrder() }}
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import db from '../db/posdb'
|
||||
import client from '../api/client'
|
||||
import { apiError } from '../api/errors'
|
||||
|
||||
// Orders taken offline (plan step 4.4): the cart lines are queued by id (`_wire`, built when
|
||||
// the order was taken: @xenia/api wireLine) and priced by the server when they reach it; the
|
||||
// synthetic order shows the menu's price as an estimate until then. A line the server refuses
|
||||
// is taken out, the rest is sent, and the refused one is kept in `kv.refused_lines` with the
|
||||
// reason for the waiter to see (components/RefusedLines.jsx), never dropped silently.
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -66,6 +73,7 @@ export async function queueOfflineOrder({ tableId, items, waiterId }) {
|
||||
quantity: item.quantity,
|
||||
unit_price: item._unitPrice || 0,
|
||||
unit_type: item._unitType || null,
|
||||
_estimated: true,
|
||||
status: 'active',
|
||||
kds_status: 'pending',
|
||||
selected_options: item.selected_options || [],
|
||||
@@ -238,30 +246,20 @@ async function _flushLegacyOfflineOrders() {
|
||||
await db.offline_orders.update(entry.localId, { synced: 1 })
|
||||
continue
|
||||
}
|
||||
// True legacy record — handle directly
|
||||
// True legacy record (before v0.6.4): it can't be priced by the server (no lines by id)
|
||||
if (!entry.items.some(i => i._wire)) {
|
||||
await keepRefused(entry.items.map(i => refusedEntry(i, entry.tableId, entry.uuid, OLD_FORMAT)))
|
||||
await db.offline_orders.update(entry.localId, { synced: 1 })
|
||||
await db.pos_orders.delete(`offline_${entry.uuid}`)
|
||||
continue
|
||||
}
|
||||
try {
|
||||
let orderId = null
|
||||
try {
|
||||
const statusRes = await client.get(`/api/tables/${entry.tableId}/status`)
|
||||
orderId = statusRes.data.active_order_id ?? null
|
||||
} catch { /* offline */ }
|
||||
|
||||
if (!orderId) {
|
||||
const createRes = await client.post('/api/orders/', { table_id: entry.tableId })
|
||||
orderId = createRes.data?.id
|
||||
if (!orderId) throw new Error('no order id returned')
|
||||
const { orderId } = await sendLines(entry.items, { tableId: entry.tableId, uuid: entry.uuid }, () => tableOrderId(entry.tableId))
|
||||
if (orderId == null) {
|
||||
await db.offline_orders.update(entry.localId, { synced: 1 })
|
||||
await db.pos_orders.delete(`offline_${entry.uuid}`)
|
||||
continue
|
||||
}
|
||||
|
||||
await client.post(`/api/orders/${orderId}/items`, {
|
||||
items: entry.items.map(item => ({
|
||||
product_id: item.product_id,
|
||||
quantity: item.quantity,
|
||||
selected_options: item.selected_options || [],
|
||||
removed_ingredients: item.removed_ingredients || [],
|
||||
notes: item.notes || '',
|
||||
})),
|
||||
})
|
||||
|
||||
const fullRes = await client.get(`/api/orders/${orderId}`)
|
||||
await db.offline_orders.update(entry.localId, { synced: 1, serverId: orderId })
|
||||
await db.pos_orders.delete(`offline_${entry.uuid}`)
|
||||
@@ -295,32 +293,30 @@ async function _flushLegacyOfflinePayments() {
|
||||
// ── Op handlers ───────────────────────────────────────────────────────────────
|
||||
|
||||
async function _flushCreateOrder(op, idMap) {
|
||||
// Already synced by legacy drain? Check idMap or look for real order
|
||||
let orderId = null
|
||||
try {
|
||||
const statusRes = await client.get(`/api/tables/${op.tableId}/status`)
|
||||
orderId = statusRes.data.active_order_id ?? null
|
||||
} catch { /* offline */ }
|
||||
|
||||
if (!orderId) {
|
||||
const createRes = await client.post('/api/orders/', { table_id: op.tableId })
|
||||
orderId = createRes.data?.id
|
||||
if (!orderId) throw new Error('no order id returned')
|
||||
const synthetic = await db.pos_orders.get(op.localOrderId)
|
||||
// queued before 4.4: nothing the server can price → all refused, no empty order opened
|
||||
if (!op.items.some(i => i._wire)) {
|
||||
await keepRefused(op.items.map(i => refusedEntry(i, op.tableId, op.uuid, OLD_FORMAT)))
|
||||
for (const it of synthetic?.items ?? []) idMap[it.id] = REFUSED
|
||||
await db.offline_orders.where('uuid').equals(op.uuid).modify({ synced: 1 })
|
||||
await db.offline_ops.update(op.localId, { synced: 1 })
|
||||
await db.pos_orders.delete(op.localOrderId)
|
||||
return
|
||||
}
|
||||
|
||||
await client.post(`/api/orders/${orderId}/items`, {
|
||||
items: op.items.map(item => ({
|
||||
product_id: item.product_id,
|
||||
quantity: item.quantity,
|
||||
selected_options: item.selected_options || [],
|
||||
removed_ingredients: item.removed_ingredients || [],
|
||||
notes: item.notes || '',
|
||||
})),
|
||||
})
|
||||
// the table's open order (one may have been opened meanwhile), or a new one, once a line
|
||||
// is known to be accepted
|
||||
const { orderId, sent } = await sendLines(op.items, { tableId: op.tableId, uuid: op.uuid }, () => tableOrderId(op.tableId))
|
||||
|
||||
// Capture synthetic order item ids BEFORE deleting it
|
||||
const syntheticOrder = await db.pos_orders.get(op.localOrderId)
|
||||
const syntheticItemIds = syntheticOrder?.items?.map(i => i.id) ?? []
|
||||
const allLocalIds = synthetic?.items?.map(i => i.id) ?? []
|
||||
allLocalIds.forEach((id, i) => { if (!sent.includes(i)) idMap[id] = REFUSED })
|
||||
if (orderId == null) { // every line refused: nothing opened on the table
|
||||
await db.offline_orders.where('uuid').equals(op.uuid).modify({ synced: 1 })
|
||||
await db.offline_ops.update(op.localId, { synced: 1 })
|
||||
await db.pos_orders.delete(op.localOrderId)
|
||||
return
|
||||
}
|
||||
const syntheticItemIds = allLocalIds.filter((_, i) => sent.includes(i))
|
||||
|
||||
// Fetch full hydrated order
|
||||
const fullRes = await client.get(`/api/orders/${orderId}`)
|
||||
@@ -330,7 +326,7 @@ async function _flushCreateOrder(op, idMap) {
|
||||
idMap[op.localOrderId] = orderId
|
||||
|
||||
// Map offline item ids → real item ids by position (last N added server items)
|
||||
if (syntheticItemIds.length > 0 && serverOrder.items) {
|
||||
if (syntheticItemIds.length > 0 && serverOrder.items && sent.length > 0) {
|
||||
const addedServerItems = serverOrder.items.slice(-syntheticItemIds.length)
|
||||
syntheticItemIds.forEach((localItemId, idx) => {
|
||||
if (addedServerItems[idx]) {
|
||||
@@ -393,14 +389,16 @@ async function _flushPay(op, idMap) {
|
||||
return
|
||||
}
|
||||
|
||||
// Resolve local item ids
|
||||
const resolvedLocal = (op.localItemIds || []).map(lid => idMap[lid] ?? lid)
|
||||
// Resolve local item ids (items the server refused when the order was sent can't be paid:
|
||||
// the waiter sees them in the refused list)
|
||||
const resolvedLocal = (op.localItemIds || []).map(lid => idMap[lid] ?? lid).filter(id => id !== REFUSED)
|
||||
const stillLocal = resolvedLocal.filter(id => String(id).startsWith('offline_item_'))
|
||||
if (stillLocal.length > 0) {
|
||||
throw new Error('offline item ids not yet resolved')
|
||||
}
|
||||
|
||||
const allIds = [...resolvedLocal, ...(op.realItemIds || [])]
|
||||
if (!allIds.length) { await db.offline_ops.update(op.localId, { synced: 1 }); return }
|
||||
await client.post(`/api/orders/${realOrderId}/pay-offline`, {
|
||||
uuid: op.uuid,
|
||||
item_ids: allIds,
|
||||
@@ -410,6 +408,94 @@ async function _flushPay(op, idMap) {
|
||||
await db.offline_ops.update(op.localId, { synced: 1 })
|
||||
}
|
||||
|
||||
// ── Sending queued lines; refused ones come back to the waiter ──────────────────
|
||||
|
||||
const REFUSED_KEY = 'refused_lines'
|
||||
const REFUSED = 'refused'
|
||||
const OLD_FORMAT = 'Παλιά μορφή παραγγελίας: προσθέστε το ξανά'
|
||||
|
||||
/** Lines the server refused when an offline order was sent: [{ at, tableId, product, quantity, reason }]. */
|
||||
export async function refusedLines() {
|
||||
return (await db.kv.get(REFUSED_KEY))?.value ?? []
|
||||
}
|
||||
|
||||
export async function clearRefusedLines() {
|
||||
await db.kv.put({ key: REFUSED_KEY, value: [] })
|
||||
window.dispatchEvent(new Event('refused-lines'))
|
||||
}
|
||||
|
||||
async function keepRefused(entries) {
|
||||
if (!entries.length) return
|
||||
await db.kv.put({ key: REFUSED_KEY, value: [...(await refusedLines()), ...entries] })
|
||||
window.dispatchEvent(new Event('refused-lines'))
|
||||
}
|
||||
|
||||
/** The line a refusal names (order.line.*, order.not_sold_here carry `line`, 1-based), or null
|
||||
* when the error isn't about one line (network, server error, the whole order). */
|
||||
function refusedLine(err, count) {
|
||||
const status = err?.response?.status
|
||||
const line = err?.response?.data?.error?.params?.line
|
||||
const refusal = status === 400 || status === 404 || status === 409 || status === 422
|
||||
return refusal && Number.isInteger(line) && line >= 1 && line <= count ? line : null
|
||||
}
|
||||
|
||||
/** Post `pending` lines; a refused line is taken out (with its reason) and the rest posted again. */
|
||||
async function postLines(pending, refused, ctx, post) {
|
||||
while (pending.length) {
|
||||
try {
|
||||
await post(pending.map(({ item }) => item._wire))
|
||||
return pending
|
||||
} catch (err) {
|
||||
const n = refusedLine(err, pending.length)
|
||||
if (n == null) throw err
|
||||
const [{ item }] = pending.splice(n - 1, 1)
|
||||
refused.push(refusedEntry(item, ctx.tableId, ctx.uuid, apiError(err, 'Ο server δεν το δέχτηκε')))
|
||||
}
|
||||
}
|
||||
return pending
|
||||
}
|
||||
|
||||
/**
|
||||
* Send queued items, priced by the server. A quote first finds the lines the server refuses
|
||||
* (so no order is opened for nothing), then `getOrderId()` gives the order and the rest is
|
||||
* added (a line refused there is taken out too). An item queued before 4.4 (no `_wire`) can't
|
||||
* be priced and is refused straight away. Network errors throw and the op stays queued (its
|
||||
* refusals are found again next time). Returns { orderId (null: all refused), sent: [indexes] }.
|
||||
*/
|
||||
async function sendLines(items, ctx, getOrderId) {
|
||||
const refused = items.filter(item => !item._wire).map(item => refusedEntry(item, ctx.tableId, ctx.uuid, OLD_FORMAT))
|
||||
const opts = { noOverride: true }
|
||||
let pending = items.map((item, index) => ({ item, index })).filter(({ item }) => item._wire)
|
||||
pending = await postLines(pending, refused, ctx, lines => client.post('/api/orders/quote', { lines }, opts))
|
||||
let orderId = null
|
||||
if (pending.length) {
|
||||
orderId = await getOrderId()
|
||||
pending = await postLines(pending, refused, ctx, lines => client.post(`/api/orders/${orderId}/items`, { lines }, opts))
|
||||
}
|
||||
await keepRefused(refused)
|
||||
return { orderId, sent: pending.map(({ index }) => index) }
|
||||
}
|
||||
|
||||
async function tableOrderId(tableId) {
|
||||
let orderId = null
|
||||
try {
|
||||
orderId = (await client.get(`/api/tables/${tableId}/status`)).data.active_order_id ?? null
|
||||
} catch { /* offline */ }
|
||||
if (!orderId) {
|
||||
orderId = (await client.post('/api/orders/', { table_id: tableId })).data?.id
|
||||
if (!orderId) throw new Error('no order id returned')
|
||||
}
|
||||
return orderId
|
||||
}
|
||||
|
||||
function refusedEntry(item, tableId, uuid, reason) {
|
||||
return {
|
||||
at: new Date().toISOString(), uuid, tableId,
|
||||
product: item._productSnapshot?.name ?? `#${item.product_id}`,
|
||||
quantity: item.quantity, reason,
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Queue size ───────────────────────────────────────────────────────────────
|
||||
|
||||
export async function pendingOrderCount() {
|
||||
|
||||
Reference in New Issue
Block a user