feat: delivery areas drawn on a map (plan 6R.G)
An area is a list of postcodes, a shape drawn on a map or a circle around a point. The fee engine (both copies, byte-identical) matches a shape only by the customer's pin, then postcodes; point-in-polygon (edges inside) and haversine circles; shared cases in fee_cases.json. - Alembic 0053: delivery_areas.kind / geometry, orders.online_lat / lng - /api/connect/fees: areas with kind + geometry (validated: 3-200 corners, 50 m - 50 km), the venue's place (PUT /venue-point, setting venue.location, sent to the cloud as fees.venue_point), preview by lat / lng - manager: DeliveryMap (Leaflet + OpenStreetMap tiles): draw / move / remove corners, circles, the venue on the map, an overview, test an order by a point - pulled online orders keep the pin; the site re-checks the fee with it; the counter links the pin to a map - tests: backend (shapes, venue point, pinned orders), manager logic, e2e manager.mjs and order_app.mjs 6R.G blocks Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -20,6 +20,7 @@
|
||||
"@xenia/signage": "^0.0.0",
|
||||
"@xenia/ui": "^0.0.0",
|
||||
"axios": "^1.21.1",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-react": "^1.73.0",
|
||||
"qrcode.react": "^4.2.0",
|
||||
"react": "^19.3.1",
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
// A map of where the venue delivers (plan 6R.G, owner 2026-11-20): Leaflet on OpenStreetMap tiles
|
||||
// (attribution shown, as their tile policy asks; the manager needs the internet for the tiles only).
|
||||
// mode 'polygon' value [[lat, lng], …] tap the map: a corner is added; drag a corner: it moves;
|
||||
// tap a corner: it is removed
|
||||
// mode 'circle' value {center, radius_m} tap the map or drag the pin: the centre moves (the radius
|
||||
// is typed beside the map)
|
||||
// mode 'point' value [lat, lng] | null tap the map: the point (the venue's place, a test order)
|
||||
// mode 'view' nothing to edit every area drawn, the venue's pin
|
||||
// `areas`: the venue's areas, drawn faintly (the one being edited left out by `skipId`); `venue`
|
||||
// {lat, lng} | null: its pin, and where the map starts (else the areas, else Greece).
|
||||
// Colours are the tokens (the pins' HTML uses them as variables; the SVG shapes read their values).
|
||||
import { useEffect, useRef } from 'react'
|
||||
import L from 'leaflet'
|
||||
import 'leaflet/dist/leaflet.css'
|
||||
|
||||
const GREECE = [38.3, 23.3]
|
||||
const TILE = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png'
|
||||
const ATTRIBUTION = '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
|
||||
|
||||
// a token's value: SVG paths take colours as attributes, where CSS variables don't work
|
||||
const token = name => getComputedStyle(document.documentElement).getPropertyValue(name).trim()
|
||||
|
||||
const dot = (colour, size = 14, square = false) => L.divIcon({
|
||||
className: '',
|
||||
iconSize: [size, size],
|
||||
iconAnchor: [size / 2, size / 2],
|
||||
html: `<span style="display:block;width:${size}px;height:${size}px;border-radius:${square ? '3px' : '50%'};background:${colour};border:2px solid var(--x-on-colour);box-shadow:0 1px 4px rgb(var(--x-scrim-rgb) / .45)"></span>`,
|
||||
})
|
||||
|
||||
const pin = (colour, label = '') => L.divIcon({
|
||||
className: '',
|
||||
iconSize: [26, 26],
|
||||
iconAnchor: [13, 26],
|
||||
html: `<span style="display:flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:50% 50% 50% 0;transform:rotate(-45deg);background:${colour};border:2px solid var(--x-on-colour);box-shadow:0 1px 4px rgb(var(--x-scrim-rgb) / .45)"><span style="transform:rotate(45deg);color:var(--x-on-colour);font:700 11px/1 system-ui">${label}</span></span>`,
|
||||
})
|
||||
|
||||
function drawArea(a, style) {
|
||||
if (a.kind === 'polygon' && Array.isArray(a.geometry) && a.geometry.length >= 3) return L.polygon(a.geometry, style)
|
||||
if (a.kind === 'circle' && a.geometry?.center) return L.circle(a.geometry.center, { radius: a.geometry.radius_m, ...style })
|
||||
return null
|
||||
}
|
||||
|
||||
export default function DeliveryMap({ mode = 'view', value = null, onChange, areas = [], skipId = null, venue = null, height = 360, testId = 'delivery-map' }) {
|
||||
const box = useRef(null)
|
||||
const map = useRef(null)
|
||||
const others = useRef(null)
|
||||
const edit = useRef(null)
|
||||
const latest = useRef({ mode, value, onChange })
|
||||
useEffect(() => { latest.current = { mode, value, onChange } }) // the map's click handler reads the newest
|
||||
|
||||
// the map, once
|
||||
useEffect(() => {
|
||||
const m = L.map(box.current, { zoomControl: true, attributionControl: true })
|
||||
L.tileLayer(TILE, { maxZoom: 19, attribution: ATTRIBUTION }).addTo(m)
|
||||
m.attributionControl.setPrefix('<a href="https://leafletjs.com">Leaflet</a>')
|
||||
others.current = L.layerGroup().addTo(m)
|
||||
edit.current = L.layerGroup().addTo(m)
|
||||
m.on('click', e => {
|
||||
const { mode: md, value: v, onChange: change } = latest.current
|
||||
const p = [round(e.latlng.lat), round(e.latlng.lng)]
|
||||
if (md === 'polygon') change?.([...(v || []), p])
|
||||
else if (md === 'circle') change?.({ ...(v || { radius_m: 1000 }), center: p })
|
||||
else if (md === 'point') change?.(p)
|
||||
})
|
||||
map.current = m
|
||||
// fit what there is to see: the edited shape, else the areas, else the venue, else Greece
|
||||
// (bounds worked out here: a circle's own bounds need a map that already has a view)
|
||||
const boxes = [mode === 'polygon' ? boundsOf({ kind: 'polygon', geometry: value }) : null,
|
||||
mode === 'circle' ? boundsOf({ kind: 'circle', geometry: value }) : null,
|
||||
...areas.map(boundsOf)].filter(Boolean)
|
||||
if (boxes.length) {
|
||||
m.fitBounds(boxes.reduce((all, b) => all.extend(b), L.latLngBounds(boxes[0].getSouthWest(), boxes[0].getNorthEast())).pad(0.15))
|
||||
} else if (mode === 'point' && value) {
|
||||
m.setView(value, 15)
|
||||
} else if (venue) {
|
||||
m.setView([venue.lat, venue.lng], 14)
|
||||
} else {
|
||||
m.setView(GREECE, 7)
|
||||
}
|
||||
// the dialog may still be opening: size the map once it is laid out
|
||||
const ro = new ResizeObserver(() => m.invalidateSize())
|
||||
ro.observe(box.current)
|
||||
return () => { ro.disconnect(); m.remove(); map.current = null }
|
||||
}, []) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// the other areas and the venue's pin
|
||||
useEffect(() => {
|
||||
const g = others.current
|
||||
if (!g) return
|
||||
g.clearLayers()
|
||||
const faint = token('--x-info')
|
||||
for (const a of areas) {
|
||||
if (a.id === skipId || !a.is_active) continue
|
||||
const layer = drawArea(a, { color: faint, weight: 1.5, fillOpacity: 0.08, interactive: mode === 'view' })
|
||||
if (layer) layer.bindTooltip(a.name).addTo(g)
|
||||
}
|
||||
if (venue && mode !== 'point') L.marker([venue.lat, venue.lng], { icon: pin('var(--x-danger)'), interactive: false }).addTo(g)
|
||||
}, [areas, skipId, venue, mode])
|
||||
|
||||
// what is being edited
|
||||
useEffect(() => {
|
||||
const g = edit.current
|
||||
if (!g) return
|
||||
g.clearLayers()
|
||||
const accent = token('--x-accent')
|
||||
if (mode === 'polygon') {
|
||||
const corners = value || []
|
||||
if (corners.length >= 2) L.polygon(corners, { color: accent, weight: 2.5, fillOpacity: 0.2, interactive: false }).addTo(g)
|
||||
corners.forEach((c, i) => {
|
||||
const mk = L.marker(c, { icon: dot('var(--x-accent)', 14, true), draggable: true, bubblingMouseEvents: false, keyboard: false })
|
||||
mk.on('dragend', e => {
|
||||
const ll = e.target.getLatLng()
|
||||
onChange?.(corners.map((x, j) => (j === i ? [round(ll.lat), round(ll.lng)] : x)))
|
||||
})
|
||||
mk.on('click', () => onChange?.(corners.filter((_, j) => j !== i)))
|
||||
mk.addTo(g)
|
||||
})
|
||||
} else if (mode === 'circle' && value?.center) {
|
||||
L.circle(value.center, { radius: value.radius_m || 0, color: accent, weight: 2.5, fillOpacity: 0.2, interactive: false }).addTo(g)
|
||||
const mk = L.marker(value.center, { icon: dot('var(--x-accent)', 16), draggable: true, bubblingMouseEvents: false, keyboard: false })
|
||||
mk.on('dragend', e => { const ll = e.target.getLatLng(); onChange?.({ ...value, center: [round(ll.lat), round(ll.lng)] }) })
|
||||
mk.addTo(g)
|
||||
} else if (mode === 'point' && value) {
|
||||
L.marker(value, { icon: pin('var(--x-accent)'), interactive: false }).addTo(g)
|
||||
}
|
||||
}, [mode, value, onChange])
|
||||
|
||||
const count = mode === 'polygon' ? (value || []).length : mode === 'circle' ? (value?.center ? 1 : 0) : (value ? 1 : 0)
|
||||
return (
|
||||
<div ref={box} className="w-full rounded-control border border-line overflow-hidden z-0 relative"
|
||||
style={{ height }} data-testid={testId} data-mode={mode} data-count={count} />
|
||||
)
|
||||
}
|
||||
|
||||
function round(x) { return Math.round(x * 1e6) / 1e6 }
|
||||
|
||||
/** The box around an area's shape, without a map: a polygon's corners, a circle's centre ± radius. */
|
||||
function boundsOf(a) {
|
||||
if (a?.kind === 'polygon' && Array.isArray(a.geometry) && a.geometry.length) return L.latLngBounds(a.geometry)
|
||||
if (a?.kind === 'circle' && a.geometry?.center && a.geometry.radius_m > 0) {
|
||||
const [lat, lng] = a.geometry.center
|
||||
const dLat = a.geometry.radius_m / 111320
|
||||
const dLng = a.geometry.radius_m / (111320 * Math.max(0.01, Math.cos(lat * Math.PI / 180)))
|
||||
return L.latLngBounds([lat - dLat, lng - dLng], [lat + dLat, lng + dLng])
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -6,6 +6,8 @@
|
||||
// products, free) or refuses the order below a minimum; "stop here" makes the first match
|
||||
// win. The cloud applies the same rules at checkout (the same engine), so "Test an order"
|
||||
// shows exactly what a customer will be charged. No rules = no fee.
|
||||
// 6R.G: an area is a list of postcodes, a shape drawn on the map or a circle (DeliveryMap, Leaflet +
|
||||
// OpenStreetMap); the venue's own place on the map is set once here; "Test an order" by a point.
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useSearchParams } from 'react-router-dom'
|
||||
import toast from 'react-hot-toast'
|
||||
@@ -13,12 +15,13 @@ import { ArrowDown, ArrowUp, MapPin, Pencil, Plus, Trash2, Truck } from 'lucide-
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { SALES_POINTS } from '@xenia/access'
|
||||
import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, Spinner, Switch, Tabs } from '@xenia/ui'
|
||||
import { Button, Dialog, EmptyState, Field, IconButton, Input, NumberInput, Segmented, Select, Spinner, Switch, Tabs } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import FeeProductCard from './FeeProductCard'
|
||||
import OrderingLink from './OrderingLink'
|
||||
import OrderingSettings from './OrderingSettings'
|
||||
import { ACTIONS, DAYS, describeRule, emptyRule, moveRule, parsePostcodes, previewBody, ruleBody, ruleProblems, ruleToForm } from './feesLogic'
|
||||
import { ACTIONS, AREA_KINDS, DAYS, RADIUS_MAX, RADIUS_MIN, areaBody, areaProblem, describeRule, distanceText, emptyRule, moveRule, previewBody, ruleBody, ruleProblems, ruleToForm } from './feesLogic'
|
||||
import DeliveryMap from './DeliveryMap'
|
||||
|
||||
const chip = on => `px-3 min-h-[var(--x-control-sm)] rounded-full text-label font-medium transition-colors duration-fast
|
||||
${on ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`
|
||||
@@ -95,6 +98,22 @@ export default function FeesPage() {
|
||||
))}
|
||||
</ol>
|
||||
))}
|
||||
{section === 'areas' && (
|
||||
<div className="grid gap-3 mb-3">
|
||||
<div className="flex items-center gap-3 px-card py-card-y rounded-card border border-line bg-surface-2" data-testid="venue-point">
|
||||
<MapPin size={16} className="text-danger-ink shrink-0" aria-hidden="true" />
|
||||
<span className="flex-1 min-w-0 text-body text-ink">
|
||||
{data.venue_point ? t('fees.venueSet') : t('fees.venueNotSet')}
|
||||
</span>
|
||||
<Button size="sm" variant="secondary" onClick={() => setDialog({ kind: 'venue' })} data-testid="venue-edit">
|
||||
{data.venue_point ? t('fees.venueMove') : t('fees.venueSetButton')}
|
||||
</Button>
|
||||
</div>
|
||||
{(data.venue_point || data.areas.some(a => a.kind !== 'postcodes')) && (
|
||||
<DeliveryMap mode="view" areas={data.areas} venue={data.venue_point} height={320} testId="areas-map" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{section === 'areas' && (data.areas.length === 0 ? (
|
||||
<EmptyState icon={<MapPin size={28} />} title={t('fees.noAreas')} />
|
||||
) : (
|
||||
@@ -104,7 +123,11 @@ export default function FeesPage() {
|
||||
<MapPin size={16} className="text-ink-3 shrink-0" aria-hidden="true" />
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className={`block text-body font-medium ${a.is_active ? 'text-ink' : 'text-ink-3 line-through'}`}>{a.name}</span>
|
||||
<span className="block text-caption text-ink-2 truncate">{a.postcodes.length ? a.postcodes.join(', ') : t('fees.byNameOnly')}</span>
|
||||
<span className="block text-caption text-ink-2 truncate">
|
||||
{a.kind === 'polygon' ? t('fees.areaDrawn', { count: a.geometry?.length ?? 0 })
|
||||
: a.kind === 'circle' ? t('fees.areaCircle', { distance: distanceText(a.geometry?.radius_m) })
|
||||
: a.postcodes.length ? a.postcodes.join(', ') : t('fees.byNameOnly')}
|
||||
</span>
|
||||
</span>
|
||||
<span className="flex gap-1.5">
|
||||
<IconButton size="sm" variant="ghost" tone="accent" label={t('fees.edit')} onClick={() => setDialog({ kind: 'area', item: a })}><Pencil size={16} /></IconButton>
|
||||
@@ -119,14 +142,18 @@ export default function FeesPage() {
|
||||
: <EmptyState title={t('fees.noSettings')} />)}
|
||||
</div>
|
||||
</section>
|
||||
<TestOrder areas={data.areas} />
|
||||
<TestOrder areas={data.areas} venue={data.venue_point} />
|
||||
</div>
|
||||
|
||||
{dialog?.kind === 'area' && (
|
||||
<AreaDialog area={dialog.item} onClose={() => setDialog(null)}
|
||||
<AreaDialog area={dialog.item} areas={data.areas} venue={data.venue_point} onClose={() => setDialog(null)}
|
||||
onSave={body => act(() => (dialog.item ? client.put(`/api/connect/fees/areas/${dialog.item.id}`, body) : client.post('/api/connect/fees/areas', body)),
|
||||
t('fees.saved')).then(ok => ok && setDialog(null))} />
|
||||
)}
|
||||
{dialog?.kind === 'venue' && (
|
||||
<VenuePointDialog venue={data.venue_point} areas={data.areas} onClose={() => setDialog(null)}
|
||||
onSave={body => act(() => client.put('/api/connect/fees/venue-point', body), t('fees.saved')).then(ok => ok && setDialog(null))} />
|
||||
)}
|
||||
{dialog?.kind === 'rule' && (
|
||||
<RuleDialog rule={dialog.item} areas={data.areas} onClose={() => setDialog(null)}
|
||||
onSave={body => act(() => (dialog.item ? client.put(`/api/connect/fees/rules/${dialog.item.id}`, body) : client.post('/api/connect/fees/rules', body)),
|
||||
@@ -184,32 +211,87 @@ function RuleRow({ rule, n, areaNames, first, last, onMove, onToggle, onEdit, on
|
||||
)
|
||||
}
|
||||
|
||||
function AreaDialog({ area, onClose, onSave }) {
|
||||
function AreaDialog({ area, areas, venue, onClose, onSave }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [name, setName] = useState(area?.name ?? '')
|
||||
const [kind, setKind] = useState(area?.kind ?? 'postcodes')
|
||||
const [codes, setCodes] = useState((area?.postcodes ?? []).join(', '))
|
||||
const [corners, setCorners] = useState(area?.kind === 'polygon' ? area.geometry : [])
|
||||
const [circle, setCircle] = useState(area?.kind === 'circle' ? area.geometry
|
||||
: { center: venue ? [venue.lat, venue.lng] : null, radius_m: 2000 })
|
||||
const [active, setActive] = useState(area?.is_active ?? true)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const save = async () => { setBusy(true); await onSave({ name: name.trim(), postcodes: parsePostcodes(codes), is_active: active }); setBusy(false) }
|
||||
const form = { name, kind, codes, corners, circle, active }
|
||||
const problem = areaProblem(form)
|
||||
const save = async () => { setBusy(true); await onSave(areaBody(form)); setBusy(false) }
|
||||
return (
|
||||
<Dialog open size="sm" title={area ? t('fees.editArea') : t('fees.addArea')} onClose={busy ? undefined : onClose}
|
||||
<Dialog open size={kind === 'postcodes' ? 'sm' : 'lg'} title={area ? t('fees.editArea') : t('fees.addArea')} onClose={busy ? undefined : onClose}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={busy}>{t('fees.cancel')}</Button>
|
||||
<Button onClick={save} loading={busy} disabled={!name.trim()} data-testid="area-save">{t('fees.save')}</Button>
|
||||
<Button onClick={save} loading={busy} disabled={!!problem} data-testid="area-save">{t('fees.save')}</Button>
|
||||
</>}>
|
||||
<div className="grid gap-3">
|
||||
<Field label={t('fees.areaName')} hint={t('fees.areaNameHint')} required>
|
||||
<Input value={name} onChange={e => setName(e.target.value)} maxLength={80} autoFocus data-testid="area-name" />
|
||||
</Field>
|
||||
<Field label={t('fees.postcodes')} hint={t('fees.postcodesHint')}>
|
||||
<Input value={codes} onChange={e => setCodes(e.target.value)} data-testid="area-postcodes" />
|
||||
<Field label={t('fees.areaKind')}>
|
||||
<Segmented value={kind} onChange={setKind} options={AREA_KINDS.map(k => ({ value: k, label: t(`fees.kind.${k}`), testId: `area-kind-${k}` }))} />
|
||||
</Field>
|
||||
{kind === 'postcodes' && (
|
||||
<Field label={t('fees.postcodes')} hint={t('fees.postcodesHint')}>
|
||||
<Input value={codes} onChange={e => setCodes(e.target.value)} data-testid="area-postcodes" />
|
||||
</Field>
|
||||
)}
|
||||
{kind === 'polygon' && (
|
||||
<div className="grid gap-2">
|
||||
<p className="text-label text-ink-2">{t('fees.drawHint')}</p>
|
||||
<DeliveryMap mode="polygon" value={corners} onChange={setCorners} areas={areas} skipId={area?.id} venue={venue} height={420} />
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-label text-ink-2 flex-1" data-testid="area-corners">{t('fees.corners', { count: corners.length })}</span>
|
||||
<Button size="sm" variant="secondary" onClick={() => setCorners(c => c.slice(0, -1))} disabled={!corners.length}>{t('fees.undoCorner')}</Button>
|
||||
<Button size="sm" variant="secondary" onClick={() => setCorners([])} disabled={!corners.length}>{t('fees.clearShape')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{kind === 'circle' && (
|
||||
<div className="grid gap-2">
|
||||
<p className="text-label text-ink-2">{t('fees.circleHint')}</p>
|
||||
<DeliveryMap mode="circle" value={circle} onChange={setCircle} areas={areas} skipId={area?.id} venue={venue} height={420} />
|
||||
<Field label={t('fees.radius')} hint={t('fees.radiusHint', { distance: distanceText(circle?.radius_m) })}>
|
||||
<NumberInput value={circle?.radius_m ?? null} min={RADIUS_MIN} max={RADIUS_MAX} step={100} suffix="m"
|
||||
onChange={v => setCircle(c => ({ ...c, radius_m: v }))} invalid={problem === 'radius'} data-testid="area-radius" />
|
||||
</Field>
|
||||
</div>
|
||||
)}
|
||||
{problem && problem !== 'name' && <p className="text-label text-warning-ink" data-testid="area-problem">{t(`fees.areaProblem.${problem}`)}</p>}
|
||||
<Switch checked={active} onChange={setActive} label={t('fees.areaActive')} />
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
function VenuePointDialog({ venue, areas, onClose, onSave }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [point, setPoint] = useState(venue ? [venue.lat, venue.lng] : null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const save = async p => { setBusy(true); await onSave(p ? { lat: p[0], lng: p[1] } : {}); setBusy(false) }
|
||||
return (
|
||||
<Dialog open size="lg" title={t('fees.venueOnMap')} onClose={busy ? undefined : onClose}
|
||||
footer={<>
|
||||
{venue && <Button variant="secondary" onClick={() => save(null)} disabled={busy}>{t('fees.venueClear')}</Button>}
|
||||
<Button variant="secondary" onClick={onClose} disabled={busy}>{t('fees.cancel')}</Button>
|
||||
<Button onClick={() => save(point)} loading={busy} disabled={!point} data-testid="venue-save">{t('fees.save')}</Button>
|
||||
</>}>
|
||||
<div className="grid gap-2">
|
||||
<p className="text-label text-ink-2">{t('fees.venueHint')}</p>
|
||||
<DeliveryMap mode="point" value={point} onChange={setPoint} areas={areas} venue={venue} height={420} testId="venue-map" />
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
function RuleDialog({ rule, areas, onClose, onSave }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { t: tc } = useTranslation('common')
|
||||
@@ -318,13 +400,13 @@ function RuleDialog({ rule, areas, onClose, onSave }) {
|
||||
)
|
||||
}
|
||||
|
||||
function TestOrder({ areas }) {
|
||||
function TestOrder({ areas, venue }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { t: tc } = useTranslation('common')
|
||||
const { formatMoney } = useFormat()
|
||||
// where / area_id stay null until picked: they follow the areas as they're added or removed
|
||||
const [picked, setForm] = useState({ sales_point: 'online_delivery', where: null, area_id: null,
|
||||
postcode: '', subtotal: '15', items: '2', day: 'now', time: '' })
|
||||
postcode: '', point: null, subtotal: '15', items: '2', day: 'now', time: '' })
|
||||
const form = {
|
||||
...picked,
|
||||
where: picked.where ?? (areas.length ? 'area' : 'postcode'),
|
||||
@@ -351,8 +433,11 @@ function TestOrder({ areas }) {
|
||||
<Select value={form.where} onChange={e => set('where', e.target.value)} aria-label={t('fees.testWhere')}>
|
||||
<option value="area">{t('fees.testByArea')}</option>
|
||||
<option value="postcode">{t('fees.testByPostcode')}</option>
|
||||
<option value="point">{t('fees.testByPoint')}</option>
|
||||
</Select>
|
||||
{form.where === 'area' ? (
|
||||
{form.where === 'point' ? (
|
||||
<DeliveryMap mode="point" value={form.point} onChange={p => set('point', p)} areas={areas} venue={venue} height={240} testId="test-map" />
|
||||
) : form.where === 'area' ? (
|
||||
<Select value={form.area_id} onChange={e => set('area_id', e.target.value)} aria-label={t('fees.areas')} data-testid="test-area">
|
||||
<option value="">{t('fees.testNoArea')}</option>
|
||||
{areas.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
|
||||
|
||||
@@ -98,6 +98,9 @@ export function previewBody(form) {
|
||||
sales_point: form.sales_point,
|
||||
area_id: form.where === 'area' && form.area_id !== '' ? Number(form.area_id) : null,
|
||||
postcode: form.where === 'postcode' ? form.postcode.trim() || null : null,
|
||||
// 6R.G: a point picked on the map
|
||||
lat: form.where === 'point' && form.point ? form.point[0] : null,
|
||||
lng: form.where === 'point' && form.point ? form.point[1] : null,
|
||||
subtotal: num(form.subtotal) ?? 0, items: Math.max(0, Math.round(num(form.items) ?? 0)),
|
||||
weekday: form.day === 'now' ? null : Number(form.day),
|
||||
time: form.day === 'now' ? null : (form.time || null),
|
||||
@@ -150,3 +153,32 @@ export function orderingBody(form) {
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ── 6R.G: areas drawn on a map ───────────────────────────────────────────────────────────
|
||||
export const AREA_KINDS = ['postcodes', 'polygon', 'circle']
|
||||
export const RADIUS_MIN = 50
|
||||
export const RADIUS_MAX = 50000
|
||||
|
||||
/** The area dialog's form → the request body; `kind` decides which of the three is sent. */
|
||||
export function areaBody({ name, kind = 'postcodes', codes = '', corners = [], circle = null, active = true }) {
|
||||
const body = { name: String(name ?? '').trim(), kind, is_active: active, postcodes: [] }
|
||||
if (kind === 'postcodes') body.postcodes = parsePostcodes(codes)
|
||||
else if (kind === 'polygon') body.geometry = corners
|
||||
else body.geometry = { center: circle?.center ?? null, radius_m: circle?.radius_m ?? null }
|
||||
return body
|
||||
}
|
||||
|
||||
/** What keeps the area from being saved: 'name' | 'corners' | 'centre' | 'radius' | null. */
|
||||
export function areaProblem({ name, kind = 'postcodes', corners = [], circle = null }) {
|
||||
if (!String(name ?? '').trim()) return 'name'
|
||||
if (kind === 'polygon' && corners.length < 3) return 'corners'
|
||||
if (kind === 'circle' && !circle?.center) return 'centre'
|
||||
if (kind === 'circle' && !(circle?.radius_m >= RADIUS_MIN && circle.radius_m <= RADIUS_MAX)) return 'radius'
|
||||
return null
|
||||
}
|
||||
|
||||
/** A distance for people: "800 m", "2.5 km" (one decimal at most). */
|
||||
export function distanceText(m) {
|
||||
if (m == null || Number.isNaN(m)) return ''
|
||||
return m < 1000 ? `${Math.round(m)} m` : `${Math.round(m / 100) / 10} km`
|
||||
}
|
||||
|
||||
@@ -45,9 +45,9 @@ test('moving rules and the test form', () => {
|
||||
assert.deepEqual(moveRule(rules, 2, -1), [2, 1, 3])
|
||||
assert.deepEqual(moveRule(rules, 3, 1), [1, 2, 3])
|
||||
assert.deepEqual(previewBody({ sales_point: 'online_delivery', where: 'postcode', area_id: '1', postcode: ' 24131 ', subtotal: '12,5', items: '3', day: 'now', time: '' }),
|
||||
{ sales_point: 'online_delivery', area_id: null, postcode: '24131', subtotal: 12.5, items: 3, weekday: null, time: null })
|
||||
{ sales_point: 'online_delivery', area_id: null, postcode: '24131', lat: null, lng: null, subtotal: 12.5, items: 3, weekday: null, time: null })
|
||||
assert.deepEqual(previewBody({ sales_point: 'online_delivery', where: 'area', area_id: '2', postcode: '', subtotal: '', items: '', day: '5', time: '23:30' }),
|
||||
{ sales_point: 'online_delivery', area_id: 2, postcode: null, subtotal: 0, items: 0, weekday: 5, time: '23:30' })
|
||||
{ sales_point: 'online_delivery', area_id: 2, postcode: null, lat: null, lng: null, subtotal: 0, items: 0, weekday: 5, time: '23:30' })
|
||||
})
|
||||
|
||||
test('online ordering settings: hours per day, any time, numbers', async () => {
|
||||
@@ -75,3 +75,26 @@ test('table bookings online: settings round trip (S.6)', async () => {
|
||||
assert.deepEqual(orderingBody({ ...form, res: { ...form.res, anyTime: true, party_max: '' } }).reservations,
|
||||
{ ...reservations, hours: {}, party_max: 10 })
|
||||
})
|
||||
|
||||
test('6R.G: an area form for each kind, and what keeps it from saving', async () => {
|
||||
const { areaBody, areaProblem, distanceText } = await import('../src/pages/online/feesLogic.js')
|
||||
assert.deepEqual(areaBody({ name: ' Centre ', codes: '24100, 24131' }), { name: 'Centre', kind: 'postcodes', is_active: true, postcodes: ['24100', '24131'] })
|
||||
const sq = [[37, 22], [37, 22.1], [37.1, 22.1]]
|
||||
assert.deepEqual(areaBody({ name: 'Drawn', kind: 'polygon', corners: sq, codes: '1' }), { name: 'Drawn', kind: 'polygon', is_active: true, postcodes: [], geometry: sq })
|
||||
assert.deepEqual(areaBody({ name: 'Ring', kind: 'circle', circle: { center: [37, 22], radius_m: 1500 }, active: false }).geometry, { center: [37, 22], radius_m: 1500 })
|
||||
assert.equal(areaProblem({ name: ' ' }), 'name')
|
||||
assert.equal(areaProblem({ name: 'x', kind: 'polygon', corners: sq.slice(0, 2) }), 'corners')
|
||||
assert.equal(areaProblem({ name: 'x', kind: 'polygon', corners: sq }), null)
|
||||
assert.equal(areaProblem({ name: 'x', kind: 'circle', circle: { radius_m: 500 } }), 'centre')
|
||||
assert.equal(areaProblem({ name: 'x', kind: 'circle', circle: { center: [37, 22], radius_m: 20 } }), 'radius')
|
||||
assert.equal(areaProblem({ name: 'x', kind: 'circle', circle: { center: [37, 22], radius_m: null } }), 'radius')
|
||||
assert.equal(distanceText(800), '800 m')
|
||||
assert.equal(distanceText(2549), '2.5 km')
|
||||
})
|
||||
|
||||
test('6R.G: a test order by a point on the map', () => {
|
||||
const body = previewBody({ sales_point: 'online_delivery', where: 'point', point: [37.05, 22.05], area_id: 3, postcode: '1', subtotal: '10', items: '1', day: 'now' })
|
||||
assert.deepEqual([body.lat, body.lng, body.area_id, body.postcode], [37.05, 22.05, null, null])
|
||||
const none = previewBody({ sales_point: 'online_delivery', where: 'area', area_id: '', postcode: '', subtotal: '10', items: '1', day: 'now' })
|
||||
assert.deepEqual([none.lat, none.lng], [null, null])
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user