diff --git a/local_backend/modules/fiscal/manifest.py b/local_backend/modules/fiscal/manifest.py index 857ef5c..1571e51 100644 --- a/local_backend/modules/fiscal/manifest.py +++ b/local_backend/modules/fiscal/manifest.py @@ -15,8 +15,8 @@ MODULE = Module( SettingDef('fiscal.eftpos_id', '1', "EFTPOS terminal ID sent in CD commands (integer string, e.g. '1')", type='int'), SettingDef('fiscal.enabled', 'false', "Master switch for fiscal printing: 'true' | 'false'", type='bool'), SettingDef('fiscal.end_message', '[]', 'JSON array of up to 5 strings printed at end of receipt via FM commands', type='json'), - SettingDef('fiscal.in_folder', '', 'Path the backend reads fiscal reply files FROM (output of the fiscal driver)', type='json'), - SettingDef('fiscal.out_folder', '', 'Path the backend writes fiscal command files TO (input for the fiscal driver)', type='json'), + SettingDef('fiscal.in_folder', '', 'Path the backend reads fiscal reply files FROM (output of the fiscal driver)', type='str'), + SettingDef('fiscal.out_folder', '', 'Path the backend writes fiscal command files TO (input for the fiscal driver)', type='str'), SettingDef('fiscal.type', 'txt_file', "Fiscal driver type: 'txt_file' (dTEC100extra) — more types coming", type='str'), SettingDef('fiscal.vat_groups', '[]', 'JSON array of VAT group definitions: [{machine_id: int, friendly_name: str}]', type='json'), ), diff --git a/local_backend/routers/settings.py b/local_backend/routers/settings.py index e8b66db..408997c 100644 --- a/local_backend/routers/settings.py +++ b/local_backend/routers/settings.py @@ -57,6 +57,12 @@ def update_setting( sd = setting_defs()[key][0] if (sd.type == "enum" and body.value not in sd.choices) or (sd.type == "bool" and body.value not in ("true", "false")) or (sd.type == "int" and not body.value.lstrip("-").isdigit()): raise XeniaError("validation.setting_value", key=key, value=body.value) + if sd.type == "json": # 6.14a: a broken JSON setting (courses, quick notes, table colours…) would break the apps reading it + import json + try: + json.loads(body.value) + except ValueError: + raise XeniaError("validation.setting_value", key=key, value=body.value[:40]) if key == "venue.timezone": try: timeutil.validate_tz(body.value) diff --git a/local_backend/tests/test_settings_json.py b/local_backend/tests/test_settings_json.py new file mode 100644 index 0000000..25b0425 --- /dev/null +++ b/local_backend/tests/test_settings_json.py @@ -0,0 +1,11 @@ +"""Settings (plan step 6.14a): a JSON setting must be JSON (a broken one would break the apps that +read it: courses, quick notes, the waiter app's table colours); the fiscal folders are plain paths.""" + + +def test_json_settings_are_checked(client, make_user, login): + h = login(make_user(role="owner")) + assert client.put("/api/settings/orders.courses", headers=h, json={"value": '[{"id":1,"name":"Main","color":"#ef4444"}]'}).status_code == 200 + r = client.put("/api/settings/orders.courses", headers=h, json={"value": "[{broken"}) + assert r.status_code == 422 and "validation.setting_value" in r.text + assert client.put("/api/settings/fiscal.out_folder", headers=h, json={"value": "/mnt/fiscal/in"}).status_code == 200 + assert client.put("/api/settings/fiscal.in_folder", headers=h, json={"value": ""}).status_code == 200 diff --git a/manager_dashboard/src/pages/Settings/SettingsPage.jsx b/manager_dashboard/src/pages/Settings/SettingsPage.jsx index 297e183..ef71135 100644 --- a/manager_dashboard/src/pages/Settings/SettingsPage.jsx +++ b/manager_dashboard/src/pages/Settings/SettingsPage.jsx @@ -1,48 +1,62 @@ -import { useState } from 'react' +// Settings (plan step 6.14a; every tab on v2): General, Venue & language, the customer display and +// menu tablets (with those apps), Sign-in & security, Operation, Appearance (the waiter app's table +// colours), Printing, Fiscal device (with that app) and Development. The tab is in the address +// (?tab=…), so a link or a reload opens the same one. Everything here needs core.settings.manage. +import { useSearchParams } from 'react-router-dom' import { useCan, useModule } from '@xenia/access' import { useTranslation } from '@xenia/i18n' -import CustomerDisplaySettings from './sections/CustomerDisplaySettings' -import MenuTabletSettings from './sections/MenuTabletSettings' -import VenueSettings from './sections/VenueSettings' -import AppInfoTab from './tabs/AppInfoTab' -import ColoursTab from './tabs/ColoursTab' -import OperationTab from './tabs/OperationTab' +import { Button } from '@xenia/ui' import PrintingSettings from '../printing/PrintingSettings' -import SecurityTab from './tabs/SecurityTab' -import DevelopmentTab from './tabs/DevelopmentTab' -import FiscalTab from './tabs/FiscalTab' -import { TabGroup } from '../../ui/Tabs' +import CustomerDisplaySettings from './sections/CustomerDisplaySettings' +import DevelopmentSettings from './sections/DevelopmentSettings' +import FiscalSettings from './sections/FiscalSettings' +import MenuTabletSettings from './sections/MenuTabletSettings' +import OperationSettings from './sections/OperationSettings' +import SecuritySettings from './sections/SecuritySettings' +import SystemSettings from './sections/SystemSettings' +import TableColours from './sections/TableColours' +import VenueSettings from './sections/VenueSettings' -const TABS = ['app-info', 'venue', 'customer-display', 'menu-tablets', 'security', 'operation', 'colours', 'print-fonts', 'fiscal', 'development'] +const TABS = { + 'app-info': () => , + venue: () =>
, + 'customer-display': () =>
, + 'menu-tablets': () =>
, + security: () => , + operation: () => , + colours: () => , + 'print-fonts': () => , + fiscal: () => , + development: () => , +} export default function SettingsPage() { const { t } = useTranslation('manager') - const [activeTab, setActiveTab] = useState('app-info') - // the customer display's idle screen (3.4): only where there are displays and the user sets them up + const [params, setParams] = useSearchParams() + // tabs that need an app (and, for the screens, the key to set them up) const displayOn = useModule('customer_display') const displayKey = useCan('customer_display.manage') - const display = displayOn && displayKey - // guests ordering from the menu tablets (6.6): where there are tablets and the user sets them up const tabletOn = useModule('menu_tablet') const tabletKey = useCan('menu_tablet.manage') + const display = displayOn && displayKey const tablets = tabletOn && tabletKey - const tabs = TABS.filter(id => (id !== 'customer-display' || display) && (id !== 'menu-tablets' || tablets)).map(id => ({ id, label: t(`settings.tabs.${id}`) })) - + const waiterApp = useModule('waiter_app') + const fiscal = useModule('fiscal') + const shown = { 'customer-display': display, 'menu-tablets': tablets, colours: waiterApp, fiscal } + const tabs = Object.keys(TABS).filter(id => shown[id] ?? true) + const active = tabs.includes(params.get('tab')) ? params.get('tab') : tabs[0] + const Tab = TABS[active] return ( -
- -
- {activeTab === 'app-info' && } - {activeTab === 'venue' &&
} - {activeTab === 'customer-display' && display &&
} - {activeTab === 'menu-tablets' && tablets &&
} - {activeTab === 'security' && } - {activeTab === 'operation' && } - {activeTab === 'colours' && } - {activeTab === 'print-fonts' && } - {activeTab === 'fiscal' && } - {activeTab === 'development' && } +
+
+
+ {tabs.map(id => ( + + ))} +
+
) } diff --git a/manager_dashboard/src/pages/Settings/sections/DataTransfer.jsx b/manager_dashboard/src/pages/Settings/sections/DataTransfer.jsx new file mode 100644 index 0000000..c72d9c9 --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/DataTransfer.jsx @@ -0,0 +1,81 @@ +// Export / import (plan step 6.14a; was part of the v1 AppInfoTab): the catalogue (categories and +// products, no printers) and the tables (zones and tables) as a file, to copy a setup to another +// venue or keep a copy. Importing adds to what is there (nothing is deleted), after two confirmations. +import { useState } from 'react' +import { useMutation, useQueryClient } from '@tanstack/react-query' +import toast from 'react-hot-toast' +import { Download, Upload } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Button, Dialog } from '@xenia/ui' +import client from '../../../api/client' +import { SettingRow, SettingsCard } from './SettingsCard' +import { bundleSummary } from './settingsLogic' + +const BUNDLES = ['catalog', 'tables'] + +export default function DataTransfer() { + const { t } = useTranslation('manager') + const qc = useQueryClient() + const [pending, setPending] = useState(null) // { bundle, file, summary, step: 1 | 2 } + const importIt = useMutation({ + mutationFn: ({ bundle, file }) => client.post(`/api/data-transfer/import/${bundle}`, file).then(r => r.data), + onSuccess: (_r, { bundle }) => { + toast.success(t(`settings.transfer.imported.${bundle}`)) + setPending(null) + for (const k of ['system-stats', 'products', 'categories', 'tables', 'table-groups']) qc.invalidateQueries({ queryKey: [k] }) + }, + onError: err => toast.error(errorMessage(err, t)), + }) + const exportIt = bundle => client.get(`/api/data-transfer/export/${bundle}`, { responseType: 'blob' }).then(res => { + const name = (res.headers['content-disposition'] ?? '').match(/filename="([^"]+)"/)?.[1] ?? `xenia-${bundle}.json` + const url = URL.createObjectURL(res.data) + const a = document.createElement('a') + a.href = url + a.download = name + a.click() + URL.revokeObjectURL(url) + }).catch(err => toast.error(errorMessage(err, t))) + const pick = (bundle, e) => { + const f = e.target.files?.[0] + e.target.value = '' + if (!f) return + f.text().then(text => { + let file = null + try { file = JSON.parse(text) } catch { /* not JSON */ } + const summary = bundleSummary(file, bundle) + if (!summary) { toast.error(t('settings.transfer.wrongFile', { kind: t(`settings.transfer.kinds.${bundle}`) })); return } + setPending({ bundle, file, summary, step: 1 }) + }) + } + return ( + + {BUNDLES.map(b => ( + + + + + + + ))} + {pending && ( + setPending(null)} + title={pending.step === 1 ? t('settings.transfer.confirmTitle') : t('settings.transfer.finalTitle')} + description={pending.step === 1 + ? t(`settings.transfer.summary.${pending.bundle}`, { groups: pending.summary.groups, items: pending.summary.items }) + : t('settings.transfer.finalBody')} + footer={<> + + {pending.step === 1 + ? + : } + }> + {pending.step === 1 &&

{t('settings.transfer.merge')}

} +
+ )} +
+ ) +} diff --git a/manager_dashboard/src/pages/Settings/sections/DevelopmentSettings.jsx b/manager_dashboard/src/pages/Settings/sections/DevelopmentSettings.jsx new file mode 100644 index 0000000..688d815 --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/DevelopmentSettings.jsx @@ -0,0 +1,23 @@ +// Settings → Development (plan step 6.14a; was the v1 DevelopmentTab): for testing only. Printing +// "spoof": every print job is dropped silently and the apps behave as if it printed. +import { useTranslation } from '@xenia/i18n' +import { Spinner, Switch } from '@xenia/ui' +import { SettingRow, SettingsCard } from './SettingsCard' +import { useSettings } from './useSettings' + +export default function DevelopmentSettings() { + const { t } = useTranslation('manager') + const s = useSettings() + if (s.loading) return
+ const spoof = s.get('dev.spoof_printing', 'false') === 'true' + return ( +
+

{t('settings.dev.warning')}

+ + + s.save('dev.spoof_printing', v)} aria-label={t('settings.dev.spoof')} data-testid="setting-dev.spoof_printing" /> + + +
+ ) +} diff --git a/manager_dashboard/src/pages/Settings/sections/FiscalSettings.jsx b/manager_dashboard/src/pages/Settings/sections/FiscalSettings.jsx new file mode 100644 index 0000000..1e35b1e --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/FiscalSettings.jsx @@ -0,0 +1,150 @@ +// Settings → Fiscal device (plan step 6.14a; was the v1 FiscalTab; only with the fiscal app on): +// sending receipts to the fiscal device (FIM) on each payment, the driver type, the two folders the +// server and the driver exchange files through (with a check that both can be reached), the clerk +// and card-terminal numbers, up to five lines printed at the end of a receipt, and the VAT groups as +// programmed in the device. +import { useState } from 'react' +import { useMutation } from '@tanstack/react-query' +import toast from 'react-hot-toast' +import { CheckCircle2, Plus, Trash2, XCircle } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Button, Field, IconButton, Input, Select, Spinner, Switch } from '@xenia/ui' +import client from '../../../api/client' +import { SettingRow, SettingsCard } from './SettingsCard' +import { cleanVatGroups, endLines, readJson } from './settingsLogic' +import { useSettings } from './useSettings' + +export default function FiscalSettings() { + const { t } = useTranslation('manager') + const s = useSettings() + if (s.loading) return
+ const on = s.get('fiscal.enabled', 'false') === 'true' + return ( +
+ + + s.save('fiscal.enabled', v)} aria-label={t('settings.fiscal.enabled')} data-testid="setting-fiscal.enabled" /> + + + setTyped(e.target.value.trim())} + onBlur={() => { if (ok && value !== saved) s.save(k, value); if (ok) setTyped(null) }} data-testid={`setting-${k}`} /> + + + ) +} + +function Folders({ s }) { + const { t } = useTranslation('manager') + const [out, setOut] = useState(() => s.get('fiscal.out_folder')) + const [inn, setIn] = useState(() => s.get('fiscal.in_folder')) + const [result, setResult] = useState(null) + const test = useMutation({ + mutationFn: () => client.post('/api/fiscal/test-folders', { out_folder: out.trim(), in_folder: inn.trim() }).then(r => r.data), + onSuccess: setResult, + onError: err => toast.error(errorMessage(err, t)), + }) + const save = () => { s.save('fiscal.out_folder', out.trim()); s.save('fiscal.in_folder', inn.trim()); setResult(null) } + const ready = out.trim() && inn.trim() + return ( + +
+ + setOut(e.target.value)} data-testid="fiscal-out" /> + + + setIn(e.target.value)} data-testid="fiscal-in" /> + + + + + + {result && (result.ok ? ( +

+ ) : ( +
+ + {result.out_folder_error && {t('settings.fiscal.out')}: {result.out_folder_error}} + {result.in_folder_error && {t('settings.fiscal.in')}: {result.in_folder_error}} +
+ ))} +
+
+ ) +} + +function EndMessage({ s }) { + const { t } = useTranslation('manager') + const [lines, setLines] = useState(() => endLines(s.get('fiscal.end_message', '[]'))) + return ( + +
+ {lines.map((l, i) => ( + + {i + 1} + setLines(ls => ls.map((x, j) => (j === i ? e.target.value : x)))} /> + + ))} + +
+
+ ) +} + +function VatGroups({ s }) { + const { t } = useTranslation('manager') + const [groups, setGroups] = useState(() => readJson(s.get('fiscal.vat_groups', '[]'), []).map(g => ({ machine_id: String(g.machine_id ?? ''), friendly_name: g.friendly_name ?? '' }))) + const set = (i, k, v) => setGroups(gs => gs.map((g, j) => (j === i ? { ...g, [k]: v } : g))) + const save = () => { + const clean = cleanVatGroups(groups) + s.save('fiscal.vat_groups', JSON.stringify(clean)) + setGroups(clean.map(g => ({ machine_id: String(g.machine_id), friendly_name: g.friendly_name }))) + } + return ( + +
+ {!groups.length &&

{t('settings.fiscal.noVat')}

} + {groups.map((g, i) => ( + + + set(i, 'machine_id', e.target.value)} /> + + + set(i, 'friendly_name', e.target.value)} /> + + setGroups(gs => gs.filter((_, j) => j !== i))}> + + ))} + + + + +
+
+ ) +} diff --git a/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx b/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx new file mode 100644 index 0000000..9511226 --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/OperationSettings.jsx @@ -0,0 +1,139 @@ +// Settings → Operation (plan step 6.14a; was the v1 OperationTab): what each role may do, what the +// waiters do by themselves (start / end their shift, see their takings), card payments, how tables +// and orders behave (closing, the kitchen screens' serve step, courses, quick notes for lines), +// table flags, quick messages to the staff, and sending the digital menu to the cloud now. +// Each part shows only with its app on. Dropped from v1: "automatic store schedule" (its switches +// were kept in the browser only and nothing ever read them). +import { useState } from 'react' +import { useMutation } from '@tanstack/react-query' +import toast from 'react-hot-toast' +import { ArrowDown, ArrowUp, Plus, RefreshCw, Trash2 } from 'lucide-react' +import { useModule } from '@xenia/access' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Button, IconButton, Input, Spinner, Switch } from '@xenia/ui' +import client from '../../../api/client' +import QuickMessages from './QuickMessages' +import RolePermissions from './RolePermissions' +import { SettingRow, SettingsCard } from './SettingsCard' +import TableFlags from './TableFlags' +import { addCourse, cleanNotes, move, nextColour, readJson } from './settingsLogic' +import { useSettings } from './useSettings' +import { COURSE_COLOURS } from './venueColours' + +export default function OperationSettings() { + const ordering = useModule('ordering') + const chat = useModule('chat') + const qrMenu = useModule('connect_menu') + return ( +
+ + {ordering && } + {ordering && } + {chat && } + {qrMenu && } +
+ ) +} + +function Toggle({ s, k, fallback = 'false', label, hint }) { + return ( + + s.save(k, v)} aria-label={label} data-testid={`setting-${k}`} /> + + ) +} + +function OrderingSettings() { + const { t } = useTranslation('manager') + const s = useSettings() + if (s.loading) return
+ const o = k => t(`settings.ops.${k}`) + return (<> + + + + + + + + + + + + + + {s.get('orders.courses_enabled') === 'true' && } + + + ) +} + +/** orders.courses: [{ id, name, color }] in the order they are served. */ +function Courses({ s }) { + const { t } = useTranslation('manager') + const saved = readJson(s.get('orders.courses', '[]'), []) + const [names, setNames] = useState({}) // typed names not saved yet, by id + const save = next => s.save('orders.courses', JSON.stringify(next)) + return ( +
+ {saved.map((c, i) => ( +
+
+ ))} + +
+ ) +} + +/** orders.quick_notes: the notes a waiter can add to a line with one tap. */ +function QuickNotes({ s }) { + const { t } = useTranslation('manager') + const notes = readJson(s.get('orders.quick_notes', '[]'), []) + const [typed, setTyped] = useState('') + const [edits, setEdits] = useState({}) + const save = next => s.save('orders.quick_notes', JSON.stringify(cleanNotes(next))) + const add = () => { if (typed.trim()) { save([...notes, typed]); setTyped('') } } + return ( +
+ {t('settings.ops.quickNotes')} + {t('settings.ops.quickNotesHint')} + {notes.map((n, i) => ( +
+ setEdits(x => ({ ...x, [i]: e.target.value }))} + onBlur={() => { if (edits[i] != null && edits[i] !== n) save(notes.map((x, j) => (j === i ? edits[i] : x))); setEdits({}) }} /> + save(notes.filter((_, j) => j !== i))}> +
+ ))} +
+ setTyped(e.target.value)} + onKeyDown={e => { if (e.key === 'Enter') add() }} data-testid="quick-note-new" /> + +
+
+ ) +} + +function MenuSync() { + const { t } = useTranslation('manager') + const sync = useMutation({ + mutationFn: () => client.post('/api/system/sync-menu'), + onSuccess: () => toast.success(t('settings.ops.synced')), + onError: err => toast.error(errorMessage(err, t)), + }) + return ( + + + + + + ) +} diff --git a/manager_dashboard/src/pages/Settings/sections/QuickMessages.jsx b/manager_dashboard/src/pages/Settings/sections/QuickMessages.jsx new file mode 100644 index 0000000..c7a3a38 --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/QuickMessages.jsx @@ -0,0 +1,46 @@ +// Quick messages (plan step 6.14a; was part of the v1 OperationTab): ready texts a manager sends +// to the staff with one tap (chat app). Add, edit in place, delete. +import { useState } from 'react' +import { useMutation, useQueryClient } from '@tanstack/react-query' +import toast from 'react-hot-toast' +import { Plus, Trash2 } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Button, IconButton, Input, Spinner } from '@xenia/ui' +import client from '../../../api/client' +import { useLiveQuery } from '../../../live/useLiveQuery' +import { SettingsCard } from './SettingsCard' + +export default function QuickMessages() { + const { t } = useTranslation('manager') + const qc = useQueryClient() + const [typed, setTyped] = useState('') + const [edits, setEdits] = useState({}) + const { data: list = [], isPending } = useLiveQuery({ queryKey: ['quick-templates'], queryFn: () => client.get('/api/notifications/templates').then(r => r.data) }) + const done = () => qc.invalidateQueries({ queryKey: ['quick-templates'] }) + const onError = err => toast.error(errorMessage(err, t)) + const add = useMutation({ mutationFn: body => client.post('/api/notifications/templates', { body, sort_order: list.length + 1 }), onSuccess: () => { setTyped(''); done() }, onError }) + const edit = useMutation({ mutationFn: ({ id, body }) => client.put(`/api/notifications/templates/${id}`, { body }), onSuccess: () => { toast.success(t('settings.saved')); done() }, onError }) + const remove = useMutation({ mutationFn: id => client.delete(`/api/notifications/templates/${id}`), onSuccess: done, onError }) + const submit = () => { if (typed.trim()) add.mutate(typed.trim()) } + return ( + +
+ {isPending ? : !list.length &&

{t('settings.messages.none')}

} + {list.map((m, i) => ( +
+ {i + 1}. + setEdits(x => ({ ...x, [m.id]: e.target.value }))} + onBlur={() => { const v = edits[m.id]?.trim(); if (v && v !== m.body) edit.mutate({ id: m.id, body: v }); setEdits({}) }} /> + remove.mutate(m.id)}> +
+ ))} +
+ setTyped(e.target.value)} + onKeyDown={e => { if (e.key === 'Enter') submit() }} data-testid="message-new" /> + +
+
+
+ ) +} diff --git a/manager_dashboard/src/pages/Settings/sections/SecuritySettings.jsx b/manager_dashboard/src/pages/Settings/sections/SecuritySettings.jsx new file mode 100644 index 0000000..d608f10 --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/SecuritySettings.jsx @@ -0,0 +1,115 @@ +// Settings → Sign-in & security (plan step 6.14a; was the v1 SecurityTab): how each app signs +// people in (SignInSettings, 2.6f), locking the dashboard after a while without use (unlocked with +// a PIN) and signing out after a longer while, and the owner's recovery codes (five one-time +// codes to get in when the password is lost; shown once, when made). +import { useState } from 'react' +import { useMutation } from '@tanstack/react-query' +import toast from 'react-hot-toast' +import { Copy, RefreshCw } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Button, IconButton, Select, Spinner, Switch } from '@xenia/ui' +import client from '../../../api/client' +import { useLiveQuery } from '../../../live/useLiveQuery' +import { Pill } from '../../overview/parts' +import { SettingRow, SettingsCard } from './SettingsCard' +import SignInSettings from './SignInSettings' +import { IDLE_STEPS, idleParts } from './settingsLogic' +import { useSettings } from './useSettings' + +export default function SecuritySettings() { + return ( +
+ + + +
+ ) +} + +function IdleSettings() { + const { t } = useTranslation('manager') + const s = useSettings() + if (s.loading) return
+ const lock = s.get('security.auto_lock', 'false') === 'true' + const out = s.get('security.auto_logout', 'false') === 'true' + const lockSecs = Number(s.get('security.auto_lock_seconds', '300')) + const outSecs = Number(s.get('security.auto_logout_seconds', '1800')) + const span = v => { const p = idleParts(v); return t(`settings.security.${p.unit}`, { count: p.n }) } + const options = current => [...new Set([...IDLE_STEPS, current])].sort((a, b) => a - b).map(v => ({ value: String(v), label: span(v) })) + return ( + + + s.save('security.auto_lock', v)} aria-label={t('settings.security.lock')} data-testid="setting-security.auto_lock" /> + + {lock && ( + + s.save('security.auto_logout_seconds', e.target.value)} options={options(outSecs)} /> + + )} + + ) +} + +function RecoveryCodes() { + const { t } = useTranslation('manager') + const [codes, setCodes] = useState(null) + const [confirm, setConfirm] = useState(false) + const { data, refetch } = useLiveQuery({ queryKey: ['recovery-status'], queryFn: () => client.get('/api/recovery/status').then(r => r.data) }) + const make = useMutation({ + mutationFn: () => client.post('/api/recovery/generate').then(r => r.data), + onSuccess: d => { setCodes(d.codes); setConfirm(false); refetch() }, + onError: err => toast.error(errorMessage(err, t)), + }) + const left = data?.unused_count + const copy = text => navigator.clipboard?.writeText(text).then(() => toast.success(t('settings.security.copied'))) + return ( + + + {left == null ? : {t('settings.security.ofFive', { count: left })}} + +
+ {codes ? ( +
+

{t('settings.security.copyNow')}

+
    + {codes.map(c => ( +
  • + {c} + copy(c)}> +
  • + ))} +
+ + + + +
+ ) : confirm ? ( +
+

{t('settings.security.replace', { count: left ?? 0 })}

+ + + + +
+ ) : ( + + )} +

{t('settings.security.recoveryHow')}

+
+
+ ) +} diff --git a/manager_dashboard/src/pages/Settings/sections/SystemSettings.jsx b/manager_dashboard/src/pages/Settings/sections/SystemSettings.jsx new file mode 100644 index 0000000..14f769f --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/SystemSettings.jsx @@ -0,0 +1,168 @@ +// Settings → General (plan step 6.14a; was the v1 AppInfoTab): the system (version and whether an +// update is out, license, running or locked, how long it has been up), the local network the +// phones use (the server's address, changed by hand or found by itself; the pairing QR), what the +// venue has set up, exporting / importing the catalogue and the tables, and the support account's +// lock / unlock. The time zone is in "Venue & language" (it was here twice). +import { useState } from 'react' +import { useMutation, useQueryClient } from '@tanstack/react-query' +import toast from 'react-hot-toast' +import { QRCodeSVG } from 'qrcode.react' +import { Lock, LockOpen, QrCode, RefreshCw } from 'lucide-react' +import { useAccess } from '@xenia/access' +import { errorMessage } from '@xenia/api' +import { useFormat, useTranslation } from '@xenia/i18n' +import { Button, Dialog, Input, Spinner } from '@xenia/ui' +import client from '../../../api/client' +import { useLiveQuery } from '../../../live/useLiveQuery' +import { Pill } from '../../overview/parts' +import DataTransfer from './DataTransfer' +import { SettingRow, SettingsCard } from './SettingsCard' +import { lanAddress, uptime, waiterPairUrl } from './settingsLogic' + +export default function SystemSettings() { + const { t } = useTranslation('manager') + const fmt = useFormat() + const qc = useQueryClient() + const { user } = useAccess() + const [qr, setQr] = useState(null) + const { data: status, isPending } = useLiveQuery({ queryKey: ['system-status'], queryFn: () => client.get('/api/system/status').then(r => r.data), refetchInterval: 30_000 }) + const { data: stats } = useLiveQuery({ queryKey: ['system-stats'], queryFn: () => client.get('/api/system/stats').then(r => r.data), staleTime: 60_000 }) + const refresh = useMutation({ + mutationFn: () => client.post('/api/system/sync-license').catch(() => null), // the cloud may be away: still refresh what we know + onSettled: () => { qc.invalidateQueries({ queryKey: ['system-status'] }); qc.invalidateQueries({ queryKey: ['license-status'] }) }, + }) + const lock = useMutation({ + mutationFn: on => client.post(on ? '/api/system/lock' : '/api/system/unlock'), + onSuccess: (_r, on) => { toast.success(t(on ? 'settings.system.locked' : 'settings.system.unlocked')); qc.invalidateQueries({ queryKey: ['system-status'] }) }, + onError: err => toast.error(errorMessage(err, t)), + }) + if (isPending) return
+ const up = uptime(status?.uptime_seconds) + const state = status?.locked ? ['danger', 'locked'] : status?.lock_pending ? ['warning', 'lockPending'] : ['success', 'running'] + const latest = status?.latest_version + const counts = ['categories', 'products', 'tables', 'table_groups', 'managers', 'waiters'] + + return ( +
+ + + + {status?.version ?? '—'} + {latest && latest !== status?.version && {t('settings.system.update', { version: latest })}} + {latest && latest === status?.version && {t('settings.system.upToDate')}} + + + + {t(status?.licensed ? 'settings.system.licensed' : 'settings.system.unlicensed')} + + + {t(`settings.system.states.${state[1]}`)} + + + + {t('settings.system.uptimeValue', { days: up.days, h: up.h, m: up.m })} + + + + {status?.waiter_domain && ( + + {status.waiter_domain} + + + + )} + + + + + +
+ {counts.map(k => ( +
+ {t(`settings.system.counts.${k}`)} + {stats?.[k] ?? '—'} +
+ ))} +
+
+ + + + {user?.role === 'superadmin' && ( + +
+ + +
+
+ )} + + {qr && ( + setQr(null)} title={t('settings.system.qrTitle')} description={qr.caption} + footer={}> +
+
+

{qr.url}

+
+
+ )} +
+ ) +} + +/** The server's address on the venue's Wi-Fi: what the phones and the QR use (services/lan_ip.py). */ +function LanAccess({ status, onQr }) { + const { t } = useTranslation('manager') + const qc = useQueryClient() + const info = status?.lan_ip_info + const { ip, source } = lanAddress(status, window.location.hostname) + const [editing, setEditing] = useState(null) // the typed address while editing + const save = useMutation({ + mutationFn: value => client.put('/api/system/lan-ip-override', { ip: value }).then(r => r.data), + onSuccess: (_r, value) => { toast.success(t(value ? 'settings.lan.saved' : 'settings.lan.automatic')); setEditing(null); qc.invalidateQueries({ queryKey: ['system-status'] }) }, + onError: err => toast.error(errorMessage(err, t)), + }) + return ( + + {info?.mismatch && ( +
+ {t('settings.lan.mismatch', { ip, detected: info.detected })} + +
+ )} + + {editing != null ? ( + + setEditing(e.target.value)} + onKeyDown={e => { if (e.key === 'Enter' && editing.trim()) save.mutate(editing.trim()); if (e.key === 'Escape') setEditing(null) }} data-testid="lan-ip" /> + + + {info?.override && } + + + + ) : ( + + {ip ?? '—'} + {source && {t(`settings.lan.source.${source}`)}} + + + )} + + {ip && (<> + + + http://{ip} + + + + + http://{ip}/manager + + )} +
+ ) +} diff --git a/manager_dashboard/src/pages/Settings/sections/TableColours.jsx b/manager_dashboard/src/pages/Settings/sections/TableColours.jsx new file mode 100644 index 0000000..9672cec --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/TableColours.jsx @@ -0,0 +1,154 @@ +// Settings → Appearance (plan step 6.14a; was the v1 ColoursTab): the colours of the table cards on +// the waiter app, for its light and dark look (setting `ui.table_colours`): for each state of a +// table (free, someone else's, mine, partly paid, paid, ready in the kitchen) the card, its badge +// and their texts. "Ready in the kitchen" can flash between two sets of colours. A preview of +// each look; reset to the defaults. The colours are the venue's data (sections/venueColours.js). +import { useEffect, useState } from 'react' +import { RotateCcw } from 'lucide-react' +import { useTranslation } from '@xenia/i18n' +import { Button, Dialog, Field, Input, Spinner, Switch } from '@xenia/ui' +import { SettingsCard } from './SettingsCard' +import { buildColour, mergeColours, parseColour, readJson, setSlot } from './settingsLogic' +import { useSettings } from './useSettings' +import { CHECKER, DEFAULT_COLOURS, QUICK_SWATCHES, SLOTS, STATUSES } from './venueColours' + +const MODES = ['light', 'dark'] + +export default function TableColours() { + const { t } = useTranslation('manager') + const s = useSettings() + const [picking, setPicking] = useState(null) // { mode, status, slot } + const [resetting, setResetting] = useState(false) + if (s.loading) return
+ const colours = mergeColours(readJson(s.get('ui.table_colours', '{}'), {}), DEFAULT_COLOURS) + const save = next => s.save('ui.table_colours', JSON.stringify(next)) + return ( +
+ +
+ {MODES.map(mode => ( +
+

{t(`settings.colours.modes.${mode}`)}

+
+ {STATUSES.map(st => )} +
+ {STATUSES.map(st => ( + setPicking({ mode, status: st, slot })} + onFlash={v => save(setSlot(colours, mode, st, 'flash', v))} /> + ))} +
+ ))} +
+
+ +
+
+ {picking && ( + setPicking(null)} + onSave={v => { save(setSlot(colours, picking.mode, picking.status, picking.slot, v)); setPicking(null) }} /> + )} + {resetting && ( + setResetting(false)} title={t('settings.colours.resetTitle')} description={t('settings.colours.resetBody')} + footer={<> + + + } /> + )} +
+ ) +} + +/** A table card as the phones draw it, small; `second` shows the flash's other colours. */ +function MockCard({ cfg, label, second = false }) { + const v = k => (second ? cfg[`${k}2`] ?? cfg[k] : cfg[k]) + return ( +
+ T1 + {label} +
+ ) +} + +function useFlash(on) { + const [second, setSecond] = useState(false) + useEffect(() => { + if (!on) return undefined + const id = setInterval(() => setSecond(x => !x), 700) + return () => clearInterval(id) + }, [on]) + return on && second +} + +function StatusColours({ cfg, status, onPick, onFlash }) { + const { t } = useTranslation('manager') + const canFlash = status === 'kds_ready' + const second = useFlash(canFlash && !!cfg.flash) + return ( +
+
+
+ {t(`settings.colours.statuses.${status}`)} + {canFlash && } +
+
+ {SLOTS.map(([a, b]) => ( +
+ onPick(a)} /> + {canFlash && cfg.flash && onPick(b)} small />} +
+ ))} +
+
+ ) +} + +function Swatch({ value, label, onClick, small = false }) { + return ( + + ) +} + +function ColourDialog({ slot, value, title, onClose, onSave }) { + const { t } = useTranslation('manager') + const start = parseColour(value) ?? parseColour(DEFAULT_COLOURS.light.free.cardBg) + const [hex, setHex] = useState(start.hex) + const [alpha, setAlpha] = useState(start.alpha) + const colour = buildColour(hex, alpha) + const pick = c => { const p = parseColour(c); if (p) { setHex(p.hex); setAlpha(p.alpha) } } + return ( + + + + }> +
+
+ {colour ?? t('settings.colours.invalid')} +
+ + + setHex(e.target.value)} className="w-12 h-10 rounded-control border border-line bg-surface cursor-pointer" aria-label={t('settings.colours.colour')} /> + setHex(e.target.value.trim())} data-testid="colour-hex" /> + + + + setAlpha(Number(e.target.value))} className="w-full accent-accent" /> + + + + {(QUICK_SWATCHES[slot] ?? []).map(c => ( +
+
+ ) +} diff --git a/manager_dashboard/src/pages/Settings/sections/TableFlags.jsx b/manager_dashboard/src/pages/Settings/sections/TableFlags.jsx new file mode 100644 index 0000000..22d48be --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/TableFlags.jsx @@ -0,0 +1,119 @@ +// Table flags (plan step 6.14a; was part of the v1 OperationTab): marks the staff put on a table +// ("birthday", "VIP", "allergy"…), each with an emoji, a colour and white or black text. New, edit, +// turn off (kept, not offered) and on, delete. +import { useState } from 'react' +import { useMutation, useQueryClient } from '@tanstack/react-query' +import toast from 'react-hot-toast' +import { Pencil, Plus, Power, Trash2 } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Button, Dialog, Field, IconButton, Input, Spinner, cx } from '@xenia/ui' +import client from '../../../api/client' +import { useLiveQuery } from '../../../live/useLiveQuery' +import { Pill } from '../../overview/parts' +import { SettingsCard } from './SettingsCard' +import { FLAG_COLOURS, FLAG_DEFAULT, FLAG_TEXT } from './venueColours' + +// Emojis offered for a flag (the venue's choice; any other can be typed) +const EMOJIS = ['🧹', '⭐', '📝', '🛎️', '💎', '🤵🏻', '🔒', '🛒', '🗣️', '⛔', '🥳', '🎂', '🎉', '🍰', '🤩', '☕', '🥂', '🍾', '🍹', '💦', + '🍖', '🥩', '🍽️', '🥓', '🍳', '♿', '👶', '🤬', '🐶', '🐱', '🚧', '🔥', '❄️', '⏳', '⚠️'] + +const FLAG_TEXT_WHITE = 'var(--x-on-colour)' // a flag's default text: white on its colour + +export function FlagBadge({ flag }) { + return ( + + {flag.emoji && }{flag.name} + + ) +} +export default function TableFlags() { + const { t } = useTranslation('manager') + const qc = useQueryClient() + const [editing, setEditing] = useState(null) // a flag, or {} for a new one + const [removing, setRemoving] = useState(null) + const { data: flags = [], isPending } = useLiveQuery({ queryKey: ['flag-defs', 'all'], queryFn: () => client.get('/api/flags/defs', { params: { include_inactive: true } }).then(r => r.data) }) + const changed = () => { qc.invalidateQueries({ queryKey: ['flag-defs'] }) } + const onError = err => toast.error(errorMessage(err, t)) + const toggle = useMutation({ mutationFn: f => client.patch(`/api/flags/defs/${f.id}/toggle-active`).then(r => r.data), onSuccess: f => { toast.success(t(f.is_active ? 'settings.flags.on' : 'settings.flags.off', { name: f.name })); changed() }, onError }) + const remove = useMutation({ mutationFn: f => client.delete(`/api/flags/defs/${f.id}`), onSuccess: () => { toast.success(t('settings.flags.deleted')); setRemoving(null); changed() }, onError }) + return ( + +
+ {isPending ? : !flags.length &&

{t('settings.flags.none')}

} + {flags.map(f => ( +
+ + {!f.is_active && {t('settings.flags.offTag')}} + setEditing(f)}> + toggle.mutate(f)}> + setRemoving(f)}> +
+ ))} + +
+ {editing && setEditing(null)} onSaved={() => { setEditing(null); changed() }} />} + {removing && ( + setRemoving(null)} title={t('settings.flags.deleteTitle', { name: removing.name })} description={t('settings.flags.deleteBody')} + footer={<> + + + } /> + )} +
+ ) +} + +function FlagDialog({ flag, onClose, onSaved }) { + const { t } = useTranslation('manager') + const isNew = !flag.id + const [form, setForm] = useState({ name: flag.name ?? '', emoji: flag.emoji ?? '', color: flag.color ?? FLAG_DEFAULT, text_color: flag.text_color ?? null }) + const [tried, setTried] = useState(false) + const set = (k, v) => setForm(f => ({ ...f, [k]: v })) + const save = useMutation({ + mutationFn: body => (isNew ? client.post('/api/flags/defs', body) : client.put(`/api/flags/defs/${flag.id}`, body)), + onSuccess: () => { toast.success(t('settings.saved')); onSaved() }, + onError: err => toast.error(errorMessage(err, t)), + }) + const submit = () => { setTried(true); if (form.name.trim()) save.mutate({ ...form, name: form.name.trim(), emoji: form.emoji || null }) } + return ( + + + + }> +
+
+ + set('name', e.target.value)} data-testid="flag-name" /> + + + + {EMOJIS.map(e => ( + + ))} + + + + + {FLAG_COLOURS.map(c => ( + + ))} + + +
+
+ ) +} diff --git a/manager_dashboard/src/pages/Settings/sections/settingsLogic.js b/manager_dashboard/src/pages/Settings/sections/settingsLogic.js new file mode 100644 index 0000000..d733571 --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/settingsLogic.js @@ -0,0 +1,143 @@ +// The rules behind the settings tabs (plan step 6.14a), unit-tested in tests/settings.test.mjs. + +/** Seconds offered for locking / signing out after inactivity. */ +export const IDLE_STEPS = [5, 10, 30, 60, 120, 300, 600, 900, 1800, 3600] + +/** { n, unit } to show a number of seconds as seconds, minutes or hours. */ +export function idleParts(seconds) { + const s = Number(seconds) || 0 + if (s < 60) return { n: s, unit: 'seconds' } + if (s < 3600) return { n: Math.round(s / 60), unit: 'minutes' } + return { n: Math.round(s / 3600), unit: 'hours' } +} + +/** A JSON setting read safely: the parsed value, or `fallback` when missing / broken / of the wrong kind. */ +export function readJson(raw, fallback) { + try { + const v = JSON.parse(raw) + return v != null && (Array.isArray(fallback) ? Array.isArray(v) : typeof v === typeof fallback) ? v : fallback + } catch { + return fallback + } +} + +// ── courses and quick notes (orders.courses, orders.quick_notes) ───────────── + +/** A new course after the others, with the next colour of the palette. */ +export function addCourse(courses, palette, name) { + const id = Math.max(0, ...courses.map(c => c.id)) + 1 + return [...courses, { id, name: name(id), color: palette[courses.length % palette.length] }] +} + +/** Move the item at `from` to `to` (a new array). */ +export function move(list, from, to) { + if (to < 0 || to >= list.length || from === to) return list + const next = [...list] + const [x] = next.splice(from, 1) + next.splice(to, 0, x) + return next +} + +/** The next colour of the palette after `current` (the first when it isn't in it). */ +export function nextColour(palette, current) { + return palette[(palette.indexOf(current) + 1) % palette.length] +} + +/** Quick notes as saved: trimmed, no empty ones, no repeats. */ +export function cleanNotes(notes) { + const seen = new Set() + return notes.map(n => n.trim()).filter(n => n && !seen.has(n) && seen.add(n)) +} + +// ── table card colours (ui.table_colours, read by the waiter app) ──────────── + +/** Saved colours over the defaults, so a status or a slot missing from the saved ones keeps its default. */ +export function mergeColours(saved, defaults) { + const out = {} + for (const mode of Object.keys(defaults)) { + out[mode] = {} + for (const [status, d] of Object.entries(defaults[mode])) out[mode][status] = { ...d, ...(saved?.[mode]?.[status] ?? {}) } + } + return out +} + +/** One slot changed (a new object). */ +export function setSlot(colours, mode, status, slot, value) { + return { ...colours, [mode]: { ...colours[mode], [status]: { ...colours[mode][status], [slot]: value } } } +} + +const HEX6 = /^#[0-9a-f]{6}$/i +const HEX3 = /^#[0-9a-f]{3}$/i +const RGBA = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/ + +/** Any CSS colour of the kinds the palette uses → { hex: '#rrggbb', alpha 0..1 }. */ +export function parseColour(value) { + const s = String(value ?? '').trim() + const m = s.match(RGBA) + if (m) { + const h = n => Number(n).toString(16).padStart(2, '0') + return { hex: `#${h(m[1])}${h(m[2])}${h(m[3])}`, alpha: m[4] != null ? Math.min(1, Math.max(0, Number(m[4]))) : 1 } + } + if (HEX3.test(s)) return { hex: `#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`.toLowerCase(), alpha: 1 } + if (HEX6.test(s)) return { hex: s.toLowerCase(), alpha: 1 } + return null +} + +/** { hex, alpha } → '#rrggbb' or 'rgba(r,g,b,a)'. */ +export function buildColour(hex, alpha) { + if (!HEX6.test(hex)) return null + if (alpha >= 1) return hex.toLowerCase() + const n = i => parseInt(hex.slice(i, i + 2), 16) + return `rgba(${n(1)},${n(3)},${n(5)},${Number(alpha).toFixed(2)})` +} + +// ── fiscal device ──────────────────────────────────────────────────────────── + +/** VAT groups as saved: whole machine ids above zero with a name, each id once. */ +export function cleanVatGroups(groups) { + const seen = new Set() + return groups.map(g => ({ machine_id: Number.parseInt(String(g.machine_id).trim(), 10), friendly_name: String(g.friendly_name ?? '').trim() })) + .filter(g => g.machine_id > 0 && g.friendly_name && !seen.has(g.machine_id) && seen.add(g.machine_id)) +} + +/** The receipt's last lines: always 5 boxes to fill. */ +export function endLines(saved) { + return [...readJson(saved, []).map(String), '', '', '', '', ''].slice(0, 5) +} + +// ── data transfer ──────────────────────────────────────────────────────────── + +/** What an export file holds, or null when it isn't one of `bundle`. */ +export function bundleSummary(file, bundle) { + if (!file || file.bundle !== bundle) return null + const d = file.data ?? {} + if (bundle === 'catalog') { + const cats = d.categories ?? [] + return { groups: cats.length, items: cats.reduce((n, c) => n + (c.products?.length ?? 0), 0) + (d.uncategorized_products?.length ?? 0) } + } + const groups = d.table_groups ?? [] + return { groups: groups.length, items: groups.reduce((n, g) => n + (g.tables?.length ?? 0), 0) + (d.ungrouped_tables?.length ?? 0) } +} + +/** The pairing link the phones scan: opens the waiter app; ?pair=&k= pairs the native app. */ +export function waiterPairUrl(ip, siteId, spki) { + const p = new URLSearchParams() + if (siteId) p.set('pair', siteId) + if (siteId && spki) p.set('k', spki) + const q = p.toString() + return `http://${ip}/${q ? `?${q}` : ''}` +} + +const IPV4 = /^\d{1,3}(\.\d{1,3}){3}$/ + +/** The address phones use: the server's answer, else this page's own address when it is an IP. */ +export function lanAddress(status, hostname) { + if (status?.lan_ip) return { ip: status.lan_ip, source: status.lan_ip_info?.source ?? 'env' } + return IPV4.test(hostname) && !hostname.startsWith('127.') ? { ip: hostname, source: 'browser' } : { ip: null, source: null } +} + +/** { h, m } of an uptime in seconds. */ +export function uptime(seconds) { + const s = Math.max(0, Number(seconds) || 0) + return { days: Math.floor(s / 86400), h: Math.floor((s % 86400) / 3600), m: Math.floor((s % 3600) / 60) } +} diff --git a/manager_dashboard/src/store/tableColourStore.js b/manager_dashboard/src/pages/Settings/sections/venueColours.js similarity index 50% rename from manager_dashboard/src/store/tableColourStore.js rename to manager_dashboard/src/pages/Settings/sections/venueColours.js index a57b601..432c987 100644 --- a/manager_dashboard/src/store/tableColourStore.js +++ b/manager_dashboard/src/pages/Settings/sections/venueColours.js @@ -1,8 +1,20 @@ -import { create } from 'zustand' -import { persist } from 'zustand/middleware' +// The colours a venue gives its table cards on the waiter app (setting `ui.table_colours`, plan step +// 6.14a). These are the venue's data, not the manager's styling: listed in tests/v2-guards.test.mjs DATA. +// DEFAULT_COLOURS must stay as waiter_pwa/src/store/tableColourStore.js (the phones' own fallback): +// "Reset to defaults" writes them. -// Must stay in sync with waiter_pwa/src/store/tableColourStore.js DEFAULT_COLOURS. -// The PWA uses these as its hardcoded fallback; the manager uses them for "reset to defaults". +export const STATUSES = ['free', 'open', 'mine', 'partially_paid', 'paid', 'kds_ready'] +export const SLOTS = [['cardBg', 'cardBg2'], ['badgeBg', 'badgeBg2'], ['nameText', 'nameText2'], ['badgeText', 'badgeText2']] + +/** The squares behind a see-through colour, so its transparency shows. */ +export const CHECKER = 'repeating-conic-gradient(#cbd5e1 0% 25%, #ffffff 0% 50%) 50% / 10px 10px' + +// Course and table-flag colours offered when a venue sets them up (orders.courses, flag defs) +export const COURSE_COLOURS = ['#ef4444', '#f97316', '#eab308', '#22c55e', '#3b82f6', '#8b5cf6', '#ec4899', '#06b6d4', '#64748b', '#10b981'] +export const FLAG_COLOURS = ['#ef4444', '#f97316', '#eab308', '#22c55e', '#3b82f6', '#8b5cf6', '#ec4899', '#06b6d4', '#6b7280', '#dc2626'] +/** A flag's text: white (null, the default) or black. */ +export const FLAG_TEXT = [null, '#000000'] +export const FLAG_DEFAULT = '#6b7280' export const DEFAULT_COLOURS = { light: { @@ -93,25 +105,13 @@ export const DEFAULT_COLOURS = { }, } -const useTableColourStore = create(persist( - (set) => ({ - colours: DEFAULT_COLOURS, - setColour: (mode, status, slot, value) => - set(s => ({ - colours: { - ...s.colours, - [mode]: { - ...s.colours[mode], - [status]: { - ...s.colours[mode][status], - [slot]: value, - }, - }, - }, - })), - resetAll: () => set({ colours: DEFAULT_COLOURS }), - }), - { name: 'pos-table-colours-v2' } -)) - -export default useTableColourStore +export const QUICK_SWATCHES = { + cardBg: ['#dde5ef', '#243044', '#FF8F60', '#e8610a', '#FFDC67', '#81D264', '#a78bfa', '#38bdf8', '#f43f5e', '#1e293b'], + cardBg2: ['rgba(0,0,0,0)', '#ffffff', '#dde5ef', '#243044', '#FF8F60', '#e8610a', '#22c55e', '#3b82f6'], + badgeBg: ['rgba(255,255,255,0.92)', 'rgba(0,0,0,0.55)', 'rgba(255,255,255,0.6)', 'rgba(30,41,59,0.85)', '#ffffff', '#000000'], + badgeBg2: ['rgba(0,0,0,0)', 'rgba(255,255,255,0.92)', 'rgba(0,0,0,0.55)', '#ffffff', '#000000'], + nameText: ['#ffffff', '#1e293b', '#3d5270', '#94b8d4', '#f8fafc', '#111827', '#fef3c7', '#dcfce7'], + nameText2: ['rgba(0,0,0,0)', '#ffffff', '#1e293b', '#3d5270', '#94b8d4', '#15803d', '#bbf7d0'], + badgeText: ['#3d5270', '#94b8d4', '#e8610a', '#FF8F60', '#FFDC67', '#d4a800', '#81D264', '#ffffff', '#1e293b'], + badgeText2: ['rgba(0,0,0,0)', '#3d5270', '#94b8d4', '#15803d', '#bbf7d0', '#22c55e', '#ffffff'], +} diff --git a/manager_dashboard/src/pages/Settings/tabs/AppInfoTab.jsx b/manager_dashboard/src/pages/Settings/tabs/AppInfoTab.jsx deleted file mode 100644 index e5884ac..0000000 --- a/manager_dashboard/src/pages/Settings/tabs/AppInfoTab.jsx +++ /dev/null @@ -1,600 +0,0 @@ -import { useState } from 'react' -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import toast from 'react-hot-toast' -import { QRCodeSVG } from 'qrcode.react' -import client from '../../../api/client' -import useAuthStore from '../../../store/authStore' - -const COMMON_TIMEZONES = [ - 'Europe/Athens', 'Europe/London', 'Europe/Berlin', 'Europe/Paris', 'Europe/Rome', - 'Europe/Madrid', 'Europe/Amsterdam', 'Europe/Brussels', 'Europe/Bucharest', - 'Europe/Helsinki', 'Europe/Istanbul', 'America/New_York', 'America/Chicago', - 'America/Denver', 'America/Los_Angeles', 'UTC', -] - -function TimezoneSection() { - const qc = useQueryClient() - const { data: settings, isLoading } = useQuery({ - queryKey: ['pos-settings'], - queryFn: () => client.get('/api/settings/').then(r => r.data), - staleTime: 30_000, - }) - const updateMut = useMutation({ - mutationFn: ({ key, value }) => client.put(`/api/settings/${key}`, { value }), - onSuccess: () => { toast.success('Αποθηκεύτηκε'); qc.invalidateQueries({ queryKey: ['pos-settings'] }) }, - onError: () => toast.error('Σφάλμα αποθήκευσης'), - }) - const currentTz = settings?.['venue.timezone']?.value ?? 'Europe/Athens' - const browserTz = Intl.DateTimeFormat().resolvedOptions().timeZone - return ( -
-
-

Ζώνη Ώρας

-

- Η ζώνη ώρας που χρησιμοποιεί το backend για χρονοσφραγίδες. Αν οι ώρες έναρξης βάρδιας εμφανίζονται λανθασμένες, ρυθμίστε αυτό να ταιριάζει με την τοπική σας ζώνη. -

-
- {isLoading &&

Φόρτωση…

} - {!isLoading && ( -
-
- - {updateMut.isPending && Αποθήκευση…} -
-

- Ζώνη ώρας browser: {browserTz} - {browserTz !== currentTz && ( - ⚠ Διαφέρει από τη ρύθμιση backend - )} -

-

- Η αλλαγή ζώνης ώρας αποθηκεύεται και εφαρμόζεται στο frontend αμέσως. Για πλήρη εφαρμογή στον backend server (χρονοσφραγίδες), απαιτείται επανεκκίνηση του container. -

-
- )} -
- ) -} - - -function StatsSection() { - const { data: stats, isLoading } = useQuery({ - queryKey: ['system-stats'], - queryFn: () => client.get('/api/system/stats').then(r => r.data), - staleTime: 60_000, - }) - - const rows = [ - { label: 'Κατηγορίες', value: stats?.categories }, - { label: 'Προϊόντα (ενεργά)', value: stats?.products }, - { label: 'Τραπέζια (ενεργά)', value: stats?.tables }, - { label: 'Ζώνες Τραπεζιών', value: stats?.table_groups }, - { label: 'Managers', value: stats?.managers }, - { label: 'Σερβιτόροι', value: stats?.waiters }, - ] - - return ( -
-

Στατιστικά Συστήματος

- {isLoading &&

Φόρτωση…

} - {!isLoading && ( -
- {rows.map(({ label, value }) => ( - <> -
{label}
-
{value ?? '—'}
- - ))} -
- )} -
- ) -} - - -function DoubleConfirmImport({ isOpen, onClose, onConfirm, title, summary, isPending }) { - const [step, setStep] = useState(1) - - function handleClose() { - setStep(1) - onClose() - } - - function handleFirst() { - setStep(2) - } - - async function handleFinal() { - await onConfirm() - setStep(1) - } - - if (!isOpen) return null - - return ( -
- {step === 1 && ( -
-

Επιβεβαίωση Εισαγωγής

-

{summary}

-

Τα υπάρχοντα δεδομένα θα συγχωνευτούν — δεν θα διαγραφεί τίποτα.

-
- - -
-
- )} - {step === 2 && ( -
-

⚠️ ΤΕΛΕΥΤΑΙΑ ΠΡΟΕΙΔΟΠΟΙΗΣΗ

-

{title}

-

- Αυτή η ενέργεια δεν αναιρείται. Η βάση δεδομένων θα τροποποιηθεί μόνιμα. - Είστε απολύτως σίγουροι; -

-
- - -
-
- )} -
- ) -} - - -function DataTransferSection() { - const qc = useQueryClient() - const [catalogModal, setCatalogModal] = useState(false) - const [tablesModal, setTablesModal] = useState(false) - const [catalogPayload, setCatalogPayload] = useState(null) - const [tablesPayload, setTablesPayload] = useState(null) - const [catalogSummary, setCatalogSummary] = useState('') - const [tablesSummary, setTablesSummary] = useState('') - - const catalogImportMut = useMutation({ - mutationFn: (payload) => client.post('/api/data-transfer/import/catalog', payload).then(r => r.data), - onSuccess: () => { - toast.success('Κατάλογος εισήχθη επιτυχώς') - setCatalogModal(false) - setCatalogPayload(null) - qc.invalidateQueries({ queryKey: ['system-stats'] }) - qc.invalidateQueries({ queryKey: ['products'] }) - qc.invalidateQueries({ queryKey: ['categories'] }) - }, - onError: (err) => toast.error(err?.response?.data?.detail ?? 'Σφάλμα εισαγωγής'), - }) - - const tablesImportMut = useMutation({ - mutationFn: (payload) => client.post('/api/data-transfer/import/tables', payload).then(r => r.data), - onSuccess: () => { - toast.success('Τραπέζια εισήχθησαν επιτυχώς') - setTablesModal(false) - setTablesPayload(null) - qc.invalidateQueries({ queryKey: ['system-stats'] }) - qc.invalidateQueries({ queryKey: ['tables'] }) - }, - onError: (err) => toast.error(err?.response?.data?.detail ?? 'Σφάλμα εισαγωγής'), - }) - - function handleExport(bundle) { - client.get(`/api/data-transfer/export/${bundle}`, { responseType: 'blob' }) - .then(res => { - const disposition = res.headers['content-disposition'] ?? '' - const match = disposition.match(/filename="([^"]+)"/) - const filename = match ? match[1] : `xenia-${bundle}.json` - const url = URL.createObjectURL(res.data) - const a = document.createElement('a') - a.href = url - a.download = filename - a.click() - URL.revokeObjectURL(url) - }) - .catch(() => toast.error('Σφάλμα εξαγωγής')) - } - - function handleFileSelect(bundle, e) { - const file = e.target.files?.[0] - e.target.value = '' - if (!file) return - const reader = new FileReader() - reader.onload = (ev) => { - try { - const parsed = JSON.parse(ev.target.result) - if (parsed.bundle !== bundle) { - toast.error(`Λάθος αρχείο. Αναμένεται αρχείο τύπου '${bundle}'.`) - return - } - if (bundle === 'catalog') { - const cats = parsed.data?.categories ?? [] - const orphans = parsed.data?.uncategorized_products ?? [] - const prodCount = cats.reduce((acc, c) => acc + (c.products?.length ?? 0), 0) + orphans.length - setCatalogSummary(`Πρόκειται να εισαγάγετε ${cats.length} κατηγορίες και ${prodCount} προϊόντα.`) - setCatalogPayload(parsed) - setCatalogModal(true) - } else { - const groups = parsed.data?.table_groups ?? [] - const ungrouped = parsed.data?.ungrouped_tables ?? [] - const tableCount = groups.reduce((acc, g) => acc + (g.tables?.length ?? 0), 0) + ungrouped.length - setTablesSummary(`Πρόκειται να εισαγάγετε ${groups.length} ζώνες και ${tableCount} τραπέζια.`) - setTablesPayload(parsed) - setTablesModal(true) - } - } catch { - toast.error('Μη έγκυρο αρχείο JSON') - } - } - reader.readAsText(file) - } - - return ( -
-
-

Εισαγωγή / Εξαγωγή Δεδομένων

-

- Εξάγετε τα δεδομένα σας σε αρχείο ή εισάγετε δεδομένα από άλλη εγκατάσταση. -

-
- -
-
-

Κατάλογος Προϊόντων

-

Κατηγορίες + Προϊόντα (χωρίς εκτυπωτές)

-
-
- - -
-
- -
-
-

Τραπέζια & Ζώνες

-

Ζώνες τραπεζιών + Τραπέζια

-
-
- - -
-
- - { setCatalogModal(false); setCatalogPayload(null) }} - onConfirm={() => catalogImportMut.mutateAsync(catalogPayload)} - title="Εισαγωγή Καταλόγου Προϊόντων" - summary={catalogSummary} - isPending={catalogImportMut.isPending} - /> - { setTablesModal(false); setTablesPayload(null) }} - onConfirm={() => tablesImportMut.mutateAsync(tablesPayload)} - title="Εισαγωγή Τραπεζιών & Ζωνών" - summary={tablesSummary} - isPending={tablesImportMut.isPending} - /> -
- ) -} - - -function QRModal({ url, caption = 'Σαρώστε με το κινητό για σύνδεση στο σύστημα.', onClose }) { - return ( -
-
e.stopPropagation()} - > -

QR Σύνδεσης

-

{url}

-
- -
-

{caption}

- -
-
- ) -} - -const IPV4 = /^\d{1,3}(\.\d{1,3}){3}$/ - -// Address phones use on the LAN. The server resolves it (manual override → -// live detection → HOST_IP, see local_backend/services/lan_ip.py); if it knows -// nothing and this dashboard was itself opened by IP, that IP is the server. -function resolveLanIp(status) { - if (status?.lan_ip) return { ip: status.lan_ip, source: status.lan_ip_info?.source ?? 'env' } - const host = window.location.hostname - return IPV4.test(host) && !host.startsWith('127.') ? { ip: host, source: 'browser' } : { ip: null, source: null } -} - -const LAN_SOURCE_LABEL = { - override: 'Χειροκίνητη ρύθμιση', - detected: 'Αυτόματη ανίχνευση', - env: 'Από το .env (HOST_IP)', - browser: 'Από τη διεύθυνση του browser', -} - -const DETECTION_NOTE = { - unsupported: 'Η αυτόματη ανίχνευση λειτουργεί μόνο σε Linux server (όχι σε Docker Desktop).', - stale: 'Η αυτόματη ανίχνευση σταμάτησε να ενημερώνεται — ελέγξτε το container netinfo.', - unavailable: 'Η αυτόματη ανίχνευση δεν είναι διαθέσιμη (το container netinfo δεν τρέχει).', -} - -const SMALL_BTN = 'flex items-center gap-1 h-6 px-2 rounded-md border border-gray-300 bg-white text-gray-600 text-xs font-medium hover:bg-gray-50 transition-colors flex-shrink-0 disabled:opacity-50' - -function LanAccessSection({ status, onShowQr }) { - const qc = useQueryClient() - const info = status?.lan_ip_info - const { ip, source } = resolveLanIp(status) - const [editing, setEditing] = useState(false) - const [value, setValue] = useState('') - - const saveMut = useMutation({ - mutationFn: newIp => client.put('/api/system/lan-ip-override', { ip: newIp }).then(r => r.data), - onSuccess: (_, newIp) => { - toast.success(newIp ? 'Η IP αποθηκεύτηκε' : 'Επαναφορά σε αυτόματη ανίχνευση') - setEditing(false) - qc.invalidateQueries({ queryKey: ['system-status'] }) - }, - onError: err => toast.error(err.response?.data?.detail || 'Αποτυχία αποθήκευσης'), - }) - - function startEdit() { - setValue(info?.override || ip || '') - setEditing(true) - } - - return ( -
-

Τοπικό δίκτυο

- - {info?.mismatch && ( -
-

- Χρησιμοποιείται η IP {ip}, όμως ο server έχει τώρα - την {info.detected}. Τα κινητά και το QR δεν θα - συνδέονται μέχρι να διορθωθεί. -

- -
- )} - -
-
IP server
-
- {editing ? ( -
- setValue(e.target.value)} - onKeyDown={e => e.key === 'Enter' && value.trim() && saveMut.mutate(value.trim())} - placeholder={info?.detected || '192.168.1.50'} - className="input h-7 text-xs font-mono w-36" - autoFocus - /> - - {info?.override && ( - - )} - -
- ) : ( -
- {ip ?? '—'} - {source && ( - {LAN_SOURCE_LABEL[source]} - )} - -
- )} - {!editing && info && info.detection !== 'ok' && ( -

{DETECTION_NOTE[info.detection]}

- )} - {!ip && !editing && ( -

- Άγνωστη IP — ορίστε την εδώ (π.χ. 192.168.1.50) ή HOST_IP στο .env. -

- )} -
- - {ip && ( - <> -
Σερβιτόροι (WiFi)
-
- http://{ip} - -
-
Διαχείριση (WiFi)
-
http://{ip}/manager
- - )} -
-
- ) -} - -// Pairing URL: opens the waiter app when scanned with the phone camera, and the -// native app reads the same code (?pair=) to pair with this venue. -// k = the server's TLS public-key pin: the app refuses a server whose key -// differs, then talks to it encrypted on :8443 (plan step 7). -function waiterPairUrl(lanIp, siteId, spki) { - const params = new URLSearchParams() - if (siteId) params.set('pair', siteId) - if (siteId && spki) params.set('k', spki) - const query = params.toString() - return `http://${lanIp}/` + (query ? `?${query}` : '') -} - -function formatUptime(seconds) { - const h = Math.floor(seconds / 3600) - const m = Math.floor((seconds % 3600) / 60) - const s = seconds % 60 - return `${h}ω ${m}λ ${s}δ` -} - -export default function AppInfoTab() { - const user = useAuthStore(s => s.user) - const qc = useQueryClient() - const [refreshing, setRefreshing] = useState(false) - const [qr, setQr] = useState(null) // { url, caption } | null - const { data: status, isLoading } = useQuery({ - queryKey: ['system-status'], - queryFn: () => client.get('/api/system/status').then(r => r.data), - refetchInterval: 30_000, - }) - - async function handleRefresh() { - setRefreshing(true) - try { - await client.post('/api/system/sync-license') - await Promise.all([ - qc.invalidateQueries({ queryKey: ['system-status'] }), - qc.invalidateQueries({ queryKey: ['license-status'] }), - ]) - } catch { - // sync-license failure just means cloud was unreachable — still refresh local caches - await Promise.all([ - qc.invalidateQueries({ queryKey: ['system-status'] }), - qc.invalidateQueries({ queryKey: ['license-status'] }), - ]) - } finally { - setRefreshing(false) - } - } - - if (isLoading) return
Φόρτωση…
- return ( -
- {/* System info */} -
-
-

Σύστημα

- -
-
-
Uptime
-
{formatUptime(status?.uptime_seconds ?? 0)}
-
Έκδοση
-
- {status?.version ?? '—'} - {status?.latest_version && status.latest_version !== status.version && ( - - Διαθέσιμη {status.latest_version} - - )} - {status?.latest_version && status.latest_version === status.version && ( - - Ενημερωμένο - - )} -
-
Άδεια χρήσης
-
- {status?.licensed ? 'Ενεργή' : 'Ανενεργή'} -
-
Κατάσταση
-
- {status?.locked ? 'Κλειδωμένο' - : status?.lock_pending ? 'Εκκρεμεί Κλείδωμα' - : 'Λειτουργικό'} -
- {status?.expires_at && ( - <> -
Λήξη άδειας
-
{new Date(status.expires_at).toLocaleDateString('el-GR')}
- - )} - {status?.waiter_domain && ( - <> - {/* Retired per-client domain setup (plan step 9): shown only for sites that still have one */} -
Waiter Domain (παλιό σύστημα)
-
- {status.waiter_domain} - -
- - )} -
-
- - - - - - - - - - {user?.role === 'superadmin' && ( -
-

Sysadmin

-

Έλεγχος κλειδώματος συστήματος.

-
- - -
-
- )} - - {qr && setQr(null)} />} -
- ) -} diff --git a/manager_dashboard/src/pages/Settings/tabs/ColoursTab.jsx b/manager_dashboard/src/pages/Settings/tabs/ColoursTab.jsx deleted file mode 100644 index 49bccd6..0000000 --- a/manager_dashboard/src/pages/Settings/tabs/ColoursTab.jsx +++ /dev/null @@ -1,599 +0,0 @@ -import { useState, useEffect, useCallback, useRef } from 'react' -import { DEFAULT_COLOURS } from '../../../store/tableColourStore' -import client from '../../../api/client' -import toast from 'react-hot-toast' - -// ─── Colour slot metadata ──────────────────────────────────────────────────── - -const SLOTS = [ - { key: 'cardBg', key2: 'cardBg2', label: 'Κύριο Φόντο', hint: 'Φόντο κάρτας' }, - { key: 'badgeBg', key2: 'badgeBg2', label: 'Δευτερεύον Φόντο', hint: 'Φόντο badge κατάστασης' }, - { key: 'nameText', key2: 'nameText2', label: 'Κύριο Κείμενο', hint: 'Όνομα τραπεζιού' }, - { key: 'badgeText', key2: 'badgeText2', label: 'Δευτερεύον Κείμενο', hint: 'Ετικέτα badge' }, -] - -function useFlashToggle(active, ms = 700) { - const [frame, setFrame] = useState(false) - useEffect(() => { - if (!active) { setFrame(false); return } - const id = setInterval(() => setFrame(f => !f), ms) - return () => clearInterval(id) - }, [active, ms]) - return frame -} - -const STATUSES = [ - { key: 'free', label: 'Ελεύθερο' }, - { key: 'open', label: 'Ανοιχτό (όχι δικό μου)' }, - { key: 'mine', label: 'Ανοιχτό (δικό μου)' }, - { key: 'partially_paid', label: 'Μερικώς Πληρωμένο' }, - { key: 'paid', label: 'Πληρωμένο' }, - { key: 'kds_ready', label: 'Έτοιμο για Παράδοση (KDS)', hasFlash: true }, -] - -const STATUS_LABELS_MOCK = { - free: 'ΕΛΕΥΘΕΡΟ', - open: 'ΑΝΟΙΧΤΟ', - mine: 'ΔΙΚΟ ΜΟΥ', - partially_paid: 'ΜΕΡ. ΠΛHΡ.', - paid: 'ΠΛΗΡΩΜΕΝΟ', - kds_ready: 'READY', -} - -// Quick-suggest palettes per slot type -const QUICK_SWATCHES = { - cardBg: ['#dde5ef', '#243044', '#FF8F60', '#e8610a', '#FFDC67', '#81D264', '#a78bfa', '#38bdf8', '#f43f5e', '#1e293b'], - cardBg2: ['rgba(0,0,0,0)', '#ffffff', '#dde5ef', '#243044', '#FF8F60', '#e8610a', '#22c55e', '#3b82f6'], - badgeBg: ['rgba(255,255,255,0.92)', 'rgba(0,0,0,0.55)', 'rgba(255,255,255,0.6)', 'rgba(30,41,59,0.85)', '#ffffff', '#000000'], - badgeBg2: ['rgba(0,0,0,0)', 'rgba(255,255,255,0.92)', 'rgba(0,0,0,0.55)', '#ffffff', '#000000'], - nameText: ['#ffffff', '#1e293b', '#3d5270', '#94b8d4', '#f8fafc', '#111827', '#fef3c7', '#dcfce7'], - nameText2: ['rgba(0,0,0,0)', '#ffffff', '#1e293b', '#3d5270', '#94b8d4', '#15803d', '#bbf7d0'], - badgeText: ['#3d5270', '#94b8d4', '#e8610a', '#FF8F60', '#FFDC67', '#d4a800', '#81D264', '#ffffff', '#1e293b'], - badgeText2: ['rgba(0,0,0,0)', '#3d5270', '#94b8d4', '#15803d', '#bbf7d0', '#22c55e', '#ffffff'], -} - -// ─── Color picker modal ────────────────────────────────────────────────────── - -// Parse any css colour string into { hex, alpha }. -// Handles: #rrggbb, #rgb, rgba(r,g,b,a), rgb(r,g,b) -function parseColour(v) { - if (!v) return { hex: '#ffffff', alpha: 1 } - const s = v.trim() - // rgba / rgb - const rgbaMatch = s.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/) - if (rgbaMatch) { - const r = parseInt(rgbaMatch[1]).toString(16).padStart(2, '0') - const g = parseInt(rgbaMatch[2]).toString(16).padStart(2, '0') - const b = parseInt(rgbaMatch[3]).toString(16).padStart(2, '0') - const a = rgbaMatch[4] != null ? parseFloat(rgbaMatch[4]) : 1 - return { hex: `#${r}${g}${b}`, alpha: Math.min(1, Math.max(0, a)) } - } - // #rgb shorthand - if (/^#[0-9a-fA-F]{3}$/.test(s)) { - const [, r, g, b] = s - return { hex: `#${r}${r}${g}${g}${b}${b}`, alpha: 1 } - } - // #rrggbb - if (/^#[0-9a-fA-F]{6}$/.test(s)) return { hex: s, alpha: 1 } - return { hex: '#ffffff', alpha: 1 } -} - -function buildColour(hex, alpha) { - if (alpha >= 1) return hex - const r = parseInt(hex.slice(1, 3), 16) - const g = parseInt(hex.slice(3, 5), 16) - const b = parseInt(hex.slice(5, 7), 16) - return `rgba(${r},${g},${b},${alpha.toFixed(2)})` -} - -function ColourPickerModal({ value, onClose, onChange, slot }) { - const parsed = parseColour(value) - const [hex, setHex] = useState(parsed.hex) - const [alpha, setAlpha] = useState(parsed.alpha) - - // keep parent in sync whenever hex or alpha changes - useEffect(() => { onChange(buildColour(hex, alpha)) }, [hex, alpha]) - - function commitSwatch(v) { - const p = parseColour(v) - setHex(p.hex) - setAlpha(p.alpha) - } - - const preview = buildColour(hex, alpha) - - return ( -
-
e.stopPropagation()} - > -
-
-
Επιλογή Χρώματος
-
- {SLOTS.find(s => s.key === slot)?.label || (SLOTS.find(s => s.key2 === slot)?.label + ' (χρώμα 2)')} -
-
- -
- - {/* Preview swatch — checkerboard behind so alpha is visible */} -
-
0.5 ? '#fff' : '#374151', - textShadow: alpha > 0.5 ? '0 1px 3px rgba(0,0,0,0.5)' : 'none', - }}> - {preview} -
-
- - {/* Colour picker + hex input */} -
-
Χρώμα
-
- setHex(e.target.value)} - style={{ width: 48, height: 40, borderRadius: 8, border: '1px solid #e5e7eb', cursor: 'pointer', padding: 2, flexShrink: 0 }} - /> - { - const v = e.target.value - setHex(v) - }} - spellCheck={false} - style={{ - flex: 1, height: 40, borderRadius: 8, border: '1px solid #e5e7eb', - padding: '0 12px', fontSize: 13, fontFamily: 'monospace', color: '#111827', - }} - /> -
-
- - {/* Opacity slider — always visible */} -
-
-
Διαφάνεια
-
{Math.round(alpha * 100)}%
-
- {/* Gradient track so you can see what you're dragging */} -
- setAlpha(parseFloat(e.target.value))} - style={{ - position: 'absolute', inset: 0, width: '100%', height: '100%', - opacity: 0, cursor: 'pointer', margin: 0, - }} - /> - {/* thumb indicator */} -
-
-
- - {/* Quick swatches */} -
-
Γρήγορη επιλογή
-
- {(QUICK_SWATCHES[slot] || []).map(c => { - const p = parseColour(c) - const built = buildColour(p.hex, p.alpha) - return ( - - ) - })} -
-
- -
- -
-
-
- ) -} - -// ─── Single colour slot row ────────────────────────────────────────────────── - -function ColourSlotRow({ mode, status, slotKey, label, value, onOpen }) { - return ( -
-
- ) -} - -// ─── Mini mock table card (for preview) ────────────────────────────────────── - -function MockCard({ cfg, label, mockName, groupName = 'ΜΕΣΑ', flashFrame = false }) { - return ( -
- {/* Table name + group */} -
- {mockName} - {groupName} -
- {/* Status badge */} -
- - {label} - -
-
- ) -} - -// ─── Preview panel (6 mock cards per theme) ────────────────────────────────── - -function PreviewPanel({ colours, mode }) { - const isDark = mode === 'dark' - const panelBg = isDark ? '#0d1520' : '#f1f5f9' - const panelLabel = isDark ? '🌙 Προεπισκόπηση σκοτεινού θέματος' : '☀️ Προεπισκόπηση φωτεινού θέματος' - const labelCol = isDark ? '#94a3b8' : '#64748b' - - const mockCards = [ - { status: 'free', name: 'TABLE 1', group: 'ΜΕΣΑ' }, - { status: 'open', name: 'TABLE 2', group: 'ΜΕΣΑ' }, - { status: 'mine', name: 'TABLE 3', group: 'ΜΕΣΑ' }, - { status: 'partially_paid', name: 'TABLE 4', group: 'ΞΑΠΛΩΣΤΡΕΣ' }, - { status: 'paid', name: 'TABLE 5', group: 'ΞΑΠΛΩΣΤΡΕΣ' }, - { status: 'free', name: 'TABLE 6', group: 'ΞΑΠΛΩΣΤΡΕΣ' }, - ] - - return ( -
-
- {panelLabel} -
-
- {mockCards.map((mc, i) => ( - - ))} -
-
- ) -} - -// ─── Status block (one status, showing all 4 slots) ────────────────────────── - -function StatusBlock({ mode, status, label, hasFlash, colours, onOpen, onSetFlash }) { - const cfg = colours[mode][status] - const flashFrame = useFlashToggle(hasFlash && !!cfg.flash) - return ( -
-
-
- -
-
-
{label}
-
Πατήστε ένα χρώμα για επεξεργασία
- {hasFlash && ( -
-
onSetFlash(mode, !cfg.flash)} - style={{ - width: 36, height: 20, borderRadius: 10, - background: cfg.flash ? '#22c55e' : '#d1d5db', - position: 'relative', cursor: 'pointer', transition: 'background 0.2s', - flexShrink: 0, - }} - > -
-
- - Αναλαμπή (Flashing) - -
- )} -
-
-
- {SLOTS.map(slot => ( -
- - {hasFlash && cfg.flash && slot.key2 && ( -
-
-
-
-
- )} -
- ))} -
-
- ) -} - -// ─── Mode section (light or dark) ──────────────────────────────────────────── - -function ModeSection({ mode, colours, onOpen, onSetFlash }) { - const label = mode === 'light' ? '☀️ Φωτεινό θέμα' : '🌙 Σκοτεινό θέμα' - return ( -
-
{label}
-
- {STATUSES.map(s => ( - - ))} -
-
- ) -} - -// ─── Main tab ──────────────────────────────────────────────────────────────── - -export default function ColoursTab() { - const [colours, setColours] = useState(DEFAULT_COLOURS) - const [modal, setModal] = useState(null) // { mode, status, slot, value } - const [saving, setSaving] = useState(false) - const saveTimer = useRef(null) - - // Load from backend on mount - useEffect(() => { - client.get('/api/settings/').then(r => { - const raw = r.data?.['ui.table_colours']?.value - if (raw) { - try { - const loaded = JSON.parse(raw) - // Deep-merge with defaults so any missing statuses/slots are backfilled - const merged = { light: {}, dark: {} } - for (const mode of ['light', 'dark']) { - for (const [status, defaults] of Object.entries(DEFAULT_COLOURS[mode])) { - merged[mode][status] = { ...defaults, ...(loaded[mode]?.[status] ?? {}) } - } - } - setColours(merged) - } catch {} - } - }) - }, []) - - // Debounced save to backend — 600 ms after last change - const saveToBackend = useCallback((next) => { - clearTimeout(saveTimer.current) - setSaving(true) - saveTimer.current = setTimeout(() => { - client.put('/api/settings/ui.table_colours', { value: JSON.stringify(next) }) - .then(() => setSaving(false)) - .catch(() => { toast.error('Σφάλμα αποθήκευσης χρωμάτων'); setSaving(false) }) - }, 600) - }, []) - - function setColour(mode, status, slot, value) { - setColours(prev => { - const next = { - ...prev, - [mode]: { - ...prev[mode], - [status]: { ...prev[mode][status], [slot]: value }, - }, - } - saveToBackend(next) - return next - }) - } - - function setFlash(mode, value) { - setColours(prev => { - const next = { - ...prev, - [mode]: { - ...prev[mode], - kds_ready: { ...prev[mode].kds_ready, flash: value }, - }, - } - saveToBackend(next) - return next - }) - } - - function openModal(mode, status, slot, value) { - setModal({ mode, status, slot, value }) - } - - function handleChange(value) { - setColour(modal.mode, modal.status, modal.slot, value) - setModal(m => ({ ...m, value })) - } - - function handleReset() { - if (window.confirm('Επαναφορά όλων των χρωμάτων στις προεπιλογές; Δεν μπορεί να αναιρεθεί.')) { - setColours(DEFAULT_COLOURS) - saveToBackend(DEFAULT_COLOURS) - } - } - - return ( -
-
- {saving &&

Αποθήκευση…

} - - {/* Live previews side by side */} -
- - -
- - {/* Light + Dark mode settings */} -
- - -
-
- - {/* Reset all button at bottom */} -
- -
- - {/* Colour picker modal */} - {modal && ( - setModal(null)} - onChange={handleChange} - /> - )} -
- ) -} diff --git a/manager_dashboard/src/pages/Settings/tabs/DevelopmentTab.jsx b/manager_dashboard/src/pages/Settings/tabs/DevelopmentTab.jsx deleted file mode 100644 index 69bf65d..0000000 --- a/manager_dashboard/src/pages/Settings/tabs/DevelopmentTab.jsx +++ /dev/null @@ -1,74 +0,0 @@ -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import toast from 'react-hot-toast' -import client from '../../../api/client' - -function Toggle({ checked, onChange, disabled }) { - return ( - - ) -} - -export default function DevelopmentTab() { - const qc = useQueryClient() - - const { data: settings, isLoading } = useQuery({ - queryKey: ['settings'], - queryFn: () => client.get('/api/settings/').then(r => r.data), - }) - - const mutation = useMutation({ - mutationFn: ({ key, value }) => client.put(`/api/settings/${key}`, { value }), - onSuccess: () => { qc.invalidateQueries({ queryKey: ['settings'] }) }, - onError: () => toast.error('Σφάλμα αποθήκευσης'), - }) - - const spoofOn = settings?.['dev.spoof_printing']?.value === 'true' - - function toggleSpoof(val) { - mutation.mutate({ key: 'dev.spoof_printing', value: val ? 'true' : 'false' }) - toast.success(val ? 'Spoof mode ενεργό — εκτυπωτές σιωπηλοί' : 'Spoof mode ανενεργό — εκτυπωτές ενεργοί') - } - - if (isLoading) return
Φόρτωση…
- - return ( -
-
- Αυτές οι ρυθμίσεις προορίζονται μόνο για δοκιμές. Μην τις αφήνετε ενεργές σε παραγωγικό περιβάλλον. -
- -
-
-
-

Spoof Printer Mode

-

- Όλες οι εκτυπώσεις απορρίπτονται αθόρυβα. Οι συσκευές συμπεριφέρονται σαν η εκτύπωση να πέτυχε. -

-
- -
-
- - {spoofOn && ( -
- Spoof mode ενεργό — οι εκτυπωτές είναι σιωπηλοί. -
- )} -
- ) -} diff --git a/manager_dashboard/src/pages/Settings/tabs/FiscalTab.jsx b/manager_dashboard/src/pages/Settings/tabs/FiscalTab.jsx deleted file mode 100644 index 652d55e..0000000 --- a/manager_dashboard/src/pages/Settings/tabs/FiscalTab.jsx +++ /dev/null @@ -1,383 +0,0 @@ -import { useState, useEffect } from 'react' -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import toast from 'react-hot-toast' -import client from '../../../api/client' - -// ── Helpers ─────────────────────────────────────────────────────────────────── - -function Toggle({ checked, onChange, disabled = false }) { - return ( - - ) -} - -function SectionTitle({ children }) { - return ( -

- {children} -

- ) -} - -function SettingRow({ label, hint, children }) { - return ( -
-
-

{label}

- {hint &&

{hint}

} -
-
{children}
-
- ) -} - -// ── Main Component ──────────────────────────────────────────────────────────── - -export default function FiscalTab() { - const queryClient = useQueryClient() - const { data: settings, isLoading } = useQuery({ - queryKey: ['pos-settings'], - queryFn: () => client.get('/api/settings/').then(r => r.data), - staleTime: 30_000, - }) - - const val = (key) => settings?.[key]?.value ?? '' - - // Local state for folder paths (to show test result without saving first) - const [outFolder, setOutFolder] = useState('') - const [inFolder, setInFolder] = useState('') - const [testResult, setTestResult] = useState(null) - const [testing, setTesting] = useState(false) - - // VAT groups state (parsed from JSON setting) - const [vatGroups, setVatGroups] = useState([]) - // End message lines - const [endLines, setEndLines] = useState(['', '', '', '', '']) - - useEffect(() => { - if (!settings) return - setOutFolder(val('fiscal.out_folder')) - setInFolder(val('fiscal.in_folder')) - try { - const groups = JSON.parse(val('fiscal.vat_groups') || '[]') - setVatGroups(Array.isArray(groups) ? groups : []) - } catch { setVatGroups([]) } - try { - const lines = JSON.parse(val('fiscal.end_message') || '[]') - const padded = [...lines, '', '', '', '', ''].slice(0, 5) - setEndLines(padded) - } catch { setEndLines(['', '', '', '', '']) } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [settings]) - - const saveSetting = useMutation({ - mutationFn: ({ key, value }) => client.put(`/api/settings/${key}`, { value }), - onSuccess: () => queryClient.invalidateQueries({ queryKey: ['pos-settings'] }), - }) - - function save(key, value) { - saveSetting.mutate({ key, value }, { - onError: () => toast.error(`Αποτυχία αποθήκευσης ${key}`), - }) - } - - function saveAndToast(key, value, label) { - saveSetting.mutate({ key, value }, { - onSuccess: () => toast.success(`${label} αποθηκεύτηκε`), - onError: () => toast.error('Αποτυχία αποθήκευσης'), - }) - } - - async function testFolders() { - setTesting(true) - setTestResult(null) - try { - const res = await client.post('/api/fiscal/test-folders', { - out_folder: outFolder, - in_folder: inFolder, - }) - setTestResult(res.data) - } catch (e) { - setTestResult({ ok: false, out_folder_error: String(e), in_folder_error: null }) - } finally { - setTesting(false) - } - } - - function saveFolders() { - save('fiscal.out_folder', outFolder) - save('fiscal.in_folder', inFolder) - toast.success('Φάκελοι αποθηκεύτηκαν') - setTestResult(null) - } - - // VAT group helpers - function addVatGroup() { - setVatGroups(prev => [...prev, { machine_id: '', friendly_name: '' }]) - } - function removeVatGroup(i) { - setVatGroups(prev => prev.filter((_, idx) => idx !== i)) - } - function updateVatGroup(i, field, value) { - setVatGroups(prev => prev.map((g, idx) => idx === i ? { ...g, [field]: value } : g)) - } - function saveVatGroups() { - const cleaned = vatGroups - .filter(g => String(g.machine_id).trim() && g.friendly_name.trim()) - .map(g => ({ machine_id: parseInt(g.machine_id, 10), friendly_name: g.friendly_name.trim() })) - saveAndToast('fiscal.vat_groups', JSON.stringify(cleaned), 'Ομάδες ΦΠΑ') - } - - // End message helpers - function updateEndLine(i, value) { - setEndLines(prev => prev.map((l, idx) => idx === i ? value : l)) - } - function saveEndMessage() { - const cleaned = endLines.map(l => l.trim()) - saveAndToast('fiscal.end_message', JSON.stringify(cleaned), 'Μήνυμα τέλους') - } - - if (isLoading) return
Φόρτωση…
- - const fiscalEnabled = val('fiscal.enabled') === 'true' - - return ( -
- - {/* Master switch */} -
-
-
-

Φορολογική Εκτύπωση (ΦΗΜ)

-

- Ενεργοποιεί αυτόματη αποστολή αποδείξεων στη Φορολογική Μηχανή κατά την πληρωμή -

-
- save('fiscal.enabled', v ? 'true' : 'false')} - /> -
- - {fiscalEnabled && ( -
- Η ΦΗΜ είναι ενεργή. Κάθε πληρωμή στο PWA θα αποστέλλει αυτόματα απόδειξη. - Βεβαιωθείτε ότι οι φάκελοι και οι ομάδες ΦΠΑ είναι σωστά ρυθμισμένα. -
- )} -
- - {/* Driver type */} -
- Τύπος Προγράμματος Οδήγησης - - - -
- - {/* Folder paths */} -
- Φάκελοι Επικοινωνίας -

- Οι φάκελοι πρέπει να είναι προσβάσιμοι μέσα από το Docker container (mounted volume ή UNC path). -
- OUT folder = εκεί γράφει το Xenia (ο driver τα διαβάζει ως IN). -
- IN folder = εκεί γράφει ο driver τις απαντήσεις (το Xenia τις διαβάζει). -

- -
-
- - setOutFolder(e.target.value)} - /> -
-
- - setInFolder(e.target.value)} - /> -
-
- -
- - -
- - {testResult && ( -
- {testResult.ok ? ( - ✓ Και οι δύο φάκελοι είναι προσβάσιμοι - ) : ( -
- {testResult.out_folder_error &&
OUT: {testResult.out_folder_error}
} - {testResult.in_folder_error &&
IN: {testResult.in_folder_error}
} -
- )} -
- )} -
- - {/* Clerk / EFTPOS IDs */} -
- Ρυθμίσεις Εντολών - - save('fiscal.clerk_id', e.target.value)} - /> - - - save('fiscal.eftpos_id', e.target.value)} - /> - -
- - {/* End message */} -
- Μήνυμα Τέλους Απόδειξης (FM) -

- Μέχρι 5 γραμμές κειμένου που εκτυπώνονται στο τέλος κάθε απόδειξης. - Αφήστε κενές τις γραμμές που δεν θέλετε να χρησιμοποιήσετε. -

- {endLines.map((line, i) => ( -
- {i + 1} - updateEndLine(i, e.target.value)} - /> -
- ))} - -
- - {/* VAT Groups */} -
- Ομάδες ΦΠΑ ΦΗΜ -

- Ορίστε τις ομάδες ΦΠΑ όπως είναι προγραμματισμένες στη ΦΗΜ. - Το ID ΦΗΜ είναι ο αριθμός που χρησιμοποιεί η μηχανή (π.χ. 1, 2, 3…). - Θα χρησιμοποιηθούν κατά την ανάθεση σε προϊόντα. -

- - {vatGroups.length === 0 && ( -

Δεν έχουν οριστεί ομάδες ΦΠΑ ακόμα.

- )} - -
- {vatGroups.map((g, i) => ( -
-
- ID ΦΗΜ - updateVatGroup(i, 'machine_id', e.target.value)} - /> -
-
- Φιλικό όνομα - updateVatGroup(i, 'friendly_name', e.target.value)} - /> -
- -
- ))} -
- -
- - {vatGroups.length > 0 && ( - - )} -
-
- -
- ) -} diff --git a/manager_dashboard/src/pages/Settings/tabs/OperationTab.jsx b/manager_dashboard/src/pages/Settings/tabs/OperationTab.jsx deleted file mode 100644 index 560a5d2..0000000 --- a/manager_dashboard/src/pages/Settings/tabs/OperationTab.jsx +++ /dev/null @@ -1,744 +0,0 @@ -import { useState, useRef, useEffect } from 'react' -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import toast from 'react-hot-toast' -import client from '../../../api/client' -import RolePermissions from '../sections/RolePermissions' -import { useTranslation } from '@xenia/i18n' - -function Toggle({ checked, onChange, disabled }) { - return ( - - ) -} - -function SectionCard({ title, description, children, action }) { - return ( -
-
-
-

{title}

- {description &&

{description}

} -
- {action} -
- {children} -
- ) -} - -function OptionRow({ label, description, children }) { - return ( -
-
-

{label}

- {description &&

{description}

} -
-
{children}
-
- ) -} - -function ShiftSettingsSection() { - const qc = useQueryClient() - const { data: settings, isLoading } = useQuery({ - queryKey: ['pos-settings'], - queryFn: () => client.get('/api/settings/').then(r => r.data), - staleTime: 30_000, - }) - const updateMut = useMutation({ - mutationFn: ({ key, value }) => client.put(`/api/settings/${key}`, { value }), - onSuccess: () => { toast.success('Αποθηκεύτηκε'); qc.invalidateQueries({ queryKey: ['pos-settings'] }) }, - onError: () => toast.error('Σφάλμα αποθήκευσης'), - }) - function toggle(key, current) { - updateMut.mutate({ key, value: current === 'true' ? 'false' : 'true' }) - } - const selfStart = settings?.['shifts.waiter_self_start']?.value ?? 'true' - const selfEnd = settings?.['shifts.waiter_self_end']?.value ?? 'true' - const hideRevenue = settings?.['shifts.hide_revenue_from_waiters']?.value ?? 'false' - return ( - - {isLoading &&

Φόρτωση…

} - {!isLoading && ( - <> - - toggle('shifts.waiter_self_start', selfStart)} disabled={updateMut.isPending} /> - - - toggle('shifts.waiter_self_end', selfEnd)} disabled={updateMut.isPending} /> - - - toggle('shifts.hide_revenue_from_waiters', hideRevenue)} disabled={updateMut.isPending} /> - - - )} -
- ) -} - -function PaymentSettingsSection() { - const qc = useQueryClient() - const { data: settings, isLoading } = useQuery({ - queryKey: ['pos-settings'], - queryFn: () => client.get('/api/settings/').then(r => r.data), - staleTime: 30_000, - }) - const updateMut = useMutation({ - mutationFn: ({ key, value }) => client.put(`/api/settings/${key}`, { value }), - onSuccess: () => { toast.success('Αποθηκεύτηκε'); qc.invalidateQueries({ queryKey: ['pos-settings'] }) }, - onError: () => toast.error('Σφάλμα αποθήκευσης'), - }) - function toggle(key, current) { - updateMut.mutate({ key, value: current === 'true' ? 'false' : 'true' }) - } - const cardEnabled = settings?.['payments.card_enabled']?.value ?? 'false' - return ( - - {isLoading &&

Φόρτωση…

} - {!isLoading && ( - - toggle('payments.card_enabled', cardEnabled)} disabled={updateMut.isPending} /> - - )} -
- ) -} - -const COURSE_COLORS = ['#ef4444','#f97316','#eab308','#22c55e','#3b82f6','#8b5cf6','#ec4899','#06b6d4','#64748b','#10b981'] - -function CoursesSection({ settings, updateMut }) { - const coursesEnabled = settings?.['orders.courses_enabled']?.value === 'true' - const [courses, setCourses] = useState(() => { - try { return JSON.parse(settings?.['orders.courses']?.value || '[]') } - catch { return [] } - }) - - // Sync courses from settings when settings change (e.g. after save) - const settingsCoursesStr = settings?.['orders.courses']?.value - useEffect(() => { - try { setCourses(JSON.parse(settingsCoursesStr || '[]')) } - catch { setCourses([]) } - }, [settingsCoursesStr]) - - const dragItem = useRef(null) - const dragOverItem = useRef(null) - - function saveCourses(next) { - setCourses(next) - updateMut.mutate({ key: 'orders.courses', value: JSON.stringify(next) }) - } - - function addCourse() { - const newId = Math.max(...courses.map(c => c.id), 0) + 1 - const colorIdx = courses.length % COURSE_COLORS.length - saveCourses([...courses, { id: newId, name: `Course ${newId}`, color: COURSE_COLORS[colorIdx] }]) - } - - function deleteCourse(id) { - saveCourses(courses.filter(c => c.id !== id)) - } - - function updateName(id, name) { - saveCourses(courses.map(c => c.id === id ? { ...c, name } : c)) - } - - function cycleColor(id) { - saveCourses(courses.map(c => { - if (c.id !== id) return c - const idx = COURSE_COLORS.indexOf(c.color) - const next = COURSE_COLORS[(idx + 1) % COURSE_COLORS.length] - return { ...c, color: next } - })) - } - - function handleDragStart(e, idx) { - dragItem.current = idx - e.dataTransfer.effectAllowed = 'move' - } - - function handleDragOver(e, idx) { - e.preventDefault() - dragOverItem.current = idx - } - - function handleDrop() { - if (dragItem.current === null || dragOverItem.current === null) return - if (dragItem.current === dragOverItem.current) return - const next = [...courses] - const dragged = next.splice(dragItem.current, 1)[0] - next.splice(dragOverItem.current, 0, dragged) - dragItem.current = null - dragOverItem.current = null - saveCourses(next) - } - - const rowStyle = { display: 'flex', alignItems: 'center', gap: 8, padding: '8px 20px', borderBottom: '1px solid #f4f4f2' } - - return ( -
- {coursesEnabled && ( -
- {courses.map((course, idx) => ( -
handleDragStart(e, idx)} - onDragOver={e => handleDragOver(e, idx)} - onDrop={handleDrop} - style={{ ...rowStyle, cursor: 'grab' }} - > - {/* Drag handle */} - ⠿ - {/* Color swatch */} - -
- ))} -
- -
-
- )} -
- ) -} - -const DEFAULT_QUICK_NOTES = ['Χωρίς αλάτι', 'Βγάλτε γρήγορα', 'Αλλεργία!', 'Κόψτε σε μικρά κομμάτια', 'Έξτρα χαρτοπετσέτες'] - -function QuickNotesSection({ settings, updateMut }) { - const raw = settings?.['orders.quick_notes']?.value - const [notes, setNotes] = useState(() => { - try { return JSON.parse(raw || 'null') ?? DEFAULT_QUICK_NOTES } - catch { return DEFAULT_QUICK_NOTES } - }) - const [newNote, setNewNote] = useState('') - - const settingsRaw = settings?.['orders.quick_notes']?.value - useEffect(() => { - try { setNotes(JSON.parse(settingsRaw || 'null') ?? DEFAULT_QUICK_NOTES) } - catch { setNotes(DEFAULT_QUICK_NOTES) } - }, [settingsRaw]) - - function saveNotes(next) { - setNotes(next) - updateMut.mutate({ key: 'orders.quick_notes', value: JSON.stringify(next) }) - } - - function updateNote(idx, val) { - const next = notes.map((n, i) => i === idx ? val : n) - setNotes(next) - } - - function commitNote(idx) { - saveNotes(notes.map((n, i) => i === idx ? n.trim() : n).filter(n => n.length > 0)) - } - - function deleteNote(idx) { - saveNotes(notes.filter((_, i) => i !== idx)) - } - - function addNote() { - const trimmed = newNote.trim() - if (!trimmed) return - setNewNote('') - saveNotes([...notes, trimmed]) - } - - const rowStyle = { display: 'flex', alignItems: 'center', gap: 8, padding: '8px 20px', borderBottom: '1px solid #f4f4f2' } - - return ( -
-
- Quick Note Options -
- {notes.map((note, idx) => ( -
- updateNote(idx, e.target.value)} - onBlur={() => commitNote(idx)} - style={{ flex: 1, height: 32, borderRadius: 6, border: '1px solid #dfe2e6', padding: '0 10px', fontSize: 13, fontFamily: 'inherit' }} - /> - -
- ))} -
- setNewNote(e.target.value)} - onKeyDown={e => e.key === 'Enter' && addNote()} - placeholder="Νέα γρήγορη σημείωση…" - style={{ flex: 1, height: 32, borderRadius: 6, border: '1px solid #dfe2e6', padding: '0 10px', fontSize: 13, fontFamily: 'inherit' }} - /> - -
-
- ) -} - -function CloudSyncSection() { - const [syncing, setSyncing] = useState(false) - - async function syncNow() { - setSyncing(true) - try { - await client.post('/api/system/sync-menu') - toast.success('Το μενού στάλθηκε στο cloud') - } catch (e) { - toast.error(e.response?.data?.detail || 'Η αποστολή απέτυχε — ελέγξτε τη σύνδεση') - } finally { - setSyncing(false) - } - } - - return ( - - - - - - ) -} - -function TableOrderSettingsSection() { - const { t } = useTranslation('manager') - const qc = useQueryClient() - const { data: settings, isLoading } = useQuery({ - queryKey: ['pos-settings'], - queryFn: () => client.get('/api/settings/').then(r => r.data), - staleTime: 30_000, - }) - const updateMut = useMutation({ - mutationFn: ({ key, value }) => client.put(`/api/settings/${key}`, { value }), - onSuccess: () => { toast.success('Αποθηκεύτηκε'); qc.invalidateQueries({ queryKey: ['pos-settings'] }) }, - onError: () => toast.error('Σφάλμα αποθήκευσης'), - }) - function toggle(key, current) { - updateMut.mutate({ key, value: current === 'true' ? 'false' : 'true' }) - } - const autoClose = settings?.['orders.auto_close_on_full_payment']?.value ?? 'false' - const closeUnpaid = settings?.['orders.close_with_unpaid']?.value ?? 'false' - const bypassKds = settings?.['orders.bypass_kds_serve']?.value ?? 'false' - return ( - - {isLoading &&

Φόρτωση…

} - {!isLoading && ( - <> - - toggle('orders.auto_close_on_full_payment', autoClose)} disabled={updateMut.isPending} /> - - {/* 4.8: closing with unpaid items; when off, the phones take the payment first */} - - toggle('orders.close_with_unpaid', closeUnpaid)} disabled={updateMut.isPending} data-testid="setting-orders.close_with_unpaid" /> - - - toggle('orders.bypass_kds_serve', bypassKds)} disabled={updateMut.isPending} /> - - - toggle('orders.courses_enabled', settings?.['orders.courses_enabled']?.value ?? 'false')} - disabled={updateMut.isPending} - /> - - - - - )} -
- ) -} - -// ─── Flag definitions ───────────────────────────────────────────────────────── - -const FLAG_COLORS = [ - '#ef4444', '#f97316', '#eab308', '#22c55e', '#3b82f6', - '#8b5cf6', '#ec4899', '#06b6d4', '#6b7280', '#dc2626', -] -const RESTAURANT_EMOJIS = [ - '🧹', '⭐', '📝', '🛎️', '💎', - '🤵🏻', '🔒', '🛒', '🗣️', '⛔', - '🥳', '🎂', '🎉', '🍰', '🤩', - '☕', '🥂', '🍾', '🍹', '💦', - '🍖', '🥩', '🍽️', '🥓', '🍳', - '♿', '👶', '🤬', '🐶', '🐱', - '🚧', '🔥', '❄️', '⏳', '⚠️', -] - -function EmojiPicker({ value, onChange }) { - const [open, setOpen] = useState(false) - return ( -
- - {open && ( -
- {RESTAURANT_EMOJIS.map(e => ( - - ))} - -
- )} -
- ) -} - -function FlagDefsSection() { - const qc = useQueryClient() - const [editingId, setEditingId] = useState(null) - const [editForm, setEditForm] = useState({}) - const [newForm, setNewForm] = useState({ name: '', emoji: '', color: '#6b7280', text_color: null }) - const [showNew, setShowNew] = useState(false) - const { data: flags = [], isLoading } = useQuery({ - queryKey: ['flag-defs'], - queryFn: () => client.get('/api/flags/defs?include_inactive=true').then(r => r.data), - staleTime: 30_000, - }) - const createMut = useMutation({ - mutationFn: (body) => client.post('/api/flags/defs', body), - onSuccess: () => { toast.success('Δημιουργήθηκε'); qc.invalidateQueries({ queryKey: ['flag-defs'] }); setShowNew(false); setNewForm({ name: '', emoji: '', color: '#6b7280', text_color: null }) }, - onError: () => toast.error('Σφάλμα'), - }) - const updateMut = useMutation({ - mutationFn: ({ id, ...body }) => client.put(`/api/flags/defs/${id}`, body), - onSuccess: () => { toast.success('Αποθηκεύτηκε'); qc.invalidateQueries({ queryKey: ['flag-defs'] }); setEditingId(null) }, - onError: () => toast.error('Σφάλμα αποθήκευσης'), - }) - const toggleMut = useMutation({ - mutationFn: (id) => client.patch(`/api/flags/defs/${id}/toggle-active`), - onSuccess: (res) => { toast.success(res.data.is_active ? 'Ενεργοποιήθηκε' : 'Απενεργοποιήθηκε'); qc.invalidateQueries({ queryKey: ['flag-defs'] }) }, - onError: () => toast.error('Σφάλμα'), - }) - const deleteMut = useMutation({ - mutationFn: (id) => client.delete(`/api/flags/defs/${id}`), - onSuccess: () => { toast.success('Διαγράφηκε'); qc.invalidateQueries({ queryKey: ['flag-defs'] }) }, - onError: (err) => toast.error(err.response?.data?.detail || 'Σφάλμα'), - }) - function startEdit(flag) { - setEditingId(flag.id) - setEditForm({ name: flag.name, emoji: flag.emoji || '', color: flag.color || '#6b7280', text_color: flag.text_color || null, sort_order: flag.sort_order }) - } - const rowStyle = { display: 'flex', alignItems: 'center', gap: 10, padding: '10px 20px', borderBottom: '1px solid #f4f4f2' } - const newRowButton = ( - - ) - return ( - - {showNew && ( -
- setNewForm(f => ({ ...f, emoji: v }))} /> - setNewForm(f => ({ ...f, name: e.target.value }))} - style={{ flex: 1, minWidth: 160, height: 36, borderRadius: 8, border: '1px solid #dfe2e6', padding: '0 12px', fontSize: 13, fontFamily: 'inherit' }} /> -
- {FLAG_COLORS.map(c => ( -
-
- Χρώμα γραφής: - {[{ val: null, label: 'Α', bg: newForm.color || '#6b7280', text: '#ffffff' }, { val: '#000000', label: 'Α', bg: newForm.color || '#6b7280', text: '#000000' }].map(opt => ( - - ))} -
- - -
- )} - {isLoading &&

Φόρτωση…

} - {!isLoading && flags.length === 0 && ( -

Δεν υπάρχουν σημαίες ακόμα.

- )} - {flags.map(flag => ( -
- {editingId === flag.id ? ( -
- setEditForm(f => ({ ...f, emoji: v }))} /> - setEditForm(f => ({ ...f, name: e.target.value }))} - style={{ flex: 1, minWidth: 120, height: 32, borderRadius: 6, border: '1px solid #dfe2e6', padding: '0 10px', fontSize: 13, fontFamily: 'inherit' }} /> -
- {FLAG_COLORS.map(c => ( -
-
- {[{ val: null, text: '#ffffff' }, { val: '#000000', text: '#000000' }].map(opt => ( - - ))} -
- - -
- ) : ( - <> -
- {flag.emoji || '🏷️'} -
- {flag.name} - {!flag.is_active && Ανενεργή} - - - - - )} -
- ))} -
- ) -} - -// ─── Quick message templates ────────────────────────────────────────────────── - -function QuickTemplatesSection() { - const qc = useQueryClient() - const [editingId, setEditingId] = useState(null) - const [editBody, setEditBody] = useState('') - const [newBody, setNewBody] = useState('') - const [showNew, setShowNew] = useState(false) - const { data: templates = [], isLoading } = useQuery({ - queryKey: ['quick-templates'], - queryFn: () => client.get('/api/notifications/templates').then(r => r.data), - staleTime: 30_000, - }) - const createMut = useMutation({ - mutationFn: (body) => client.post('/api/notifications/templates', body), - onSuccess: () => { toast.success('Δημιουργήθηκε'); qc.invalidateQueries({ queryKey: ['quick-templates'] }); setShowNew(false); setNewBody('') }, - onError: () => toast.error('Σφάλμα'), - }) - const updateMut = useMutation({ - mutationFn: ({ id, body }) => client.put(`/api/notifications/templates/${id}`, { body }), - onSuccess: () => { toast.success('Αποθηκεύτηκε'); qc.invalidateQueries({ queryKey: ['quick-templates'] }); setEditingId(null) }, - onError: () => toast.error('Σφάλμα αποθήκευσης'), - }) - const deleteMut = useMutation({ - mutationFn: (id) => client.delete(`/api/notifications/templates/${id}`), - onSuccess: () => { toast.success('Διαγράφηκε'); qc.invalidateQueries({ queryKey: ['quick-templates'] }) }, - onError: () => toast.error('Σφάλμα'), - }) - const newButton = ( - - ) - return ( - - {showNew && ( -
- setNewBody(e.target.value)} - style={{ flex: 1, height: 36, borderRadius: 8, border: '1px solid #dfe2e6', padding: '0 12px', fontSize: 13, fontFamily: 'inherit' }} /> - - -
- )} - {isLoading &&

Φόρτωση…

} - {!isLoading && templates.length === 0 && ( -

Δεν υπάρχουν πρότυπα ακόμα.

- )} - {templates.map((t, idx) => ( -
- {idx + 1}. - {editingId === t.id ? ( - <> - setEditBody(e.target.value)} - style={{ flex: 1, height: 32, borderRadius: 6, border: '1px solid #dfe2e6', padding: '0 10px', fontSize: 13, fontFamily: 'inherit' }} /> - - - - ) : ( - <> - {t.body} - - - - )} -
- ))} -
- ) -} - -// ─── Auto schedule settings ─────────────────────────────────────────────────── - -const SCHED_STORAGE_KEY = 'xenia_schedule_settings_v1' -const SCHED_DEFAULTS = { - autoStartWorkday: false, - autoCloseWorkday: false, - autoCloseShiftsOnWorkday: false, - autoStartStaffShift: false, - autoCloseStaffShift: false, -} - -function loadSchedSettings() { - try { return { ...SCHED_DEFAULTS, ...JSON.parse(localStorage.getItem(SCHED_STORAGE_KEY) || '{}') } } - catch { return { ...SCHED_DEFAULTS } } -} - -function AutoScheduleSection() { - const [s, setS] = useState(loadSchedSettings) - - function toggle(key) { - setS(prev => { - const next = { ...prev, [key]: !prev[key] } - const stored = JSON.parse(localStorage.getItem(SCHED_STORAGE_KEY) || '{}') - localStorage.setItem(SCHED_STORAGE_KEY, JSON.stringify({ ...stored, ...next })) - return next - }) - } - - return ( - - - toggle('autoStartWorkday')} /> - - - toggle('autoCloseWorkday')} /> - - {s.autoCloseWorkday && ( -
- - toggle('autoCloseShiftsOnWorkday')} /> - -
- )} - - toggle('autoStartStaffShift')} /> - - - toggle('autoCloseStaffShift')} /> - -
- ) -} - -export default function OperationTab() { - return ( -
- - - - - - - - -
- ) -} diff --git a/manager_dashboard/src/pages/Settings/tabs/SecurityTab.jsx b/manager_dashboard/src/pages/Settings/tabs/SecurityTab.jsx deleted file mode 100644 index 39b444a..0000000 --- a/manager_dashboard/src/pages/Settings/tabs/SecurityTab.jsx +++ /dev/null @@ -1,350 +0,0 @@ -import { useState } from 'react' -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import toast from 'react-hot-toast' -import { Shield, Lock, LogOut, User, ShieldCheck, Copy, RefreshCw, X } from 'lucide-react' -import client from '../../../api/client' -import SignInSettings from '../sections/SignInSettings' -import { PANEL_CLASS } from '../../../ui/tokens' -import Button from '../../../ui/Button' - -const INACTIVITY_PRESETS = [ - { label: '5 δευτερόλεπτα', value: 5 }, - { label: '10 δευτερόλεπτα', value: 10 }, - { label: '30 δευτερόλεπτα', value: 30 }, - { label: '1 λεπτό', value: 60 }, - { label: '2 λεπτά', value: 120 }, - { label: '5 λεπτά', value: 300 }, - { label: '10 λεπτά', value: 600 }, - { label: '15 λεπτά', value: 900 }, - { label: '30 λεπτά', value: 1800 }, - { label: '1 ώρα', value: 3600 }, -] - -function fmtSeconds(s) { - const n = parseInt(s, 10) - if (isNaN(n) || n <= 0) return '' - if (n < 60) return `${n}s` - if (n < 3600) return `${Math.round(n / 60)}m` - return `${Math.round(n / 3600)}h` -} - -// ─── Shared primitives ──────────────────────────────────────────────────────── - -function SectionCard({ icon: Icon, title, description, children }) { - return ( -
-
-
- -
-
-

{title}

- {description &&

{description}

} -
-
- {children} -
- ) -} - -function OptionRow({ label, description, children }) { - return ( -
-
-

{label}

- {description &&

{description}

} -
-
{children}
-
- ) -} - -function Toggle({ checked, onChange, disabled }) { - return ( - - ) -} - -function TimeSelect({ value, onChange, disabled }) { - return ( -
- -
- ) -} - -// ─── Recovery Codes section ─────────────────────────────────────────────────── - -function RecoveryCodesSection() { - const [revealedCodes, setRevealedCodes] = useState(null) - const [confirming, setConfirming] = useState(false) - - const { data: statusData, refetch: refetchStatus } = useQuery({ - queryKey: ['recovery-code-status'], - queryFn: () => client.get('/api/recovery/status').then(r => r.data), - }) - - const generateMut = useMutation({ - mutationFn: () => client.post('/api/recovery/generate').then(r => r.data), - onSuccess: (data) => { - setRevealedCodes(data.codes) - setConfirming(false) - refetchStatus() - }, - onError: () => toast.error('Σφάλμα δημιουργίας κωδικών'), - }) - - const unused = statusData?.unused_count ?? null - - function copyAll() { - if (!revealedCodes) return - navigator.clipboard.writeText(revealedCodes.join('\n')) - toast.success('Οι κωδικοί αντιγράφηκαν!') - } - - return ( - -
- - {/* Status badge */} -
-
- Διαθέσιμοι κωδικοί: - {unused === null ? ( - Φόρτωση… - ) : ( - - {unused} / 5 - - )} -
- {unused === 0 && ( - - Δεν υπάρχουν κωδικοί! - - )} - {unused > 0 && unused <= 2 && ( - - Λίγοι κωδικοί - - )} -
- - {/* Revealed codes (shown once after generation) */} - {revealedCodes && ( -
-
-

- Αντιγράψτε τώρα — δεν θα εμφανιστούν ξανά! -

- -
-
- {revealedCodes.map((code, i) => ( -
- {code} - -
- ))} -
- -
- )} - - {/* Generate / confirm */} - {!revealedCodes && ( - confirming ? ( -
-

- Αυτό θα ακυρώσει τους {unused} υπάρχοντες κωδικούς και θα δημιουργήσει 5 νέους. -

-
- - -
-
- ) : ( - - ) - )} - -

- Αποθηκεύστε τους σε ασφαλές μέρος. Κάθε κωδικός δουλεύει μόνο μία φορά. - Χρησιμοποιείται στη σελίδα σύνδεσης με το όνομα χρήστη + κωδικό ανάκτησης. -

-
-
- ) -} - - -// ─── Main tab ───────────────────────────────────────────────────────────────── - -export default function SecurityTab() { - const qc = useQueryClient() - - const { data: settings, isLoading } = useQuery({ - queryKey: ['pos-settings'], - queryFn: () => client.get('/api/settings/').then(r => r.data), - staleTime: 30_000, - }) - - const updateMut = useMutation({ - mutationFn: ({ key, value }) => client.put(`/api/settings/${key}`, { value }), - onSuccess: () => { - toast.success('Αποθηκεύτηκε') - qc.invalidateQueries({ queryKey: ['pos-settings'] }) - }, - onError: () => toast.error('Σφάλμα αποθήκευσης'), - }) - - function get(key, fallback) { - return settings?.[key]?.value ?? fallback - } - - function save(key, value) { - updateMut.mutate({ key, value }) - } - - const busy = updateMut.isPending - - if (isLoading) { - return ( -
- Φόρτωση… -
- ) - } - - const autoLock = get('security.auto_lock', 'false') === 'true' - const autoLockSecs = get('security.auto_lock_seconds', '300') - const autoLogout = get('security.auto_logout', 'false') === 'true' - const autoLogoutSecs = get('security.auto_logout_seconds', '1800') - - return ( -
- - {/* Sign-in (2.6f): the v2 settings auth.* replace the v1 security.login_method card */} - - - {/* ── Αυτόματο κλείδωμα ────────────────────────────────────────────── */} - - - save('security.auto_lock', v ? 'true' : 'false')} - disabled={busy} - /> - - - {autoLock && ( - - save('security.auto_lock_seconds', v)} - disabled={busy} - /> - - )} - - - {/* ── Αυτόματη αποσύνδεση ──────────────────────────────────────────── */} - - - save('security.auto_logout', v ? 'true' : 'false')} - disabled={busy} - /> - - - {autoLogout && ( - - save('security.auto_logout_seconds', v)} - disabled={busy} - /> - - )} - - {autoLock && autoLogout && parseInt(autoLogoutSecs, 10) <= parseInt(autoLockSecs, 10) && ( -
- Ο χρόνος αποσύνδεσης είναι μικρότερος ή ίσος με τον χρόνο κλειδώματος — η οθόνη θα αποσυνδεθεί πριν κλειδώσει. -
- )} -
- - {/* ── Κωδικοί Ανάκτησης ────────────────────────────────────────────── */} - - -
- ) -} diff --git a/manager_dashboard/tests/settings.test.mjs b/manager_dashboard/tests/settings.test.mjs new file mode 100644 index 0000000..ce5f027 --- /dev/null +++ b/manager_dashboard/tests/settings.test.mjs @@ -0,0 +1,63 @@ +// The settings tabs' rules as plain data (plan step 6.14a). +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { + addCourse, buildColour, bundleSummary, cleanNotes, cleanVatGroups, endLines, idleParts, lanAddress, mergeColours, move, + nextColour, parseColour, readJson, setSlot, uptime, waiterPairUrl, +} from '../src/pages/Settings/sections/settingsLogic.js' + +test('idle times, JSON settings read safely', () => { + assert.deepEqual(idleParts(30), { n: 30, unit: 'seconds' }) + assert.deepEqual(idleParts(300), { n: 5, unit: 'minutes' }) + assert.deepEqual(idleParts(3600), { n: 1, unit: 'hours' }) + assert.deepEqual(readJson('[1,2]', []), [1, 2]) + assert.deepEqual(readJson('{"a":1}', []), []) + assert.deepEqual(readJson('nope', []), []) + assert.deepEqual(readJson(null, ['x']), ['x']) +}) + +test('courses and quick notes', () => { + const pal = ['A', 'B'] + const c = addCourse([{ id: 3, name: 'Main', color: 'A' }], pal, id => `Course ${id}`) + assert.deepEqual(c[1], { id: 4, name: 'Course 4', color: 'B' }) + assert.deepEqual(move([1, 2, 3], 0, 2), [2, 3, 1]) + assert.deepEqual(move([1, 2, 3], 0, -1), [1, 2, 3]) + assert.equal(nextColour(pal, 'B'), 'A') + assert.equal(nextColour(pal, 'Z'), 'A') + assert.deepEqual(cleanNotes([' Χωρίς αλάτι ', '', 'Χωρίς αλάτι', 'Extra']), ['Χωρίς αλάτι', 'Extra']) +}) + +test('table colours: merged with the defaults, parsed and built', () => { + const defaults = { light: { free: { cardBg: '#111111', nameText: '#222222' } }, dark: { free: { cardBg: '#333333' } } } + const merged = mergeColours({ light: { free: { cardBg: '#abcdef' } } }, defaults) + assert.deepEqual(merged, { light: { free: { cardBg: '#abcdef', nameText: '#222222' } }, dark: { free: { cardBg: '#333333' } } }) + assert.equal(setSlot(merged, 'dark', 'free', 'cardBg', '#000000').dark.free.cardBg, '#000000') + assert.equal(merged.dark.free.cardBg, '#333333') // not changed in place + assert.deepEqual(parseColour('rgba(255,255,255,0.92)'), { hex: '#ffffff', alpha: 0.92 }) + assert.deepEqual(parseColour('#FFF'), { hex: '#ffffff', alpha: 1 }) + assert.equal(parseColour('teal'), null) + assert.equal(buildColour('#ff8f60', 1), '#ff8f60') + assert.equal(buildColour('#ff8f60', 0.5), 'rgba(255,143,96,0.50)') + assert.equal(buildColour('#ff8', 1), null) +}) + +test('fiscal: VAT groups and the receipt end lines', () => { + assert.deepEqual(cleanVatGroups([{ machine_id: ' 1 ', friendly_name: ' Food ' }, { machine_id: '1', friendly_name: 'Again' }, + { machine_id: '', friendly_name: 'No id' }, { machine_id: '2', friendly_name: '' }, { machine_id: '3', friendly_name: 'Drinks' }]), + [{ machine_id: 1, friendly_name: 'Food' }, { machine_id: 3, friendly_name: 'Drinks' }]) + assert.deepEqual(endLines('["THANK YOU"]'), ['THANK YOU', '', '', '', '']) + assert.deepEqual(endLines('bad'), ['', '', '', '', '']) +}) + +test('export files, the pairing link, the LAN address, uptime', () => { + const cat = { bundle: 'catalog', data: { categories: [{ products: [1, 2] }, { products: [3] }], uncategorized_products: [4] } } + assert.deepEqual(bundleSummary(cat, 'catalog'), { groups: 2, items: 4 }) + assert.equal(bundleSummary(cat, 'tables'), null) + assert.deepEqual(bundleSummary({ bundle: 'tables', data: { table_groups: [{ tables: [1, 2] }], ungrouped_tables: [3] } }, 'tables'), { groups: 1, items: 3 }) + assert.equal(waiterPairUrl('192.168.1.5', 'S1', 'abc'), 'http://192.168.1.5/?pair=S1&k=abc') + assert.equal(waiterPairUrl('192.168.1.5'), 'http://192.168.1.5/') + assert.deepEqual(lanAddress({ lan_ip: '10.0.0.2', lan_ip_info: { source: 'override' } }, 'x'), { ip: '10.0.0.2', source: 'override' }) + assert.deepEqual(lanAddress({}, '192.168.1.9'), { ip: '192.168.1.9', source: 'browser' }) + assert.deepEqual(lanAddress({}, 'localhost'), { ip: null, source: null }) + assert.deepEqual(uptime(90061), { days: 1, h: 1, m: 1 }) +}) diff --git a/manager_dashboard/tests/v2-guards.test.mjs b/manager_dashboard/tests/v2-guards.test.mjs index 785c8b9..fa86b5c 100644 --- a/manager_dashboard/tests/v2-guards.test.mjs +++ b/manager_dashboard/tests/v2-guards.test.mjs @@ -15,6 +15,7 @@ const v2 = JSON.parse(readFileSync(path.join(ROOT, 'v2.json'), 'utf8')) const DATA = new Set([ 'src/pages/signage/signageLogic.js', 'src/pages/signage/SignageFields.jsx', 'src/pages/signage/SlideEditor.jsx', 'src/pages/signage/MenuEditor.jsx', 'src/pages/platform/DeviceConfigFields.jsx', 'src/pages/products/categoryColours.js', + 'src/pages/Settings/sections/venueColours.js', ]) const GREEK = /[Ͱ-Ͽἀ-῿]/ const COLOUR = [ diff --git a/manager_dashboard/v2.json b/manager_dashboard/v2.json index b9f9ea2..2d2e166 100644 --- a/manager_dashboard/v2.json +++ b/manager_dashboard/v2.json @@ -1,9 +1,9 @@ { "_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.", "paths": [ - "src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders", "src/pages/printing", "src/pages/schedule", "src/pages/reports", "src/pages/finance", "src/pages/customers", "src/pages/inventory", "src/pages/notes" + "src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders", "src/pages/printing", "src/pages/schedule", "src/pages/reports", "src/pages/finance", "src/pages/customers", "src/pages/inventory", "src/pages/notes" ], "strict": [ - "src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders", "src/pages/printing", "src/pages/staff", "src/pages/schedule", "src/pages/reports/kit", "src/pages/reports/today", "src/pages/reports/store", "src/pages/reports/products", "src/pages/reports/staff", "src/pages/reports/misc", "src/pages/reports/technical", "src/pages/reports/prepzones", "src/pages/reports/expenses", "src/pages/finance", "src/pages/customers", "src/pages/inventory", "src/pages/notes" + "src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders", "src/pages/printing", "src/pages/staff", "src/pages/schedule", "src/pages/reports/kit", "src/pages/reports/today", "src/pages/reports/store", "src/pages/reports/products", "src/pages/reports/staff", "src/pages/reports/misc", "src/pages/reports/technical", "src/pages/reports/prepzones", "src/pages/reports/expenses", "src/pages/finance", "src/pages/customers", "src/pages/inventory", "src/pages/notes", "src/pages/Settings/SettingsPage.jsx", "src/pages/Settings/sections/SystemSettings.jsx", "src/pages/Settings/sections/DataTransfer.jsx", "src/pages/Settings/sections/SecuritySettings.jsx", "src/pages/Settings/sections/OperationSettings.jsx", "src/pages/Settings/sections/TableFlags.jsx", "src/pages/Settings/sections/QuickMessages.jsx", "src/pages/Settings/sections/TableColours.jsx", "src/pages/Settings/sections/FiscalSettings.jsx", "src/pages/Settings/sections/DevelopmentSettings.jsx" ] } diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index 745f96d..c0e4ca7 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -385,6 +385,286 @@ "operation": { "closeUnpaid": "Κλείσιμο τραπεζιού με απλήρωτα", "closeUnpaidHint": "Ανενεργό: το κλείσιμο τραπεζιού με απλήρωτα ζητά πρώτα την πληρωμή και μετά το κλείνει. Ενεργό: κλείνει και τα απλήρωτα καταγράφονται ως απλήρωτα." + }, + "title": "Ρυθμίσεις", + "save": "Αποθήκευση", + "back": "Πίσω", + "system": { + "title": "Σύστημα", + "version": "Έκδοση", + "update": "Υπάρχει η {{version}}", + "upToDate": "Ενημερωμένο", + "license": "Άδεια", + "expires": "Έως {{date}}", + "licensed": "Ενεργή", + "unlicensed": "Ανενεργή", + "state": "Κατάσταση", + "states": { + "running": "Λειτουργεί", + "lockPending": "Θα κλειδώσει στο κλείσιμο της μέρας", + "locked": "Κλειδωμένο" + }, + "uptime": "Σε λειτουργία", + "uptimeValue": "{{days}} μ {{h}} ω {{m}} λ", + "refresh": "Έλεγχος ξανά", + "oldDomain": "Διεύθυνση σερβιτόρων (παλιό σύστημα)", + "oldDomainHint": "Την έχουν μόνο καταστήματα που εγκαταστάθηκαν πριν τη σύζευξη της εφαρμογής.", + "qr": "QR", + "qrTitle": "Σαρώστε για σύνδεση", + "setUp": "Τι έχει ρυθμιστεί", + "counts": { + "categories": "Κατηγορίες", + "products": "Προϊόντα (ενεργά)", + "tables": "Τραπέζια (ενεργά)", + "table_groups": "Ζώνες τραπεζιών", + "managers": "Υπεύθυνοι", + "waiters": "Σερβιτόροι" + }, + "support": "Υποστήριξη", + "supportHint": "Κλείδωμα ή ξεκλείδωμα του συστήματος (μόνο ο λογαριασμός υποστήριξης).", + "unlock": "Ξεκλείδωμα", + "lock": "Κλείδωμα", + "locked": "Το σύστημα κλειδώθηκε", + "unlocked": "Το σύστημα ξεκλειδώθηκε" + }, + "lan": { + "title": "Τοπικό δίκτυο", + "intro": "Η διεύθυνση του server στο Wi-Fi του καταστήματος: τη χρησιμοποιούν τα κινητά και το QR σύζευξης.", + "mismatch": "Χρησιμοποιείται η {{ip}}, αλλά ο server έχει τώρα την {{detected}}. Τα κινητά και το QR δεν θα συνδέονται μέχρι να διορθωθεί.", + "useDetected": "Χρήση της διεύθυνσης που βρέθηκε ({{ip}})", + "address": "Διεύθυνση server", + "unknown": "Άγνωστη ακόμα: γράψτε την εδώ (π.χ. 192.168.1.50).", + "detection": { + "unsupported": "Η αυτόματη εύρεση δουλεύει μόνο σε server Linux (όχι Docker Desktop).", + "stale": "Η αυτόματη εύρεση σταμάτησε να ενημερώνεται: ελέγξτε το container netinfo.", + "unavailable": "Η αυτόματη εύρεση δεν είναι διαθέσιμη (το container netinfo δεν τρέχει)." + }, + "saved": "Η διεύθυνση αποθηκεύτηκε", + "automatic": "Επιστροφή στην αυτόματη εύρεση", + "auto": "Αυτόματη εύρεση", + "change": "Αλλαγή", + "source": { + "override": "Ορίστηκε με το χέρι", + "detected": "Βρέθηκε αυτόματα", + "env": "Από την εγκατάσταση (HOST_IP)", + "browser": "Από τη διεύθυνση αυτής της σελίδας" + }, + "waiters": "Σερβιτόροι (Wi-Fi)", + "waitersHint": "Τα κινητά στο ίδιο Wi-Fi ανοίγουν αυτή, ή σαρώνουν το QR.", + "qrCaption": "Σαρώστε με την κάμερα του κινητού: ανοίγει την εφαρμογή σερβιτόρου. Το κινητό πρέπει να είναι στο ίδιο Wi-Fi.", + "manager": "Υπεύθυνοι (Wi-Fi)" + }, + "transfer": { + "title": "Εξαγωγή και εισαγωγή", + "intro": "Αποθηκεύστε τον κατάλογο ή τα τραπέζια σε αρχείο, ή φέρτε τα από άλλο κατάστημα.", + "kinds": { + "catalog": "Κατάλογος", + "tables": "Τραπέζια και ζώνες" + }, + "hints": { + "catalog": "Κατηγορίες και προϊόντα (όχι οι εκτυπωτές).", + "tables": "Ζώνες και τραπέζια." + }, + "export": "Εξαγωγή", + "import": "Εισαγωγή", + "imported": { + "catalog": "Ο κατάλογος εισήχθη", + "tables": "Τα τραπέζια εισήχθησαν" + }, + "wrongFile": "Αυτό δεν είναι αρχείο: {{kind}}.", + "confirmTitle": "Εισαγωγή αυτού του αρχείου;", + "finalTitle": "Τελευταίος έλεγχος", + "summary": { + "catalog": "Θα προστεθούν {{groups}} κατηγορίες και {{items}} προϊόντα.", + "tables": "Θα προστεθούν {{groups}} ζώνες και {{items}} τραπέζια." + }, + "merge": "Προστίθενται σε όσα υπάρχουν: τίποτα δεν διαγράφεται.", + "finalBody": "Αλλάζει τα δεδομένα του καταστήματος και δεν αναιρείται. Να γίνει η εισαγωγή;", + "continue": "Συνέχεια", + "importYes": "Ναι, εισαγωγή" + }, + "security": { + "idleTitle": "Όταν δεν χρησιμοποιείται", + "idleIntro": "Το κλείδωμα ζητά PIN για να συνεχίσει· η αποσύνδεση ζητά πλήρη σύνδεση.", + "lock": "Κλείδωμα μετά από λίγο", + "lockHint": "Η οθόνη κλειδώνει· ξεκλειδώνει με PIN.", + "lockAfter": "Κλείδωμα μετά από", + "logout": "Αποσύνδεση μετά από περισσότερο", + "logoutHint": "Η σύνδεση λήγει· ο χρήστης συνδέεται ξανά.", + "logoutAfter": "Αποσύνδεση μετά από", + "logoutFirst": "Η αποσύνδεση έρχεται πριν (ή μαζί με) το κλείδωμα, οπότε η οθόνη θα αποσυνδεθεί χωρίς να κλειδώσει πρώτα.", + "seconds_one": "{{count}} δευτερόλεπτο", + "seconds_other": "{{count}} δευτερόλεπτα", + "minutes_one": "{{count}} λεπτό", + "minutes_other": "{{count}} λεπτά", + "hours_one": "{{count}} ώρα", + "hours_other": "{{count}} ώρες", + "recoveryTitle": "Κωδικοί ανάκτησης", + "recoveryIntro": "Πέντε κωδικοί μιας χρήσης για σύνδεση όταν χαθεί ο κωδικός πρόσβασης. Ο καθένας δουλεύει μία φορά.", + "recoveryLeft": "Κωδικοί που απομένουν", + "ofFive_one": "{{count}} από 5", + "ofFive_other": "{{count}} από 5", + "copyNow": "Αντιγράψτε τους τώρα: δεν θα εμφανιστούν ξανά.", + "copy": "Αντιγραφή", + "copyAll": "Αντιγραφή όλων", + "done": "Έτοιμο", + "copied": "Αντιγράφηκε", + "replace": "Οι {{count}} κωδικοί που απομένουν παύουν να ισχύουν και φτιάχνονται 5 νέοι.", + "replaceYes": "Νέοι κωδικοί", + "remake": "Νέοι κωδικοί", + "make": "Δημιουργία κωδικών ανάκτησης", + "recoveryHow": "Φυλάξτε τους σε ασφαλές μέρος. Στη σελίδα σύνδεσης: το όνομα χρήστη και ένας κωδικός αντί για τον κωδικό πρόσβασης." + }, + "ops": { + "staffTitle": "Σερβιτόροι", + "staffIntro": "Τι κάνουν οι σερβιτόροι μόνοι τους.", + "selfStart": "Ξεκινούν τη βάρδιά τους", + "selfStartHint": "Αλλιώς την ξεκινά ένας υπεύθυνος.", + "selfEnd": "Κλείνουν τη βάρδιά τους", + "selfEndHint": "Αλλιώς την κλείνει ένας υπεύθυνος (με την καταμέτρηση).", + "hideTakings": "Απόκρυψη εισπράξεων από τους σερβιτόρους", + "hideTakingsHint": "Η επισκόπηση βάρδιας δεν δείχνει τι εισέπραξαν ή τι παραδίδουν.", + "paymentsTitle": "Πληρωμές", + "card": "Πληρωμή με κάρτα", + "cardHint": "Οι σερβιτόροι καταγράφουν πληρωμή με κάρτα. Δεν συνδέεται με POS: μόνο καταγράφεται.", + "ordersTitle": "Τραπέζια και παραγγελίες", + "ordersIntro": "Πώς συμπεριφέρονται τα τραπέζια και οι παραγγελίες.", + "autoClose": "Κλείσιμο τραπεζιού όταν πληρωθούν όλα", + "autoCloseHint": "Η παραγγελία κλείνει μόνη της με την τελευταία πληρωμή.", + "bypassKds": "Παράκαμψη του σερβιρίσματος στις οθόνες κουζίνας", + "bypassKdsHint": "Τα νέα είδη μετρούν ως σερβιρισμένα αμέσως: κανείς δεν επιβεβαιώνει.", + "courses": "Πιάτα σε σειρά (courses)", + "coursesHint": "Οι γραμμές παίρνουν σειρά (ορεκτικό, κυρίως, γλυκό…) και πάνε στην κουζίνα με αυτή.", + "courseColour": "Αλλαγή χρώματος", + "courseName": "Όνομα σειράς", + "courseN": "Σειρά {{n}}", + "addCourse": "Προσθήκη σειράς", + "up": "Πάνω", + "down": "Κάτω", + "remove": "Αφαίρεση: {{name}}", + "quickNotes": "Γρήγορες σημειώσεις", + "quickNotesHint": "Σημειώσεις που προσθέτει ο σερβιτόρος σε μια γραμμή με ένα πάτημα.", + "quickNote": "Γρήγορη σημείωση", + "newQuickNote": "Νέα γρήγορη σημείωση…", + "add": "Προσθήκη", + "menuTitle": "Ψηφιακό μενού", + "menuIntro": "Ονόματα, περιγραφές, τιμές και φωτογραφίες πάνε στο μενού QR μόνα τους κάθε λίγα λεπτά.", + "syncNow": "Αποστολή τώρα", + "syncNowHint": "Αντί να περιμένετε την επόμενη φορά.", + "sync": "Αποστολή", + "synced": "Το μενού στάλθηκε" + }, + "flags": { + "title": "Σημάνσεις τραπεζιών", + "intro": "Σημάδια που βάζει το προσωπικό σε ένα τραπέζι: γενέθλια, VIP, αλλεργία…", + "none": "Δεν υπάρχουν σημάνσεις ακόμα.", + "new": "Νέα σήμανση", + "newTitle": "Νέα σήμανση", + "preview": "Σήμανση", + "on": "Η σήμανση {{name}} προσφέρεται ξανά", + "off": "Η σήμανση {{name}} δεν προσφέρεται πια", + "offTag": "Ανενεργή", + "deleted": "Η σήμανση διαγράφηκε", + "edit": "Επεξεργασία: {{name}}", + "turnOff": "Να μην προσφέρεται: {{name}}", + "turnOn": "Να προσφέρεται ξανά: {{name}}", + "delete": "Διαγραφή: {{name}}", + "deleteTitle": "Διαγραφή: {{name}};", + "deleteBody": "Φεύγει από τα τραπέζια που την έχουν.", + "deleteYes": "Διαγραφή", + "name": "Όνομα", + "nameNeeded": "Γράψτε ένα όνομα.", + "emoji": "Emoji", + "colour": "Χρώμα", + "text": "Κείμενο", + "textLight": "Λευκά γράμματα", + "textDark": "Μαύρα γράμματα" + }, + "messages": { + "title": "Γρήγορα μηνύματα", + "intro": "Έτοιμα κείμενα που στέλνει ένας υπεύθυνος στο προσωπικό με ένα πάτημα.", + "none": "Δεν υπάρχουν γρήγορα μηνύματα ακόμα.", + "text": "Μήνυμα", + "delete": "Διαγραφή μηνύματος", + "new": "Νέο γρήγορο μήνυμα…" + }, + "colours": { + "title": "Χρώματα τραπεζιών στην εφαρμογή σερβιτόρων", + "intro": "Τα χρώματα μιας κάρτας τραπεζιού σε κάθε κατάσταση, για τη φωτεινή και τη σκοτεινή εμφάνιση.", + "modes": { + "light": "Φωτεινή εμφάνιση", + "dark": "Σκοτεινή εμφάνιση" + }, + "statuses": { + "free": "Ελεύθερο", + "open": "Ανοιχτό", + "mine": "Δικό μου", + "partially_paid": "Μερικώς", + "paid": "Πληρωμένο", + "kds_ready": "Έτοιμο" + }, + "slots": { + "cardBg": "Κάρτα", + "badgeBg": "Ετικέτα", + "nameText": "Όνομα τραπεζιού", + "badgeText": "Κείμενο ετικέτας" + }, + "second": "αναλαμπή", + "flash": "Αναλαμπή", + "reset": "Επαναφορά προεπιλεγμένων χρωμάτων", + "resetTitle": "Επαναφορά προεπιλεγμένων χρωμάτων;", + "resetBody": "Όλα τα παραπάνω χρώματα αντικαθίστανται.", + "resetYes": "Επαναφορά", + "pickTitle": "Επιλογή χρώματος", + "use": "Χρήση αυτού του χρώματος", + "invalid": "δεν είναι χρώμα", + "colour": "Χρώμα", + "opacity": "Αδιαφάνεια", + "quick": "Προτάσεις" + }, + "fiscal": { + "title": "Φορολογικός μηχανισμός", + "intro": "Οι αποδείξεις πάνε στον φορολογικό μηχανισμό (ΦΗΜ) μέσω του προγράμματος οδήγησής του.", + "enabled": "Αποστολή αποδείξεων στον ΦΗΜ", + "enabledHint": "Σε κάθε πληρωμή.", + "onWarning": "Ενεργό: κάθε πληρωμή στέλνει απόδειξη. Ελέγξτε τους φακέλους και τις ομάδες ΦΠΑ.", + "type": "Πρόγραμμα οδήγησης", + "typeHint": "Προς το παρόν μόνο αρχεία κειμένου (dTEC100extra).", + "types": { + "txt_file": "Αρχεία κειμένου (dTEC100extra)" + }, + "clerk": "Αριθμός ταμία", + "clerkHint": "Στέλνεται με κάθε απόδειξη (εντολές CR / CD).", + "eftpos": "Αριθμός τερματικού καρτών", + "eftposHint": "Στέλνεται με τις πληρωμές με κάρτα (εντολή CD).", + "wholeNumber": "Ακέραιος αριθμός πάνω από μηδέν.", + "foldersTitle": "Φάκελοι", + "foldersIntro": "Ο server και το πρόγραμμα οδήγησης ανταλλάσσουν αρχεία μέσω δύο φακέλων που βλέπει ο server (συνδεδεμένος φάκελος ή διαδρομή δικτύου).", + "out": "Εξερχόμενα (προς το πρόγραμμα)", + "outHint": "Γράφει ο server· διαβάζει το πρόγραμμα οδήγησης.", + "in": "Εισερχόμενα (από το πρόγραμμα)", + "inHint": "Εδώ γράφει τις απαντήσεις του το πρόγραμμα οδήγησης.", + "test": "Έλεγχος φακέλων", + "reachable": "Και οι δύο φάκελοι είναι προσβάσιμοι.", + "unreachable": "Ένας φάκελος δεν είναι προσβάσιμος", + "endTitle": "Τελευταίες γραμμές απόδειξης", + "endIntro": "Έως πέντε γραμμές στο τέλος κάθε απόδειξης· αφήστε τις άλλες κενές.", + "line": "Γραμμή {{n}}", + "vatTitle": "Ομάδες ΦΠΑ", + "vatIntro": "Όπως είναι προγραμματισμένες στον ΦΗΜ: ο αριθμός της και ένα όνομα για να την αναγνωρίζετε. Τις χρησιμοποιούν τα προϊόντα.", + "noVat": "Δεν υπάρχουν ομάδες ΦΠΑ ακόμα.", + "machineId": "Αριθμός", + "vatName": "Όνομα", + "vatNameHint": "π.χ. Φαγητό, Ποτά, Αλκοόλ", + "removeVat": "Αφαίρεση ομάδας", + "addVat": "Προσθήκη ομάδας" + }, + "dev": { + "warning": "Μόνο για δοκιμές. Μην τα αφήνετε ενεργά ενώ λειτουργεί το κατάστημα.", + "title": "Δοκιμές", + "spoof": "Προσποιητή εκτύπωση", + "spoofHint": "Κάθε εκτύπωση απορρίπτεται· οι εφαρμογές συμπεριφέρονται σαν να τυπώθηκε.", + "spoofOn": "Ενεργό: οι εκτυπωτές δεν τυπώνουν τίποτα." } }, "logs": { diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index 427d0fe..7be3ca1 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -385,6 +385,286 @@ "operation": { "closeUnpaid": "Close a table with unpaid items", "closeUnpaidHint": "Off: closing a table with unpaid items asks for the payment first, then closes it. On: it closes and the unpaid items are recorded as unpaid." + }, + "title": "Settings", + "save": "Save", + "back": "Back", + "system": { + "title": "System", + "version": "Version", + "update": "{{version}} is out", + "upToDate": "Up to date", + "license": "License", + "expires": "Until {{date}}", + "licensed": "Active", + "unlicensed": "Not active", + "state": "State", + "states": { + "running": "Working", + "lockPending": "Will lock at the day's close", + "locked": "Locked" + }, + "uptime": "Running for", + "uptimeValue": "{{days}} d {{h}} h {{m}} min", + "refresh": "Check again", + "oldDomain": "Waiter address (old setup)", + "oldDomainHint": "Only venues installed before the app pairing still have one.", + "qr": "QR code", + "qrTitle": "Scan to connect", + "setUp": "What is set up", + "counts": { + "categories": "Categories", + "products": "Products (active)", + "tables": "Tables (active)", + "table_groups": "Table zones", + "managers": "Managers", + "waiters": "Waiters" + }, + "support": "Support", + "supportHint": "Lock or unlock the system (support account only).", + "unlock": "Unlock", + "lock": "Lock", + "locked": "System locked", + "unlocked": "System unlocked" + }, + "lan": { + "title": "Local network", + "intro": "The server's address on the venue's Wi-Fi: the phones and the pairing QR use it.", + "mismatch": "The address in use is {{ip}}, but the server now has {{detected}}. Phones and the QR won't connect until this is fixed.", + "useDetected": "Use the detected address ({{ip}})", + "address": "Server address", + "unknown": "Not known yet: type it here (e.g. 192.168.1.50).", + "detection": { + "unsupported": "Finding it automatically works on a Linux server only (not Docker Desktop).", + "stale": "Finding it automatically stopped updating: check the netinfo container.", + "unavailable": "Finding it automatically isn't available (the netinfo container isn't running)." + }, + "saved": "Address saved", + "automatic": "Back to finding it automatically", + "auto": "Find it automatically", + "change": "Change", + "source": { + "override": "Set by hand", + "detected": "Found automatically", + "env": "From the install (HOST_IP)", + "browser": "From this page's address" + }, + "waiters": "Waiters (Wi-Fi)", + "waitersHint": "Phones on the same Wi-Fi open this, or scan the QR.", + "qrCaption": "Scan with the phone's camera: it opens the waiter app. The phone must be on the same Wi-Fi.", + "manager": "Managers (Wi-Fi)" + }, + "transfer": { + "title": "Export and import", + "intro": "Save the catalogue or the tables to a file, or bring them in from another venue.", + "kinds": { + "catalog": "Catalogue", + "tables": "Tables and zones" + }, + "hints": { + "catalog": "Categories and products (not the printers).", + "tables": "Table zones and tables." + }, + "export": "Export", + "import": "Import", + "imported": { + "catalog": "Catalogue imported", + "tables": "Tables imported" + }, + "wrongFile": "This isn't a {{kind}} file.", + "confirmTitle": "Import this file?", + "finalTitle": "Last check", + "summary": { + "catalog": "{{groups}} categories and {{items}} products will be added.", + "tables": "{{groups}} zones and {{items}} tables will be added." + }, + "merge": "They are added to what is here: nothing is deleted.", + "finalBody": "This changes the venue's data and can't be undone. Import it?", + "continue": "Continue", + "importYes": "Yes, import" + }, + "security": { + "idleTitle": "When the dashboard isn't used", + "idleIntro": "Locking asks for a PIN to go on; signing out asks for the full sign-in.", + "lock": "Lock after a while", + "lockHint": "The screen locks; a PIN unlocks it.", + "lockAfter": "Lock after", + "logout": "Sign out after a longer while", + "logoutHint": "The session ends; the person signs in again.", + "logoutAfter": "Sign out after", + "logoutFirst": "Signing out comes before (or with) locking, so the screen will sign out without locking first.", + "seconds_one": "{{count}} second", + "seconds_other": "{{count}} seconds", + "minutes_one": "{{count}} minute", + "minutes_other": "{{count}} minutes", + "hours_one": "{{count}} hour", + "hours_other": "{{count}} hours", + "recoveryTitle": "Recovery codes", + "recoveryIntro": "Five one-time codes to sign in when the password is lost. Each works once.", + "recoveryLeft": "Codes left", + "ofFive_one": "{{count}} of 5", + "ofFive_other": "{{count}} of 5", + "copyNow": "Copy them now: they won't be shown again.", + "copy": "Copy", + "copyAll": "Copy all", + "done": "Done", + "copied": "Copied", + "replace": "The {{count}} codes left stop working and 5 new ones are made.", + "replaceYes": "Make new codes", + "remake": "Make new codes", + "make": "Make recovery codes", + "recoveryHow": "Keep them somewhere safe. On the sign-in page: your username and a code instead of the password." + }, + "ops": { + "staffTitle": "Waiters", + "staffIntro": "What waiters may do on their own.", + "selfStart": "Start their own shift", + "selfStartHint": "Otherwise a manager starts it.", + "selfEnd": "End their own shift", + "selfEndHint": "Otherwise a manager ends it (with the cash count).", + "hideTakings": "Hide takings from waiters", + "hideTakingsHint": "Their shift overview doesn't show what they took or should hand over.", + "paymentsTitle": "Payments", + "card": "Card payments", + "cardHint": "Waiters can record a card payment. It isn't connected to a card terminal: it is recorded only.", + "ordersTitle": "Tables and orders", + "ordersIntro": "How tables and orders behave.", + "autoClose": "Close a table when everything is paid", + "autoCloseHint": "The order closes by itself with the last payment.", + "bypassKds": "Skip the kitchen screens' serve step", + "bypassKdsHint": "New items count as served at once: no one confirms serving them.", + "courses": "Courses", + "coursesHint": "Lines get a course (starter, main, dessert…) and go to the kitchen in that order.", + "courseColour": "Change the colour", + "courseName": "Course name", + "courseN": "Course {{n}}", + "addCourse": "Add a course", + "up": "Move up", + "down": "Move down", + "remove": "Remove {{name}}", + "quickNotes": "Quick notes", + "quickNotesHint": "Notes a waiter adds to a line with one tap.", + "quickNote": "Quick note", + "newQuickNote": "A new quick note…", + "add": "Add", + "menuTitle": "Digital menu", + "menuIntro": "Names, descriptions, prices and photos go to the QR menu by themselves every few minutes.", + "syncNow": "Send it now", + "syncNowHint": "Instead of waiting for the next time.", + "sync": "Send", + "synced": "The menu was sent" + }, + "flags": { + "title": "Table flags", + "intro": "Marks the staff put on a table: birthday, VIP, allergy…", + "none": "No flags yet.", + "new": "New flag", + "newTitle": "New flag", + "preview": "Flag", + "on": "{{name}} is offered again", + "off": "{{name}} is no longer offered", + "offTag": "Off", + "deleted": "Flag deleted", + "edit": "Edit {{name}}", + "turnOff": "Stop offering {{name}}", + "turnOn": "Offer {{name}} again", + "delete": "Delete {{name}}", + "deleteTitle": "Delete {{name}}?", + "deleteBody": "It goes from the tables that have it.", + "deleteYes": "Delete", + "name": "Name", + "nameNeeded": "Enter a name.", + "emoji": "Emoji", + "colour": "Colour", + "text": "Text", + "textLight": "White text", + "textDark": "Black text" + }, + "messages": { + "title": "Quick messages", + "intro": "Ready texts a manager sends to the staff with one tap.", + "none": "No quick messages yet.", + "text": "Message", + "delete": "Delete the message", + "new": "A new quick message…" + }, + "colours": { + "title": "Table colours on the waiter app", + "intro": "The colours of a table card in each state, for the app's light and dark look.", + "modes": { + "light": "Light look", + "dark": "Dark look" + }, + "statuses": { + "free": "Free", + "open": "Open", + "mine": "Mine", + "partially_paid": "Part paid", + "paid": "Paid", + "kds_ready": "Ready" + }, + "slots": { + "cardBg": "Card", + "badgeBg": "Badge", + "nameText": "Table name", + "badgeText": "Badge text" + }, + "second": "flash", + "flash": "Flash", + "reset": "Back to the default colours", + "resetTitle": "Back to the default colours?", + "resetBody": "Every colour above is replaced.", + "resetYes": "Reset", + "pickTitle": "Pick a colour", + "use": "Use this colour", + "invalid": "not a colour", + "colour": "Colour", + "opacity": "Opacity", + "quick": "Suggestions" + }, + "fiscal": { + "title": "Fiscal device", + "intro": "Receipts go to the fiscal device (FIM) through its driver.", + "enabled": "Send receipts to the fiscal device", + "enabledHint": "On each payment.", + "onWarning": "On: every payment sends a receipt. Check the folders and the VAT groups.", + "type": "Driver", + "typeHint": "Only the text-file driver (dTEC100extra) for now.", + "types": { + "txt_file": "Text files (dTEC100extra)" + }, + "clerk": "Clerk number", + "clerkHint": "Sent with each receipt (CR / CD commands).", + "eftpos": "Card terminal number", + "eftposHint": "Sent with card payments (CD command).", + "wholeNumber": "A whole number above zero.", + "foldersTitle": "Folders", + "foldersIntro": "The server and the driver exchange files through two folders the server can reach (a mounted folder or a network path).", + "out": "Outgoing (to the driver)", + "outHint": "The server writes here; the driver reads it.", + "in": "Incoming (from the driver)", + "inHint": "The driver writes its replies here.", + "test": "Check the folders", + "reachable": "Both folders can be reached.", + "unreachable": "A folder can't be reached", + "endTitle": "Receipt end lines", + "endIntro": "Up to five lines printed at the end of each receipt; leave the others empty.", + "line": "Line {{n}}", + "vatTitle": "VAT groups", + "vatIntro": "As programmed in the fiscal device: its number and a name to recognise it by. Products use them.", + "noVat": "No VAT groups yet.", + "machineId": "Number", + "vatName": "Name", + "vatNameHint": "e.g. Food, Drinks, Alcohol", + "removeVat": "Remove this group", + "addVat": "Add a group" + }, + "dev": { + "warning": "For testing only. Don't leave these on while the venue is working.", + "title": "Testing", + "spoof": "Pretend to print", + "spoofHint": "Every print job is dropped; the apps behave as if it printed.", + "spoofOn": "On: the printers print nothing." } }, "logs": { diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs index 4da7e1d..a4ec7fe 100644 --- a/tests/e2e/manager.mjs +++ b/tests/e2e/manager.mjs @@ -610,7 +610,7 @@ try { // 3.4: the customer display's idle screen, the venue's choice await api('PUT', '/api/platform/modules/customer_display', { token: boss, body: { enabled: true } }).catch(() => {}) await page.goto(`${APP}/settings`) - await page.getByText('Customer display', { exact: true }).click() + await page.getByTestId('settings-tab-customer-display').click() await page.getByTestId('display-style-qr').click() await page.getByTestId('display-qr-caption').fill('Order online') await page.getByTestId('display-save').click() @@ -625,7 +625,7 @@ try { // 4.3: Settings → Operation → "What each role may do" replaces the three waiter switches await page.goto(`${APP}/settings`) - await page.getByRole('button', { name: 'Operation', exact: true }).click() + await page.getByTestId('settings-tab-operation').click() await page.getByTestId('settings-role-permissions').waitFor({ timeout: 10_000 }) r.check('settings: Operation has "What each role may do", the old waiter switches are gone', await page.getByText('Ακυρώσεις Παραγγελιών από Σερβιτόρους').count() === 0 && await page.getByText('Αναίρεση Πληρωμής από Σερβιτόρους').count() === 0) @@ -645,7 +645,7 @@ try { r.check('settings: back to the role defaults → Maria takes payments again', (await mariaPerms()).keys.includes('ordering.orders.close')) await page.goto(`${APP}/settings`) - await page.getByText('Sign-in & security', { exact: true }).click() + await page.getByTestId('settings-tab-security').click() const waiterMode = page.getByTestId('setting-auth.waiter_login_mode') await waiterMode.waitFor({ timeout: 10_000 }) await waiterMode.selectOption('tap') @@ -671,7 +671,7 @@ try { r.check('settings: sign out after 14 days by default; 30 days is saved', idleDefault === '14' && await settingValue('auth.idle_days') === '30', idleDefault) await idleSel.selectOption('14') - await page.getByText('Venue & language', { exact: true }).click() + await page.getByTestId('settings-tab-venue').click() const tzSelect = page.getByTestId('setting-venue.timezone') await tzSelect.waitFor({ timeout: 10_000 }) await tzSelect.selectOption('Europe/London') @@ -686,7 +686,7 @@ try { await tzSelect.selectOption('Europe/Athens') await sleep(800) - await page.getByText('Printing', { exact: true }).click() + await page.getByTestId('settings-tab-print-fonts').click() const alertSel = page.getByTestId('setting-print.alert_after_failures') await alertSel.waitFor({ timeout: 10_000 }) await alertSel.selectOption('5') @@ -695,6 +695,81 @@ try { await alertSel.selectOption('2') await sleep(500) + // ── 6.14a: every settings tab on v2 ─────────────────────────────────────────── + const st6 = 'settings v2:' + const waitSetting = async (key, want) => { let v; for (let i = 0; i < 30 && (v = await settingValue2(key)) !== want; i++) await sleep(150); return v } + const settingValue2 = async key => (await api('GET', '/api/settings/', { token: boss }))[key]?.value + await page.goto(`${APP}/settings`) + r.check(`${st6} General: the version, the local network, what is set up`, await page.getByTestId('system-version').waitFor({ timeout: 10_000 }).then(() => true).catch(() => false) + && await page.getByTestId('settings-lan').count() === 1 && (await page.getByTestId('system-stats').textContent()).includes('Categories')) + const [catFile] = await Promise.all([page.waitForEvent('download', { timeout: 10_000 }), page.getByTestId('export-catalog').click()]) + const catPath = await catFile.path() + await page.getByTestId('import-tables').setInputFiles(catPath) + r.check(`${st6} importing the catalogue file as tables is refused`, await page.getByText("This isn't a Tables and zones file.").waitFor({ timeout: 5000 }).then(() => true).catch(() => false)) + await page.getByTestId('import-catalog').setInputFiles(catPath) + r.check(`${st6} the exported catalogue reads back: the import asks first, with what it adds`, await page.getByTestId('import-next').waitFor({ timeout: 5000 }).then(() => true).catch(() => false)) + await page.keyboard.press('Escape') + await page.screenshot({ path: path.join(OUT, 'manager-settings-general.png'), fullPage: true }) + await page.getByTestId('settings-tab-security').click() + await page.getByTestId('setting-security.auto_lock').click() + r.check(`${st6} Security: lock after a while is saved`, await waitSetting('security.auto_lock', 'true') === 'true' && await page.getByTestId('settings-recovery').count() === 1) + await page.getByTestId('setting-security.auto_lock').click() + await waitSetting('security.auto_lock', 'false') + await page.getByTestId('settings-tab-operation').click() + const coursesOn = page.getByTestId('setting-orders.courses_enabled') + await coursesOn.waitFor({ timeout: 10_000 }) + if (await coursesOn.getAttribute('aria-checked') !== 'true') { await coursesOn.click(); await waitSetting('orders.courses_enabled', 'true') } + const coursesBefore = JSON.parse(await settingValue2('orders.courses') || '[]').length + await page.getByTestId('course-add').click() + let coursesNow = coursesBefore + for (let i = 0; i < 30 && coursesNow === coursesBefore; i++) { await sleep(150); coursesNow = JSON.parse(await settingValue2('orders.courses') || '[]').length } + r.check(`${st6} Operation: a course added`, coursesNow === coursesBefore + 1, `${coursesBefore} → ${coursesNow}`) + await page.getByTestId('quick-note-new').fill('E2E: well done') + await page.getByTestId('quick-note-add').click() + let notesNow = [] + for (let i = 0; i < 30 && !notesNow.includes('E2E: well done'); i++) { await sleep(150); notesNow = JSON.parse(await settingValue2('orders.quick_notes') || '[]') } + r.check(`${st6} Operation: a quick note added`, notesNow.includes('E2E: well done'), JSON.stringify(notesNow)) + await page.getByTestId('flag-new').click() + await page.getByTestId('flag-save').click() + r.check(`${st6} a table flag needs a name`, (await page.getByTestId('flag-dialog').textContent()).includes('Enter a name')) + await page.getByTestId('flag-name').fill('E2E VIP') + await page.getByTestId('flag-save').click() + await page.locator('[data-testid="flag-row"]', { hasText: 'E2E VIP' }).waitFor({ timeout: 8000 }).catch(() => {}) + r.check(`${st6} a table flag added`, (await api('GET', '/api/flags/defs?include_inactive=true', { token: boss })).some(f => f.name === 'E2E VIP')) + await page.screenshot({ path: path.join(OUT, 'manager-settings-operation.png'), fullPage: true }) + await page.getByTestId('settings-tab-colours').click() + await page.getByTestId('colours-free').first().locator('button').first().click() + await page.getByTestId('colour-hex').fill('#123456') + await page.getByTestId('colour-save').click() + let tc = null + for (let i = 0; i < 30 && tc?.light?.free?.cardBg !== '#123456'; i++) { await sleep(150); tc = JSON.parse(await settingValue2('ui.table_colours') || '{}') } + r.check(`${st6} Appearance: a table colour for the waiter app saved`, tc?.light?.free?.cardBg === '#123456', JSON.stringify(tc?.light?.free)) + await page.screenshot({ path: path.join(OUT, 'manager-settings-colours.png'), fullPage: true }) + await page.getByText('Back to the default colours', { exact: true }).click() + await page.getByRole('button', { name: 'Reset', exact: true }).click() + for (let i = 0; i < 30 && tc?.light?.free?.cardBg === '#123456'; i++) { await sleep(150); tc = JSON.parse(await settingValue2('ui.table_colours') || '{}') } + await page.getByTestId('settings-tab-development').click() + await page.getByTestId('setting-dev.spoof_printing').click() + r.check(`${st6} Development: pretend printing is saved`, await waitSetting('dev.spoof_printing', 'true') === 'true') + await page.getByTestId('setting-dev.spoof_printing').click() + await waitSetting('dev.spoof_printing', 'false') + await api('PUT', '/api/platform/modules/fiscal', { token: boss, body: { enabled: true } }).catch(() => {}) + await page.goto(`${APP}/settings?tab=fiscal`) + if (await page.getByTestId('settings-fiscal').waitFor({ timeout: 8000 }).then(() => true).catch(() => false)) { + await page.getByTestId('fiscal-out').fill('/tmp/e2e-fiscal-out') + await page.getByTestId('fiscal-in').fill('/tmp/e2e-fiscal-in') + await page.getByTestId('fiscal-save-folders').click() + r.check(`${st6} Fiscal: the folders saved as plain paths`, await waitSetting('fiscal.out_folder', '/tmp/e2e-fiscal-out') === '/tmp/e2e-fiscal-out') + await api('PUT', '/api/platform/modules/fiscal', { token: boss, body: { enabled: false } }).catch(() => {}) + } + await page.getByTestId('user-menu').click() + await page.getByRole('menuitemradio', { name: 'Ελληνικά' }).click() + await page.goto(`${APP}/settings?tab=operation`) + r.check(`${st6} Settings in Greek`, await page.getByTestId('settings-tab-operation').filter({ hasText: 'Λειτουργία' }).waitFor({ timeout: 8000 }).then(() => true).catch(() => false) + && await page.getByTestId('settings-flags').filter({ hasText: 'Σημάνσεις τραπεζιών' }).count() === 1) + await page.getByTestId('user-menu').click() + await page.getByRole('menuitemradio', { name: 'English' }).click() + await page.goto(`${APP}/reports/technical`) await page.getByText('Log files', { exact: true }).click() const today = new Date().toISOString().slice(0, 10) @@ -1060,9 +1135,7 @@ try { // ── 6.10: printers, the ticket's look and prep zones on v2 ─────────────────── const pz = 'printing:' - const settingValue2 = async key => (await api('GET', '/api/settings/', { token: boss }))[key]?.value - await page.goto(`${APP}/settings`) - await page.getByText('Printing', { exact: true }).click() + await page.goto(`${APP}/settings?tab=print-fonts`) await page.getByTestId('printers-card').waitFor({ timeout: 10_000 }).catch(() => {}) await page.getByTestId('printer-new').click() await page.getByTestId('printer-save').click()